text
stringlengths
14
6.51M
unit TipoRecursoEditFormUn; interface uses osCustomEditFrm, DB, DBClient, osClientDataset, StdCtrls, Mask, DBCtrls, Menus, ImgList, Controls, Classes, ActnList, osActionList, ComCtrls, ToolWin, Buttons, ExtCtrls, acCustomSQLMainDataUn; type TTipoRecursoEditForm = class(TosCustomEditForm) DominioClientDataSet: TosClientDataset; Label2: TLabel; DescricaoEdit: TDBEdit; DominioClientDataSetIDTIPORECURSO: TIntegerField; DominioClientDataSetDESCRICAO: TStringField; procedure DominioClientDataSetBeforePost(DataSet: TDataSet); procedure DominioClientDataSetAfterApplyUpdates(Sender: TObject; var OwnerData: OleVariant); private public end; var TipoRecursoEditForm: TTipoRecursoEditForm; implementation uses TipoRecursoDataUn, osUtils, SQLMainData; {$R *.DFM} procedure TTipoRecursoEditForm.DominioClientDataSetBeforePost(DataSet: TDataSet); begin inherited; TipoRecursoData.Validate(DataSet); end; procedure TTipoRecursoEditForm.DominioClientDataSetAfterApplyUpdates( Sender: TObject; var OwnerData: OleVariant); begin inherited; if TClientDataSet(Sender).UpdateStatus in [usModified, usInserted, usDeleted] then MainData.UpdateVersion(tnTipoRecurso); end; initialization OSRegisterClass(TTipoRecursoEditForm); end.
unit test_unit1; interface uses test_unit2, crt, sysutils; procedure menuPrincipal(var vSerie: tvSerie; var mlvSerie: tmlvSerie; var vUsuario:tvUsuario; var mlvUsuario: tmlvUsuario; var vTop: tvTop); implementation function haySeriesCargadas(vSerie: tvSerie):boolean; {Pre: Recibe el vector series. * Post: Devuelve true si tiene cargada al menos una serie y false en caso contrario.} var bool: boolean; begin if vSerie[1].nombre = '' then bool := False else bool := True; haySeriesCargadas := bool; end; procedure actualizarVisualSerie(var vSerie: tvSerie; rVisualizacion: trVisualizacion); {Pre: Recibe el vector serie y un registro del tipo visualizacion de usuario * Post: Suma la cantidad de visualizaciones de los episodios visto por el usuario a * las visualizaciones de los mismos episodios en el vector serie. * En el caso de que cantidad de visualizaciones del episodio en el vector serie * sea el maximo permitido por el tipo longint, que es 2147483647, o estas visualizaciones * mas la suma de las visualizaciones del usuario usuario lo superen se asociara como * cantidad de visualizaciones el maximo de longint.} const MAX_LONGINT = 2147483647; var aux: longint; begin if (vSerie[rVisualizacion.posSerieEnvSerie].vTemp[rVisualizacion.numTempEnLaSerie].vVideo[rVisualizacion.numEpiDeLaTemp].visualizaciones <> MAX_LONGINT) then begin aux := vSerie[rVisualizacion.posSerieEnvSerie].vTemp[rVisualizacion.numTempEnLaSerie].vVideo[rVisualizacion.numEpiDeLaTemp].visualizaciones + rVisualizacion.cantVisualizaciones; if (aux < vSerie[rVisualizacion.posSerieEnvSerie].vTemp[rVisualizacion.numTempEnLaSerie].vVideo[rVisualizacion.numEpiDeLaTemp].visualizaciones) then {Si al sumar las visualizaciones se genera un overflow} vSerie[rVisualizacion.posSerieEnvSerie].vTemp[rVisualizacion.numTempEnLaSerie].vVideo[rVisualizacion.numEpiDeLaTemp].visualizaciones:= MAX_LONGINT else vSerie[rVisualizacion.posSerieEnvSerie].vTemp[rVisualizacion.numTempEnLaSerie].vVideo[rVisualizacion.numEpiDeLaTemp].visualizaciones:= vSerie[rVisualizacion.posSerieEnvSerie].vTemp[rVisualizacion.numTempEnLaSerie].vVideo[rVisualizacion.numEpiDeLaTemp].visualizaciones + rVisualizacion.cantVisualizaciones; end; end; procedure procesarVisualizaciones(var vSerie: tvSerie; vUsuario: tvUsuario; mlvUsuario: tmlvUsuario); {Pre: Recibe el vector serie y usuario mas el maximo logico del usuario. * Post: Carga las visualizaciones de los usuarios al vector series} var i, j : integer; begin for i:= 1 to mlvUsuario do for j:= 1 to vUsuario[i].mlvVisualizacion do actualizarVisualSerie(vSerie, vUsuario[i].vVisualizacion[j]); end; procedure crearVisualizacion(var rUsuario: trUsuario; posSerie: integer; posTemp: integer; posEpi: integer; visualizaciones: integer); {Pre: Recibe un registro del tipo usuario, una posicion de serie, temporada y episodio y una * cantidad de visualizaciones * Post: Crea una visualizacion en el vectorvvisualizacion del registro usuario con completado sus datos con la posiciones y visualizaciones dadas} begin rUsuario.mlvVisualizacion := rUsuario.mlvVisualizacion + 1; rUsuario.vVisualizacion[rUsuario.mlvVisualizacion].posSerieEnvSerie := posSerie; rUsuario.vVisualizacion[rUsuario.mlvVisualizacion].numTempEnLaSerie := posTemp; rUsuario.vVisualizacion[rUsuario.mlvVisualizacion].numEpiDeLaTemp := posEpi; rUsuario.vVisualizacion[rUsuario.mlvVisualizacion].cantVisualizaciones := visualizaciones; end; procedure sumarVisualizacion(var rUsuario: trUsuario; posicion : integer; visualizaciones: tCantVisualizaciones); {Pre: Recibe un registro de usuario, una posicion de su vector visualizacion y una cantidad de visualizaciones * Post: Suma la cantidad de visualizaciones a la posicion indicada. Si la cantidad de * visualizaciones supera el maximo valor posible para byte, que es 255, entonces se asigna a * visualizaciones 255.} const MAX_BYTE = 255; var aux : integer; begin if rUsuario.vVisualizacion[posicion].cantVisualizaciones <> MAX_BYTE then begin aux := rUsuario.vVisualizacion[posicion].cantVisualizaciones + visualizaciones; if (aux < rUsuario.vVisualizacion[posicion].cantVisualizaciones) then rUsuario.vVisualizacion[posicion].cantVisualizaciones := MAX_BYTE else rUsuario.vVisualizacion[posicion].cantVisualizaciones := aux; end; end; function esvVisualizacionLleno(rUsuario: trUsuario):boolean; {Pre: Recibe un registro de usuario * Post : Devuelve True si el registro de usuario tiene su vector de visualizaciones lleno * y false en caso contrario} begin if rUsuario.vVisualizacion[MAX_VISUALIZACIONES_POR_USUARIO].posSerieEnvSerie <> 0 then esvVisualizacionLleno := True else esvVisualizacionLleno := False; end; procedure buscarPosicionVisualizacion(rUsuario: trUsuario; posSerie : integer; posTemp : integer; posEpi:integer; var posicion: integer); {Pre: Recibe un registro de usuario y las variables de posicion para serie, temporada y episodio. * Post: Busca si ya existian visualizaciones para el episodio en el registro Usuario. * De encontrarse devuelve la posicion y en caso contrario devuelve 0} var i: integer; begin i:= 1; while ((i <= rUsuario.mlvVisualizacion) and ( (rUsuario.vVisualizacion[i].posSerieEnvSerie <> posSerie) or (rUsuario.vVisualizacion[i].numTempEnLaSerie <> posTemp) or (rUsuario.vVisualizacion[i].numEpiDeLaTemp <> posEpi))) do inc(i); if i > rUsuario.mlvVisualizacion then posicion := 0 else posicion := i; end; procedure actualizarVisualUsuario(var rUsuario: trUsuario; posSerie: integer; posTemp: integer; posEpi: integer; visualRandom: tCantVisualizaciones); {Pre: Recibe el vector usuario, una cantidad de visualizaciones y las posiciones de una * serie, temporada y episodio * Post: En caso de ya existir visualizaciones para ese episodio se suman a las anteriores, * en caso de no existir se crea una visualizacion nueva} var posicion: integer; begin buscarPosicionVisualizacion(rUsuario, posSerie, posTemp, posEpi, posicion); if (posicion <> 0) then begin sumarVisualizacion(rUsuario, posicion, visualRandom); end else if not esvVisualizacionLleno(rUsuario) then begin crearVisualizacion(rUsuario, posSerie, posTemp, posEpi, visualRandom); end; end; procedure generarVisualRandom(var visualRandom: tCantVisualizaciones); {Pre: Recibe la variable visualRandom entero * Post : Devuelve la cantidad de visualizaciones random la cual tiene una probabilidad del 60% * de ser 0, 20% de ser 1, 10% de ser 2, 5% de ser 3, 3% de ser 4, 1% de ser 5 y 1% de ser 150.} var num : integer; begin randomize; num := random(100); case num of 0..59 : visualRandom := 0; 60..79 : visualRandom := 1; 80..89 : visualRandom := 2; 90..94 : visualRandom := 3; 95..97 : visualRandom := 4; 98 : visualRandom := 5; 99 : visualRandom := 150; end; end; procedure seleccionarEpiTempSerieRandom(vSerie: tvSerie; mlvSerie: tmlvSerie; var posSerie: integer; var posTemp: integer; var posEpi: integer); {Pre: Recibe el vector serie y su maximo logico mas las posiciones serie, temporada y episodio. * Post: Selecciona un episodio al azar de una temporada al azar de una de las series al azar * del vector serie y guarda sus posiciones} begin randomize; posSerie := random(mlvSerie) + 1; posTemp := random(vSerie[posSerie].cantTemp) + 1; posEpi := random(vSerie[posSerie].vTemp[posTemp].cantEpiDeTemp) + 1; end; procedure solicitarValor(var valor: integer; limInf: integer; limSup: integer; cadena: string); {Pre: Recibe una opcion, limite superior e inferior del tipo byte y una cadena como mensaje. * Post: Solicita al usuario que ingrese un numero de opcion entre el limite inferior y superior, * solicitando nuevamente en caso de que el numero ingresado este fuera de los limites} begin write('Ingrese ',cadena, ' : '); {$I-} readln(valor); {$I+} while (IOResult <> 0) or (valor < limInf) or (valor > limSup) do begin writeln('ERROR: ',cadena,' ingresada invalida. Debe ser entre ', limInf, ' y ', limSup, '.'); write('Ingrese ', cadena, ' : '); {$I-} readln(valor); {$I+} end; end; procedure generarVisualizaciones(vSerie: tvSerie; mlvSerie: tmlvSerie; var vUsuario: tvUsuario; var mlvUsuario: tmlvUsuario; cantVisual: integer); {Pre: Recibe los vectores serie y usuario mas sus maximos logicos. * Post: Genera visualizaciones aleatorias para los usuarios de valores entre 0 y 150 con * distintas probabilidades.} var posSerie, posTemp, posEpi, i, j: integer; visualRandom: tCantVisualizaciones; begin for i:= 1 to mlvUsuario do for j:= 1 to cantVisual do begin seleccionarEpiTempSerieRandom(vSerie, mlvSerie, posSerie, posTemp, posEpi); generarVisualRandom(visualRandom); actualizarVisualUsuario(vUsuario[j], posSerie, posTemp, posEpi, visualRandom); end; end; procedure limpiarVisualEpisodios(var vSerie: tvSerie; mlvSerie: tmlvSerie); {Pre: Recibe el vector serie y su maximo logico. * Post: Limpia las visualizaciones de todos los episodios.} var i, j , k : integer; begin for i:= 1 to mlvSerie do for j:= 1 to vSerie[i].cantTemp do for k:= 1 to vSerie[i].vTemp[j].cantEpiDeTemp do vSerie[i].vTemp[j].vVideo[k].visualizaciones := 0; end; procedure menuGenerarYProcesarVisualizaciones(var vSerie: tvSerie; mlvSerie: tmlvSerie; var vUsuario: tvUsuario; mlvUsuario: tmlvUsuario); {Pre: Recibe los vectores serie con series cargadas y el vector usuario con al menos un usuario.} {Post: Genera para cada usuario una cantidad de visualizaciones, ingresada por el usuario * entre 0 y el valor maximo para un integer que es 32767, para episodios seleccionados al azar. * Luego para cada episodio carga la cantidad de visualizaciones generada para los usuarios.} const MAX_INTEGER = 32767; var cantVisual: integer; begin clrscr; writeln('Menu generar y procesar visualizaciones'); writeln; if haySeriesCargadas(vSerie) then begin solicitarValor(cantVisual, 1, MAX_INTEGER, 'cantidad de visualizaciones'); generarVisualizaciones(vSerie, mlvSerie, vUsuario, mlvUsuario, cantVisual); writeln; writeln('Visualizaciones generadas.'); writeln; limpiarVisualEpisodios(vSerie, mlvSerie); procesarVisualizaciones(vSerie, vUsuario, mlvUsuario); writeln('Visualizaciones procesadas'); end else begin writeln('ERROR: Primero debe inicializar las series para poder generar y procesar ', 'las visualizacones'); end; writeln; writeln('Presione cualquier tecla para volver al menu principal'); readkey; end; function segAHhmmss(segundos: longint):string; {Pre: Recibe una cantidad de segundos * Post: Devuelve el tiempo en una cadena del tipo HH:MM:SS donde HH es hora, MM minutos y SS * segundos} var hh, mm, ss : integer; begin hh := segundos div 3600; mm := (segundos mod 3600) div 60; ss := (segundos mod 3600) mod 60; segAHhmmss:= format('%.2d', [hh]) + ':' + format('%.2d', [mm]) + ':' + format('%.2d', [ss]); end; procedure menuTemporada(rSerie: trSerie); {Pre: Recibe un registro de serie. * Post: Imprime en pantalla los episodios de las temporadas con su duracion expresada en * HH:MM:SS} var i, j: integer; begin clrscr; writeln('Temporadas de ',rSerie.nombre); writeln; for i:= 1 to rSerie.cantTemp do begin writeln('Temporada ',i); writeln(' ', format('%-4s',['N'] ), format('%-55s', ['Titulo']), format('%-9s', ['Duracion']), format('%8s', ['Visualizaciones'])); for j:= 1 to rSerie.vTemp[i].cantEpiDeTemp do writeln(' ', format('%-4d', [j]), format('%-55s', [rSerie.vTemp[i].vVideo[j].titulo]), format('%-9s', [(segAHhmmss(rSerie.vTemp[i].vVideo[j].duracionEnSegundos))]), format('%8d', [rSerie.vTemp[i].vVideo[j].visualizaciones])); writeln; end; writeln('Presione cualquier tecla para volver al menu de series'); readkey; end; procedure menuSerie(vSerie: tvSerie; mlvSerie: tmlvSerie); {Pre: Recibe el vector serie y su maximo logico. * Post: Imprime el listado de las series cargadas en el vector serie o error en caso de * encontrarse vacio.} var opcion : integer; i: integer; salir: boolean; begin salir := False; while not salir do begin clrscr; writeln('Menu Series'); writeln; if haySeriesCargadas(vSerie) then begin for i:= 1 to mlvSerie do writeln(i, ' ', vSerie[i].nombre); writeln(mlvSerie + 1, ' Volver al menu principal'); writeln; solicitarValor(opcion, 1 , mlvSerie + 1, 'opcion'); if (opcion = mlvSerie + 1) then salir:= True else menuTemporada(vSerie[opcion]); end else begin writeln('ERROR: No hay series cargadas'); writeln('Presione cualquier tecla para volver al menu principal'); salir:= True; readkey; end end; end; procedure limpiarDatosVideo(var rVideo: trVideo); {Pre: Recibe un registro de video. * Post: Limpia sus datos.} begin rVideo.titulo := ''; rVideo.descripcion := ''; rVideo.duracionEnSegundos := 0; rVideo.visualizaciones := 0; end; procedure iniciarTop(var vTop: tvTop); {Pre: Recibe el vector top. * Post: Limpia sus datos.} var i: integer; begin for i:= 1 to CANT_TOP do limpiarDatosVideo(vTop[i]) end; procedure agregarUsuario(var vUsuario: tvUsuario; var mlvUsuario: tmlvUsuario; nombre: string); {Pre: El vector usuario no debe estar completo y el nombre debe ser valido, es decir, todo * en minuscula y que no se repita. * Post: Ingresa el usuario al vector usuario} begin mlvUsuario := mlvUsuario + 1; vUsuario[mlvUsuario].nombreUsuario := nombre; end; procedure limpiarVisualUsuario(var rVisualizacion: trVisualizacion); {Pre: Recibe un registro de visualizacion de usuario * Post: Limpia sus datos} begin rVisualizacion.posSerieEnvSerie := 0; rVisualizacion.numTempEnLaSerie := 0; rVisualizacion.numEpiDeLaTemp := 0; rVisualizacion.cantVisualizaciones :=0 end; procedure limpiarDatosUsuario(var vUsuario: tvUsuario; var mlvUsuario: tmlvUsuario); {Pre: Reecibe el vector usuario y su maximo logico. * Post: Limpia los datos del vector y reinicia el maximo logico a cero} var i, j : integer; begin mlvUsuario := 0; for i:= 1 to MAX_USUARIOS do begin vUsuario[i].nombreUsuario := ''; for j:= 1 to MAX_VISUALIZACIONES_POR_USUARIO do limpiarVisualUsuario(vUsuario[i].vVisualizacion[j]); end; end; procedure iniciarUsuario(var vUsuario: tvUsuario; var mlvUsuario: tmlvUsuario); {Pre: Recibe el vector usuario y su maximo logico. * Post: Limpia los datos del vector, reinicia el maximo logico a cero y agrega un * usuario inicial llamado 'usuario'.} begin limpiarDatosUsuario(vUsuario, mlvUsuario); agregarUsuario(vUsuario, mlvUsuario, 'usuario'); end; procedure limpiarDatosSerie(var vSerie: tvSerie; var mlvSerie: tmlvSerie); {Pre: Recibe el vector serie y su maximo logico * Post: Limpia los datos del vector serie y reinicia el maximo logico a cero} var i, j , k : integer; begin mlvSerie := 0; for i:= 1 to MAX_CANTIDAD_SERIES do begin vSerie[i].nombre := ''; vSerie[i].descripcion := ''; vSerie[i].cantTemp := 0; for j:= 1 to MAX_TEMPORADAS_POR_SERIE do begin vSerie[i].vTemp[j].anioDeEmision := '0000'; vSerie[i].vTemp[j].cantEpiDeTemp := 0; for k:= 1 to MAX_EPISODIOS_POR_TEMPORADA do limpiarDatosVideo(vSerie[i].vTemp[j].vVideo[k]) end; end; end; procedure iniciarSerie(var vSerie: tvSerie; var mlvSerie: tmlvSerie); {Pre: Ricibe el vector serie y su maximo logico. * Post: Limpia los datos del vector serie y del maximo logico. Luego carga las series en el vector serie} begin limpiarDatosSerie(vSerie, mlvSerie); cargarDatosSerie(vSerie, mlvSerie); end; procedure inicializar(var vSerie: tvSerie; var mlvSerie: tmlvSerie; var vUsuario: tvUsuario; var mlvUsuario: tmlvUsuario; var vTop: tvTop); {Pre: Recibe el vector Serie, Usuario y Top mas sus maximos logicos. * Post : Limpia los datos de los vectores, carga las series en el vector series y un usuario * 'usuario'en el vector usuario} begin iniciarSerie(vSerie, mlvSerie); iniciarUsuario(vUsuario, mlvUsuario); iniciarTop(vTop); end; function existeUsuario(vUsuario: tvUsuario; mlvUsuario: tmlvUsuario; nombre: string): boolean; {Pre: Recibe el vector usuario, su maximo logico y un nombre valido del tipo cadena. * Post: Devuelve True en caso de que exista el usuario en el vector usuario.} var i: integer; bool: boolean; begin i:= 1; while ((i <= mlvUsuario) and (vUsuario[i].nombreUsuario <> nombre)) do inc(i); if i > mlvUsuario then bool := False else bool := True; existeUsuario := bool; end; function cadenaMinuscula(cadena: string):boolean; {Pre: Recibe una cadena. * Post: Devuelve true en caso de que la cadena este formado solo por caracteres de letra minuscula * sin contar la 'enie' para respetar ASCII y false en caso contrario.} var i: byte; bool: boolean; begin i:= 1; while ((i <= length(cadena)) and (cadena[i] >= 'a') and (cadena[i] <= 'z')) do begin inc(i); end; if i > length(cadena) then bool := True else bool := False; cadenaMinuscula := bool; end; procedure obtenerNombreUsuarioValido(vUsuario: tvUsuario; mlvUsuario: tmlvUsuario; var nombre: string); {Pre: Recibe un nombre del tipo string por referencia. * Post: Devuelve un nombre de usuario valido.} begin write('Ingrese el nombre de usuario : '); {$I-} readln(nombre); {$I+} while ( (IOResult <> 0) or (length(nombre) > 8) or (length(nombre) <= 0) or (not cadenaMinuscula(nombre)) or existeUsuario(vUsuario, mlvUsuario, nombre) ) do begin writeln('ERROR: El nombre de usuario ingresado no es valido.'); writeln('El nombre debe tener menos de 8 caracteres de largo.'); writeln('Estar en minusculas.'); writeln('No se puede repetir con el de los usuarios ya existenes.'); writeln('La letra enie no esta considerada.'); writeln; write('Ingrese el nombre de usuario : '); {$I-} readln(nombre); {$I+} end; end; function esVectorUsuarioLleno(vUsuario: tvUsuario):boolean; {Pre: Recibe el vector usuario; * Post: Devuelve true si el vector usuario se encuentra en su limite de capacidad de usuarios * y false en caso contrario} var bool : boolean; begin if vUsuario[MAX_USUARIOS].nombreUsuario = '' then bool := False else bool := True; esVectorUsuarioLleno := bool; end; procedure menuAgregarUsuario(var vUsuario: tvUsuario; var mlvUsuario: tmlvUsuario); {Pre: Recibe el vector usuario y su maximo. * Post: Agrega un nuevo usuario valido al vector usuario.} var nombre: string; begin clrscr; writeln('Menu Agregar Usuario'); writeln; if esVectorUsuarioLleno(vUsuario) then begin writeln('ERROR: No se puede crear mas usuarios, limite de ', MAX_USUARIOS, ' usuarios alcanzada'); end else begin obtenerNombreUsuarioValido(vUsuario, mlvUsuario, nombre); agregarUsuario(vUsuario, mlvUsuario, nombre); end; writeln; writeln('Presione cualquier tecla para volver al menu principal.'); readkey; end; procedure menuIniciarlizar(var vSerie: tvSerie; var mlvSerie: tmlvSerie; var vUsuario: tvUsuario; var mlvUsuario: tmlvUsuario; var vTop: tvTop); {Pre: Recibe el vector Serie, Usuario y Top mas sus maximos logicos. *Post: Carga las series e imprime un mensaje 'series iniciadas' } begin clrscr; inicializar(vSerie, mlvSerie, vUsuario, mlvUsuario, vTop); writeln('Inicializar Series'); writeln; writeln('Series iniciadas'); writeln; writeln('Presione cualquier tecla para volver al menu principal'); readkey; end; procedure menuLimpiarVisualizaciones(var vSerie: tvSerie; mlvSerie: tmlvSerie; var vUsuario: tvUsuario; mlvUsuario: tmlvUsuario); {Pre: Recibe los vectores serie y usuario mas sus maximos logicos. * Post: Limpia las visualizaciones de ambos} var i, j: integer; begin clrscr; writeln('Menu Limpiar Visualizaciones'); for i:= 1 to mlvUsuario do for j:= 1 to vUsuario[i].mlvVisualizacion do limpiarVisualUsuario(vUsuario[i].vVisualizacion[j]); limpiarVisualEpisodios(vSerie, mlvSerie); writeln; writeln('Visualizaciones limpias'); writeln; writeln('Presione cualquier tecla para volver al menu principal.'); readkey; end; procedure imprimirTop(vTop: tvTop); {Pre : Recibe el vector Top * Post: Imprime en pantalla los CANT TOP video mas vistos con sus visualizaciones, episodio * y titulo} var i: integer; begin writeln('TOP ',CANT_TOP); writeln('TOP Visualizaciones Episodio Titulo'); for i:= 1 to CANT_TOP do writeln( format('%3d', [i]), format('%10d', [vTop[i].visualizaciones]), ' ', format('%-30s', [vTop[i].descripcion]), format('%-30s', [vTop[i].titulo])); writeln; writeln('Presione cualquier tecla para volver al menu principal.'); readkey; end; procedure ingresarAlTop(rVideo: trVideo; var vTop: tvTop); {Pre: Recibe un registro de Video con visualizaciones suficientes para entrar en el top * y el vector Top. * Post : Calcula la posicion en la que debe ir el rVideo y se ingresa. Los demas registros * se mueven una posicion con lo cual elimina la ultima posicion del top que habia antes * de invocar el procedimiento} var pos, i : integer; begin pos:= 1; while rVideo.visualizaciones < vTop[pos].visualizaciones do inc(pos); for i:= (CANT_TOP - 1) downto (pos) do vTop[i + 1]:= vTop[i]; vTop[pos] := rVideo; end; procedure calcularTop(vSerie: tvSerie; mlvSerie: tmlvSerie; var vTop: tvTop); {Pre: Recibe el vector Top, vector serie y el maximo logico del vSerie * Post : Carga en el vector Top los videos del vector serie mas vistos. * Los videos con cero visualizaciones no se agregan. * Si dos episodios tienen la misma cantidad de visualizaciones se dejan un posiciones * contiguas.} var i, j, k : integer; begin for i:= 1 to mlvSerie do for j:= 1 to vSerie[i].cantTemp do for k:= 1 to vSerie[i].vTemp[j].cantEpiDeTemp do begin if vSerie[i].vTemp[j].vVideo[k].visualizaciones > vTop[CANT_TOP].visualizaciones then begin ingresarAlTop(vSerie[i].vTemp[j].vVideo[k], vTop); end; end; end; procedure menuTop(vSerie: tvSerie; mlvSerie: tmlvSerie; var vTop: tvTop); {Pre: Recibe el vector serie y top. * Post: Calcula el top de videos mas visto y los imprime por pantalla. * En caso de que el vector series contenga series imprime un error.} begin clrscr; writeln('Menu Top'); writeln; if haySeriesCargadas(vSerie) then begin iniciarTop(vTop); calcularTop(vSerie, mlvSerie, vTop); imprimirTop(vTop); end else begin writeln('ERROR: No hay series cargadas.'); writeln('Presione cualquier tecla para volver al menu principal'); readkey end; end; procedure menuPrincipal(var vSerie: tvSerie; var mlvSerie: tmlvSerie; var vUsuario:tvUsuario; var mlvUsuario: tmlvUsuario; var vTop: tvTop); {Pre: Recibe el vector series, usuario y top mas sus maximos logicos. * Post: Muestra el menu principal} var salir: boolean; opcion: integer; begin salir := False; while not salir do begin clrscr; writeln('Menu Principal'); writeln; writeln('1: Inicializar'); writeln('2: Agregar usuario'); writeln('3: Menu series '); writeln('4: Generar y procesar visualizaciones'); writeln('5: Mostrar top'); writeln('6: Limpiar visualizaciones'); writeln('7: Salir'); writeln; solicitarValor(opcion, 1, 7, 'opcion'); case opcion of 1: menuIniciarlizar(vSerie, mlvSerie, vUsuario, mlvUsuario, vTop); 2: menuAgregarUsuario(vUsuario, mlvUsuario); 3: menuSerie(vSerie, mlvSerie); 4: menuGenerarYProcesarVisualizaciones(vSerie, mlvSerie, vUsuario, mlvUsuario); 5: menuTop(vSerie, mlvSerie, vTop); 6: menuLimpiarVisualizaciones(vSerie, mlvSerie, vUsuario, mlvUsuario); 7: salir:= True; end; end; writeln; writeln('Hasta pronto.'); end; begin end.
program SMBiosTables; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, uSMBIOS { you can add units after this }; procedure ListSMBiosTables; Var SMBios: TSMBios; Entry: TSMBiosTableEntry; begin SMBios := TSMBios.Create; try Writeln(Format('SMBIOS Version %s',[SMBios.SmbiosVersion])); Writeln(Format('%d SMBios tables found',[Length(SMBios.SMBiosTablesList)])); Writeln; Writeln('Type Handle Length Index Description'); for Entry in SMBios.SMBiosTablesList do Writeln(Format('%3d %4x %3d %4d %s',[Entry.Header.TableType, Entry.Header.Handle, Entry.Header.Length, Entry.Index, SMBiosTablesDescr[Entry.Header.TableType]])); finally SMBios.Free; end; end; begin try ListSMBiosTables; except on E:Exception do Writeln(E.Classname, ':', E.Message); end; Writeln('Press Enter to exit'); Readln; end.
unit TestuNextRow; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, System.SysUtils, System.Generics.Collections, System.Generics.Defaults, System.Types, System.Classes, uCSVUpdater; type // Test methods for class TCSVUpdater TTestNextRow = class(TTestCase) strict private FStringStream : TStringStream; public procedure SetUp; override; procedure TearDown; override; published procedure A_Null_Stream_Returns_Empty; procedure An_Empty_Row_Returns_Empty; procedure Correct_Row_Returns_After_Empty_Field; procedure A_Simple_Row_returns_correct_Value; procedure Multiple_Rows_Iteratively_Returns_Correct_Values; procedure Multiple_Rows_Iteratively_Returns_Correct_From_Large_FileStream; procedure A_Row_with_One_Complex_Field_returns_correct_Value; procedure A_Row_With_Two_Complex_Fields_returns_correct_Value; procedure A_Row_with_Multiple_CR_In_One_Field_Returns_Correct_Value; end; implementation uses GlenKleidon.CSVUtils; { TTestNextRow } procedure TTestNextRow.A_Null_Stream_Returns_Empty; var lExpected, lResult : string; begin lResult := nextRow(nil,#13#10, '"'); lExpected := ''; check(lExpected = lResult, 'Expected :"'+lExpected+'"'#13#10 + 'Actual :"'+lResult +'"'); end; procedure TTestNextRow.An_Empty_Row_Returns_Empty; var lExpected, lResult : string; begin self.FStringStream.WriteString(#13#10+'Row2Field1,Row2Field2'); self.FStringStream.Position := 0; lResult := nextRow(Self.FStringStream,#13#10, '"'); lExpected := ''; check(lExpected = lResult, 'Expected :"'+lExpected+'"'#13#10 + 'Actual :"'+lResult +'"'); end; procedure TTestNextRow.A_Row_with_Multiple_CR_In_One_Field_Returns_Correct_Value; begin raise Exception.Create('Not Implemented'); end; procedure TTestNextRow.A_Row_with_One_Complex_Field_returns_correct_Value; begin raise Exception.Create('Not Implemented'); end; procedure TTestNextRow.A_Row_With_Two_Complex_Fields_returns_correct_Value; begin raise Exception.Create('Not Implemented'); end; procedure TTestNextRow.Correct_Row_Returns_After_Empty_Field; var lExpected, lResult : string; begin self.FStringStream.WriteString(#13#10+'Row2Field1,Row2Field2'); self.FStringStream.Position := 0; //Ignore First Row. nextRow(Self.FStringStream,#13#10, '"'); //Return Second Row lResult := nextRow(Self.FStringStream,#13#10, '"'); lExpected := 'Row2Field1,Row2Field2'; check(lExpected = lResult, 'Expected :"'+lExpected+'"'#13#10 + 'Actual :"'+lResult +'"'); end; procedure TTestNextRow.A_Simple_Row_returns_correct_Value; var lExpected, lResult : string; begin self.FStringStream.WriteString('Row1Field1,Row1Field2'#13#10+'Row2Field1,Row2Field2'); self.FStringStream.Position := 0; lResult := nextRow(Self.FStringStream,#13#10, '"'); lExpected := 'Row1Field1,Row1Field2'; check(lExpected = lResult, 'Expected :"'+lExpected+'"'#13#10 + 'Actual :"'+lResult +'"'); end; procedure TTestNextRow.Multiple_Rows_Iteratively_Returns_Correct_Values; var lExpected, lResult : string; begin self.FStringStream.WriteString('Row1Field1,Row1Field2'#13#10+'Row2Field1,Row2Field2'); self.FStringStream.Position := 0; //First Row. lResult := nextRow(Self.FStringStream,#13#10, '"'); //Return Second Row lExpected := 'Row1Field1,Row1Field2'; check(lExpected = lResult, 'ROW1 Expected :"'+lExpected+'"'#13#10 + 'ROW1 Actual :"'+lResult +'"'); lResult := nextRow(Self.FStringStream,#13#10, '"'); lExpected := 'Row2Field1,Row2Field2'; check(lExpected = lResult, 'ROW2 Expected :"'+lExpected+'"'#13#10 + 'ROW2 Actual :"'+lResult +'"'); end; procedure TTestNextRow.Multiple_Rows_Iteratively_Returns_Correct_From_Large_FileStream; var lFileStream : TFileStream; lExpected, lResult: string; c: integer; begin lFilestream := TFileStream.Create(expandFIleName('.\data\lots-of-fun-stuff.csv'),fmOpenRead); try lFilestream.Position := 0; c := 0; //skip over header; lResult := nextRow(lFilestream,#13#10, '"'); while lResult<>'' do begin inc(c); nextRow(lFilestream,#13#10, '"'); nextRow(lFilestream,#13#10, '"'); lResult := nextRow(lFilestream,#13#10, '"'); lExpected := '23,2013-1-9,"Halo Reach","Game","A Prequel to the original and famous Halo series"'; check(lExpected = lResult, 'Row '+ c.ToString + 'Expected :"'+lExpected+'"'#13#10 + 'Row '+ c.ToString + 'Actual :"'+lResult +'"'); end; finally freeandnil(lFilestream); end; end; procedure TTestNextRow.SetUp; begin inherited; self.FStringStream := TStringStream.Create(''); end; procedure TTestNextRow.TearDown; begin inherited; freeAndNil(self.FStringStream); end; initialization // Register any test cases with the test runner RegisterTest(TTestNextRow.Suite); end.
unit viewfoto; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, Menus, Types, getrectinselection; type TStateFoto=(sfPic,sfHint,sfBeforeSelectioned,sfSelectioned,sfMove,sfScale);//текущее состояние фотографии {TmyPoints=record//Точка X,Y:integer; end; } TcoordX=record//координата X точки и признак выколотости X:integer; flag:boolean; end; TmyarrayXs=record//массив координат X точек и признак выколотости X:array of TcoordX; end; TmyXY=record//Строка координата Y и левый и правый край Xl,Xr,Y:integer; end; PmyRect=^TmyRect;//Указатель на координаты прямоугольника {TmyRect=record//координаты прямоугольника xl,yl,xr,yr:integer; end; } ParRect=^TarRect;//Указатель на массив прямоугольников выделения TarRect=array of TmyRect;//массив прямоугольников выделения PmySortarray=^TmySortarray;//Указатель на отсортированный список укзателей???(возможно не нужно) TmySortarray=array of PmyRect;//отсортированный список указателей???(возможно не нужно) PcurSelection=^TmySelection;//указатель на ваделенную область TmySelection=record//Выделенная область xmin,xmax:integer; ymin,ymax:integer; FRects:array of TmyRect; FSortRectsfor_Y_top:TmySortarray;//???(возможно не нужно) end; TmyListSelections=array of TmySelection;//Список выделенных ообластей { Tfrmviewfoto } Tfrmviewfoto = class(TForm) MenuItem1: TMenuItem; PopupMenu1: TPopupMenu; ScrollBox1: TScrollBox; ShapeFoto: TShape; Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure MenuItem1Click(Sender: TObject); procedure ShapeFotoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ShapeFotoMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure ShapeFotoMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ShapeFotoMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure ShapeFotoMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure ShapeFotoPaint(Sender: TObject); procedure Timer1Timer(Sender: TObject); private FcountStroki:integer; aRow:integer; FbmpFoto:TBitmap; Fstate:byte; //0-не рисуем, 1-рисуем Ffirstview:boolean; FminY,FmaxY:integer; FarrayPoint:array of TmyPoints;//Точки обведенного контура FXinY: array of TmyarrayXs;//Значения Х распределенные по Y - строкам FStroki:array of TmyXY; //FRects:array of TmyRect; //????? FListSelections:TmyListSelections; FStateFoto:TStateFoto;//0-исходная картинка,1-всплывающая подсказка,2-выделение Fcountpoint:integer; procedure SearchStartSelect;//Ищем вверху начало областей которые можно заполнить procedure FillSelection(leftx_l,leftx_r,y_start:integer;indexright_old:integer=-1);//Заполняем область procedure CreateRect; procedure SortRectInSelection(curSelection:PcurSelection); procedure checkSelections(x,y:integer); procedure MoveXinY; procedure AddPoints(xold,yold,x,y:integer); procedure checkstateDown(Sender: TObject;Button: TMouseButton); procedure checkstateUp(Sender: TObject;Button: TMouseButton); function checkstateMove(Sender: TObject;Button: TShiftState):boolean; procedure Test;//Временная процедура для тестирования const ColorSelect = clYellow; const WidthSelect = 1; const Fdeltax = 15; public procedure setFoto(jpg:TJpegImage); end; var frmviewfoto: Tfrmviewfoto; implementation {$R *.lfm} { Tfrmviewfoto } procedure Tfrmviewfoto.FormShow(Sender: TObject); begin if not Ffirstview then begin shapeFoto.Width:=FbmpFoto.Width; shapeFoto.Height:=FbmpFoto.Height; shapeFoto.Canvas.Draw(0,0,FbmpFoto); //shapeFoto:=0; Ffirstview:=true; Setlength(Farraypoint,2*FbmpFoto.Width+2*FbmpFoto.Height); end; timer1.Enabled:=true; end; procedure Tfrmviewfoto.MenuItem1Click(Sender: TObject); begin FStateFoto:=sfBeforeSelectioned;//переводим в режим подготовки к рисованию end; procedure Tfrmviewfoto.ShapeFotoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin //checkstateDown(Sender,Button); end; procedure Tfrmviewfoto.ShapeFotoMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if not checkstateMove(Sender,Shift) then exit; case FStateFoto of sfSelectioned: begin if FState=0 then //если перед этим не была нажата левая клавиша begin FState:=1;//признак того, что мы выделяем Fcountpoint:=0; shapeFoto.Canvas.Pixels[x,y]:=ColorSelect;//рисуем начальную точку Farraypoint[Fcountpoint].X:=X;//координаты первой точки Farraypoint[Fcountpoint].Y:=Y; if Y<FminY then FminY:=Y; if Y>FmaxY then FmaxY:=Y; exit; end; if Y<FminY then FminY:=Y; if Y>FmaxY then FmaxY:=Y; if (abs(Farraypoint[Fcountpoint].X-X)>1)or(abs(Farraypoint[Fcountpoint].Y-Y)>1) then//если есть дырка //то добавляем точки addPoints(Farraypoint[Fcountpoint].X,Farraypoint[Fcountpoint].Y,X,Y);//добавляем точки между старой и новой точкой inc(Fcountpoint);//увеличиваем счетчик if Fcountpoint>high(Farraypoint) then setlength(Farraypoint,2*high(Farraypoint));//если необходимо увеличиваем массив Farraypoint[Fcountpoint].X:=X;//координаты новой точки Farraypoint[Fcountpoint].Y:=Y; shapeFoto.Canvas.Pixels[Farraypoint[Fcountpoint].X,Farraypoint[Fcountpoint].Y]:=ColorSelect;//рисуем новую точку на экране //shapeFoto.Invalidate; end; sfPic: begin //checkSelections(X,Y); end; end; end; procedure Tfrmviewfoto.ShapeFotoMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var i:integer; begin checkstateUP(Sender,Button); exit; if Fstate=0 then exit; //Если мы не выделяли перед этим то выходим if (abs(Farraypoint[Fcountpoint].X-Farraypoint[0].X)>1)or (abs(Farraypoint[Fcountpoint].Y-Farraypoint[0].Y)>1) then //если между конечной и начальной точкой дырка, то заполняем её addPoints(Farraypoint[Fcountpoint].X,Farraypoint[Fcountpoint].Y,Farraypoint[0].X,Farraypoint[0].Y); FState:=0;//признак того, что мы не выделяем for i:=0 to Fcountpoint do FbmpFoto.Canvas.Pixels[farraypoint[i].X,farraypoint[i].Y]:=ColorSelect;//рисуем точки в памяти MoveXinY; SearchStartSelect; //CreateRect; end; procedure Tfrmviewfoto.ShapeFotoMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin end; procedure Tfrmviewfoto.ShapeFotoMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin end; procedure Tfrmviewfoto.MoveXinY;//группируем точки по координате Y var i,ii,coordY,lastX:integer; begin setlength(FXinY,FmaxY-FminY+1); for i:=0 to Fcountpoint do//high(farraypoint) do begin coordY:=farraypoint[i].Y-FminY; if high(FXinY[coordY].X)=-1 then setlength(FXinY[coordY].X,1) else setlength(FXinY[coordY].X,high(FXinY[coordY].X)+2); lastX:=high(FXinY[coordY].X); FXinY[coordY].X[lastX].X:=farraypoint[i].X; for ii:=lastX downto 1 do begin if farraypoint[i].X<FXinY[coordY].X[ii-1].X then begin FXinY[coordY].X[ii].X:=FXinY[coordY].X[ii-1].X; FXinY[coordY].X[ii-1].X:=farraypoint[i].X; end else break; end; end; end; procedure Tfrmviewfoto.Test; var f:textfile; tmpstr:string; i,count,countX:integer; sl:TStringList; first:boolean; begin first:=false; FXinY:=nil; if not fileexists(ExtractFilePath(Application.ExeName)+{directoryseparator+}'тест.csv') then exit; finalize(FXinY); sl:=TStringList.Create; assignfile(f,ExtractFilePath(Application.ExeName)+{directoryseparator+}'тест.csv'); reset(f); count:=0; while not eof(f) do begin readln(f, tmpstr); if not first then begin first:=true; continue; end; inc(count); setlength(FXinY,count); extractstrings([';'],['0'],pchar(tmpstr),sl,true); //showmessage(sl.Text); countX:=0; for i:=1 to sl.Count-1 do begin if sl[i]='1' then begin inc(countX); setlength(FXinY[count-1].X,countX); FXinY[count-1].X[countX-1].X:=i+450; FbmpFoto.Canvas.Pixels[FXinY[count-1].X[countX-1].X,count+550]:=clyellow; //ShapeFoto.Repaint; end; end; sl.Clear; end; closefile(f); FreeAndNil(sl); ShapeFoto.Refresh; FminY:=551; FmaxY:=550+count; SearchStartSelect; CreateRect; end; procedure Tfrmviewfoto.SearchStartSelect;//поиск начальных позиций для закрашивания var ix,iy,Min,max:integer; procedure SearchHole(min,max,y:integer);//Поиск двух не соседних точек var iix,leftl,leftr:integer; begin //Проверяем наличие двух не соседних точек leftl:=-1; leftr:=-1; for iix:=0 to high(FXiny[y].X) do begin if FXinY[y].X[iix].flag then continue; if FXinY[y].X[iix].X>(max+1) then break; if leftl=-1 then begin leftl:=FXinY[y].X[iix].X;//Кандидат на левую границу leftr:=FXinY[y].X[iix].X;//Кандидат на правую границу continue; end; if (leftr+1)=FXinY[y].X[iix].X then//сосед begin leftr:=FXinY[y].X[iix].X;//новая правая граница continue; end else begin if ((leftr+1)>=min)and((leftr+1)<=max)and((FXinY[y].X[iix].X-leftr)>1) then begin FillSelection(leftl,FXinY[y].X[iix].X,y); leftl:=-1; leftr:=-1; continue; end else begin leftl:=FXinY[y].X[iix].X;//Кандидат на левую границу leftr:=FXinY[y].X[iix].X;//Кандидат на правую границу end; end; end; end; begin //Ищем одну(одинокую) точку или последовательность точек не выколотую min:=-1; setlength(FStroki, (high(FXinY)+1)*2); for iy:=0 to high(FXinY) do begin for ix:=0 to high(FXinY[iy].X) do begin if (min=-1) and (not FXinY[iy].X[ix].flag) then begin min:=ix; max:=min; continue; end; if ((FXinY[iy].X[ix].X-1)=FXinY[iy].X[max].X) and (not FXinY[iy].X[ix].flag) then//соседняя точка и не выколотая begin max:=ix; continue; end else begin SearchHole(FXinY[iy].X[min].X,FXinY[iy].X[max].X,iy+1); min:=ix; max:=min; end; end; if (min>-1)and(max>-1)and(iy<high(FXinY)) then SearchHole(FXinY[iy].X[min].X,FXinY[iy].X[max].X,iy+1); min:=-1; max:=-1; end; setlength(FStroki,FcountStroki); dec(FcountStroki); end; procedure Tfrmviewfoto.FillSelection(leftx_l, leftx_r, y_start: integer; indexright_old: integer); var iy,ixl,indexleft,indexleftold,indexrightold,indexright,leftxold,rightxold,leftxtmp,leftxnew,rightxnew:integer; first,firstline,endfill:boolean; startFcountStroki:integer; function checknewstring:byte;{проверяем надо ли искать первую точку строки или она уже найдена } begin if (leftxtmp=-1) then //начало поиска новой строки - значит ищем первую точку begin if FXinY[iy].x[ixl].flag then begin//если очередная точка "выколота"(уже использовалась), то переходим к следующей точке result:=2; exit; end; if ((rightxold-1)<=FXinY[iy].x[ixl].X){нет дырки - есть разрыв заполнения т.е.если новая точка "слишком" справа} then begin leftxtmp:=-1; result:=1;//значит прекращаем заполнение - все exit; end; indexleft:=ixl;//запоминаем индекс левого края левой границы //кандидат на левый край левой границы leftxtmp:=FXinY[iy].x[ixl].X; indexright:=ixl;//запоминаем индекс правого края левой границы result:=2; end else result:=255; end; function checknewrightedgeleftborder:byte; begin if ((rightxold-1)<=FXinY[iy].x[ixl].X)//нет дырки - есть разрыв заполнения then //если новая точка "слишком" справа begin leftxtmp:=-1;//поиск левой границы заново if leftxnew=-1 then result:=0 else result:=1;//если первоначальное заполнение, то прекращаем заполнение, иначе переходим к первоначальному exit; end; if FXinY[iy].x[ixl].flag then //если очередная(соседняя) точка "выколота", то переходим к следующей точке begin leftxtmp:=-1;//поиск левой границы заново result:=2;//переход к следующей точке exit; end; //кандидат на правый край левой границы leftxtmp:=FXinY[iy].x[ixl].X;//Устанавливаем новую левую границу indexright:=ixl;//запоминаем индекс правого края левой границы result:=2; end; function checkrightborder:boolean; begin result:=true; if firstline and FXinY[iy].x[ixl].flag then //если очередная точка "выколота", то переходим к следующей точке begin leftxtmp:=-1; result:=false; exit; end; if ((leftxold+1)>=FXinY[iy].x[ixl].X)//нет дырки - есть разрыв заполнения then //если новая точка "слишком" слева begin leftxtmp:=-1; dec(ixl); { indexleft:=ixl; //кандидат на левую границу leftxtmp:=FXinY[iy].x[ixl].X; indexright:=ixl; if ((rightxold-1)<=FXinY[iy].x[ixl].X)//нет дырки - есть разрыв заполнения then //если новая точка "слишком" справа begin leftxtmp:=-1; if leftxnew=-1 then result:=0 else result:=1; exit; end;} result:=false; end; end; procedure correctpoint; begin if (FXinY[iy].X[indexright].X<(FXinY[iy-1].X[indexleftold].X-1))and(indexleftold>-1) then//если левый край линии сильно левее предыдущей границы FXinY[iy-1].X[indexleftold].flag:=false;//отменяем выкалывание, иначе будет пропуск строки if (FXinY[iy].x[ixl].X>(FXinY[iy-1].X[indexrightold].X+1))and(indexrightold>-1) then//если правый край линии сильно правее предыдущей границы FXinY[iy-1].X[indexrightold].flag:=false;//отменяем выкалывание, иначе будет пропуск строки end; function checksharppeakright:boolean; begin result:=//(FXinY[iy].x[ixl].X<(FXinY[iy-1].X[indexrightold].X-1))and(indexrightold>-1)//если правый край линии сильно левее предыдущей границы (FXinY[iy].x[ixl].X<(rightxold-1))and(indexrightold>-1)//если правый край линии сильно левее предыдущей границы and(high(FXinY[iy].x)>ixl)and//и это не последняя точка ((FXinY[iy].x[ixl+1].X-1)<>FXinY[iy].x[ixl].X)//и следующая точка не соседняя, т.е. острая вершина end; begin shapeFoto.Canvas.Pen.Color:=clblue; leftxold:=leftx_l; rightxold:=leftx_r; leftxtmp:=-1; leftxnew:=-1; rightxnew:=-1; first:=false; endfill:=false; firstline:=true; indexleftold:=-1; indexrightold:=indexright_old; startFcountStroki:=FcountStroki; for iy:=y_start to high(FXinY) do begin for ixl:=0 to high(FXinY[iy].x) do begin case checknewstring of //Если ищем первую точку, то 0,1: if not first then begin endfill:=true; break; end else break;//прекращаем заполнение - очередная левая точка не найдена //1:break;//пробуем продолжить заполнение со следующей строки - если было вторичное заполнение ??? 2:continue;//левая точка найдена или выколота переходим к следующей end; //если ищем вторую точку if (FXinY[iy].x[ixl].X-1)=(FXinY[iy].x[ixl-1].X) then//если СОСЕДНЯЯ точка begin case checknewrightedgeleftborder of ////ищем правый край левой границы 0,1: begin//прекращаем заполнение if indexrightold>-1 then begin endfill:=true; break; end else exit; end; //1:break;//переходим к первоначальному заполнению 2:continue;//левая точка найдена или выколота переходим к следующей end; end else //если НЕ соседняя точка begin if not checkrightborder then //ищем правый край линии continue; //получаем отрезок if first then //Если в данной строке это уже не первая линия, то начинаем заполнение в новой процедуре begin if (leftxtmp>=(rightxold-1))then //если новая левая граница намного правее предыдущей правой, т.е. нет дырки есть разрыв заполнения break; FillSelection(leftxtmp,FXinY[iy].x[ixl].X,iy,indexrightold); leftxtmp:=-1; continue; end; first:=true;//признак того, что в этой строке уже нарисован отрезок correctpoint; FXinY[iy].X[indexright].flag:=true;//выкалываем левую границу if checksharppeakright then //Если справа оказалась острая вершина begin //FillSelection(FXinY[iy].x[ixl].X,FXinY[iy].x[ixl+1].X,iy); FillSelection(FXinY[iy].x[ixl].X,rightxold,iy,indexrightold); end else FXinY[iy].x[ixl].flag:=true;//выкалываем правую границу if FcountStroki>high(FStroki) then setlength(Fstroki,(high(Fstroki)+1)+2*(high(FXinY)+1));//Если массив не вмещает точки, то увеличиваем размер массива FStroki[FcountStroki].Y:=iy+FminY; FStroki[FcountStroki].Xl:=leftxtmp+1; FStroki[FcountStroki].Xr:=FXinY[iy].x[ixl].X-1; shapeFoto.Canvas.Line(leftxtmp+1,iy+FminY,FXinY[iy].x[ixl].X,iy+FminY); //sleep(100); inc(FcountStroki); leftxnew:=leftxtmp; rightxnew:=FXinY[iy].x[ixl].X; indexleftold:=indexleft; indexrightold:=ixl; leftxtmp:=-1; if firstline then firstline:=false; end; end; if endfill then begin break; end; if leftxnew=-1 then break //Если отрезок не найден, то прекращаем else begin leftxold:=leftxnew; rightxold:=rightxnew; leftxnew:=-1; rightxnew:=-1; first:=false; end; end; if not endfill then begin FcountStroki:=startFcountStroki; end; end; procedure Tfrmviewfoto.CreateRect; var Rct:ParRect;//Для удобства чтобы запись покороче была(вместо FListSelections[high(FListSelections)].FRects) curSelection:PcurSelection;//Для удобства - запись короче (вместо FListSelections[high(FListSelections)]) procedure saveRect(xl,yl,xr,yr,numberRect:integer); begin Rct^[numberRect].xl:=xl; Rct^[numberRect].yl:=yl; Rct^[numberRect].xr:=xr; Rct^[numberRect].yr:=yr; if xl<curSelection^.xmin then curSelection^.xmin:=xl; if xr>curSelection^.xmax then curSelection^.xmax:=xr; if yl<curSelection^.ymin then curSelection^.ymin:=yl; if yr>curSelection^.ymax then curSelection^.ymax:=yr; //временно рисуем потом убрать //FbmpFoto.Canvas.frame(FRects[numberRect].xl,FRects[numberRect].yl,FRects[numberRect].xr+1,FRects[numberRect].yr+1);//добавляем 1 т.к. рисуется до этой координаты ShapeFoto.Canvas.frame(Rct^[numberRect].xl,Rct^[numberRect].yl,Rct^[numberRect].xr+1,Rct^[numberRect].yr+1); //ShapeFoto.Canvas.Pixels[Rct^[numberRect].xr+1,Rct^[numberRect].yr+1]:=clred; //ShapeFoto.Canvas.Pixels[Rct^[numberRect].xl,Rct^[numberRect].yl]:=clred; end; var istr:integer; xl,yl,xr,yr,curRect,sumxl,sumxr,countStrok:integer; procedure InitNewRect(); begin xl:=FStroki[istr].Xl; sumxl:=xl; yl:=FStroki[istr].Y; xr:=FStroki[istr].Xr; sumxr:=xr; yr:=FStroki[istr].Y; countStrok:=1; end; begin if high(FListSelections)=-1 then setlength(FListSelections,1) else setlength(FListSelections,high(FListSelections)+2); curSelection:=@FListSelections[high(FListSelections)]; //FbmpFoto.Canvas.Pen.Width:=1; ShapeFoto.Canvas.Pen.Width:=1; //FbmpFoto.Canvas.Pen.color:=clgreen; shapeFoto.Canvas.Pen.color:=clgreen; curRect:=0; xl:=-1; yl:=-1; xr:=-1; yr:=-1; sumxl:=0; sumxr:=0; countStrok:=0; Setlength(curSelection^.FRects,high(FStroki)+1); Rct:=@curSelection^.FRects; curSelection^.xmin:=maxLongint; curSelection^.xmax:=-maxLongint; curSelection^.ymin:=maxLongint; curSelection^.ymax:=-maxLongint; for istr:=0 to high(FStroki) do begin shapeFoto.Canvas.Line(FStroki[istr].Xl,FStroki[istr].Y,FStroki[istr].Xr,FStroki[istr].Y);//Заливаем выделенную область continue; if xl=-1 then//новый прямоугольник в самом начале begin InitNewRect; continue; end; if (abs(FStroki[istr].Xl-xl)<=Fdeltax)and(abs(FStroki[istr].Xr-xr)<=Fdeltax)and//разница между краями не больше допустимого(Fdeltax) (FStroki[istr].Xr>=(FStroki[istr-1].Xl+1))//не новое заполнение then begin sumxl:=sumxl+FStroki[istr].Xl; sumxr:=sumxr+FStroki[istr].Xr; yr:=FStroki[istr].Y; inc(countStrok); //continue; end else begin //сохраним прямоугольник saveRect(round(sumxl/countStrok),yl,round(sumxr/countStrok),yr,currect); inc(currect); //новый прямоугольник InitNewRect; end; end; if xl>-1 then begin //сохраним прямоугольник saveRect(round(sumxl/countStrok),yl,round(sumxr/countStrok),yr,currect); end; Setlength(Rct^,currect+1); Rct:=nil; SortRectInSelection(curSelection);//Сортируем по координате Y ??? curSelection:=nil; end; procedure Tfrmviewfoto.SortRectInSelection(curSelection: PcurSelection); procedure SelectionSort_top(curarrayRects: PmySortarray); //сортировка выбором var i,ii,best_i:integer; best_value:PmyRect; begin for i:=0 to high(curarrayRects^)-1 do begin best_value:=curarrayRects^[i]; best_i:=i; for ii:=i+1 to high(curarrayRects^) do if curarrayRects^[ii]^.yl<best_value^.yl then begin best_value:=curarrayRects^[ii]; best_i:=ii; end; curarrayRects^[best_i]:=curarrayRects^[i]; curarrayRects^[i]:=best_value; end; end; var i:integer; begin //Зададим размеры массивов указателей для сортировки setlength(curSelection^.FSortRectsfor_Y_top,high(curSelection^.FRects)+1); //инициализируем массивы for i:=0 to high(curSelection^.FSortRectsfor_Y_top) do curSelection^.FSortRectsfor_Y_top[i]:=@curSelection^.FRects[i]; SelectionSort_top(@curSelection^.FSortRectsfor_Y_top);//сортируем по Y левый верхний угол по возрастанию end; procedure Tfrmviewfoto.checkSelections(x, y: integer); function checkSelect(index:integer):boolean; begin result:=(y>=FListSelections[index].ymin)and (y<=FListSelections[index].ymax)and (x>=FListSelections[index].xmin)and (x<=FListSelections[index].xmax); end; function checkRect(index:integer):boolean; var i:integer; begin result:=false; for i:=0 to high(FListSelections[index].FSortRectsfor_Y_top) do begin if (y>=FListSelections[index].FSortRectsfor_Y_top[i]^.yl)and (y<=FListSelections[index].FSortRectsfor_Y_top[i]^.yr)and (x>=FListSelections[index].FSortRectsfor_Y_top[i]^.xl)and (x<=FListSelections[index].FSortRectsfor_Y_top[i]^.xr)then begin result:=true; ShapeFoto.Canvas.Pen.Color:=clred; ShapeFoto.Canvas.Frame(FListSelections[index].FSortRectsfor_Y_top[i]^.xl, FListSelections[index].FSortRectsfor_Y_top[i]^.yl, FListSelections[index].FSortRectsfor_Y_top[i]^.xr+1, FListSelections[index].FSortRectsfor_Y_top[i]^.yr+1); break; end; end; end; var isel:integer; begin for isel:=0 to high(FListSelections) do if checkSelect(isel) then if checkRect(isel) then begin //Что-то делаем break; end; end; procedure Tfrmviewfoto.ShapeFotoPaint(Sender: TObject); begin if FbmpFoto<>nil then ShapeFoto.Canvas.CopyRect(ShapeFoto.Canvas.ClipRect,FbmpFoto.Canvas,ShapeFoto.Canvas.ClipRect);//перерисовываем только испорченную область, свойство cliprect end; procedure Tfrmviewfoto.Timer1Timer(Sender: TObject); begin timer1.Enabled:=false; //test; end; procedure Tfrmviewfoto.FormCreate(Sender: TObject); begin Ffirstview:=false; FState:=0; Fcountpoint:=0; WindowState:=wsMaximized; FminY:=MaxInt; FmaxY:=-MaxInt; FcountStroki:=0; aRow:=1; end; procedure Tfrmviewfoto.AddPoints(xold, yold, x, y: integer); var i,deltax,deltay,maxi,znak:integer; step:extended; begin deltax:=x-xold;deltay:=y-yold; maxi:=0; if abs(deltay)>=abs(deltax) then begin step:=deltax/abs(deltay); if deltay<0 then znak:=-1 else znak:=1; maxi:=abs(deltay)-1; end else begin step:=deltay/abs(deltax); if deltax<0 then znak:=-1 else znak:=1; maxi:=abs(deltax)-1; end; for i:=1 to maxi do begin inc(Fcountpoint); if abs(deltay)>=abs(deltax) then begin farraypoint[Fcountpoint].X:=xold+round(step*i); farraypoint[Fcountpoint].Y:=yold+znak*i; end else begin farraypoint[Fcountpoint].X:=xold+znak*i; farraypoint[Fcountpoint].Y:=yold+round(step*i); end; shapeFoto.Canvas.Pixels[farraypoint[Fcountpoint].X,farraypoint[Fcountpoint].Y]:=ColorSelect; end; end; procedure Tfrmviewfoto.checkstateDown(Sender: TObject; Button: TMouseButton); begin end; procedure Tfrmviewfoto.checkstateUp(Sender: TObject; Button: TMouseButton); var i:integer; begin if (Sender is TShape) then//Если событие вызвала фотография begin case Button of mbLeft://Если нажата левая клавиша begin case FStateFoto of sfPic://Если фотка находится в исходном состоянии begin PopupMenu1.PopUp;//Покажем контекстное меню end; sfSelectioned: begin FStateFoto:=sfPic; if (abs(Farraypoint[Fcountpoint].X-Farraypoint[0].X)>1)or (abs(Farraypoint[Fcountpoint].Y-Farraypoint[0].Y)>1) then //если между конечной и начальной точкой дырка, то заполняем её addPoints(Farraypoint[Fcountpoint].X,Farraypoint[Fcountpoint].Y,Farraypoint[0].X,Farraypoint[0].Y); MoveXinY; SearchStartSelect; //CreateRect; {if high(FListSelections)=-1 then setlength(FListSelections,1) else setlength(FListSelections,high(FListSelections)+2); FListSelections[high(FListSelections)].FRects:=getRectFromPoints(Farraypoint,Fcountpoint,Fdeltax,FminY,FmaxY);} //ShapeFoto.Canvas.Pen.Color:=clred; {for i:=0 to high(FListSelections[high(FListSelections)].FRects)-1 do ShapeFoto.Canvas.Frame(FListSelections[high(FListSelections)].FRects[i].xl, FListSelections[high(FListSelections)].FRects[i].yl, FListSelections[high(FListSelections)].FRects[i].xr ,FListSelections[high(FListSelections)].FRects[i].yr); } end; end; end; end; end; end; function Tfrmviewfoto.checkstateMove(Sender: TObject; Button: TShiftState ): boolean; begin if (Sender is TShape) then//Если событие вызвала фотография begin if (ssLeft in Button) then //Если нажата левая клавиша begin case FStateFoto of sfBeforeSelectioned://готова начать выделение begin FStateFoto:=sfSelectioned; result:=true; end; end; end; end; end; procedure Tfrmviewfoto.setFoto(jpg: TJpegImage); begin if FbmpFoto=nil then FbmpFoto:=TBitMap.Create; FbmpFoto.SetSize(jpg.Width,jpg.Height); FbmpFoto.Canvas.Draw(0,0,jpg); end; end.
unit gpsptform; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, ButtonPanel, ColorBox, Spin, mvExtraData; type TGPSSymbol = (gpsPlus, gpsCross, gpsFilledCircle, gpsOpenCircle, gpsFilledRect, gpsOpenRect); TGPSExtraData = class(TDrawingExtraData) private FSymbol: TGPSSymbol; FSize: Integer; public constructor Create(aID: Integer); override; property Symbol: TGPSSymbol read FSymbol write FSymbol; property Size: Integer read FSize write FSize; end; { TGPSPointForm } TGPSPointForm = class(TForm) ButtonPanel1: TButtonPanel; clbSymbolColor: TColorBox; cbSymbols: TComboBox; edGPSPointLabel: TEdit; Label1: TLabel; Label2: TLabel; lblSymbol: TLabel; lblSize: TLabel; Panel1: TPanel; seSize: TSpinEdit; procedure FormShow(Sender: TObject); private public procedure GetData(var AName: String; var AColor: TColor; var ASymbol: TGPSSymbol; var ASize: Integer); procedure SetData(const AName: String; AColor: TColor; ASymbol: TGPSSymbol; ASize: Integer); end; var GPSPointForm: TGPSPointForm; implementation {$R *.lfm} constructor TGPSExtraData.Create(aID: Integer); begin inherited Create(aID); FSymbol := gpsPlus; FSize := 10; end; procedure TGPSPointForm.FormShow(Sender: TObject); begin edGPSPointLabel.SetFocus; end; procedure TGPSPointForm.GetData(var AName: String; var AColor: TColor; var ASymbol: TGPSSymbol; var ASize: Integer); begin AName := edGPSPointLabel.Text; AColor := clbSymbolColor.Selected; ASymbol := TGPSSymbol(cbSymbols.ItemIndex); ASize := seSize.Value; end; procedure TGPSPointForm.Setdata(const AName: String; AColor: TColor; ASymbol: TGPSSymbol; ASize: Integer); begin edGPSPointLabel.Text := AName; clbSymbolColor.Selected := AColor; cbSymbols.ItemIndex := ord(ASymbol); seSize.Value := ASize end; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { Copyright(c) 2016 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit FMX.TextLayout.GPU; {$MINENUMSIZE 4} interface {$SCOPEDENUMS ON} uses System.Types, System.UITypes, System.Generics.Collections, FMX.Types, FMX.TextLayout, FMX.FontGlyphs, FMX.Graphics; type PCharRec = ^TCharRec; TCharRec = record Glyph: TFontGlyph; SrcRect: TRectF; Bitmap: TBitmap; BitmapRef: Boolean; end; TCharDic = class(TDictionary<UCS4Char, PCharRec>) private FBaseline: Single; procedure CharRecNotifyHandler(Sender: TObject; const Value: PCharRec; Action: System.Generics.Collections.TCollectionNotification); public constructor Create(ACapacity: Integer = 0); property Baseline: Single read FBaseline write FBaseline; end; TFamilyDic = class(TDictionary<Int64, TCharDic>) private procedure CharDicNotifyHandler(Sender: TObject; const Value: TCharDic; Action: System.Generics.Collections.TCollectionNotification); public constructor Create; end; (* --------GPUFrame------------- |(GPURun)(GPURun)...(GPURun)| <- GPULine (several GPURun's with different font and/or color) |(GPURun) | <- GPULine (no additional styling, so only a single GPURun) |(GPURun) | <- GPULine | | ... | | | | ----------------------------- *) TGPURun = class private FChars: TList<UCS4Char>; FStartIndex: Integer; FLength: Integer; FImageRect: TRectF; FColor: TAlphaColor; FFont: TFont; FIsDefaultColor: Boolean; FTrimmed: Boolean; FClipBounds: TList<TRectF>; FClipped: Boolean; public constructor Create; destructor Destroy; override; procedure SetColor(AColor: TAlphaColor; IsDefault: Boolean); procedure Clip; procedure SetText(const AText: string; const AStartIndex, ALength: Integer); procedure DeleteTextFromStart(ACount: Integer); procedure DeleteTextFromEnd(ACount: Integer); // property Chars: TList<UCS4Char> read FChars; property StartIndex: Integer read FStartIndex; property Length: Integer read FLength; property ImageRect: TRectF read FImageRect write FImageRect; property Color: TAlphaColor read FColor; property IsDefaultColor: Boolean read FIsDefaultColor; property Font: TFont read FFont write FFont; property IsTrimmed: Boolean read FTrimmed write FTrimmed; property IsClipped: Boolean read FClipped; property ClipBounds: TList<TRectF> read FClipBounds; end; TGPULine = class(TList<TGPURun>) private FHeight: Single; FWidth: Single; FTopLeft: TPointF; public constructor Create; destructor Destroy; override; // property Height: Single read FHeight write FHeight; property Width: Single read FWidth write FWidth; property TopLeft: TPointF read FTopLeft write FTopLeft; end; TGPUFrame = class(TList<TGPULine>) private FHeight: Single; FWidth: Single; FTopLeft: TPointF; public constructor Create; destructor Destroy; override; // property TopLeft: TPointF read FTopLeft write FTopLeft; property Height: Single read FHeight write FHeight; property Width: Single read FWidth write FWidth; end; TTextLayoutNG = class(TTextLayout) public const AntialiasMargin = 1; MaxUsefulCharMapOccupancy = 0.95; // At 5% of free space or lower the charmap is considered full. public type TCharMap = record Texture: TBitmap; BinPack: TGuillotineBinPack; end; TCharMaps = TList<TCharMap>; private class var FFamilyDic: TFamilyDic; FCharMaps: TCharMaps; FRendering: Integer; FNewGlyphList: TList<PCharRec>; FDisableGlyphPopulation: Boolean; private FOldColor: TAlphaColor; FScale: Single; FScaleFactor: Single; FFrame: TGPUFrame; FFrame3D: TGPUFrame; FEllipsisChar: UCS4Char; FFontKey: Int64; FStrokeBrush: TStrokeBrush; procedure CharMapNotify(Sender: TObject; const Item: TCharMap; Action: System.Generics.Collections.TCollectionNotification); function CreateFrame: TGPUFrame; procedure ApplyAttributes(AFrame: TGPUFrame); function MeasureRange(APos, ALength: Integer): TRegion; function GetCharDictionary(const AFont: TFont = nil): TCharDic; procedure UpdateCharRec(const ACanvas: TCanvas; NeedBitmap: Boolean; var NewRec: PCharRec; HasItem: Boolean; const CharDic: TCharDic; const AFont: TFont; const Ch: UCS4Char; const NeedPath: Boolean = False); function AddOrGetChar(const ACanvas: TCanvas; const Ch: UCS4Char; const CharDic: TCharDic; const AFont: TFont; const NeedPath: Boolean = False): PCharRec; class procedure MapGlyphToCache(CharRec: PCharRec); protected procedure DoRenderLayout; override; procedure DoDrawLayout(const ACanvas: TCanvas); override; function GetTextHeight: Single; override; function GetTextWidth: Single; override; function GetTextRect: TRectF; override; function DoPositionAtPoint(const APoint: TPointF): Integer; override; function DoRegionForRange(const ARange: TTextRange): TRegion; override; public constructor Create(const ACanvas: TCanvas = nil); override; destructor Destroy; override; class procedure Uninitialize; class procedure BeginRender; class procedure EndRender; class property CharMaps: TCharMaps read FCharMaps; class property DisableGlyphPopulation: Boolean read FDisableGlyphPopulation write FDisableGlyphPopulation; // procedure ConvertToPath(const APath: TPathData); override; end; implementation uses System.Classes, System.Math, System.SysUtils, System.Character, System.Math.Vectors, FMX.Consts, FMX.Platform, FMX.Canvas.GPU, FMX.Text; const BitmapSize = 1024; function FontStyleToInt(const AStyle: TFontStyles): Cardinal; begin Result := $F00000; if TFontStyle.fsBold in AStyle then Result := Result + $10000; if TFontStyle.fsItalic in AStyle then Result := Result + $20000; end; function FontFamilyToInt(const AFamily: string): Int64; var I: Integer; begin Result := AFamily.Length; for I := 0 to AFamily.Length - 1 do Result := Result + Ord(AFamily.Chars[I]); end; function FontFamilyKey(const AFont: TFont; const AScale: Single): Int64; begin if SameValue(AScale, 1.0, Epsilon) then Result := $FF000000 + FontFamilyToInt(AFont.Family) + FontStyleToInt(AFont.Style) + (1000 * Trunc(AFont.Size)) else Result := $0F000000 + FontFamilyToInt(AFont.Family) + FontStyleToInt(AFont.Style) + (1000 * Trunc(AFont.Size)); end; function IsCombiningCharacter(const Ch: Char): Boolean; begin Result := Ch.GetUnicodeCategory in [TUnicodeCategory.ucCombiningMark, TUnicodeCategory.ucEnclosingMark, TUnicodeCategory.ucNonSpacingMark] end; { TCharDic } procedure TCharDic.CharRecNotifyHandler(Sender: TObject; const Value: PCharRec; Action: System.Generics.Collections.TCollectionNotification); begin if Action = cnRemoved then begin FreeAndNil(Value.Glyph); if not Value.BitmapRef then FreeAndNil(Value.Bitmap); Dispose(Value); end; end; constructor TCharDic.Create(ACapacity: Integer); begin inherited Create(ACapacity); OnValueNotify := CharRecNotifyHandler; end; { TFamilyDic } procedure TFamilyDic.CharDicNotifyHandler(Sender: TObject; const Value: TCharDic; Action: System.Generics.Collections.TCollectionNotification); begin if Action = cnRemoved then Value.DisposeOf; end; constructor TFamilyDic.Create; begin inherited Create; OnValueNotify := CharDicNotifyHandler; end; { TNGRun } procedure TGPURun.Clip; var I: Integer; begin if not FClipped then begin FClipped := True; FClipBounds := TList<TRectF>.Create; for I := 0 to FChars.Count - 1 do FClipBounds.Add(TRectF.Empty); end; end; constructor TGPURun.Create; begin FChars := TList<UCS4Char>.Create; FIsDefaultColor := True; FClipBounds := nil; FClipped := False; end; procedure TGPURun.DeleteTextFromEnd(ACount: Integer); var CharsLength: Integer; begin while ACount > 0 do begin CharsLength := System.Char.ConvertFromUtf32(FChars.Last).Length; Dec(FLength, CharsLength); FChars.Delete(FChars.Count - 1); FClipBounds.Delete(FClipBounds.Count - 1); Dec(ACount); end; end; procedure TGPURun.DeleteTextFromStart(ACount: Integer); var CharsLength: Integer; begin while ACount > 0 do begin CharsLength := System.Char.ConvertFromUtf32(FChars[0]).Length; Inc(FStartIndex, CharsLength); Dec(FLength, CharsLength); FChars.Delete(0); FClipBounds.Delete(0); Dec(ACount); end; end; destructor TGPURun.Destroy; begin FreeAndNil(FChars); FreeAndNil(FClipBounds); inherited; end; procedure TGPURun.SetColor(AColor: TAlphaColor; IsDefault: Boolean); begin if IsDefault then if IsDefaultColor then //Just changing value of default color FColor := AColor else else begin //Overriding default color with attribute color FColor := AColor; FIsDefaultColor := False; end; end; procedure TGPURun.SetText(const AText: string; const AStartIndex, ALength: Integer); var I, CharLength: Integer; begin FStartIndex := AStartIndex; FLength := ALength; FChars.Clear; I := 0; while I < FLength do begin FChars.Add(System.Char.ConvertToUtf32(AText, I + FStartIndex, CharLength)); Inc(I, CharLength); end; end; { TNGLine } constructor TGPULine.Create; begin FHeight := 0; FWidth := 0; inherited Create; end; destructor TGPULine.Destroy; var I: Integer; begin for I := 0 to Count - 1 do Items[I].DisposeOf; inherited; end; { TNGFrame } constructor TGPUFrame.Create; begin FHeight := 0; FWidth := 0; FTopLeft := TPointF.Zero; inherited Create; end; destructor TGPUFrame.Destroy; var I: Integer; begin for I := 0 to Count - 1 do Items[I].DisposeOf; inherited; end; { TTextLayoutNG } constructor TTextLayoutNG.Create(const ACanvas: TCanvas); var ScreenSrv: IFMXScreenService; begin inherited Create(ACanvas); if FFamilyDic = nil then begin FFamilyDic := TFamilyDic.Create; FCharMaps := TCharMaps.Create; FCharMaps.OnNotify := CharMapNotify; end; if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, ScreenSrv) then FScale := ScreenSrv.GetScreenScale else FScale := 1; FScaleFactor := 1 / FScale; FEllipsisChar := Word(SChrHorizontalEllipsis); FFrame := TGPUFrame.Create; FStrokeBrush := TStrokeBrush.Create(TBrushKind.Solid, TAlphaColorRec.Black); end; destructor TTextLayoutNG.Destroy; begin FreeAndNil(FFrame); FreeAndNil(FFrame3D); FStrokeBrush.Free; inherited; end; class procedure TTextLayoutNG.Uninitialize; begin FreeAndNil(FNewGlyphList); FreeAndNil(FCharMaps); FreeAndNil(FFamilyDic); TFontGlyphManager.UnInitialize; end; procedure TTextLayoutNG.CharMapNotify(Sender: TObject; const Item: TCharMap; Action: System.Generics.Collections.TCollectionNotification); begin {$IFNDEF AUTOREFCOUNT} if Action in [cnRemoved, cnExtracted] then begin Item.Texture.Free; Item.BinPack.Free; end; {$ENDIF} end; procedure TTextLayoutNG.ConvertToPath(const APath: TPathData); var CharDic: TCharDic; Rec: PCharRec; LLine: TGPULine; LRun: TGPURun; I, J, K: Integer; LinePath: TPathData; TextR: TRectF; LineAdvance, VerticalAdvance, LineVerticalAdvance: Single; BaselineMaxValue, BaselineOffset: Single; CharPath: TPathData; begin if Text.IsEmpty then Exit; if FFrame3D = nil then begin FFrame3D := CreateFrame; ApplyAttributes(FFrame3D); end; BaselineOffset := 0; BaselineMaxValue := GetCharDictionary(Font).Baseline; VerticalAdvance := 0; for I := 0 to FFrame3D.Count - 1 do try LinePath := TPathData.Create; LLine := FFrame3D[I]; LineAdvance := 0; LineVerticalAdvance := 0; if AttributesCount > 0 then begin for J := 0 to LLine.Count - 1 do begin CharDic := GetCharDictionary(LLine[J].Font); BaselineMaxValue := Max(BaselineMaxValue, CharDic.Baseline); end; end; CharPath := TPathData.Create; try for J := 0 to LLine.Count - 1 do begin LRun := LLine[J]; CharDic := GetCharDictionary(LRun.Font); if AttributesCount > 0 then BaselineOffset := (BaselineMaxValue - CharDic.Baseline) * FScaleFactor; for K := 0 to LRun.Chars.Count - 1 do begin Rec := AddOrGetChar(nil, LRun.Chars[K], CharDic, LRun.Font, True); if (Rec.Glyph <> nil) and (Rec.Glyph.Path <> nil) then begin if not SameValue(BaselineOffset, 0, TEpsilon.FontSize) then begin CharPath.Assign(Rec.Glyph.Path); CharPath.Translate(0, BaselineOffset); LinePath.AddPath(CharPath); end else LinePath.AddPath(Rec.Glyph.Path); end; LinePath.Translate(-Rec.Glyph.Advance, 0); LineAdvance := LineAdvance + Rec.Glyph.Advance; LineVerticalAdvance := Max(LineVerticalAdvance, Rec.Glyph.VerticalAdvance); end; end; finally CharPath.Free; end; LinePath.Translate(LineAdvance, 0); //Aligning line TextR := LinePath.GetBounds; case HorizontalAlign of TTextAlign.Center: begin OffsetRect(TextR, -TextR.Left, 0); OffsetRect(TextR, (MaxSize.X - Padding.Left - Padding.Right - TextR.Width) / 2, 0); OffsetRect(TextR, TopLeft.X, 0); end; TTextAlign.Leading: begin OffsetRect(TextR, -TextR.Left, 0); OffsetRect(TextR, TopLeft.X, 0); end; TTextAlign.Trailing: begin OffsetRect(TextR, -TextR.Left, 0); OffsetRect(TextR, (MaxSize.X - Padding.Left - Padding.Right - TextR.Width), 0); OffsetRect(TextR, TopLeft.X, 0); end; end; //Only horizontal alignment LinePath.Translate(TextR.Left, VerticalAdvance); VerticalAdvance := VerticalAdvance + LineVerticalAdvance; // APath.AddPath(LinePath); finally FreeAndNil(LinePath); end; // TextR := APath.GetBounds; APath.Translate(0, -TextR.Top); case VerticalAlign of TTextAlign.Center: APath.Translate(0, (MaxSize.Y - Padding.Top - Padding.Bottom - TextR.Height) / 2); TTextAlign.Leading:; TTextAlign.Trailing: APath.Translate(0, (MaxSize.Y - Padding.Top - Padding.Bottom - TextR.Height)); end; APath.Translate(0, TopLeft.Y); end; procedure TTextLayoutNG.UpdateCharRec(const ACanvas: TCanvas; NeedBitmap: Boolean; var NewRec: PCharRec; HasItem: Boolean; const CharDic: TCharDic; const AFont: TFont; const Ch: UCS4Char; const NeedPath: Boolean = False); var Map: TBitmapData; J: Integer; Bitmap: TBitmap; LFont: TFont; GlyphSettings: TFontGlyphSettings; begin if not HasItem then New(NewRec) else begin FreeAndNil(NewRec.Glyph); if not NewRec.BitmapRef then FreeAndNil(NewRec.Bitmap); end; if AFont = nil then LFont := Self.Font else LFont := AFont; GlyphSettings := []; if NeedBitmap then GlyphSettings := [TFontGlyphSetting.Bitmap, TFontGlyphSetting.PremultipliedAlpha]; if NeedPath then GlyphSettings := GlyphSettings + [TFontGlyphSetting.Path]; NewRec.Glyph := TFontGlyphManager.Current.GetGlyph(Ch, LFont, FScale, GlyphSettings); CharDic.Baseline := TFontGlyphManager.Current.GetBaseline(LFont, FScale); if not (TFontGlyphStyle.NoGlyph in NewRec.Glyph.Style) and (NewRec.Glyph.Bitmap <> nil) and (NewRec.Glyph.Bitmap.Width > 0) and (NewRec.Glyph.Bitmap.Height > 0) then begin if FRendering > 0 then begin Bitmap := TBitmap.Create(NewRec.Glyph.Bitmap.Width + AntialiasMargin * 2, NewRec.Glyph.Bitmap.Height + AntialiasMargin * 2); Bitmap.BitmapScale := FScale; if Bitmap.Map(TMapAccess.Write, Map) then try FillChar(Map.Data^, Map.Pitch * Map.Height, 0); NewRec.Bitmap := Bitmap; NewRec.BitmapRef := False; NewRec.SrcRect := TRectF.Create(0, 0, NewRec.Glyph.Bitmap.Width, NewRec.Glyph.Bitmap.Height); NewRec.SrcRect.Offset(AntialiasMargin, AntialiasMargin); for J := 0 to NewRec.Glyph.Bitmap.Height - 1 do Move(NewRec.Glyph.Bitmap.Scanline[J]^, Map.GetPixelAddr(AntialiasMargin, J + AntialiasMargin)^, NewRec.Glyph.Bitmap.Pitch); finally Bitmap.Unmap(Map); end; if FNewGlyphList = nil then FNewGlyphList := TList<PCharRec>.Create; FNewGlyphList.Add(NewRec); end else MapGlyphToCache(NewRec); end else begin NewRec.Bitmap := nil; NewRec.SrcRect := TRectF.Empty; end; if not HasItem then CharDic.Add(Ch, NewRec); end; class procedure TTextLayoutNG.BeginRender; begin Inc(FRendering); end; class procedure TTextLayoutNG.EndRender; var I: Integer; Rec: PCharRec; begin Dec(FRendering); if (FNewGlyphList <> nil) and (FNewGlyphList.Count > 0) and (FRendering = 0) and not FDisableGlyphPopulation then begin for I := 0 to FNewGlyphList.Count - 1 do begin Rec := FNewGlyphList[I]; if (Rec.Glyph.Bitmap.Width > 0) and (Rec.Glyph.Bitmap.Height > 0) then MapGlyphToCache(Rec); end; FNewGlyphList.Clear; end; end; function TTextLayoutNG.AddOrGetChar(const ACanvas: TCanvas; const Ch: UCS4Char; const CharDic: TCharDic; const AFont: TFont; const NeedPath: Boolean = False): PCharRec; var NeedBitmap, HasItem: Boolean; begin NeedBitmap := ACanvas <> nil; // if not exists - place in bitmap and add to dictionaty HasItem := CharDic.TryGetValue(Ch, Result); if not HasItem or (NeedBitmap and (Result.Bitmap = nil) and not (TFontGlyphStyle.NoGlyph in Result.Glyph.Style)) or (NeedPath and not (TFontGlyphStyle.HasPath in Result.Glyph.Style)) then UpdateCharRec(ACanvas, NeedBitmap, Result, HasItem, CharDic, AFont, Ch, NeedPath); end; procedure TTextLayoutNG.DoDrawLayout(const ACanvas: TCanvas); var CharDic: TCharDic; Rec: PCharRec; Pos: TPointF; R, SrcR, ClipBounds: TRectF; LLine: TGPULine; LRun: TGPURun; I, J, K: Integer; VerticalAligned, HorizontalAligned, ColoredGlyph: Boolean; Styles: TFontStyles; Thickness: Single; BaselineMaxValue, BaselineOffset: Single; begin if Text.IsEmpty then Exit; if FOldColor <> Color then begin FOldColor := Color; for I := 0 to FFrame.Count - 1 do begin LLine := FFrame[I]; for J := 0 to LLine.Count - 1 do begin LRun := LLine[J]; LRun.SetColor(Color, True); end; end; end; if not SameValue(FScale, ACanvas.Scale, Epsilon) then begin FScale := ACanvas.Scale; FScaleFactor := 1 / FScale; DoRenderLayout; end; HorizontalAligned := SameValue(Frac(TopLeft.X), 0.0, TEpsilon.Position) and SameValue(Frac(ACanvas.Matrix.m31), 0.0, TEpsilon.Position); VerticalAligned := SameValue(Frac(TopLeft.Y), 0.0, TEpsilon.Position) and SameValue(Frac(ACanvas.Matrix.m32), 0.0, TEpsilon.Position); BaselineOffset := 0; BaselineMaxValue := GetCharDictionary(Font).Baseline; for I := 0 to FFrame.Count - 1 do begin LLine := FFrame[I]; Pos := LLine.TopLeft + TopLeft; if AttributesCount > 0 then begin for J := 0 to LLine.Count - 1 do begin CharDic := GetCharDictionary(LLine[J].Font); BaselineMaxValue := Max(BaselineMaxValue, CharDic.Baseline); end; end; for J := 0 to LLine.Count - 1 do begin LRun := LLine[J]; if LRun.Font <> nil then Styles := LRun.Font.Style else Styles := Self.Font.Style; CharDic := GetCharDictionary(LRun.Font); if AttributesCount > 0 then BaselineOffset := (BaselineMaxValue - CharDic.Baseline) * FScaleFactor; TCustomCanvasGpu(ACanvas).ModulateColor := LRun.Color; for K := 0 to LRun.Chars.Count - 1 do begin Rec := AddOrGetChar(ACanvas, LRun.Chars[K], CharDic, LRun.Font); if Rec.Bitmap <> nil then begin if HorizontalAligned then R.Left := ACanvas.AlignToPixelHorizontally(Pos.X) + Rec.Glyph.Origin.X * FScaleFactor else R.Left := Pos.X + Rec.Glyph.Origin.X * FScaleFactor; if VerticalAligned then R.Top := ACanvas.AlignToPixelVertically(Pos.Y + BaselineOffset) + Rec.Glyph.Origin.Y * FScaleFactor else R.Top := Pos.Y + BaselineOffset + Rec.Glyph.Origin.Y * FScaleFactor; R.Right := R.Left + (Rec.SrcRect.Width * FScaleFactor); R.Bottom := R.Top + (Rec.SrcRect.Height * FScaleFactor); SrcR := Rec.SrcRect; if LRun.IsClipped then begin ClipBounds := LRun.ClipBounds[K]; SrcR.Top := SrcR.Top + ClipBounds.Top * FScale; R.Top := R.Top + ClipBounds.Top; SrcR.Bottom := SrcR.Bottom - ClipBounds.Bottom * FScale; R.Bottom := R.Bottom - ClipBounds.Bottom; SrcR.Left := SrcR.Left + ClipBounds.Left * FScale; R.Left := R.Left + ClipBounds.Left; SrcR.Right := SrcR.Right - ClipBounds.Right * FScale; R.Right := R.Right - ClipBounds.Right; end; // Draw ColoredGlyph := TFontGlyphStyle.ColorGlyph in Rec.Glyph.Style; if ColoredGlyph then TCustomCanvasGpu(ACanvas).ModulateColor := $FFFFFFFF; ACanvas.DrawBitmap(Rec.Bitmap, SrcR, R, Opacity); if ColoredGlyph then TCustomCanvasGpu(ACanvas).ModulateColor := LRun.Color; end; // Offset current position Pos.X := Pos.X + (Rec.Glyph.Advance * FScaleFactor); end; if LRun.IsTrimmed then begin Rec := AddOrGetChar(ACanvas, FEllipsisChar, GetCharDictionary(Self.Font), Self.Font); TCustomCanvasGpu(ACanvas).ModulateColor := Self.Color; if Rec.Bitmap <> nil then begin if HorizontalAligned then R.Left := ACanvas.AlignToPixelHorizontally(Pos.X) + Rec.Glyph.Origin.X * FScaleFactor else R.Left := Pos.X + Rec.Glyph.Origin.X * FScaleFactor; if VerticalAligned then R.Top := ACanvas.AlignToPixelVertically(Pos.Y + BaselineOffset) + Rec.Glyph.Origin.Y * FScaleFactor else R.Top := Pos.Y + BaselineOffset + Rec.Glyph.Origin.Y * FScaleFactor; R.Right := R.Left + (Rec.SrcRect.Width * FScaleFactor); R.Bottom := R.Top + (Rec.SrcRect.Height * FScaleFactor); // Draw ACanvas.DrawBitmap(Rec.Bitmap, Rec.SrcRect, R, Opacity); end; end; if ([TFontStyle.fsStrikeOut, TFontStyle.fsUnderline] * Styles) <> [] then begin FStrokeBrush.Color := LRun.Color; if LRun.Font <> nil then Thickness := LRun.Font.Size / 15 else Thickness := Self.Font.Size / 15; FStrokeBrush.Thickness := Thickness; if TFontStyle.fsStrikeOut in Styles then ACanvas.DrawLine(TPointF.Create(Pos.X - LRun.ImageRect.Width, Pos.Y + BaselineOffset + LRun.ImageRect.Height / 2), TPointF.Create(Pos.X, Pos.Y + BaselineOffset + LRun.ImageRect.Height / 2), Opacity, FStrokeBrush); if TFontStyle.fsUnderline in Styles then ACanvas.DrawLine(TPointF.Create(Pos.X - LRun.ImageRect.Width, Pos.Y + BaselineOffset + CharDic.Baseline * FScaleFactor + 1.5 * Thickness), TPointF.Create(Pos.X, Pos.Y + BaselineOffset + CharDic.Baseline * FScaleFactor + 1.5 * Thickness), Opacity, FStrokeBrush); end; end; end; TCustomCanvasGpu(ACanvas).ModulateColor := $FFFFFFFF; end; procedure TTextLayoutNG.DoRenderLayout; procedure AlignFrame; var LTop, LLeft: Single; I: Integer; begin LLeft := Padding.Left; case HorizontalAlign of TTextAlign.Center: begin LLeft := (MaxSize.X - Padding.Right - Padding.Left - FFrame.Width) / 2; for I := 0 to FFrame.Count - 1 do FFrame[I].TopLeft := TPointF.Create((MaxSize.X - Padding.Right - Padding.Left - FFrame[I].Width) / 2, 0); end; TTextAlign.Trailing: begin LLeft := MaxSize.X - Padding.Right - FFrame.Width; for I := 0 to FFrame.Count - 1 do FFrame[I].TopLeft := TPointF.Create(MaxSize.X - Padding.Right - FFrame[I].Width, 0); end; end; LTop := Padding.Top; case VerticalAlign of TTextAlign.Center: LTop := (MaxSize.Y - Padding.Top - Padding.Bottom - FFrame.Height) / 2; TTextAlign.Trailing: LTop := MaxSize.Y - Padding.Bottom - FFrame.Height; end; FFrame.TopLeft := TPointF.Create(LLeft, LTop); for I := 0 to FFrame.Count - 1 do begin FFrame[I].TopLeft := TPointF.Create(FFrame[I].TopLeft.X, LTop); LTop := LTop + FFrame[I].Height; end; end; procedure CheckClipping; var I, J, K: Integer; X: Single; Run: TGPURun; Rec: PCharRec; ChDic: TCharDic; R: TRectF; begin if (FFrame.Width < MaxSize.X) and (FFrame.Height < MaxSize.Y) then Exit; //Checking for lines upper than top border if VerticalAlign <> TTextAlign.Leading then while FFrame.Count > 0 do if FFrame[0].TopLeft.Y < 0 then if (FFrame[0].TopLeft.Y + FFrame[0].Height) < 0 then //Remove Invisible line begin FFrame.TopLeft.Offset(0, FFrame[0].Height); FFrame.Height := FFrame.Height - FFrame[0].Height; FFrame.Delete(0); end else begin //Adding clip rects for J := 0 to FFrame[0].Count - 1 do begin Run := FFrame[0][J]; if (Run.ImageRect.Height + FFrame[0].TopLeft.Y) > 0 then begin Run.Clip; ChDic := GetCharDictionary(Run.Font); for K := 0 to Run.Chars.Count - 1 do begin Rec := AddOrGetChar(nil, Run.Chars[K], ChDic, Run.Font); X := Rec.Glyph.Origin.Y * FScaleFactor + FFrame[0].TopLeft.Y; if X < 0 then begin R := Run.ClipBounds[K]; R.Top := Abs(X); Run.ClipBounds[K] := R; end; end; end; end; Break; end else Break; //Checking for lines lower than bottom border if VerticalAlign <> TTextAlign.Trailing then while FFrame.Count > 0 do {---> if (FFrame[FFrame.Count - 1].TopLeft.Y + FFrame[FFrame.Count - 1].Height) > MaxSize.Y then if FFrame[FFrame.Count - 1].TopLeft.Y > MaxSize.Y then <---} {+++>} if (((FFrame[FFrame.Count - 1].TopLeft.Y + FFrame[FFrame.Count - 1].Height) > MaxSize.Y) and (VerticalAlign <> TTextAlign.Center)) or // 2017/01/11 修正显示省略字符 by Aone (FFrame[FFrame.Count - 1].TopLeft.Y > MaxSize.Y) then {<+++} begin FFrame.Height := FFrame.Height - FFrame[FFrame.Count - 1].Height; FFrame.Delete(FFrame.Count - 1); end else begin for J := 0 to FFrame.Last.Count - 1 do begin Run := FFrame.Last[J]; if (Run.ImageRect.Height + FFrame.Last.TopLeft.Y) > MaxSize.Y then begin Run.Clip; ChDic := GetCharDictionary(Run.Font); for K := 0 to Run.Chars.Count - 1 do begin Rec := AddOrGetChar(nil, Run.Chars[K], ChDic, Run.Font); X := MaxSize.Y - FFrame.Last.TopLeft.Y - Rec.Glyph.VerticalAdvance * FScaleFactor; if X < 0 then begin R := Run.ClipBounds[K]; R.Bottom := Abs(X); Run.ClipBounds[K] := R; end; end; end; end; Break; end ;{+++>---> // 2017/01/11 修正显示省略字符 by Aone else Break; <---} // for I := 0 to FFrame.Count - 1 do if FFrame[I].Width > MaxSize.X then begin //Checking for characters that are lefter than left border if HorizontalAlign <> TTextAlign.Leading then begin X := FFrame[I].TopLeft.X; if X < 0 then while FFrame[I].Count > 0 do if X < 0 then begin Run := FFrame[I][0]; if Run.Length > 0 then begin ChDic := GetCharDictionary(Run.Font); while X < 0 do begin Run.Clip; Rec := AddOrGetChar(nil, Run.Chars[0], ChDic, Run.Font); if (X + Rec.Glyph.Advance * FScaleFactor) < 0 then begin Run.DeleteTextFromStart(1); FFrame[I].TopLeft.Offset(Rec.Glyph.Advance * FScaleFactor, 0); FFrame[I].Width := FFrame[I].Width - Rec.Glyph.Advance * FScaleFactor; end else begin R := Run.ClipBounds[0]; R.Left := Abs(X); Run.ClipBounds[0] := R; end; X := X + Rec.Glyph.Advance * FScaleFactor; end; end; if Run.Length = 0 then FFrame[I].Delete(0); end else Break; end; //Checking for characters that are righter than right border if HorizontalAlign <> TTextAlign.Trailing then begin X := FFrame[I].TopLeft.X; J := 0; while (X < MaxSize.X) and (J < FFrame[I].Count) do begin Run := FFrame[I][J]; ChDic := GetCharDictionary(Run.Font); for K := 0 to Run.Chars.Count - 1 do begin Rec := AddOrGetChar(nil, Run.Chars[K], ChDic, Run.Font); X := X + Rec.Glyph.Advance * FScaleFactor; if X > MaxSize.X then begin Run.Clip; FFrame[I].Width := X - FFrame[I].TopLeft.X; if K < (Run.Chars.Count - 1) then Run.DeleteTextFromEnd(Run.Chars.Count - K - 1); R := Run.ClipBounds[K]; R.Right := X - MaxSize.X; Run.ClipBounds[K] := R; FFrame[I].DeleteRange(J + 1, FFrame[I].Count - J - 1); if Run.Length = 0 then FFrame[I].Delete(J); Break; end; end; Inc(J); end; end; end; end; procedure ReduceFrameSize; var MaxWidth: Single; I: Integer; begin MaxWidth := 0; for I := 0 to FFrame.Count - 1 do MaxWidth := Max(MaxWidth, FFrame[I].Width); FFrame.Width := MaxWidth; end; var CharDic: TCharDic; Rec, Rec1: PCharRec; R: TRectF; LLine, NewLine: TGPULine; LRun, NewRun: TGPURun; I, LineIndex, RunIndex, CharIndex, RunLength: Integer; WidthLimit, LineWidth, LineWidthLimit: Single; {+++>}h: Single; // 2017/01/11 修正显示省略字符 by Aone CurrentPos, RemainLength, RunEndIndex, WordBeginIndex, CharLength: Integer; begin FOldColor := Self.Color; FreeAndNil(FFrame); FreeAndNil(FFrame3D); if LayoutCanvas <> nil then if not SameValue(FScale, LayoutCanvas.Scale, Epsilon) then begin FScale := LayoutCanvas.Scale; FScaleFactor := 1 / FScale; end; FFontKey := FontFamilyKey(Font, FScale); //Splitting text FFrame := CreateFrame; //Applying attributes ApplyAttributes(FFrame); //Calculation metrics WidthLimit := MaxSize.X - Padding.Left - Padding.Right; LineIndex := 0; {+++>}h := Padding.Top; // 2017/01/11 修正显示省略字符 by Aone while LineIndex < FFrame.Count do begin LLine := FFrame[LineIndex]; LLine.Width := 0; LLine.Height := 0; RunIndex := 0; while RunIndex < LLine.Count do begin LRun := LLine[RunIndex]; CharDic := GetCharDictionary(LRun.Font); if LRun.Length = 0 then begin Rec := AddOrGetChar(nil, System.Char.ConvertToUtf32('|', 0), CharDic, LRun.Font); // LLine.Width := 1; LLine.Height := Rec.Glyph.VerticalAdvance * FScaleFactor; // LRun.ImageRect := TRectF.Create(0, 0, LLine.Width, LLine.Height); end else LRun.ImageRect := TRectF.Create(0, 0, 0, 0); RemainLength := LRun.StartIndex + LRun.Length; CharIndex := LRun.StartIndex; while CharIndex < RemainLength do begin Rec := AddOrGetChar(nil, System.Char.ConvertToUtf32(Text, CharIndex, CharLength), CharDic, LRun.Font); //Checking for MaxSize exceeding if (LRun.ImageRect.Width > 0) and (WordWrap or (Trimming <> TTextTrimming.None)) and ((LLine.Width + Rec.Glyph.Advance * FScaleFactor) > WidthLimit) then begin if WordWrap then begin //Wrapping text to several lines if Text.Chars[CharIndex].GetUnicodeCategory <> TUnicodeCategory.ucSpaceSeparator then begin WordBeginIndex := CharIndex; {---> while (WordBeginIndex > LRun.StartIndex) and (Text.Chars[WordBeginIndex - 1].GetUnicodeCategory <> TUnicodeCategory.ucSpaceSeparator) do {+++> while (WordBeginIndex > LRun.StartIndex) do // 单字符折行(只适用 Android & iOS 平台) {+++>} while (WordBeginIndex > LRun.StartIndex) and not (Text.Chars[WordBeginIndex - 1].GetUnicodeCategory in [TUnicodeCategory.ucSpaceSeparator ,TUnicodeCategory.ucOtherLetter // 2016.12.22 修正中英文混排折行 by Aone // 2017.01.13 修正避开首字标点 by Aone ,TUnicodeCategory.ucConnectPunctuation // 字元為可連接兩個字元的連接子標點符號。 ,TUnicodeCategory.ucDashPunctuation // 字元為破折號或連字號。 ,TUnicodeCategory.ucOtherPunctuation // 字元為不是連接子標點符號、破折號標點符號、開始標點符號、結束標點符號、啟始引號標點符號或終結引號標點符號的標點符號。 //,TUnicodeCategory.ucOpenPunctuation // 字元為成對標點符號標記的其中一個開頭字元,例如括弧、方括弧和大括號。 ,TUnicodeCategory.ucClosePunctuation // 字元為成對標點符號標記的其中一個結束字元,例如括弧、方括弧和大括號。 //,TUnicodeCategory.ucInitialPunctuation // 字元為開頭或啟始引號。 ,TUnicodeCategory.ucFinalPunctuation // 字元為結束或終結引號。 ]) do Dec(WordBeginIndex); if Text.Chars[WordBeginIndex].IsLowSurrogate then Dec(WordBeginIndex); RunEndIndex := WordBeginIndex; {+++>} // 2017.01.13 修正避开首字标点 by Aone while (RunEndIndex > LRun.StartIndex) and (Text.Chars[RunEndIndex].GetUnicodeCategory in [TUnicodeCategory.ucConnectPunctuation // 字元為可連接兩個字元的連接子標點符號。 ,TUnicodeCategory.ucDashPunctuation // 字元為破折號或連字號。 ,TUnicodeCategory.ucOtherPunctuation // 字元為不是連接子標點符號、破折號標點符號、開始標點符號、結束標點符號、啟始引號標點符號或終結引號標點符號的標點符號。 //,TUnicodeCategory.ucOpenPunctuation // 字元為成對標點符號標記的其中一個開頭字元,例如括弧、方括弧和大括號。 ,TUnicodeCategory.ucClosePunctuation // 字元為成對標點符號標記的其中一個結束字元,例如括弧、方括弧和大括號。 //,TUnicodeCategory.ucInitialPunctuation // 字元為開頭或啟始引號。 ,TUnicodeCategory.ucFinalPunctuation // 字元為結束或終結引號。 ]) do begin Dec(WordBeginIndex); Dec(RunEndIndex); end; {<+++} while (RunEndIndex > LRun.StartIndex) and (Text.Chars[RunEndIndex - 1].GetUnicodeCategory = TUnicodeCategory.ucSpaceSeparator) do Dec(RunEndIndex); if Text.Chars[RunEndIndex].IsLowSurrogate then Dec(RunEndIndex); if WordBeginIndex = LLine[0].StartIndex then begin CurrentPos := CharIndex; if Text.Chars[CharIndex - 1].IsLowSurrogate then LRun.SetText(Self.Text, LRun.StartIndex, Max((CharIndex - 2) - LRun.StartIndex + 1, 0)) else LRun.SetText(Self.Text, LRun.StartIndex, Max((CharIndex - 1) - LRun.StartIndex + 1, 0)); end else begin LRun.SetText(Self.Text, LRun.StartIndex, Max(RunEndIndex - LRun.StartIndex, 0)); CurrentPos := WordBeginIndex; end; end else begin RunEndIndex := CharIndex; WordBeginIndex := CharIndex; while (RunEndIndex >= LRun.StartIndex) and (Text.Chars[RunEndIndex].GetUnicodeCategory = TUnicodeCategory.ucSpaceSeparator) do Dec(RunEndIndex); if Text.Chars[RunEndIndex].IsLowSurrogate then Dec(RunEndIndex); while (WordBeginIndex <= (LRun.StartIndex + LRun.Length)) and (Text.Chars[WordBeginIndex].GetUnicodeCategory = TUnicodeCategory.ucSpaceSeparator) do Inc(WordBeginIndex); LRun.SetText(Self.Text, LRun.StartIndex, RunEndIndex - LRun.StartIndex + 1); CurrentPos := WordBeginIndex; end; {+++>} h := h + LLine.Height; // 2017/01/11 修正显示省略字符 by Aone end else begin CurrentPos := CharIndex; {+++>} end; // 2017/01/11 修正显示省略字符 by Aone if (not WordWrap) or ((VerticalAlign = TTextAlign.Leading) and (h > MaxSize.Y - LLine.Height)) then begin {<+++} //Getting back to last visible if Trimming <> TTextTrimming.None then begin Rec := AddOrGetChar(nil, FEllipsisChar, GetCharDictionary(Self.Font), Self.Font); LineWidth := LLine.Width; LineWidthLimit := WidthLimit - Rec.Glyph.Advance * FScaleFactor; while (CurrentPos >= LRun.StartIndex) and (LineWidth > LineWidthLimit) do begin Rec := AddOrGetChar(nil, System.Char.ConvertToUtf32(Text, LRun.StartIndex), CharDic, LRun.Font); LineWidth := LineWidth - Rec.Glyph.Advance * FScaleFactor; Dec(CurrentPos); end; end; //Checking for trimming RunLength := LRun.Length; case Trimming of TTextTrimming.None: RunLength := CurrentPos - LRun.StartIndex; TTextTrimming.Character: if CurrentPos > 0 then {---> if Text.Chars[CurrentPos - 1].IsLetterOrDigit then {+++>} // 2017.01.13 修正避开首字标点 by Aone if Text.Chars[CurrentPos - 1].IsLetterOrDigit or Text.Chars[CurrentPos - 1].IsPunctuation or (Text.Chars[CurrentPos - 1].GetUnicodeCategory = TUnicodeCategory.ucOtherLetter) then {<+++} begin RunLength := CurrentPos - LRun.StartIndex - 1; while (RunLength > 0) and not Text.Chars[LRun.StartIndex + RunLength - 1].IsLetterOrDigit do Dec(RunLength); end else RunLength := GetLexemeEnd(Text, GetPrevLexemeBegin(Text, CurrentPos)) + 1 - LRun.StartIndex else RunLength := 0; TTextTrimming.Word: begin RunLength := GetLexemeBegin(Text, CurrentPos) + 1 - LRun.StartIndex; if (LRun.StartIndex + RunLength) = (CurrentPos + 1) then RunLength := GetLexemeEnd(Text, GetPrevLexemeBegin(Text, CurrentPos)) - LRun.StartIndex + 1; end; end; LRun.SetText(Self.Text, LRun.StartIndex, RunLength); LRun.IsTrimmed := (Trimming <> TTextTrimming.None); CurrentPos := RemainLength; if CurrentPos < (LRun.StartIndex + LRun.Length) then CurrentPos := LRun.StartIndex + LRun.Length; end; //Decreasing Run's length RunEndIndex := LRun.StartIndex + LRun.Length; if CharIndex >= RunEndIndex then begin I := CharIndex - 1; R := LRun.ImageRect; while (I >= 0) and (I >= RunEndIndex) do begin if Text.Chars[I].IsLowSurrogate then Dec(I); Rec1 := AddOrGetChar(nil, System.Char.ConvertToUtf32(Text, I), CharDic, LRun.Font); LLine.Width := LLine.Width - (Rec1.Glyph.Advance * FScaleFactor); R.Width := R.Width - Rec1.Glyph.Advance * FScaleFactor; Dec(I); end; LRun.ImageRect := R; end; if LRun.IsTrimmed then begin Rec1 := AddOrGetChar(nil, FEllipsisChar, GetCharDictionary(Self.Font), Self.Font); R := LRun.ImageRect; R.Width := R.Width + Rec1.Glyph.Advance * FScaleFactor; LRun.ImageRect := R; LLine.Width := LLine.Width + Rec1.Glyph.Advance * FScaleFactor; LLine.Height := Max(LLine.Height, Rec1.Glyph.VerticalAdvance * FScaleFactor); end; //Applying wrapping if WordWrap and (CurrentPos < RemainLength) then begin //Forming new line NewLine := TGPULine.Create; NewRun := TGPURun.Create; NewRun.Font := LRun.Font; NewRun.SetColor(LRun.Color, LRun.IsDefaultColor); NewRun.SetText(Self.Text, CurrentPos, RemainLength - CurrentPos); NewLine.Add(NewRun); for I := RunIndex + 1 to LLine.Count - 1 do NewLine.Add(LLine[I]); LLine.DeleteRange(RunIndex + 1, LLine.Count - (RunIndex + 1)); FFrame.Insert(LineIndex + 1, NewLine); RunIndex := LLine.Count; end; Break; end else begin R := LRun.ImageRect; R.Width := R.Width + Rec.Glyph.Advance * FScaleFactor; R.Height := Max(R.Height, Rec.Glyph.VerticalAdvance * FScaleFactor); LRun.ImageRect := R; LLine.Width := LLine.Width + (Rec.Glyph.Advance * FScaleFactor); LLine.Height := Max(LLine.Height, R.Height); end; Inc(CharIndex, CharLength); end; Inc(RunIndex); end; // FFrame.Width := Max(FFrame.Width, LLine.Width); FFrame.Height := FFrame.Height + LLine.Height; Inc(LineIndex); end; AlignFrame; CheckClipping; ReduceFrameSize; end; function TTextLayoutNG.GetCharDictionary(const AFont: TFont = nil): TCharDic; var FamilyKey: Int64; begin Result := nil; if AFont = nil then FamilyKey := FFontKey else FamilyKey := FontFamilyKey(AFont, FScale); if not FFamilyDic.TryGetValue(FamilyKey, Result) then begin Result := TCharDic.Create(1024); FFamilyDic.Add(FamilyKey, Result); end; end; function TTextLayoutNG.GetTextHeight: Single; begin if not SameValue(MaxSize.Y, TTextLayout.MaxLayoutSize.Y, Epsilon) then Result := Min(FFrame.Height, MaxSize.Y) else Result := FFrame.Height; end; function TTextLayoutNG.GetTextRect: TRectF; begin Result := TRectF.Create(FFrame.TopLeft, TextWidth, TextHeight); Result.Offset(TopLeft); if FFrame.TopLeft.Y < 0 then Result.Offset(0, Abs(FFrame.TopLeft.Y)); end; function TTextLayoutNG.GetTextWidth: Single; begin Result := FFrame.Width; end; function TTextLayoutNG.CreateFrame: TGPUFrame; var ST: TStringList; LLine: TGPULine; LRun: TGPURun; I, StartIndex: Integer; begin Result := TGPUFrame.Create; if Text.IsEmpty then begin LLine := TGPULine.Create; LRun := TGPURun.Create; LRun.Font := nil; LRun.SetColor(Self.Color, True); LLine.Add(LRun); Result.Add(LLine); end else begin ST := TStringList.Create; try ST.Text := Self.Text; StartIndex := 0; for I := 0 to ST.Count - 1 do begin LLine := TGPULine.Create; LRun := TGPURun.Create; LRun.Font := nil; LRun.SetColor(Self.Color, True); StartIndex := Self.Text.IndexOf(ST[I], StartIndex); LRun.SetText(Self.Text, StartIndex, ST[I].Length); LLine.Add(LRun); Result.Add(LLine); Inc(StartIndex, LRun.Length); if I < (ST.Count - 1) then Inc(StartIndex, ST.LineBreak.Length); end; finally FreeAndNil(ST); end; end; end; procedure TTextLayoutNG.ApplyAttributes(AFrame: TGPUFrame); procedure ApplyAttribute(Run: TGPURun; Attribute: TTextAttribute); begin Run.SetColor(Attribute.Color, False); if Run.Font = nil then Run.Font := Attribute.Font else if Attribute.Font <> nil then begin Run.Font.Family := Attribute.Font.Family; Run.Font.Size := Attribute.Font.Size; Run.Font.Style := Run.Font.Style + Attribute.Font.Style; end; end; var I, CurrentPos, RemainLength, LineIndex, RunIndex: Integer; LAttribute: TTextAttributedRange; LLine: TGPULine; LRun, NewRun: TGPURun; begin for I := 0 to AttributesCount - 1 do begin LAttribute := Attributes[I]; CurrentPos := LAttribute.Range.Pos; RemainLength := LAttribute.Range.Length; while RemainLength > 0 do begin //Looking for Run for LineIndex := 0 to AFrame.Count - 1 do begin RunIndex := 0; LLine := AFrame[LineIndex]; while RunIndex < LLine.Count do begin LRun := LLine[RunIndex]; if CurrentPos < (LRun.StartIndex + LRun.Length) then begin if CurrentPos > LRun.StartIndex then begin //Attibute start's not from the begin of the run, need to //split run NewRun := TGPURun.Create; NewRun.SetText(Text, LRun.StartIndex, CurrentPos - LRun.StartIndex); NewRun.Font := LRun.Font; NewRun.SetColor(LRun.Color, LRun.IsDefaultColor); LLine.Insert(RunIndex, NewRun); Inc(RunIndex); LRun.SetText(Text, CurrentPos, LRun.Length - NewRun.Length); end; //Current position and start of the Run are equal NewRun := nil; if RemainLength < LRun.Length then begin //Attribute length is less than current Run, need to create //a new Run after current NewRun := TGPURun.Create; NewRun.SetText(Self.Text, LRun.StartIndex + RemainLength, LRun.Length - RemainLength); NewRun.Font := LRun.Font; NewRun.SetColor(LRun.Color, LRun.IsDefaultColor); LRun.SetText(Text, LRun.StartIndex, LRun.Length - NewRun.Length); end; //Applying attribute ApplyAttribute(LRun, LAttribute.Attribute); Dec(RemainLength, LRun.Length); Inc(CurrentPos, LRun.Length); if NewRun <> nil then begin //Inserting new run after applying attribute LLine.Insert(RunIndex + 1, NewRun); Inc(RunIndex); Inc(CurrentPos, NewRun.Length); end; end; if RemainLength <= 0 then Break; Inc(RunIndex); end; if RemainLength <= 0 then Break; end; end; end; end; class procedure TTextLayoutNG.MapGlyphToCache(CharRec: PCharRec); var GlyphSize: TPoint; Map: TBitmapData; I, LIndex: Integer; LRect: TRect; CharMap: TCharMap; begin // CharRec.Bitmap already has AntialiasMargin applied to it. if CharRec.Bitmap <> nil then GlyphSize := TPoint.Create(CharRec.Bitmap.Width, CharRec.Bitmap.Height) else GlyphSize := TPoint.Create(CharRec.Glyph.Bitmap.Width + AntialiasMargin * 2, CharRec.Glyph.Bitmap.Height + AntialiasMargin * 2); LRect := TRect.Empty; LIndex := -1; for I := 0 to FCharMaps.Count - 1 do if FCharMaps[I].BinPack.Occupancy < MaxUsefulCharMapOccupancy then begin LRect := FCharMaps[I].BinPack.Insert(GlyphSize, False); if not LRect.IsEmpty then begin LIndex := I; Break; end; end; if LIndex = -1 then begin CharMap.Texture := TBitmap.Create(BitmapSize, BitmapSize); if CharRec.Bitmap <> nil then CharMap.Texture.BitmapScale := CharRec.Bitmap.BitmapScale; CharMap.BinPack := TGuillotineBinPack.Create(TPoint.Create(BitmapSize, BitmapSize)); FCharMaps.Add(CharMap); LRect := CharMap.BinPack.Insert(GlyphSize, False); if LRect.IsEmpty then Exit; end else CharMap := FCharMaps[LIndex]; if not CharRec.BitmapRef then FreeAndNil(CharRec.Bitmap); if CharMap.Texture.Map(TMapAccess.Write, Map) then try CharRec.Bitmap := CharMap.Texture; CharRec.BitmapRef := True; CharRec.SrcRect := TRectF.Create(LRect.Left + AntialiasMargin, LRect.Top + AntialiasMargin, LRect.Right - AntialiasMargin, LRect.Bottom - AntialiasMargin); for I := 0 to CharRec.Glyph.Bitmap.Height - 1 do Move(CharRec.Glyph.Bitmap.Scanline[I]^, Map.GetPixelAddr(LRect.Left + AntialiasMargin, LRect.Top + AntialiasMargin + I)^, CharRec.Glyph.Bitmap.Pitch); finally CharMap.Texture.Unmap(Map); end; end; function TTextLayoutNG.MeasureRange(APos, ALength: Integer): TRegion; var I, LengthOffset, LLength, CharsLength: Integer; CharDic: TCharDic; Rec: PCharRec; R, R1: TRectF; Offset: Single; LRun: TGPURun; LineIndex, RunIndex: Integer; begin SetLength(Result, 0); LLength := Text.Length; while ((APos + ALength) < LLength) and IsCombiningCharacter(Text.Chars[APos + ALength]) do //Skipping combining characters Inc(ALength); if (APos < LLength) and Text.Chars[APos].IsLowSurrogate then begin Dec(APos); Inc(ALength); end; for LineIndex := 0 to FFrame.Count - 1 do begin Offset := 0; if (LineIndex > 0) and (Length(Result) > 0) and (FFrame[LineIndex - 1].Count > 0) and (FFrame[LineIndex].Count > 0) then Dec(ALength, FFrame[LineIndex].First.StartIndex - FFrame[LineIndex - 1].Last.StartIndex - FFrame[LineIndex - 1].Last.Length); for RunIndex := 0 to FFrame[LineIndex].Count - 1 do begin LRun := FFrame[LineIndex][RunIndex]; LengthOffset := LRun.StartIndex; R := TRectF.Create(0, 0, 0, 0); if APos < (LRun.StartIndex + LRun.Length) then begin CharDic := GetCharDictionary(LRun.Font); for I := 0 to LRun.Chars.Count - 1 do begin CharsLength := System.Char.ConvertFromUtf32(LRun.Chars[I]).Length; Rec := AddOrGetChar(nil, LRun.Chars[I], CharDic, LRun.Font); if LengthOffset < APos then begin Offset := Offset + Rec.Glyph.Advance * FScaleFactor; Inc(LengthOffset, CharsLength); end else if ALength > 0 then begin R1 := TRectF.Create(Offset, 0, Offset + Rec.Glyph.Advance * FScaleFactor, FFrame[LineIndex].Height); if R.IsEmpty then R := R1 else R.Union(R1); Offset := Offset + Rec.Glyph.Advance * FScaleFactor; Dec(ALength, CharsLength); Inc(LengthOffset, CharsLength); end else Break; end; end else if APos = LLength then begin R := LRun.ImageRect; R.Left := R.Right; Dec(ALength); end else if ALength > 0 then Offset := Offset + LRun.ImageRect.Width else Break; if R.Right > 0 then begin SetLength(Result, Length(Result) + 1); R.Offset(FFrame[LineIndex].TopLeft); Result[High(Result)] := R; R := R.Empty; end; end; if R.Right > 0 then begin SetLength(Result, Length(Result) + 1); R.Offset(FFrame[LineIndex].TopLeft); Result[High(Result)] := R; R := R.Empty; end; if ALength = 0 then Exit; end; end; function TTextLayoutNG.DoPositionAtPoint(const APoint: TPointF): Integer; function RegionContains(const ARect: TRectF; const LPoint: TPointF): Boolean; begin Result := ((LPoint.X > ARect.Left) or SameValue(LPoint.X, ARect.Left, Epsilon)) and ((LPoint.X < ARect.Right)or SameValue(LPoint.X, ARect.Right, Epsilon)) and ((LPoint.Y > ARect.Top) or SameValue(LPoint.Y, ARect.Top, Epsilon)) and ((LPoint.Y < ARect.Bottom) or SameValue(LPoint.Y, ARect.Bottom, Epsilon)); end; var I, Index, Length, CharsLength: Integer; CharDic: TCharDic; Rec: PCharRec; LPoint: TPointF; R: TRectF; Offset: Single; LRun: TGPURun; LineIndex, RunIndex: Integer; begin Result := -1; LPoint := TPointF.Create(APoint.X - TopLeft.X - Padding.Left, APoint.Y - TopLeft.Y - Padding.Top); LPoint.Offset(0, -FFrame.TopLeft.Y); for LineIndex := 0 to FFrame.Count - 1 do begin Offset := FFrame[LineIndex].TopLeft.X; if LPoint.Y > FFrame[LineIndex].Height then begin LPoint.Offset(0, -FFrame[LineIndex].Height); Continue; end; if LPoint.X < FFrame[LineIndex].TopLeft.X then Exit(FFrame[LineIndex].First.StartIndex); if LPoint.X > (FFrame[LineIndex].TopLeft.X + FFrame[LineIndex].Width) then Exit(FFrame[LineIndex].Last.StartIndex + FFrame[LineIndex].Last.Length); for RunIndex := 0 to FFrame[LineIndex].Count - 1 do begin LRun := FFrame[LineIndex][RunIndex]; if LRun.Chars.Count = 0 then Exit(LRun.StartIndex); CharDic := GetCharDictionary(LRun.Font); CharsLength := 0; for I := 0 to LRun.Chars.Count - 1 do begin Rec := AddOrGetChar(nil, LRun.Chars[I], CharDic, LRun.Font); R := TRectF.Create(Offset, 0, Offset + Rec.Glyph.Advance * FScaleFactor, FFrame[LineIndex].Height); if RegionContains(R, LPoint) then begin Index := CharsLength + LRun.StartIndex; if LPoint.X > (R.Left + R.Width * 3 / 5) then Inc(Index); Length := Text.Length; if Text.Chars[Index].IsLowSurrogate then //Moving to the end of the surrogate pair Inc(Index); while ((Index + 1) < Length) and IsCombiningCharacter(Text.Chars[Index + 1]) do //Skipping combining characters Inc(Index); Exit(Min(Index, Text.Length)); end; Offset := Offset + Rec.Glyph.Advance * FScaleFactor; Inc(CharsLength, System.Char.ConvertFromUtf32(LRun.Chars[I]).Length); end; end; end; end; function TTextLayoutNG.DoRegionForRange(const ARange: TTextRange): TRegion; var i: Integer; begin SetLength(Result, 0); if (ARange.Pos < 0) or (ARange.Length < 0) then Exit; if (ARange.Pos = Text.Length) and (ARange.Length = 0) then if Text.IsEmpty then begin SetLength(Result, 1); Result[0] := Self.TextRect; Exit; end else begin Result := MeasureRange(Text.Length - 1, 1); for i := Low(Result) to High(Result) do Result[i].Left := Result[i].Right; end else begin Result := MeasureRange(ARange.Pos, ARange.Length); if Length(Result) = 0 then begin SetLength(Result, 1); Result[0] := Self.TextRect; Result[0].Right := Result[0].Left; Exit; end; end; for i := Low(Result) to High(Result) do Result[i].Offset(TopLeft); end; initialization finalization TTextLayoutNG.Uninitialize; end.
unit TestRaise; { This unit compiles but is not semantically meaningfull it is test cases for the code formatting utility to test the 'raise' keyword } interface implementation uses SysUtils; { inspired by code in inifiles } function Test1: TDateTime; var DateStr: string; begin DateStr := 'Fooo'; Result := 0.0; try Result := StrToDate(DateStr); except on EConvertError do // Ignore EConvertError exceptions else raise; end; end; function Test1_2: TDateTime; var DateStr: string; begin DateStr := 'Fooo'; Result := 0.0; try Result := StrToDate(DateStr); except // Ignore EConvertError exceptions on EConvertError do ; // and math errors on EMathError do else raise; end; end; function Test2: TDateTime; var DateStr: string; begin DateStr := 'Fooo'; Result := Now; try Result := StrToDate(DateStr); except on EConvertError do if DateStr = '' then raise else end; end; function Test3: TDateTime; var DateStr: string; begin DateStr := 'Fooo'; Result := Now; try Result := StrToDate(DateStr); except on EConvertError do if DateStr = '' then raise else raise end; end; function Test4: TDateTime; var DateStr: string; begin DateStr := 'Fooo'; Result := Now; try Result := StrToDate(DateStr); except on EConvertError do if DateStr = '' then raise else if DateStr = 'foo' then begin raise end else raise end; end; procedure TestIf(const pi: integer); begin if pi > 4 then else begin end; end; end.
{* * DateTimeUtils.pas * * Auxilary functions for date/time manipulation. * * Copyright (c) 2006-2007 by the MODELbuilder developers team * Originally written by Darius Blaszijk, <dhkblaszyk@zeelandnet.nl> * Creation date: 31-Oct-2006 * Website: www.modelbuilder.org * * This file is part of the MODELbuilder project and licensed * under the LGPL, see COPYING.LGPL included in this distribution, * for details about the copyright. * *} unit DateTimeUtils; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Math, Miscelaneous; function DateTimeToISO8601(DateTime: TDateTime): string; function ISO8601ToDateTime(DateTime: string): TDateTime; function TimeToISO8601(DateTime: TDateTime): string; function ISO8601ToTime(DateTime: string): TDateTime; function FmtStringToDateTime(FormatStr: string; DateTimeStr: string; var DateTime: TDateTime; BaseYear: integer = 0): boolean; implementation function DateTimeToISO8601(DateTime: TDateTime): string; begin Result := FormatDateTime('yyyy-mm-dd', DateTime) + 'T' + FormatDateTime('hh:mm:ss', DateTime) end; function ISO8601ToDateTime(DateTime: string): TDateTime; var y, m, d, h, n, s: word; begin y := StrToInt(Copy(DateTime, 1, 4)); m := StrToInt(Copy(DateTime, 6, 2)); d := StrToInt(Copy(DateTime, 9, 2)); h := StrToInt(Copy(DateTime, 12, 2)); n := StrToInt(Copy(DateTime, 15, 2)); s := StrToInt(Copy(DateTime, 18, 2)); Result := EncodeDate(y,m,d) + EncodeTime(h,n,s,0); end; function TimeToISO8601(DateTime: TDateTime): string; begin Result := FormatDateTime('hh:mm:ss', DateTime) end; function ISO8601ToTime(DateTime: string): TDateTime; var h, n, s: word; begin h := StrToInt(Copy(DateTime, 1, 2)); n := StrToInt(Copy(DateTime, 4, 2)); s := StrToInt(Copy(DateTime, 7, 2)); Result := EncodeTime(h,n,s,0); end; //convert a string given a format string to datetime { date time formatting characters: d : day of month m : month y : year h : hour n : minute s : second } function FmtStringToDateTime(FormatStr: string; DateTimeStr: string; var DateTime: TDateTime; BaseYear: integer = 0): boolean; var d, m, y, h, n, s: string; len: integer; i: integer; Date: TDateTime; Time: TDateTime; begin d := ''; m := ''; y := ''; h := ''; n := ''; s := ''; len := Min(length(FormatStr), length(DateTimeStr)); for i := 1 to len do case FormatStr[i] of 'd': d := d + DateTimeStr[i]; 'm': m := m + DateTimeStr[i]; 'y': y := y + DateTimeStr[i]; 'h': h := h + DateTimeStr[i]; 'n': n := n + DateTimeStr[i]; 's': s := s + DateTimeStr[i]; end; if d = '' then d := '0'; if m = '' then m := '0'; if y = '' then y := '0'; if h = '' then h := '0'; if n = '' then n := '0'; if s = '' then s := '0'; if IsNumeric(d) and IsNumeric(m) and IsNumeric(y) and IsNumeric(h) and IsNumeric(n) and IsNumeric(s) then begin Result := TryEncodeDate(StrToInt(y) + BaseYear, StrToInt(m), StrToInt(d), Date); if not Result then exit; Result := TryEncodeTime(StrToInt(h), StrToInt(n), StrToInt(s), 0, Time); DateTime := Date + Time; end else Result := False; end; end.
unit tabCtrlMan; interface uses Windows, SysUtils, Classes, ComCtrls, HEditor; const TAB_ID = '//<テキスト音楽「サクラ」ver.2>'; TAB_HEADER = '//<HEAD'; PAGE_FROM = '//<PAGE'; //ページの区切り PAGE_TO = '//</PAGE>'; type PTabPage = ^TTabPage; TTabPage = record TabName: string; TabText: string; Caret: TPoint; end; TTabMan = class(TList) private FActivePage: Integer; public Tabs: TTabControl; Editor: TEditor; property ActivePage: Integer read FActivePage; constructor Create(c:TTabControl; e: TEditor); destructor Destroy; override; procedure Clear; override; procedure AddTabPage(name,text: string; car: TPoint); procedure DeleteTabPage(Index: Integer); procedure ChangeName(Index: Integer; name: string); procedure ChangeActivePage(Index: Integer; OldText: string; OldCaret: TPoint); procedure LoadFromFile(fname: string); procedure SaveToFile(fname: string); procedure SetActivePageText(text: string); function GetAllText: string; procedure GotoLine(lineNo: Integer; var page, line: Integer); procedure SetAllText(text: string); end; implementation uses StrUnit; { TTabMan } procedure TTabMan.AddTabPage(name, text: string; car: TPoint); var p: PTabPage; begin New(p); p^.TabName := name; p^.TabText := text; p^.Caret := car; Add(p); Tabs.Tabs.Add(name); end; procedure TTabMan.ChangeActivePage(Index: Integer; OldText: string; OldCaret: TPoint); var p: PTabPage ; begin if Count <= Index then Exit; if FActivePage >= 0 then begin p := Items[FActivePage]; //前の状態を記憶 p^.Caret := OldCaret; p^.TabText := OldText; end; p := Items[Index]; //今度の状態を取得 Editor.Lines.Text := p^.TabText ; Editor.Col := p^.Caret.X ; Editor.Row := p^.Caret.Y ; FActivePage := Index; Tabs.TabIndex := Index; end; procedure TTabMan.ChangeName(Index: Integer; name: string); var p: PTabPage ; begin if Count <= Index then Exit; p := Items[Index]; p.TabName := name; Tabs.Tabs.Strings[Index] := name; end; procedure TTabMan.Clear; var i: Integer; p: PTabPage ; begin for i:=0 to Count-1 do begin p := Items[i]; if p=nil then Continue; Dispose(p); Items[i] := nil; end; Tabs.Tabs.Clear ; inherited Clear; FActivePage := -1; Editor.Lines.Text := ''; end; constructor TTabMan.Create(c:TTabControl; e: TEditor); begin Tabs := c; Editor := e; c.Tabs.Clear ; c.Tabs.Add('Main'); e.Lines.Text := ''; FActivePage := -1; end; procedure TTabMan.DeleteTabPage(Index: Integer); var p: PTabPage ; begin if Count <= Index then Exit; p := Items[Index]; Dispose(p); Self.Delete(Index); Tabs.Tabs.Delete(Index); if Index=FActivePage then begin if Index = Count then Index := Count-1; FActivePage := -1; ChangeActivePage(Index,'',POINT(0,0)); end; end; destructor TTabMan.Destroy; begin Clear ; inherited; end; function TTabMan.GetAllText: string; var i: Integer; p: PTabPage; begin Result := ''; Result := Result + TAB_ID + #13#10; Result := Result + TAB_HEADER+' ACTIVE='+IntToStr(FActivePage)+'/>'#13#10; for i:=0 to Count-1 do begin p := Items[i]; Result := Result + PAGE_FROM + ' NAME="' + p^.TabName + '" ' + 'COL=' + IntToStr(p^.Caret.X)+' ROW='+ IntToStr(p^.Caret.Y) + '>'#13#10; Result := Result + p^.TabText + #13#10; Result := Result + PAGE_TO + #13#10; end; end; procedure TTabMan.GotoLine(lineNo: Integer; var page, line: Integer); var sl: TStringList; i: Integer; s: string; cnt: Integer; ln: Integer; begin sl := TStringList.Create ; try sl.Text := GetAllText; cnt := 0; ln := 0; for i:=0 to sl.Count-1 do begin if i = lineNo then Break; s := sl.Strings[i]; if s=PAGE_TO then begin Inc(cnt); end else if Copy(s,1,Length(PAGE_FROM))=PAGE_FROM then begin ln := -1; end; Inc(ln); end; page := cnt; line := ln; finally sl.Free ; end; end; procedure TTabMan.LoadFromFile(fname: string); var s: TStringList; begin s := TStringList.Create ; try s.LoadFromFile(fname); SetAllText(s.Text); finally s.Free ; end; end; procedure TTabMan.SaveToFile(fname: string); var s: TStringList; begin s := TStringList.Create ; try s.Text := GetAllText ; s.SaveToFile(fname); finally s.Free ; end; end; procedure TTabMan.SetActivePageText(text: string); var p: PTabPage; begin if FActivePage>=0 then begin p := Items[FActivePage]; p^.TabText := text; end; end; procedure TTabMan.SetAllText(text: string); var ptr: PChar; InitActivePage: Integer; procedure skipSpace(var ptr: PChar); begin while ptr^ in [' ',#9,#13,#10] do Inc(ptr); end; procedure readTabPage; var ss, key,val: string; tabname, tabtext: string; acol,arow: Integer; begin skipSpace(ptr); //get active page if StrLComp(ptr, 'ACTIVE', Length('ACTIVE'))=0 then begin Inc(ptr, Length('ACTIVE')); skipSpace(ptr); if ptr^ = '=' then Inc(ptr); ss := ''; while ptr^ in ['0'..'9'] do begin ss := ss + ptr^; Inc(ptr); end; InitActivePage:=StrToIntDef(ss,0); end; skipSpace(ptr); if ptr^ = '/' then Inc(ptr); if ptr^ = '>' then Inc(ptr); //get pages while ptr^ <> #0 do begin skipSpace(ptr); if StrLComp(ptr, PChar(PAGE_FROM), Length(PAGE_FROM)) = 0 then begin Inc(ptr, Length(PAGE_FROM)); //属性を取得 tabname := 'page'; tabtext := ''; acol := 0; arow := 0; while ptr^ <> #0 do begin skipSpace(ptr); if ptr^='>' then Break; key := UpperCase(GetTokenChars([' ','=','>'],ptr)); if (ptr-1)^ = '>' then Break; val := GetTokenChars([' ','=','>'],ptr); if (ptr-1)^ = '>' then Dec(ptr); if key='NAME' then begin if Copy(val,1,1)='"' then System.delete(val,1,1); if Copy(val,Length(val),1)='"' then System.delete(val,Length(val),1); tabname := val; end else if key='COL' then begin acol := Trunc(StrToValue(val)); end else if key='ROW' then begin arow := Trunc(StrToValue(val)); end; end; skipSpace(ptr); if ptr^ = '>' then Inc(ptr); skipSpace(ptr); //本文を取得 ss := ''; while ptr^ <> #0 do begin if StrLComp(ptr, PAGE_TO, Length(PAGE_TO)) = 0 then begin Inc(ptr, Length(PAGE_TO)); Break; end; if ptr^ in LeadBytes then begin ss := ss + ptr^ + (ptr+1)^; Inc(ptr,2); end else begin ss := ss + ptr^; Inc(ptr); end; end; AddTabPage(tabname, ss, POINT(acol,arow)); end else begin Inc(ptr); end; end; end; begin Clear; InitActivePage := 0; ptr := PChar(text); skipSpace(ptr); if StrLComp(ptr, PChar(TAB_ID), Length(TAB_ID))=0 then begin Inc(ptr, Length(TAB_ID)); readTabPage; end else begin //ただのテキスト Self.AddTabPage('main', text, POINT(0,0)); end; ChangeActivePage(InitActivePage,'',POINT(0,0)); end; end.
unit MediaStream.Filer.Tsm; interface uses SysUtils,Classes, Windows, SyncObjs, MediaStream.Filer, MediaProcessing.Definitions,MediaStream.Writer.Tsm; type TStreamFilerTsm = class (TStreamFiler) private FWriter: TMediaStreamWriter_Tsm; protected procedure DoWriteData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); override; public constructor Create; override; destructor Destroy; override; procedure Close; override; class function DefaultExt: string; override; end; implementation { TStreamFilerTsm } procedure TStreamFilerTsm.Close; begin FWriter.Close; inherited; end; constructor TStreamFilerTsm.Create; begin inherited; FWriter:=TMediaStreamWriter_Tsm.Create; end; class function TStreamFilerTsm.DefaultExt: string; begin result:='.tsm'; end; destructor TStreamFilerTsm.Destroy; begin inherited; FreeAndNil(FWriter); end; procedure TStreamFilerTsm.DoWriteData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); begin if FWriter.Stream=nil then FWriter.AssignToStream(FStream); FWriter.WriteData(aFormat,aData,aDataSize); end; end.
unit UI.Toast.AndroidLike; interface uses UI.Base, UI.Utils, UI.Standard, System.SysUtils, System.Classes, System.Types, FMX.Types, FMX.Controls, FMX.StdCtrls, FMX.Objects, System.UITypes, FMX.Graphics, System.Actions, System.Rtti, System.Generics.Collections, System.Generics.Defaults, FMX.Styles, FMX.TextLayout, FMX.Effects, FMX.Layouts; type TToast = class(TComponent) private FTimer: TTimer; FStartTime: Int64; FText: TTextView; FPH, FPW: Single; FQueue: TQueue<string>; protected procedure DoToastTimer(Sender: TObject); procedure DoSetText(const Text: string); procedure InitTimer(); procedure InitText(); procedure AdjustTextPosition(); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ShowToast(const AMsg: string); property Text: TTextView read FText; property Queue: TQueue<string> read FQueue; end; implementation uses FMX.Forms; const FViewTime = 1500; FMinViewTime = 500; procedure TToast.AdjustTextPosition; begin if (FPW > 0) and (FPH > 0) then begin FText.Position.Y := FPH - FText.Size.Height - FText.Margins.Bottom; FText.Position.X := (FPW - FText.Size.Width) / 2; end; end; constructor TToast.Create(AOwner: TComponent); begin inherited Create(AOwner); if not (AOwner is TFmxObject) then raise Exception.Create('The Owner must be TFmxObject.'); FStartTime := 0; FQueue := TQueue<string>.Create; InitTimer(); end; destructor TToast.Destroy; begin FText := nil; if Assigned(FTimer) then FTimer := nil; FreeAndNil(FQueue); inherited Destroy; end; procedure TToast.DoSetText(const Text: string); begin if not Assigned(FText) then InitText; if FText.Parent is TControl then begin FPW := TControl(FText.Parent).LocalRect.Width; FPH := TControl(FText.Parent).LocalRect.Height; end else if FText.Parent is TCommonCustomForm then begin FPW := TCommonCustomForm(FText.Parent).ClientRect.Width; FPH := TCommonCustomForm(FText.Parent).ClientRect.Height; end else begin FPW := 0; FPH := 0; end; if FPW > 0 then FText.MaxWidth := FPW - FText.Margins.Width; FText.Text := Text; FText.Index := FText.Parent.ChildrenCount - 1; AdjustTextPosition; end; procedure TToast.DoToastTimer(Sender: TObject); var LTime: Int64; begin if (csDestroying in ComponentState) then Exit; LTime := GetTimestamp - FStartTime; if (LTime >= FMinViewTime) then begin if FQueue.Count > 0 then begin DoSetText(FQueue.Dequeue); FStartTime := GetTimestamp; end else if (LTime > FViewTime) then begin FStartTime := 0; FTimer.Enabled := False; if Assigned(FText) then begin FText.Parent.RemoveObject(FText); FreeAndNil(FText); end; end; end; end; procedure TToast.InitText; var P: TFmxObject; begin FText := TTextView.Create(Owner); {$IFDEF MSWINDOWS} FText.Name := 'ToastText'; {$ENDIF} P := TFmxObject(Owner); FText.BeginUpdate; FText.Padding.Rect := RectF(16, 6, 16, 6); FText.Margins.Rect := RectF(24, 0, 24, 48); FText.Parent := P; FText.HitTest := False; FText.MinHeight := 32; FText.Opacity := 1.0; FText.Gravity := TLayoutGravity.Center; FText.Background.ItemDefault.Color := $7f000000; FText.Background.ItemDefault.Kind := TViewBrushKind.Solid; FText.Background.XRadius := 15; FText.Background.YRadius := 15; FText.TextSettings.Color.Default := $fff0f0f0; FText.TextSettings.WordWrap := True; FText.WidthSize := TViewSize.WrapContent; FText.HeightSize := TViewSize.WrapContent; FText.AutoSize := True; FText.Index := P.ChildrenCount - 1; FText.EndUpdate; end; procedure TToast.InitTimer; begin FTimer := TTimer.Create(Owner); FTimer.Enabled := False; FTimer.Interval := 200; FTimer.OnTimer := DoToastTimer; end; procedure TToast.ShowToast(const AMsg: string); begin if AMsg = '' then Exit; if TThread.CurrentThread.ThreadID = MainThreadID then begin FQueue.Enqueue(AMsg); FTimer.Enabled := True; end else TThread.Queue(nil, procedure begin FQueue.Enqueue(AMsg); FTimer.Enabled := True; end); end; end.
unit untEasyDBToolUtil; interface const //获取数据库名称 EASY_DATABASE_USER = 'SELECT * FROM vw_sysDataBase_User ORDER BY Name'; EASY_DATABASE_ALL = 'SELECT * FROM vw_sysDataBase ORDER BY Name'; EASY_DATATYPES = 'SELECT * FROM vw_sysTypes'; EASY_TABLE = 'SELECT * FROM vw_sysTables_User ORDER BY Name'; EASY_TABLEFIELD = 'SELECT * FROM vw_sysTable_Fields ' +' WHERE TableName = ''%s''' + ' ORDER BY FieldNo'; { EASY_DATABASE_USER = 'Select Name, dbid, sid, crdate, filename, version FROM Master..SysDatabases ' + ' WHERE name NOT IN(''model'' ,''master'', ''msdb'', ''tempdb'') ' + ' ORDER BY Name '; EASY_DATABASE_ALL = 'Select Name, dbid, sid, crdate, filename, version FROM Master..SysDatabases ' + ' ORDER BY Name '; //数据类型 EASY_DATATYPES = 'select name from systypes'; //当前用户数据表 EASY_TABLE = 'Select Name FROM SysObjects Where XType=''U'' ORDER BY Name'; //指定表的字段信息 EASY_TABLEFIELD = 'SELECT (CASE WHEN A.colorder = 1 THEN d.name ELSE '''' END) TableName, ' +' A.colorder FieldOrder, A.name AS FieldName, ' +' (CASE WHEN COLUMNPROPERTY(A.id, A.name,''IsIdentity'') = 1 THEN ''√'' ELSE '''' END) Flag, ' +' (case when (SELECT count(*) FROM sysobjects ' +' WHERE (name in ' +' (SELECT name ' +' FROM sysindexes ' +' WHERE (id = a.id) AND (indid in ' +' (SELECT indid ' +' FROM sysindexkeys ' +' WHERE (id = a.id) AND (colid in ' +' (SELECT colid ' +' FROM syscolumns ' +' WHERE (id = a.id) AND (name = a.name))))))) AND ' +' (xtype = ''PK''))>0 then ''√'' else '''' end) PrimaryKey, ' +' b.name DataType, a.length DataByte, ' +' COLUMNPROPERTY(a.id,a.name,''PRECISION'') as DataLong, ' +' isnull(COLUMNPROPERTY(a.id,a.name,''Scale''),0) as DataPrecision, ' +' (case when a.isnullable=1 then ''√'' else '''' end) AllowNULL, ' +' isnull(e.text,'''') DefaultValue, ' +' 1 AS FieldRemark ' +' FROM syscolumns a left join systypes b ' +' on a.xtype=b.xusertype inner join sysobjects d ' +' on a.id=d.id and d.xtype=''U'' and d.name<>''dtproperties'' ' +' left join syscomments e on a.cdefault=e.id ' +' left join sysproperties g on a.id=g.id AND a.colid = g.smallid ' +' WHERE d.name = ''%s''' +' order by a.id,a.colorder '; } implementation end.
unit BT_TaskIntf; interface uses Classes, Contnrs, Types, SysUtils; type TMeasureIden = type Integer; TBTTaskStatus = (tsReady, tsRunning, tsFinished, tsStoped); // TBTIden = AnsiString; TBTProcStatus = (psSucc, psFailDueToError, psDueToTimeout); TBTProcUIHint = Record MeasureIndex : Integer; MeasureProcCode : Integer; ProcResult: TBTProcStatus; Info : AnsiString; End; PBTDevItemUIHint = ^TBTDevItemUIHint; TBTDevItemUIHint = Record Curr, Last: TBTProcUIHint; End; type IDevCtrl = Interface ['{A41BD88B-C6AD-4C4A-86AD-E9B6D7916544}'] Procedure StartPort; Procedure StopPort; End; TBTInitInfo = type Pointer; IBTDevItem = Interface ['{808D4D00-A2B3-44E1-B09D-FE42C35E75B2}'] function get_ProcSummary: PBTDevItemUIHint; function get_InitInfo: TBTInitInfo; // function get_ExecuteCount: Integer; // Procedure set_ExecuteCount(const Value: Integer); function get_Executing: Boolean; function get_BProcStore: TObject; function get_DevCtrl: IDevCtrl; function get_LogFile: TFileName; function ThreadExecuteBProc(const AProc: TObject): Boolean; Procedure ResetLog; Procedure LogDebug(Info: AnsiString); Property ProcSummary: PBTDevItemUIHint Read get_ProcSummary; Property InitInfo: TBTInitInfo Read get_InitInfo; // Property ExecutedCount: Integer Read get_ExecuteCount Write set_ExecuteCount; Property Executing: Boolean Read get_Executing; Property BProcStore: TObject Read get_BProcStore; Property DevCtrl: IDevCtrl Read get_DevCtrl; Property LogFile: TFileName Read get_LogFile; End; IBTProgress = Interface ['{1C56D84C-6160-4C77-89BC-236FACD32816}'] function get_ProgressNumerator: Cardinal; // Procedure set_ProgressNumerator(Value: Cardinal); function get_ProgressDenominator: Cardinal; // Procedure set_ProgresDenominator(Value: Cardinal); Procedure IncNumerator; Procedure ResetNumerator; Property Numerator: Cardinal Read get_ProgressNumerator;// Write set_ProgressNumerator; Property Denominator: Cardinal Read get_ProgressDenominator;// Write set_ProgresDenominator; End; //任务接口用来控制协调所有工作的进行。 IBTTask = Interface ['{2FD5A1A9-1F92-4F34-A4B0-02F1F92467DD}'] function get_WorkItemUIList: TComponentList; function get_Status: TBTTaskStatus; function get_HasValidDevice: Boolean; function get_WishCatchEInterruptByUser: Boolean; Procedure Start; Procedure Stop; Procedure LogDebug(Info: AnsiString); Procedure _AllDevExecuteBProcAndWait(ACustomMeasureProc: TObject{TBTCustomMeasureProc}); Procedure _SingleDevExecuteBProcAndWait(ACustomMeasureProc: TObject{TBTCustomMeasureProc}; ADevice: IBTDevItem); Procedure GetProgress(var ANumerator, ADenominator: Cardinal); Property TestItemUIList: TComponentList Read get_WorkItemUIList; Property HasValidDevice: Boolean Read get_HasValidDevice; Property Status: TBTTaskStatus Read get_Status; Property WishCatchEInterruptByUser: Boolean Read get_WishCatchEInterruptByUser; End; ISaveData2XLS = Interface ['{D779ED9A-443B-4D80-853A-27C063CD447E}'] Procedure Save; End; ISaveData2XLS2 = Interface ['{9356D930-BE13-4E38-9FB3-4932ECBFD39C}'] Procedure Save(const ATag: Integer); End; TBTInitInfoHelperClass = Class of TBTInitInfoHelper; TBTInitInfoHelper = Class function UniqueDesc(const AInitInfo: TBTInitInfo): String; virtual; abstract; Procedure Clone(const AFrom: TBTInitInfo; var ADest: TBTInitInfo; AllowMem: Boolean = False); virtual; abstract; function PortName(const AInitInfo: TBTInitInfo): String; virtual; abstract; function SerialCode(const AInitInfo: TBTInitInfo): String; virtual; abstract; // Procedure UpdateInfo(const APortName: String; const ASerialCode: String; var ADest: TBTInitInfo); virtual; abstract; // Procedure NewInfo(const APortName: String; const ASerialCode: String; var ADest: TBTInitInfo); virtual; abstract; Procedure DisposeInfo(var ADest: TBTInitInfo); virtual; abstract; end; TGetBTInitInfoHelperClassFunc = function:TBTInitInfoHelper; const CONST_STR_WORKSTATUS: Array [Low(TBTTaskStatus)..High(TBTTaskStatus)] of String = (' 准备就绪 ', ' 正在测试 ', ' 测试完成 ', ' 测试被中止 '); CONST_STR_WORKPROCRESULT: Array [Low(TBTProcStatus)..High(TBTProcStatus)] of String = ('成功', '出错失败', '超时失败'); implementation end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLGeometryCoordinates<p> Helper functions to convert between different three dimensional coordinate systems. Room for optimisations.<p> <b>History : </b><font size=-1><ul> <li>10/12/14 - PW - Renamed GeometryCoordinates unit into GLGeometryCoordinates <li>30/04/03 - EG - Hyperbolic functions moved to GLVectorGeometry.pas <li>30/04/03 - ARH - Remove math.pas dependency <li>24/04/03 - ARH - Double versions added <li>10/04/03 - ARH - Added ProlateSpheroidal,OblateSpheroidal, BiPolarCylindrical <li>09/04/03 - ARH - Initial Version (Cylindrical,Spherical) </ul> } unit GLGeometryCoordinates; interface uses GLVectorGeometry; {: Convert cylindrical to cartesian [single]. theta in rad} procedure Cylindrical_Cartesian(const r,theta,z1:single;var x,y,z:single);overload; {: Convert cylindrical to cartesian [double]. theta in rads} procedure Cylindrical_Cartesian(const r,theta,z1:double;var x,y,z:double);overload; {: Convert cylindrical to cartesian [single] (with error check). theta in rad} procedure Cylindrical_Cartesian(const r,theta,z1:single;var x,y,z:single; var ierr:integer);overload; {: Convert cylindrical to cartesian [double] (with error check). theta in rad} procedure Cylindrical_Cartesian(const r,theta,z1:double;var x,y,z:double; var ierr:integer);overload; {: Convert cartesian to cylindrical [single]} procedure Cartesian_Cylindrical(const x,y,z1:single; var r,theta,z:single);overload; {: Convert cartesion to cylindrical [double]} procedure Cartesian_Cylindrical(const x,y,z1:double; var r,theta,z:double);overload; {: Convert spherical to cartesion. [single] theta,phi in rads} procedure Spherical_Cartesian(const r,theta,phi:single;var x,y,z:single);overload; {: Convert spherical to cartesion. [double] theta,phi in rads} procedure Spherical_Cartesian(const r,theta,phi:double;var x,y,z:double);overload; {: Convert spherical to cartesian [single] (with error check).theta,phi in rad} procedure Spherical_Cartesian(const r,theta,phi:single;var x,y,z:single; var ierr:integer);overload; {: Convert spherical to cartesian [double] (with error check).theta,phi in rad} procedure Spherical_Cartesian(const r,theta,phi:double;var x,y,z:double; var ierr:integer);overload; {: Convert cartesian to spherical [single]} procedure Cartesian_Spherical(const x,y,z:single; var r,theta,phi:single);overload; procedure Cartesian_Spherical(const v : TAffineVector; var r, theta, phi : Single); overload; {: Convert cartesion to spherical [double]} procedure Cartesian_Spherical(const x,y,z:double; var r,theta,phi:double);overload; {: Convert Prolate-Spheroidal to Cartesian. [single] eta, phi in rad} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:single; var x,y,z:single);overload; {: Convert Prolate-Spheroidal to Cantesian. [double] eta,phi in rad} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:double; var x,y,z:double);overload; {: Convert Prolate-Spheroidal to Cartesian [single](with error check). eta,phi in rad} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:single; var x,y,z:single; var ierr:integer);overload; {: Convert Prolate-Spheroidal to Cartesian [single](with error check). eta,phi in rad} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:double; var x,y,z:double; var ierr:integer);overload; {: Convert Oblate-Spheroidal to Cartesian. [Single] eta, phi in rad} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:single; var x,y,z:single);overload; {: Convert Oblate-Spheroidal to Cartesian. [Double] eta, phi in rad} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:double; var x,y,z:double);overload; {: Convert Oblate-Spheroidal to Cartesian (with error check). eta,phi in rad} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:single; var x,y,z:single; var ierr:integer);overload; {: Convert Oblate-Spheroidal to Cartesian (with error check).[Double] eta,phi in rad} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:double; var x,y,z:double; var ierr:integer);overload; {: Convert Bipolar to Cartesian. u in rad} procedure BipolarCylindrical_Cartesian(const u,v,z1,a:single; var x,y,z:single);overload; {: Convert Bipolar to Cartesian. [Double] u in rad} procedure BipolarCylindrical_Cartesian(const u,v,z1,a:double; var x,y,z:double);overload; {: Convert Bipolar to Cartesian (with error check). u in rad} procedure BipolarCylindrical_Cartesian(const u,v,z1,a:single; var x,y,z:single; var ierr:integer);overload; {: Convert Bipolar to Cartesian (with error check). [Double] u in rad} procedure BipolarCylindrical_Cartesian(const u,v,z1,a:double; var x,y,z:double; var ierr:integer);overload; //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- implementation //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // ----- Cylindrical_Cartesian --------------------------------------------- {** Convert Cylindrical to Cartesian with no checks. Ref: http://mathworld.wolfram.com/CylindricalCoordinates.html} procedure Cylindrical_Cartesian(const r,theta,z1:single;var x,y,z:single); begin SinCosine(theta,r,y,x); z := z1; end; // ----- Cylindrical_Cartesian ------------------------------------------------- {** Convert Cylindrical to Cartesian with no checks. Double version Ref: http://mathworld.wolfram.com/CylindricalCoordinates.html} procedure Cylindrical_Cartesian(const r,theta,z1:double;var x,y,z:double); begin SinCosine(theta,r,y,x); z := z1; end; // ----- Cylindrical_Cartesian ------------------------------------------------- {** Convert Cylindrical to Cartesian with checks. ierr: [0] = ok, [1] = r out of bounds. Acceptable r: [0,inf) [2] = theta out of bounds. Acceptable theta: [0,2pi) [3] = z1 out of bounds. Acceptable z1 : (-inf,inf) Ref: http://mathworld.wolfram.com/CylindricalCoordinates.html} procedure Cylindrical_Cartesian(const r,theta,z1:single;var x,y,z:single; var ierr:integer); begin {** check input parameters} if (r < 0.0) then ierr := 1 else if ((theta < 0.0) or (theta >= 2*pi)) then ierr := 2 else ierr := 0; if (ierr = 0) then begin SinCosine(theta,r,y,x); z := z1; end; end; // ----- Cylindrical_Cartesian ------------------------------------------------- {** Convert Cylindrical to Cartesian with checks. ierr: [0] = ok, [1] = r out of bounds. Acceptable r: [0,inf) [2] = theta out of bounds. Acceptable theta: [0,2pi) [3] = z1 out of bounds. Acceptable z1 : (-inf,inf) Ref: http://mathworld.wolfram.com/CylindricalCoordinates.html} procedure Cylindrical_Cartesian(const r,theta,z1:double;var x,y,z:double; var ierr:integer); begin {** check input parameters} if (r < 0.0) then ierr := 1 else if ((theta < 0.0) or (theta >= 2*pi)) then ierr := 2 else ierr := 0; if (ierr = 0) then begin SinCosine(theta,r,y,x); z := z1; end; end; // ----- Cartesian_Cylindrical ------------------------------------------------- {** Convert Cartesian to Cylindrical no checks. Single} procedure Cartesian_Cylindrical(const x,y,z1:single; var r,theta,z:single); begin r := sqrt(x*x+y*y); theta := ArcTangent2(y,x); z := z1; end; // ----- Cartesian_Cylindrical ------------------------------------------------- {** Convert Cartesian to Cylindrical no checks. Duoble} procedure Cartesian_Cylindrical(const x,y,z1:double; var r,theta,z:double); begin r := sqrt(x*x+y*y); theta := ArcTangent2(y,x); z := z1; end; // ----- Spherical_Cartesian --------------------------------------------------- {** Convert Spherical to Cartesian with no checks. Ref: http://mathworld.wolfram.com/SphericalCoordinates.html} procedure Spherical_Cartesian(const r,theta,phi:single; var x,y,z:single); var a : single; begin SinCosine(phi,r,a,z); // z = r*cos(phi), a=r*sin(phi) SinCosine(theta,a,y,x); // x = a*cos(theta), y = a*sin(theta)} end; // ----- Spherical_Cartesian --------------------------------------------------- {** Convert Spherical to Cartesian with no checks. Double version. Ref: http://mathworld.wolfram.com/SphericalCoordinates.html} procedure Spherical_Cartesian(const r,theta,phi:double; var x,y,z:double); var a : double; begin SinCosine(phi,r,a,z); // z = r*cos(phi), a=r*sin(phi) SinCosine(theta,a,y,x); // x = a*cos(theta), y = a*sin(theta)} end; // ----- Spherical_Cartesian --------------------------------------------------- {** Convert Spherical to Cartesian with checks. ierr: [0] = ok, [1] = r out of bounds [2] = theta out of bounds [3] = phi out of bounds Ref: http://mathworld.wolfram.com/SphericalCoordinates.html} procedure Spherical_Cartesian(const r,theta,phi:single; var x,y,z:single; var ierr:integer); var a : single; begin if (r < 0.0) then ierr := 1 else if ((theta < 0.0) or (theta >= 2*pi)) then ierr := 2 else if ((phi < 0.0) or (phi >= 2*pi)) then ierr := 3 else ierr := 0; if (ierr = 0) then begin SinCosine(phi,r,a,z); // z = r*cos(phi), a=r*sin(phi) SinCosine(theta,a,y,x); // x = a*cos(theta), y = a*sin(theta)} end; end; // ----- Spherical_Cartesian --------------------------------------------------- {** Convert Spherical to Cartesian with checks. ierr: [0] = ok, [1] = r out of bounds [2] = theta out of bounds [3] = phi out of bounds Ref: http://mathworld.wolfram.com/SphericalCoordinates.html} procedure Spherical_Cartesian(const r,theta,phi:double; var x,y,z:double; var ierr:integer); var a : double; begin if (r < 0.0) then ierr := 1 else if ((theta < 0.0) or (theta >= 2*pi)) then ierr := 2 else if ((phi < 0.0) or (phi >= 2*pi)) then ierr := 3 else ierr := 0; if (ierr = 0) then begin SinCosine(phi,r,a,z); // z = r*cos(phi), a=r*sin(phi) SinCosine(theta,a,y,x); // x = a*cos(theta), y = a*sin(theta)} end; end; // ----- Cartesian_Spherical --------------------------------------------------- {** convert Cartesian to Spherical, no checks, single Ref: http://mathworld.wolfram.com/SphericalCoordinates.html NB: Could be optimised by using jclmath.pas unit? } procedure Cartesian_Spherical(const x,y,z:single; var r,theta,phi:single); begin r := sqrt((x*x)+(y*y)+(z*z)); theta := ArcTangent2(y,x); phi := ArcCosine(z/r); end; // Cartesian_Spherical // procedure Cartesian_Spherical(const v : TAffineVector; var r, theta, phi : Single); begin r := VectorLength(v); theta := ArcTangent2(v.V[1], v.V[0]); phi := ArcCosine(v.V[2]/r); end; // ----- Cartesian_Spherical --------------------------------------------------- {** convert Cartesian to Spherical, no checks, double Ref: http://mathworld.wolfram.com/SphericalCoordinates.html NB: Could be optimised by using jclmath.pas unit? } procedure Cartesian_Spherical(const x,y,z:double; var r,theta,phi:double); begin r := Sqrt((x*x)+(y*y)+(z*z)); theta := ArcTangent2(y,x); phi := ArcCosine(z/r); end; // ----- ProlateSpheroidal_Cartesian ------------------------------------------- {** Convert Prolate-Spheroidal to Cartesian with no checks. A system of curvilinear coordinates in which two sets of coordinate surfaces are obtained by revolving the curves of the elliptic cylindrical coordinates about the x-axis, which is relabeled the z-axis. The third set of coordinates consists of planes passing through this axis. The coordinate system is parameterised by parameter a. A default value of a=1 is suggesed: http://documents.wolfram.com/v4/AddOns/StandardPackages/Calculus/VectorAnalysis.html Ref: http://mathworld.wolfram.com/ProlateSpheroidalCoordinates.html} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:single;var x,y,z:single); var sn,cs,snphi,csphi,shx,chx : single; begin SinCosine(eta,a,sn,cs); SinCosine(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := sn*shx*csphi; // x = a*sin(eta)*sinh(xi)*cos(phi) y := sn*shx*snphi; // y = a*sin(eta)*sinh(xi)*sin(phi) z := cs*chx; // z = a*cos(eta)*cosh(xi) end; // ----- ProlateSpheroidal_Cartesian ------------------------------------------- {** Convert Prolate-Spheroidal to Cartesian with no checks. Double version. A system of curvilinear coordinates in which two sets of coordinate surfaces are obtained by revolving the curves of the elliptic cylindrical coordinates about the x-axis, which is relabeled the z-axis. The third set of coordinates consists of planes passing through this axis. The coordinate system is parameterised by parameter a. A default value of a=1 is suggesed: http://documents.wolfram.com/v4/AddOns/StandardPackages/Calculus/VectorAnalysis.html Ref: http://mathworld.wolfram.com/ProlateSpheroidalCoordinates.html} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:double;var x,y,z:double); var sn,cs,snphi,csphi,shx,chx : double; begin SinCosine(eta,a,sn,cs); SinCosine(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := sn*shx*csphi; // x = a*sin(eta)*sinh(xi)*cos(phi) y := sn*shx*snphi; // y = a*sin(eta)*sinh(xi)*sin(phi) z := cs*chx; // z = a*cos(eta)*cosh(xi) end; // ----- ProlateSpheroidal_Cartesian ------------------------------------------- {** Convert Prolate-Spheroidal to Cartesian with checks. ierr: [0] = ok, [1] = xi out of bounds. Acceptable xi: [0,inf) [2] = eta out of bounds. Acceptable eta: [0,pi] [3] = phi out of bounds. Acceptable phi: [0,2pi) Ref: http://mathworld.wolfram.com/ProlateSpheroidalCoordinates.html} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:single; var x,y,z:single; var ierr:integer);overload; var sn,cs,snphi,csphi,shx,chx : single; begin if (xi < 0.0) then ierr := 1 else if ((eta < 0.0) or (eta > pi)) then ierr := 2 else if ((phi < 0.0) or (phi >= 2*pi)) then ierr := 3 else ierr := 0; if (ierr = 0) then begin SinCosine(eta,a,sn,cs); SinCosine(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := sn*shx*csphi; // x = a*sin(eta)*sinh(xi)*cos(phi) y := sn*shx*snphi; // y = a*sin(eta)*sinh(xi)*sin(phi) z := cs*chx; // z = a*cos(eta)*cosh(xi) end; end; // ----- ProlateSpheroidal_Cartesian ------------------------------------------- {** Convert Prolate-Spheroidal to Cartesian with checks. Double Version. ierr: [0] = ok, [1] = xi out of bounds. Acceptable xi: [0,inf) [2] = eta out of bounds. Acceptable eta: [0,pi] [3] = phi out of bounds. Acceptable phi: [0,2pi) Ref: http://mathworld.wolfram.com/ProlateSpheroidalCoordinates.html} procedure ProlateSpheroidal_Cartesian(const xi,eta,phi,a:double; var x,y,z:double; var ierr:integer);overload; var sn,cs,snphi,csphi,shx,chx : double; begin if (xi < 0.0) then ierr := 1 else if ((eta < 0.0) or (eta > pi)) then ierr := 2 else if ((phi < 0.0) or (phi >= 2*pi)) then ierr := 3 else ierr := 0; if (ierr = 0) then begin SinCosine(eta,a,sn,cs); SinCosine(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := sn*shx*csphi; // x = a*sin(eta)*sinh(xi)*cos(phi) y := sn*shx*snphi; // y = a*sin(eta)*sinh(xi)*sin(phi) z := cs*chx; // z = a*cos(eta)*cosh(xi) end; end; // ----- OblateSpheroidal_Cartesian ------------------------------------------- {** Convert Oblate-Spheroidal to Cartesian with no checks. A system of curvilinear coordinates in which two sets of coordinate surfaces are obtained by revolving the curves of the elliptic cylindrical coordinates about the y-axis which is relabeled the z-axis. The third set of coordinates consists of planes passing through this axis. The coordinate system is parameterised by parameter a. A default value of a=1 is suggesed: http://documents.wolfram.com/v4/AddOns/StandardPackages/Calculus/VectorAnalysis.html Ref: http://mathworld.wolfram.com/OblateSpheroidalCoordinates.html} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:single;var x,y,z:single); var sn,cs,snphi,csphi,shx,chx : single; begin SinCosine(eta,a,sn,cs); SinCosine(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := cs*chx*csphi; // x = a*cos(eta)*cosh(xi)*cos(phi) y := cs*chx*snphi; // y = a*cos(eta)*cosh(xi)*sin(phi) z := sn*shx; // z = a*sin(eta)*sinh(xi) end; // ----- OblateSpheroidal_Cartesian ------------------------------------------- {** Convert Oblate-Spheroidal to Cartesian with no checks. Double Version. A system of curvilinear coordinates in which two sets of coordinate surfaces are obtained by revolving the curves of the elliptic cylindrical coordinates about the y-axis which is relabeled the z-axis. The third set of coordinates consists of planes passing through this axis. The coordinate system is parameterised by parameter a. A default value of a=1 is suggesed: http://documents.wolfram.com/v4/AddOns/StandardPackages/Calculus/VectorAnalysis.html Ref: http://mathworld.wolfram.com/OblateSpheroidalCoordinates.html} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:double;var x,y,z:double); var sn,cs,snphi,csphi,shx,chx : double; begin SinCosine(eta,a,sn,cs); SinCosine(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := cs*chx*csphi; // x = a*cos(eta)*cosh(xi)*cos(phi) y := cs*chx*snphi; // y = a*cos(eta)*cosh(xi)*sin(phi) z := sn*shx; // z = a*sin(eta)*sinh(xi) end; // ----- OblateSpheroidal_Cartesian ------------------------------------------- {** Convert Oblate-Spheroidal to Cartesian with checks. ierr: [0] = ok, [1] = xi out of bounds. Acceptable xi: [0,inf) [2] = eta out of bounds. Acceptable eta: [-0.5*pi,0.5*pi] [3] = phi out of bounds. Acceptable phi: [0,2*pi) Ref: http://mathworld.wolfram.com/ProlateSpheroidalCoordinates.html} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:single; var x,y,z:single; var ierr:integer);overload; var sn,cs,snphi,csphi,shx,chx : single; begin if (xi < 0.0) then ierr := 1 else if ((eta < -0.5*pi) or (eta > 0.5*pi)) then ierr := 2 else if ((phi < 0.0) or (phi >= 2*pi)) then ierr := 3 else ierr := 0; if (ierr = 0) then begin SinCosine(eta,a,sn,cs); SinCosine(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := cs*chx*csphi; // x = a*cos(eta)*cosh(xi)*cos(phi) y := cs*chx*snphi; // y = a*cos(eta)*cosh(xi)*sin(phi) z := sn*shx; // z = a*sin(eta)*sinh(xi) end; end; // ----- OblateSpheroidal_Cartesian ------------------------------------------- {** Convert Oblate-Spheroidal to Cartesian with checks. Double Version. ierr: [0] = ok, [1] = xi out of bounds. Acceptable xi: [0,inf) [2] = eta out of bounds. Acceptable eta: [-0.5*pi,0.5*pi] [3] = phi out of bounds. Acceptable phi: [0,2*pi) Ref: http://mathworld.wolfram.com/ProlateSpheroidalCoordinates.html} procedure OblateSpheroidal_Cartesian(const xi,eta,phi,a:double; var x,y,z:double; var ierr:integer);overload; var sn,cs,snphi,csphi,shx,chx : double; begin if (xi < 0.0) then ierr := 1 else if ((eta < -0.5*pi) or (eta > 0.5*pi)) then ierr := 2 else if ((phi < 0.0) or (phi >= 2*pi)) then ierr := 3 else ierr := 0; if (ierr = 0) then begin SinCosine(eta,a,sn,cs); SinCosine(phi,snphi,csphi); shx:=sinh(xi); chx:=cosh(xi); x := cs*chx*csphi; // x = a*cos(eta)*cosh(xi)*cos(phi) y := cs*chx*snphi; // y = a*cos(eta)*cosh(xi)*sin(phi) z := sn*shx; // z = a*sin(eta)*sinh(xi) end; end; // ----- BipolarCylindrical_Cartesian ------------------------------------------ {** Convert BiPolarCylindrical to Cartesian with no checks. http://mathworld.wolfram.com/BipolarCylindricalCoordinates.html } procedure BipolarCylindrical_Cartesian(const u,v,z1,a:single;var x,y,z:single); var cs,sn,shx,chx:single; begin SinCosine(u,sn,cs); shx:=sinh(v); chx:=cosh(v); x := a*shx/(chx-cs); y := a*sn/(chx-cs); z := z1; end; // ----- BipolarCylindrical_Cartesian ------------------------------------------ {** Convert BiPolarCylindrical to Cartesian with no checks. Double Version http://mathworld.wolfram.com/BipolarCylindricalCoordinates.html } procedure BipolarCylindrical_Cartesian(const u,v,z1,a:double;var x,y,z:double); var cs,sn,shx,chx:double; begin SinCosine(u,sn,cs); shx:=sinh(v); chx:=cosh(v); x := a*shx/(chx-cs); y := a*sn/(chx-cs); z := z1; end; // ----- BipolarCylindrical_Cartesian ------------------------------------------ {** Convert Oblate-Spheroidal to Cartesian with checks. ierr: [0] = ok, [1] = u out of bounds. Acceptable u: [0,2*pi) [2] = v out of bounds. Acceptable v: (-inf,inf) [3] = z1 out of bounds. Acceptable z1: (-inf,inf) Ref: http://mathworld.wolfram.com/BiPolarCylindricalCoordinates.html} procedure BipolarCylindrical_Cartesian(const u,v,z1,a:single;var x,y,z:single; var ierr:integer);overload; var cs,sn,shx,chx:single; begin if ((u < 0.0) or (u >= 2*pi)) then ierr := 1 else ierr := 0; if (ierr = 0) then begin SinCosine(u,sn,cs); shx:=sinh(v); chx:=cosh(v); x := a*shx/(chx-cs); y := a*sn/(chx-cs); z := z1; end; end; // ----- BipolarCylindrical_Cartesian ------------------------------------------ {** Convert Oblate-Spheroidal to Cartesian with checks. Double Version ierr: [0] = ok, [1] = u out of bounds. Acceptable u: [0,2*pi) [2] = v out of bounds. Acceptable v: (-inf,inf) [3] = z1 out of bounds. Acceptable z1: (-inf,inf) Ref: http://mathworld.wolfram.com/BiPolarCylindricalCoordinates.html} procedure BipolarCylindrical_Cartesian(const u,v,z1,a:double;var x,y,z:double; var ierr:integer);overload; var cs,sn,shx,chx:double; begin if ((u < 0.0) or (u >= 2*pi)) then ierr := 1 else ierr := 0; if (ierr = 0) then begin SinCosine(u,sn,cs); shx:=sinh(v); chx:=cosh(v); x := a*shx/(chx-cs); y := a*sn/(chx-cs); z := z1; end; end; // ============================================================================= end.
unit UDbfIndex; interface uses sysutils,classes, db, UDbfPagedFile,UDbfCursor,UDbfIndexFile,UDbfCommon; type //==================================================================== //=== Index support //==================================================================== TIndexCursor = class(TVirtualCursor) public OnBracketStr:TOnBracketStr; OnBracketNum:TOnBracketNum; constructor Create(dbfIndexFile:TIndexFile); function Next:boolean; override; function Prev:boolean; override; procedure First; override; procedure Last; override; function GetPhysicalRecno:integer; override; procedure SetPhysicalRecno(Recno:integer); override; function GetSequentialRecordCount:integer; override; function GetSequentialRecno:integer; override; procedure SetSequentialRecno(Recno:integer); override; procedure GotoBookmark(Bookmark:rBookmarkData); override; function GetBookMark:rBookmarkData; override; procedure Insert(Recno:integer; Buffer:PChar); override; procedure Update(Recno: integer; PrevBuffer,NewBuffer: PChar); override; function SetIndexFile:TIndexFile; public IndexBookmark:rBookmarkData; destructor Destroy; override; end; //==================================================================== // TIndexCursor = class; //==================================================================== PIndexPosInfo = ^TIndexPage; //==================================================================== implementation //========================================================== //============ TIndexCursor //========================================================== constructor TIndexCursor.Create(dbfIndexFile:TIndexFile); begin inherited Create(dbfIndexFile); //IndexBookmark.BookmarkFlag:=TBookmarkFlag(-1); IndexBookmark.IndexBookmark:=-1; IndexBookmark.RecNo:=-1; end; destructor TIndexCursor.Destroy; {override;} begin inherited Destroy; end; procedure TIndexCursor.Insert(Recno:integer; Buffer:PChar); begin // Insert doesn't need checkpos. SetIndexFile.Insert(Recno,Buffer); // TODO SET RecNo and Key end; procedure TIndexCursor.Update(Recno: integer; PrevBuffer,NewBuffer: PChar); begin with SetIndexFile do begin CheckPos(IndexBookmark); Update(Recno,PrevBuffer,NewBuffer); end; end; procedure TIndexCursor.First; begin with SetIndexFile do begin // CheckPos(IndexBookmark); not needed First; IndexBookmark:=GetBookmark; end; end; procedure TIndexCursor.Last; begin with SetIndexFile do begin // CheckPos(IndexBookmark); not needed Last; IndexBookmark:=GetBookmark; end; end; function TIndexCursor.Prev:boolean; begin with SetIndexFile do begin CheckPos(IndexBookmark); if Prev then begin Result:=true; IndexBookmark:=GetBookmark; end else begin Result:=false; //IndexBookmark.BookmarkFlag:=TBookmarkFlag(-1); IndexBookmark.IndexBookmark:=-1; IndexBookmark.RecNo:=-1; end; end; end; function TIndexCursor.Next:boolean; begin with SetIndexFile do begin CheckPos(IndexBookmark); if Next then begin Result:=true; IndexBookmark:=GetBookmark; end else begin Result:=false; //IndexBookmark.BookmarkFlag:=TBookmarkFlag(-1); IndexBookmark.IndexBookmark:=-1; IndexBookmark.RecNo:=-1; end; end; end; function TIndexCursor.GetPhysicalRecno:integer; begin SetIndexFile.CheckPos(IndexBookmark); Result:=SetIndexFile.PhysicalRecno; end; procedure TIndexCursor.SetPhysicalRecno(Recno:integer); begin with SetIndexFile do begin GotoRecno(Recno); IndexBookmark:=GetBookMark; end; end; function TIndexCursor.GetSequentialRecordCount:integer; begin with SetIndexFile do begin result:=GetSequentialRecordCount; end; end; function TIndexCursor.GetSequentialRecno:integer; begin with SetIndexFile do begin CheckPos(IndexBookmark); result:=GetSequentialRecno; end; end; procedure TIndexCursor.SetSequentialRecNo(Recno:integer); begin SetIndexFile.SetSequentialRecno(Recno); end; procedure TIndexCursor.GotoBookmark(Bookmark:rBookmarkData); begin with SetIndexFile do begin GotoBookMark(Bookmark); IndexBookmark:=GetBookmark; end; if (IndexBookmark.RecNo<>Bookmark.RecNo) then begin Bookmark.RecNo:=IndexBookmark.RecNo; end; end; function TIndexCursor.GetBookMark:rBookmarkData; begin Result:=IndexBookmark; end; function TIndexCursor.SetIndexFile:TIndexFile; begin Result:=TIndexFile(PagedFile); Result.OnBracketStr:=OnBracketStr; Result.OnBracketNum:=OnBracketNum; end; end.
unit Unit_MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, Kruger_TLB; type TForm1 = class(TForm) txtVolume: TEdit; txtPressure: TEdit; Label1: TLabel; Label2: TLabel; Button1: TButton; lvResults: TListView; txtInfo: TMemo; bnSpectrum: TButton; bnPerformancePoints: TButton; bnDrives: TButton; bnChart: TButton; sd: TSaveDialog; procedure Button1Click(Sender: TObject); procedure bnSpectrumClick(Sender: TObject); procedure bnPerformancePointsClick(Sender: TObject); procedure bnDrivesClick(Sender: TObject); procedure bnChartClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses Unit_GlobalFunctions, DateUtils; {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var SelectionInformation : SelectInfo; SelectionEngine : ICentSelect; Fans : IFans; Fan : IFan; i : integer; ListItem : TListItem; Spectrum : ISpectrum; begin SelectionEngine := CoCentSelect.Create; SelectionInformation.RecordDirectory := ExtractFilePath(Application.ExeName) + '\records\'; SelectionInformation.Volume := strtoint(txtVolume.Text); SelectionInformation.Pressure := strtoint(txtPressure.Text); SelectionInformation.ProductType := ptAny; SelectionInformation.VolumeUnit := vuM3S; SelectionInformation.PressureUnit := puPa; SelectionInformation.PressureType := ptStatic; SelectionInformation.CallType := 0; SelectionInformation.Hz := 50; SelectionInformation.Temperature := 20; SelectionInformation.Altitude := 0; SelectionInformation.ProductType := ptAny; SelectionInformation.MinStyle := msSC; SelectionInformation.MinClass := fcI; SelectionInformation.SoundCondition := scRoom; SelectionInformation.FanCasing := fcSingleFrame; SelectionInformation.FanWidth := fwAny; // Single; SelectionInformation.VelocityUnit := vuMS; SelectionInformation.OutletType := otDucted; SelectionInformation.ServiceFactor := 1.3; SelectionInformation.AltitudeUnit := auFT; SelectionInformation.SoundDistance := 1; SelectionInformation.SoundDistanceUnit := duM; SelectionInformation.TemperatureUnit := DegreeC; SelectionInformation.BladeType := btForwardCurve; Fans := (SelectionEngine.Select(SelectionInformation) As IFans); //One based collection of results to maintain compatibility with legacy software. lvResults.Clear; for i := 1 to Fans.Count do begin Fan := Fans.Item(i) As IFan; with lvResults.Items.Add do begin Caption := Fan.FanDescription; Data := TRowData.Create(Fan); SubItems.Add(FormatFloat('0 rpm',Fan.FanSpeed)); SubItems.Add(FormatFloat('0.00 kW',Fan.PwrCondition)); SubItems.Add(Fan.FanMotorFrame); SubItems.Add(FormatFloat('0.## kW',Fan.FanMotorRating)); SubItems.Add(FormatFloat('0 dB',Fan.Inlet_LwLin_Overall)); end; end; if lvResults.Items.Count > 0 then lvResults.ItemFocused := lvResults.Items[0]; end; procedure TForm1.bnSpectrumClick(Sender: TObject); var Fan : IFan; Spectrum : ISpectrum; SelectionEngine : ICentSelect; LwSpectrum : SingleArray; LwASpectrum : SingleArray; LpASpectrum : SingleArray; begin txtInfo.Clear; if Assigned(lvResults.ItemFocused) then begin Fan := IFan(TRowData(lvResults.ItemFocused.Data).ComObj); SelectionEngine := CoCentSelect.Create; Spectrum := SelectionEngine.SoundSpectrumEx(Fan,0,false) As ISpectrum; SafeArrayToSingleArray(Spectrum.Inlet_LwLin_Spectrum,lwSpectrum); SafeArrayToSingleArray(Spectrum.Inlet_LwA_Spectrum,lwASpectrum); SafeArrayToSingleArray(Spectrum.Inlet_LpA_Spectrum,lpASpectrum); txtInfo.Lines.Add(Format('Inlet Lw %0.0f %0.0f %0.0f %0.0f %0.0f %0.0f %0.0f %0.0f',[LwSpectrum[0],LwSpectrum[1],LwSpectrum[2],LwSpectrum[3],LwSpectrum[4],LwSpectrum[5],LwSpectrum[6],LwSpectrum[7]])); txtInfo.Lines.Add(Format('Inlet LwA %0.0f %0.0f %0.0f %0.0f %0.0f %0.0f %0.0f %0.0f',[LwASpectrum[0],LwSpectrum[1],LwSpectrum[2],LwSpectrum[3],LwSpectrum[4],LwSpectrum[5],LwSpectrum[6],LwSpectrum[7]])); txtInfo.Lines.Add(Format('Inlet LpA %0.0f %0.0f %0.0f %0.0f %0.0f %0.0f %0.0f %0.0f',[LpASpectrum[0],LwSpectrum[1],LwSpectrum[2],LwSpectrum[3],LwSpectrum[4],LwSpectrum[5],LwSpectrum[6],LwSpectrum[7]])); end else showmessage('Please select a fan from the list first'); end; procedure TForm1.bnPerformancePointsClick(Sender: TObject); var i : integer; Fan : IFan; Curve : ICurve; SelectionEngine : ICentSelect; Volume : SingleArray; Pressure : SingleArray; Power : SingleArray; begin txtInfo.Clear; if Assigned(lvResults.ItemFocused) then begin Fan := IFan(TRowData(lvResults.ItemFocused.Data).ComObj); SelectionEngine := CoCentSelect.Create; Curve := SelectionEngine.CurvePoints(Fan,0) As ICurve; SafeArrayToSingleArray(Curve.VolumePoints,Volume); SafeArrayToSingleArray(Curve.PressurePoints,Pressure); SafeArrayToSingleArray(Curve.PowerPoints,Power); txtInfo.Lines.Add(' Nr m3/s Pa kW'); for i := 0 to Length(Volume) - 1 do begin txtInfo.Lines.Add(Format('%3d%15.4f%15.4f%15.4f',[i+1,Volume[i],Pressure[i],Power[i]])); end; txtInfo.SelStart := 1; txtInfo.SelLength := 1; end else showmessage('Please select a fan from the list first'); end; procedure TForm1.bnDrivesClick(Sender: TObject); var i : integer; Fan : IFan; Drives : IDrives; Drive : IDrive; DriveInfo : IDriveInfo; Volume : SingleArray; Pressure : SingleArray; Power : SingleArray; begin txtInfo.Clear; if Assigned(lvResults.ItemFocused) then begin Fan := IFan(TRowData(lvResults.ItemFocused.Data).ComObj); Drives := CoDrives.Create; DriveInfo := CoDriveInfo.Create; DriveInfo.RecordDirectory := ExtractFilePath(Application.ExeName) + '\records\'; DriveInfo.Distance := 0; // 0 = Standard. 1 to 7 as Program ComboBox. Over 10 = user specified distance in mm DriveInfo.BearingLoad := 1; // 0 = low. 1 = medium. 2 = heavy. 3 = Extra Heavy DriveInfo.StartTime := 0; // 0 = Standard times. Over 0 = user defined time in seconds DriveInfo.SPZ := TRUE; // True or False DriveInfo.SPA := TRUE; // True or False DriveInfo.SPB := TRUE; // True or False DriveInfo.SPC := TRUE; // True or False DriveInfo.Pole2 := TRUE; // True or False DriveInfo.Pole4 := TRUE; // True or False DriveInfo.Pole6 := TRUE; // True or False DriveInfo.Pole8 := TRUE; // True or False DriveInfo.L50_Life := 75000; // INTEGER DriveInfo.L50_Life := 300000; // INTEGER DriveInfo.MotorPosition := 1; // 1 = Z. 2 = W DriveInfo.FanHanding := 0; // 0 = CW90. 1 = CW180. 2 = CW270. 3 = CW360. 4 = CCW90. 5 = CCW180. 6 = CCW270. 7 = CCW360. DriveInfo.FanArrangement := 1; // 1 = Set Drives.SelectDrives(Fan,DriveInfo); txtInfo.Lines.Add(' Nr Deviation Actual Speed Starting Torque'); for i := 0 to Drives.Count - 1 do begin Drive := Drives.Items(i); txtInfo.Lines.Add(Format('%3d%18.4f%18.0d%18.4f',[i+1,Drive.Deviation,Drive.ActualFanSpeed,Drive.StartingTorque])); end; txtInfo.SelStart := 1; txtInfo.SelLength := 1; end else showmessage('Please select a fan from the list first'); end; procedure TForm1.bnChartClick(Sender: TObject); var Fan : IFan; Spectrum : ISpectrum; SelectionEngine : ICentSelect; LwSpectrum : SingleArray; LwASpectrum : SingleArray; LpASpectrum : SingleArray; begin txtInfo.Clear; if Assigned(lvResults.ItemFocused) then begin Fan := IFan(TRowData(lvResults.ItemFocused.Data).ComObj); SelectionEngine := CoCentSelect.Create; sd.FileName := StringReplace(Fan.FanDescription,'/','-',[rfReplaceAll]); if sd.Execute then begin (* coGIF = $00000000; coBMP = $00000001; coWMF = $00000002; *) SelectionEngine.GenerateChart(Fan,sd.FileName,800,600,sd.FilterIndex-1); end; end else showmessage('Please select a fan from the list first'); end; end.
//////////////////////////////////////////// // Кодировка и расчет CRC для приборов Логика СПТ-941 //////////////////////////////////////////// unit Devices.Logica.SPT941; interface uses Windows, GMGlobals, GMConst, Classes, SysUtils, Devices.ReqCreatorBase, GMSqlQuery, GMBlockValues, GMGenerics, Generics.Collections, UsefulQueries; function LogicaSPT941_CheckCRC(buf: array of Byte; Len: int): bool; type TSPT941ArchReqPeriodInfo = record name: string; period: int; depth: int; function NameWithChannel(channel: int): string; end; const FSPT941ArchReqPeriodTypes: array[0..2] of TSPT941ArchReqPeriodInfo = ( (name: DEV_STATE_NAMES_LAST_ARCH_REQ_FULL_DEPTH; period: 30 * UTC_DAY; depth: 1990 * UTC_HOUR), (name: DEV_STATE_NAMES_LAST_ARCH_REQ_MONTH_DEPTH; period: 7 * UTC_DAY; depth: 31 * UTC_DAY), (name: DEV_STATE_NAMES_LAST_ARCH_REQ_DAY_DEPTH; period: UTC_HOUR; depth: UTC_DAY) ); type TSPT941ReqCreator = class(TDevReqCreator) private FRequestNumber: int; FCurrentReqChn: int; procedure InitSessionRequest; procedure CurrentsRequestChn(); procedure ProcessCurrentsQuery(q: TGMSqlQuery; obj: pointer); procedure WrapAndSend(const body: string; reqType: T485RequestType); procedure CurrentsRequest; procedure LoadRequestNumber; procedure SaveRequestNumber; procedure AddArchives; procedure AddOneArchiveRequest(udt1, udt2: LongWord); function UTimeToReqString(udt: LongWord): string; function MaxArchRecordsInRequest: int; procedure AddArchives_OneChannel; function NeedReqArch_OnePeriod(const periodName: string; period: int): bool; protected function NeedReqArch(): int; virtual; // для тестов function CurrentsRequestType(Chn: int): T485RequestType; virtual; function CanRequestPack(): bool; virtual; function ChannelCount: int; virtual; public procedure AddRequests(); override; end; T941ArchChannnel = class public ID_Prm: int; RecordIndex: int; end; TSPT941AnswerParser = class private FValues: TGMCollection<TValueFromBaseClass>; FChannels: TGMCollection<T941ArchChannnel>; FParseError: string; Fgbv: TGeomerBlockValues; function CheckPackage: bool; function ParsePackage: bool; function ParseCurrents: bool; function FindWordPos(idx: int): int; function ReadValueFromPosition(pos: int; var res: double): bool; function CheckEnoughLengthForVal(pos, valLength: int): bool; procedure AddValue(id_prm: int; UTime: LongWord; val: double; valType: TGMValueType); function ParseArch: bool; procedure ReadArchChannels; procedure ReadArchChannel(q: TGMSqlQuery; obj: pointer); function ReadArcRecord(var pos: int): bool; function ReadArcRecord_CheckLength(sequenceStart: int; var dataStart, dataLen: int): bool; function ReadArcRecord_ProcessValues(utime: LongWord; dataStart, dataLen: int): bool; public function Parse(gbv: TGeomerBlockValues): bool; property ParseError: string read FParseError; property Values: TGMCollection<TValueFromBaseClass> read FValues; constructor Create(); destructor Destroy; override; end; implementation uses DateUtils, ProgramLogFile, ArchIntervalBuilder, Math, Devices.Logica.Base; const PNUM_TAG = $4A; PNUM_TAG_STR = ' 4A '; OCTET_STRING_TAG = $04; OCTET_STRING_TAG_STR = ' 04 '; ARCHDATE_TAG = $49; ARCHDATE_TAG_STR = ' 49 '; SEQUENCE_TAG = $30; FNC_ARCH = $61; FNC_ARCH_STR = ' 61 '; FNC_CURRENTS = $72; FNC_CURRENTS_STR = ' 72 '; function LogicaSPT941_CheckCRC(buf: array of Byte; Len: int): bool; begin Result := LogicaM4_CheckCRC(buf, len); end; { TSPT941ReqCreator } procedure TSPT941ReqCreator.InitSessionRequest(); var buf: array[0..15] of Byte; i: int; begin for i := 0 to 15 do buf[i] := $FF; // инициализация линии AddBufRequestToSendBuf(buf, 16, rqtDummy); buf[0] := $10; buf[1] := FReqDetails.DevNumber and $FF; buf[2] := $90; buf[3] := $00; buf[4] := $00; buf[5] := $05; buf[6] := $00; buf[7] := $3f; buf[8] := $00; buf[9] := $00; buf[10] := $00; buf[11] := $00; LogicaM4_CRC(buf, 12); AddBufRequestToSendBuf(buf, 14, rqtDummy); end; function TSPT941ReqCreator.CanRequestPack: bool; begin Result := FReqDetails.ObjType <> OBJ_TYPE_GM; end; procedure TSPT941ReqCreator.WrapAndSend(const body: string; reqType: T485RequestType); const SOH = ' 10 '; FRM = ' 90 '; ATR = ' 00 '; var buf: array[0..1024] of byte; tmp: ArrayOfByte; req, NT, ID, DL1, DL0: string; l: int; begin inc(FRequestNumber); FRequestNumber := FRequestNumber mod 100; NT := ' ' + IntToHex(FReqDetails.DevNumber and $FF, 2); ID := ' ' + IntToHex(FRequestNumber, 2); l := Length(TextNumbersStringToArray(body)); DL1 := ' ' + IntToHex(l mod 256, 2); DL0 := ' ' + IntToHex((l div 256) and $FF, 2); req := SOH + NT + FRM + ID + ATR + DL1 + DL0 + body; tmp := TextNumbersStringToArray(req); l := Length(tmp); WriteBuf(buf, 0, tmp, l); LogicaM4_CRC(buf, l); FReqDetails.ReqID := FRequestNumber; AddBufRequestToSendBuf(buf, l + 2, reqType); end; procedure TSPT941ReqCreator.ProcessCurrentsQuery(q: TGMSqlQuery; obj: pointer); const DL = ' 03 '; var Ch, Data, res: string; prm: int; begin if not CanRequestPack() then FReqDetails.ClearReqLink(); prm := q.FieldByName('CurrentsAddr').AsInteger; Data := ' ' + IntToHex(prm mod 256, 2) + ' ' + IntToHex((prm div 256) and $FF, 2); Ch := ' ' + IntToHex(q.FieldByName('CurrentsArgument').AsInteger, 2); res := PNUM_TAG_STR + DL + Ch + Data; FReqDetails.AddReqLink(q.FieldByName('ID_Prm').AsInteger); if CanRequestPack() then TSTringBuilder(obj).Append(res) else WrapAndSend(FNC_CURRENTS_STR + res, CurrentsRequestType(FCurrentReqChn)); end; function TSPT941ReqCreator.CurrentsRequestType(Chn: int): T485RequestType; begin Result := rqtSPT941; end; procedure TSPT941ReqCreator.CurrentsRequestChn(); var sb: TSTringBuilder; begin FReqDetails.ReqLinkCount := 0; sb := TSTringBuilder.Create(); try ReadFromQuery( 'select * from Params '+ #13#10' where ID_Device = ' + IntToStr(FReqDetails.ID_Device) + #13#10' and coalesce(CurrentsArgument, 0) = ' + IntToStr(FCurrentReqChn) + #13#10' order by ID_Src, N_Src', ProcessCurrentsQuery, sb); if CanRequestPack() and (Trim(sb.ToString()) > '') then WrapAndSend(FNC_CURRENTS_STR + sb.ToString(), CurrentsRequestType(FCurrentReqChn)); finally sb.Free(); end; end; function TSPT941ReqCreator.ChannelCount(): int; begin Result := 1; end; procedure TSPT941ReqCreator.CurrentsRequest(); var i: int; begin for i := 0 to ChannelCount() - 1 do begin FCurrentReqChn := i; CurrentsRequestChn(); end; end; procedure TSPT941ReqCreator.LoadRequestNumber(); begin FRequestNumber := StrToIntDef(QueryResult('select LastReqNumber from ObjectStates where ID_Obj = ' + IntToStr(FReqDetails.ID_Obj)), 0); end; procedure TSPT941ReqCreator.SaveRequestNumber(); begin ExecPLSQL(Format('perform ObjectSetLastReqNumber(%d, %d)', [FReqDetails.ID_Obj, (FRequestNumber + 1) mod 256])); end; function TSPT941ReqCreator.UTimeToReqString(udt: LongWord): string; var y, m, d, h, n, s, z: Word; begin DecodeDateTime(UTCtoLocal(udt), y, m, d, h, n, s, z); if (y < 2000) or (y > 2255) then y := YearOf(Now()); Result := Format('04 %2x %2x %2x %2x', [y - 2000, m, d, h]); end; procedure TSPT941ReqCreator.AddOneArchiveRequest(udt1, udt2: LongWord); const DL = ' 05 '; CNT = ' FF FF '; RECTYPE = ' 00 '; var N, body, ch: string; begin ProgramLog.AddMessage(Format('AddOneArchiveRequest id_device = %d chn = %d, u1 = %d(%s), u2 = %d(%s)', [FReqDetails.ID_Device, FCurrentReqChn, udt1, DateTimeToStr(UTCtoLocal(udt1)), udt2, DateTimeToStr(UTCtoLocal(udt2))])); N := ' ' + IntToHex(MaxArchRecordsInRequest(), 2) + ' '; Ch := ' ' + IntToHex(FCurrentReqChn, 2) + ' '; body := FNC_ARCH_STR + OCTET_STRING_TAG_STR + DL + CNT + Ch + RECTYPE + N + ARCHDATE_TAG_STR + UTimeToReqString(udt1); // ARCHDATE_TAG_STR + UTimeToReqString(udt2); WrapAndSend(body, CurrentsRequestType(FCurrentReqChn)); end; function TSPT941ReqCreator.MaxArchRecordsInRequest(): int; begin Result := IfThen(CanRequestPack(), 4, 1); end; function TSPT941ReqCreator.NeedReqArch_OnePeriod(const periodName: string; period: int): bool; var lastReq: ULong; begin Result := false; lastReq := Min(StrToIntDef(SQLReq_GetDevState(FReqDetails.ID_Device, periodName), 0), NowGM() + UTC_HOUR); if int64(NowGM()) - lastReq > period then begin Result := true; end; end; function TSPT941ReqCreator.NeedReqArch(): int; var i: int; begin Result := -1; for i := 0 to High(FSPT941ArchReqPeriodTypes) do begin if NeedReqArch_OnePeriod(FSPT941ArchReqPeriodTypes[i].NameWithChannel(FCurrentReqChn), FSPT941ArchReqPeriodTypes[i].period) then begin Result := i; Exit; end; end; end; procedure TSPT941ReqCreator.AddArchives_OneChannel; var lst: TList<ArchReqInterval>; a: ArchReqInterval; intrvBuilder: TArchIntervalBuilder; sql: string; ut_depth: ULong; reqType, i: int; begin reqType := NeedReqArch(); if reqType < 0 then Exit; ut_depth := int64((NowGM() div UTC_HOUR) * UTC_HOUR) - FSPT941ArchReqPeriodTypes[reqType].depth; sql := Format('select UTime from ArchHourRequestStartDateForDevice(%d, %d) order by 1', [FReqDetails.ID_Device, ut_depth]); intrvBuilder := TArchIntervalBuilder.Create(sql); try lst := intrvBuilder.BuildIntervalList(UTC_HOUR, MaxArchRecordsInRequest()); try for a in lst do begin FReqDetails.UTimeArch := a.UTime1; FReqDetails.Priority := rqprArchives; AddOneArchiveRequest(a.UTime1, a.UTime2); end; for i := High(FSPT941ArchReqPeriodTypes) downto reqType do SQLReq_SetDevState(FReqDetails.ID_Device, FSPT941ArchReqPeriodTypes[i].NameWithChannel(FCurrentReqChn), NowGM()); finally lst.Free(); end; finally intrvBuilder.Free(); end; end; procedure TSPT941ReqCreator.AddArchives; var i: int; begin for i := 0 to ChannelCount() - 1 do begin FCurrentReqChn := i; AddArchives_OneChannel(); end; end; procedure TSPT941ReqCreator.AddRequests; begin LoadRequestNumber(); InitSessionRequest(); CurrentsRequest(); AddArchives(); SaveRequestNumber(); end; { TSPT941ReqParser } function TSPT941AnswerParser.CheckPackage(): bool; var len: int; begin Result := false; len := ReadWord(Fgbv.gmBufRec, 5) + 7{header} + 2{crc}; if (Fgbv.gmLenRec < 7) or (len <> Fgbv.gmLenRec) then begin FParseError := 'Bad Length'; Exit; end; if not LogicaSPT941_CheckCRC(Fgbv.gmBufRec, Fgbv.gmLenRec) then begin FParseError := 'Bad CRC'; Exit; end; if (Fgbv.gmBufRec[0] <> Fgbv.ReqDetails.buf[0]) // SOH or (Fgbv.gmBufRec[1] <> Fgbv.ReqDetails.buf[1]) // DevNumber or (Fgbv.gmBufRec[2] <> Fgbv.ReqDetails.buf[2]) // FRM or (Fgbv.gmBufRec[3] <> Fgbv.ReqDetails.buf[3]) // ID or (Fgbv.gmBufRec[4] <> Fgbv.ReqDetails.buf[4]) // ATR or (Fgbv.gmBufRec[7] <> Fgbv.ReqDetails.buf[7]) // FNC then begin FParseError := 'Wrong Package'; Exit; end; Result := true; end; constructor TSPT941AnswerParser.Create; begin inherited; FValues := TGMCollection<TValueFromBaseClass>.Create(); FChannels := TGMCollection<T941ArchChannnel>.Create(); end; destructor TSPT941AnswerParser.Destroy; begin FValues.Free(); FChannels.Free(); inherited; end; function TSPT941AnswerParser.CheckEnoughLengthForVal(pos, valLength: int): bool; begin Result := (Fgbv.gmLenRec > pos + 1{len} + valLength{val} + 2{crc}) and (Fgbv.gmBufRec[pos + 1] = valLength); FParseError := 'Bad Data: too short '; end; function TSPT941AnswerParser.ReadValueFromPosition(pos: int; var res: double): bool; var y, m, d, h, n, s, dl: int; begin Result := false; case Fgbv.gmBufRec[pos] of $43: // IEEFloat begin Result := CheckEnoughLengthForVal(pos, 4); if Result then res := ReadSingle(Fgbv.gmBufRec, pos + 2); end; $44: // MIXED begin Result := CheckEnoughLengthForVal(pos, 8); if Result then res := ReadUINT(Fgbv.gmBufRec, pos + 2) + ReadSingle(Fgbv.gmBufRec, pos + 6); end; $05: // NULL begin res := NAN; Result := true; end; $41: // IntU begin res := ReadUINT(Fgbv.gmBufRec, pos + 2); Result := true; end; $47: // TIME begin s := Fgbv.gmBufRec[pos + 2] * 256 + Fgbv.gmBufRec[pos + 3]; n := Fgbv.gmBufRec[pos + 4]; h := Fgbv.gmBufRec[pos + 5]; res := EncodeTime(h, n, s, 0); Result := true; end; $48: // DATE begin d := Fgbv.gmBufRec[pos + 2]; m := Fgbv.gmBufRec[pos + 3]; y := 2000 + Fgbv.gmBufRec[pos + 4]; res := Encodedate(y, m, d); Result := true; end; $49: // ARCHDATE begin m := 1; d := 1; h := 0; dl := Fgbv.gmBufRec[pos + 1]; Result := dl > 0; if Result then begin y := 2000 + Fgbv.gmBufRec[pos + 2]; if dl > 1 then m := Fgbv.gmBufRec[pos + 3]; if dl > 2 then d := Fgbv.gmBufRec[pos + 4]; if dl > 3 then h := Fgbv.gmBufRec[pos + 5]; res := EncodeDateTime(y, m, d, h, 0, 0, 0); end; end; $4B: // FLAGS begin res := ReadInt64(Fgbv.gmBufRec, pos + 2); Result := true; end else begin FParseError := 'Bad Data: unknown value type at pos ' + IntToStr(pos); end; end; if not Result then FParseError := 'Bad Data: Too short'; end; function TSPT941AnswerParser.FindWordPos(idx: int): int; var i: int; n: int; val: double; begin Result := -1; n := 8; if not ReadValueFromPosition(n, val) then Exit; for i := 0 to idx - 1 do begin if not ReadValueFromPosition(n, val) then Exit; inc(n, 2{байт типа данных + байт длины данных} + Fgbv.gmBufRec[n + 1]{длина данных}); end; Result := n; end; procedure TSPT941AnswerParser.AddValue(id_prm: int; UTime: LongWord; val: double; valType: TGMValueType); var v: TValueFromBaseClass; begin v := FValues.Add(); v.ID_Prm := id_prm; v.Val.Chn := TObject(id_prm); v.Val.UTime := UTime; v.Val.Val := val; v.Val.ValType := valType; end; function TSPT941AnswerParser.ParseCurrents(): bool; var i: int; n: int; val: double; begin Result := false; for i := 0 to Fgbv.ReqDetails.ReqLinkCount - 1 do begin n := FindWordPos(i); if n < 0 then Exit; if not ReadValueFromPosition(n, val) then Exit; if not IsNan(val) then AddValue(Fgbv.ReqDetails.ReqLinks[i].id, Fgbv.gmTime, val, valueTypeCurrent); end; Result := true; end; procedure TSPT941AnswerParser.ReadArchChannel(q: TGMSqlQuery; obj: pointer); var chn: T941ArchChannnel; begin chn := FChannels.Add(); chn.ID_Prm := q.FieldByName('ID_Prm').AsInteger; chn.RecordIndex := q.FieldByName('HourArchAddr').AsInteger; end; procedure TSPT941AnswerParser.ReadArchChannels(); var sql: string; begin FChannels.Clear(); sql := Format('select ID_Prm, HourArchAddr from Params where ID_Device = %d and coalesce(HourArchAddr, 0) > 0', [Fgbv.ReqDetails.ID_Device]); ReadFromQuery(sql, ReadArchChannel); end; function TSPT941AnswerParser.ReadArcRecord_CheckLength(sequenceStart: int; var dataStart, dataLen: int): bool; var n, coeff: int; begin Result := false; if Fgbv.gmBufRec[sequenceStart + 1] < $80 then begin dataLen := Fgbv.gmBufRec[sequenceStart + 1]; dataStart := sequenceStart + 2; end else begin n := Fgbv.gmBufRec[sequenceStart + 1] - $80; // длина DL if sequenceStart + n + 1 >= Fgbv.gmLenRec then Exit; dataStart := sequenceStart + 1 {DL} + n {длина DL} + 1; dataLen := 0; coeff := 1; while n > 0 do begin dataLen := dataLen + Fgbv.gmBufRec[sequenceStart + 1 + n] * coeff; dec(n); coeff := coeff * 256; end; end; Result := dataStart + dataLen < Fgbv.gmLenRec;; end; function TSPT941AnswerParser.ReadArcRecord_ProcessValues(utime: LongWord; dataStart, dataLen: int): bool; var i, n, pos: int; val: double; begin Result := false; n := 1; pos := dataStart; while pos < dataStart + dataLen do begin if not ReadValueFromPosition(pos, val) then Exit; if not IsNan(val) then begin for i := 0 to FChannels.Count - 1 do begin if FChannels[i].RecordIndex = n then AddValue(FChannels[i].ID_Prm, utime, val, valueTypeHourArch); end; end; pos := pos + Fgbv.gmBufRec[pos + 1] + 2; inc(n); end; Result := true; end; function TSPT941AnswerParser.ReadArcRecord(var pos: int): bool; var dt: TDateTime; sequenceStart, dataStart, dataLen: int; val: double; begin Result := false; if Fgbv.gmBufRec[pos] <> ARCHDATE_TAG then begin FParseError := 'ARCHDATE_TAG not found pos: ' + IntToStr(pos); Exit; end; if not ReadValueFromPosition(pos, val) then begin FParseError := 'ARCHDATE not found pos: ' + IntToStr(pos); Exit; end; dt := val; sequenceStart := pos + 1 + Fgbv.gmBufRec[pos + 1] + 1; // ARCHDATE_TAG + DL + DL bytes if (sequenceStart >= Fgbv.gmLenRec) or (Fgbv.gmBufRec[sequenceStart] <> SEQUENCE_TAG) then begin FParseError := 'SEQUENCE_TAG not found pos: ' + IntToStr(pos); Exit; end; if not ReadArcRecord_CheckLength(sequenceStart, dataStart, dataLen) then begin FParseError := 'CheckLength failed pos: ' + IntToStr(pos); Exit; end; Result := ReadArcRecord_ProcessValues(LocalToUTC(dt), dataStart, dataLen); pos := dataStart + dataLen; end; function TSPT941AnswerParser.ParseArch(): bool; var pos: int; begin Result := false; ReadArchChannels(); pos := 8; while pos < FGbv.gmLenRec - 2{CRC} do begin if not ReadArcRecord(pos) then Exit; end; Result := true; end; function TSPT941AnswerParser.ParsePackage(): bool; begin Result := false; case Fgbv.gmBufRec[7] of FNC_CURRENTS: Result := ParseCurrents(); FNC_ARCH: Result := ParseArch(); else FParseError := 'Bad FNC'; end; end; function TSPT941AnswerParser.Parse(gbv: TGeomerBlockValues): bool; begin FGbv := gbv; Result := CheckPackage() and ParsePackage(); end; { TSPT941ArchReqPeriodInfo } function TSPT941ArchReqPeriodInfo.NameWithChannel(channel: int): string; begin Result := name + IntToStr(channel); end; end.
{*******************************************************} { } { Delphi LiveBindings Framework } { } { Copyright(c) 2012-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit Vcl.Bind.Grid; interface uses System.SysUtils, System.Classes, Data.Bind.Components, Data.Bind.Grid, System.Bindings.Outputs, System.Generics.Collections, Vcl.Grids; implementation type TBaseLinkGridToDataSourceControlManager = class(TInterfacedObject, ILinkGridToDataSourceControlManager) private FCustomGrid: TDrawGrid; FDefaultColumnWidth: Integer; function AddColumn( const ADescription: TCreateColumnDescription): Integer; overload; function DescribeColumn( AIndex: Integer; const ADescription: TCreateColumnDescription): TLinkGridColumnDescription; overload; procedure UpdateColumn(AIndex: Integer; const ACreateDescription: TCreateColumnDescription); overload; protected function CreateColumn( const ADescription: TCreateColumnDescription; AGrid: TDrawGrid): Integer; virtual; function CreateColumnDescription( AIndex: Integer; ADescription: TCreateColumnDescription): TLinkGridColumnDescription; virtual; abstract; procedure ApplyDescription(const ADescription: TCreateColumnDescription; AColumn: Integer); virtual; function GetDefaultColumnWidth: Integer; procedure SetDefaultColumnWidth(AWidth: Integer); procedure BeginUpdate; procedure EndUpdate; function CanAddColumn(AColumn: TBaseLinkGridToDataSourceColumn): Boolean; overload; function CanAddColumn(ADataSource: TBaseLinkingBindSource; const AMemberName: string): Boolean; overload; procedure ClearColumns; virtual; function DescribeColumn(AIndex: Integer; AColumn: TBaseLinkGridToDataSourceColumn): TLinkGridColumnDescription; overload; function DescribeColumn(AIndex: Integer; ADataSource: TBaseLinkingBindSource; const AMemberName: string): TLinkGridColumnDescription; overload; function AddColumn(AColumn: TBaseLinkGridToDataSourceColumn): Integer; overload; function AddColumn(ADataSource: TBaseLinkingBindSource; const AMemberName: string): Integer; overload; procedure UpdateColumn(AIndex: Integer; AColumn: TBaseLinkGridToDataSourceColumn); overload; procedure UpdateColumn(AIndex: Integer; ADataSource: TBaseLinkingBindSource; const AMemberName: string); overload; function GetColumnStyles: TArray<string>; public constructor Create(ACustomGrid: TDrawGrid); end; TLinkStringGridToDataSourceControlManager = class(TBaseLinkGridToDataSourceControlManager) private FStringGrid: TStringGrid; protected function CreateColumnDescription(AIndex: Integer; ADescription: TCreateColumnDescription): TLinkGridColumnDescription; override; procedure ApplyDescription(const ADescription: TCreateColumnDescription; AColumn: Integer); override; procedure ClearColumns; override; public constructor Create(AStringGrid: TStringGrid); end; TBaseLinkGridToDataSourceColumnFactory = class(TLinkGridToDataSourceColumnFactory) public function UsesUnits: TArray<string>; override; function FrameworkExt: string; override; end; TLinkStringGridToDataSourceColumnFactory = class(TBaseLinkGridToDataSourceColumnFactory) public function GridClasses: TArray<TComponentClass>; override; function Supports(AIntf: TGuid; AGrid: TComponent): Boolean; override; function CreateFactory(AIntf: TGuid; AGrid: TComponent): IInterface; override; end; { TBaseLinkGridToDataSourceControlManager } function TBaseLinkGridToDataSourceControlManager.AddColumn( ADataSource: TBaseLinkingBindSource; const AMemberName: string): Integer; var LDescription: TCreateColumnDescription; begin LDescription := TCreateColumnDescription.Create(ADataSource, AMemberName); Result := AddColumn(LDescription); end; procedure TBaseLinkGridToDataSourceControlManager.BeginUpdate; begin // FMX only // Self.FCustomGrid.BeginUpdate; end; function TBaseLinkGridToDataSourceControlManager.DescribeColumn( AIndex: Integer; AColumn: TBaseLinkGridToDataSourceColumn): TLinkGridColumnDescription; begin Result := DescribeColumn(AIndex, TCreateColumnDescription.Create(AColumn as TLinkGridToDataSourceColumn)); end; function TBaseLinkGridToDataSourceControlManager.DescribeColumn( AIndex: Integer; ADataSource: TBaseLinkingBindSource; const AMemberName: string): TLinkGridColumnDescription; begin Result := DescribeColumn(AIndex, TCreateColumnDescription.Create(ADataSource, AMemberName)); end; function TBaseLinkGridToDataSourceControlManager.AddColumn( AColumn: TBaseLinkGridToDataSourceColumn): Integer; begin Result := AddColumn(TCreateColumnDescription.Create(AColumn as TLinkGridToDataSourceColumn)); end; procedure TBaseLinkGridToDataSourceControlManager.UpdateColumn(AIndex: Integer; const ACreateDescription: TCreateColumnDescription); var LColumn: Integer; begin LColumn := AIndex; if (LColumn >= 0) and (LColumn < FCustomGrid.ColCount) then begin if ACreateDescription.Width <> -1 then FCustomGrid.ColWidths[LColumn] := ACreateDescription.Width else FCustomGrid.ColWidths[LColumn] := GetDefaultColumnWidth; ApplyDescription(ACreateDescription, LColumn); end; end; procedure TBaseLinkGridToDataSourceControlManager.UpdateColumn(AIndex: Integer; AColumn: TBaseLinkGridToDataSourceColumn); var LCreateDescription: TCreateColumnDescription; begin LCreateDescription := TCreateColumnDescription.Create(AColumn as TLinkGridToDataSourceColumn); UpdateColumn(AIndex, LCreateDescription); end; procedure TBaseLinkGridToDataSourceControlManager.UpdateColumn(AIndex: Integer; ADataSource: TBaseLinkingBindSource; const AMemberName: string); var LCreateDescription: TCreateColumnDescription; begin LCreateDescription := TCreateColumnDescription.Create(ADataSource, AMemberName); UpdateColumn(AIndex, LCreateDescription); end; function TBaseLinkGridToDataSourceControlManager.AddColumn( const ADescription: TCreateColumnDescription): Integer; var LColumn: Integer; begin LColumn := CreateColumn(ADescription, FCustomGrid); if ADescription.Width <> -1 then FCustomGrid.ColWidths[LColumn] := ADescription.Width else FCustomGrid.ColWidths[LColumn] := GetDefaultColumnWidth; ApplyDescription(ADescription, LColumn); Result := LColumn; end; procedure TBaseLinkGridToDataSourceControlManager.ApplyDescription(const ADescription: TCreateColumnDescription; AColumn: Integer); begin // end; function TBaseLinkGridToDataSourceControlManager.CreateColumn( const ADescription: TCreateColumnDescription; AGrid: TDrawGrid): Integer; begin if AGrid.Tag > 0 then // Use tag to keep track of whether grid has columns or not. Otherwise, no way to tell. if AGrid.Tag > AGrid.FixedCols then AGrid.ColCount := AGrid.Tag + 1; Result := AGrid.Tag; AGrid.Tag := AGrid.Tag + 1; end; function TBaseLinkGridToDataSourceControlManager.DescribeColumn( AIndex: Integer; const ADescription: TCreateColumnDescription): TLinkGridColumnDescription; begin Result := CreateColumnDescription(AIndex, ADescription); end; function TBaseLinkGridToDataSourceControlManager.GetColumnStyles: TArray<string>; begin Result := nil; end; function TBaseLinkGridToDataSourceControlManager.GetDefaultColumnWidth: Integer; begin Result := FDefaultColumnWidth; end; procedure TBaseLinkGridToDataSourceControlManager.SetDefaultColumnWidth( AWidth: Integer); begin FDefaultColumnWidth := AWidth; end; procedure TBaseLinkGridToDataSourceControlManager.EndUpdate; begin // FMX Only //FCustomGrid.EndUpdate; end; function TBaseLinkGridToDataSourceControlManager.CanAddColumn( AColumn: TBaseLinkGridToDataSourceColumn): Boolean; begin Result := True; end; function TBaseLinkGridToDataSourceControlManager.CanAddColumn( ADataSource: TBaseLinkingBindSource; const AMemberName: string): Boolean; begin Result := True; end; procedure TBaseLinkGridToDataSourceControlManager.ClearColumns; begin FCustomGrid.Tag := 0; end; constructor TBaseLinkGridToDataSourceControlManager.Create(ACustomGrid: TDrawGrid); begin FCustomGrid := ACustomGrid; FDefaultColumnWidth := 64; end; { TLinkStringGridToDataSourceColumnFactory } function TLinkStringGridToDataSourceColumnFactory.CreateFactory(AIntf: TGuid; AGrid: TComponent): IInterface; begin Result := TLinkStringGridToDataSourceControlManager.Create(TStringGrid(AGrid)); end; function TLinkStringGridToDataSourceColumnFactory.GridClasses: TArray<TComponentClass>; begin Result := TArray<TComponentClass>.Create(TStringGrid); end; function TLinkStringGridToDataSourceColumnFactory.Supports(AIntf: TGuid; AGrid: TComponent): Boolean; begin Result := False; if AIntf = ILinkGridToDataSourceControlManager then if AGrid.InheritsFrom(TStringGrid) then Result := True; end; { TBaseLinkGridToDataSourceColumnFactory } function TBaseLinkGridToDataSourceColumnFactory.FrameworkExt: string; const sDfm = 'dfm'; begin Result := sDfm; end; function TBaseLinkGridToDataSourceColumnFactory.UsesUnits: TArray<string>; begin Result := TArray<string>.Create('Vcl.Bind.Grid'); // Do not localize end; { TLinkStringGridToDataSourceControlManager } procedure TLinkStringGridToDataSourceControlManager.ApplyDescription( const ADescription: TCreateColumnDescription; AColumn: Integer); begin FStringGrid.Cells[AColumn, 0] := ADescription.Header; end; procedure TLinkStringGridToDataSourceControlManager.ClearColumns; var I: Integer; begin inherited; if csDestroying in FStringGrid.ComponentState then Exit; // Clear data so that data doesn't show up later when add columns for I := 0 to FStringGrid.RowCount - 1 do FStringGrid.Rows[I].Clear; FStringGrid.ColCount := FCustomGrid.FixedCols; FStringGrid.RowCount := FCustomGrid.FixedRows + 1 end; constructor TLinkStringGridToDataSourceControlManager.Create( AStringGrid: TStringGrid); begin FStringGrid := AStringGrid; inherited Create(AStringGrid); end; const // sUnknown = '''(unknown)'''; sBlob = '''(blob)'''; sSelf = 'Self'; sSelectedText = 'SelectedText(Self)'; function TLinkStringGridToDataSourceControlManager.CreateColumnDescription( AIndex: Integer; ADescription: TCreateColumnDescription): TLinkGridColumnDescription; var LColumn: TLinkGridColumnDescription; FPairsList: TList<TLinkGridColumnExpressionPair>; LPair: TLinkGridColumnExpressionPair; LFormatColumnExpressions: TArray<TLinkGridColumnExpressionPair>; LFormatCellExpressions: TArray<TLinkGridColumnExpressionPair>; LParseCellExpressions: TArray<TLinkGridColumnExpressionPair>; LCellExpression: String; LMemberName: string; LMemberType: TScopeMemberType; LMemberGetter: string; LMemberSetter: string; LSelectedText: string; begin LMemberName := ADescription.MemberName; LMemberType := ADescription.MemberType; LMemberGetter := ADescription.MemberGetter; LMemberSetter := ADescription.MemberSetter; FPairsList := TList<TLinkGridColumnExpressionPair>.Create; try FPairsList.Clear; LFormatColumnExpressions := FPairsList.ToArray; if LMemberGetter = '' then LCellExpression := '' else begin case LMemberType of // Support unknown types such as TField of type ftAggregate // mtUnknown: // begin // LCellExpression := sUnknown // end; mtObject, mtBitmap: begin LCellExpression := sBlob end; else LCellExpression := LMemberGetter; Assert(LCellExpression <> ''); end; end; if ADescription.CustomFormat <> '' then LCellExpression := Format(ADescription.CustomFormat, [LCellExpression]); FPairsList.Clear; if LCellExpression <> '' then begin LPair := TLinkGridColumnExpressionPair.Create( Format('Cells[%d]', [AIndex]), LCellExpression, ADescription.CustomFormat <> ''); FPairsList.Add(LPair); LFormatCellExpressions := FPairsList.ToArray; end; if ADescription.ReadOnly then // No parse expression if read only LCellExpression := '' else begin if (LMemberSetter = '') then LCellExpression := '' else begin case LMemberType of // Support unknown types such as TField of type ftAggregate // mtUnknown: // LCellExpression := ''; mtObject, mtBitmap: LCellExpression := ''; else LCellExpression := LMemberSetter; Assert(LCellExpression <> ''); end; end; end; FPairsList.Clear; if LCellExpression <> '' then begin if ADescription.CustomParse <> '' then LSelectedText := Format(ADescription.CustomParse, [sSelectedText]) else LSelectedText := sSelectedText; LPair := TLinkGridColumnExpressionPair.Create( LSelectedText, LCellExpression, ADescription.CustomParse <> ''); // do not localize FPairsList.Add(LPair); end; LParseCellExpressions := FPairsList.ToArray; LColumn := TLinkGridColumnDescription.Create(nil, '', AIndex, '', ADescription.MemberName, ADescription.ColumnStyle, LFormatColumnExpressions, LFormatCellExpressions, LParseCellExpressions); Result := LColumn; finally FPairsList.Free; end; end; initialization RegisterLinkGridToDataSourceColumnFactory([TLinkStringGridToDataSourceColumnFactory]); finalization UnregisterLinkGridToDataSourceColumnFactory([TLinkStringGridToDataSourceColumnFactory]); end.
{ updcrc macro derived from article Copyright (C) 1986 Stephen Satchell. NOTE: First argument must be in range 0 to 255. Second argument is referenced twice. Programmers may incorporate any or all code into their programs, giving proper credit within the source. Publication of the source routines is permitted so long as proper credit is given to Stephen Satchell, Satchell Evaluations and Chuck Forsberg, Omen Technology. } FUNCTION updcrc(cp : BYTE; crc : INTEGER) : INTEGER; CONST { crctab calculated by Mark G. Mendel, Network Systems Corporation } crctab : ARRAY[0..255] OF INTEGER = ( $0000, $1021, $2042, $3063, $4084, $50a5, $60c6, $70e7, $8108, $9129, $a14a, $b16b, $c18c, $d1ad, $e1ce, $f1ef, $1231, $0210, $3273, $2252, $52b5, $4294, $72f7, $62d6, $9339, $8318, $b37b, $a35a, $d3bd, $c39c, $f3ff, $e3de, $2462, $3443, $0420, $1401, $64e6, $74c7, $44a4, $5485, $a56a, $b54b, $8528, $9509, $e5ee, $f5cf, $c5ac, $d58d, $3653, $2672, $1611, $0630, $76d7, $66f6, $5695, $46b4, $b75b, $a77a, $9719, $8738, $f7df, $e7fe, $d79d, $c7bc, $48c4, $58e5, $6886, $78a7, $0840, $1861, $2802, $3823, $c9cc, $d9ed, $e98e, $f9af, $8948, $9969, $a90a, $b92b, $5af5, $4ad4, $7ab7, $6a96, $1a71, $0a50, $3a33, $2a12, $dbfd, $cbdc, $fbbf, $eb9e, $9b79, $8b58, $bb3b, $ab1a, $6ca6, $7c87, $4ce4, $5cc5, $2c22, $3c03, $0c60, $1c41, $edae, $fd8f, $cdec, $ddcd, $ad2a, $bd0b, $8d68, $9d49, $7e97, $6eb6, $5ed5, $4ef4, $3e13, $2e32, $1e51, $0e70, $ff9f, $efbe, $dfdd, $cffc, $bf1b, $af3a, $9f59, $8f78, $9188, $81a9, $b1ca, $a1eb, $d10c, $c12d, $f14e, $e16f, $1080, $00a1, $30c2, $20e3, $5004, $4025, $7046, $6067, $83b9, $9398, $a3fb, $b3da, $c33d, $d31c, $e37f, $f35e, $02b1, $1290, $22f3, $32d2, $4235, $5214, $6277, $7256, $b5ea, $a5cb, $95a8, $8589, $f56e, $e54f, $d52c, $c50d, $34e2, $24c3, $14a0, $0481, $7466, $6447, $5424, $4405, $a7db, $b7fa, $8799, $97b8, $e75f, $f77e, $c71d, $d73c, $26d3, $36f2, $0691, $16b0, $6657, $7676, $4615, $5634, $d94c, $c96d, $f90e, $e92f, $99c8, $89e9, $b98a, $a9ab, $5844, $4865, $7806, $6827, $18c0, $08e1, $3882, $28a3, $cb7d, $db5c, $eb3f, $fb1e, $8bf9, $9bd8, $abbb, $bb9a, $4a75, $5a54, $6a37, $7a16, $0af1, $1ad0, $2ab3, $3a92, $fd2e, $ed0f, $dd6c, $cd4d, $bdaa, $ad8b, $9de8, $8dc9, $7c26, $6c07, $5c64, $4c45, $3ca2, $2c83, $1ce0, $0cc1, $ef1f, $ff3e, $cf5d, $df7c, $af9b, $bfba, $8fd9, $9ff8, $6e17, $7e36, $4e55, $5e74, $2e93, $3eb2, $0ed1, $1ef0 ); BEGIN updcrc := crctab[((crc SHR 8) AND $FF)] XOR (crc SHL 8) XOR cp; END; 
{*******************************************************} { } { Delphi Runtime Library } { SOAP Support } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Soap.SOAPLinked; interface uses System.Classes, System.SysUtils, System.TypInfo, Soap.IntfInfo, Soap.InvokeRegistry, Soap.OPToSOAPDomConv, Soap.Rio, Soap.SOAPAttachIntf, Soap.SOAPPasInv, Soap.WebNode, Soap.WSDLIntf; type TLinkedWebNode = class(TComponent, IWebNode) private FInvoker: TSoapPascalInvoker; IntfInfo: PTypeInfo; FClass: TClass; FMimeBoundary: string; FWebNodeOptions: WebNodeOptions; FMethIntf: TIntfMethEntry; FStaticRequest: TBytes; FStaticResponse: TBytes; protected function GetMimeBoundary: string; procedure SetMimeBoundary(const Value: string); function GetWebNodeOptions: WebNodeOptions; procedure SetWebNodeOptions(Value: WebNodeOptions); function GetResponseStream: TStream; virtual; procedure InvokeImplementation(const Request: TStream; Response: TStream); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; { IWebNode } procedure BeforeExecute(const IntfMetaData: TIntfMetaData; const MethodMetaData: TIntfMethEntry; MethodIndex: Integer; AttachHandler: IMimeAttachmentHandler); virtual; procedure Execute(const DataMsg: String; Resp: TStream); overload; virtual; procedure Execute(const Request: TStream; Response: TStream); overload; virtual; function Execute(const Request: TStream): TStream; overload; published property Invoker: TSoapPascalInvoker read FInvoker; property StaticRequest: TBytes read FStaticRequest write FStaticRequest; property StaticResponse: TBytes read FStaticResponse write FStaticResponse; property MimeBoundary: string read GetMimeBoundary write SetMimeBoundary; end; TLogLinkedWebNode = class(TLinkedWebNode) private FReqFile: string; FRespFile: string; protected function GetResponseStream: TStream; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Execute(const Request: TStream; Response: TStream); override; published property ReqFile: string read FReqFile write FReqFile; property RespFile: string read FRespFile write FRespFile; end; TLinkedRIO = class(TRIO) private FLinkedWebNode: TLinkedWebNode; FDOMConverter: TOPToSoapDomConvert; FDefaultConverter: TOPToSoapDomConvert; function GetDomConverter: TOpToSoapDomConvert; procedure SetDomConverter(Value: TOPToSoapDomConvert); function GetDefaultConverter: TOPToSoapDomConvert; protected function GetResponseStream(BindingType: TWebServiceBindingType): TStream; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public function QueryInterface(const IID: TGUID; out Obj): HResult; override; stdcall; constructor Create(AOwner: TComponent); overload; override; constructor CreateFile(AOwner: TComponent; ReqFile, RespFile: string); overload; destructor Destroy; override; property WebNode: TLinkedWebNode read FLinkedWebNode; published property Converter: TOPToSoapDomConvert read GetDomConverter write SetDOMConverter; end; TLinkedOPToSoapDomConvert = class(TOPToSoapDomConvert) FLinkedRIO: TLinkedRIO; public constructor CreateLinked(AOwner: TComponent; ALinkedRIO: TLinkedRIO); function InvContextToMsg(const IntfMD: TIntfMetaData; MethNum: Integer; Con: TInvContext; Headers: THeaderList): TStream; override; end; function LoadDataFromFile(const FileName: string): TBytes; procedure WriteDataToFile(const FileName: string; const Data: TBytes); implementation uses Soap.OPConvert, Soap.SOAPAttach, Soap.SOAPConst, Soap.WebServExp, Xml.XMLDoc; { TLinkedRIO } constructor TLinkedRIO.Create(AOwner: TComponent); begin FLinkedWebNode := TLinkedWebNode.Create(nil); FLinkedWebNode.IntfInfo := IntfMD.Info; FWebNode := FLinkedWebNode as IWebNode; { Converter } FDOMConverter := GetDefaultConverter; FConverter := FDOMConverter as IOPConvert; inherited; end; constructor TLinkedRIO.CreateFile(AOwner: TComponent; ReqFile, RespFile: string); begin FLinkedWebNode := TLogLinkedWebNode.Create(nil); FLinkedWebNode.IntfInfo := IntfMD.Info; TLogLinkedWebNode(FLinkedWebNode).FReqFile := ReqFile; TLogLinkedWebNode(FLinkedWebNode).FRespFile := RespFile; FWebNode := FLinkedWebNode as IWebNode; { Converter } FDOMConverter := GetDefaultConverter; FConverter := FDOMConverter as IOPConvert; inherited Create(AOwner); end; destructor TLinkedRIO.Destroy; begin FConverter := nil; FWebNode := nil; WebNode.Free; inherited; end; function TLinkedRIO.QueryInterface(const IID: TGUID; out Obj): HResult; begin Result := inherited QueryInterface(IID, Obj); FLinkedWebNode.IntfInfo := IntfMD.Info; end; function TLinkedRIO.GetDefaultConverter: TOPToSoapDomConvert; begin if (FDefaultConverter = nil) then begin FDefaultConverter := TLinkedOPToSoapDomConvert.CreateLinked(Self, Self); FDefaultConverter.Name := 'Converter1'; { do not localize } FDefaultConverter.SetSubComponent(True); end; Result := FDefaultConverter; end; function TLinkedRIO.GetDomConverter: TOpToSoapDomConvert; begin if not Assigned(FDOMConverter) then begin FDOMConverter := GetDefaultConverter; FConverter := FDOMConverter as IOPConvert; end; Result := FDOMConverter; end; procedure TLinkedRIO.SetDomConverter(Value: TOPToSoapDomConvert); begin if Assigned(FDOMConverter) and (FDomConverter.Owner = Self) then begin FConverter := nil; if FDomConverter <> FDefaultConverter then FDomConverter.Free; end; FDomConverter := Value; if Value <> nil then begin FConverter := Value as IOPConvert; FDomConverter.FreeNotification(Self); end; end; function TLinkedRIO.GetResponseStream(BindingType: TWebServiceBindingType): TStream; begin Result := FLinkedWebNode.GetResponseStream; end; procedure TLinkedRIO.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FDomConverter) then begin FConverter := nil; FDomConverter := nil; end; end; { TLinkedWebNode } constructor TLinkedWebNode.Create(AOwner: TComponent); begin inherited; FInvoker := TSoapPascalInvoker.Create(nil); end; destructor TLinkedWebNode.Destroy; begin FInvoker.Free; inherited; end; function TLinkedWebNode.GetMimeBoundary: string; begin Result := FMimeBoundary; end; procedure TlinkedWebNode.SetMimeBoundary(const Value: string); begin FMimeBoundary := Value; end; function TlinkedWebNode.GetWebNodeOptions: WebNodeOptions; begin Result := FWebNodeOptions; end; procedure TLinkedWebNode.InvokeImplementation(const Request: TStream; Response: TStream); var BindingType: TWebServiceBindingType; XMLReq: TMemoryStream; AttachHandler: IMimeAttachmentHandler; begin InvRegistry.GetClassFromIntfInfo(IntfInfo, FClass); if FClass = nil then raise Exception.CreateFmt(SNoClassRegistered, [IntfInfo.Name]); { Check what Input is expecting } BindingType := GetBindingType(FMethIntf, True); AttachHandler := nil; AttachHandler := GetMimeAttachmentHandler(BindingType); try { Create MIME stream if we're MIME bound } if (BindingType = btMIME) then begin XMLReq := TMemoryStream.Create; try FMimeBoundary := SBorlandMimeBoundary; AttachHandler.ProcessMultiPartForm(Request, XMLReq, FMimeBoundary, Nil, FInvoker.Converter.Attachments, FInvoker.Converter.TempDir); FInvoker.Invoke(FClass, IntfInfo, '', XMLReq, Response, BindingType); finally XMLReq.Free; end; end else begin FMimeBoundary := ''; FInvoker.Invoke(FClass, IntfInfo, '', Request, Response, BindingType); end; if FInvoker.Converter.Attachments.Count > 0 then begin AttachHandler.CreateMimeStream(Response, FInvoker.Converter.Attachments); AttachHandler.FinalizeStream; FMimeBoundary := SBorlandMimeBoundary; Response.Position := 0; Response.CopyFrom(AttachHandler.GetMIMEStream, 0); end else FMimeBoundary := ''; finally AttachHandler := nil; end; end; procedure TlinkedWebNode.SetWebNodeOptions(Value: WebNodeOptions); begin FWebNodeOptions := Value; end; function TLinkedWebNode.GetResponseStream: TStream; begin Result := TMemoryStream.Create; end; procedure TLinkedWebNode.BeforeExecute(const IntfMetaData: TIntfMetaData; const MethodMetaData: TIntfMethEntry; MethodIndex: Integer; AttachHandler: IMimeAttachmentHandler); begin { Store away method's descriptor (i.e. RTTI) } FMethIntf := MethodMetaData; end; function TLinkedWebNode.Execute(const Request: TStream): TStream; begin Result := TMemoryStream.Create; Execute(Request, Result); end; procedure TLinkedWebNode.Execute(const Request: TStream; Response: TStream); var AResponse: TBytes; begin if Length(FStaticResponse) = 0 then InvokeImplementation(Request, Response) else begin AResponse := FStaticResponse; Response.Position := 0; Response.Size := Length(AResponse); Response.Write(AResponse, 0, Length(AResponse)); end; end; procedure TLinkedWebNode.Execute(const DataMsg: String; Resp: TStream); var Stream: TMemoryStream; AStr: TBytes; begin AStr := TEncoding.UTF8.GetBytes(DataMsg); Stream := TMemoryStream.Create; try Stream.SetSize(Longint(Length(AStr))); Stream.Write(AStr, 0, Length(AStr)); Execute(Stream, Resp); finally Stream.Free; end; end; { TLogLinkedWebNode } constructor TLogLinkedWebNode.Create(AOwner: TComponent); begin inherited; end; destructor TLogLinkedWebNode.Destroy; begin inherited; end; function TLogLinkedWebNode.GetResponseStream: TStream; var FName: String; begin { By sending a Response stream base on the response file, we get logging automatically!! } FName := RespFile; if FName = '' then FName := FMethIntf.Name + '_resp.xml'; { do not localize } Result := TFileStream.Create(FName, fmCreate); end; procedure TLogLinkedWebNode.Execute(const Request: TStream; Response: TStream); var LogStream: TStream; XMLData : String; StringStream : TStringStream; FName: String; begin { Load request to file } { Default to method name if none specified } FName := ReqFile; if FName = '' then FName := FMethIntf.Name + '.xml'; { do not localize } StringStream := TStringStream.Create(''); try StringStream.CopyFrom( Request, 0 ); XMLData := StringStream.DataString; try // Try to get formatted data but that may fail, // as in the case of attachments XMLData := FormatXMLData(StringStream.DataString); StringStream.Position := 0; StringStream.WriteString(XMLData); except { Ignore failure to format XML data } end; LogStream := TFileStream.Create(FName, fmCreate); try LogStream.CopyFrom(StringStream, 0); finally LogStream.Free; end; finally StringStream.Free; end; { Pass on for processing } inherited; end; { TLinkedOPToSoapDomConvert } constructor TLinkedOPToSoapDomConvert.CreateLinked(AOwner: TComponent; ALinkedRIO: TLinkedRIO); begin FLinkedRIO := ALinkedRIO; inherited Create(AOwner); end; function TLinkedOPToSoapDomConvert.InvContextToMsg(const IntfMD: TIntfMetaData; MethNum: Integer; Con: TInvContext; Headers: THeaderList): TStream; var AStream: TMemoryStream; AResponse: TBytes; begin // SysDebugEnter('TLinkedOPToSoapDomConvert.InvContextToMsg'); AResponse := FLinkedRIO.WebNode.StaticRequest; if Length(AResponse) > 0 then begin AStream := TMemoryStream.Create; AStream.Size := Length(AResponse); AStream.Write(AResponse, 0, Length(AResponse)); Result := AStream; end else begin Result := inherited; end; // SysDebugLeave('TLinkedOPToSoapDomConvert.InvContextToMsg'); end; function LoadDataFromFile(const FileName: string): TBytes; var FileStream: TFileStream; begin FileStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try SetLength(Result, FileStream.Size); FileStream.Read(Result, 0, Length(Result)); finally FileStream.Free; end; end; procedure WriteDataToFile(const FileName: string; const Data: TBytes); var FileStream: TFileStream; begin FileStream := TFileStream.Create(FileName, fmCreate); try FileStream.Write(Data, 0, Length(Data)) finally FileStream.Free; end; end; end.
unit GuestForm; interface uses Global, LTClasses, LTConsts, LTUtils, DAOMember, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TfrGuest = class(TForm) btGuestLogin: TButton; btCancel: TButton; Label1: TLabel; GroupBox1: TGroupBox; edTeacherID: TLabeledEdit; edTeacherPassword: TLabeledEdit; GroupBox2: TGroupBox; edStudentName: TLabeledEdit; edStudentPhone: TLabeledEdit; edStudentGrade: TLabeledEdit; edStudentSchool: TLabeledEdit; btCheck: TButton; procedure btCancelClick(Sender: TObject); procedure btGuestLoginClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btCheckClick(Sender: TObject); private { Private declarations } FConfirmTeacher: Boolean; FDAOMember: TDAOMember; public { Public declarations } end; var frGuest: TfrGuest; function Guest: Boolean; implementation {$R *.dfm} function Guest: Boolean; begin frGuest := TfrGuest.Create(nil); try frGuest.Position := poScreenCenter; frGuest.ShowModal; Result := frGuest.ModalResult = mrOk; finally frGuest.Free; end; end; procedure TfrGuest.btCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TfrGuest.btCheckClick(Sender: TObject); var Confirm: Boolean; begin Confirm := FDAOMember.Validate(Trim(edTeacherID.Text), Trim(edTeacherPassword.Text)); if not(Confirm) then begin Showmessage('강사 아이디 또는 비밀번호가 틀렸습니다'); exit; end; FConfirmTeacher := True; Showmessage('강사인증이 확인 되었습니다'); end; procedure TfrGuest.btGuestLoginClick(Sender: TObject); var Academy: TAcademy; Guest: TGuest; begin if FConfirmTeacher = False then exit; Academy := FDAOMember.Authentication(Trim(edTeacherID.Text), Trim(edTeacherPassword.Text)); try gUser.Academy.Assign(Academy); gUser.UserId := CreateGuestID; gUser.Level := AUTH_GUEST; gUser.TeacherId := edTeacherID.Text; gUser.Name := edStudentName.Text; gUser.Phone := edStudentPhone.Text; gUser.School := edStudentSchool.Text; gUser.Grade := edStudentGrade.Text; FDAOMember.InsertGuest(gUser); ModalResult := mrOk; finally Academy.Free; end; end; procedure TfrGuest.FormCreate(Sender: TObject); begin FDAOMember := TDAOMember.Create; FConfirmTeacher := False; end; procedure TfrGuest.FormDestroy(Sender: TObject); begin FDAOMember.Free; end; end.
{ Test program for basic RTL functionality Copyright (C) 2020- Michael Van Canneyt michael@freepascal.org 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. } program testrtl; {$mode objfpc} uses browserconsole, consoletestrunner, frmrtlrun, simplelinkedlist, // tcstream, tccompstreaming, // tcsyshelpers, // tcgenarrayhelper, // tcstringhelp, // tcgenericdictionary, // tcgenericlist, // tcgenericqueue, tcgenericstack, strutils, sysutils; var Application : TTestRunner; begin SysUtils.HookUncaughtExceptions; Application:=TTestRunner.Create(nil); Application.RunFormClass:=TConsoleRunner; Application.Initialize; Application.Run; // Application.Free; end.
unit testablasunit; interface uses Math, Sysutils, Ap, ablasf, ablas; function TestABLAS(Silent : Boolean):Boolean; procedure RefCMatrixRightTRSM(M : AlglibInteger; N : AlglibInteger; const A : TComplex2DArray; I1 : AlglibInteger; J1 : AlglibInteger; IsUpper : Boolean; IsUnit : Boolean; OpType : AlglibInteger; var X : TComplex2DArray; I2 : AlglibInteger; J2 : AlglibInteger); procedure RefCMatrixLeftTRSM(M : AlglibInteger; N : AlglibInteger; const A : TComplex2DArray; I1 : AlglibInteger; J1 : AlglibInteger; IsUpper : Boolean; IsUnit : Boolean; OpType : AlglibInteger; var X : TComplex2DArray; I2 : AlglibInteger; J2 : AlglibInteger); procedure RefRMatrixRightTRSM(M : AlglibInteger; N : AlglibInteger; const A : TReal2DArray; I1 : AlglibInteger; J1 : AlglibInteger; IsUpper : Boolean; IsUnit : Boolean; OpType : AlglibInteger; var X : TReal2DArray; I2 : AlglibInteger; J2 : AlglibInteger); procedure RefRMatrixLeftTRSM(M : AlglibInteger; N : AlglibInteger; const A : TReal2DArray; I1 : AlglibInteger; J1 : AlglibInteger; IsUpper : Boolean; IsUnit : Boolean; OpType : AlglibInteger; var X : TReal2DArray; I2 : AlglibInteger; J2 : AlglibInteger); function InternalCMatrixTRInverse(var A : TComplex2DArray; N : AlglibInteger; IsUpper : Boolean; IsunitTriangular : Boolean):Boolean; function InternalRMatrixTRInverse(var A : TReal2DArray; N : AlglibInteger; IsUpper : Boolean; IsunitTriangular : Boolean):Boolean; procedure RefCMatrixSYRK(N : AlglibInteger; K : AlglibInteger; Alpha : Double; const A : TComplex2DArray; IA : AlglibInteger; JA : AlglibInteger; OpTypeA : AlglibInteger; Beta : Double; var C : TComplex2DArray; IC : AlglibInteger; JC : AlglibInteger; IsUpper : Boolean); procedure RefRMatrixSYRK(N : AlglibInteger; K : AlglibInteger; Alpha : Double; const A : TReal2DArray; IA : AlglibInteger; JA : AlglibInteger; OpTypeA : AlglibInteger; Beta : Double; var C : TReal2DArray; IC : AlglibInteger; JC : AlglibInteger; IsUpper : Boolean); procedure RefCMatrixGEMM(M : AlglibInteger; N : AlglibInteger; K : AlglibInteger; Alpha : Complex; const A : TComplex2DArray; IA : AlglibInteger; JA : AlglibInteger; OpTypeA : AlglibInteger; const B : TComplex2DArray; IB : AlglibInteger; JB : AlglibInteger; OpTypeB : AlglibInteger; Beta : Complex; var C : TComplex2DArray; IC : AlglibInteger; JC : AlglibInteger); procedure RefRMatrixGEMM(M : AlglibInteger; N : AlglibInteger; K : AlglibInteger; Alpha : Double; const A : TReal2DArray; IA : AlglibInteger; JA : AlglibInteger; OpTypeA : AlglibInteger; const B : TReal2DArray; IB : AlglibInteger; JB : AlglibInteger; OpTypeB : AlglibInteger; Beta : Double; var C : TReal2DArray; IC : AlglibInteger; JC : AlglibInteger); function testablasunit_test_silent():Boolean; function testablasunit_test():Boolean; implementation procedure NaiveMatrixMatrixMultiply(const A : TReal2DArray; AI1 : AlglibInteger; AI2 : AlglibInteger; AJ1 : AlglibInteger; AJ2 : AlglibInteger; TransA : Boolean; const B : TReal2DArray; BI1 : AlglibInteger; BI2 : AlglibInteger; BJ1 : AlglibInteger; BJ2 : AlglibInteger; TransB : Boolean; Alpha : Double; var C : TReal2DArray; CI1 : AlglibInteger; CI2 : AlglibInteger; CJ1 : AlglibInteger; CJ2 : AlglibInteger; Beta : Double);forward; function TestTRSM(MinN : AlglibInteger; MaxN : AlglibInteger):Boolean;forward; function TestSYRK(MinN : AlglibInteger; MaxN : AlglibInteger):Boolean;forward; function TestGEMM(MinN : AlglibInteger; MaxN : AlglibInteger):Boolean;forward; function TestTrans(MinN : AlglibInteger; MaxN : AlglibInteger):Boolean;forward; function TestRANK1(MinN : AlglibInteger; MaxN : AlglibInteger):Boolean;forward; function TestMV(MinN : AlglibInteger; MaxN : AlglibInteger):Boolean;forward; function TestCopy(MinN : AlglibInteger; MaxN : AlglibInteger):Boolean;forward; function TestABLAS(Silent : Boolean):Boolean; var Threshold : Double; TRSMErrors : Boolean; SYRKErrors : Boolean; GEMMErrors : Boolean; TRANSErrors : Boolean; RANK1Errors : Boolean; MVErrors : Boolean; CopyErrors : Boolean; WasErrors : Boolean; RA : TReal2DArray; begin TRSMErrors := False; SYRKErrors := False; GEMMErrors := False; TRANSErrors := False; RANK1Errors := False; MVErrors := False; CopyErrors := False; WasErrors := False; Threshold := 10000*MachineEpsilon; TRSMErrors := TRSMErrors or TestTRSM(1, 3*ABLASBlockSize(RA)+1); SYRKErrors := SYRKErrors or TestSYRK(1, 3*ABLASBlockSize(RA)+1); GEMMErrors := GEMMErrors or TestGEMM(1, 3*ABLASBlockSize(RA)+1); TRANSErrors := TRANSErrors or TestTRANS(1, 3*ABLASBlockSize(RA)+1); RANK1Errors := RANK1Errors or TestRANK1(1, 3*ABLASBlockSize(RA)+1); MVErrors := MVErrors or TestMV(1, 3*ABLASBlockSize(RA)+1); CopyErrors := CopyErrors or TestCopy(1, 3*ABLASBlockSize(RA)+1); // // report // WasErrors := TRSMErrors or SYRKErrors or GEMMErrors or TRANSErrors or RANK1Errors or MVErrors or CopyErrors; if not Silent then begin Write(Format('TESTING ABLAS'#13#10'',[])); Write(Format('* TRSM: ',[])); if TRSMErrors then begin Write(Format('FAILED'#13#10'',[])); end else begin Write(Format('OK'#13#10'',[])); end; Write(Format('* SYRK: ',[])); if SYRKErrors then begin Write(Format('FAILED'#13#10'',[])); end else begin Write(Format('OK'#13#10'',[])); end; Write(Format('* GEMM: ',[])); if GEMMErrors then begin Write(Format('FAILED'#13#10'',[])); end else begin Write(Format('OK'#13#10'',[])); end; Write(Format('* TRANS: ',[])); if TRANSErrors then begin Write(Format('FAILED'#13#10'',[])); end else begin Write(Format('OK'#13#10'',[])); end; Write(Format('* RANK1: ',[])); if RANK1Errors then begin Write(Format('FAILED'#13#10'',[])); end else begin Write(Format('OK'#13#10'',[])); end; Write(Format('* MV: ',[])); if MVErrors then begin Write(Format('FAILED'#13#10'',[])); end else begin Write(Format('OK'#13#10'',[])); end; Write(Format('* COPY: ',[])); if CopyErrors then begin Write(Format('FAILED'#13#10'',[])); end else begin Write(Format('OK'#13#10'',[])); end; if WasErrors then begin Write(Format('TEST FAILED'#13#10'',[])); end else begin Write(Format('TEST PASSED'#13#10'',[])); end; Write(Format(''#13#10''#13#10'',[])); end; Result := not WasErrors; end; (************************************************************************* Reference implementation -- ALGLIB routine -- 15.12.2009 Bochkanov Sergey *************************************************************************) procedure RefCMatrixRightTRSM(M : AlglibInteger; N : AlglibInteger; const A : TComplex2DArray; I1 : AlglibInteger; J1 : AlglibInteger; IsUpper : Boolean; IsUnit : Boolean; OpType : AlglibInteger; var X : TComplex2DArray; I2 : AlglibInteger; J2 : AlglibInteger); var A1 : TComplex2DArray; A2 : TComplex2DArray; TX : TComplex1DArray; I : AlglibInteger; J : AlglibInteger; VC : Complex; RUpper : Boolean; i_ : AlglibInteger; i1_ : AlglibInteger; begin if N*M=0 then begin Exit; end; SetLength(A1, N, N); I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin A1[I,J] := C_Complex(0); Inc(J); end; Inc(I); end; if IsUpper then begin I:=0; while I<=N-1 do begin J:=I; while J<=N-1 do begin A1[I,J] := A[I1+I,J1+J]; Inc(J); end; Inc(I); end; end else begin I:=0; while I<=N-1 do begin J:=0; while J<=I do begin A1[I,J] := A[I1+I,J1+J]; Inc(J); end; Inc(I); end; end; RUpper := IsUpper; if IsUnit then begin I:=0; while I<=N-1 do begin A1[I,I] := C_Complex(1); Inc(I); end; end; SetLength(A2, N, N); if OpType=0 then begin I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin A2[I,J] := A1[I,J]; Inc(J); end; Inc(I); end; end; if OpType=1 then begin I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin A2[I,J] := A1[J,I]; Inc(J); end; Inc(I); end; RUpper := not RUpper; end; if OpType=2 then begin I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin A2[I,J] := Conj(A1[J,I]); Inc(J); end; Inc(I); end; RUpper := not RUpper; end; InternalCMatrixTRInverse(A2, N, RUpper, False); SetLength(TX, N); I:=0; while I<=M-1 do begin i1_ := (J2) - (0); for i_ := 0 to N-1 do begin TX[i_] := X[I2+I,i_+i1_]; end; J:=0; while J<=N-1 do begin VC := C_Complex(0.0); for i_ := 0 to N-1 do begin VC := C_Add(VC,C_Mul(TX[i_],A2[i_,J])); end; X[I2+I,J2+J] := VC; Inc(J); end; Inc(I); end; end; (************************************************************************* Reference implementation -- ALGLIB routine -- 15.12.2009 Bochkanov Sergey *************************************************************************) procedure RefCMatrixLeftTRSM(M : AlglibInteger; N : AlglibInteger; const A : TComplex2DArray; I1 : AlglibInteger; J1 : AlglibInteger; IsUpper : Boolean; IsUnit : Boolean; OpType : AlglibInteger; var X : TComplex2DArray; I2 : AlglibInteger; J2 : AlglibInteger); var A1 : TComplex2DArray; A2 : TComplex2DArray; TX : TComplex1DArray; I : AlglibInteger; J : AlglibInteger; VC : Complex; RUpper : Boolean; i_ : AlglibInteger; i1_ : AlglibInteger; begin if N*M=0 then begin Exit; end; SetLength(A1, M, M); I:=0; while I<=M-1 do begin J:=0; while J<=M-1 do begin A1[I,J] := C_Complex(0); Inc(J); end; Inc(I); end; if IsUpper then begin I:=0; while I<=M-1 do begin J:=I; while J<=M-1 do begin A1[I,J] := A[I1+I,J1+J]; Inc(J); end; Inc(I); end; end else begin I:=0; while I<=M-1 do begin J:=0; while J<=I do begin A1[I,J] := A[I1+I,J1+J]; Inc(J); end; Inc(I); end; end; RUpper := IsUpper; if IsUnit then begin I:=0; while I<=M-1 do begin A1[I,I] := C_Complex(1); Inc(I); end; end; SetLength(A2, M, M); if OpType=0 then begin I:=0; while I<=M-1 do begin J:=0; while J<=M-1 do begin A2[I,J] := A1[I,J]; Inc(J); end; Inc(I); end; end; if OpType=1 then begin I:=0; while I<=M-1 do begin J:=0; while J<=M-1 do begin A2[I,J] := A1[J,I]; Inc(J); end; Inc(I); end; RUpper := not RUpper; end; if OpType=2 then begin I:=0; while I<=M-1 do begin J:=0; while J<=M-1 do begin A2[I,J] := Conj(A1[J,I]); Inc(J); end; Inc(I); end; RUpper := not RUpper; end; InternalCMatrixTRInverse(A2, M, RUpper, False); SetLength(TX, M); J:=0; while J<=N-1 do begin i1_ := (I2) - (0); for i_ := 0 to M-1 do begin TX[i_] := X[i_+i1_,J2+J]; end; I:=0; while I<=M-1 do begin VC := C_Complex(0.0); for i_ := 0 to M-1 do begin VC := C_Add(VC,C_Mul(A2[I,i_],TX[i_])); end; X[I2+I,J2+J] := VC; Inc(I); end; Inc(J); end; end; (************************************************************************* Reference implementation -- ALGLIB routine -- 15.12.2009 Bochkanov Sergey *************************************************************************) procedure RefRMatrixRightTRSM(M : AlglibInteger; N : AlglibInteger; const A : TReal2DArray; I1 : AlglibInteger; J1 : AlglibInteger; IsUpper : Boolean; IsUnit : Boolean; OpType : AlglibInteger; var X : TReal2DArray; I2 : AlglibInteger; J2 : AlglibInteger); var A1 : TReal2DArray; A2 : TReal2DArray; TX : TReal1DArray; I : AlglibInteger; J : AlglibInteger; VR : Double; RUpper : Boolean; i_ : AlglibInteger; begin if N*M=0 then begin Exit; end; SetLength(A1, N, N); I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin A1[I,J] := 0; Inc(J); end; Inc(I); end; if IsUpper then begin I:=0; while I<=N-1 do begin J:=I; while J<=N-1 do begin A1[I,J] := A[I1+I,J1+J]; Inc(J); end; Inc(I); end; end else begin I:=0; while I<=N-1 do begin J:=0; while J<=I do begin A1[I,J] := A[I1+I,J1+J]; Inc(J); end; Inc(I); end; end; RUpper := IsUpper; if IsUnit then begin I:=0; while I<=N-1 do begin A1[I,I] := 1; Inc(I); end; end; SetLength(A2, N, N); if OpType=0 then begin I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin A2[I,J] := A1[I,J]; Inc(J); end; Inc(I); end; end; if OpType=1 then begin I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin A2[I,J] := A1[J,I]; Inc(J); end; Inc(I); end; RUpper := not RUpper; end; InternalRMatrixTRInverse(A2, N, RUpper, False); SetLength(TX, N); I:=0; while I<=M-1 do begin APVMove(@TX[0], 0, N-1, @X[I2+I][0], J2, J2+N-1); J:=0; while J<=N-1 do begin VR := 0.0; for i_ := 0 to N-1 do begin VR := VR + TX[i_]*A2[i_,J]; end; X[I2+I,J2+J] := VR; Inc(J); end; Inc(I); end; end; (************************************************************************* Reference implementation -- ALGLIB routine -- 15.12.2009 Bochkanov Sergey *************************************************************************) procedure RefRMatrixLeftTRSM(M : AlglibInteger; N : AlglibInteger; const A : TReal2DArray; I1 : AlglibInteger; J1 : AlglibInteger; IsUpper : Boolean; IsUnit : Boolean; OpType : AlglibInteger; var X : TReal2DArray; I2 : AlglibInteger; J2 : AlglibInteger); var A1 : TReal2DArray; A2 : TReal2DArray; TX : TReal1DArray; I : AlglibInteger; J : AlglibInteger; VR : Double; RUpper : Boolean; i_ : AlglibInteger; i1_ : AlglibInteger; begin if N*M=0 then begin Exit; end; SetLength(A1, M, M); I:=0; while I<=M-1 do begin J:=0; while J<=M-1 do begin A1[I,J] := 0; Inc(J); end; Inc(I); end; if IsUpper then begin I:=0; while I<=M-1 do begin J:=I; while J<=M-1 do begin A1[I,J] := A[I1+I,J1+J]; Inc(J); end; Inc(I); end; end else begin I:=0; while I<=M-1 do begin J:=0; while J<=I do begin A1[I,J] := A[I1+I,J1+J]; Inc(J); end; Inc(I); end; end; RUpper := IsUpper; if IsUnit then begin I:=0; while I<=M-1 do begin A1[I,I] := 1; Inc(I); end; end; SetLength(A2, M, M); if OpType=0 then begin I:=0; while I<=M-1 do begin J:=0; while J<=M-1 do begin A2[I,J] := A1[I,J]; Inc(J); end; Inc(I); end; end; if OpType=1 then begin I:=0; while I<=M-1 do begin J:=0; while J<=M-1 do begin A2[I,J] := A1[J,I]; Inc(J); end; Inc(I); end; RUpper := not RUpper; end; InternalRMatrixTRInverse(A2, M, RUpper, False); SetLength(TX, M); J:=0; while J<=N-1 do begin i1_ := (I2) - (0); for i_ := 0 to M-1 do begin TX[i_] := X[i_+i1_,J2+J]; end; I:=0; while I<=M-1 do begin VR := APVDotProduct(@A2[I][0], 0, M-1, @TX[0], 0, M-1); X[I2+I,J2+J] := VR; Inc(I); end; Inc(J); end; end; (************************************************************************* Internal subroutine. Triangular matrix inversion -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 *************************************************************************) function InternalCMatrixTRInverse(var A : TComplex2DArray; N : AlglibInteger; IsUpper : Boolean; IsunitTriangular : Boolean):Boolean; var NOunit : Boolean; I : AlglibInteger; J : AlglibInteger; V : Complex; AJJ : Complex; T : TComplex1DArray; i_ : AlglibInteger; begin Result := True; SetLength(T, N-1+1); // // Test the input parameters. // NOunit := not IsunitTriangular; if IsUpper then begin // // Compute inverse of upper triangular matrix. // J:=0; while J<=N-1 do begin if NOunit then begin if C_EqualR(A[J,J],0) then begin Result := False; Exit; end; A[J,J] := C_RDiv(1,A[J,J]); AJJ := C_Opposite(A[J,J]); end else begin AJJ := C_Complex(-1); end; // // Compute elements 1:j-1 of j-th column. // if J>0 then begin for i_ := 0 to J-1 do begin T[i_] := A[i_,J]; end; I:=0; while I<=J-1 do begin if I+1<J then begin V := C_Complex(0.0); for i_ := I+1 to J-1 do begin V := C_Add(V,C_Mul(A[I,i_],T[i_])); end; end else begin V := C_Complex(0); end; if NOunit then begin A[I,J] := C_Add(V,C_Mul(A[I,I],T[I])); end else begin A[I,J] := C_Add(V,T[I]); end; Inc(I); end; for i_ := 0 to J-1 do begin A[i_,J] := C_Mul(AJJ, A[i_,J]); end; end; Inc(J); end; end else begin // // Compute inverse of lower triangular matrix. // J:=N-1; while J>=0 do begin if NOunit then begin if C_EqualR(A[J,J],0) then begin Result := False; Exit; end; A[J,J] := C_RDiv(1,A[J,J]); AJJ := C_Opposite(A[J,J]); end else begin AJJ := C_Complex(-1); end; if J+1<N then begin // // Compute elements j+1:n of j-th column. // for i_ := J+1 to N-1 do begin T[i_] := A[i_,J]; end; I:=J+1; while I<=N-1 do begin if I>J+1 then begin V := C_Complex(0.0); for i_ := J+1 to I-1 do begin V := C_Add(V,C_Mul(A[I,i_],T[i_])); end; end else begin V := C_Complex(0); end; if NOunit then begin A[I,J] := C_Add(V,C_Mul(A[I,I],T[I])); end else begin A[I,J] := C_Add(V,T[I]); end; Inc(I); end; for i_ := J+1 to N-1 do begin A[i_,J] := C_Mul(AJJ, A[i_,J]); end; end; Dec(J); end; end; end; (************************************************************************* Internal subroutine. Triangular matrix inversion -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 *************************************************************************) function InternalRMatrixTRInverse(var A : TReal2DArray; N : AlglibInteger; IsUpper : Boolean; IsunitTriangular : Boolean):Boolean; var NOunit : Boolean; I : AlglibInteger; J : AlglibInteger; V : Double; AJJ : Double; T : TReal1DArray; i_ : AlglibInteger; begin Result := True; SetLength(T, N-1+1); // // Test the input parameters. // NOunit := not IsunitTriangular; if IsUpper then begin // // Compute inverse of upper triangular matrix. // J:=0; while J<=N-1 do begin if NOunit then begin if AP_FP_Eq(A[J,J],0) then begin Result := False; Exit; end; A[J,J] := 1/A[J,J]; AJJ := -A[J,J]; end else begin AJJ := -1; end; // // Compute elements 1:j-1 of j-th column. // if J>0 then begin for i_ := 0 to J-1 do begin T[i_] := A[i_,J]; end; I:=0; while I<=J-1 do begin if I<J-1 then begin V := APVDotProduct(@A[I][0], I+1, J-1, @T[0], I+1, J-1); end else begin V := 0; end; if NOunit then begin A[I,J] := V+A[I,I]*T[I]; end else begin A[I,J] := V+T[I]; end; Inc(I); end; for i_ := 0 to J-1 do begin A[i_,J] := AJJ*A[i_,J]; end; end; Inc(J); end; end else begin // // Compute inverse of lower triangular matrix. // J:=N-1; while J>=0 do begin if NOunit then begin if AP_FP_Eq(A[J,J],0) then begin Result := False; Exit; end; A[J,J] := 1/A[J,J]; AJJ := -A[J,J]; end else begin AJJ := -1; end; if J<N-1 then begin // // Compute elements j+1:n of j-th column. // for i_ := J+1 to N-1 do begin T[i_] := A[i_,J]; end; I:=J+1; while I<=N-1 do begin if I>J+1 then begin V := APVDotProduct(@A[I][0], J+1, I-1, @T[0], J+1, I-1); end else begin V := 0; end; if NOunit then begin A[I,J] := V+A[I,I]*T[I]; end else begin A[I,J] := V+T[I]; end; Inc(I); end; for i_ := J+1 to N-1 do begin A[i_,J] := AJJ*A[i_,J]; end; end; Dec(J); end; end; end; (************************************************************************* Reference SYRK subroutine. -- ALGLIB routine -- 16.12.2009 Bochkanov Sergey *************************************************************************) procedure RefCMatrixSYRK(N : AlglibInteger; K : AlglibInteger; Alpha : Double; const A : TComplex2DArray; IA : AlglibInteger; JA : AlglibInteger; OpTypeA : AlglibInteger; Beta : Double; var C : TComplex2DArray; IC : AlglibInteger; JC : AlglibInteger; IsUpper : Boolean); var AE : TComplex2DArray; I : AlglibInteger; J : AlglibInteger; VC : Complex; i_ : AlglibInteger; begin I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin if IsUpper and (J>=I) or not IsUpper and (J<=I) then begin if AP_FP_Eq(Beta,0) then begin C[I+IC,J+JC] := C_Complex(0); end else begin C[I+IC,J+JC] := C_MulR(C[I+IC,J+JC],Beta); end; end; Inc(J); end; Inc(I); end; if AP_FP_Eq(Alpha,0) then begin Exit; end; if N*K>0 then begin SetLength(AE, N, K); end; I:=0; while I<=N-1 do begin J:=0; while J<=K-1 do begin if OpTypeA=0 then begin AE[I,J] := A[IA+I,JA+J]; end; if OpTypeA=2 then begin AE[I,J] := Conj(A[IA+J,JA+I]); end; Inc(J); end; Inc(I); end; I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin VC := C_Complex(0); if K>0 then begin VC := C_Complex(0.0); for i_ := 0 to K-1 do begin VC := C_Add(VC,C_Mul(AE[I,i_],Conj(AE[J,i_]))); end; end; VC := C_MulR(VC,Alpha); if IsUpper and (J>=I) then begin C[IC+I,JC+J] := C_Add(VC,C[IC+I,JC+J]); end; if not IsUpper and (J<=I) then begin C[IC+I,JC+J] := C_Add(VC,C[IC+I,JC+J]); end; Inc(J); end; Inc(I); end; end; (************************************************************************* Reference SYRK subroutine. -- ALGLIB routine -- 16.12.2009 Bochkanov Sergey *************************************************************************) procedure RefRMatrixSYRK(N : AlglibInteger; K : AlglibInteger; Alpha : Double; const A : TReal2DArray; IA : AlglibInteger; JA : AlglibInteger; OpTypeA : AlglibInteger; Beta : Double; var C : TReal2DArray; IC : AlglibInteger; JC : AlglibInteger; IsUpper : Boolean); var AE : TReal2DArray; I : AlglibInteger; J : AlglibInteger; VR : Double; begin I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin if IsUpper and (J>=I) or not IsUpper and (J<=I) then begin if AP_FP_Eq(Beta,0) then begin C[I+IC,J+JC] := 0; end else begin C[I+IC,J+JC] := C[I+IC,J+JC]*Beta; end; end; Inc(J); end; Inc(I); end; if AP_FP_Eq(Alpha,0) then begin Exit; end; if N*K>0 then begin SetLength(AE, N, K); end; I:=0; while I<=N-1 do begin J:=0; while J<=K-1 do begin if OpTypeA=0 then begin AE[I,J] := A[IA+I,JA+J]; end; if OpTypeA=1 then begin AE[I,J] := A[IA+J,JA+I]; end; Inc(J); end; Inc(I); end; I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin VR := 0; if K>0 then begin VR := APVDotProduct(@AE[I][0], 0, K-1, @AE[J][0], 0, K-1); end; VR := Alpha*VR; if IsUpper and (J>=I) then begin C[IC+I,JC+J] := VR+C[IC+I,JC+J]; end; if not IsUpper and (J<=I) then begin C[IC+I,JC+J] := VR+C[IC+I,JC+J]; end; Inc(J); end; Inc(I); end; end; (************************************************************************* Reference GEMM, ALGLIB subroutine *************************************************************************) procedure RefCMatrixGEMM(M : AlglibInteger; N : AlglibInteger; K : AlglibInteger; Alpha : Complex; const A : TComplex2DArray; IA : AlglibInteger; JA : AlglibInteger; OpTypeA : AlglibInteger; const B : TComplex2DArray; IB : AlglibInteger; JB : AlglibInteger; OpTypeB : AlglibInteger; Beta : Complex; var C : TComplex2DArray; IC : AlglibInteger; JC : AlglibInteger); var AE : TComplex2DArray; BE : TComplex2DArray; I : AlglibInteger; J : AlglibInteger; VC : Complex; i_ : AlglibInteger; begin SetLength(AE, M, K); I:=0; while I<=M-1 do begin J:=0; while J<=K-1 do begin if OpTypeA=0 then begin AE[I,J] := A[IA+I,JA+J]; end; if OpTypeA=1 then begin AE[I,J] := A[IA+J,JA+I]; end; if OpTypeA=2 then begin AE[I,J] := Conj(A[IA+J,JA+I]); end; Inc(J); end; Inc(I); end; SetLength(BE, K, N); I:=0; while I<=K-1 do begin J:=0; while J<=N-1 do begin if OpTypeB=0 then begin BE[I,J] := B[IB+I,JB+J]; end; if OpTypeB=1 then begin BE[I,J] := B[IB+J,JB+I]; end; if OpTypeB=2 then begin BE[I,J] := Conj(B[IB+J,JB+I]); end; Inc(J); end; Inc(I); end; I:=0; while I<=M-1 do begin J:=0; while J<=N-1 do begin VC := C_Complex(0.0); for i_ := 0 to K-1 do begin VC := C_Add(VC,C_Mul(AE[I,i_],BE[i_,J])); end; VC := C_Mul(Alpha,VC); if C_NotEqualR(Beta,0) then begin VC := C_Add(VC,C_Mul(Beta,C[IC+I,JC+J])); end; C[IC+I,JC+J] := VC; Inc(J); end; Inc(I); end; end; (************************************************************************* Reference GEMM, ALGLIB subroutine *************************************************************************) procedure RefRMatrixGEMM(M : AlglibInteger; N : AlglibInteger; K : AlglibInteger; Alpha : Double; const A : TReal2DArray; IA : AlglibInteger; JA : AlglibInteger; OpTypeA : AlglibInteger; const B : TReal2DArray; IB : AlglibInteger; JB : AlglibInteger; OpTypeB : AlglibInteger; Beta : Double; var C : TReal2DArray; IC : AlglibInteger; JC : AlglibInteger); var AE : TReal2DArray; BE : TReal2DArray; I : AlglibInteger; J : AlglibInteger; VC : Double; i_ : AlglibInteger; begin SetLength(AE, M, K); I:=0; while I<=M-1 do begin J:=0; while J<=K-1 do begin if OpTypeA=0 then begin AE[I,J] := A[IA+I,JA+J]; end; if OpTypeA=1 then begin AE[I,J] := A[IA+J,JA+I]; end; Inc(J); end; Inc(I); end; SetLength(BE, K, N); I:=0; while I<=K-1 do begin J:=0; while J<=N-1 do begin if OpTypeB=0 then begin BE[I,J] := B[IB+I,JB+J]; end; if OpTypeB=1 then begin BE[I,J] := B[IB+J,JB+I]; end; Inc(J); end; Inc(I); end; I:=0; while I<=M-1 do begin J:=0; while J<=N-1 do begin VC := 0.0; for i_ := 0 to K-1 do begin VC := VC + AE[I,i_]*BE[i_,J]; end; VC := Alpha*VC; if AP_FP_Neq(Beta,0) then begin VC := VC+Beta*C[IC+I,JC+J]; end; C[IC+I,JC+J] := VC; Inc(J); end; Inc(I); end; end; procedure NaiveMatrixMatrixMultiply(const A : TReal2DArray; AI1 : AlglibInteger; AI2 : AlglibInteger; AJ1 : AlglibInteger; AJ2 : AlglibInteger; TransA : Boolean; const B : TReal2DArray; BI1 : AlglibInteger; BI2 : AlglibInteger; BJ1 : AlglibInteger; BJ2 : AlglibInteger; TransB : Boolean; Alpha : Double; var C : TReal2DArray; CI1 : AlglibInteger; CI2 : AlglibInteger; CJ1 : AlglibInteger; CJ2 : AlglibInteger; Beta : Double); var ARows : AlglibInteger; ACols : AlglibInteger; BRows : AlglibInteger; BCols : AlglibInteger; I : AlglibInteger; J : AlglibInteger; K : AlglibInteger; L : AlglibInteger; R : AlglibInteger; V : Double; X1 : TReal1DArray; X2 : TReal1DArray; i_ : AlglibInteger; i1_ : AlglibInteger; begin // // Setup // if not TransA then begin ARows := AI2-AI1+1; ACols := AJ2-AJ1+1; end else begin ARows := AJ2-AJ1+1; ACols := AI2-AI1+1; end; if not TransB then begin BRows := BI2-BI1+1; BCols := BJ2-BJ1+1; end else begin BRows := BJ2-BJ1+1; BCols := BI2-BI1+1; end; Assert(ACols=BRows, 'NaiveMatrixMatrixMultiply: incorrect matrix sizes!'); if (ARows<=0) or (ACols<=0) or (BRows<=0) or (BCols<=0) then begin Exit; end; L := ARows; R := BCols; K := ACols; SetLength(X1, K+1); SetLength(X2, K+1); I:=1; while I<=L do begin J:=1; while J<=R do begin if not TransA then begin if not TransB then begin i1_ := (AJ1)-(BI1); V := 0.0; for i_ := BI1 to BI2 do begin V := V + B[i_,BJ1+J-1]*A[AI1+I-1,i_+i1_]; end; end else begin V := APVDotProduct(@B[BI1+J-1][0], BJ1, BJ2, @A[AI1+I-1][0], AJ1, AJ2); end; end else begin if not TransB then begin i1_ := (AI1)-(BI1); V := 0.0; for i_ := BI1 to BI2 do begin V := V + B[i_,BJ1+J-1]*A[i_+i1_,AJ1+I-1]; end; end else begin i1_ := (AI1)-(BJ1); V := 0.0; for i_ := BJ1 to BJ2 do begin V := V + B[BI1+J-1,i_]*A[i_+i1_,AJ1+I-1]; end; end; end; if AP_FP_Eq(Beta,0) then begin C[CI1+I-1,CJ1+J-1] := Alpha*V; end else begin C[CI1+I-1,CJ1+J-1] := Beta*C[CI1+I-1,CJ1+J-1]+Alpha*V; end; Inc(J); end; Inc(I); end; end; (************************************************************************* ?Matrix????TRSM tests Returns False for passed test, True - for failed *************************************************************************) function TestTRSM(MinN : AlglibInteger; MaxN : AlglibInteger):Boolean; var N : AlglibInteger; M : AlglibInteger; MX : AlglibInteger; I : AlglibInteger; J : AlglibInteger; OpType : AlglibInteger; UpperType : AlglibInteger; UnitType : AlglibInteger; XOffsI : AlglibInteger; XOffsJ : AlglibInteger; AOffsIType : AlglibInteger; AOffsJType : AlglibInteger; AOffsI : AlglibInteger; AOffsJ : AlglibInteger; RefRA : TReal2DArray; RefRXL : TReal2DArray; RefRXR : TReal2DArray; RefCA : TComplex2DArray; RefCXL : TComplex2DArray; RefCXR : TComplex2DArray; RA : TReal2DArray; CA : TComplex2DArray; RXR1 : TReal2DArray; RXL1 : TReal2DArray; CXR1 : TComplex2DArray; CXL1 : TComplex2DArray; RXR2 : TReal2DArray; RXL2 : TReal2DArray; CXR2 : TComplex2DArray; CXL2 : TComplex2DArray; Threshold : Double; begin Threshold := AP_Sqr(MaxN)*100*MachineEpsilon; Result := False; MX:=MinN; while MX<=MaxN do begin // // Select random M/N in [1,MX] such that max(M,N)=MX // M := 1+RandomInteger(MX); N := 1+RandomInteger(MX); if AP_FP_Greater(RandomReal,0.5) then begin M := MX; end else begin N := MX; end; // // Initialize RefRA/RefCA by random matrices whose upper // and lower triangle submatrices are non-degenerate // well-conditioned matrices. // // Matrix size is 2Mx2M (four copies of same MxM matrix // to test different offsets) // SetLength(RefRA, 2*M, 2*M); I:=0; while I<=M-1 do begin J:=0; while J<=M-1 do begin RefRA[I,J] := 0.2*RandomReal-0.1; Inc(J); end; Inc(I); end; I:=0; while I<=M-1 do begin RefRA[I,I] := (2*RandomInteger(1)-1)*(2*M+RandomReal); Inc(I); end; I:=0; while I<=M-1 do begin J:=0; while J<=M-1 do begin RefRA[I+M,J] := RefRA[I,J]; RefRA[I,J+M] := RefRA[I,J]; RefRA[I+M,J+M] := RefRA[I,J]; Inc(J); end; Inc(I); end; SetLength(RefCA, 2*M, 2*M); I:=0; while I<=M-1 do begin J:=0; while J<=M-1 do begin RefCA[I,J].X := 0.2*RandomReal-0.1; RefCA[I,J].Y := 0.2*RandomReal-0.1; Inc(J); end; Inc(I); end; I:=0; while I<=M-1 do begin RefCA[I,I].X := (2*RandomInteger(2)-1)*(2*M+RandomReal); RefCA[I,I].Y := (2*RandomInteger(2)-1)*(2*M+RandomReal); Inc(I); end; I:=0; while I<=M-1 do begin J:=0; while J<=M-1 do begin RefCA[I+M,J] := RefCA[I,J]; RefCA[I,J+M] := RefCA[I,J]; RefCA[I+M,J+M] := RefCA[I,J]; Inc(J); end; Inc(I); end; // // Generate random XL/XR. // // XR is NxM matrix (matrix for 'Right' subroutines) // XL is MxN matrix (matrix for 'Left' subroutines) // SetLength(RefRXR, N, M); I:=0; while I<=N-1 do begin J:=0; while J<=M-1 do begin RefRXR[I,J] := 2*RandomReal-1; Inc(J); end; Inc(I); end; SetLength(RefRXL, M, N); I:=0; while I<=M-1 do begin J:=0; while J<=N-1 do begin RefRXL[I,J] := 2*RandomReal-1; Inc(J); end; Inc(I); end; SetLength(RefCXR, N, M); I:=0; while I<=N-1 do begin J:=0; while J<=M-1 do begin RefCXR[I,J].X := 2*RandomReal-1; RefCXR[I,J].Y := 2*RandomReal-1; Inc(J); end; Inc(I); end; SetLength(RefCXL, M, N); I:=0; while I<=M-1 do begin J:=0; while J<=N-1 do begin RefCXL[I,J].X := 2*RandomReal-1; RefCXL[I,J].Y := 2*RandomReal-1; Inc(J); end; Inc(I); end; // // test different types of operations, offsets, and so on... // // to avoid unnecessary slowdown we don't test ALL possible // combinations of operation types. We just generate one random // set of parameters and test it. // SetLength(RA, 2*M, 2*M); SetLength(RXR1, N, M); SetLength(RXR2, N, M); SetLength(RXL1, M, N); SetLength(RXL2, M, N); SetLength(CA, 2*M, 2*M); SetLength(CXR1, N, M); SetLength(CXR2, N, M); SetLength(CXL1, M, N); SetLength(CXL2, M, N); OpType := RandomInteger(3); UpperType := RandomInteger(2); UnitType := RandomInteger(2); XOffsI := RandomInteger(2); XOffsJ := RandomInteger(2); AOffsIType := RandomInteger(2); AOffsJType := RandomInteger(2); AOffsI := M*AOffsIType; AOffsJ := M*AOffsJType; // // copy A, XR, XL (fill unused parts with random garbage) // I:=0; while I<=2*M-1 do begin J:=0; while J<=2*M-1 do begin if (I>=AOffsI) and (I<AOffsI+M) and (J>=AOffsJ) and (J<AOffsJ+M) then begin CA[I,J] := RefCA[I,J]; RA[I,J] := RefRA[I,J]; end else begin CA[I,J] := C_Complex(RandomReal); RA[I,J] := RandomReal; end; Inc(J); end; Inc(I); end; I:=0; while I<=N-1 do begin J:=0; while J<=M-1 do begin if (I>=XOffsI) and (J>=XOffsJ) then begin CXR1[I,J] := RefCXR[I,J]; CXR2[I,J] := RefCXR[I,J]; RXR1[I,J] := RefRXR[I,J]; RXR2[I,J] := RefRXR[I,J]; end else begin CXR1[I,J] := C_Complex(RandomReal); CXR2[I,J] := CXR1[I,J]; RXR1[I,J] := RandomReal; RXR2[I,J] := RXR1[I,J]; end; Inc(J); end; Inc(I); end; I:=0; while I<=M-1 do begin J:=0; while J<=N-1 do begin if (I>=XOffsI) and (J>=XOffsJ) then begin CXL1[I,J] := RefCXL[I,J]; CXL2[I,J] := RefCXL[I,J]; RXL1[I,J] := RefRXL[I,J]; RXL2[I,J] := RefRXL[I,J]; end else begin CXL1[I,J] := C_Complex(RandomReal); CXL2[I,J] := CXL1[I,J]; RXL1[I,J] := RandomReal; RXL2[I,J] := RXL1[I,J]; end; Inc(J); end; Inc(I); end; // // Test CXR // CMatrixRightTRSM(N-XOffsI, M-XOffsJ, CA, AOffsI, AOffsJ, UpperType=0, UnitType=0, OpType, CXR1, XOffsI, XOffsJ); RefCMatrixRightTRSM(N-XOffsI, M-XOffsJ, CA, AOffsI, AOffsJ, UpperType=0, UnitType=0, OpType, CXR2, XOffsI, XOffsJ); I:=0; while I<=N-1 do begin J:=0; while J<=M-1 do begin Result := Result or AP_FP_Greater(AbsComplex(C_Sub(CXR1[I,J],CXR2[I,J])),Threshold); Inc(J); end; Inc(I); end; // // Test CXL // CMatrixLeftTRSM(M-XOffsI, N-XOffsJ, CA, AOffsI, AOffsJ, UpperType=0, UnitType=0, OpType, CXL1, XOffsI, XOffsJ); RefCMatrixLeftTRSM(M-XOffsI, N-XOffsJ, CA, AOffsI, AOffsJ, UpperType=0, UnitType=0, OpType, CXL2, XOffsI, XOffsJ); I:=0; while I<=M-1 do begin J:=0; while J<=N-1 do begin Result := Result or AP_FP_Greater(AbsComplex(C_Sub(CXL1[I,J],CXL2[I,J])),Threshold); Inc(J); end; Inc(I); end; if OpType<2 then begin // // Test RXR // RMatrixRightTRSM(N-XOffsI, M-XOffsJ, RA, AOffsI, AOffsJ, UpperType=0, UnitType=0, OpType, RXR1, XOffsI, XOffsJ); RefRMatrixRightTRSM(N-XOffsI, M-XOffsJ, RA, AOffsI, AOffsJ, UpperType=0, UnitType=0, OpType, RXR2, XOffsI, XOffsJ); I:=0; while I<=N-1 do begin J:=0; while J<=M-1 do begin Result := Result or AP_FP_Greater(AbsReal(RXR1[I,J]-RXR2[I,J]),Threshold); Inc(J); end; Inc(I); end; // // Test RXL // RMatrixLeftTRSM(M-XOffsI, N-XOffsJ, RA, AOffsI, AOffsJ, UpperType=0, UnitType=0, OpType, RXL1, XOffsI, XOffsJ); RefRMatrixLeftTRSM(M-XOffsI, N-XOffsJ, RA, AOffsI, AOffsJ, UpperType=0, UnitType=0, OpType, RXL2, XOffsI, XOffsJ); I:=0; while I<=M-1 do begin J:=0; while J<=N-1 do begin Result := Result or AP_FP_Greater(AbsReal(RXL1[I,J]-RXL2[I,J]),Threshold); Inc(J); end; Inc(I); end; end; Inc(MX); end; end; (************************************************************************* SYRK tests Returns False for passed test, True - for failed *************************************************************************) function TestSYRK(MinN : AlglibInteger; MaxN : AlglibInteger):Boolean; var N : AlglibInteger; K : AlglibInteger; MX : AlglibInteger; I : AlglibInteger; J : AlglibInteger; UpperType : AlglibInteger; XOffsI : AlglibInteger; XOffsJ : AlglibInteger; AOffsIType : AlglibInteger; AOffsJType : AlglibInteger; AOffsI : AlglibInteger; AOffsJ : AlglibInteger; AlphaType : AlglibInteger; BetaType : AlglibInteger; RefRA : TReal2DArray; RefRC : TReal2DArray; RefCA : TComplex2DArray; RefCC : TComplex2DArray; Alpha : Double; Beta : Double; RA1 : TReal2DArray; RA2 : TReal2DArray; CA1 : TComplex2DArray; CA2 : TComplex2DArray; RC : TReal2DArray; RCT : TReal2DArray; CC : TComplex2DArray; CCT : TComplex2DArray; Threshold : Double; begin Threshold := MaxN*100*MachineEpsilon; Result := False; MX:=MinN; while MX<=MaxN do begin // // Select random M/N in [1,MX] such that max(M,N)=MX // K := 1+RandomInteger(MX); N := 1+RandomInteger(MX); if AP_FP_Greater(RandomReal,0.5) then begin K := MX; end else begin N := MX; end; // // Initialize RefRA/RefCA by random Hermitian matrices, // RefRC/RefCC by random matrices // // RA/CA size is 2Nx2N (four copies of same NxN matrix // to test different offsets) // SetLength(RefRA, 2*N, 2*N); SetLength(RefCA, 2*N, 2*N); I:=0; while I<=N-1 do begin RefRA[I,I] := 2*RandomReal-1; RefCA[I,I] := C_Complex(2*RandomReal-1); J:=I+1; while J<=N-1 do begin RefRA[I,J] := 2*RandomReal-1; RefCA[I,J].X := 2*RandomReal-1; RefCA[I,J].Y := 2*RandomReal-1; RefRA[J,I] := RefRA[I,J]; RefCA[J,I] := Conj(RefCA[I,J]); Inc(J); end; Inc(I); end; I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin RefRA[I+N,J] := RefRA[I,J]; RefRA[I,J+N] := RefRA[I,J]; RefRA[I+N,J+N] := RefRA[I,J]; RefCA[I+N,J] := RefCA[I,J]; RefCA[I,J+N] := RefCA[I,J]; RefCA[I+N,J+N] := RefCA[I,J]; Inc(J); end; Inc(I); end; SetLength(RefRC, N, K); SetLength(RefCC, N, K); I:=0; while I<=N-1 do begin J:=0; while J<=K-1 do begin RefRC[I,J] := 2*RandomReal-1; RefCC[I,J].X := 2*RandomReal-1; RefCC[I,J].Y := 2*RandomReal-1; Inc(J); end; Inc(I); end; // // test different types of operations, offsets, and so on... // // to avoid unnecessary slowdown we don't test ALL possible // combinations of operation types. We just generate one random // set of parameters and test it. // SetLength(RA1, 2*N, 2*N); SetLength(RA2, 2*N, 2*N); SetLength(CA1, 2*N, 2*N); SetLength(CA2, 2*N, 2*N); SetLength(RC, N, K); SetLength(RCT, K, N); SetLength(CC, N, K); SetLength(CCT, K, N); UpperType := RandomInteger(2); XOffsI := RandomInteger(2); XOffsJ := RandomInteger(2); AOffsIType := RandomInteger(2); AOffsJType := RandomInteger(2); AlphaType := RandomInteger(2); BetaType := RandomInteger(2); AOffsI := N*AOffsIType; AOffsJ := N*AOffsJType; Alpha := AlphaType*(2*RandomReal-1); Beta := BetaType*(2*RandomReal-1); // // copy A, C (fill unused parts with random garbage) // I:=0; while I<=2*N-1 do begin J:=0; while J<=2*N-1 do begin if (I>=AOffsI) and (I<AOffsI+N) and (J>=AOffsJ) and (J<AOffsJ+N) then begin CA1[I,J] := RefCA[I,J]; CA2[I,J] := RefCA[I,J]; RA1[I,J] := RefRA[I,J]; RA2[I,J] := RefRA[I,J]; end else begin CA1[I,J] := C_Complex(RandomReal); CA2[I,J] := CA1[I,J]; RA1[I,J] := RandomReal; RA2[I,J] := RA1[I,J]; end; Inc(J); end; Inc(I); end; I:=0; while I<=N-1 do begin J:=0; while J<=K-1 do begin if (I>=XOffsI) and (J>=XOffsJ) then begin RC[I,J] := RefRC[I,J]; RCT[J,I] := RefRC[I,J]; CC[I,J] := RefCC[I,J]; CCT[J,I] := RefCC[I,J]; end else begin RC[I,J] := RandomReal; RCT[J,I] := RC[I,J]; CC[I,J] := C_Complex(RandomReal); CCT[J,I] := CCT[J,I]; end; Inc(J); end; Inc(I); end; // // Test complex // Only one of transform types is selected and tested // if AP_FP_Greater(RandomReal,0.5) then begin CMatrixSYRK(N-XOffsI, K-XOffsJ, Alpha, CC, XOffsI, XOffsJ, 0, Beta, CA1, AOffsI, AOffsJ, UpperType=0); RefCMatrixSYRK(N-XOffsI, K-XOffsJ, Alpha, CC, XOffsI, XOffsJ, 0, Beta, CA2, AOffsI, AOffsJ, UpperType=0); end else begin CMatrixSYRK(N-XOffsI, K-XOffsJ, Alpha, CCT, XOffsJ, XOffsI, 2, Beta, CA1, AOffsI, AOffsJ, UpperType=0); RefCMatrixSYRK(N-XOffsI, K-XOffsJ, Alpha, CCT, XOffsJ, XOffsI, 2, Beta, CA2, AOffsI, AOffsJ, UpperType=0); end; I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin Result := Result or AP_FP_Greater(AbsComplex(C_Sub(CA1[I,J],CA2[I,J])),Threshold); Inc(J); end; Inc(I); end; // // Test real // Only one of transform types is selected and tested // if AP_FP_Greater(RandomReal,0.5) then begin RMatrixSYRK(N-XOffsI, K-XOffsJ, Alpha, RC, XOffsI, XOffsJ, 0, Beta, RA1, AOffsI, AOffsJ, UpperType=0); RefRMatrixSYRK(N-XOffsI, K-XOffsJ, Alpha, RC, XOffsI, XOffsJ, 0, Beta, RA2, AOffsI, AOffsJ, UpperType=0); end else begin RMatrixSYRK(N-XOffsI, K-XOffsJ, Alpha, RCT, XOffsJ, XOffsI, 1, Beta, RA1, AOffsI, AOffsJ, UpperType=0); RefRMatrixSYRK(N-XOffsI, K-XOffsJ, Alpha, RCT, XOffsJ, XOffsI, 1, Beta, RA2, AOffsI, AOffsJ, UpperType=0); end; I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin Result := Result or AP_FP_Greater(AbsReal(RA1[I,J]-RA2[I,J]),Threshold); Inc(J); end; Inc(I); end; Inc(MX); end; end; (************************************************************************* GEMM tests Returns False for passed test, True - for failed *************************************************************************) function TestGEMM(MinN : AlglibInteger; MaxN : AlglibInteger):Boolean; var M : AlglibInteger; N : AlglibInteger; K : AlglibInteger; MX : AlglibInteger; I : AlglibInteger; J : AlglibInteger; AOffsI : AlglibInteger; AOffsJ : AlglibInteger; AOpType : AlglibInteger; AOpTypeR : AlglibInteger; BOffsI : AlglibInteger; BOffsJ : AlglibInteger; BOpType : AlglibInteger; BOpTypeR : AlglibInteger; COffsI : AlglibInteger; COffsJ : AlglibInteger; RefRA : TReal2DArray; RefRB : TReal2DArray; RefRC : TReal2DArray; RefCA : TComplex2DArray; RefCB : TComplex2DArray; RefCC : TComplex2DArray; AlphaR : Double; BetaR : Double; AlphaC : Complex; BetaC : Complex; RC1 : TReal2DArray; RC2 : TReal2DArray; CC1 : TComplex2DArray; CC2 : TComplex2DArray; Threshold : Double; begin Threshold := MaxN*100*MachineEpsilon; Result := False; MX:=MinN; while MX<=MaxN do begin // // Select random M/N/K in [1,MX] such that max(M,N,K)=MX // M := 1+RandomInteger(MX); N := 1+RandomInteger(MX); K := 1+RandomInteger(MX); I := RandomInteger(3); if I=0 then begin M := MX; end; if I=1 then begin N := MX; end; if I=2 then begin K := MX; end; // // Initialize A/B/C by random matrices with size (MaxN+1)*(MaxN+1) // SetLength(RefRA, MaxN+1, MaxN+1); SetLength(RefRB, MaxN+1, MaxN+1); SetLength(RefRC, MaxN+1, MaxN+1); SetLength(RefCA, MaxN+1, MaxN+1); SetLength(RefCB, MaxN+1, MaxN+1); SetLength(RefCC, MaxN+1, MaxN+1); I:=0; while I<=MaxN do begin J:=0; while J<=MaxN do begin RefRA[I,J] := 2*RandomReal-1; RefRB[I,J] := 2*RandomReal-1; RefRC[I,J] := 2*RandomReal-1; RefCA[I,J].X := 2*RandomReal-1; RefCA[I,J].Y := 2*RandomReal-1; RefCB[I,J].X := 2*RandomReal-1; RefCB[I,J].Y := 2*RandomReal-1; RefCC[I,J].X := 2*RandomReal-1; RefCC[I,J].Y := 2*RandomReal-1; Inc(J); end; Inc(I); end; // // test different types of operations, offsets, and so on... // // to avoid unnecessary slowdown we don't test ALL possible // combinations of operation types. We just generate one random // set of parameters and test it. // SetLength(RC1, MaxN+1, MaxN+1); SetLength(RC2, MaxN+1, MaxN+1); SetLength(CC1, MaxN+1, MaxN+1); SetLength(CC2, MaxN+1, MaxN+1); AOffsI := RandomInteger(2); AOffsJ := RandomInteger(2); AOpType := RandomInteger(3); AOpTypeR := RandomInteger(2); BOffsI := RandomInteger(2); BOffsJ := RandomInteger(2); BOpType := RandomInteger(3); BOpTypeR := RandomInteger(2); COffsI := RandomInteger(2); COffsJ := RandomInteger(2); AlphaR := RandomInteger(2)*(2*RandomReal-1); BetaR := RandomInteger(2)*(2*RandomReal-1); if AP_FP_Greater(RandomReal,0.5) then begin AlphaC.X := 2*RandomReal-1; AlphaC.Y := 2*RandomReal-1; end else begin AlphaC := C_Complex(0); end; if AP_FP_Greater(RandomReal,0.5) then begin BetaC.X := 2*RandomReal-1; BetaC.Y := 2*RandomReal-1; end else begin BetaC := C_Complex(0); end; // // copy C // I:=0; while I<=MaxN do begin J:=0; while J<=MaxN do begin RC1[I,J] := RefRC[I,J]; RC2[I,J] := RefRC[I,J]; CC1[I,J] := RefCC[I,J]; CC2[I,J] := RefCC[I,J]; Inc(J); end; Inc(I); end; // // Test complex // CMatrixGEMM(M, N, K, AlphaC, RefCA, AOffsI, AOffsJ, AOpType, RefCB, BOffsI, BOffsJ, BOpType, BetaC, CC1, COffsI, COffsJ); RefCMatrixGEMM(M, N, K, AlphaC, RefCA, AOffsI, AOffsJ, AOpType, RefCB, BOffsI, BOffsJ, BOpType, BetaC, CC2, COffsI, COffsJ); I:=0; while I<=MaxN do begin J:=0; while J<=MaxN do begin Result := Result or AP_FP_Greater(AbsComplex(C_Sub(CC1[I,J],CC2[I,J])),Threshold); Inc(J); end; Inc(I); end; // // Test real // RMatrixGEMM(M, N, K, AlphaR, RefRA, AOffsI, AOffsJ, AOpTypeR, RefRB, BOffsI, BOffsJ, BOpTypeR, BetaR, RC1, COffsI, COffsJ); RefRMatrixGEMM(M, N, K, AlphaR, RefRA, AOffsI, AOffsJ, AOpTypeR, RefRB, BOffsI, BOffsJ, BOpTypeR, BetaR, RC2, COffsI, COffsJ); I:=0; while I<=MaxN do begin J:=0; while J<=MaxN do begin Result := Result or AP_FP_Greater(AbsReal(RC1[I,J]-RC2[I,J]),Threshold); Inc(J); end; Inc(I); end; Inc(MX); end; end; (************************************************************************* transpose tests Returns False for passed test, True - for failed *************************************************************************) function TestTrans(MinN : AlglibInteger; MaxN : AlglibInteger):Boolean; var M : AlglibInteger; N : AlglibInteger; MX : AlglibInteger; I : AlglibInteger; J : AlglibInteger; AOffsI : AlglibInteger; AOffsJ : AlglibInteger; BOffsI : AlglibInteger; BOffsJ : AlglibInteger; V1 : Double; V2 : Double; Threshold : Double; RefRA : TReal2DArray; RefRB : TReal2DArray; RefCA : TComplex2DArray; RefCB : TComplex2DArray; begin Result := False; Threshold := 1000*MachineEpsilon; MX:=MinN; while MX<=MaxN do begin // // Select random M/N in [1,MX] such that max(M,N)=MX // Generate random V1 and V2 which are used to fill // RefRB/RefCB with control values. // M := 1+RandomInteger(MX); N := 1+RandomInteger(MX); if RandomInteger(2)=0 then begin M := MX; end else begin N := MX; end; V1 := RandomReal; V2 := RandomReal; // // Initialize A by random matrix with size (MaxN+1)*(MaxN+1) // Fill B with control values // SetLength(RefRA, MaxN+1, MaxN+1); SetLength(RefRB, MaxN+1, MaxN+1); SetLength(RefCA, MaxN+1, MaxN+1); SetLength(RefCB, MaxN+1, MaxN+1); I:=0; while I<=MaxN do begin J:=0; while J<=MaxN do begin RefRA[I,J] := 2*RandomReal-1; RefCA[I,J].X := 2*RandomReal-1; RefCA[I,J].Y := 2*RandomReal-1; RefRB[I,J] := I*V1+J*V2; RefCB[I,J] := C_Complex(I*V1+J*V2); Inc(J); end; Inc(I); end; // // test different offsets (zero or one) // // to avoid unnecessary slowdown we don't test ALL possible // combinations of operation types. We just generate one random // set of parameters and test it. // AOffsI := RandomInteger(2); AOffsJ := RandomInteger(2); BOffsI := RandomInteger(2); BOffsJ := RandomInteger(2); RMatrixTranspose(M, N, RefRA, AOffsI, AOffsJ, RefRB, BOffsI, BOffsJ); I:=0; while I<=MaxN do begin J:=0; while J<=MaxN do begin if (I<BOffsI) or (I>=BOffsI+N) or (J<BOffsJ) or (J>=BOffsJ+M) then begin Result := Result or AP_FP_Greater(AbsReal(RefRB[I,J]-(V1*I+V2*J)),Threshold); end else begin Result := Result or AP_FP_Greater(AbsReal(RefRB[I,J]-RefRA[AOffsI+J-BOffsJ,AOffsJ+I-BOffsI]),Threshold); end; Inc(J); end; Inc(I); end; CMatrixTranspose(M, N, RefCA, AOffsI, AOffsJ, RefCB, BOffsI, BOffsJ); I:=0; while I<=MaxN do begin J:=0; while J<=MaxN do begin if (I<BOffsI) or (I>=BOffsI+N) or (J<BOffsJ) or (J>=BOffsJ+M) then begin Result := Result or AP_FP_Greater(AbsComplex(C_SubR(RefCB[I,J],V1*I+V2*J)),Threshold); end else begin Result := Result or AP_FP_Greater(AbsComplex(C_Sub(RefCB[I,J],RefCA[AOffsI+J-BOffsJ,AOffsJ+I-BOffsI])),Threshold); end; Inc(J); end; Inc(I); end; Inc(MX); end; end; (************************************************************************* rank-1tests Returns False for passed test, True - for failed *************************************************************************) function TestRANK1(MinN : AlglibInteger; MaxN : AlglibInteger):Boolean; var M : AlglibInteger; N : AlglibInteger; MX : AlglibInteger; I : AlglibInteger; J : AlglibInteger; AOffsI : AlglibInteger; AOffsJ : AlglibInteger; UOffs : AlglibInteger; VOffs : AlglibInteger; Threshold : Double; RefRA : TReal2DArray; RefRB : TReal2DArray; RefCA : TComplex2DArray; RefCB : TComplex2DArray; RU : TReal1DArray; RV : TReal1DArray; CU : TComplex1DArray; CV : TComplex1DArray; begin Result := False; Threshold := 1000*MachineEpsilon; MX:=MinN; while MX<=MaxN do begin // // Select random M/N in [1,MX] such that max(M,N)=MX // M := 1+RandomInteger(MX); N := 1+RandomInteger(MX); if RandomInteger(2)=0 then begin M := MX; end else begin N := MX; end; // // Initialize A by random matrix with size (MaxN+1)*(MaxN+1) // Fill B with control values // SetLength(RefRA, MaxN+MaxN, MaxN+MaxN); SetLength(RefRB, MaxN+MaxN, MaxN+MaxN); SetLength(RefCA, MaxN+MaxN, MaxN+MaxN); SetLength(RefCB, MaxN+MaxN, MaxN+MaxN); I:=0; while I<=2*MaxN-1 do begin J:=0; while J<=2*MaxN-1 do begin RefRA[I,J] := 2*RandomReal-1; RefCA[I,J].X := 2*RandomReal-1; RefCA[I,J].Y := 2*RandomReal-1; RefRB[I,J] := RefRA[I,J]; RefCB[I,J] := RefCA[I,J]; Inc(J); end; Inc(I); end; SetLength(RU, 2*M); SetLength(CU, 2*M); I:=0; while I<=2*M-1 do begin RU[I] := 2*RandomReal-1; CU[I].X := 2*RandomReal-1; CU[I].Y := 2*RandomReal-1; Inc(I); end; SetLength(RV, 2*N); SetLength(CV, 2*N); I:=0; while I<=2*N-1 do begin RV[I] := 2*RandomReal-1; CV[I].X := 2*RandomReal-1; CV[I].Y := 2*RandomReal-1; Inc(I); end; // // test different offsets (zero or one) // // to avoid unnecessary slowdown we don't test ALL possible // combinations of operation types. We just generate one random // set of parameters and test it. // AOffsI := RandomInteger(MaxN); AOffsJ := RandomInteger(MaxN); UOffs := RandomInteger(M); VOffs := RandomInteger(N); CMatrixRank1(M, N, RefCA, AOffsI, AOffsJ, CU, UOffs, CV, VOffs); I:=0; while I<=2*MaxN-1 do begin J:=0; while J<=2*MaxN-1 do begin if (I<AOffsI) or (I>=AOffsI+M) or (J<AOffsJ) or (J>=AOffsJ+N) then begin Result := Result or AP_FP_Greater(AbsComplex(C_Sub(RefCA[I,J],RefCB[I,J])),Threshold); end else begin Result := Result or AP_FP_Greater(AbsComplex(C_Sub(RefCA[I,J],C_Add(RefCB[I,J],C_Mul(CU[I-AOffsI+UOffs],CV[J-AOffsJ+VOffs])))),Threshold); end; Inc(J); end; Inc(I); end; RMatrixRank1(M, N, RefRA, AOffsI, AOffsJ, RU, UOffs, RV, VOffs); I:=0; while I<=2*MaxN-1 do begin J:=0; while J<=2*MaxN-1 do begin if (I<AOffsI) or (I>=AOffsI+M) or (J<AOffsJ) or (J>=AOffsJ+N) then begin Result := Result or AP_FP_Greater(AbsReal(RefRA[I,J]-RefRB[I,J]),Threshold); end else begin Result := Result or AP_FP_Greater(AbsReal(RefRA[I,J]-(RefRB[I,J]+RU[I-AOffsI+UOffs]*RV[J-AOffsJ+VOffs])),Threshold); end; Inc(J); end; Inc(I); end; Inc(MX); end; end; (************************************************************************* MV tests Returns False for passed test, True - for failed *************************************************************************) function TestMV(MinN : AlglibInteger; MaxN : AlglibInteger):Boolean; var M : AlglibInteger; N : AlglibInteger; MX : AlglibInteger; I : AlglibInteger; J : AlglibInteger; AOffsI : AlglibInteger; AOffsJ : AlglibInteger; XOffs : AlglibInteger; YOffs : AlglibInteger; OpCA : AlglibInteger; OpRA : AlglibInteger; Threshold : Double; RV1 : Double; RV2 : Double; CV1 : Complex; CV2 : Complex; RefRA : TReal2DArray; RefCA : TComplex2DArray; RX : TReal1DArray; RY : TReal1DArray; CX : TComplex1DArray; CY : TComplex1DArray; i_ : AlglibInteger; i1_ : AlglibInteger; begin Result := False; Threshold := 1000*MachineEpsilon; MX:=MinN; while MX<=MaxN do begin // // Select random M/N in [1,MX] such that max(M,N)=MX // M := 1+RandomInteger(MX); N := 1+RandomInteger(MX); if RandomInteger(2)=0 then begin M := MX; end else begin N := MX; end; // // Initialize A by random matrix with size (MaxN+MaxN)*(MaxN+MaxN) // Initialize X by random vector with size (MaxN+MaxN) // Fill Y by control values // SetLength(RefRA, MaxN+MaxN, MaxN+MaxN); SetLength(RefCA, MaxN+MaxN, MaxN+MaxN); I:=0; while I<=2*MaxN-1 do begin J:=0; while J<=2*MaxN-1 do begin RefRA[I,J] := 2*RandomReal-1; RefCA[I,J].X := 2*RandomReal-1; RefCA[I,J].Y := 2*RandomReal-1; Inc(J); end; Inc(I); end; SetLength(RX, 2*MaxN); SetLength(CX, 2*MaxN); SetLength(RY, 2*MaxN); SetLength(CY, 2*MaxN); I:=0; while I<=2*MaxN-1 do begin RX[I] := 2*RandomReal-1; CX[I].X := 2*RandomReal-1; CX[I].Y := 2*RandomReal-1; RY[I] := I; CY[I] := C_Complex(I); Inc(I); end; // // test different offsets (zero or one) // // to avoid unnecessary slowdown we don't test ALL possible // combinations of operation types. We just generate one random // set of parameters and test it. // AOffsI := RandomInteger(MaxN); AOffsJ := RandomInteger(MaxN); XOffs := RandomInteger(MaxN); YOffs := RandomInteger(MaxN); OpCA := RandomInteger(3); OpRA := RandomInteger(2); CMatrixMV(M, N, RefCA, AOffsI, AOffsJ, OpCA, CX, XOffs, CY, YOffs); I:=0; while I<=2*MaxN-1 do begin if (I<YOffs) or (I>=YOffs+M) then begin Result := Result or C_NotEqualR(CY[I],I); end else begin CV1 := CY[I]; if OpCA=0 then begin i1_ := (XOffs)-(AOffsJ); CV2 := C_Complex(0.0); for i_ := AOffsJ to AOffsJ+N-1 do begin CV2 := C_Add(CV2,C_Mul(RefCA[AOffsI+I-YOffs,i_],CX[i_+i1_])); end; end; if OpCA=1 then begin i1_ := (XOffs)-(AOffsI); CV2 := C_Complex(0.0); for i_ := AOffsI to AOffsI+N-1 do begin CV2 := C_Add(CV2,C_Mul(RefCA[i_,AOffsJ+I-YOffs],CX[i_+i1_])); end; end; if OpCA=2 then begin i1_ := (XOffs)-(AOffsI); CV2 := C_Complex(0.0); for i_ := AOffsI to AOffsI+N-1 do begin CV2 := C_Add(CV2,C_Mul(Conj(RefCA[i_,AOffsJ+I-YOffs]),CX[i_+i1_])); end; end; Result := Result or AP_FP_Greater(AbsComplex(C_Sub(CV1,CV2)),Threshold); end; Inc(I); end; RMatrixMV(M, N, RefRA, AOffsI, AOffsJ, OpRA, RX, XOffs, RY, YOffs); I:=0; while I<=2*MaxN-1 do begin if (I<YOffs) or (I>=YOffs+M) then begin Result := Result or AP_FP_Neq(RY[I],I); end else begin RV1 := RY[I]; if OpRA=0 then begin RV2 := APVDotProduct(@RefRA[AOffsI+I-YOffs][0], AOffsJ, AOffsJ+N-1, @RX[0], XOffs, XOffs+N-1); end; if OpRA=1 then begin i1_ := (XOffs)-(AOffsI); RV2 := 0.0; for i_ := AOffsI to AOffsI+N-1 do begin RV2 := RV2 + RefRA[i_,AOffsJ+I-YOffs]*RX[i_+i1_]; end; end; Result := Result or AP_FP_Greater(AbsReal(RV1-RV2),Threshold); end; Inc(I); end; Inc(MX); end; end; (************************************************************************* COPY tests Returns False for passed test, True - for failed *************************************************************************) function TestCopy(MinN : AlglibInteger; MaxN : AlglibInteger):Boolean; var M : AlglibInteger; N : AlglibInteger; MX : AlglibInteger; I : AlglibInteger; J : AlglibInteger; AOffsI : AlglibInteger; AOffsJ : AlglibInteger; BOffsI : AlglibInteger; BOffsJ : AlglibInteger; Threshold : Double; RV1 : Double; RV2 : Double; CV1 : Complex; CV2 : Complex; RA : TReal2DArray; RB : TReal2DArray; CA : TComplex2DArray; CB : TComplex2DArray; begin Result := False; Threshold := 1000*MachineEpsilon; MX:=MinN; while MX<=MaxN do begin // // Select random M/N in [1,MX] such that max(M,N)=MX // M := 1+RandomInteger(MX); N := 1+RandomInteger(MX); if RandomInteger(2)=0 then begin M := MX; end else begin N := MX; end; // // Initialize A by random matrix with size (MaxN+MaxN)*(MaxN+MaxN) // Initialize X by random vector with size (MaxN+MaxN) // Fill Y by control values // SetLength(RA, MaxN+MaxN, MaxN+MaxN); SetLength(CA, MaxN+MaxN, MaxN+MaxN); SetLength(RB, MaxN+MaxN, MaxN+MaxN); SetLength(CB, MaxN+MaxN, MaxN+MaxN); I:=0; while I<=2*MaxN-1 do begin J:=0; while J<=2*MaxN-1 do begin RA[I,J] := 2*RandomReal-1; CA[I,J].X := 2*RandomReal-1; CA[I,J].Y := 2*RandomReal-1; RB[I,J] := 1+2*I+3*J; CB[I,J] := C_Complex(1+2*I+3*J); Inc(J); end; Inc(I); end; // // test different offsets (zero or one) // // to avoid unnecessary slowdown we don't test ALL possible // combinations of operation types. We just generate one random // set of parameters and test it. // AOffsI := RandomInteger(MaxN); AOffsJ := RandomInteger(MaxN); BOffsI := RandomInteger(MaxN); BOffsJ := RandomInteger(MaxN); CMatrixCopy(M, N, CA, AOffsI, AOffsJ, CB, BOffsI, BOffsJ); I:=0; while I<=2*MaxN-1 do begin J:=0; while J<=2*MaxN-1 do begin if (I<BOffsI) or (I>=BOffsI+M) or (J<BOffsJ) or (J>=BOffsJ+N) then begin Result := Result or C_NotEqualR(CB[I,J],1+2*I+3*J); end else begin Result := Result or AP_FP_Greater(AbsComplex(C_Sub(CA[AOffsI+I-BOffsI,AOffsJ+J-BOffsJ],CB[I,J])),Threshold); end; Inc(J); end; Inc(I); end; RMatrixCopy(M, N, RA, AOffsI, AOffsJ, RB, BOffsI, BOffsJ); I:=0; while I<=2*MaxN-1 do begin J:=0; while J<=2*MaxN-1 do begin if (I<BOffsI) or (I>=BOffsI+M) or (J<BOffsJ) or (J>=BOffsJ+N) then begin Result := Result or AP_FP_Neq(RB[I,J],1+2*I+3*J); end else begin Result := Result or AP_FP_Greater(AbsReal(RA[AOffsI+I-BOffsI,AOffsJ+J-BOffsJ]-RB[I,J]),Threshold); end; Inc(J); end; Inc(I); end; Inc(MX); end; end; (************************************************************************* Silent unit test *************************************************************************) function testablasunit_test_silent():Boolean; begin Result := TestABLAS(True); end; (************************************************************************* Unit test *************************************************************************) function testablasunit_test():Boolean; begin Result := TestABLAS(False); end; end.
{ @html(<b>) Transports Plug-in @html(</b>) - Copyright (c) Danijel Tkalcec @html(<br><br>) This unit defines a Plug-in interface, which should be implemented when writing third-party transports to be used with the RealThinClient SDK components. } unit rtcTransports; interface uses Classes; const // Interface GUID IRTCMessageReceiverGUID: TGUID = '{C9E3606F-ED08-43F4-AF97-F55A3EC8F14B}'; type { @abstract(Transport Plugin interface) This interface should be *IMPLEMENTED* when writing a "receiver" transport plugin, which can be linked to TRtcMessageClient in place of the TRtcMessageServer component. } IRTCMessageReceiver = interface ['{C9E3606F-ED08-43F4-AF97-F55A3EC8F14B}'] { ProcessMessage need to be called *only* once per request, with a complete request data waiting in the "aRequest" stream and an empty "aReply" stream to receive the response. Request processing is done in a "blocking mode", which means that the caller will have the complete response filled in the "aReply" stream, before the call returns. } procedure ProcessMessage(aRequest, aReply: TStream); end; implementation end.
unit unUtils; interface uses SysUtils, Math, dialogs; function DefaultDateFormat(const Value: AnsiString): AnsiString; function RoundWithDecimals(X: double; Decimals: integer): Double; Function IsNumber(strNumber: AnsiString): Boolean; function IsFloat(strNumber: AnsiString): Boolean; function formatNumber(strNumber: AnsiString): AnsiString; implementation const VALID_NUMBERS: set of Char = ['0'..'9',',']; function DefaultDateFormat(const Value: AnsiString): AnsiString; var AuxDay, AuxMonth, AuxYear: AnsiString; IntDay, IntMonth, IntYear: smallint; begin Result := Value; if (Value = '') then Exit; if System.Pos('-', Value) = 0 then Exit; AuxYear := copy(Value,1,4); AuxMonth := copy(Value,6,2); AuxDay := copy(Value,9,2); IntDay := StrToIntDef(AuxDay, 10); IntMonth := StrToIntDef(AuxMonth, 10); IntYear := StrToIntDef(AuxYear, 1900); Result := SysUtils.FormatFloat('00', IntDay) + '/' + SysUtils.FormatFloat('00', IntMonth) + '/' + IntToStr(IntYear); end; function RoundWithDecimals(X: double; Decimals: integer): Double; var Mult: Double; begin Mult := Power(10, Decimals); Result := Trunc(X*Mult+0.5*Sign(X))/Mult; end; Function IsNumber(strNumber : AnsiString) : Boolean; var i : Integer; begin for i:=1 to Length(strNumber) do begin if not (strNumber[i] in [#48..#57]) then begin Result := False; Exit; end; end; Result := (strNumber <> ''); end; function IsFloat(strNumber: AnsiString): Boolean; var i : Integer; begin for i:=1 to Length(strNumber) do begin if not (strNumber[i] in VALID_NUMBERS) then begin Result := False; Exit; end; end; Result := (strNumber <> ''); end; function formatNumber(strNumber: AnsiString): AnsiString; begin strNumber := Trim(strNumber); strNumber := StringReplace(strNumber, ' ', '', [rfReplaceAll]); if strNumber[length(strNumber)] = ',' then strNumber := Trim(StringReplace(Trim(strNumber), ',', '', [rfReplaceAll])); Result := strNumber; end; end.
unit Test.Devices.Logica.SPT961.ReqCreator; interface uses TestFrameWork, Devices.Logica.SPT961, GMGlobals, Test.Devices.Base.ReqCreator; type TSPT961ReqCreatorFortest = class(TSPT961ReqCreator) end; TLogicaSPT961ReqCreatorTest = class(TDeviceReqCreatorTestBase) private sptReqCreator: TSPT961ReqCreatorFortest; procedure CheckResultString(const errMsg, resString: string); procedure CleanArchives; protected procedure SetUp; override; procedure TearDown; override; function GetDevType(): int; override; procedure DoCheckRequests(); override; published procedure testCommonPrm(); procedure testIndexPrm(); procedure testArchStructure(); procedure testArchData(); procedure testFromExtData(); procedure testTimeArray; procedure CheckRequests(); override; end; implementation uses DateUtils, SysUtils, GMConst; { TLogicaReqCreatorTest } procedure TLogicaSPT961ReqCreatorTest.CleanArchives(); var i: int; begin for i := ReqList.Count - 1 downto 0 do begin if ReqList[i].Priority > rqprCurrents then ReqList.Delete(i); end; end; procedure TLogicaSPT961ReqCreatorTest.CheckRequests; begin ReqCreator.AddDeviceToSendBuf(); CleanArchives(); Check(ReqList.Count >= 15); // архивы пока не дергаем CheckReqHexString(0, '$10, 1, $18, $18, $10, $1F, $1D, $10, 2, 9, $30, 9, $36, $33, $C, $10, 3, $22, $51'); CheckReqHexString(1, '$10, 1, $18, $18, $10, $1F, $1D, $10, 2, 9, $30, 9, $36, $35, $C, $10, 3, 5, $C8'); CheckReqHexString(2, '$10, 1, $18, $18, $10, $1F, $1D, $10, 2, 9, $30, 9, $36, $36, $C, $10, 3, $9E, $14'); CheckReqHexString(3, '$10, 1, $18, $18, $10, $1F, $1D, $10, 2, 9, $31, 9, $31, $35, $35, $C, $10, 3, $98, $E8'); CheckReqHexString(4, '$10, 1, $18, $18, $10, $1F, $1D, $10, 2, 9, $31, 9, $31, $35, $36, $C, $10, 3, 3, $34'); CheckReqHexString(5, '$10, 1, $18, $18, $10, $1F, $1D, $10, 2, 9, $31, 9, $31, $35, $37, $C, $10, 3, $75, $80'); CheckReqHexString(6, '$10, 1, $18, $18, $10, $1F, $1D, $10, 2, 9, $31, 9, $31, $37, $31, $C, $10, 3, $16, $9A'); CheckReqHexString(7, '$10, 1, $18, $18, $10, $1F, $1D, $10, 2, 9, $32, 9, $31, $35, $35, $C, $10, 3, $50, $9D'); CheckReqHexString(8, '$10, 1, $18, $18, $10, $1F, $1D, $10, 2, 9, $32, 9, $31, $35, $36, $C, $10, 3, $CB, $41'); CheckReqHexString(9, '$10, 1, $18, $18, $10, $1F, $1D, $10, 2, 9, $32, 9, $31, $35, $37, $C, $10, 3, $BD, $F5'); CheckReqHexString(10, '$10, 1, $18, $18, $10, $1F, $1D, $10, 2, 9, $32, 9, $31, $37, $31, $C, $10, 3, $DE, $EF'); CheckReqHexString(11, '$10, 1, $18, $18, $10, $1F, $1D, $10, 2, 9, $31, 9, $31, $36, $30, $C, $10, 3, $CA, $7F'); CheckReqHexString(12, '$10, 1, $18, $18, $10, $1F, $1D, $10, 2, 9, $31, 9, $31, $36, $33, $C, $10, 3, $51, $A3'); CheckReqHexString(13, '$10, 1, $18, $18, $10, $1F, $1D, $10, 2, 9, $32, 9, $31, $36, $30, $C, $10, 3, 2, $A'); CheckReqHexString(14, '$10, 1, $18, $18, $10, $1F, $1D, $10, 2, 9, $32, 9, $31, $36, $33, $C, $10, 3, $99, $D6'); end; procedure TLogicaSPT961ReqCreatorTest.CheckResultString(const errMsg, resString: string); var i, n: int; creo: string; begin creo := ArrayToString(sptReqCreator.bufSend, sptReqCreator.LengthSend, false, true); Check(Length(creo) = Length(resString), errMsg + ' - length differs'); n := 0; for i := 1 to Length(resString) do begin if creo[i] <> resString[i] then begin n := i; break; end; end; Check(n = 0, errMsg + ' - ErrorPos = ' + IntToStr(n)); end; procedure TLogicaSPT961ReqCreatorTest.DoCheckRequests; begin inherited; end; function TLogicaSPT961ReqCreatorTest.GetDevType: int; begin Result := DEVTYPE_SPT_961; end; procedure TLogicaSPT961ReqCreatorTest.SetUp; var reqdetails: TRequestDetails; begin inherited; reqdetails.Init(); sptReqCreator := TSPT961ReqCreatorFortest.Create(nil, reqdetails); end; procedure TLogicaSPT961ReqCreatorTest.TearDown; begin inherited; sptReqCreator.Free(); end; procedure TLogicaSPT961ReqCreatorTest.testArchData; begin sptReqCreator.Chn := 0; sptReqCreator.archDT1 := EncodeDate(2013, 10, 14); sptReqCreator.ArchType := gmarchDay; sptReqCreator.ArchData(); CheckResultString('ArchData', '10 01 00 00 10 1F 18 10 02 09 30 09 36 35 35 33 32 0C 09 31 34 09 31 30 09 32 30 31 33 09 30 09 30 09 30 0C 10 03 FB C6'); end; procedure TLogicaSPT961ReqCreatorTest.testArchStructure; begin sptReqCreator.Chn := 0; sptReqCreator.ArchType := gmarchDay; sptReqCreator.ArchStructure(); CheckResultString('ArchStructure', '10 01 00 00 10 1F 19 10 02 09 30 09 36 35 35 33 32 0C 10 03 8E 0D'); end; procedure TLogicaSPT961ReqCreatorTest.testCommonPrm; begin sptReqCreator.Chn := 1; sptReqCreator.Prm := 160; sptReqCreator.CommonPrm(); CheckResultString('CommonPrm', '10 01 00 00 10 1F 1D 10 02 09 31 09 31 36 30 0C 10 03 91 3F'); end; procedure TLogicaSPT961ReqCreatorTest.testFromExtData; begin Check(sptReqCreator.FromExtData('1 123'), 'correct Extdata'); Check((sptReqCreator.Chn = 1) and (sptReqCreator.Prm = 123), 'correct Extdata result'); Check(sptReqCreator.FromExtData(' 1 123 '), 'correct Extdata with extra spaces'); Check((sptReqCreator.Chn = 1) and (sptReqCreator.Prm = 123), 'correct Extdata with extra spaces result'); Check(sptReqCreator.FromExtData(' 1 123 586 ', rqtSPT961_DAY), 'correct Extdata Arch with extra spaces'); Check((sptReqCreator.Chn = 1) and (sptReqCreator.Prm = 586), 'correct Extdata Arch with extra spaces result'); Check(not sptReqCreator.FromExtData(' 0 '), 'Insufficient ExtData'); Check(not sptReqCreator.FromExtData(''), 'Empty ExtData'); Check(not sptReqCreator.FromExtData('0 de'), 'Incorrect ExtData 1'); Check(not sptReqCreator.FromExtData('de 1'), 'Incorrect ExtData 2'); Check(not sptReqCreator.FromExtData('de ab'), 'Incorrect ExtData both'); Check(not sptReqCreator.FromExtData('-1 1'), 'Negative ExtData'); Check(not sptReqCreator.FromExtData('1 -1'), 'Negative ExtData 2'); Check(sptReqCreator.FromExtData('1 1 -1'), 'Negative ExtData 3'); Check(not sptReqCreator.FromExtData('1 1 -1', rqtSPT961_DAY), 'Negative ExtData 4'); Check(not sptReqCreator.FromExtData('1,1'), 'Comma Text'); Check(sptReqCreator.FromExtData(' 00 002 0003 de'), ' Excessive ExtData'); Check((sptReqCreator.Chn = 0) and (sptReqCreator.Prm = 2), 'Excessive Extdata result'); Check(sptReqCreator.FromExtData(' 00 002 0003 de', rqtSPT961_DAY), 'Excessive ExtData Arch'); Check((sptReqCreator.Chn = 0) and (sptReqCreator.Prm = 3), 'Excessive Extdata Arch result'); ////// Check(sptReqCreator.FromExtData(' 1 123 586 789', rqtSPT961_HOUR), 'correct Extdata Arch with extra spaces'); Check((sptReqCreator.Chn = 1) and (sptReqCreator.Prm = 789), 'correct Extdata Arch with extra spaces result'); Check(not sptReqCreator.FromExtData('1 1 1 -1', rqtSPT961_HOUR), 'Negative ExtData 4'); Check(not sptReqCreator.FromExtData('1 1 1 dede', rqtSPT961_HOUR), 'Incorrect ExtData Hour'); Check(sptReqCreator.FromExtData(' 00 002 0003 000004 de', rqtSPT961_HOUR), 'Excessive ExtData Arch'); Check((sptReqCreator.Chn = 0) and (sptReqCreator.Prm = 4), 'Excessive Extdata Arch result'); end; procedure TLogicaSPT961ReqCreatorTest.testIndexPrm; begin sptReqCreator.Chn := 0; sptReqCreator.Prm := 96; sptReqCreator.IdxStart := 1; sptReqCreator.IdxCount := 9; sptReqCreator.IndexPrm(); CheckResultString('IndexPrm', '10 01 00 00 10 1F 0C 10 02 09 30 09 39 36 09 31 09 39 0C 10 03 F6 F9'); end; procedure TLogicaSPT961ReqCreatorTest.testTimeArray; begin sptReqCreator.Chn := 0; sptReqCreator.Prm := 72; sptReqCreator.archDT1 := EncodeDate(2013, 10, 09); sptReqCreator.archDT2 := EncodeDate(2013, 10, 14); sptReqCreator.TimeArray(); CheckResultString('TimeArray', '10 01 00 00 10 1F 0E 10 02 09 30 09 37 32 0C 09 31 34 09 31 30 09 32 30 31 33 09 30 09 30 09 30 0C 09 39 09 31 30 09 32 30 31 33 09 30 09 30 09 30 0C 10 03 A3 42'); end; initialization RegisterTest('GMIOPSrv/Devices/Logica', TLogicaSPT961ReqCreatorTest.Suite); end.
unit Collision; interface uses AsphyreDef, Math; type TPolygon_Points = array of TPoint2; TCollision = class private public constructor Create; // возвращает true если отрезки[a1,a2] и [b1,b2] пересекаюстя // иначе - false (не учитывается пересечение граничными точками !!!) function Piece_Intersect(a1,a2,b1,b2: TPoint2): boolean; // возвращает true если граничные точки отрезка[a1,a2] попадают // в [b1,b2] или наоборот function Is_Piece_Points(a1,a2,b1,b2: TPoint2): boolean; // возвращает true если полигоны p1 и p2 пересекаюстя // иначе - false function Polygon_Intersect(p1,p2: TPolygon_Points): boolean; // возвращает true если полигон p и отрезок [a1,a2] пересекаюстя // иначе - false function Polygon_and_Piece_Intersect(p: TPolygon_Points; a1,a2: TPoint2): boolean; // рисует на экране полигон procedure Draw_Polygon(p: TPolygon_Points; Color: Cardinal); // возвращает true если окружности c центрами в с1 и с2 и // радиусами r1 и r2 пересекаюстя, иначе - false function Circle_Intersect(c1: TPoint2; r1: single; c2: TPoint2; r2: single): boolean; // возвращает точку пересечения отрезков [a1,a2] и [b1,b2] // Вызывать только если отрезки пересекаются !!! // если отрезки совпадают - выдает середину наименьшего function Piece_Int_Point(a1,a2,b1,b2: TPoint2): TPoint2; // возвращает одну из точек пересечения отрезка [a1,a2] и полигона "p" // Если не пересекаются возвращяет (0,0) !!! // если совпадают - выдает середину наименьшего из (ребро, грань) function Polygon_and_Piece_Int_Point(p: TPolygon_Points; a1,a2: TPoint2): TPoint2; // возвращает точку пересечения отрезка [a1,a2] и полигона "p" // Если точек несколько возвращает среднюю между ними // Если не пересекаются возвращяет (0,0) !!! // если совпадают - выдает середину наименьшего из (ребро, грань) function Polygon_and_Piece_Int_Point_2(p: TPolygon_Points; a1,a2: TPoint2): TPoint2; // возвращает true если точка "z" попадает в регион "p" // Регион "p" - замкнутая ломаная // (последняя точка должна совпадать с 1-й) function Point_in_RGN(p: TPolygon_Points; z: TPoint2): boolean; //--------------------------------------------------------------- // возвращает знак полуплоскости точки «c» относительно прямой (a, b). // Если точка «c» лежит на прямой, то Orient() возвращает 0. function Orient(a,b,c: TPoint2): shortint; // возвращяет длинну отрезка [с1, с2] function Long(c1: TPoint2; c2: TPoint2): single; // возвращяет точку - середину отрезка [с1, с2] function Center(c1, c2: TPoint2): TPoint2; // возвращает true если точка "c" принадлежит отрезку [а1,a2] function Point_in_Piece(a1,a2,c: TPoint2): boolean; // возвращает true если прямия [a1,a2] совпадает с [d1,d2] function Line_in_Line(a1,a2,d1,d2: TPoint2): boolean; // поворачивает точку "a" относительно точки "o" на угол "ug" // по часовой (ug - в радианах) function Rotate_point(a, o: TPoint2; ug: single): TPoint2; // возвращяет острый угол в радианах между векторами (o, a2) и (o, b2) function Corner_vectors(o, a2, b2: TPoint2): single; end; implementation uses Unit1; { TCollision } constructor TCollision.Create; begin end; function TCollision.Orient(a,b,c: TPoint2): shortint; var temp: single; begin temp:= (a.x - c.x)*(b.y - c.y) - (a.y - c.y)*(b.x - c.x); if temp <= 0 then begin if temp = 0 then result:= 0 else result:= -1; end else begin result:= 1; end; end; function TCollision.Piece_Intersect(a1, a2, b1, b2: TPoint2): boolean; var temp1,temp2: shortint; begin result:= false; //если отрезок левее if (a1.x < b1.x)and(a1.x < b2.x)and (a2.x < b1.x)and(a2.x < b2.x) then exit; //если отрезок правее if (a1.x > b1.x)and(a1.x > b2.x)and (a2.x > b1.x)and(a2.x > b2.x) then exit; //если отрезок выше if (a1.y < b1.y)and(a1.y < b2.y)and (a2.y < b1.y)and(a2.y < b2.y) then exit; //если отрезок ниже if (a1.y > b1.y)and(a1.y > b2.y)and (a2.y > b1.y)and(a2.y > b2.y) then exit; temp1:= Orient(Point2(b1.x,b1.y),Point2(b2.x,b2.y),Point2(a1.x,a1.y))* Orient(Point2(b1.x,b1.y),Point2(b2.x,b2.y),Point2(a2.x,a2.y)); temp2:= Orient(Point2(a1.x,a1.y),Point2(a2.x,a2.y),Point2(b1.x,b1.y))* Orient(Point2(a1.x,a1.y),Point2(a2.x,a2.y),Point2(b2.x,b2.y)); if temp1 <> temp2 then exit; if temp1 <= 0 then result:= true else result:= false; end; function TCollision.Piece_Int_Point(a1, a2, b1, b2: TPoint2): TPoint2; var d1, d2, n1, n2, c: TPoint2; begin if Long(a1,a2) <= Long(b1,b2) then begin // отрезок, кот делим d1:= Point2(a1.x, a1.y); d2:= Point2(a2.x, a2.y); // 2-й отрезок n1:= Point2(b1.x, b1.y); n2:= Point2(b2.x, b2.y); end else begin // отрезок, кот делим d1:= Point2(b1.x, b1.y); d2:= Point2(b2.x, b2.y); // 2-й отрезок n1:= Point2(a1.x, a1.y); n2:= Point2(a2.x, a2.y); end; //если отрезки совпадают if Line_in_Line(a1, a2, b1, b2) then begin result:= Center(d1, d2); exit; end; while (abs(d1.x - d2.x) > 0.001) or (abs(d1.y - d2.y) > 0.001) do begin c:= Center(d1, d2); if Piece_Intersect(d1,c, n1,n2) or Is_Piece_Points(d1,c, n1,n2) then begin d2:= Point2(c.x, c.y); end else begin d1:= Point2(c.x, c.y); end; end; result:= Point2(d1.x, d1.y); end; function TCollision.Point_in_Piece(a1, a2, c: TPoint2): boolean; var k, b: single; begin result:= false; //если точка левее if (a1.x < c.x)and(a2.x < c.x)then exit; //если точка правее if (a1.x > c.x)and(a2.x > c.x) then exit; //если точка выше if (a1.y < c.y)and(a2.y < c.y) then exit; //если точка ниже if (a1.y > c.y)and(a2.y > c.y) then exit; if Orient(Point2(a1.x,a1.y),Point2(a2.x,a2.y),Point2(c.x,c.y)) = 0 then result:= true; end; function TCollision.Point_in_RGN(p: TPolygon_Points; z: TPoint2): boolean; var i: integer; np: integer; lx, rx, s: single; count: integer; begin np:= length(p); // находим ширину региона lx:= p[0].x; rx:= p[0].x; for i:= 1 to np-1 do begin if lx < p[i].x then lx:= p[i].x; if rx > p[i].x then rx:= p[i].x; end; s:= rx - lx; // проверяем на пересечение отрезка или левой // граничной точки с полигоном count:= 0; for i:= 0 to np-2 do begin if Piece_Intersect(p[i],p[i+1],z,Point2(z.x-s, z.y)) or Point_in_Piece(p[i],p[i+1],Point2(z.x-s, z.y)) then begin inc(count); end; end; // если нечетно if (count mod 2 <> 0) then result:= true else result:= false; end; function TCollision.Polygon_and_Piece_Intersect(p: TPolygon_Points; a1, a2: TPoint2): boolean; var i: integer; np: integer; begin result:= false; np:= length(p); for i:= 0 to np-2 do begin result:= result or Piece_Intersect(p[i],p[i+1],a1,a2) or Is_Piece_Points(p[i],p[i+1],a1,a2); end; end; function TCollision.Polygon_and_Piece_Int_Point(p: TPolygon_Points; a1, a2: TPoint2): TPoint2; var i: integer; np: integer; begin result:= Point2(0,0); np:= length(p); for i:= 0 to np-2 do begin if Piece_Intersect(p[i],p[i+1],a1,a2) or Is_Piece_Points(p[i],p[i+1],a1,a2) then begin result:= Piece_Int_Point(p[i],p[i+1],a1,a2); exit; end; end; end; function TCollision.Polygon_and_Piece_Int_Point_2(p: TPolygon_Points; a1, a2: TPoint2): TPoint2; var i: integer; np: integer; a: array of TPoint2; na: integer; xl,xr,yt,yb: single; begin result:= Point2(0,0); np:= length(p); SetLength(a,np-1); na:= -1; // Ищем точки пересечения for i:= 0 to np-2 do begin if Piece_Intersect(p[i],p[i+1],a1,a2) or Is_Piece_Points(p[i],p[i+1],a1,a2) then begin inc(na); a[na]:= Piece_Int_Point(p[i],p[i+1],a1,a2); end; end; // находим граничные точки xl:= a[0].x; xr:= a[0].x; yt:= a[0].y; yb:= a[0].y; for i:= 1 to na do begin if a[i].x < xl then xl:= a[i].x; if a[i].x > xr then xr:= a[i].x; if a[i].y < yt then yt:= a[i].y; if a[i].y > yb then yb:= a[i].y; end; result.x:= (xl + xr)/2; result.y:= (yt + yb)/2; end; function TCollision.Polygon_Intersect(p1, p2: TPolygon_Points): boolean; var i,j: integer; np1,np2: integer; begin result:= false; np1:= length(p1); np2:= length(p2); for i:= 0 to np1-2 do begin for j:= 0 to np2-2 do begin result:= result or Piece_Intersect(p1[i],p1[i+1],p2[j],p2[j+1]) or Is_Piece_Points(p1[i],p1[i+1],p2[j],p2[j+1]); end; result:= result or Piece_Intersect(p1[i],p1[i+1],p2[np2-1],p2[0]) or Is_Piece_Points(p1[i],p1[i+1],p2[np2-1],p2[0]); end; end; procedure TCollision.Draw_Polygon(p: TPolygon_Points; Color: Cardinal); var i: integer; np1: integer; begin np1:= length(p); for i:= 0 to np1-2 do begin Form1.MyCanvas.Line(p[i].x, p[i].y - Form1.Engine.WorldY, p[i+1].x, p[i+1].y - Form1.Engine.WorldY, Color,Color,1); end; end; function TCollision.Is_Piece_Points(a1, a2, b1, b2: TPoint2): boolean; begin if Point_in_Piece(a1,a2,b1) or Point_in_Piece(a1,a2,b2) or Point_in_Piece(b1,b2,a1) or Point_in_Piece(b1,b2,a2) then begin result:= true; end else begin result:= false; end; end; function TCollision.Line_in_Line(a1, a2, d1, d2: TPoint2): boolean; var k1, k2, b1, b2: single; begin k1:= (a2.y - a1.y)/(a2.x - a1.x); b1:= a1.y - k1*a1.x; k2:= (d2.y - d1.y)/(d2.x - d1.x); b2:= d1.y - k2*d1.x; if (k1 = k2)and(b1 = b2) then result:= true else result:= false; end; function TCollision.Long(c1, c2: TPoint2): single; begin result:= sqrt(sqr(c1.x - c2.x) + sqr(c1.y - c2.y)); end; function TCollision.Center(c1, c2: TPoint2): TPoint2; begin result.x:= (c1.x + c2.x)/2; result.y:= (c1.y + c2.y)/2; end; function TCollision.Circle_Intersect(c1: TPoint2; r1: single; c2: TPoint2; r2: single): boolean; begin if (sqrt(sqr(c1.x - c2.x) + sqr(c1.y - c2.y)) <= r1 + r2) then result:= true else result:= false; end; function TCollision.Corner_vectors(o, a2, b2: TPoint2): single; var ax, ay, bx, by: single; begin ax:= a2.x - o.x; ay:= a2.y - o.y; bx:= b2.x - o.x; by:= b2.y - o.y; result:= (ax*bx + ay*by)/(sqrt(ax*ax+ay*ay)*sqrt(bx*bx+by*by)); result:= ArcCos(result); end; function TCollision.Rotate_point(a, o: TPoint2; ug: single): TPoint2; var nx, ny: single; begin a.x:= a.x - o.x; a.y:= a.y - o.y; nx:= a.x*cos(ug) - a.y*sin(ug) + o.x; ny:= a.y*cos(ug) + a.x*sin(ug) + o.y; result:= Point2(nx, ny); end; end.
unit uFileSystemWatcher; interface uses {$IF CompilerVersion > 22} Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, {$ELSE} Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, {$IFEND} CNClrLib.Control.EnumTypes, CNClrLib.Control.Base, CNClrLib.Component.FileSystemWatcher, CNClrLib.Component.FolderBrowserDialog; type TfrmFileSystemWatcher = class(TForm) CnFileSystemWatcher1: TCnFileSystemWatcher; btnStart: TButton; btnStop: TButton; GroupBox1: TGroupBox; chkFilename: TCheckBox; chkAttributes: TCheckBox; chkDirectoryName: TCheckBox; chkCreationTime: TCheckBox; chkSize: TCheckBox; chkLastAccess: TCheckBox; chkLastWrite: TCheckBox; Label1: TLabel; txtPath: TEdit; chkIncludeSubDir: TCheckBox; Label2: TLabel; txtFilter: TEdit; btnBrowse: TButton; CnFolderBrowserDialog1: TCnFolderBrowserDialog; GroupBox2: TGroupBox; btnClose: TButton; MemoLog: TMemo; procedure btnCloseClick(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure btnStopClick(Sender: TObject); procedure txtPathChange(Sender: TObject); procedure btnBrowseClick(Sender: TObject); procedure txtFilterChange(Sender: TObject); procedure chkIncludeSubDirClick(Sender: TObject); procedure chkFilenameClick(Sender: TObject); procedure chkDirectoryNameClick(Sender: TObject); procedure chkAttributesClick(Sender: TObject); procedure chkSizeClick(Sender: TObject); procedure chkLastWriteClick(Sender: TObject); procedure chkLastAccessClick(Sender: TObject); procedure chkCreationTimeClick(Sender: TObject); procedure CnFileSystemWatcher1Changed(Sender: TObject; E: _FileSystemEventArgs); procedure CnFileSystemWatcher1Created(Sender: TObject; E: _FileSystemEventArgs); procedure CnFileSystemWatcher1Deleted(Sender: TObject; E: _FileSystemEventArgs); procedure CnFileSystemWatcher1Renamed(Sender: TObject; E: _RenamedEventArgs); private procedure EnableRaisingEvents(AEnable: Boolean); public { Public declarations } end; var frmFileSystemWatcher: TfrmFileSystemWatcher; implementation {$R *.dfm} uses CNClrLib.Enums; procedure TfrmFileSystemWatcher.btnBrowseClick(Sender: TObject); begin if CnFolderBrowserDialog1.ShowDialog = TDialogResult.drOK then txtPath.Text := CnFolderBrowserDialog1.SelectedPath; end; procedure TfrmFileSystemWatcher.btnCloseClick(Sender: TObject); begin CnFileSystemWatcher1.EnableRaisingEvents := False; Close; end; procedure TfrmFileSystemWatcher.btnStartClick(Sender: TObject); begin EnableRaisingEvents(True); end; procedure TfrmFileSystemWatcher.btnStopClick(Sender: TObject); begin EnableRaisingEvents(False); end; procedure TfrmFileSystemWatcher.chkAttributesClick(Sender: TObject); begin if chkAttributes.Checked then CnFileSystemWatcher1.NotifyFilter := CnFileSystemWatcher1.NotifyFilter + [TNotifyFilters.nfAttributes] else CnFileSystemWatcher1.NotifyFilter := CnFileSystemWatcher1.NotifyFilter - [TNotifyFilters.nfAttributes]; end; procedure TfrmFileSystemWatcher.chkCreationTimeClick(Sender: TObject); begin if chkCreationTime.Checked then CnFileSystemWatcher1.NotifyFilter := CnFileSystemWatcher1.NotifyFilter + [TNotifyFilters.nfCreationTime] else CnFileSystemWatcher1.NotifyFilter := CnFileSystemWatcher1.NotifyFilter - [TNotifyFilters.nfCreationTime]; end; procedure TfrmFileSystemWatcher.chkDirectoryNameClick(Sender: TObject); begin if chkDirectoryName.Checked then CnFileSystemWatcher1.NotifyFilter := CnFileSystemWatcher1.NotifyFilter + [TNotifyFilters.nfDirectoryName] else CnFileSystemWatcher1.NotifyFilter := CnFileSystemWatcher1.NotifyFilter - [TNotifyFilters.nfDirectoryName]; end; procedure TfrmFileSystemWatcher.chkFilenameClick(Sender: TObject); begin if chkFilename.Checked then CnFileSystemWatcher1.NotifyFilter := CnFileSystemWatcher1.NotifyFilter + [TNotifyFilters.nfFileName] else CnFileSystemWatcher1.NotifyFilter := CnFileSystemWatcher1.NotifyFilter - [TNotifyFilters.nfFileName]; end; procedure TfrmFileSystemWatcher.chkIncludeSubDirClick(Sender: TObject); begin CnFileSystemWatcher1.IncludeSubdirectories := chkIncludeSubDir.Checked; end; procedure TfrmFileSystemWatcher.chkLastAccessClick(Sender: TObject); begin if chkLastAccess.Checked then CnFileSystemWatcher1.NotifyFilter := CnFileSystemWatcher1.NotifyFilter + [TNotifyFilters.nfLastAccess] else CnFileSystemWatcher1.NotifyFilter := CnFileSystemWatcher1.NotifyFilter - [TNotifyFilters.nfLastAccess]; end; procedure TfrmFileSystemWatcher.chkLastWriteClick(Sender: TObject); begin if chkLastWrite.Checked then CnFileSystemWatcher1.NotifyFilter := CnFileSystemWatcher1.NotifyFilter + [TNotifyFilters.nfLastWrite] else CnFileSystemWatcher1.NotifyFilter := CnFileSystemWatcher1.NotifyFilter - [TNotifyFilters.nfLastWrite]; end; procedure TfrmFileSystemWatcher.chkSizeClick(Sender: TObject); begin if chkSize.Checked then CnFileSystemWatcher1.NotifyFilter := CnFileSystemWatcher1.NotifyFilter + [TNotifyFilters.nfSize] else CnFileSystemWatcher1.NotifyFilter := CnFileSystemWatcher1.NotifyFilter - [TNotifyFilters.nfSize]; end; procedure TfrmFileSystemWatcher.CnFileSystemWatcher1Changed(Sender: TObject; E: _FileSystemEventArgs); var strChangeType: String; begin case E.ChangeType of WatcherChangeTypes_Created: strChangeType := 'Created'; WatcherChangeTypes_Deleted: strChangeType := 'Deleted'; WatcherChangeTypes_Changed: strChangeType := 'Changed'; WatcherChangeTypes_Renamed: strChangeType := 'Renamed'; else strChangeType := 'Created, Deleted, Changed, Renamed'; end; // Specify what is done when a file is changed, created, or deleted. MemoLog.Lines.Add('File: ' + E.FullPath + ' ' + strChangeType); MemoLog.Lines.Add(''); end; procedure TfrmFileSystemWatcher.CnFileSystemWatcher1Created(Sender: TObject; E: _FileSystemEventArgs); begin // Specify what is done when a file is created. MemoLog.Lines.Add('File: ' + E.FullPath + ' has been created)'); MemoLog.Lines.Add(''); end; procedure TfrmFileSystemWatcher.CnFileSystemWatcher1Deleted(Sender: TObject; E: _FileSystemEventArgs); begin // Specify what is done when a file is deleted. MemoLog.Lines.Add('File: ' + E.FullPath + ' has been deleted)'); MemoLog.Lines.Add(''); end; procedure TfrmFileSystemWatcher.CnFileSystemWatcher1Renamed(Sender: TObject; E: _RenamedEventArgs); begin // Specify what is done when a file is renamed. MemoLog.Lines.Add(Format('File: %s renamed to %s', [E.OldFullPath, E.FullPath])); end; procedure TfrmFileSystemWatcher.EnableRaisingEvents(AEnable: Boolean); begin CnFileSystemWatcher1.EnableRaisingEvents := AEnable; btnStart.Enabled := not AEnable; btnStop.Enabled := AEnable; GroupBox1.Enabled := not AEnable; btnBrowse.Enabled := not AEnable; txtPath.Enabled := not AEnable; chkIncludeSubDir.Enabled := not AEnable; end; procedure TfrmFileSystemWatcher.txtFilterChange(Sender: TObject); begin CnFileSystemWatcher1.Filter := txtFilter.Text; end; procedure TfrmFileSystemWatcher.txtPathChange(Sender: TObject); begin CnFileSystemWatcher1.Path := ''; if DirectoryExists(txtPath.Text) then CnFileSystemWatcher1.Path := txtPath.Text; end; end.
{*******************************************************} { } { Delphi Runtime Library } { } { File: TpcShrd.h } { Copyright (c) Microsoft Corporation } { } { Translator: Embarcadero Technologies, Inc. } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Winapi.TpcShrd; {$ALIGN ON} {$MINENUMSIZE 4} {$WEAKPACKAGEUNIT} {$HPPEMIT ''} {$HPPEMIT '#include "tpcshrd.h"'} {$HPPEMIT ''} interface uses Winapi.Windows; const MICROSOFT_TABLETPENSERVICE_PROPERTY = 'MicrosoftTabletPenServiceProperty'; {$EXTERNALSYM MICROSOFT_TABLETPENSERVICE_PROPERTY} TABLET_DISABLE_PRESSANDHOLD = $00000001; {$EXTERNALSYM TABLET_DISABLE_PRESSANDHOLD} TABLET_DISABLE_PENTAPFEEDBACK = $00000008; {$EXTERNALSYM TABLET_DISABLE_PENTAPFEEDBACK} TABLET_DISABLE_PENBARRELFEEDBACK = $00000010; {$EXTERNALSYM TABLET_DISABLE_PENBARRELFEEDBACK} TABLET_DISABLE_TOUCHUIFORCEON = $00000100; {$EXTERNALSYM TABLET_DISABLE_TOUCHUIFORCEON} TABLET_DISABLE_TOUCHUIFORCEOFF = $00000200; {$EXTERNALSYM TABLET_DISABLE_TOUCHUIFORCEOFF} TABLET_DISABLE_TOUCHSWITCH = $00008000; {$EXTERNALSYM TABLET_DISABLE_TOUCHSWITCH} TABLET_DISABLE_FLICKS = $00010000; {$EXTERNALSYM TABLET_DISABLE_FLICKS} TABLET_ENABLE_FLICKSONCONTEXT = $00020000; {$EXTERNALSYM TABLET_ENABLE_FLICKSONCONTEXT} TABLET_ENABLE_FLICKLEARNINGMODE = $00040000; {$EXTERNALSYM TABLET_ENABLE_FLICKLEARNINGMODE} TABLET_DISABLE_SMOOTHSCROLLING = $00080000; {$EXTERNALSYM TABLET_DISABLE_SMOOTHSCROLLING} TABLET_DISABLE_FLICKFALLBACKKEYS = $00100000; {$EXTERNALSYM TABLET_DISABLE_FLICKFALLBACKKEYS} TABLET_ENABLE_MULTITOUCHDATA = $01000000; {$EXTERNALSYM TABLET_ENABLE_MULTITOUCHDATA} MAX_PACKET_PROPERTY_COUNT = 32; {$EXTERNALSYM MAX_PACKET_PROPERTY_COUNT} MAX_PACKET_BUTTON_COUNT = 32; {$EXTERNALSYM MAX_PACKET_BUTTON_COUNT} IP_CURSOR_DOWN = $00000001; {$EXTERNALSYM IP_CURSOR_DOWN} IP_INVERTED = $00000002; {$EXTERNALSYM IP_INVERTED} IP_MARGIN = $00000004; {$EXTERNALSYM IP_MARGIN} type CURSOR_ID = DWORD; {$EXTERNALSYM CURSOR_ID} SYSTEM_EVENT = USHORT; {$EXTERNALSYM SYSTEM_EVENT} PTABLET_CONTEXT_ID = ^TABLET_CONTEXT_ID; TABLET_CONTEXT_ID = DWORD; {$EXTERNALSYM TABLET_CONTEXT_ID} type PROPERTY_UNITS = type Integer; {$EXTERNALSYM PROPERTY_UNITS} const PROPERTY_UNITS_DEFAULT = 0; {$EXTERNALSYM PROPERTY_UNITS_DEFAULT} PROPERTY_UNITS_INCHES = 1; {$EXTERNALSYM PROPERTY_UNITS_INCHES} PROPERTY_UNITS_CENTIMETERS = 2; {$EXTERNALSYM PROPERTY_UNITS_CENTIMETERS} PROPERTY_UNITS_DEGREES = 3; {$EXTERNALSYM PROPERTY_UNITS_DEGREES} PROPERTY_UNITS_RADIANS = 4; {$EXTERNALSYM PROPERTY_UNITS_RADIANS} PROPERTY_UNITS_SECONDS = 5; {$EXTERNALSYM PROPERTY_UNITS_SECONDS} PROPERTY_UNITS_POUNDS = 6; {$EXTERNALSYM PROPERTY_UNITS_POUNDS} PROPERTY_UNITS_GRAMS = 7; {$EXTERNALSYM PROPERTY_UNITS_GRAMS} PROPERTY_UNITS_SILINEAR = 8; {$EXTERNALSYM PROPERTY_UNITS_SILINEAR} PROPERTY_UNITS_SIROTATION = 9; {$EXTERNALSYM PROPERTY_UNITS_SIROTATION} PROPERTY_UNITS_ENGLINEAR = 10; {$EXTERNALSYM PROPERTY_UNITS_ENGLINEAR} PROPERTY_UNITS_ENGROTATION = 11; {$EXTERNALSYM PROPERTY_UNITS_ENGROTATION} PROPERTY_UNITS_SLUGS = 12; {$EXTERNALSYM PROPERTY_UNITS_SLUGS} PROPERTY_UNITS_KELVIN = 13; {$EXTERNALSYM PROPERTY_UNITS_KELVIN} PROPERTY_UNITS_FAHRENHEIT = 14; {$EXTERNALSYM PROPERTY_UNITS_FAHRENHEIT} PROPERTY_UNITS_AMPERE = 15; {$EXTERNALSYM PROPERTY_UNITS_AMPERE} PROPERTY_UNITS_CANDELA = 16; {$EXTERNALSYM PROPERTY_UNITS_CANDELA} type tagXFORM = record eM11: Single; eM12: Single; eM21: Single; eM22: Single; eDx: Single; eDy: Single; end; {$EXTERNALSYM tagXFORM} XFORM = tagXFORM; {$EXTERNALSYM XFORM} TXForm = tagXFORM; PXForm = ^TXForm; SYSTEM_EVENT_DATA = record bModifier: Byte; wKey: WCHAR; xPos: Integer; yPos: Integer; bCursorMode: Byte; dwButtonState: DWORD; end; {$EXTERNALSYM SYSTEM_EVENT_DATA} tagSYSTEM_EVENT_DATA = SYSTEM_EVENT_DATA; {$EXTERNALSYM tagSYSTEM_EVENT_DATA} TSystemEventData = SYSTEM_EVENT_DATA; PSystemEventData = ^TSystemEventData; STROKE_RANGE = record iStrokeBegin: Cardinal; iStrokeEnd: Cardinal; end; {$EXTERNALSYM STROKE_RANGE} tagSTROKE_RANGE = STROKE_RANGE; {$EXTERNALSYM tagSTROKE_RANGE} TStrokeRange = STROKE_RANGE; PStrokeRange = ^TStrokeRange; PROPERTY_METRICS = record nLogicalMin: Integer; nLogicalMax: Integer; Units: PROPERTY_UNITS; fResolution: Single; end; {$EXTERNALSYM PROPERTY_METRICS} _PROPERTY_METRICS = PROPERTY_METRICS; {$EXTERNALSYM _PROPERTY_METRICS} TPropertyMetrics = PROPERTY_METRICS; PPropertyMetrics = ^TPropertyMetrics; PACKET_PROPERTY = record guid: TGUID; PropertyMetrics: TPropertyMetrics; end; {$EXTERNALSYM PACKET_PROPERTY} _PACKET_PROPERTY = PACKET_PROPERTY; {$EXTERNALSYM _PACKET_PROPERTY} TPacketProperty = PACKET_PROPERTY; PPacketProperty = ^TPacketProperty; PACKET_DESCRIPTION = record cbPacketSize: Cardinal; cPacketProperties: Cardinal; pPacketProperties: PPacketProperty; cButtons: Cardinal; pguidButtons: PGUID; end; {$EXTERNALSYM PACKET_DESCRIPTION} _PACKET_DESCRIPTION = PACKET_DESCRIPTION; {$EXTERNALSYM _PACKET_DESCRIPTION} TPacketDescription = PACKET_DESCRIPTION; PPacketDescription = ^TPacketDescription; implementation end.
unit BillContentExportQry; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap; type TBillContentExportW = class(TDSWrap) private FStoreHouse: TFieldWrap; FBillTitle: TFieldWrap; FPriceR: TFieldWrap; FID: TFieldWrap; FBillNumber: TFieldWrap; FAmount: TFieldWrap; FBarcode: TFieldWrap; FBatchNumber: TFieldWrap; FBillDate: TFieldWrap; FCustomsDeclarationNumber: TFieldWrap; FDescriptionComponentName: TFieldWrap; FPriceD: TFieldWrap; FPriceD1: TFieldWrap; FPriceD2: TFieldWrap; FPriceD3: TFieldWrap; FDatasheet: TFieldWrap; FDiagram: TFieldWrap; FDocumentNumber: TFieldWrap; FDollar: TFieldWrap; FDrawing: TFieldWrap; FEuro: TFieldWrap; FImage: TFieldWrap; FLoadDate: TFieldWrap; FOriginCountry: TFieldWrap; FOriginCountryCode: TFieldWrap; FPackaging: TFieldWrap; FPriceE: TFieldWrap; FPriceE1: TFieldWrap; FPriceE2: TFieldWrap; FPriceR1: TFieldWrap; FPriceR2: TFieldWrap; FProducer: TFieldWrap; FReleaseDate: TFieldWrap; FSaleCount: TFieldWrap; FSaleD: TFieldWrap; FSaleE: TFieldWrap; FSaleR: TFieldWrap; FSeller: TFieldWrap; FShipmentDate: TFieldWrap; FStorage: TFieldWrap; FStoragePlace: TFieldWrap; FSumSaleR: TFieldWrap; FValue: TFieldWrap; FWidth: TFieldWrap; procedure DoAfterOpen(Sender: TObject); procedure OnDataSheetGetText(Sender: TField; var Text: String; DisplayText: Boolean); protected procedure InitFields; virtual; public constructor Create(AOwner: TComponent); override; procedure AfterConstruction; override; procedure ApplyNotShipmentFilter; procedure ApplyShipmentFilter; procedure SetDisplayFormat(const AFields: Array of TField); property StoreHouse: TFieldWrap read FStoreHouse; property BillTitle: TFieldWrap read FBillTitle; property PriceR: TFieldWrap read FPriceR; property ID: TFieldWrap read FID; property BillNumber: TFieldWrap read FBillNumber; property Amount: TFieldWrap read FAmount; property Barcode: TFieldWrap read FBarcode; property BatchNumber: TFieldWrap read FBatchNumber; property BillDate: TFieldWrap read FBillDate; property CustomsDeclarationNumber: TFieldWrap read FCustomsDeclarationNumber; property DescriptionComponentName: TFieldWrap read FDescriptionComponentName; property PriceD: TFieldWrap read FPriceD; property PriceD1: TFieldWrap read FPriceD1; property PriceD2: TFieldWrap read FPriceD2; property PriceD3: TFieldWrap read FPriceD3; property Datasheet: TFieldWrap read FDatasheet; property Diagram: TFieldWrap read FDiagram; property DocumentNumber: TFieldWrap read FDocumentNumber; property Dollar: TFieldWrap read FDollar; property Drawing: TFieldWrap read FDrawing; property Euro: TFieldWrap read FEuro; property Image: TFieldWrap read FImage; property LoadDate: TFieldWrap read FLoadDate; property OriginCountry: TFieldWrap read FOriginCountry; property OriginCountryCode: TFieldWrap read FOriginCountryCode; property Packaging: TFieldWrap read FPackaging; property PriceE: TFieldWrap read FPriceE; property PriceE1: TFieldWrap read FPriceE1; property PriceE2: TFieldWrap read FPriceE2; property PriceR1: TFieldWrap read FPriceR1; property PriceR2: TFieldWrap read FPriceR2; property Producer: TFieldWrap read FProducer; property ReleaseDate: TFieldWrap read FReleaseDate; property SaleCount: TFieldWrap read FSaleCount; property SaleD: TFieldWrap read FSaleD; property SaleE: TFieldWrap read FSaleE; property SaleR: TFieldWrap read FSaleR; property Seller: TFieldWrap read FSeller; property ShipmentDate: TFieldWrap read FShipmentDate; property Storage: TFieldWrap read FStorage; property StoragePlace: TFieldWrap read FStoragePlace; property SumSaleR: TFieldWrap read FSumSaleR; property Value: TFieldWrap read FValue; property Width: TFieldWrap read FWidth; end; TQryBillContentExport = class(TQueryBase) procedure FDQueryCalcFields(DataSet: TDataSet); private FW: TBillContentExportW; procedure DoBeforeOpen(Sender: TObject); { Private declarations } protected procedure DoOnCalcFields; procedure InitFieldDefs; virtual; public constructor Create(AOwner: TComponent); override; function SearchByPeriod(ABeginDate, AEndDate: TDate): Integer; property W: TBillContentExportW read FW; { Public declarations } end; implementation uses NotifyEvents, System.IOUtils, StrHelper, System.StrUtils; constructor TBillContentExportW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', 'ID', True); FBillTitle := TFieldWrap.Create(Self, 'BillTitle', 'Счёт'); FBillNumber := TFieldWrap.Create(Self, 'BillNumber'); FBillDate := TFieldWrap.Create(Self, 'BillDate'); FShipmentDate := TFieldWrap.Create(Self, 'ShipmentDate'); FWidth := TFieldWrap.Create(Self, 'Width'); FValue := TFieldWrap.Create(Self, 'Value', 'Наименование'); FStoreHouse := TFieldWrap.Create(Self, 'StoreHouse', 'Склад'); FProducer := TFieldWrap.Create(Self, 'Producer', 'Производитель'); FDescriptionComponentName := TFieldWrap.Create(Self, 'DescriptionComponentName', 'Краткое описание'); FDatasheet := TFieldWrap.Create(Self, 'DataSheet', 'Спецификация'); FDiagram := TFieldWrap.Create(Self, 'Diagram', 'Схема'); FDrawing := TFieldWrap.Create(Self, 'Drawing', 'Чертёж'); FImage := TFieldWrap.Create(Self, 'Image', 'Изображение'); FReleaseDate := TFieldWrap.Create(Self, 'ReleaseDate', 'Дата выпуска'); FAmount := TFieldWrap.Create(Self, 'Amount', 'Остаток'); FPackaging := TFieldWrap.Create(Self, 'Packaging', 'Упаковка'); FPriceR := TFieldWrap.Create(Self, 'PriceR', '₽'); FPriceD := TFieldWrap.Create(Self, 'PriceD', '$'); FPriceE := TFieldWrap.Create(Self, 'PriceE', '€'); FPriceR1 := TFieldWrap.Create(Self, 'PriceR1', '₽'); FPriceD1 := TFieldWrap.Create(Self, 'PriceD1', '$'); FPriceE1 := TFieldWrap.Create(Self, 'PriceE1', '€'); FPriceR2 := TFieldWrap.Create(Self, 'PriceR2', '₽'); FPriceD2 := TFieldWrap.Create(Self, 'PriceD2', '$'); FPriceE2 := TFieldWrap.Create(Self, 'PriceE2', '€'); FOriginCountryCode := TFieldWrap.Create(Self, 'OriginCountryCode', 'Цифровой код'); FOriginCountry := TFieldWrap.Create(Self, 'OriginCountry', 'Название'); FBatchNumber := TFieldWrap.Create(Self, 'BatchNumber', 'Номер партии'); FCustomsDeclarationNumber := TFieldWrap.Create(Self, 'CustomsDeclarationNumber', 'Номер таможенной декларации'); FStorage := TFieldWrap.Create(Self, 'Storage', 'Стеллаж №'); FStoragePlace := TFieldWrap.Create(Self, 'StoragePlace', 'Место №'); FSeller := TFieldWrap.Create(Self, 'Seller', 'Организация-продавец'); FDocumentNumber := TFieldWrap.Create(Self, 'DocumentNumber', '№ документа'); FBarcode := TFieldWrap.Create(Self, 'Barcode', 'Цифровой код'); FLoadDate := TFieldWrap.Create(Self, 'LoadDate', 'Дата загрузки'); FDollar := TFieldWrap.Create(Self, 'Dollar', '$'); FEuro := TFieldWrap.Create(Self, 'Euro', '€'); FSaleCount := TFieldWrap.Create(Self, 'SaleCount', 'Кол-во продажи'); FSaleR := TFieldWrap.Create(Self, 'SaleR', '₽'); FSaleD := TFieldWrap.Create(Self, 'SaleD', '$'); FSaleE := TFieldWrap.Create(Self, 'SaleE', '€'); FSumSaleR := TFieldWrap.Create(Self, 'SumSaleR', '₽'); TNotifyEventWrap.Create(AfterOpen, DoAfterOpen, EventList); end; procedure TBillContentExportW.AfterConstruction; begin inherited; if DataSet.Active then InitFields; end; procedure TBillContentExportW.DoAfterOpen(Sender: TObject); begin SetFieldsRequired(False); SetFieldsReadOnly(False); InitFields; end; procedure TBillContentExportW.InitFields; begin SetDisplayFormat([PriceR2.F, PriceD2.F, PriceE2.F, PriceR1.F, PriceD1.F, PriceE1.F, PriceR.F, PriceD.F, PriceE.F, SaleR.F, SaleD.F, SaleE.F, SumSaleR.F]); Datasheet.F.OnGetText := OnDataSheetGetText; Diagram.F.OnGetText := OnDataSheetGetText; Drawing.F.OnGetText := OnDataSheetGetText; Image.F.OnGetText := OnDataSheetGetText; BillTitle.F.FieldKind := fkInternalCalc; end; procedure TBillContentExportW.OnDataSheetGetText(Sender: TField; var Text: String; DisplayText: Boolean); var S: string; begin S := Sender.AsString; if DisplayText and not S.IsEmpty then Text := TPath.GetFileNameWithoutExtension(S); end; procedure TBillContentExportW.SetDisplayFormat(const AFields: Array of TField); var I: Integer; begin Assert(Length(AFields) > 0); for I := Low(AFields) to High(AFields) do begin // Если поле не TNumericField - значит запрос вернул 0 записей и не удалось определить тип поля if (AFields[I] is TNumericField) then (AFields[I] as TNumericField).DisplayFormat := '###,##0.00'; end; end; constructor TQryBillContentExport.Create(AOwner: TComponent); begin inherited; FW := TBillContentExportW.Create(FDQuery); TNotifyEventWrap.Create(W.BeforeOpen, DoBeforeOpen, W.EventList); end; procedure TQryBillContentExport.DoOnCalcFields; begin inherited; W.BillTitle.F.AsString := Format('Счёт №%s от %s%s', [Format('%.' + W.Width.F.AsString + 'd', [W.BillNumber.F.AsInteger]), FormatDateTime('dd.mm.yyyy', W.BillDate.F.AsDateTime), IfThen(W.ShipmentDate.F.IsNull, '', Format(' отгружен %s', [FormatDateTime('dd.mm.yyyy', W.ShipmentDate.F.AsDateTime)]))]); end; procedure TQryBillContentExport.FDQueryCalcFields(DataSet: TDataSet); begin inherited; DoOnCalcFields; end; function TQryBillContentExport.SearchByPeriod(ABeginDate, AEndDate: TDate): Integer; var AED: TDate; ANewSQL: string; ASD: TDate; AStipulation: string; begin if ABeginDate <= AEndDate then begin ASD := ABeginDate; AED := AEndDate; end else begin ASD := AEndDate; AED := ABeginDate; end; // Делаем замену в SQL запросе AStipulation := Format('%s >= date(''%s'')', [W.BillDate.FieldName, FormatDateTime('YYYY-MM-DD', ASD)]); ANewSQL := ReplaceInSQL(SQL, AStipulation, 0); // Делаем замену в SQL запросе AStipulation := Format('%s <= date(''%s'')', [W.BillDate.FieldName, FormatDateTime('YYYY-MM-DD', AED)]); ANewSQL := ReplaceInSQL(ANewSQL, AStipulation, 1); FDQuery.SQL.Text := ANewSQL; W.RefreshQuery; Result := FDQuery.RecordCount; end; {$R *.dfm} procedure TBillContentExportW.ApplyNotShipmentFilter; begin DataSet.Filter := Format('%s is null', [ShipmentDate.FieldName]); DataSet.Filtered := True; end; procedure TBillContentExportW.ApplyShipmentFilter; begin DataSet.Filter := Format('%s is not null', [ShipmentDate.FieldName]); DataSet.Filtered := True; end; procedure TQryBillContentExport.DoBeforeOpen(Sender: TObject); begin InitFieldDefs; W.CreateDefaultFields(False); W.InitFields; end; procedure TQryBillContentExport.InitFieldDefs; begin if FDQuery.FieldDefs.Count > 0 then begin FDQuery.FieldDefs.Clear; FDQuery.Fields.Clear; end; FDQuery.FieldDefs.Update; // Вычисляемое название счёта FDQuery.FieldDefs.Add(W.BillTitle.FieldName, ftWideString, 100); end; end.
unit mCoverSheetDisplayPanel_CPRS_Labs; { ================================================================================ * * Application: Demo * Developer: doma.user@domain.ext * Site: Salt Lake City ISC * Date: 2015-12-21 * * Description: Lab result panel for CPRS Coversheet. * * Notes: * ================================================================================ } interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.ImageList, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Menus, Vcl.ImgList, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Buttons, iCoverSheetIntf, mCoverSheetDisplayPanel_CPRS, oDelimitedString; type TfraCoverSheetDisplayPanel_CPRS_Labs = class(TfraCoverSheetDisplayPanel_CPRS) private { Private declarations } protected { Overridded events - TfraCoverSheetDisplayPanel_CPRS } procedure OnAddItems(aList: TStrings); override; procedure OnGetDetail(aRec: TDelimitedString; aResult: TStrings); override; public constructor Create(aOwner: TComponent); override; end; var fraCoverSheetDisplayPanel_CPRS_Labs: TfraCoverSheetDisplayPanel_CPRS_Labs; implementation uses uCore, ORFn, ORNet; {$R *.dfm} { TfraCoverSheetDisplayPanel_CPRS_Labs } constructor TfraCoverSheetDisplayPanel_CPRS_Labs.Create(aOwner: TComponent); begin inherited; AddColumn(0, 'Lab Test'); AddColumn(1, 'Date/Time'); CollapseColumns; end; procedure TfraCoverSheetDisplayPanel_CPRS_Labs.OnGetDetail(aRec: TDelimitedString; aResult: TStrings); var aID: string; begin aID := aRec.GetPiece(1); if aID = '' then Exit; if Copy(aRec.GetPiece(1), 1, 2) = '0;' then Exit; if StrToFloatDef(Copy(aID, 1, Pos(';', aID) - 1), -1) < 1 then Exit; CallVistA(CPRSParams.DetailRPC, [Patient.DFN, aRec.GetPieceAsInteger(1), aRec.GetPiece(1)], aResult); end; procedure TfraCoverSheetDisplayPanel_CPRS_Labs.OnAddItems(aList: TStrings); var aRec: TDelimitedString; aStr: string; begin try lvData.Items.BeginUpdate; for aStr in aList do begin aRec := TDelimitedString.Create(aStr); if lvData.Items.Count = 0 then { Executes before any item is added } if aRec.GetPieceEquals(1, 0) and (aList.Count = 1) then begin CollapseColumns; lvData.Items.Add.Caption := aRec.GetPiece(2); Break; end else if aRec.GetPieceIsNull(1) and (aList.Count = 1) then CollapseColumns else ExpandColumns; with lvData.Items.Add do begin Caption := MixedCase(aRec.GetPiece(2)); if aRec.GetPieceIsNotNull(1) then begin SubItems.Add(FormatDateTime(DT_FORMAT, aRec.GetPieceAsTDateTime(3))); Data := aRec; end; end; end; finally lvData.Items.EndUpdate; end; end; end.
unit UntLibPedido; interface uses FMX.Layouts, FMX.StdCtrls, FMX.Types, FMX.Objects, FMX.Dialogs, FMX.Forms, System.Classes, UntLib; type TStatusPedido = (spNenhum, spAberto, spFechado, spAguardando, spEnviado); TPedidoAtual = class private class var FIconCart : TLayout; FToolBar : TToolBar; FStatusPedido : TStatusPedido; FNumPedido : Integer; FFormCarrinho : TComponentClass; class procedure ClickCart(Sender: TObject); public class procedure MostrarOcultarCarrinho; class function ExistePedidoAberto: Boolean; class property IconCart : TLayout read FIconCart write FIconCart; class property ToolBar : TToolBar read FToolBar write FToolBar; //Informações sobre PedidoAtual class property Status : TStatusPedido read FStatusPedido write FStatusPedido; class property NumPedido : Integer read FNumPedido write FNumPedido; class property FormCarrinho : TComponentClass read FFormCarrinho write FFormCarrinho; end; implementation { TPedidoAtual } class procedure TPedidoAtual.ClickCart(Sender: TObject); begin TLibrary.AbrirForm(FFormCarrinho); end; class function TPedidoAtual.ExistePedidoAberto: Boolean; begin Result := FNumPedido > 0; end; class procedure TPedidoAtual.MostrarOcultarCarrinho; var I : Integer; begin if (TToolBar(ToolBar).FindComponent(IconCart.Name) = nil) then ToolBar.AddObject(TFMXObject(IconCart)); IconCart.Align := TAlignLayout.Right; IconCart.BringToFront; IconCart.HitTest := True; IconCart.OnClick := ClickCart; IconCart.Visible := (Status = spAberto); if IconCart.Visible then begin for I := 0 to Pred(IconCart.ControlsCount) do begin if ((IconCart.Controls[I]) is TPath) then begin ((IconCart.Controls[I]) as TPath).OnClick := ClickCart; ((IconCart.Controls[I]) as TPath).HitTest := True; end; if ((IconCart.Controls[I]) is TSpeedButton) then ((IconCart.Controls[I]) as TSpeedButton).OnClick := ClickCart; end; end; end; end.
unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Spin, ImgList, ComCtrls, ToolWin; type TMainForm = class(TForm) PersonsList: TListBox; GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; FNameEdit: TEdit; LNameEdit: TEdit; DocEdit: TEdit; AddrEdit: TEdit; PhoneEdit: TEdit; AgeEdit: TSpinEdit; OpenDlg: TOpenDialog; SaveDlg: TSaveDialog; ToolBar1: TToolBar; AddBtn: TToolButton; EditBtn: TToolButton; RestBtn: TToolButton; DelBtn: TToolButton; ClearBtn: TToolButton; ToolButton6: TToolButton; OpenBtn: TToolButton; SaveBtn: TToolButton; ToolButton9: TToolButton; ImageList1: TImageList; procedure ToolButton1Click(Sender: TObject); procedure ToolButton2Click(Sender: TObject); procedure ToolButton3Click(Sender: TObject); procedure ToolButton4Click(Sender: TObject); procedure ToolButton5Click(Sender: TObject); procedure ToolButton7Click(Sender: TObject); procedure ToolButton8Click(Sender: TObject); procedure ToolButton9Click(Sender: TObject); private { Private declarations } public { Public declarations } end; THuman = class FirstName: String; LastName: String; Age: Integer; Document: String; Address: String; Phone: String; constructor Create(AName: String); end; var MainForm: TMainForm; implementation {$R *.DFM} constructor THuman.Create(AName: String); begin inherited Create; FirstName := AName; end; procedure TMainForm.ToolButton1Click(Sender: TObject); begin PersonsList.Items.AddObject('Unknown', THuman.Create('Unknown')); end; procedure TMainForm.ToolButton2Click(Sender: TObject); begin with PersonsList, PersonsList.Items do begin if ItemIndex = -1 then Exit; if not Assigned(Objects[ItemIndex]) then Objects[ItemIndex] := THuman.Create(Items[ItemIndex]); with Objects[ItemIndex] as THuman do begin FNameEdit.Text := FirstName; LNameEdit.Text := LastName; AgeEdit.Value := Age; DocEdit.Text := Document; AddrEdit.Text := Address; PhoneEdit.Text := Phone; end; end; end; procedure TMainForm.ToolButton3Click(Sender: TObject); begin if PersonsList.ItemIndex = -1 then begin ShowMessage('Не выбран элемент'); Exit; end; with PersonsList do with Items.Objects[ItemIndex] as THuman do begin FirstName := FNameEdit.Text; LastName := LNameEdit.Text; Age := AgeEdit.Value; Document := DocEdit.Text; Address := AddrEdit.Text; Phone := PhoneEdit.Text; Items[ItemIndex] := FirstName+' '+Copy(LastName,1,1); end; FNameEdit.Clear; LNameEdit.Clear; AgeEdit.Clear; DocEdit.Clear; AddrEdit.Clear; PhoneEdit.Clear; end; procedure TMainForm.ToolButton4Click(Sender: TObject); begin with PersonsList do Items.Delete(ItemIndex); end; procedure TMainForm.ToolButton5Click(Sender: TObject); begin PersonsList.Items.Clear; end; procedure TMainForm.ToolButton7Click(Sender: TObject); var F: TextFile; i: Integer; begin try with OpenDlg, PersonsList.Items do begin if Not Execute then Exit; LoadFromFile(FileName); AssignFile(F, Copy(FileName,1,Length(FileName)-4)+'.lso'); Reset(F); i := 0; while Not EOF(F) do begin Objects[i] := THuman.Create(''); Readln(F, (Objects[i] as THuman).FirstName); Readln(F, (Objects[i] as THuman).LastName); Readln(F, (Objects[i] as THuman).Age); Readln(F, (Objects[i] as THuman).Document); Readln(F, (Objects[i] as THuman).Address); Readln(F, (Objects[i] as THuman).Phone); Inc(i); end; CloseFile(F); end; except on E: EFOpenError do ShowMessage('Ошибка открытия файла'); end;end; procedure TMainForm.ToolButton8Click(Sender: TObject); var F: TextFile; i: Integer; begin try with SaveDlg, PersonsList.Items do begin if Not Execute then Exit; SaveToFile(FileName); AssignFile(F, Copy(FileName,1,Length(FileName)-4)+'.lso'); Rewrite(F); for i := 0 to Count - 1 do if Objects[i] <> Nil then begin Writeln(F, (Objects[i] as THuman).FirstName); Writeln(F, (Objects[i] as THuman).LastName); Writeln(F, (Objects[i] as THuman).Age); Writeln(F, (Objects[i] as THuman).Document); Writeln(F, (Objects[i] as THuman).Address); Writeln(F, (Objects[i] as THuman).Phone); end; CloseFile(F); end; except on E: EFOpenError do ShowMessage('Ошибка открытия файла'); end; end; procedure TMainForm.ToolButton9Click(Sender: TObject); begin Close; end; end.
unit Backlog; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopupDetail, RzButton, RzTabs, Vcl.StdCtrls, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, Vcl.Mask, RzEdit, RzDBEdit; type TfrmBacklog = class(TfrmBasePopupDetail) edAppAmount: TRzDBNumericEdit; dteLastTransactionDate: TRzDBDateTimeEdit; RzDBNumericEdit1: TRzDBNumericEdit; RzDBNumericEdit2: TRzDBNumericEdit; RzDBNumericEdit3: TRzDBNumericEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } protected procedure Save; override; procedure Cancel; override; procedure BindToObject; override; function ValidEntry: boolean; override; end; implementation {$R *.dfm} uses LoanData, IFinanceGlobal; procedure TfrmBacklog.BindToObject; begin inherited; end; procedure TfrmBacklog.Cancel; begin inherited; end; procedure TfrmBacklog.FormCreate(Sender: TObject); begin inherited; dteLastTransactionDate.Date := ifn.AppDate; end; procedure TfrmBacklog.Save; begin inherited; end; function TfrmBacklog.ValidEntry: boolean; begin Result := true; end; end.
unit UnCategoriaRegistroModelo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, FMTBcd, DB, DBClient, Provider, SqlExpr, { helsonsant} Util, DataUtil, UnModelo, Dominio; type TCategoriaRegistroModelo = class(TModelo) procedure cdsBeforePost(DataSet: TDataSet); protected function GetSql: TSql; override; public function IncluirCategoria(const Categoria: Integer; const Descricao: string): TCategoriaRegistroModelo; end; implementation {$R *.dfm} { TCategoriaRegistroModelo } function TCategoriaRegistroModelo.GetSql: TSql; var _exibirRegistrosExcluidos: Boolean; _configuracao: string; begin _exibirRegistrosExcluidos := False; _configuracao := Self.FConfiguracoes.Ler('ExibirRegistrosExcluidos'); if _configuracao = '1' then _exibirRegistrosExcluidos := True; if Self.FDominio = nil then begin Self.FDominio := TDominio.Create('CategoriaRegistroModelo'); Self.FDominio.Sql .Select('CATS_OID, CAT_OID, CATS_COD, CATS_DES, ' + 'REC_STT, REC_INS, REC_UPD, REC_DEL') .From('CATS') .Where(Self.FUtil .iff(not _exibirRegistrosExcluidos, Format('REC_STT = %s', [IntToStr(Ord(srAtivo))]), '')) .Order('CATS_DES') .MetaDados('CATS_OID IS NULL'); Self.FDominio.Campos .Adicionar(TFabricaDeCampos.ObterCampoChave('CATS_OID')) .Adicionar(TFabricaDeCampos.ObterCampo('CAT_OID') .Descricao('Tipo') .TornarObrigatorio) .Adicionar(TFabricaDeCampos.ObterCampoVisivel('CATS_DES', 'Categoria', 30) .TornarObrigatorio) end; Result := Self.FDominio.Sql; end; procedure TCategoriaRegistroModelo.cdsBeforePost(DataSet: TDataSet); begin inherited; Self.FDataUtil.OidVerify(DataSet, 'cats_oid'); end; function TCategoriaRegistroModelo.IncluirCategoria( const Categoria: Integer; const Descricao: string): TCategoriaRegistroModelo; begin Self.Incluir; Self.cds.FieldByName('cat_oid').AsString := IntToStr(Categoria); Self.cds.FieldByName('cats_des').AsString := Descricao; Self.cds.Post; Self.cds.ApplyUpdates(-1); Result := Self; end; initialization RegisterClass(TCategoriaRegistroModelo); end.
unit WiseEncoder; interface uses Windows, Math, ExtCtrls, cbw, StopWatch, SysUtils, WiseHardware, WiseDaq, WisePort; type TWiseEncoderSimState = ( Idle = 0, MovingCCW = 1, MovingCW = 2 ); type TWiseEncoder = class(TWiseMultiPort) private fNativeTicks: integer; // Native number of ticks fIsGray: boolean; // Returns Gray code fValue: integer; protected { Protected declarations } public constructor Create(Name: string; isGray: boolean; var daqids: array of TDaqId; lastMask: integer; nativeTicks: integer; Timeout: TLargeInteger); overload; constructor Create(Name: string; isGray: boolean; var daqids: array of TDaqId; lastMask: integer; nativeTicks: integer); overload; constructor Create(Name: string; isGray: boolean; specs: TWiseMultiPortSpecs; nativeTicks: integer); overload; function GetValue(): integer; // reads the actual encoder property Ticks: integer read fNativeTicks; property Value: integer read GetValue; { Public declarations } published { Published declarations } end; { -- TWiseDomeEncoder -- } type TWiseDomeEncoder = class(TWiseEncoder) private fCaliTicks: integer; // ticks at calibration point ticksPerDeg: real; fCaliAz: real; // azimuth at calibration point caliTime: TDateTime; // last calibration time {$ifdef SIMULATE_DOME_ENCODER} sim_ticks: integer; sim_ticks_timer: TTimer; fSim_dir: TWiseDirection; procedure onSimTicksTimer(Sender: TObject); {$endif SIMULATE_DOME_ENCODER} function GetValue: integer; public constructor Create(name: string; daqids: array of TDaqId; lastMask: integer; travelTicks: integer; nativeTicks: integer); destructor Destroy; override; function GetAzimuth: real; procedure Calibrate(az: real); function ShortestDeltaValue(prevValue: integer): integer; // returns ticks distance between a previous and current values {$ifdef SIMULATE_DOME_ENCODER} procedure SimulateMovement(dir: TWiseDirection); {$endif SIMULATE_DOME_ENCODER} property Azimuth: real read GetAzimuth write Calibrate; property CaliTicks: integer read fCaliTicks; property CaliAz: real read fCaliAz; property Value: integer read GetValue; end; { -- TWiseFocusEncoder -- } type TWiseFocusEncoder = class(TWiseEncoder) private public constructor Create(name: string; specs: TWiseMultiPortSpecs); function GetValue: integer; property Value: integer read GetValue; end; implementation const Gray2BCD : Array[0..1023] of integer = ( 0, 1, 3, 2, 7, 6, 4, 5, 15, 14, 12, 13, 8, 9, 11, 10, 31, 30, 28, 29, 24, 25, 27, 26, 16, 17, 19, 18, 23, 22, 20, 21, 63, 62, 60, 61, 56, 57, 59, 58, 48, 49, 51, 50, 55, 54, 52, 53, 32, 33, 35, 34, 39, 38, 36, 37, 47, 46, 44, 45, 40, 41, 43, 42, 127, 126, 124, 125, 120, 121, 123, 122, 112, 113, 115, 114, 119, 118, 116, 117, 96, 97, 99, 98, 103, 102, 100, 101, 111, 110, 108, 109, 104, 105, 107, 106, 64, 65, 67, 66, 71, 70, 68, 69, 79, 78, 76, 77, 72, 73, 75, 74, 95, 94, 92, 93, 88, 89, 91, 90, 80, 81, 83, 82, 87, 86, 84, 85, 255, 254, 252, 253, 248, 249, 251, 250, 240, 241, 243, 242, 247, 246, 244, 245, 224, 225, 227, 226, 231, 230, 228, 229, 239, 238, 236, 237, 232, 233, 235, 234, 192, 193, 195, 194, 199, 198, 196, 197, 207, 206, 204, 205, 200, 201, 203, 202, 223, 222, 220, 221, 216, 217, 219, 218, 208, 209, 211, 210, 215, 214, 212, 213, 128, 129, 131, 130, 135, 134, 132, 133, 143, 142, 140, 141, 136, 137, 139, 138, 159, 158, 156, 157, 152, 153, 155, 154, 144, 145, 147, 146, 151, 150, 148, 149, 191, 190, 188, 189, 184, 185, 187, 186, 176, 177, 179, 178, 183, 182, 180, 181, 160, 161, 163, 162, 167, 166, 164, 165, 175, 174, 172, 173, 168, 169, 171, 170, 511, 510, 508, 509, 504, 505, 507, 506, 496, 497, 499, 498, 503, 502, 500, 501, 480, 481, 483, 482, 487, 486, 484, 485, 495, 494, 492, 493, 488, 489, 491, 490, 448, 449, 451, 450, 455, 454, 452, 453, 463, 462, 460, 461, 456, 457, 459, 458, 479, 478, 476, 477, 472, 473, 475, 474, 464, 465, 467, 466, 471, 470, 468, 469, 384, 385, 387, 386, 391, 390, 388, 389, 399, 398, 396, 397, 392, 393, 395, 394, 415, 414, 412, 413, 408, 409, 411, 410, 400, 401, 403, 402, 407, 406, 404, 405, 447, 446, 444, 445, 440, 441, 443, 442, 432, 433, 435, 434, 439, 438, 436, 437, 416, 417, 419, 418, 423, 422, 420, 421, 431, 430, 428, 429, 424, 425, 427, 426, 256, 257, 259, 258, 263, 262, 260, 261, 271, 270, 268, 269, 264, 265, 267, 266, 287, 286, 284, 285, 280, 281, 283, 282, 272, 273, 275, 274, 279, 278, 276, 277, 319, 318, 316, 317, 312, 313, 315, 314, 304, 305, 307, 306, 311, 310, 308, 309, 288, 289, 291, 290, 295, 294, 292, 293, 303, 302, 300, 301, 296, 297, 299, 298, 383, 382, 380, 381, 376, 377, 379, 378, 368, 369, 371, 370, 375, 374, 372, 373, 352, 353, 355, 354, 359, 358, 356, 357, 367, 366, 364, 365, 360, 361, 363, 362, 320, 321, 323, 322, 327, 326, 324, 325, 335, 334, 332, 333, 328, 329, 331, 330, 351, 350, 348, 349, 344, 345, 347, 346, 336, 337, 339, 338, 343, 342, 340, 341, 1023, 1022, 1020, 1021, 1016, 1017, 1019, 1018, 1008, 1009, 1011, 1010, 1015, 1014, 1012, 1013, 992, 993, 995, 994, 999, 998, 996, 997, 1007, 1006, 1004, 1005, 1000, 1001, 1003, 1002, 960, 961, 963, 962, 967, 966, 964, 965, 975, 974, 972, 973, 968, 969, 971, 970, 991, 990, 988, 989, 984, 985, 987, 986, 976, 977, 979, 978, 983, 982, 980, 981, 896, 897, 899, 898, 903, 902, 900, 901, 911, 910, 908, 909, 904, 905, 907, 906, 927, 926, 924, 925, 920, 921, 923, 922, 912, 913, 915, 914, 919, 918, 916, 917, 959, 958, 956, 957, 952, 953, 955, 954, 944, 945, 947, 946, 951, 950, 948, 949, 928, 929, 931, 930, 935, 934, 932, 933, 943, 942, 940, 941, 936, 937, 939, 938, 768, 769, 771, 770, 775, 774, 772, 773, 783, 782, 780, 781, 776, 777, 779, 778, 799, 798, 796, 797, 792, 793, 795, 794, 784, 785, 787, 786, 791, 790, 788, 789, 831, 830, 828, 829, 824, 825, 827, 826, 816, 817, 819, 818, 823, 822, 820, 821, 800, 801, 803, 802, 807, 806, 804, 805, 815, 814, 812, 813, 808, 809, 811, 810, 895, 894, 892, 893, 888, 889, 891, 890, 880, 881, 883, 882, 887, 886, 884, 885, 864, 865, 867, 866, 871, 870, 868, 869, 879, 878, 876, 877, 872, 873, 875, 874, 832, 833, 835, 834, 839, 838, 836, 837, 847, 846, 844, 845, 840, 841, 843, 842, 863, 862, 860, 861, 856, 857, 859, 858, 848, 849, 851, 850, 855, 854, 852, 853, 512, 513, 515, 514, 519, 518, 516, 517, 527, 526, 524, 525, 520, 521, 523, 522, 543, 542, 540, 541, 536, 537, 539, 538, 528, 529, 531, 530, 535, 534, 532, 533, 575, 574, 572, 573, 568, 569, 571, 570, 560, 561, 563, 562, 567, 566, 564, 565, 544, 545, 547, 546, 551, 550, 548, 549, 559, 558, 556, 557, 552, 553, 555, 554, 639, 638, 636, 637, 632, 633, 635, 634, 624, 625, 627, 626, 631, 630, 628, 629, 608, 609, 611, 610, 615, 614, 612, 613, 623, 622, 620, 621, 616, 617, 619, 618, 576, 577, 579, 578, 583, 582, 580, 581, 591, 590, 588, 589, 584, 585, 587, 586, 607, 606, 604, 605, 600, 601, 603, 602, 592, 593, 595, 594, 599, 598, 596, 597, 767, 766, 764, 765, 760, 761, 763, 762, 752, 753, 755, 754, 759, 758, 756, 757, 736, 737, 739, 738, 743, 742, 740, 741, 751, 750, 748, 749, 744, 745, 747, 746, 704, 705, 707, 706, 711, 710, 708, 709, 719, 718, 716, 717, 712, 713, 715, 714, 735, 734, 732, 733, 728, 729, 731, 730, 720, 721, 723, 722, 727, 726, 724, 725, 640, 641, 643, 642, 647, 646, 644, 645, 655, 654, 652, 653, 648, 649, 651, 650, 671, 670, 668, 669, 664, 665, 667, 666, 656, 657, 659, 658, 663, 662, 660, 661, 703, 702, 700, 701, 696, 697, 699, 698, 688, 689, 691, 690, 695, 694, 692, 693, 672, 673, 675, 674, 679, 678, 676, 677, 687, 686, 684, 685, 680, 681, 683, 682 ); { -- TWiseEncoder -- } constructor TWiseEncoder.Create(Name: string; isGray: boolean; var daqids: array of TDaqId; lastMask: integer; nativeTicks: integer; Timeout: TLargeInteger); begin Inherited Create(Name, daqids, lastMask, Timeout); Self.fNativeTicks := nativeTicks; Self.fIsGray := isGray; end; constructor TWiseEncoder.Create(Name: string; isGray: boolean; var daqids: array of TDaqId; lastMask: integer; nativeTicks: integer); begin Inherited Create(Name, daqids, lastMask, MaxTimeout); Self.fNativeTicks := nativeTicks; Self.fIsGray := isGray; end; constructor TWiseEncoder.Create(Name: string; isGray: boolean; specs: TWiseMultiPortSpecs; nativeTicks: integer); begin Inherited Create(Name, specs, MaxTimeout); Self.fNativeTicks := nativeTicks; Self.fIsGray := isGray; end; function TWiseEncoder.GetValue(): integer; begin fValue := TWiseMultiPort(Self).Value; if (Self.fIsGray) then fValue := Gray2BCD[fValue]; Result := fValue; end; { -- TWiseDomeEncoder -- } function TWiseDomeEncoder.GetValue: integer; begin {$ifdef SIMULATE_DOME_ENCODER} Result := Self.sim_ticks; {$else} Result := TWiseEncoder(Self).Value; {$endif SIMULATE_DOME_ENCODER} end; {$ifdef SIMULATE_DOME_ENCODER} procedure TWiseDomeEncoder.onSimTicksTimer(Sender: TObject); begin if Self.fSim_dir = DirCW then Dec(Self.sim_ticks) else if fSim_dir = DirCCW then Inc(Self.sim_ticks); if Self.sim_ticks = fNativeTicks then Self.sim_ticks := 0 else if Self.sim_ticks = -1 then Self.sim_ticks := fNativeTicks - 1; end; procedure TWiseDomeEncoder.SimulateMovement(dir: TWiseDirection); begin Self.fSim_dir := dir; case dir of DirNone: Self.sim_ticks_timer.Enabled := false; DirCCW: Self.sim_ticks_timer.Enabled := true; DirCW: Self.sim_ticks_timer.Enabled := true; end; end; {$endif SIMULATE_DOME_ENCODER} constructor TWiseDomeEncoder.Create(Name: string; daqids: array of TDaqId; lastMask: integer; travelTicks: integer; nativeTicks: integer); begin inherited Create(name, true, daqids, lastMask, nativeTicks, 50); Self.fCaliTicks := -1; Self.ticksPerDeg := 360 / travelTicks; {$ifdef SIMULATE_DOME_ENCODER} Self.sim_ticks_timer := TTimer.Create(nil); Self.sim_ticks_timer.Enabled := false; Self.sim_ticks_timer.Interval := Floor(1000 / 6); Self.sim_ticks_timer.onTimer := onSimTicksTimer; Randomize; sim_ticks := 256 + Random(Floor(Self.fNativeTicks / 2)); {$endif SIMULTE_DOME_ENCODER} end; destructor TWiseDomeEncoder.Destroy; begin inherited Destroy; end; procedure TWiseDomeEncoder.Calibrate(az: real); begin Self.fCaliTicks := Self.Value; Self.fCaliAz := az; Self.caliTime := Now; end; function TWiseDomeEncoder.GetAzimuth: real; var currTicks: integer; begin if Self.fCaliTicks = -1 then begin // not calibrated yet Result := -1.; exit; end; currTicks := Self.Value; if currTicks = Self.fCaliTicks then // at calibration point Result := Self.fCaliAz else if currTicks > Self.fCaliTicks then // between calibration point and 1024 Result := Self.fCaliAz + (Self.fCaliTicks + Self.Ticks - currTicks) * Self.ticksPerDeg else // between 1024 and calibration point Result := Self.fCaliAz + (Self.fCaliTicks - currTicks) * Self.ticksPerDeg; if Result >= 360.0 then Result := Result - 360.0 else if Result < 0 then Result := Result + 360; end; function TWiseDomeEncoder.ShortestDeltaValue(prevValue: integer): integer; var currValue: integer; begin currValue := Self.Value; if currValue = prevValue then Result := 0 else if currValue < prevValue then Result := Self.Ticks - prevValue + currValue else Result := prevValue + Self.Ticks - currValue; end; { TWiseFocusEncoder } constructor TWiseFocusEncoder.Create(name: string; specs: TWiseMultiPortSpecs); begin inherited Create(name, true, specs, 1024); end; function TWiseFocusEncoder.GetValue: integer; begin Result := Self.Value; end; end.
{ ********************************************************************* } { * Microsoft Windows ** } { * Copyright(c) Microsoft Corp., 1996-1998 ** } { ********************************************************************* } unit mshtmcid; interface uses Winapi.Windows; { ---------------------------------------------------------------------------- } { MSHTML Command IDs } { ---------------------------------------------------------------------------- } const IDM_UNKNOWN = 0; IDM_ALIGNBOTTOM = 1; IDM_ALIGNHORIZONTALCENTERS = 2; IDM_ALIGNLEFT = 3; IDM_ALIGNRIGHT = 4; IDM_ALIGNTOGRID = 5; IDM_ALIGNTOP = 6; IDM_ALIGNVERTICALCENTERS = 7; IDM_ARRANGEBOTTOM = 8; IDM_ARRANGERIGHT = 9; IDM_BRINGFORWARD = 10; IDM_BRINGTOFRONT = 11; IDM_CENTERHORIZONTALLY = 12; IDM_CENTERVERTICALLY = 13; IDM_CODE = 14; IDM_DELETE = 17; IDM_FONTNAME = 18; IDM_FONTSIZE = 19; IDM_GROUP = 20; IDM_HORIZSPACECONCATENATE = 21; IDM_HORIZSPACEDECREASE = 22; IDM_HORIZSPACEINCREASE = 23; IDM_HORIZSPACEMAKEEQUAL = 24; IDM_INSERTOBJECT = 25; IDM_MULTILEVELREDO = 30; IDM_SENDBACKWARD = 32; IDM_SENDTOBACK = 33; IDM_SHOWTABLE = 34; IDM_SIZETOCONTROL = 35; IDM_SIZETOCONTROLHEIGHT = 36; IDM_SIZETOCONTROLWIDTH = 37; IDM_SIZETOFIT = 38; IDM_SIZETOGRID = 39; IDM_SNAPTOGRID = 40; IDM_TABORDER = 41; IDM_TOOLBOX = 42; IDM_MULTILEVELUNDO = 44; IDM_UNGROUP = 45; IDM_VERTSPACECONCATENATE = 46; IDM_VERTSPACEDECREASE = 47; IDM_VERTSPACEINCREASE = 48; IDM_VERTSPACEMAKEEQUAL = 49; IDM_JUSTIFYFULL = 50; IDM_BACKCOLOR = 51; IDM_BOLD = 52; IDM_BORDERCOLOR = 53; IDM_FLAT = 54; IDM_FORECOLOR = 55; IDM_ITALIC = 56; IDM_JUSTIFYCENTER = 57; IDM_JUSTIFYGENERAL = 58; IDM_JUSTIFYLEFT = 59; IDM_JUSTIFYRIGHT = 60; IDM_RAISED = 61; IDM_SUNKEN = 62; IDM_UNDERLINE = 63; IDM_CHISELED = 64; IDM_ETCHED = 65; IDM_SHADOWED = 66; IDM_FIND = 67; IDM_SHOWGRID = 69; IDM_OBJECTVERBLIST0 = 72; IDM_OBJECTVERBLIST1 = 73; IDM_OBJECTVERBLIST2 = 74; IDM_OBJECTVERBLIST3 = 75; IDM_OBJECTVERBLIST4 = 76; IDM_OBJECTVERBLIST5 = 77; IDM_OBJECTVERBLIST6 = 78; IDM_OBJECTVERBLIST7 = 79; IDM_OBJECTVERBLIST8 = 80; IDM_OBJECTVERBLIST9 = 81; IDM_OBJECTVERBLISTLAST = IDM_OBJECTVERBLIST9; IDM_CONVERTOBJECT = 82; IDM_CUSTOMCONTROL = 83; IDM_CUSTOMIZEITEM = 84; IDM_RENAME = 85; IDM_IMPORT = 86; IDM_NEWPAGE = 87; IDM_MOVE = 88; IDM_CANCEL = 89; IDM_FONT = 90; IDM_STRIKETHROUGH = 91; IDM_DELETEWORD = 92; IDM_EXECPRINT = 93; IDM_JUSTIFYNONE = 94; IDM_FOLLOW_ANCHOR = 2008; IDM_INSINPUTIMAGE = 2114; IDM_INSINPUTBUTTON = 2115; IDM_INSINPUTRESET = 2116; IDM_INSINPUTSUBMIT = 2117; IDM_INSINPUTUPLOAD = 2118; IDM_INSFIELDSET = 2119; IDM_PASTEINSERT = 2120; IDM_REPLACE = 2121; IDM_EDITSOURCE = 2122; IDM_BOOKMARK = 2123; IDM_HYPERLINK = 2124; IDM_UNLINK = 2125; IDM_BROWSEMODE = 2126; IDM_EDITMODE = 2127; IDM_UNBOOKMARK = 2128; IDM_TOOLBARS = 2130; IDM_STATUSBAR = 2131; IDM_FORMATMARK = 2132; IDM_TEXTONLY = 2133; IDM_OPTIONS = 2135; IDM_FOLLOWLINKC = 2136; IDM_FOLLOWLINKN = 2137; IDM_VIEWSOURCE = 2139; IDM_ZOOMPOPUP = 2140; { IDM_BASELINEFONT1, IDM_BASELINEFONT2, IDM_BASELINEFONT3, IDM_BASELINEFONT4, } { and IDM_BASELINEFONT5 should be consecutive integers; } IDM_BASELINEFONT1 = 2141; IDM_BASELINEFONT2 = 2142; IDM_BASELINEFONT3 = 2143; IDM_BASELINEFONT4 = 2144; IDM_BASELINEFONT5 = 2145; IDM_HORIZONTALLINE = 2150; IDM_LINEBREAKNORMAL = 2151; IDM_LINEBREAKLEFT = 2152; IDM_LINEBREAKRIGHT = 2153; IDM_LINEBREAKBOTH = 2154; IDM_NONBREAK = 2155; IDM_SPECIALCHAR = 2156; IDM_HTMLSOURCE = 2157; IDM_IFRAME = 2158; IDM_HTMLCONTAIN = 2159; IDM_TEXTBOX = 2161; IDM_TEXTAREA = 2162; IDM_CHECKBOX = 2163; IDM_RADIOBUTTON = 2164; IDM_DROPDOWNBOX = 2165; IDM_LISTBOX = 2166; IDM_BUTTON = 2167; IDM_IMAGE = 2168; IDM_OBJECT = 2169; IDM_1D = 2170; IDM_IMAGEMAP = 2171; IDM_FILE = 2172; IDM_COMMENT = 2173; IDM_SCRIPT = 2174; IDM_JAVAAPPLET = 2175; IDM_PLUGIN = 2176; IDM_PAGEBREAK = 2177; IDM_HTMLAREA = 2178; IDM_PARAGRAPH = 2180; IDM_FORM = 2181; IDM_MARQUEE = 2182; IDM_LIST = 2183; IDM_ORDERLIST = 2184; IDM_UNORDERLIST = 2185; IDM_INDENT = 2186; IDM_OUTDENT = 2187; IDM_PREFORMATTED = 2188; IDM_ADDRESS = 2189; IDM_BLINK = 2190; IDM_DIV = 2191; IDM_TABLEINSERT = 2200; IDM_RCINSERT = 2201; IDM_CELLINSERT = 2202; IDM_CAPTIONINSERT = 2203; IDM_CELLMERGE = 2204; IDM_CELLSPLIT = 2205; IDM_CELLSELECT = 2206; IDM_ROWSELECT = 2207; IDM_COLUMNSELECT = 2208; IDM_TABLESELECT = 2209; IDM_TABLEPROPERTIES = 2210; IDM_CELLPROPERTIES = 2211; IDM_ROWINSERT = 2212; IDM_COLUMNINSERT = 2213; IDM_HELP_CONTENT = 2220; IDM_HELP_ABOUT = 2221; IDM_HELP_README = 2222; IDM_REMOVEFORMAT = 2230; IDM_PAGEINFO = 2231; IDM_TELETYPE = 2232; IDM_GETBLOCKFMTS = 2233; IDM_BLOCKFMT = 2234; IDM_SHOWHIDE_CODE = 2235; IDM_TABLE = 2236; IDM_COPYFORMAT = 2237; IDM_PASTEFORMAT = 2238; IDM_GOTO = 2239; IDM_CHANGEFONT = 2240; IDM_CHANGEFONTSIZE = 2241; IDM_INCFONTSIZE = 2242; IDM_DECFONTSIZE = 2243; IDM_INCFONTSIZE1PT = 2244; IDM_DECFONTSIZE1PT = 2245; IDM_CHANGECASE = 2246; IDM_SUBSCRIPT = 2247; IDM_SUPERSCRIPT = 2248; IDM_SHOWSPECIALCHAR = 2249; IDM_CENTERALIGNPARA = 2250; IDM_LEFTALIGNPARA = 2251; IDM_RIGHTALIGNPARA = 2252; IDM_REMOVEPARAFORMAT = 2253; IDM_APPLYNORMAL = 2254; IDM_APPLYHEADING1 = 2255; IDM_APPLYHEADING2 = 2256; IDM_APPLYHEADING3 = 2257; IDM_DOCPROPERTIES = 2260; IDM_ADDFAVORITES = 2261; IDM_COPYSHORTCUT = 2262; IDM_SAVEBACKGROUND = 2263; IDM_SETWALLPAPER = 2264; IDM_COPYBACKGROUND = 2265; IDM_CREATESHORTCUT = 2266; IDM_PAGE = 2267; IDM_SAVETARGET = 2268; IDM_SHOWPICTURE = 2269; IDM_SAVEPICTURE = 2270; IDM_DYNSRCPLAY = 2271; IDM_DYNSRCSTOP = 2272; IDM_PRINTTARGET = 2273; IDM_IMGARTPLAY = 2274; IDM_IMGARTSTOP = 2275; IDM_IMGARTREWIND = 2276; IDM_PRINTQUERYJOBSPENDING = 2277; IDM_SETDESKTOPITEM = 2278; IDM_CONTEXTMENU = 2280; IDM_GOBACKWARD = 2282; IDM_GOFORWARD = 2283; IDM_PRESTOP = 2284; IDM_CREATELINK = 2290; IDM_COPYCONTENT = 2291; IDM_LANGUAGE = 2292; IDM_REFRESH = 2300; IDM_STOPDOWNLOAD = 2301; IDM_ENABLE_INTERACTION = 2302; IDM_LAUNCHDEBUGGER = 2310; IDM_BREAKATNEXT = 2311; IDM_INSINPUTHIDDEN = 2312; IDM_INSINPUTPASSWORD = 2313; IDM_OVERWRITE = 2314; IDM_PARSECOMPLETE = 2315; IDM_HTMLEDITMODE = 2316; IDM_REGISTRYREFRESH = 2317; IDM_COMPOSESETTINGS = 2318; IDM_SHOWALLTAGS = 2320; IDM_SHOWALIGNEDSITETAGS = 2321; IDM_SHOWSCRIPTTAGS = 2322; IDM_SHOWSTYLETAGS = 2323; IDM_SHOWCOMMENTTAGS = 2324; IDM_SHOWAREATAGS = 2325; IDM_SHOWUNKNOWNTAGS = 2326; IDM_SHOWMISCTAGS = 2327; IDM_SHOWZEROBORDERATDESIGNTIME = 2328; IDM_AUTODETECT = 2329; IDM_SCRIPTDEBUGGER = 2330; IDM_GETBYTESDOWNLOADED = 2331; IDM_NOACTIVATENORMALOLECONTROLS = 2332; IDM_NOACTIVATEDESIGNTIMECONTROLS = 2333; IDM_NOACTIVATEJAVAAPPLETS = 2334; IDM_NOFIXUPURLSONPASTE = 2335; IDM_EMPTYGLYPHTABLE = 2336; IDM_ADDTOGLYPHTABLE = 2337; IDM_REMOVEFROMGLYPHTABLE = 2338; IDM_REPLACEGLYPHCONTENTS = 2339; IDM_SHOWWBRTAGS = 2340; IDM_PERSISTSTREAMSYNC = 2341; IDM_SETDIRTY = 2342; IDM_RUNURLSCRIPT = 2343; //#ifdef IE5_ZOOM IDM_ZOOMRATIO = 2344; IDM_GETZOOMNUMERATOR = 2345; IDM_GETZOOMDENOMINATOR = 2346; //#endif // IE5_ZOOM // COMMANDS FOR COMPLEX TEXT IDM_DIRLTR = 2350; IDM_DIRRTL = 2351; IDM_BLOCKDIRLTR = 2352; IDM_BLOCKDIRRTL = 2353; IDM_INLINEDIRLTR = 2354; IDM_INLINEDIRRTL = 2355; // SHDOCVW IDM_ISTRUSTEDDLG = 2356; // MSHTMLED IDM_INSERTSPAN = 2357; IDM_LOCALIZEEDITOR = 2358; // XML MIMEVIEWER IDM_SAVEPRETRANSFORMSOURCE = 2370; IDM_VIEWPRETRANSFORMSOURCE = 2371; // Scrollbar context menu IDM_SCROLL_HERE = 2380; IDM_SCROLL_TOP = 2381; IDM_SCROLL_BOTTOM = 2382; IDM_SCROLL_PAGEUP = 2383; IDM_SCROLL_PAGEDOWN = 2384; IDM_SCROLL_UP = 2385; IDM_SCROLL_DOWN = 2386; IDM_SCROLL_LEFTEDGE = 2387; IDM_SCROLL_RIGHTEDGE = 2388; IDM_SCROLL_PAGELEFT = 2389; IDM_SCROLL_PAGERIGHT = 2390; IDM_SCROLL_LEFT = 2391; IDM_SCROLL_RIGHT = 2392; // IE 6 Form Editing Commands IDM_MULTIPLESELECTION = 2393; IDM_2D_POSITION = 2394; IDM_2D_ELEMENT = 2395; IDM_1D_ELEMENT = 2396; IDM_ABSOLUTE_POSITION = 2397; IDM_LIVERESIZE = 2398; IDM_ATOMICSELECTION = 2399; // Auto URL detection mode IDM_AUTOURLDETECT_MODE = 2400; // Legacy IE50 compatible paste IDM_IE50_PASTE = 2401; // ie50 paste mode IDM_IE50_PASTE_MODE = 2402; //;begin_internal IDM_GETIPRINT = 2403; //;end_internal // for disabling selection handles IDM_DISABLE_EDITFOCUS_UI = 2404; // for visibility/display in design IDM_RESPECTVISIBILITY_INDESIGN = 2405; // set css mode IDM_CSSEDITING_LEVEL = 2406; // New outdent IDM_UI_OUTDENT = 2407; // Printing Status IDM_UPDATEPAGESTATUS = 2408; // IME Reconversion IDM_IME_ENABLE_RECONVERSION = 2409; IDM_KEEPSELECTION = 2410; IDM_UNLOADDOCUMENT = 2411; IDM_OVERRIDE_CURSOR = 2420; IDM_PEERHITTESTSAMEINEDIT = 2423; IDM_TRUSTAPPCACHE = 2425; IDM_BACKGROUNDIMAGECACHE = 2430; IDM_DEFAULTBLOCK = 6046; IDM_MIMECSET__FIRST__ = 3609; IDM_MIMECSET__LAST__ = 3640; IDM_MENUEXT_FIRST__ = 3700; IDM_MENUEXT_LAST__ = 3732; IDM_MENUEXT_COUNT = 3733; { Commands mapped from the standard set. We should } { consider deleting them from public header files. } IDM_OPEN = 2000; IDM_NEW = 2001; IDM_SAVE = 70; IDM_SAVEAS = 71; IDM_SAVECOPYAS = 2002; IDM_PRINTPREVIEW = 2003; IDM_PRINT = 27; IDM_PAGESETUP = 2004; IDM_SPELL = 2005; IDM_PASTESPECIAL = 2006; IDM_CLEARSELECTION = 2007; IDM_PROPERTIES = 28; IDM_REDO = 29; IDM_UNDO = 43; IDM_SELECTALL = 31; IDM_ZOOMPERCENT = 50; IDM_GETZOOM = 68; IDM_STOP = 2138; IDM_COPY = 15; IDM_CUT = 16; IDM_PASTE = 26; { Defines for IDM_ZOOMPERCENT } CMD_ZOOM_PAGEWIDTH = -1; CMD_ZOOM_ONEPAGE = -2; CMD_ZOOM_TWOPAGES = -3; CMD_ZOOM_SELECTION = -4; CMD_ZOOM_FIT = -5; // IDMs for CGID_EditStateCommands group IDM_CONTEXT = 1; IDM_HWND = 2; implementation end.
//////////////////////////////////////////////////////////////////////////////// // // // FileName : SUIMgr.pas // Creator : Shen Min // Date : 2003-02-26 // Comment : // // Copyright (c) 2002-2003 Sunisoft // http://www.sunisoft.com // Email: support@sunisoft.com // //////////////////////////////////////////////////////////////////////////////// unit SUIMgr; interface {$I SUIPack.inc} uses Windows, Classes, Controls, SysUtils, Forms, TypInfo, Graphics, Dialogs, SUIThemes; type // --------- TsuiFileTheme -------------------- TsuiFileTheme = class(TComponent) private m_Mgr : TsuiFileThemeMgr; m_ThemeFile : String; m_CanUse : Boolean; procedure SetThemeFile(const Value: String); public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; function CanUse() : Boolean; procedure GetBitmap(const Index : Integer; const Buf : TBitmap; SpitCount : Integer = 0; SpitIndex : Integer = 0); function GetInt(const Index : Integer) : Integer; function GetColor(const Index : Integer) : TColor; function GetBool(const Index : Integer) : Boolean; function CheckThemeFile(FileName : String) : Boolean; published property ThemeFile : String read m_ThemeFile write SetThemeFile; end; TsuiBuiltInFileTheme = class(TsuiFileTheme) private m_OldThemeFile : String; procedure SetThemeFile2(const Value: String); procedure ReadSkinData(Stream: TStream); procedure WriteSkinData(Stream : TStream); protected procedure DefineProperties(Filer: TFiler); override; published property ThemeFile : String read m_OldThemeFile write SetThemeFile2; end; // --------- TsuiThemeManager ----------------- TsuiThemeMgrCompList = class(TStringList) end; TsuiThemeManager = class(TComponent) private m_UIStyle : TsuiUIStyle; m_FileTheme : TsuiFileTheme; m_List : TsuiThemeMgrCompList; m_OnUIStyleChanged : TNotifyEvent; procedure SetUIStyle(const Value: TsuiUIStyle); procedure UpdateAll(); procedure SetList(const Value: TsuiThemeMgrCompList); procedure SetFileTheme(const Value: TsuiFileTheme); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; procedure UpdateTheme(); published property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle; property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme; property CompList : TsuiThemeMgrCompList read m_List write SetList; property OnUIStyleChanged : TNotifyEvent read m_OnUIStyleChanged write m_OnUIStyleChanged; end; procedure ThemeManagerEdit(AComp : TsuiThemeManager); procedure FileThemeEdit(AComp : TsuiFileTheme); procedure BuiltInFileThemeEdit(AComp : TsuiBuiltInFileTheme); function UsingFileTheme( const FileTheme : TsuiFileTheme; const UIStyle : TsuiUIStyle; out SuggUIStyle : TsuiUIStyle ) : Boolean; implementation uses SUIForm, frmThemeMgr, SUIThemeFile, SUIPublic; procedure ThemeManagerEdit(AComp : TsuiThemeManager); var frmMgr: TfrmMgr; Form : TWinControl; i : Integer; nIndex : Integer; Comp : TComponent; begin if not (AComp.Owner is TForm) and not (AComp.Owner is TCustomFrame) then Exit; Form := (AComp.Owner as TWinControl); frmMgr := TfrmMgr.Create(nil); for i := 0 to Form.ComponentCount - 1 do begin Comp := Form.Components[i]; if ( (Copy(Comp.ClassName, 1, 4) = 'Tsui') and (IsHasProperty(Comp, 'UIStyle')) and (IsHasProperty(Comp, 'FileTheme')) and not (Comp is TsuiThemeManager) ) then begin nIndex := frmMgr.List.Items.AddObject(Comp.Name, Comp); if AComp.m_List.IndexOf(Comp.Name) = -1 then frmMgr.List.Checked[nIndex] := false else frmMgr.List.Checked[nIndex] := true; end end; if frmMgr.ShowModal() = mrOK then begin AComp.m_List.Clear(); for i := 0 to frmMgr.List.Items.Count - 1 do begin if frmMgr.List.Checked[i] then AComp.m_List.Add(frmMgr.List.Items[i]); end; end; frmMgr.Free(); AComp.UpdateAll(); end; procedure FileThemeEdit(AComp : TsuiFileTheme); var OpenDialog: TOpenDialog; begin OpenDialog := TOpenDialog.Create(Application); OpenDialog.Filter := 'SUIPack Theme File(*.sui)|*.sui'; if OpenDialog.Execute() then AComp.ThemeFile := OpenDialog.FileName; OpenDialog.Free(); end; procedure BuiltInFileThemeEdit(AComp : TsuiBuiltInFileTheme); var OpenDialog: TOpenDialog; begin OpenDialog := TOpenDialog.Create(Application); OpenDialog.Filter := 'SUIPack Theme File(*.sui)|*.sui'; if OpenDialog.Execute() then AComp.ThemeFile := OpenDialog.FileName; OpenDialog.Free(); end; { TsuiThemeManager } constructor TsuiThemeManager.Create(AOwner: TComponent); begin inherited; m_List := TsuiThemeMgrCompList.Create(); UIStyle := SUI_THEME_DEFAULT; end; destructor TsuiThemeManager.Destroy; begin m_List.Free(); m_List := nil; inherited; end; procedure TsuiThemeManager.Notification(AComponent: TComponent; Operation: TOperation); var nIndex : Integer; begin inherited; if AComponent = nil then Exit; if (Operation = opRemove) and (AComponent <> self) then begin nIndex := m_List.IndexOf(AComponent.Name); if nIndex <> -1 then m_List.Delete(nIndex); end; if ( (Operation = opRemove) and (AComponent = m_FileTheme) )then begin m_FileTheme := nil; m_UIStyle := SUI_THEME_DEFAULT; end; end; procedure TsuiThemeManager.SetFileTheme(const Value: TsuiFileTheme); begin m_FileTheme := Value; SetUIStyle(m_UIStyle); end; procedure TsuiThemeManager.SetList(const Value: TsuiThemeMgrCompList); begin m_List.Assign(Value); end; procedure TsuiThemeManager.SetUIStyle(const Value: TsuiUIStyle); var NeedUpdate : Boolean; begin if m_UIStyle = Value then NeedUpdate := false else NeedUpdate := true; m_UIStyle := Value; UpdateAll(); if NeedUpdate then if Assigned(m_OnUIStyleChanged) then m_OnUIStyleChanged(self); end; procedure TsuiThemeManager.UpdateAll; var i : Integer; Comp : TComponent; Form : TWinControl; begin if not (Owner is TForm) and not (Owner is TCustomFrame) then Exit; Form := Owner as TWinControl; for i := 0 to m_List.Count - 1 do begin Comp := Form.FindComponent(m_List[i]); if Comp = nil then continue; SetOrdProp(Comp, 'UIStyle', Ord(UIStyle)); SetObjectProp(Comp, 'FileTheme', m_FileTheme); end; end; procedure TsuiThemeManager.UpdateTheme; begin UpdateAll(); end; { TsuiFileTheme } function TsuiFileTheme.CanUse: Boolean; begin Result := m_CanUse; end; function TsuiFileTheme.CheckThemeFile(FileName: String): Boolean; begin Result := IsSUIThemeFile(FileName); end; constructor TsuiFileTheme.Create(AOwner: TComponent); begin inherited; m_Mgr := TsuiFileThemeMgr.Create(); m_CanUse := false; end; destructor TsuiFileTheme.Destroy; begin m_Mgr.Free(); m_Mgr := nil; inherited; end; procedure TsuiFileTheme.GetBitmap(const Index: Integer; const Buf: TBitmap; SpitCount, SpitIndex: Integer); var TempBmp : TBitmap; begin if (SpitCount = 0) or (SpitIndex = 0) then begin m_Mgr.GetBitmap(Index, Buf); end else begin TempBmp := TBitmap.Create(); m_Mgr.GetBitmap(Index, TempBmp); SpitBitmap(TempBmp, Buf, SpitCount, SpitIndex); TempBmp.Free(); end; end; function TsuiFileTheme.GetBool(const Index: Integer): Boolean; begin Result := m_Mgr.GetBool(Index); end; function TsuiFileTheme.GetColor(const Index: Integer): TColor; begin Result := m_Mgr.GetColor(Index); end; function TsuiFileTheme.GetInt(const Index: Integer): Integer; begin Result := m_Mgr.GetInt(Index); end; procedure TsuiFileTheme.SetThemeFile(const Value: String); function PCharToStr(pstr : PChar) : String; begin if StrLen(pstr) = 0 then Result := '' else begin Result := pstr; SetLength(Result, StrLen(pstr)); end; end; function GetWindowsPath() : String; var WindowsPath : array [0..MAX_PATH - 1] of Char; begin GetWindowsDirectory(WindowsPath, MAX_PATH); Result := PCharToStr(WindowsPath); if Result[Length(Result)] <> '\' then Result := Result + '\' end; function GetSystemPath() : String; var SystemPath : array [0..MAX_PATH - 1] of Char; begin GetSystemDirectory(SystemPath, MAX_PATH); Result := PCharToStr(SystemPath); if Result[Length(Result)] <> '\' then Result := Result + '\' end; var FileName : String; PathName : String; i : Integer; Form : TForm; Comp : TComponent; MainUse : Boolean; First : Boolean; begin if m_ThemeFile = '' then First := true else First := false; if (m_ThemeFile = Value) then Exit; FileName := Value; if not FileExists(FileName) then begin PathName := ExtractFilePath(Application.ExeName); if PathName[Length(PathName)] <> '\' then PathName := PathName + '\'; FileName := PathName + ExtractFileName(FileName); if not FileExists(FileName) then begin PathName := GetWindowsPath(); FileName := PathName + ExtractFileName(FileName); if not FileExists(FileName) then begin PathName := GetSystemPath(); FileName := PathName + ExtractFileName(FileName); if not FileExists(FileName) then Exit; end; end; end; if not CheckThemeFile(FileName) then raise Exception.Create('Invalid skin file for SUIPack!'); m_ThemeFile := FileName; m_CanUse := m_Mgr.LoadFromFile(m_ThemeFile); if (not m_CanUse) or (not (Owner is TForm)) then Exit; Form := Owner as TForm; MainUse := false; for i := 0 to Form.ComponentCount - 1 do begin Comp := Form.Components[i]; if (Comp is TsuiForm) or (Comp is TsuiMDIForm) then begin if GetObjectProp(Comp, 'FileTheme') = self then MainUse := true; end; if ( (Copy(Comp.ClassName, 1, 4) = 'Tsui') and (IsHasProperty(Comp, 'FileTheme')) ) then begin if GetObjectProp(Comp, 'FileTheme') = self then SetObjectProp(Comp, 'FileTheme', self); end; end; if MainUse and (not First) then SetWindowPos(Form.Handle, 0, 0, 0, 0, 0, SWP_DRAWFRAME or SWP_NOMOVE or SWP_NOZORDER or SWP_NOSIZE or SWP_NOACTIVATE); end; function UsingFileTheme( const FileTheme : TsuiFileTheme; const UIStyle : TsuiUIStyle; out SuggUIStyle : TsuiUIStyle ) : Boolean; begin Result := false; SuggUIStyle := UIStyle; if UIStyle = FromThemeFile then begin if FileTheme = nil then SuggUIStyle := SUI_THEME_DEFAULT else if FileTheme.CanUse() then begin Result := true; Exit; end else SuggUIStyle := SUI_THEME_DEFAULT; end; end; { TsuiBuiltInFileTheme } procedure TsuiBuiltInFileTheme.DefineProperties(Filer: TFiler); function DoWrite() : Boolean; begin if FileExists(m_OldThemeFile) then Result := true else Result := false; end; begin inherited; Filer.DefineBinaryProperty('SkinData', ReadSkinData, WriteSkinData, DoWrite); end; procedure TsuiBuiltInFileTheme.ReadSkinData(Stream: TStream); function GetTempPath() : String; var TempPath : array [0..MAX_PATH - 1] of Char; begin Windows.GetTempPath(MAX_PATH, TempPath); Result := PCharToStr(TempPath); if Result[Length(Result)] <> '\' then Result := Result + '\' end; function GetUniqueFileName(const BaseName : String) : String; var i : Integer; BaseFileName : String; FileExt : String; begin Result := BaseName; FileExt := ExtractFileExt(BaseName); BaseFileName := ChangeFileExt(BaseName, ''); i := 0; while FileExists(Result) do begin Inc(i); Result := BaseFileName + IntToStr(i) + FileExt; end; end; var S : TMemoryStream; F : String; begin S := TMemoryStream.Create(); S.CopyFrom(Stream, Stream.Size); F := GetUniqueFileName(GetTempPath() + 'SUIPAKT.sui'); S.SaveToFile(F); inherited ThemeFile := F; S.Free(); DeleteFile(F); end; procedure TsuiBuiltInFileTheme.SetThemeFile2(const Value: String); begin m_OldThemeFile := Value; end; procedure TsuiBuiltInFileTheme.WriteSkinData(Stream: TStream); var S : TMemoryStream; begin S := TMemoryStream.Create(); S.LoadFromFile(m_OldThemeFile); Stream.CopyFrom(S, S.Size); S.Free(); end; end.
unit SearchTypes; interface uses ReveTypes, MoveGenerator {?}; const MAX_DEPTH = 50; type TMoveLine = record AtMove : Integer; Moves : array [1..MAX_DEPTH] of TMove; end; TSearchResults = record BestLine : TMoveLine; NumABs : Integer; NumEvals : Integer; Time : Cardinal; Depth : Integer; Value : Integer; end; procedure InitSearchResults(var aSearchResults : TSearchResults); procedure SearchResultsToString(var aSearchResults: TSearchResults; var aStr : string); procedure CopyMoveLine(var aOrigin, aTarget : TMoveLine); procedure FillSearchResults( var aSearchResults : TSearchResults; aDepth : Integer; aNumAbs : Cardinal; aNumEvs : Cardinal; aValue : Integer; aTime : Cardinal ); implementation uses SysUtils; procedure CopyMoveLine(var aOrigin, aTarget : TMoveLine); var i : Integer; begin {Copy BestLine to MainLine and feed it to the search.} for i := Low(aOrigin.Moves) to aOrigin.AtMove - 1 do begin aTarget.Moves[i].FromSquare := aOrigin.Moves[i].FromSquare; aTarget.Moves[i].ToSquare := aOrigin.Moves[i].ToSquare; end; aTarget.AtMove := aOrigin.AtMove - 1; end; // CopyMoveLine procedure FillSearchResults( var aSearchResults : TSearchResults; aDepth : Integer; aNumAbs : Cardinal; aNumEvs : Cardinal; aValue : Integer; aTime : Cardinal ); begin with aSearchResults do begin aSearchResults.Depth := aDepth; aSearchResults.NumABs := aNumAbs; aSearchResults.NumEvals := aNumEvs; aSearchResults.Value := aValue; aSearchResults.Time := aTime; end; end; // FillSearchResults procedure InitSearchResults(var aSearchResults : TSearchResults); begin with aSearchResults do begin BestLine.AtMove := Low(Bestline.Moves); NumABs := 0; NumEvals := 0; Time := 0; Depth := 0; Value := 0; end; end; // InitSearchResults procedure SearchResultsToString(var aSearchResults: TSearchResults; var aStr : string); const CRLF = #13#10; DELIMITER = #32; var i : Integer; isComputerMove : Boolean; sFrom, sTo : string[2]; sTime, sValue : string; sNumAbs, sNumEvs : string; sDepth : string; seperator : string[1]; begin aStr := ''; try {$RANGECHECKS ON} with aSearchResults do begin isComputerMove := True; for i := BestLine.AtMove - 1 downto Low(BestLine.Moves) do begin Str(BestLine.Moves[i].FromSquare, sFrom); Str(BestLine.Moves[i].ToSquare, sTo); if Abs(BestLine.Moves[i].FromSquare - BestLine.Moves[i].ToSquare) in [3,4,5] then begin seperator := '-'; end else begin seperator := 'x'; end; if isComputerMove then begin aStr := aStr + sFrom + seperator + sTo; end else begin aStr := aStr + '(' + sFrom + seperator + sTo + ')'; end; isComputerMove := not isComputerMove; end; Str(Time, sTime); Str(Depth, sDepth); Str(Value, sValue); Str(NumAbs div Integer(Time), sNumAbs); Str(NumEvals div Integer(Time), sNumEvs); aStr := 'Value = ' + sValue + DELIMITER + 'Time = ' + sTime + DELIMITER + 'Depth = ' + sDepth + DELIMITER + 'abs = ' + sNumAbs + DELIMITER + 'evs = ' + sNumEvs + DELIMITER + aStr; end; // with {$RANGECHECKS OFF} except on ERangeError do begin aStr := 'Not enough room to display statistics!'; end; else raise; end; end; // SearchResultsToString end.
uses Crt, SysUtils; const InputFile = 'SORT.INP'; OutputFile = 'SORT.OUT'; max = 15000; maxV = 15000; nMenu = 12; type TArr = array[1..max] of integer; TCount = array[0..maxV] of integer; var k: TArr; n: Integer; selected: Integer; start,stop:TTimeStamp; procedure Enter; var f: Text; begin Assign(f, InputFile); Reset(f); n := 0; while not SeekEof(f) do begin Inc(n); Read(f, k[n]); end; Close(f); start:=DateTimeToTimeStamp(Now); end; procedure PrintInput; var i: Integer; begin Enter; for i := 1 to n do Write(k[i]:8); Write('Press any key to return to menu...'); ReadKey end; procedure PrintResult; {In k?t qu?} var f: Text; i: Integer; ch: Char; begin Stop:=DateTimeToTimeStamp(Now); Writeln('Running Time = ', Stop.time - Start.time, ' (ms)'); Assign(f, OutputFile); Rewrite(f); for i := 1 to n do Writeln(f, k[i]); Close(f); Write('Press <P> to print Output, another key to return to menu...'); ch := ReadKey; Writeln(ch); if Upcase(ch) = 'P' then begin for i := 1 to n do Write(k[i]:8); Writeln; Write('Press any key to return to menu...'); ReadKey; end; end; procedure Swap(var x, y: Integer); var t: Integer; begin t := x; x := y; y := t; end; procedure MergeSort; var t: TArr; Flag: Boolean; len: Integer; procedure Merge(var Source, Dest: TArr; a, b, c: Integer); var i, j, p: Integer; begin p := a; i := a; j := b + 1; while (i <= b) and (j <= c) do begin if Source[i] <= Source[j] then begin Dest[p] := Source[i]; Inc(i); end else begin Dest[p] := Source[j]; Inc(j); end; Inc(p); end; if i <= b then Move(Source[i], Dest[p], (b - i + 1) * SizeOf(Source[1])) else Move(Source[j], Dest[p], (c - j + 1) * SizeOf(Source[1])); end; procedure MergeByLength(var Source, Dest: TArr; len: Integer); var a, b, c: Integer; begin a := 1; b := len; c := len shl 1; while c <= n do begin Merge(Source, Dest, a, b, c); a := a + len shl 1; b := b + len shl 1; c := c + len shl 1; end; if b < n then Merge(Source, Dest, a, b, n) else Move(Source[a], Dest[a], (n - a + 1) * SizeOf(Source[1])); end; begin Enter; len := 1; Flag := True; FillChar(t, SizeOf(t), 0); while len < n do begin if Flag then MergeByLength(k, t, len) else MergeByLength(t, k, len); len := len shl 1; Flag := not Flag; end; if not Flag then k := t; PrintResult; end; BEGIN MergeSort; END.
{*******************************************************} { } { Delphi Runtime Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} { *************************************************************************** } { } { Licensees holding a valid Borland No-Nonsense License for this Software may } { use this file in accordance with such license, which appears in the file } { license.txt that came with this Software. } { } { *************************************************************************** } {$DENYPACKAGEUNIT} {$HPPEMIT LEGACYHPP} unit Web.WebBroker; interface uses System.SysUtils, System.Classes, Web.HTTPApp, Web.WebReq; type TServerExceptionEvent = procedure (E: Exception; wr: TWebResponse) of object; TUnloadProc = procedure; TWebApplication = class(TWebRequestHandler) private FTitle: string; FUnloadProc: TUnloadProc; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CreateForm(InstanceClass: TComponentClass; var Reference); virtual; procedure Initialize; virtual; procedure Run; virtual; property Title: string read FTitle write FTitle; /// <summary>This events raises when the module is detached from the server.</summary> property OnUnload: TUnloadProc read FUnloadProc write FUnloadProc; end; var Application: TWebApplication = nil; type THandleShutdownException = procedure(E: Exception); { HandleShutdownException is defined as the last point for the developer to analyze exceptions which are occur on shutdown of the application. This function should only be called under abnormal cirrcumstances and is provided to help the developer diagnose what exception occured. To use this functionality simply define a function with the same signature as THandleShutdownException and then set the variable HandleShutdownException to your function. For example, in your function you could write the text of the exception to a text file. } var HandleShutdownException: THandleShutdownException; implementation uses {$IFDEF MSWINDOWS} Winapi.Windows, {$ENDIF} Web.BrkrConst; { TWebApplication } var OldDllProc: TDLLProc; procedure DoneVCLApplication; begin try if Assigned(Application.OnUnload) then Application.OnUnload; Application.Free; Application := nil; except on E:Exception do if Assigned(HandleShutdownException) then begin Application := nil; // Application of no use at this point so clear it System.Classes.ApplicationHandleException := nil; HandleShutdownException(E); end; end; end; procedure DLLExitProc(Reason: Integer); begin {$IFDEF MSWINDOWS} if Reason = DLL_PROCESS_DETACH then DoneVCLApplication; {$ENDIF} {$IFDEF POSIX} if Reason = 0 then DoneVCLApplication; {$ENDIF} if Assigned(OldDllProc) then OldDllProc(Reason); end; function WebRequestHandler: TWebRequestHandler; begin Result := Application; end; constructor TWebApplication.Create(AOwner: TComponent); begin Web.WebReq.WebRequestHandlerProc := WebRequestHandler; inherited Create(AOwner); System.Classes.ApplicationHandleException := HandleException; if IsLibrary then begin IsMultiThread := True; OldDllProc := DLLProc; DLLProc := DLLExitProc; end else AddExitProc(DoneVCLApplication); end; destructor TWebApplication.Destroy; begin System.Classes.ApplicationHandleException := nil; inherited Destroy; end; procedure TWebApplication.CreateForm(InstanceClass: TComponentClass; var Reference); begin // Support CreateForm for backward compatability with D3, D4, and // D5 web modules. D6 generated web modules register a factory. if WebModuleClass = nil then WebModuleClass := InstanceClass else if WebModuleClass <> InstanceClass then raise Exception.CreateRes(@sOnlyOneDataModuleAllowed); end; procedure TWebApplication.Initialize; begin // This is a place holder if InitProc <> nil then TProcedure(InitProc); end; procedure TWebApplication.Run; begin end; end.
unit FC.Trade.Brokers.OrderBase; {$I Compiler.inc} interface uses SysUtils,BaseUtils,Graphics, Serialization, FC.Definitions,FC.Trade.Brokers.BrokerBase, StockChart.Definitions; type TStockOrderBase = class (TInterfacedObject,IStockOrder) protected FAttributes : IStockAttributeCollection; FTrader : IStockTrader; FBrokerCallBack : IStockBroker; FCreateTime : TDateTime; FOpenTime : TDateTime; FOpenComment: string; FOpenPrice: TStockRealNumber; FQueriedOpenPrice: TStockRealNumber; FPendingType: TStockOrderPendingType; FPendingOpenTime: TDateTime; FPendingExpirationTime: TDateTime; FSymbol: string; FNotes: string; FColor: TColor; FCloseTime: TDateTime; FCloseComment: string; FClosePrice: TStockRealNumber; FKind : TStockOrderKind; FID : TGUID; FState : TStockOrderState; FLots : TStockOrderLots; FTakeProfit: TStockRealNumber; FTakeProfitSetTime: TDateTime; FStopLoss : TStockRealNumber; FStopLossSetTime: TDateTime; FTrailingStop: TStockRealNumber; FTrailingStopSetTime: TStockRealNumber; FPendingSuspended: boolean; procedure InitEventArgs(out aArgs: TStockOrderModifyEventArgs; aModifyType: TStockOrderModifyType); protected FWorstProfit : TStockRealNumber; FBestProfit : TStockRealNumber; FWorstPrice : TStockRealNumber; FBestPrice : TStockRealNumber; FCurrentProfit : TStockRealNumber; //Открыть ордер по текущей цене procedure OpenInternal(const aSymbol: string; aKind: TStockOrderKind; aLots: TStockOrderLots;const aComment: string); procedure SetStopLossInternal(aPrice: TStockRealNumber; aFromTrailingStop: boolean); virtual; procedure OnModifyOrder(const aModifyEventArgs: TStockOrderModifyEventArgs); virtual; public //Уникальный идентификатор ордера function GetID: TGUID; virtual; //Под каким брокером выдан ордер function GetBroker: IStockBroker; //Какой трейдер создал ордер. Cсылку сохранить нельзя, сохраняем ID function GetTrader: IStockTrader; //Произвоольное описание ордера function GetNotes: string; procedure SetNotes(const aNotes: string); function GetColor: TColor; procedure SetColor(const aColor: TColor); //Тип ордера - на покупку или продажу function GetKind : TStockOrderKind; virtual; //Валютная пара. Имеет смысл вызывать только если GetState<>osNothing function GetSymbol: string; virtual; //Текущее состояние - пустой, открыт, закрыт function GetState: TStockOrderState; virtual; //Кол-во лотов. function GetLots: TStockOrderLots; virtual; //Время создания ордера function GetCreateTime: TDateTime; //Атрибуты открытия function GetOpenTime : TDateTime; virtual; function GetOpenPrice: TStockRealNumber; virtual; function GetOpenComment: string; virtual; //Атрибуты закрытия function GetCloseTime : TDateTime; virtual; function GetClosePrice: TStockRealNumber; virtual; function GetCloseComment: string; virtual; //Худшее состояние за все время ордера function GetWorstProfit: TStockRealNumber; virtual; //худшая цена за все время ордера function GetWorstPrice: TStockRealNumber; virtual; //максимальный профит, который был за все время ордера function GetBestProfit: TStockRealNumber; virtual; //лучшая цена за все время ордера function GetBestPrice: TStockRealNumber; virtual; //Дать текущий профит function GetCurrentProfit: TStockRealNumber; virtual; //Дать для текущей ситутации границу, где сработает Trailing Stop //Если Trailing Stop не выставлен, возвращается 0 function GetCurrentTrailingStopTriggerPrice: TStockRealNumber; //Установить уровень StopLoss (в реальных ценовых единицах) procedure SetTrailingStop(aPriceDelta: TStockRealNumber); virtual; function GetTrailingStop:TStockRealNumber; virtual; //Когда установили последний StopLoss function GetTrailingStopSetTime: TDateTime; //Установить уровень StopLoss (в реальных ценовых единицах) procedure SetStopLoss(aPrice: TStockRealNumber); virtual; function GetStopLoss:TStockRealNumber; virtual; //Когда установили последний StopLoss function GetStopLossSetTime: TDateTime; //Установить уровень TakeProfit (в пунктах) procedure SetTakeProfit(aPrice: TStockRealNumber); virtual; function GetTakeProfit:TStockRealNumber; virtual; //Когда установили последний StopLoss function GetTakeProfitSetTime: TDateTime; //Закрыть по текущей цене procedure Close(const aComment: string); virtual; //Открыть ордер по текущей цене procedure Open(const aSymbol: string; aKind: TStockOrderKind; aLots: TStockOrderLots;const aComment: string); virtual; //Открыть ордер по указанной цене procedure OpenAt(const aSymbol: string; aKind: TStockOrderKind; aPrice: TStockRealNumber; aLots:TStockOrderLots; const aComment: string); overload; virtual; procedure OpenAt(const aSymbol: string; aKind: TStockOrderKind; aPrice: TStockRealNumber; aLots:TStockOrderLots; aStopLoss, aTakeProfit,aTrailingStop: TSCRealNumber; const aComment: string=''); overload; //Получить время открытия (последнее) отложенного ордера (см. OpenAt) //Эту функцию имеет смысл только, если ордер открывался через OpenAt. В противном случае будет выброшено исключение function GetPendingOpenTime: TStockRealNumber; virtual; //Получить затребованную цену открытия (см. OpenAt) //Эту функцию имеет смысл только, если ордер открывался через OpenAt. В противном случае будет выброшено исключение function GetPendingOpenPrice: TStockRealNumber; virtual; //Изменить цену отложенного открытия //Эту функцию имеет смысл использовать только если ордер открывался через OpenAt. //В противном случае будет выброшено исключение procedure SetPendingOpenPrice(const aPrice: TStockRealNumber); virtual; //Для отложенного ордера установить дату истечения procedure SetPendingExpirationTime(const aDateTime: TDateTime); //Получить тип отложенного ордера (лимитный или стоповый) //Эту функцию имеет смысл только, если ордер открывался через OpenAt. В противном случае будет выброшено исключение function GetPendingType: TStockOrderPendingType; virtual; //Дата истечения отложенного ордера function GetPendingExpirationTime: TDateTime; //Отменить отложенный ордер. Можно вызывать только если GetState=osPending procedure RevokePending; //Приостановить работу отложенного ордера. Ордер остается в состоянии ожидания, но //"замороженный" Можно вызывать только если GetState=osPending. //Внимание! Suspend автоматически сбрасывается при вызове OpenAt procedure SuspendPending; //"Размораживает" отложенный ордер procedure ResumePending; // function IsPendingSuspended: boolean; //Для нужд прикладной разработки. К ордеру можно прицепить любые внешние данные function GetAttributes:IStockAttributeCollection; constructor Create(const aStockBroker: IStockBroker; const aStockTrader: IStockTrader); overload; destructor Destroy; override; procedure Dispose; virtual; end; implementation uses Math,StockChart.Obj; { TStockOrderBase } constructor TStockOrderBase.Create(const aStockBroker: IStockBroker; const aStockTrader: IStockTrader); begin inherited Create; FTrader:=aStockTrader; FBrokerCallBack:=aStockBroker; CreateGUID(FID); FAttributes:=TSCAttributeCollection.Create; FColor:=clWindow; FCreateTime:=FBrokerCallBack.GetCurrentTime; end; destructor TStockOrderBase.Destroy; begin FAttributes:=nil; inherited; end; procedure TStockOrderBase.Dispose; begin FBrokerCallBack:=nil; end; function TStockOrderBase.GetOpenTime: TDateTime; begin result:=FOpenTime; end; function TStockOrderBase.GetPendingExpirationTime: TDateTime; begin result:=FPendingExpirationTime; end; function TStockOrderBase.GetPendingOpenPrice: TStockRealNumber; begin //Если открывались не через OpenAt if FQueriedOpenPrice=0 then raise EStockOrderErrorBadQuery.Create('Order is not pending'); result:=FQueriedOpenPrice; end; function TStockOrderBase.GetPendingOpenTime: TStockRealNumber; begin //Если открывались не через OpenAt if FQueriedOpenPrice=0 then raise EStockOrderErrorBadQuery.Create('Order is not pending'); result:=FPendingOpenTime; end; function TStockOrderBase.GetPendingType: TStockOrderPendingType; begin //Если открывались не через OpenAt if FQueriedOpenPrice=0 then raise EStockOrderErrorBadQuery.Create('Order is not pending'); result:=FPendingType; end; function TStockOrderBase.GetKind: TStockOrderKind; begin result:=FKind; end; function TStockOrderBase.GetNotes: string; begin result:=FNotes; end; function TStockOrderBase.GetTakeProfit: TStockRealNumber; begin result:=FTakeProfit; end; function TStockOrderBase.GetTakeProfitSetTime: TDateTime; begin result:=FTakeProfitSetTime; end; function TStockOrderBase.GetTrader: IStockTrader; begin result:=FTrader; end; function TStockOrderBase.GetTrailingStop: TStockRealNumber; begin result:=FTrailingStop; end; function TStockOrderBase.GetTrailingStopSetTime: TDateTime; begin result:=FTrailingStopSetTime; end; procedure TStockOrderBase.SetColor(const aColor: TColor); var aEventArgs: TStockOrderModifyEventArgs; begin if aColor<>FColor then begin FColor:=aColor; InitEventArgs(aEventArgs,omtChangeColor); OnModifyOrder(aEventArgs); end; end; procedure TStockOrderBase.SetNotes(const aNotes: string); var aEventArgs: TStockOrderModifyEventArgs; begin if aNotes<>FNotes then begin FNotes:=aNotes; InitEventArgs(aEventArgs,omtChangeNotes); OnModifyOrder(aEventArgs); end; end; procedure TStockOrderBase.SetPendingExpirationTime(const aDateTime: TDateTime); begin if FPendingOpenTime>=aDateTime then raise EStockOrderError.Create('Expiration time must be grater than open time'); FPendingExpirationTime:=aDateTime; end; procedure TStockOrderBase.SetPendingOpenPrice(const aPrice: TStockRealNumber); begin if FQueriedOpenPrice=aPrice then exit; OpenAt(FSymbol,FKind,aPrice,FLots,FOpenComment); end; procedure TStockOrderBase.SetStopLoss(aPrice: TStockRealNumber); begin SetStopLossInternal(aPrice,false); end; procedure TStockOrderBase.SetStopLossInternal(aPrice: TStockRealNumber; aFromTrailingStop: boolean); var aMarketPrice: TStockRealNumber; aEventArgs: TStockOrderModifyEventArgs; begin if FState in [osClosed,osNothing] then raise EStockOrderErrorBadQuery.Create('Invalid state'); if aPrice<0 then raise EStockOrderErrorInvalidPrice.Create('Stop Loss must be greater or equal to 0'); aPrice:=FBrokerCallBack.RoundPrice(GetSymbol,aPrice); if FStopLoss=aPrice then exit; //Если что-то устанавливается if aPrice<>0 then begin if FState=osPending then aMarketPrice:=FQueriedOpenPrice else begin if GetKind= okBuy then aMarketPrice:=FBrokerCallBack.GetCurrentPrice(FSymbol,bpkBid) else aMarketPrice:=FBrokerCallBack.GetCurrentPrice(FSymbol,bpkAsk); end; //Проверим, чтобы SL не был слшиком близко к маркет-цене if GetBroker.PriceToPoint(GetSymbol,Abs(aPrice-aMarketPrice))<GetBroker.GetMarketInfo(GetSymbol).StopLevel then raise EStockOrderErrorInvalidPrice.Create('Stop Loss is too close to the market price'); //Проверим, чтобы Stop Loss указывался с правильной стороны if (GetKind=okBuy) then if (GetState=osOpened) and (aPrice>aMarketPrice) then raise EStockOrderErrorInvalidPrice.Create('Stop Loss is greater than the market price') else if (GetState=osPending) and (aPrice>GetPendingOpenPrice) then raise EStockOrderErrorInvalidPrice.Create('Stop Loss is greater than the queried open price'); //Проверим, чтобы Stop Loss указывался с правильной стороны if (GetKind=okSell) then if (GetState=osOpened) and (aPrice<aMarketPrice) then raise EStockOrderErrorInvalidPrice.Create('Stop Loss is less than the market price') else if (GetState=osPending) and (aPrice<GetPendingOpenPrice) then raise EStockOrderErrorInvalidPrice.Create('Stop Loss is less than the queried open price'); end; FStopLoss:=aPrice; FStopLossSetTime:=FBrokerCallBack.GetCurrentTime; InitEventArgs(aEventArgs,omtChangeStopLoss); aEventArgs.StopLossFromTrailingStop:=aFromTrailingStop; OnModifyOrder(aEventArgs); end; procedure TStockOrderBase.SetTakeProfit(aPrice: TStockRealNumber); var aMarketPrice: TStockRealNumber; aEventArgs: TStockOrderModifyEventArgs; begin if FState in [osClosed,osNothing] then raise EStockOrderErrorBadQuery.Create('Invalid state'); if aPrice<0 then raise EStockOrderErrorInvalidPrice.Create('Take Profit must be greater or equal to 0'); if FTakeProfit=aPrice then exit; aPrice:=FBrokerCallBack.RoundPrice(GetSymbol,aPrice); //Если действительно хотят установить TakeProfit (а не сбросить ткуущий if aPrice<>0 then begin if FState=osPending then aMarketPrice:=FQueriedOpenPrice else begin if GetKind= okBuy then aMarketPrice:=FBrokerCallBack.GetCurrentPrice(FSymbol,bpkBid) else aMarketPrice:=FBrokerCallBack.GetCurrentPrice(FSymbol,bpkAsk); end; //Проверим, чтобы SL не был слшиком близко к маркет-цене if GetBroker.PriceToPoint(GetSymbol,Abs(aPrice-aMarketPrice))<GetBroker.GetMarketInfo(GetSymbol).StopLevel then raise EStockOrderErrorInvalidPrice.Create('Take Profit is too close to the market price'); //Проверим, чтобы Take Profit указывался с правильной стороны if (GetKind=okBuy) and (aPrice<aMarketPrice) then raise EStockOrderErrorInvalidPrice.Create('Take Profit is less than the market price'); //Проверим, чтобы Take Profit указывался с правильной стороны if (GetKind=okSell) and (aPrice>aMarketPrice) then raise EStockOrderErrorInvalidPrice.Create('Take Profit is greater than the market price'); end; if FTakeProfit<>aPrice then begin FTakeProfit:=aPrice; FTakeProfitSetTime:=FBrokerCallBack.GetCurrentTime; InitEventArgs(aEventArgs,omtChangeTakeProfit); OnModifyOrder(aEventArgs); end; end; procedure TStockOrderBase.SetTrailingStop(aPriceDelta: TStockRealNumber); var aEventArgs: TStockOrderModifyEventArgs; begin if FState in [osClosed,osNothing] then raise EStockOrderErrorBadQuery.Create('Invalid state'); if aPriceDelta<0 then raise EStockOrderErrorInvalidPrice.Create('Trailing Stop must be greater or equal to 0'); if aPriceDelta=FTrailingStop then exit; if aPriceDelta<>0 then begin if GetBroker.PriceToPoint(GetSymbol,aPriceDelta)<GetBroker.GetMarketInfo(GetSymbol).StopLevel then raise EStockOrderErrorInvalidPrice.Create('Trailing Stop is too small'); end; FTrailingStop:=aPriceDelta; FTrailingStopSetTime:=FBrokerCallBack.GetCurrentTime; InitEventArgs(aEventArgs,omtChangeTrailingStop); OnModifyOrder(aEventArgs); end; procedure TStockOrderBase.SuspendPending; var aEventArgs: TStockOrderModifyEventArgs; begin if (FState <>osPending) then raise EStockOrderErrorBadQuery.Create('Invalid state'); if FPendingSuspended then exit; FPendingSuspended:=true; InitEventArgs(aEventArgs,omtPendingSuspend); OnModifyOrder(aEventArgs); end; function TStockOrderBase.GetOpenComment: string; begin result:=FOpenComment; end; function TStockOrderBase.GetOpenPrice: TStockRealNumber; begin result:=FOpenPrice; end; function TStockOrderBase.GetCloseTime: TDateTime; begin result:=FCloseTime; end; function TStockOrderBase.GetColor: TColor; begin result:=FColor; end; function TStockOrderBase.GetCreateTime: TDateTime; begin result:=FCreateTime; end; function TStockOrderBase.GetClosePrice: TStockRealNumber; begin result:=FClosePrice; end; procedure TStockOrderBase.Close(const aComment: string); var aEventArgs: TStockOrderModifyEventArgs; begin if FState<>osOpened then raise EStockOrderErrorBadQuery.Create('Invalid state'); //Цена наоборот! if FKind=okBuy then FClosePrice:=FBrokerCallBack.GetCurrentPrice(FSymbol,bpkBid) else FClosePrice:=FBrokerCallBack.GetCurrentPrice(FSymbol,bpkAsk); FCloseTime:=FBrokerCallBack.GetCurrentTime; FCloseComment:=aComment; FState:=osClosed; Assert(FBrokerCallBack<>nil); InitEventArgs(aEventArgs,omtClose); OnModifyOrder(aEventArgs); end; procedure TStockOrderBase.OnModifyOrder(const aModifyEventArgs: TStockOrderModifyEventArgs); begin end; procedure TStockOrderBase.Open(const aSymbol: string; aKind: TStockOrderKind; aLots:TStockOrderLots;const aComment: string); begin //Нельзя открывать ордер с которым уже что-то произошло if not (FState in [osNothing,osPending]) then raise EStockOrderErrorBadQuery.Create('Invalid state'); if FState=osPending then RevokePending; OpenInternal(aSymbol, aKind,aLots,aComment); end; procedure TStockOrderBase.OpenAt(const aSymbol: string; aKind: TStockOrderKind; aPrice: TStockRealNumber; aLots:TStockOrderLots; aStopLoss, aTakeProfit, aTrailingStop: TSCRealNumber; const aComment: string); begin OpenAt(aSymbol,aKind,aPrice,aLots,aComment); SetStopLoss(aStopLoss); SetTakeProfit(aTakeProfit); SetTrailingStop(aTrailingStop); end; procedure TStockOrderBase.OpenAt(const aSymbol: string; aKind: TStockOrderKind; aPrice: TStockRealNumber; aLots:TStockOrderLots; const aComment: string); var aCurrentPrice: TStockRealNumber; aPendingType: TStockOrderPendingType; aEventArgs: TStockOrderModifyEventArgs; begin if not (FState in [osNothing,osPending]) then raise EStockOrderErrorBadQuery.Create('Invalid state'); if aPrice<=0 then raise EStockOrderErrorInvalidPrice.Create('Price must be greater than 0'); case aKind of //Покупка okBuy: begin aCurrentPrice:=FBrokerCallBack.GetCurrentPrice(aSymbol,bpkAsk); //Стоповый ордер на покупку if (aPrice>aCurrentPrice) then aPendingType:=ptStop //Лимитный ордер на покупку else aPendingType:=ptLimit; end; //Продажа okSell:begin aCurrentPrice:=FBrokerCallBack.GetCurrentPrice(aSymbol,bpkBid); //Стоповый ордер на продажу if (aPrice<aCurrentPrice) then aPendingType:=ptStop //Лимитный ордер на продажу else aPendingType:=ptLimit; end //??? else raise EAlgoError.Create; end; //Проверим, чтобы цена покупки не была слшиком близко к маркет-цене if GetBroker.PriceToPoint(GetSymbol,Abs(aPrice-aCurrentPrice))<GetBroker.GetMarketInfo(GetSymbol).StopLevel then raise EStockOrderErrorInvalidPrice.Create('Desired price is too close to the market price'); if (FState=osPending) and IsPendingSuspended then ResumePending; //Если ордер был заморожен, мы его обратно оживляем FKind:=aKind; FLots:=aLots; FState:=osPending; FPendingType:=aPendingType; FSymbol:=aSymbol; FOpenComment:=aComment; FPendingOpenTime:=FBrokerCallBack.GetCurrentTime; if FQueriedOpenPrice<>aPrice then begin FQueriedOpenPrice:=aPrice; InitEventArgs(aEventArgs,omtChangeOpenPrice); OnModifyOrder(aEventArgs); end; end; procedure TStockOrderBase.OpenInternal(const aSymbol: string; aKind: TStockOrderKind; aLots:TStockOrderLots; const aComment: string); var aEventArgs: TStockOrderModifyEventArgs; begin //Нельзя открывать ордер с которым уже что-то произошло if FState in [osOpened, osClosed] then raise EStockOrderErrorBadQuery.Create('Invalid state'); if aKind=okBuy then FOpenPrice :=FBrokerCallBack.GetCurrentPrice(aSymbol,bpkAsk) else FOpenPrice:=FBrokerCallBack.GetCurrentPrice(aSymbol,bpkBid); FSymbol:=aSymbol; FKind:=aKind; FLots:=aLots; FState:=osOpened; FOpenTime:=FBrokerCallBack.GetCurrentTime; FOpenComment:=aComment; FWorstPrice :=FOpenPrice; FBestPrice := FOpenPrice; Assert(FBrokerCallBack<>nil); InitEventArgs(aEventArgs,omtOpen); OnModifyOrder(aEventArgs); end; procedure TStockOrderBase.ResumePending; var aEventArgs: TStockOrderModifyEventArgs; begin if (FState <>osPending) then raise EStockOrderErrorBadQuery.Create('Invalid state'); if not FPendingSuspended then exit; FPendingSuspended:=false; InitEventArgs(aEventArgs,omtPendingSuspend); OnModifyOrder(aEventArgs); end; procedure TStockOrderBase.RevokePending; var aEventArgs: TStockOrderModifyEventArgs; begin if (FState <>osPending) then raise EStockOrderErrorBadQuery.Create('Invalid state'); FState:=osNothing; InitEventArgs(aEventArgs,omtPendingRevoke); OnModifyOrder(aEventArgs); end; function TStockOrderBase.GetID: TGUID; begin result:=FID; end; function TStockOrderBase.GetWorstPrice: TStockRealNumber; begin result:=FWorstPrice; end; function TStockOrderBase.GetWorstProfit: TStockRealNumber; begin result:=FWorstProfit; end; procedure TStockOrderBase.InitEventArgs(out aArgs: TStockOrderModifyEventArgs; aModifyType: TStockOrderModifyType); begin FillChar(aArgs,sizeof(aArgs),0); aArgs.ModifyType:=aModifyType; end; function TStockOrderBase.IsPendingSuspended: boolean; begin result:=FPendingSuspended; end; function TStockOrderBase.GetAttributes: IStockAttributeCollection; begin result:=FAttributes; end; function TStockOrderBase.GetBestPrice: TStockRealNumber; begin result:=FBestPrice; end; function TStockOrderBase.GetBestProfit: TStockRealNumber; begin result:=FBestProfit; end; function TStockOrderBase.GetBroker: IStockBroker; begin result:=FBrokerCallBack as IStockBroker; end; function TStockOrderBase.GetState: TStockOrderState; begin result:=FState; end; function TStockOrderBase.GetStopLoss: TStockRealNumber; begin result:=FStopLoss; end; function TStockOrderBase.GetStopLossSetTime: TDateTime; begin result:=FStopLossSetTime; end; function TStockOrderBase.GetSymbol: string; begin result:=FSymbol; end; function TStockOrderBase.GetCurrentProfit: TStockRealNumber; begin result:=FCurrentProfit; end; function TStockOrderBase.GetCurrentTrailingStopTriggerPrice: TStockRealNumber; begin if GetTrailingStop=0 then result:=0 else result:=GetBestPrice-GetTrailingStop; end; function TStockOrderBase.GetCloseComment: string; begin result:=FCloseComment; end; function TStockOrderBase.GetLots: TStockOrderLots; begin result:=FLots; end; end.
unit ringbufu; { This code implements a ring buffer in a slightly unconventional way, by way of a heap manager rather than an actual buffer with a copy in/out mechanism. User workflow to use the ring is as follows: 1. User provides an area of memory for the ring code to manage. This large memory area is referred to as the "slab". 2. User reserves of an area of the slab to write data to (can be any size). Ring responds with a pointer to the area if there is room, or NIL if the reservation couldn't be serviced (ie. ring is full). 3. User writes to the area provided by the ring and then "commits" the write via a supplied pointer and length. User can commit multiple sub-areas if desired, ie. if they have allocated 8k of data and put datums at 2k, 3k, 1k, and 2k, they can commit each datum individually. 4. When user needs to retrieve what they commited, they issue retrieve() and get back either a pointer to what they committed in FIFO order, or NIL if retrieval failed (ie. ring is empty). Internal details: All pointers are assumed to be paragraph-aligned (ie. aligned to the nearest 16-byte boundary) and normalized (ie. offset is 0). If any input to the ring code doesn't follow these conventions, it will be adjusted on entry. (ie. Ring code will normalize commits, but will truncate a commit if the commit offset is still non-zero after normalization.) Ring code will pad reserve amounts to next paragraph boundary. Internal management of pointers is segments only. This means, by design, ring code will always return normalized pointers. 2048-word array will handle commit locations, and have its own head and tail index pointers. This should be enough for most purposes if the average commit size is over 300 bytes; if this is not granular enough, increase qSize. FIFO management: tail=head means queue is empty. Tail can shrink right onto the head. Head must NOT grow right onto the tail, but stop just short of it to prevent false isEmpty condition. All head and tail operations advance the head/tail index after all store/read ops have finished. (ie. store seg, then advance head. Read seg, then advance tail.) The location and size of the reserved area (resSeg) is used to determine where new slab allocations land. Code exists to ensure resSeg wraps around the end of the slab, checks commits to ensure they are inside the reserved area, and shrinks the reserved area as commits occur. Code should be interrupt-safe, because: - Commit never references or alters the tail data - Retrieve never references or alters the head or reservation data (other than resetting isFull, which is an atomic operation) - Reservations never happen while a commit or retrieve is in progress Miscellaneous: The user can reserve a new area before completely filling up the old reservation with commits. This allows the user to do things like reserve an area, do some calcs, and then reserve again with a larger requested amount. The same pointer will be returned as the first reservation; only the internal counter amountP will have changed. Future Enhancements: - Create numSegments as a variable that tracks how many segments are currently "in use". This will require adding a size record to the FIFO array, and some logic. } interface uses objects; const qSize=1 SHL 11; {size of FIFO queue; must be power of 2} {2048} type PSlabRing=^TSlabRing; TSlabRing=object(TObject) slabStart:word; {segment that indicates first available byte of slab} slabEnd:word; {segment that indicates first NON-available byte of slab} slabSizeP:word; {size of slab in 16-byte paragraphs} slabSize:longint; {size of slab in bytes} head:word; {index into FIFO queue; insertion point of new commits} tail:word; {index into FIFO queue; indicates first FIFO data out} resSeg:word; {last successful reserved segment returned} resAmtP:word; {last successful reserved amount in parapgraphs} isFull:boolean; {indicates "full" by holding status of last reserve} numElements:word; {indicates number of queue elements in use} FIFO:array[0..qSize-1] of word; {FIFO queue of segments on the slab} constructor init(_start,_end:pointer); destructor done; virtual; function reserve(amountb:word):pointer; {Reserves a slab area and returns pointer if successful or NIL if not. Internally, checks to see if head+amount exists on the slab and returns pointer if successful. If head+amount would go past end of slab, moves head to beginning of slab and tries again, making sure to not run into the tail.} function commit(datum:pointer;amountb:word):boolean; {commits a section (or all) of the reserved area to the queue in FIFO order. Returns TRUE if successful or FALSE if error (ie. outside reserved area). Internally, records the segment in the FIFO queue, then grows the head.} function retrieve:pointer; {retrieves a queue item in FIFO order. Internally, returns tail segment in FIFO queue, then shrinks the tail.} function isEmpty:boolean; {returns head=tail} end; implementation {assembler functions will be inlined via inline() when time permits!} Function NormPtr(p: Pointer): Pointer; Assembler; {Normalizes an x86 16-bit seg:ofs pointer.} Asm mov dx,word ptr [p+2] {seg} mov ax,word ptr [p] {ofs} mov bx,ax {bx=ofs} and ax,0Fh {ax=offset remainder} mov cl,4 shr bx,cl {bx=ofs div 16=num paragraphs} add dx,bx {increase seg by # of paragraphs} End; Function SegToPtr(_seg:word):Pointer; Assembler; {Returns pointer in DX:AX} Asm mov dx,_seg xor ax,ax End; constructor TSlabRing.init; begin inherited Init; {Pad start to nearest paragraph; truncate end to nearest paragraph. Better safe than sorry.} word(_start):=(word(_start) + 16-1) AND NOT (16-1); _start:=NormPtr(_start); _end:=NormPtr(_end); word(_end):=0; asm les di,self {we are altering object method data} mov ax,word ptr [_start+2] mov word ptr es:[di].slabStart,ax mov ax,word ptr [_end+2] mov word ptr es:[di].slabend,ax end; slabSizeP:=slabEnd-slabStart; slabSize:=slabSizeP; slabSize:=slabSize*16; {the above idiocy prevents TP arith overflow bug due to wrong longint casting} resSeg:=slabStart; end; destructor TSlabRing.done; begin inherited Done; end; function TSlabRing.reserve; {head and tail FIFO indexes are NOT manipulated here. This only tells the caller if they can have a segment [amount] bytes free or not.} var amountp:word; p:pointer; function reserveArea(_seg,amtp:word):pointer; begin resSeg:=_seg; resAmtP:=amtp; reserveArea:=segToPtr(resSeg); isFull:=false; end; begin {pad amount to nearest paragraph, then divide by 16 to convert to paragraphs} asm mov ax,amountb add ax,(16-1) {and amount,not (16-1)} {unnecessary} mov cl,4 shr ax,cl mov amountp,ax end; {different logic if insertion point is ahead or behind tail} if resSeg>=FIFO[tail] then begin {would reservation go beyond end of slab?} if resSeg+amountp<slabend then p:=reserveArea(resSeg,amountp) else begin {can we wraparound to beginning of slab without hitting tail?} if (slabStart+amountp<FIFO[tail]) or isEmpty then p:=reserveArea(slabStart,amountp) else p:=NIL; end; end else begin {head is already behind tail; only check for running into tail} if resSeg+amountp<FIFO[tail] then p:=reserveArea(resSeg,amountp) else p:=NIL; end; if p=NIL then isFull:=true; reserve:=p; end; Function TSlabRing.commit; {Records the datum into the FIFO queue, then advances the head. Checks to see if we are trying to commit past the reserved area. A successful commit shrinks the reserved area.} var datumSeg:word; amountp:word; begin datum:=NormPtr(datum); {in case user forgot to} asm {no @Self because source/target are not object's public/private fields} mov ax,word ptr [datum+2] mov datumSeg,ax end; amountp:=amountb SHR 4; {check if user is trying to commit outside of the reserved area} if (datumSeg<resSeg) or (datumSeg>=resSeg+resAmtP) then begin commit:=false; exit; end; {check if user is trying to commit something that has already been commited} {this check fails to catch 1 out of every [qSize] iterations, but since a user doing that would be a rare occurance anyway, I'm taking those odds} if head<>0 then if datumSeg=FIFO[head-1] then begin commit:=false; exit; end; {commit segment to the FIFO queue and advance index with wraparound} FIFO[head]:=datumSeg; inc(numElements); head:=(head+1) AND (qsize-1); {adjust reserved area by how much was committed} inc(resSeg,amountP); dec(resAmtP,amountP); {exit indicating success} commit:=true; end; function TSlabRing.retrieve; begin if not isEmpty then begin {retrieve segment from the FIFO queue and advance index with wraparound} retrieve:=segToPtr(FIFO[tail]); dec(numElements); tail:=(tail+1) AND (qsize-1); {if we pull even ONE item, we really can't consider ourselves "full"} isFull:=false; end else retrieve:=NIL; end; function TSlabRing.isEmpty; begin isEmpty:=(head=tail); end; end.
unit uGeodata; interface uses Generics.Collections,SysUtils,infra.Classes; type TTag = class(TObject) strict private aKey : String; aValue: String; public function getKey() :String; function getValue():String; procedure setKey(paKey : String); procedure setValue(paValue: String); constructor Create(paKey,paValue:String); destructor Destroy();override; end; TNd = class(TObject) strict private aRef: String; public function getRef() : String; procedure setRef(paValue:String); constructor Create(paRef:String); destructor Destroy();override; end; TMember = class(TObject) strict private aType : String; aRef : String; aRole : String; public function getType(): String; function getRef() : String; function getRole(): String; procedure setType(paType:String); procedure setRef(paRef:String); procedure setRole(paRole:String); constructor Create(paType,paRef,paRole : String); destructor Destroy();override; end; TNode = class(TObject) strict private aID : String; aLon : String; aLat : String; aElev : String; aOwnsTag : Boolean; aListofTags : TList<TTag>; public function getID() : String; function getLon() : String; function getLat() : String; function getElev(): String; function getTag(index : integer):TTag; function SizeTags():Integer; procedure setID (paID : String); procedure setLon(paLon : String); procedure setLat(paLat : String); procedure setElev(paElev : String); procedure AddTagItem(paTag : TTag); procedure ClearTags(); constructor Create(paID : String;paLon,paLat : String); destructor Destroy();override; end; TWay = class(TObject) strict private aID : String; aListofNd : TList<TNd>; aListofTags : TList<TTag>; aOwnsNd : Boolean; aOwnsTag : Boolean; public function getID() : String; function getNd (index : integer):TNd; function getTag(index : integer):TTag; function OwnsNd():Boolean; function OwnsTag():Boolean; function sizeofTags():integer; function sizeofNd():integer; procedure setID (paID : String); procedure AddTagItem(paTag : TTag); procedure AddNdItem (paNd : TNd); procedure ClearTags(); procedure ClearNd(); constructor Create(paID : String); destructor Destroy();override; end; TRelation = class(TObject) strict private aID : String; aListOfMember : TList<TMember>; aListofTags : TList<TTag>; aOwnsMember : Boolean; aOwnsTag : Boolean; public function getID() : String; function getMember (index : integer):TMember; function getTag (index : integer):TTag; function OwnsMember() : Boolean; function OwnsTag() : Boolean; procedure setID (paID : String); procedure AddTagItem(paTag : TTag); procedure AddMemberItem (paMember : TMember); procedure ClearTags(); procedure ClearMember(); constructor Create(paID : String); destructor Destroy; override; end; TOsmElements = class(TObject) strict private aID : string; aCaption : String; aValue : String; aData : string; aListOfNodes: TList<TNode>; public procedure AddNodeItem(paNode : TNode); procedure removeNodesFrom(paIndex :integer;Count:integer); function getNodeItem(paIndex : integer): TNode; function sizeofNodes():Integer; procedure setID(paID:String); function getID() :string; function getCaption() : String; function getValue() : String; function getData() : string; function isEdgeNode(paNode:TNode) : Boolean; constructor Create(paCaption,paValue:string;paData:string); destructor Destroy(); override; end; implementation { TTag } constructor TTag.Create(paKey, paValue: String); begin inherited Create; aKey := paKey; aValue := paValue; end; destructor TTag.Destroy; begin inherited; end; function TTag.getKey: String; begin Result := aKey; end; function TTag.getValue: String; begin Result := aValue; end; procedure TTag.setKey(paKey: String); begin aKey := paKey; end; procedure TTag.setValue(paValue: String); begin aValue := paValue; end; { TNode } procedure TNode.ClearTags; var i : Integer; begin for I := 0 to aListofTags.Count - 1 do aListofTags.Items[i].Free; aListofTags.Free; end; constructor TNode.Create(paID: String; paLon,paLat: String); begin inherited Create; aID := paID; aLon := paLon; aLat := paLat; aElev := ''; aOwnsTag := False; aListofTags := TList<TTag>.Create; end; destructor TNode.Destroy; begin ClearTags(); inherited; end; function TNode.getElev: String; begin Result := aElev; end; function TNode.getID: String; begin Result := aID; end; function TNode.getLat: String; begin Result := aLat; end; function TNode.getLon: String; begin Result := aLon; end; function TNode.getTag(index: integer): TTag; begin if index < SizeTags() then Result := aListofTags[index] else Result := nil; end; procedure TNode.setElev(paElev: String); begin aElev := paElev; end; procedure TNode.setID(paID: String); begin aID := paID; end; procedure TNode.setLat(paLat: String); begin aLat := paLat; end; procedure TNode.setLon(paLon: String); begin aLon := paLon; end; procedure TNode.AddTagItem(paTag: TTag); begin aListofTags.Add(paTag); aOwnsTag := True; end; function TNode.SizeTags: Integer; begin Result := aListofTags.Count; end; { TNd } constructor TNd.Create(paRef: String); begin aRef:=paRef; end; destructor TNd.Destroy; begin inherited; end; function TNd.getRef: String; begin Result:=aRef; end; procedure TNd.setRef(paValue: String); begin aRef:=paValue; end; { TMember } constructor TMember.Create(paType, paRef, paRole: String); begin inherited Create; aType := paType; aRef := paRef; aRole := paRole; end; destructor TMember.Destroy; begin inherited; end; function TMember.getRef: String; begin Result :=aRef; end; function TMember.getRole: String; begin Result :=aRole; end; function TMember.getType: String; begin Result :=aType; end; procedure TMember.setRef(paRef: String); begin aRef := paRef; end; procedure TMember.setRole(paRole: String); begin aRole := paRole; end; procedure TMember.setType(paType: String); begin aType := paType; end; { TWay } procedure TWay.AddNdItem(paNd: TNd); begin aListofNd.Add(paNd); aOwnsNd := True; end; procedure TWay.AddTagItem(paTag: TTag); begin aListofTags.Add(paTag); aOwnsTag := True; end; procedure TWay.ClearNd; var i:Integer; begin for i := 0 to aListofNd.Count - 1 do aListofNd.Items[i].Free; aListofNd.Free; end; procedure TWay.ClearTags; var i : Integer; begin for i := 0 to aListofTags.Count - 1 do aListofTags.Items[i].Free; aListofTags.Free; end; constructor TWay.Create(paID: String); begin inherited Create; aID := paId; aOwnsNd := false; aOwnsTag:= false; aListofTags := TList<TTag>.Create; aListofNd := TList<TNd>.Create; end; destructor TWay.Destroy; begin ClearNd; ClearTags; inherited; end; function TWay.getID: String; begin Result := aID; end; function TWay.getNd(index: integer): TNd; begin if (aListofNd.Count > 0) then Result := aListofNd[index] else Result := nil; end; function TWay.getTag(index: integer): TTag; begin if (aListofTags.Count >0) then Result := aListofTags[index] else Result := nil; end; function TWay.OwnsNd: Boolean; begin Result := aOwnsNd; end; function TWay.OwnsTag: Boolean; begin Result := aOwnsTag; end; procedure TWay.setID(paID: String); begin aID := paID; end; function TWay.sizeofNd: integer; begin Result := aListofNd.Count; end; function TWay.sizeofTags: integer; begin Result := aListofTags.Count; end; { TRelation } procedure TRelation.AddMemberItem(paMember: TMember); begin aListOfMember.Add(paMember); aOwnsMember := True; end; procedure TRelation.AddTagItem(paTag: TTag); begin aListofTags.Add(paTag); aOwnsTag := True; end; procedure TRelation.ClearMember; var i : Integer; begin for I := 0 to aListOfMember.Count - 1 do aListOfMember.Items[i].Free; aListOfMember.Free; end; procedure TRelation.ClearTags; var i : Integer; begin for I := 0 to aListofTags.Count - 1 do aListofTags.Items[i].Free; aListofTags.Free; end; constructor TRelation.Create(paID: String); begin inherited Create; aID :=paID; aListofTags := TList<TTag>.Create; aListOfMember := TList<TMember>.Create; end; destructor TRelation.Destroy; begin ClearMember; ClearTags; inherited; end; function TRelation.getID: String; begin Result := aID; end; function TRelation.getMember(index: integer): TMember; begin if(aListOfMember.Count >0) then Result := aListOfMember[index] else Result := nil; end; function TRelation.getTag(index: integer): TTag; begin if(aListofTags.Count >0) then Result := aListofTags[index] else Result := nil; end; function TRelation.OwnsMember: Boolean; begin Result:= aOwnsMember; end; function TRelation.OwnsTag: Boolean; begin Result := aOwnsTag; end; procedure TRelation.setID(paID: String); begin aID := paID; end; { TOsmElements } procedure TOsmElements.AddNodeItem(paNode: TNode); begin aListOfNodes.Add(paNode); end; constructor TOsmElements.Create(paCaption, paValue: string; paData: string); begin aCaption := paCaption; aValue := paValue; aData := paData; aListOfNodes := TList<TNode>.Create; end; destructor TOsmElements.Destroy; begin aListOfNodes.Free; inherited; end; function TOsmElements.getCaption: String; begin Result := aCaption; end; function TOsmElements.getData: string; begin Result := aData; end; function TOsmElements.getID: string; begin Result := aID; end; function TOsmElements.getNodeItem(paIndex: integer): TNode; begin Result := aListOfNodes.Items[paIndex]; end; function TOsmElements.getValue: String; begin Result := aValue; end; function TOsmElements.isEdgeNode(paNode: TNode): Boolean; var i:Integer; begin if( (aListOfNodes.Items[0].getID = paNode.getID) or (aListOfNodes.Items[aListOfNodes.Count - 1].getID = paNode.getID) ) then Result:= True else Result:= False; end; procedure TOsmElements.removeNodesFrom(paIndex, Count: integer); begin aListOfNodes.DeleteRange(paIndex,Count); end; procedure TOsmElements.setID(paID: String); begin aID:= paID; end; function TOsmElements.sizeofNodes: Integer; begin Result := aListOfNodes.Count; end; end.
{******************************************} { } { FastReport v4.0 } { UniDAC components design editors } { } // Created by: Devart // E-mail: unidac@devart.com { } {******************************************} unit frxUniDACEditor; interface {$I frx.inc} implementation uses Windows, Classes, SysUtils, Forms, Dialogs, frxUniDACComponents, frxCustomDB, frxDsgnIntf, frxRes, Uni, UniProvider, frxDACEditor {$IFDEF Delphi6} , Variants {$ENDIF}; type TfrxUniDatabaseProperty = class(TfrxComponentProperty) public function GetValue: String; override; end; TfrxUniTableNameProperty = class(TfrxTableNameProperty) public procedure GetValues; override; end; TfrxProviderNameProperty = class(TfrxStringProperty) public function GetAttributes: TfrxPropertyAttributes; override; procedure SetValue(const Value: String); override; procedure GetValues; override; end; { TfrxUniDatabaseProperty } function TfrxUniDatabaseProperty.GetValue: String; var db: TfrxUniDACDatabase; begin db := TfrxUniDACDatabase(GetOrdValue); if db = nil then begin if (UniDACComponents <> nil) and (UniDACComponents.DefaultDatabase <> nil) then Result := UniDACComponents.DefaultDatabase.Name else Result := frxResources.Get('prNotAssigned'); end else Result := inherited GetValue; end; { TfrxUniTableNameProperty } procedure TfrxUniTableNameProperty.GetValues; begin inherited; with TfrxUniDACTable(Component).Table do if Connection <> nil then Connection.GetTableNames(Values); end; { TfrxProviderNameProperty } function TfrxProviderNameProperty.GetAttributes: TfrxPropertyAttributes; begin Result := [paMultiSelect, paValueList, paSortList]; end; procedure TfrxProviderNameProperty.SetValue(const Value: String); begin inherited; Designer.UpdateDataTree; end; procedure TfrxProviderNameProperty.GetValues; begin inherited; UniProviders.GetProviderNames(Values); end; initialization frxPropertyEditors.Register(TypeInfo(TfrxUniDACDatabase), TfrxUniDACTable, 'Database', TfrxUniDatabaseProperty); frxPropertyEditors.Register(TypeInfo(TfrxUniDACDatabase), TfrxUniDACQuery, 'Database', TfrxUniDatabaseProperty); frxPropertyEditors.Register(TypeInfo(String), TfrxUniDACTable, 'TableName', TfrxUniTableNameProperty); frxPropertyEditors.Register(TypeInfo(String), TfrxUniDACDatabase, 'ProviderName', TfrxProviderNameProperty); end.
{*******************************************************} { } { Delphi REST Client Framework } { } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit REST.Backend.Providers; {$SCOPEDENUMS ON} interface uses System.Classes, System.Generics.Collections, System.SysUtils, System.SyncObjs, REST.Backend.MetaTypes; type IBackendProvider = interface; IBackendService = interface; IBackendProvider = interface ['{C563AC66-8AF4-45D8-906C-161B061B912F}'] function GetProviderID: string; property ProviderID: string read GetProviderID; end; IBackendService = interface ['{E8BD0783-0E4D-459F-9EEC-11B5F29FE792}'] end; IBackendApi = interface ['{B2608078-946B-475D-B2DD-8523FDC1C773}'] end; IBackendServiceComponent = interface ['{085164DF-FCA7-45CD-BAC3-42C6B0B08170}'] function GetProvider: IBackendProvider; function GetServiceIID: TGuid; property Provider: IBackendProvider read GetProvider; property ServiceIID: TGuid read GetServiceIID; end; TBackendAPIThread = class(TPersistent) private FOnStarting: TNotifyEvent; FOnTerminated: TNotifyEvent; protected procedure DoThreadStarting; virtual; procedure OnThreadTerminate(Sender: TObject); procedure DoThreadTerminated; virtual; public property OnStarting: TNotifyEvent read FOnStarting write FOnStarting; property OnTerminated: TNotifyEvent read FOnTerminated write FOnTerminated; end; TBackendAPIThread<T: class> = class(TBackendAPIThread) public type TExecuteProc = TProc<T>; TExecuteEvent = procedure(Sender: TObject; AApi: T) of object; private type TInternalThread = class(TThread) private FProc: TProc; FAPI: T; protected procedure Execute; override; public constructor Create(const API: T; const AProc: TProc); destructor Destroy; override; end; protected type TOnCreateAPI = TFunc<T>; private FThread: TThread; FEvent: TEvent; FOnCreateAPI: TOnCreateAPI; function CreateAPI: T; function GetFatalException: TObject; function GetStarted: Boolean; function GetFinished: Boolean; protected function CreateThread(const ASender: TObject; const AEvent: TExecuteEvent; const AExecuteProc: TExecuteProc): TThread; procedure Start(const ASender: TObject; const AEvent: TExecuteEvent; const AExecuteProc: TExecuteProc); overload; property OnCreateAPI: TOnCreateAPI read FOnCreateAPI write FOnCreateAPI; public constructor Create; destructor Destroy; override; procedure Start(const AExecuteProc: TExecuteProc); overload; procedure Start(const ASender: TObject; const AEvent: TExecuteEvent); overload; procedure WaitFor; property FatalException: TObject read GetFatalException; property Started: Boolean read GetStarted; property Finished: Boolean read GetFinished; end; TBackendProviders = class public type TFactoryMethod = function(const AProvider: IBackendProvider; const IID: TGUID): IBackendService of object; TService = class private FIID: TGuid; FUnitNames: TArray<string>; FFactoryMethod: TFactoryMethod; public property IID: TGUID read FIID; property UnitNames: TArray<string> read FUnitNames; property FactoryProc: TFactoryMethod read FFactoryMethod; end; TProvider = class private FProviderID: string; FDisplayName: string; FServices: TList<TService>; function GetService(I: Integer): TService; function GetCount: Integer; public constructor Create; destructor Destroy; override; function FindService(const IID: TGUID): TService; property ProviderID: string read FProviderID; property DisplayName: string read FDisplayName; property Count: Integer read GetCount; property Services[I: Integer]: TService read GetService; end; private class var FInstance: TBackendProviders; private FProviders: TList<TProvider>; class function GetInstance: TBackendProviders; static; function GetCount: Integer; function GetProvider(I: Integer): TProvider; public constructor Create; destructor Destroy; override; procedure Register(const AProviderID: string; const ADisplayName: string); procedure Unregister(const AProviderID: string); procedure RegisterService(const AProviderID: string; const AIID: TGuid; const AFactory: TFactoryMethod; const AUnitNames: TArray<string>); procedure UnregisterService(const AProviderID: string; const IID: TGuid); function FindProvider(const AProviderID: string): TProvider; function FindService(const AProviderID: string; const IID: TGUID): TService; property Count: Integer read GetCount; property Providers[I: Integer]: TProvider read GetProvider; class property Instance: TBackendProviders read GetInstance; end; TBackendAuthentication = (Default, Root, Application, User, Session, None); TBackendDefaultAuthentication = (Root, Application, User, Session, None); IAuthAccess = interface ['{E4F2AAC7-A81B-40E5-AF79-F60505B3C0A9}'] procedure Login(const ALogin: TBackendEntityValue); procedure Logout; procedure SetAuthentication(const Value: TBackendAuthentication); procedure SetDefaultAuthentication( const Value: TBackendDefaultAuthentication); function GetProvider: IBackendProvider; property Provider: IBackendProvider read GetProvider; end; IBackendAuthReg = interface ['{6EB1DC55-C0C7-434D-8CE7-CD6F215A1B6F}'] procedure RegisterForAuth(const AAuthAccess: IAuthAccess); procedure UnregisterForAuth(const AAuthAccess: IAuthAccess); end; // Base class for provider components (no livebindings support) TBackendServiceComponent = class(TComponent, IBackendServiceComponent) private FProvider: IBackendProvider; function GetProvider: IBackendProvider; // IBackendServiceComponent function IBackendServiceComponent.GetServiceIID = GetBackendServiceIID; protected procedure ProviderChanged; virtual; function CreateService(const AProvider: IBackendProvider): IBackendService; procedure SetProvider(const Value: IBackendProvider); function GetBackendServiceIID: TGUID; virtual; abstract; // IBackendServiceComponent procedure UpdateProvider(const AProvider: IBackendProvider); virtual; abstract; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure ClearProvider; virtual; public constructor Create(AOwner: TComponent); override; property ServiceIID: TGUID read GetBackendServiceIID; property Provider: IBackendProvider read GetProvider write SetProvider; end; TBackendServiceComponent<TI: IBackendService; T: Class> = class(TBackendServiceComponent) public type TExecuteProc = TProc<T>; TExecuteEvent = procedure(Sender: TObject; AAPI: T) of object; TAPIThread = TBackendAPIThread<T>; private FBackendService: TI; FBackendServiceAPI: T; FAPIThread: TAPIThread; function CreateService(const AProvider: IBackendProvider): TI; procedure SetAPIThread( const AValue: TAPIThread); protected function GetBackendServiceAPI: T; function GetBackendService: TI; procedure ClearProvider; override; function GetBackendServiceIID: TGUID; override; procedure UpdateProvider(const AValue: IBackendProvider); override; function InternalCreateBackendServiceAPI: T; virtual; abstract; function InternalCreateIndependentBackendServiceAPI: T; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property APIThread: TAPIThread read FAPIThread write SetAPIThread; end; TBackendServiceComponentAuth<TI: IBackendService; T: Class> = class(TBackendServiceComponent<TI, T>) private FAuth: IBackendAuthReg; FAuthAccess: IAuthAccess; procedure SetAuth(const Value: IBackendAuthReg); protected function CreateAuthAccess: IAuthAccess; virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public destructor Destroy; override; property Auth: IBackendAuthReg read FAuth write SetAuth; end; implementation uses System.TypInfo, REST.Utils, REST.Backend.Consts, REST.Backend.Exception, REST.Backend.ServiceTypes; { TBackendProviders } constructor TBackendProviders.Create; begin FProviders := TObjectList<TProvider>.Create; end; destructor TBackendProviders.Destroy; begin FProviders.Free; inherited; end; function TBackendProviders.FindProvider(const AProviderID: string): TProvider; var LProvider: TProvider; begin Result := nil; for LProvider in FProviders do if SameText(LProvider.ProviderID, AProviderID) then begin Result := LProvider; break; end; end; function TBackendProviders.FindService(const AProviderID: string; const IID: TGUID): TService; var LProvider: TProvider; begin Result := nil; LProvider := FindProvider(AProviderID); if LProvider <> nil then Result := LProvider.FindService(IID); end; { TBackendProviders.TService } function TBackendProviders.GetCount: Integer; begin Result := FProviders.Count; end; class function TBackendProviders.GetInstance: TBackendProviders; begin if FInstance = nil then FInstance := TBackendProviders.Create; Result := FInstance; end; function TBackendProviders.GetProvider(I: Integer): TProvider; begin Result := FProviders[I]; end; procedure TBackendProviders.Register(const AProviderID, ADisplayName: string); var LProvider: TProvider; begin if FindProvider(AProviderID) <> nil then raise EBackendProviderError.CreateFmt(sDuplicateProviderID, [AProviderID]); LProvider := TProvider.Create; LProvider.FProviderID := AProviderID; LProvider.FDisplayName := ADisplayName; FProviders.Add(LProvider); end; procedure TBackendProviders.RegisterService(const AProviderID: string; const AIID: TGuid; const AFactory: TFactoryMethod; const AUnitNames: TArray<string>); var LProvider: TProvider; LService: TService; begin LProvider := FindProvider(AProviderID); if LProvider = nil then raise EBackendProviderError.CreateFmt(sProviderNotFound, [AProviderID]); LService := LProvider.FindService(AIID); if LService <> nil then raise EBackendProviderError.CreateFmt(sDuplicateService, [AProviderID]); LService := TService.Create; LService.FIID := AIID; LService.FUnitNames := AUnitNames; LService.FFactoryMethod := AFactory; LProvider.FServices.Add(LService); end; procedure TBackendProviders.Unregister(const AProviderID: string); var LProvider: TProvider; begin LProvider := FindProvider(AProviderID); if LProvider = nil then raise EBackendProviderError.CreateFmt(sUnregisterProviderNotFound, [AProviderID]); FProviders.Remove(LProvider); end; procedure TBackendProviders.UnregisterService(const AProviderID: string; const IID: TGuid); var LProvider: TProvider; LService: TService; begin LProvider := FindProvider(AProviderID); if LProvider = nil then raise EBackendProviderError.CreateFmt(sProviderNotFound, [AProviderID]); LService := LProvider.FindService(IID); if LService <> nil then LProvider.FServices.Remove(LService) else raise EBackendProviderError.CreateFmt(sUnregisterServiceNotFound, [AProviderID]); end; { TBackendProviders.TProvider } constructor TBackendProviders.TProvider.Create; begin FServices := TObjectList<TService>.Create; end; destructor TBackendProviders.TProvider.Destroy; begin FServices.Free; inherited; end; function TBackendProviders.TProvider.FindService(const IID: TGUID): TService; var LService: TService; begin Result := nil; for LService in FServices do if IID = LService.IID then begin Result := LService; break; end end; function TBackendProviders.TProvider.GetCount: Integer; begin Result := FServices.Count; end; function TBackendProviders.TProvider.GetService(I: Integer): TService; begin Result := FServices[I]; end; { TBackendServiceComponent } procedure TBackendServiceComponent.SetProvider(const Value: IBackendProvider); begin if FProvider <> Value then begin if FProvider <> nil then begin if FProvider is TComponent then TComponent(FProvider).RemoveFreeNotification(Self); end; UpdateProvider(Value); FProvider := Value; if FProvider <> nil then begin if FProvider is TComponent then TComponent(FProvider).FreeNotification(Self); end else begin end; ProviderChanged; end; end; procedure TBackendServiceComponent.ProviderChanged; begin end; procedure TBackendServiceComponent.ClearProvider; begin FProvider := nil; end; constructor TBackendServiceComponent.Create(AOwner: TComponent); var LProvider: IBackendProvider; begin inherited; // Find a default provider if not Supports(AOwner, IBackendProvider, LProvider) then if csDesigning in ComponentState then LProvider := TRESTFindDefaultComponent.FindDefaultIntfT<IBackendProvider>(Self); if LProvider <> nil then if TBackendProviders.Instance.FindService(LProvider.ProviderID, ServiceIID) <> nil then // Valid provider Provider := LProvider; end; function TBackendServiceComponent.CreateService( const AProvider: IBackendProvider): IBackendService; var LService: TBackendProviders.TService; begin LService := TBackendProviders.Instance.FindService(AProvider.ProviderID, ServiceIID); if LService <> nil then begin Result := LService.FactoryProc(AProvider, ServiceIID) as IBackendService; end else raise EBackendServiceError.CreateFmt(sServiceNotSupportedByProvider, [AProvider.ProviderID]); end; function TBackendServiceComponent.GetProvider: IBackendProvider; begin Result := FProvider; end; procedure TBackendServiceComponent.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; /// clean up component-references if (Operation = opRemove) then begin if (FProvider is TComponent) and (TComponent(FProvider) = AComponent) then ClearProvider; end; end; { TBackendServiceComponent<TService: IBackendService; TApi: Class> } destructor TBackendServiceComponent<TI, T>.Destroy; begin FAPIThread.Free; ClearProvider; inherited; end; constructor TBackendServiceComponent<TI, T>.Create(AOwner: TComponent); begin inherited; FAPIThread := TAPIThread.Create; FAPIThread.OnCreateAPI := function: T begin Result := InternalCreateIndependentBackendServiceAPI; end; end; function TBackendServiceComponent<TI, T>.CreateService( const AProvider: IBackendProvider): TI; begin Result := TI(inherited CreateService(AProvider)); Assert(Supports(Result, ServiceIID)); end; function TBackendServiceComponent<TI, T>.GetBackendServiceAPI: T; begin if FBackendServiceAPI = nil then begin if FBackendService <> nil then FBackendServiceAPI := InternalCreateBackendServiceAPI // TBackendQueryApi.Create(FService.CreateQueryApi) else raise EBackendServiceError.CreateFmt(sNoBackendService, [Self.ClassName]); end; Result := FBackendServiceAPI; end; function TBackendServiceComponent<TI, T>.GetBackendService: TI; begin Result := FBackendService; end; function TBackendServiceComponent<TI, T>.GetBackendServiceIID: TGUID; begin Result := GetTypeData(TypeInfo(TI)).Guid; end; function TBackendServiceComponent<TI, T>.InternalCreateIndependentBackendServiceAPI: T; begin raise ENotImplemented.Create('InternalCreateIndependentBackendServiceAPI'); // do not localize end; procedure TBackendServiceComponent<TI, T>.SetAPIThread(const AValue: TAPIThread); begin FAPIThread.Assign(AValue); end; procedure TBackendServiceComponent<TI, T>.ClearProvider; begin inherited; FBackendService := nil; FreeAndNil(FBackendServiceAPI); end; procedure TBackendServiceComponent<TI, T>.UpdateProvider(const AValue: IBackendProvider); begin ClearProvider; if AValue <> nil then FBackendService := CreateService(AValue); // May raise an exception end; { TBackendThread } constructor TBackendAPIThread<T>.TInternalThread.Create(const API: T; const AProc: TProc); begin inherited Create(True); FAPI := API; FProc := AProc; end; destructor TBackendAPIThread<T>.TInternalThread.Destroy; begin FAPI.Free; inherited; end; procedure TBackendAPIThread<T>.TInternalThread.Execute; begin FProc(); end; { TBackendThreadProperties<T> } constructor TBackendAPIThread<T>.Create; begin inherited Create; FEvent := TEvent.Create; end; function TBackendAPIThread<T>.CreateAPI: T; begin if Assigned(FOnCreateAPI) then Result := FOnCreateAPI else begin Assert(False); // unexpected Result := nil; end; end; function TBackendAPIThread<T>.CreateThread(const ASender: TObject; const AEvent: TExecuteEvent; const AExecuteProc: TExecuteProc): TThread; var LBackendServiceAPI: T; begin FEvent.ResetEvent; LBackendServiceAPI := CreateAPI; Result := TInternalThread.Create(LBackendServiceAPI, procedure begin FEvent.SetEvent; // Thread started if Assigned(AExecuteProc) then AExecuteProc(LBackendServiceAPI) else AEvent(ASender, LBackendServiceAPI) end); end; destructor TBackendAPIThread<T>.Destroy; begin FEvent.Free; FThread.Free; // Blocking inherited; end; function TBackendAPIThread<T>.GetFatalException: TObject; begin if FThread <> nil then Result := FThread.FatalException else Result := nil; end; function TBackendAPIThread<T>.GetFinished: Boolean; begin Result := (FThread <> nil) and FThread.Finished; end; function TBackendAPIThread<T>.GetStarted: Boolean; begin Result := (FThread <> nil) and FThread.Started; end; procedure TBackendAPIThread<T>.Start(const ASender: TObject; const AEvent: TExecuteEvent); begin Start(ASender, AEvent, nil); end; procedure TBackendAPIThread<T>.Start( const AExecuteProc: TExecuteProc); begin Start(TObject(nil), TExecuteEvent(nil), AExecuteProc); end; procedure TBackendAPIThread<T>.Start(const ASender: TObject; const AEvent: TExecuteEvent; const AExecuteProc: TExecuteProc); begin if Assigned(FThread) and (not FThread.Finished) then raise EBackendServiceError.Create(sBackendThreadRunning); FThread.Free; FThread := CreateThread(ASender, AEvent, AExecuteProc); DoThreadStarting; FThread.OnTerminate := OnThreadTerminate; FThread.Start; end; procedure TBackendAPIThread<T>.WaitFor; begin if FThread <> nil then begin // Wait until thread is started FEvent.WaitFor; FThread.WaitFor; end; end; { TBackendAPIThread } procedure TBackendAPIThread.DoThreadStarting; begin if Assigned(FOnStarting) then FOnStarting(Self); end; procedure TBackendAPIThread.DoThreadTerminated; begin if Assigned(FOnTerminated) then FOnTerminated(Self); end; procedure TBackendAPIThread.OnThreadTerminate(Sender: TObject); begin DoThreadTerminated; end; { TBackendServiceComponentAuth<TI, T> } function TBackendServiceComponentAuth<TI, T>.CreateAuthAccess: IAuthAccess; begin Result := nil; end; destructor TBackendServiceComponentAuth<TI, T>.Destroy; begin Auth := nil; // Unregister for auth inherited; end; procedure TBackendServiceComponentAuth<TI, T>.Notification( AComponent: TComponent; Operation: TOperation); begin inherited; /// clean up component-references if (Operation = opRemove) then begin if (FAuth is TComponent) and (TComponent(FAuth) = AComponent) then Auth := nil; end; end; procedure TBackendServiceComponentAuth<TI, T>.SetAuth( const Value: IBackendAuthReg); begin if FAuth <> Value then begin if FAuth <> nil then begin if FAuth is TComponent then TComponent(FAuth).RemoveFreeNotification(Self); if FAuthAccess <> nil then try FAuth.UnregisterForAuth(FAuthAccess); finally FAuthAccess := nil; end; end; FAuth := Value; if FAuth <> nil then begin if FAuth is TComponent then TComponent(FAuth).FreeNotification(Self); FAuthAccess := CreateAuthAccess; if FAuthAccess <> nil then FAuth.RegisterForAuth(FAuthAccess); end; end; end; initialization finalization TBackendProviders.FInstance.Free; end.
{ ID: nghoang4 PROG: gift1 LANG: PASCAL } const fileinp = 'gift1.in'; fileout = 'gift1.out'; maxN = 10; type Str14 = string[14]; MyData = record ten: Str14; tien: integer; end; var a: array[1..maxN] of MyData; n, i, j, m, k: integer; s: str14; procedure Change(s: Str14; m: integer); var i: integer; begin for i:=1 to n do if a[i].ten = s then begin inc(a[i].tien,m); break; end; end; begin assign(input,fileinp); reset(input); assign(output,fileout); rewrite(output); readln(n); for i:=1 to n do begin readln(a[i].ten); a[i].tien:=0; end; for j:=1 to n do begin readln(s); readln(m,k); if k > 0 then Change(s,-(m - m mod k)); for i:=1 to k do begin readln(s); Change(s,m div k); end; end; for i:=1 to n do writeln(a[i].ten,' ',a[i].tien); close(input); close(output); end.
{ this file is part of Ares Aresgalaxy ( http://aresgalaxy.sourceforge.net ) 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., 675 Mass Ave, Cambridge, MA 02139, USA. ***************************************************************** The following delphi code is based on Emule (0.46.2.26) Kad's implementation http://emule.sourceforge.net and KadC library http://kadc.sourceforge.net/ ***************************************************************** } { Description: DHT special 128 bit integer functions } unit dht_int160; interface uses sysutils,windows,synsock; type CU_INT160=array[0..4] of cardinal; pCU_INT160=^CU_INT160; pbytearray=^tbytearray; tbytearray=array[0..1023] of byte; procedure CU_INT160_xor(inValue:pCu_INT160; value:pCu_INT160); function CU_INT160_tohexstr(value:pCu_INT160; reversed:boolean = true ):string; function CU_INT160_tohexbinstr(value:pCu_INT160; doreverse:boolean=true):string; procedure CU_INT160_fill(inValue:pCu_INT160; value:pCu_INT160); overload; procedure CU_Int160_fill(m_data:pCU_INT160; value:pCU_INT160; numBits:cardinal); overload; function CU_INT160_Compare(Value1:pCu_INT160; value2:pCu_INT160):boolean; function CU_INT160_compareTo(m_data:pCU_INT160; value:cardinal):integer; overload; function CU_Int160_compareTo(m_data:pCU_Int160; other:pCU_INT160):integer; overload; function CU_INT160_getBitNumber(m_data:pCU_INT160; bit:cardinal):cardinal; procedure CU_Int160_setBitNumber(m_data:pCU_INT160; bit:cardinal; value:cardinal); procedure CU_Int160_shiftLeft(m_data:pCU_INT160; bits:cardinal); procedure CU_Int160_setValue(m_data:pCU_INT160; value:cardinal); procedure CU_Int160_add(m_data:pCU_INT160; value:pCU_Int160); overload; procedure CU_Int160_add(m_data:pCU_INT160; value:cardinal); overload; function CU_INT160_MinorOf(m_data:pCU_INT160; value:cardinal):boolean; overload; function CU_INT160_MinorOf(m_data:pCU_INT160; value:pCU_INT160):boolean; overload; function CU_INT160_Majorof(m_data:pCU_INT160; value:pCU_INT160):boolean; procedure CU_Int160_toBinaryString(m_data:pCU_INT160; var str:string; trim:boolean=false); procedure CU_Int160_setValueBE(m_data:pCU_INT160; valueBE:pbytearray); procedure CU_INT160_fillNXor(Destination:pCU_INT160; initialValue:pCU_INT160; xorvalue:pCU_INT160); procedure CU_INT160_copytoBuffer(source:pCU_INT160; destination:pbytearray); procedure CU_INT160_copyFromBuffer(source:pbytearray; destination:pCU_INT160); procedure CU_INT160_copyFromBufferRev(source:pbytearray; destination:pCU_INT160); var m_data:CU_INT160; implementation uses helper_strings; procedure CU_INT160_copyFromBuffer(source:pbytearray; destination:pCU_INT160); begin move(source[0],destination[0],4); move(source[4],destination[1],4); move(source[8],destination[2],4); move(source[12],destination[3],4); move(source[16],destination[4],4); end; procedure CU_INT160_copyFromBufferRev(source:pbytearray; destination:pCU_INT160); begin move(source[0],destination[0],4); move(source[4],destination[1],4); move(source[8],destination[2],4); move(source[12],destination[3],4); move(source[16],destination[4],4); destination[0]:=synsock.ntohl(destination[0]); destination[1]:=synsock.ntohl(destination[1]); destination[2]:=synsock.ntohl(destination[2]); destination[3]:=synsock.ntohl(destination[3]); destination[4]:=synsock.ntohl(destination[4]); end; procedure CU_INT160_copytoBuffer(source:pCU_INT160; destination:pbytearray); begin move(source[0],destination[0],4); move(source[1],destination[4],4); move(source[2],destination[8],4); move(source[3],destination[12],4); move(source[4],destination[16],4); end; procedure CU_INT160_fillNXor(Destination:pCU_INT160; initialValue:pCU_INT160; xorvalue:pCU_INT160); begin destination[0]:=initialValue[0] xor xorvalue[0]; destination[1]:=initialValue[1] xor xorvalue[1]; destination[2]:=initialValue[2] xor xorvalue[2]; destination[3]:=initialValue[3] xor xorvalue[3]; destination[4]:=initialValue[4] xor xorvalue[4]; end; procedure CU_Int160_setValue(m_data:pCU_INT160; value:cardinal); begin m_data[0]:=0; m_data[1]:=0; m_data[2]:=0; m_data[3]:=0; m_data[4]:=value; end; procedure CU_Int160_setValueBE(m_data:pCU_INT160; valueBE:pbytearray); var i:integer; begin m_data[0]:=0; m_data[1]:=0; m_data[2]:=0; m_data[3]:=0; m_data[4]:=0; for i:=0 to 19 do m_data[i div 4]:=m_data[i div 4] or (cardinal(valueBE[i]) shl (8*(3-(i mod 4)))); end; procedure CU_Int160_shiftLeft(m_data:pCU_INT160; bits:cardinal); var temp:CU_INT160; indexShift,i:integer; bit64Value,shifted:int64; begin if ((bits=0) or ( ((m_data[0]=0) and (m_data[1]=0) and (m_data[2]=0) and (m_data[3]=0) and (m_data[4]=0)) ) ) then exit; if bits>159 then begin CU_Int160_setValue(m_data,0); exit; end; temp[0]:=0; temp[1]:=0; temp[2]:=0; temp[3]:=0; temp[4]:=0; indexShift:=integer(bits) div 32; shifted:=0; i:=4; while (i>=indexShift) do begin bit64Value:=int64(m_data[i]); shifted:=shifted+(bit64Value shl int64(bits mod 32)); temp[i-indexShift]:=cardinal(shifted); shifted:=shifted shr 32; dec(i); end; for i:=0 to 4 do m_data[i]:=temp[i]; end; procedure CU_Int160_add(m_data:pCU_INT160; value:pCU_Int160); var sum:int64; i:integer; begin if CU_INT160_compareTo(value,0)=0 then exit; sum:=0; for i:=4 downto 0 do begin sum:=sum+m_data[i]; sum:=sum+value[i]; m_data[i]:=cardinal(sum); sum:=sum shr 32; end; end; procedure CU_Int160_add(m_data:pCU_INT160; value:cardinal); var temp:CU_INT160; begin if value=0 then exit; CU_Int160_SetValue(@temp,value); CU_Int160_add(m_data,@temp); end; function CU_INT160_getBitNumber(m_data:pCU_INT160; bit:cardinal):cardinal; var uLongNum,shift:integer; begin result:=0; if (bit>159) then exit; ulongNum:=bit div 32; shift:=31-(bit mod 32); result:= ((m_data[ulongNum] shr shift) and 1); end; procedure CU_Int160_setBitNumber(m_data:pCU_INT160; bit:cardinal; value:cardinal); var ulongNum,shift:integer; begin ulongNum:=bit div 32; shift:=31-(bit mod 32); m_data[ulongNum]:=m_data[ulongNum] or (1 shl shift); if value=0 then m_data[ulongNum]:=m_data[ulongNum] xor (1 shl shift); end; function CU_INT160_compareTo(m_data:pCU_INT160; value:cardinal):integer; begin if ((m_data[0]>0) or (m_data[1]>0) or (m_data[2]>0) or (m_data[3]>0) or (m_data[4]>value)) then begin result:=1; exit; end; if m_data[4]<value then begin result:=-1; exit; end; result:=0; end; function CU_INT160_Compare(Value1:pCu_INT160; value2:pCu_INT160):boolean; begin result:=((Value1[0]=Value2[0]) and (Value1[1]=Value2[1]) and (Value1[2]=Value2[2]) and (Value1[3]=Value2[3]) and (Value1[4]=Value2[4])); end; procedure CU_INT160_xor(inValue:pCu_INT160; value:pCu_INT160); begin inValue[0]:=inValue[0] xor value[1]; inValue[1]:=inValue[1] xor value[1]; inValue[2]:=inValue[2] xor value[2]; inValue[3]:=inValue[3] xor value[3]; inValue[4]:=inValue[4] xor value[4]; end; procedure CU_INT160_fill(inValue:pCu_INT160; value:pCu_INT160); begin inValue[0]:=value[0]; inValue[1]:=value[1]; inValue[2]:=value[2]; inValue[3]:=value[3]; inValue[4]:=value[4]; end; procedure CU_Int160_fill(m_data:pCU_INT160; value:pCU_INT160; numBits:cardinal); var i:integer; numULONGs:cardinal; begin // Copy the whole ULONGs numULONGs:=numBits div 32; for i:=0 to numULONGs-1 do begin m_data[i]:=value[i]; end; // Copy the remaining bits for i:=(32*numULONGs) to numBits-1 do CU_INT160_setBitNumber(m_data,i, CU_INT160_getBitNumber(value,i)); // Pad with random bytes (Not seeding based on time to allow multiple different ones to be created in quick succession) for i:=numBits to 159 do CU_INT160_setBitNumber(m_data,i, (random(2))); end; procedure CU_Int160_toBinaryString(m_data:pCU_INT160; var str:string; trim:boolean=false); var b,i:integer; begin str:=''; for i:=0 to 159 do begin b:=CU_Int160_getBitNumber(m_data,i); if ((not trim) or (b<>0)) then begin str:=str+Format('%d',[b]); trim:=false; end; end; if length(str)=0 then str:='0'; end; function CU_INT160_tohexbinstr(value:pCu_INT160; doreverse:boolean=true):string; var num:cardinal; begin setLength(result,20); if doreverse then begin num:=synsock.htonl(value[0]); move(num,result[1],4); num:=synsock.htonl(value[1]); move(num,result[5],4); num:=synsock.htonl(value[2]); move(num,result[9],4); num:=synsock.htonl(value[3]); move(num,result[13],4); num:=synsock.htonl(value[4]); move(num,result[17],4); end else begin move(value[1],result[5],4); move(value[2],result[9],4); move(value[3],result[13],4); move(value[4],result[17],4); end; //result:=result; end; function CU_INT160_tohexstr(value:pCu_INT160; reversed:boolean = true):string; var num:cardinal; begin setLength(result,20); if reversed then begin num:=synsock.ntohl(value[0]); move(num,result[1],4); num:=synsock.ntohl(value[1]); move(num,result[5],4); num:=synsock.ntohl(value[2]); move(num,result[9],4); num:=synsock.ntohl(value[3]); move(num,result[13],4); num:=synsock.ntohl(value[4]); move(num,result[17],4); end else begin move(value[0],result[1],4); move(value[1],result[5],4); move(value[2],result[9],4); move(value[3],result[13],4); move(value[4],result[17],4); end; result:=bytestr_to_hexstr(result); end; function CU_INT160_MinorOf(m_data:pCU_INT160; value:cardinal):boolean; begin result:=(CU_INT160_compareTo(m_data,value)<0); end; function CU_INT160_MinorOf(m_data:pCU_INT160; value:pCU_INT160):boolean; overload; begin result:=(CU_INT160_compareTo(m_data,value)<0); end; function CU_INT160_Majorof(m_data:pCU_INT160; value:pCU_INT160):boolean; overload; begin result:=(CU_INT160_compareTo(m_data,value)>0); end; function CU_Int160_compareTo(m_data:pCU_Int160; other:pCU_INT160):integer; var i:integer; begin result:=0; for i:=0 to 4 do begin if m_data[i]<other[i] then begin result:=-1; exit; end; if m_data[i]>other[i] then begin result:=1; exit; end; end; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLFileSMD<p> SMD vector file format implementation.<p> <b>History :</b><font size=-1><ul> <li>24/03/07 - DaStr - Added explicit pointer dereferencing (thanks Burkhard Carstens) (Bugtracker ID = 1678644) <li>28/01/07 - DaStr - Optimized bone weights loading a bit <li>14/01/07 - DaStr - Fixed bone weights for HL2 models (thanks DIVON) <li>24/01/05 - SG - Fix for comma decimal separator in save function (dikoe Kenguru) <li>30/03/04 - EG - Basic Half-Life2/XSI support <li>05/06/03 - SG - Separated from GLVectorFileObjects.pas </ul></font> } unit GLFileSMD; interface uses System.Classes, System.SysUtils, GLVectorFileObjects, GLTexture, GLApplicationFileIO, GLVectorTypes, GLVectorGeometry, GLMaterial; type // TGLSMDVectorFile // {: The SMD vector file is Half-life's skeleton format.<p> The SMD is a text-based file format. They come in two flavors: one that old Skeleton and triangle (mesh) data, and animation files that store Skeleton frames.<p> This reader curently reads both, but requires that the main file (the one with mesh data) be read first. } TGLSMDVectorFile = class(TVectorFile) public { Public Declarations } class function Capabilities : TDataFileCapabilities; override; procedure LoadFromStream(aStream : TStream); override; procedure SaveToStream(aStream : TStream); override; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses GLUtils; // ------------------ // ------------------ TGLSMDVectorFile ------------------ // ------------------ // Capabilities // class function TGLSMDVectorFile.Capabilities : TDataFileCapabilities; begin Result:=[dfcRead, dfcWrite]; end; // LoadFromStream // procedure TGLSMDVectorFile.LoadFromStream(aStream : TStream); procedure AllocateMaterial(const name : String); var matLib : TGLMaterialLibrary; begin if Owner is TGLBaseMesh then begin matLib:=TGLBaseMesh(GetOwner).MaterialLibrary; if Assigned(matLib) then begin if matLib.Materials.GetLibMaterialByName(name)=nil then begin if CompareText(name, 'null.bmp')<>0 then begin try matLib.AddTextureMaterial(name, name) except on E: ETexture do begin if not Owner.IgnoreMissingTextures then raise; end; end; end else matLib.AddTextureMaterial(name, ''); end; end; end; end; var i, j, k, nVert, nTex, firstFrame : Integer; nbBones, boneID : Integer; mesh : TSkeletonMeshObject; sl, tl : TStringList; bone : TSkeletonBone; frame : TSkeletonFrame; faceGroup : TFGVertexNormalTexIndexList; v : TAffineVector; boneIDs : TVertexBoneWeightDynArray; weightCount: Integer; begin sl:=TStringList.Create; tl:=TStringList.Create; try sl.LoadFromStream(aStream); if sl[0]<>'version 1' then raise Exception.Create('SMD version 1 required'); if sl[1]<>'nodes' then raise Exception.Create('nodes not found'); if sl.IndexOf('triangles')>=0 then begin mesh:=TSkeletonMeshObject.CreateOwned(Owner.MeshObjects); mesh.Mode:=momFaceGroups; end else if Owner.MeshObjects.Count>0 then mesh:=(Owner.MeshObjects[0] as TSkeletonMeshObject) else raise Exception.Create('SMD is an animation, load model SMD first.'); // read skeleton nodes i:=2; if Owner.Skeleton.RootBones.Count=0 then begin // new bone structure while sl[i]<>'end' do begin tl.CommaText:=sl[i]; with Owner.Skeleton do if (tl[2]<>'-1') then bone:=TSkeletonBone.CreateOwned(RootBones.BoneByID(StrToInt(tl[2]))) else bone:=TSkeletonBone.CreateOwned(RootBones); if Assigned(bone) then begin bone.BoneID:=StrToInt(tl[0]); bone.Name:=tl[1]; end; Inc(i); end; end else begin // animation file, skip structure while sl[i]<>'end' do Inc(i); end; Inc(i); if sl[i]<>'skeleton' then raise Exception.Create('skeleton not found'); Inc(i); // read animation time frames nbBones:=Owner.Skeleton.RootBones.BoneCount-1; firstFrame:=Owner.Skeleton.Frames.Count; while sl[i]<>'end' do begin if Copy(sl[i], 1, 5)<>'time ' then raise Exception.Create('time not found, got: '+sl[i]); frame:=TSkeletonFrame.CreateOwned(Owner.Skeleton.Frames); frame.Name:=ResourceName+' '+sl[i]; Inc(i); while Pos(Copy(sl[i], 1, 1), ' 1234567890')>0 do begin tl.CommaText:=sl[i]; while StrToInt(tl[0])>frame.Position.Count do begin frame.Position.Add(NullVector); frame.Rotation.Add(NullVector); end; frame.Position.Add(GLUtils.StrToFloatDef(tl[1]), GLUtils.StrToFloatDef(tl[2]), GLUtils.StrToFloatDef(tl[3])); v:=AffineVectorMake(GLUtils.StrToFloatDef(tl[4]), GLUtils.StrToFloatDef(tl[5]), GLUtils.StrToFloatDef(tl[6])); frame.Rotation.Add(v); Inc(i); end; while frame.Position.Count<nbBones do begin frame.Position.Add(NullVector); frame.Rotation.Add(NullVector); end; Assert(frame.Position.Count=nbBones, 'Invalid number of bones in frame '+IntToStr(Owner.Skeleton.Frames.Count)); end; if Owner is TGLActor then with TGLActor(Owner).Animations.Add do begin k:=Pos('.', ResourceName); if k>0 then Name:=Copy(ResourceName, 1, k-1) else Name:=ResourceName; Reference:=aarSkeleton; StartFrame:=firstFrame; EndFrame:=Self.Owner.Skeleton.Frames.Count-1; end; Inc(i); if (i<sl.Count) and (sl[i]='triangles') then begin // read optional mesh data Inc(i); if mesh.BonesPerVertex<1 then mesh.BonesPerVertex:=1; faceGroup:=nil; while sl[i]<>'end' do begin if (faceGroup=nil) or (faceGroup.MaterialName<>sl[i]) then begin faceGroup:=TFGVertexNormalTexIndexList.CreateOwned(mesh.FaceGroups); faceGroup.Mode:=fgmmTriangles; faceGroup.MaterialName:=sl[i]; AllocateMaterial(sl[i]); end; Inc(i); for k:=1 to 3 do with mesh do begin tl.CommaText:=sl[i]; if tl.Count>9 then begin // Half-Life 2 SMD, specifies bones and weights weightCount := StrToInt(tl[9]); SetLength(boneIDs,weightCount); for j := 0 to weightCount - 1 do begin BoneIDs[j].BoneID := StrToInt(tl[10+j*2]); BoneIDs[j].Weight := GLUtils.StrToFloatDef(tl[11+j*2]); end; nVert:=FindOrAdd(boneIDs, AffineVectorMake(GLUtils.StrToFloatDef(tl[1]), GLUtils.StrToFloatDef(tl[2]), GLUtils.StrToFloatDef(tl[3])), AffineVectorMake(GLUtils.StrToFloatDef(tl[4]), GLUtils.StrToFloatDef(tl[5]), GLUtils.StrToFloatDef(tl[6]))); nTex:=TexCoords.FindOrAdd(AffineVectorMake(GLUtils.StrToFloatDef(tl[7]), GLUtils.StrToFloatDef(tl[8]), 0)); faceGroup.Add(nVert, nVert, nTex); Inc(i); end else begin // Half-Life 1 simple format boneID:=StrToInt(tl[0]); nVert:=FindOrAdd(boneID,AffineVectorMake(GLUtils.StrToFloatDef(tl[1]), GLUtils.StrToFloatDef(tl[2]), GLUtils.StrToFloatDef(tl[3])), AffineVectorMake(GLUtils.StrToFloatDef(tl[4]), GLUtils.StrToFloatDef(tl[5]), GLUtils.StrToFloatDef(tl[6]))); nTex:=TexCoords.FindOrAdd(AffineVectorMake(GLUtils.StrToFloatDef(tl[7]), GLUtils.StrToFloatDef(tl[8]), 0)); faceGroup.Add(nVert, nVert, nTex); Inc(i); end; end; end; Owner.Skeleton.RootBones.PrepareGlobalMatrices; mesh.PrepareBoneMatrixInvertedMeshes; end; finally tl.Free; sl.Free; end; end; // SaveToStream // procedure TGLSMDVectorFile.SaveToStream(aStream : TStream); var str, nodes : TStrings; i,j,k,l,b : Integer; p,r,v,n,t : TAffineVector; procedure GetNodesFromBonesRecurs(bone : TSkeletonBone; ParentID : Integer; bl : TStrings); var i : Integer; begin bl.Add(Format('%3d "%s" %3d',[bone.BoneID,bone.Name,ParentID])); for i:=0 to bone.Count-1 do GetNodesFromBonesRecurs(bone.Items[i],bone.BoneID,bl); end; begin str:=TStringList.Create; nodes:=TStringList.Create; try str.Add('version 1'); // Add the bones str.Add('nodes'); for i:=0 to Owner.Skeleton.RootBones.Count-1 do begin GetNodesFromBonesRecurs(Owner.Skeleton.RootBones[i],-1,nodes); end; str.AddStrings(nodes); str.Add('end'); // Now add the relavent frames if Owner.Skeleton.Frames.Count>0 then begin str.Add('skeleton'); for i:=0 to Owner.Skeleton.Frames.Count-1 do begin str.Add(Format('time %d',[i])); for j:=0 to Owner.Skeleton.Frames[i].Position.Count-1 do begin p:=Owner.Skeleton.Frames[i].Position[j]; r:=Owner.Skeleton.Frames[i].Rotation[j]; str.Add(StringReplace( Format('%3d %.6f %.6f %.6f %.6f %.6f %.6f', [j,p.V[0],p.V[1],p.V[2],r.V[0],r.V[1],r.V[2]]), ',', '.', [rfReplaceAll])); end; end; str.Add('end'); end; // Add the mesh data if Owner.MeshObjects.Count>0 then begin str.Add('triangles'); for i:=0 to Owner.MeshObjects.Count-1 do if Owner.MeshObjects[i] is TSkeletonMeshObject then with TSkeletonMeshObject(Owner.MeshObjects[i]) do begin for j:=0 to FaceGroups.Count-1 do with TFGVertexNormalTexIndexList(FaceGroups[j]) do begin for k:=0 to (VertexIndices.Count div 3)-1 do begin str.Add(MaterialName); for l:=0 to 2 do begin v:=Vertices[VertexIndices[3*k+l]]; n:=Normals[NormalIndices[3*k+l]]; t:=TexCoords[TexCoordIndices[3*k+l]]; b:=VerticesBonesWeights^[VertexIndices[3*k+l]]^[0].BoneID; str.Add(StringReplace( Format('%3d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f', [b,v.V[0],v.V[1],v.V[2],n.V[0],n.V[1],n.V[2],t.V[0],t.V[1]]), ',', '.', [rfReplaceAll])); end; end; end; end; str.Add('end'); end; str.SaveToStream(aStream); finally str.Free; nodes.Free; end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterVectorFileFormat('smd', 'Half-Life SMD files', TGLSMDVectorFile); end.
unit Unit1; interface uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, //GLScene GLKeyboard, GLVectorGeometry, GLScene, GLVectorFileObjects, GLObjects, GLWin32Viewer, GLCadencer, GLNavigator, GLGeomObjects, GLCrossPlatform, GLCoordinates, GLUtils, GLBaseClasses, GLFile3DS; type TForm1 = class(TForm) GLScene1: TGLScene; GLLightSource1: TGLLightSource; DummyCube1: TGLDummyCube; FreeForm1: TGLFreeForm; Sphere1: TGLSphere; ArrowLine1: TGLArrowLine; GLSceneViewer2: TGLSceneViewer; GLCamera2: TGLCamera; GLCadencer1: TGLCadencer; Timer1: TTimer; DummyCube2: TGLDummyCube; Sphere2: TGLSphere; GLLightSource2: TGLLightSource; Panel1: TPanel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; TrackBar1: TTrackBar; Button1: TButton; Lines1: TGLLines; LabelFPS: TLabel; procedure FormCreate(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure Timer1Timer(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } colTotalTime : Single; // for timing collision detection colCount : Integer; procedure AddToTrail(const p : TVector); public { Public declarations } mousex, mousey: integer; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin SetGLSceneMediaDir(); FreeForm1.LoadFromFile('BoxedIn.3ds'); FreeForm1.BuildOctree; Label1.Caption:='Octree Nodes : '+inttostr(FreeForm1.Octree.NodeCount); Label2.Caption:='Tri Count Octree: '+inttostr(FreeForm1.Octree.TriCountOctree); Label3.Caption:='Tri Count Mesh : '+inttostr(FreeForm1.Octree.TriCountMesh); Lines1.AddNode(0, 0, 0); Lines1.ObjectStyle:=Lines1.ObjectStyle+[osDirectDraw]; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); var rayStart, rayVector : TVector; velocity : Single; pPoint : TVector; pNormal : TVector; t : Int64; begin if IsKeyDown(VK_ESCAPE) then close; Velocity:=Trackbar1.Position*deltaTime*50; t:=StartPrecisionTimer; with FreeForm1 do begin SetVector(rayStart, Sphere2.AbsolutePosition); SetVector(rayVector, Sphere2.AbsoluteDirection); NormalizeVector(rayVector); //Note: since collision may be performed on multiple meshes, we might need to know which hit // is closest (ie: d:=raystart - pPoint). if OctreeSphereSweepIntersect(raystart, rayvector, velocity, Sphere2.Radius, @pPoint, @pNormal) then begin // Show the polygon intersection point NormalizeVector(pNormal); Sphere1.Position.AsVector:=pPoint; Sphere1.Direction.AsVector:=pNormal; // Make it rebound... with Sphere2.Direction do AsAffineVector:=VectorReflect(AsAffineVector, AffineVectorMake(pNormal)); // Add some "english"... with Sphere2.Direction do begin X:=x+random/10; Y:=y+random/10; Z:=z+random/10; end; // Add intersect point to trail AddToTrail(pPoint); end else begin Sphere2.Move(velocity); //No collision, so just move the ball. end; end; // Last trail point is always the sphere's current position Lines1.Nodes.Last.AsVector:=Sphere2.Position.AsVector; colTotalTime:=colTotalTime+StopPrecisionTimer(t); Inc(colCount); end; procedure TForm1.AddToTrail(const p : TVector); var i, k : Integer; begin Lines1.Nodes.Last.AsVector:=p; Lines1.AddNode(0, 0, 0); if Lines1.Nodes.Count>20 then // limit trail to 20 points Lines1.Nodes[0].Free; for i:=0 to 19 do begin k:=Lines1.Nodes.Count-i-1; if k>=0 then TGLLinesNode(Lines1.Nodes[k]).Color.Alpha:=0.95-i*0.05; end; end; procedure TForm1.Timer1Timer(Sender: TObject); var t : Single; begin if colCount>0 then t:=colTotalTime*1000/colCount else t:=0; LabelFPS.Caption:=Format('%.2f FPS - %.3f ms for collisions/frame', [GLSceneViewer2.FramesPerSecond, t]); GLSceneViewer2.ResetPerformanceMonitor; colTotalTime:=0; colCount:=0; end; procedure TForm1.Button1Click(Sender: TObject); begin //If the ball gets stuck in a pattern, hit the reset button. With Sphere2.Position do begin X:=random; Y:=random; Z:=random; end; With Sphere2.Direction do begin X:=random; if random > 0.5 then x:=-x; Y:=random; if random > 0.5 then y:=-y; Z:=random; if random > 0.5 then z:=-z; end; end; end.
unit uMainForm; interface uses System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Imaging.Jpeg, // GLScene GLTexture, GLCadencer, GLWin32Viewer, GLScene, GLObjects, GLGraph, GLVectorLists, GLVectorTypes, GLVectorGeometry, GLSLShader, GLGeomObjects, GLVectorFileObjects, GLSimpleNavigation, GLCustomShader, GLCrossPlatform, GLMaterial, GLCoordinates, GLBaseClasses, GLUtils, // FileFormats TGA, GLFileMD2, GLFileMS3D, GLFile3DS, DDSImage; type TGLSLTestForm = class(TForm) Scene: TGLScene; Viewer: TGLSceneViewer; Cadencer: TGLCadencer; Camera: TGLCamera; Light: TGLLightSource; LightCube: TGLDummyCube; GLSphere1: TGLSphere; GLXYZGrid1: TGLXYZGrid; GLArrowLine1: TGLArrowLine; Panel1: TPanel; LightMovingCheckBox: TCheckBox; GUICube: TGLDummyCube; WorldCube: TGLDummyCube; Fighter: TGLActor; Teapot: TGLActor; Sphere_big: TGLActor; Sphere_little: TGLActor; MaterialLibrary: TGLMaterialLibrary; ShadeEnabledCheckBox: TCheckBox; TurnPitchrollCheckBox: TCheckBox; GLSLShader: TGLSLShader; GLSimpleNavigation1: TGLSimpleNavigation; procedure FormCreate(Sender: TObject); procedure CadencerProgress(Sender: TObject; const deltaTime, newTime: double); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure LightCubeProgress(Sender: TObject; const deltaTime, newTime: Double); procedure ShadeEnabledCheckBoxClick(Sender: TObject); procedure GLSLShaderApply(Shader: TGLCustomGLSLShader); procedure GLSLShaderInitialize(Shader: TGLCustomGLSLShader); procedure GLSLShaderUnApply(Shader: TGLCustomGLSLShader; var ThereAreMorePasses: Boolean); procedure GLSLShaderApplyEx(Shader: TGLCustomGLSLShader; Sender: TObject); procedure GLSLShaderInitializeEx(Shader: TGLCustomGLSLShader; Sender: TObject); private { Private declarations } public { Public declarations } end; var GLSLTestForm: TGLSLTestForm; implementation {$R *.dfm} procedure TGLSLTestForm.FormCreate(Sender: TObject); begin //First load scripts from shader directory SetGLSceneMediaDir(); GLSLShader.LoadShaderPrograms('Shader.Vert','Shader.Frag'); GLSLShader.Enabled := True; //Second load models from media directory SetGLSceneMediaDir(); Fighter.LoadFromFile('waste.md2'); //Fighter Fighter.SwitchToAnimation(0, True); Fighter.AnimationMode := aamLoop; Fighter.Scale.Scale(3); Teapot.LoadFromFile('Teapot.3ds'); //Teapot (no texture coordinates) Teapot.Scale.Scale(0.8); Sphere_big.LoadFromFile('Sphere_big.3DS'); //Sphere_big Sphere_big.Scale.Scale(70); Sphere_little.LoadFromFile('Sphere_little.3ds'); //Sphere_little Sphere_little.Scale.Scale(4); // Then load textures. MaterialLibrary.LibMaterialByName('Earth').Material.Texture.Image.LoadFromFile('Earth.jpg'); MaterialLibrary.LibMaterialByName('WasteSkin').Material.Texture.Image.LoadFromFile('waste.jpg'); end; procedure TGLSLTestForm.ShadeEnabledCheckBoxClick(Sender: TObject); begin GLSLShader.Enabled := ShadeEnabledCheckBox.Checked; end; procedure TGLSLTestForm.GLSLShaderApply(Shader: TGLCustomGLSLShader); begin {* Old variant of Apply with Shader do begin Param['DiffuseColor'].AsVector4f := VectorMake(1, 1, 1, 1); Param['AmbientColor'].AsVector4f := VectorMake(0.2, 0.2, 0.2, 1); Param['LightIntensity'].AsVector1f := 1; Param['MainTexture'].AsTexture2D[0] := MaterialLibrary.LibMaterialByName('Earth').Material.Texture; end; *} end; procedure TGLSLTestForm.GLSLShaderApplyEx(Shader: TGLCustomGLSLShader; Sender: TObject); begin with Shader do begin Param['DiffuseColor'].AsVector4f := VectorMake(1, 1, 1, 1); Param['AmbientColor'].AsVector4f := VectorMake(0.2, 0.2, 0.2, 1); Param['LightIntensity'].AsVector1f := 1; SetTex('MainTexture', TGLLibMaterial(Sender).Material.Texture); end; end; procedure TGLSLTestForm.GLSLShaderInitialize(Shader: TGLCustomGLSLShader); begin with Shader do begin // Nothing. end; end; procedure TGLSLTestForm.GLSLShaderInitializeEx(Shader: TGLCustomGLSLShader; Sender: TObject); begin with Shader do begin // For AMD's shaders validation SetTex('MainTexture', TGLLibMaterial(Sender).Material.Texture); end; end; procedure TGLSLTestForm.GLSLShaderUnApply(Shader: TGLCustomGLSLShader; var ThereAreMorePasses: Boolean); begin with Shader do begin // Nothing. end; end; procedure TGLSLTestForm.CadencerProgress(Sender: TObject; const deltaTime, newTime: double); begin Viewer.Invalidate; if TurnPitchrollCheckBox.Checked then begin Sphere_big.Pitch(40 * deltaTime); Sphere_big.Turn(40 * deltaTime); Sphere_little.Roll(40 * deltaTime); end; end; procedure TGLSLTestForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Cadencer.Enabled := False; end; procedure TGLSLTestForm.LightCubeProgress(Sender: TObject; const deltaTime, newTime: Double); begin if LightMovingCheckBox.Checked then LightCube.MoveObjectAround(Camera.TargetObject, sin(NewTime) * deltaTime * 10, deltaTime * 20); end; end.
unit ProductsBasketView2; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ProductsBaseView1, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxCustomData, cxStyles, cxTL, cxMaskEdit, cxDBLookupComboBox, cxDropDownEdit, cxButtonEdit, cxTLdxBarBuiltInMenu, dxSkinsCore, dxSkinsDefaultPainters, cxCalendar, cxCurrencyEdit, Vcl.ExtCtrls, Vcl.Menus, System.Actions, Vcl.ActnList, dxBar, cxBarEditItem, cxClasses, Vcl.ComCtrls, cxInplaceContainer, cxDBTL, cxTLData, ProductsViewModel, ProductsBaseView0; type TViewProductsBasket2 = class(TViewProductsBase1) actBasketClear: TAction; actBasketDelete: TAction; dxBarButton2: TdxBarButton; dxBarButton3: TdxBarButton; dxBarButton4: TdxBarButton; dxBarButton5: TdxBarButton; dxBarButton6: TdxBarButton; procedure actBasketClearExecute(Sender: TObject); procedure actBasketDeleteExecute(Sender: TObject); procedure cxDBTreeListEditing(Sender: TcxCustomTreeList; AColumn: TcxTreeListColumn; var Allow: Boolean); private function GetBasketViewModel: TProductsViewModel; procedure SetBasketViewModel(const Value: TProductsViewModel); { Private declarations } protected function CreateProductView: TViewProductsBase0; override; procedure InitializeColumns; override; public constructor Create(AOwner: TComponent); override; procedure UpdateView; override; property BasketViewModel: TProductsViewModel read GetBasketViewModel write SetBasketViewModel; { Public declarations } end; implementation uses DialogUnit; {$R *.dfm} constructor TViewProductsBasket2.Create(AOwner: TComponent); begin inherited; Name := 'ViewProductsBasket'; end; procedure TViewProductsBasket2.actBasketClearExecute(Sender: TObject); var Arr: TArray<Integer>; begin if not TDialog.Create.ClearBasketDialog then Exit; Arr := W.ID.AsIntArray; // Отвязываем полностью cxDBTreeList от данных!!! W.DataSource.Enabled := False; try BasketViewModel.qProducts.DeleteFromBasket(Arr); finally W.DataSource.Enabled := True; end; end; procedure TViewProductsBasket2.actBasketDeleteExecute(Sender: TObject); begin inherited; BeginUpdate; try BasketViewModel.qProducts.DeleteFromBasket(GetSelectedID); finally EndUpdate; end; end; function TViewProductsBasket2.CreateProductView: TViewProductsBase0; begin Result := TViewProductsBasket2.Create(nil); end; procedure TViewProductsBasket2.cxDBTreeListEditing(Sender: TcxCustomTreeList; AColumn: TcxTreeListColumn; var Allow: Boolean); begin inherited; Allow := AColumn = clSaleCount; end; function TViewProductsBasket2.GetBasketViewModel: TProductsViewModel; begin Result := Model as TProductsViewModel; end; procedure TViewProductsBasket2.InitializeColumns; begin inherited; Assert(M <> nil); // clSaleCount.Position.Band.Position.ColIndex := 1; // clSaleR.Position.Band.Position.ColIndex := 2; InitializeLookupColumn(clStorehouseId, BasketViewModel.qStoreHouseList.W.DataSource, lsEditFixedList, BasketViewModel.qStoreHouseList.W.Abbreviation.FieldName); end; procedure TViewProductsBasket2.SetBasketViewModel (const Value: TProductsViewModel); begin if Value = Model then Exit; Model := Value; MyApplyBestFit; end; procedure TViewProductsBasket2.UpdateView; var OK: Boolean; begin inherited; OK := (cxDBTreeList.DataController.DataSource <> nil) and (M <> nil) and (BasketViewModel.qProductsBase.FDQuery.Active); actBasketDelete.Enabled := OK and (cxDBTreeList.FocusedNode <> nil) and (cxDBTreeList.SelectionCount > 0) and (cxDBTreeList.DataController.DataSet.RecordCount > 0); actBasketClear.Enabled := OK and (cxDBTreeList.DataController.DataSet.RecordCount > 0); end; end.
unit ControllerConversor_U; interface {$region 'Uses interface'} uses Pattern.Singleton_U, Classes; {$endregion} type TControllerConversor = class private Data: TStringList; Dados: string; FDelimitador: string; FPalavrasDireita: Integer; FPalavrasEsquerda: Integer; procedure ProcessarDados; procedure ConfigurarDataString; procedure LimparLixoDosDados; function QuebrarNome(Posicao: Integer): Integer; function QuebrarProximaPalavra(Posicao: Integer): Integer; function QuebrarPalavraAnterior(Posicao: Integer): Integer; const NewDelimitador = '@@'; LetrasMaiusculas = 'ABCDEFGHIJKLMNOPQRSTUVWXYZÁÉÍÓÚÀÈÌÒÙÂÊÎÔÛÃÕÇ .'; public constructor Create; procedure DeletarEntre(Inicio, Fim: string); procedure SubstituirEntre(Inicio, Fim: string); function LerArquivo: TStringList; function GetData: TStringList; property Delimitador: string write FDelimitador; property PalavrasDireita: Integer write FPalavrasDireita; property PalavrasEsquerda: Integer write FPalavrasEsquerda; destructor Destroy; override; end; ControllerConversor = TSingleton<TControllerConversor>; implementation {$region 'Uses implementation'} uses DM_U, SysUtils, Forms; {$endregion} constructor TControllerConversor.Create; begin inherited; Data := TStringList.Create; end; destructor TControllerConversor.Destroy; begin inherited; FreeAndNil(Data); end; procedure TControllerConversor.ConfigurarDataString; begin Data.Clear; Data.LoadFromFile(DM.OpenDialog.FileName, TEncoding.UTF8); Data.Clear; Dados := EmptyStr; Application.ProcessMessages; end; procedure TControllerConversor.LimparLixoDosDados; var I: Integer; begin Dados := StringReplace(Dados, ';', '.', [rfReplaceAll]); Dados := StringReplace(Dados, FDelimitador, NewDelimitador, [rfReplaceAll]); for I := 0 to 3 do Dados := StringReplace(Dados, ' ', ' ', [rfReplaceAll]); end; function TControllerConversor.LerArquivo: TStringList; var Linha: string; I: Integer; InicioRegistro: Boolean; DadosBrutos: TStringList; begin DadosBrutos := TStringList.Create; DadosBrutos.LoadFromFile(DM.OpenDialog.FileName, TEncoding.UTF8); InicioRegistro := False; ConfigurarDataString; for I := 0 to Pred(DadosBrutos.Count) do begin Linha := DadosBrutos[I]; Application.ProcessMessages; if (Length(Linha) > 0) and (String('0123456789').Contains(Linha.Chars[0])) then begin //inicia nova linha do CSV if InicioRegistro then begin LimparLixoDosDados; ProcessarDados; Dados := StringReplace(Dados, NewDelimitador, FDelimitador, [rfReplaceAll]); Data.Add(Dados); end; InicioRegistro := True; Dados := EmptyStr; end; if InicioRegistro then Dados := Dados + ' ' + Linha + ' '; end; for I := Pred(Data.Count) downto 0 do begin if Data[I].Trim = EmptyStr then Data.Delete(I); end; DadosBrutos.Free; Result := Data; end; procedure TControllerConversor.ProcessarDados; var UltimaPosicao, LengthDados, I, J: Integer; PalavrasEsquerda: string; PosEsquerda, PosDireita: Integer; begin LengthDados := Pred(Length(Dados)) - 1; UltimaPosicao := LengthDados; for I := LengthDados downto 0 do begin Application.ProcessMessages; if (Dados[I] = '@') and (Dados[I + 1] = '@') and ((UltimaPosicao + 3) > I) then begin UltimaPosicao := I; Insert(';', Dados, I); PosDireita := QuebrarNome(I+5); PosEsquerda := I; for J := 0 to Pred(FPalavrasDireita) do PosDireita := QuebrarProximaPalavra(PosDireita + 2); for J := 0 to Pred(FPalavrasEsquerda) do PosEsquerda := QuebrarPalavraAnterior(PosEsquerda); // garantir que o nome ficará smepre na mesma coluna; for J := 0 to Pred(FPalavrasEsquerda) do begin PalavrasEsquerda := Copy(Dados, 0, Pos('@', Dados)); if PalavrasEsquerda.CountChar(';') < FPalavrasEsquerda then Insert(';', Dados, Pos('@', Dados)); end; end; end; end; function TControllerConversor.QuebrarProximaPalavra(Posicao: Integer): Integer; var PosAtual, LengthDados: Integer; begin Result := Posicao; LengthDados := Pred(Length(Dados)) - 1; PosAtual := Posicao; while (PosAtual < LengthDados) do begin if (Dados[PosAtual] = ' ') then begin Insert(';', Dados, PosAtual); Exit(PosAtual); end; Inc(PosAtual); end; end; function TControllerConversor.QuebrarPalavraAnterior(Posicao: Integer): Integer; var PosAtual: Integer; begin Result := Posicao; PosAtual := Posicao; while (PosAtual > 1) do begin if (Dados[PosAtual] = ' ') then begin Insert(';', Dados, PosAtual); Exit(PosAtual); end; PosAtual := Pred(PosAtual); end; end; function TControllerConversor.QuebrarNome(Posicao: Integer): Integer; var PosAtual, LengthDados: Integer; begin Result := Posicao; LengthDados := Pred(Length(Dados)) - 1; PosAtual := Posicao; while (PosAtual < LengthDados) do begin if not (LetrasMaiusculas.Contains(Dados[PosAtual])) then begin Insert(';', Dados, PosAtual -1); exit(PosAtual -1); end; Inc(PosAtual); end; end; procedure TControllerConversor.DeletarEntre(Inicio, Fim: string); var Linha: String; I: Integer; PosInicial, PosFinal: Integer; begin for I := 0 to Pred(Data.Count) do begin Linha := Data[I]; PosInicial := Pos(Inicio, Linha); PosFinal := Pos(Fim, Copy(Linha, PosInicial, Length(Linha))) + PosInicial; Delete(Linha, PosInicial, (PosFinal - PosInicial)); Data[I] := Linha; end; end; procedure TControllerConversor.SubstituirEntre(Inicio, Fim: string); var I: Integer; begin for I := 0 to Pred(Data.Count) do Data[I] := StringReplace(Data[I], Inicio, Fim, [rfReplaceAll]); end; function TControllerConversor.GetData: TStringList; begin Result := Data; end; end.
unit UnImpressaoRelatorio; {Verificado -.edit; } interface uses Menus, Classes, SysUtils, Forms, Sqlexpr,Tabela; type TRBModulosRelatorio = (mrEstoque,mrPontoLoja,mrFinanceiro,mrFaturamento,mrChamado,mrCRM,mrCaixa,mrTodos); TImpressaoRelatorio = class private Aux : TSql; function RelatorioAutorizado(VpaNomRelatorio : string):boolean; procedure ImprimirFiltroPedido(Sender: TObject); procedure MarcaMenu(Sender: TObject); function RelatorioModulo(VpaModulo : TRBModulosRelatorio;VpaNomArquivo : String) : Boolean; function ExisteRelatorioModulo(VpaModulo : TRBModulosRelatorio;VpaDiretorio : String):Boolean; procedure AdicionaRelatoriosDiretorio(VpaModulo :TRBModulosRelatorio;VpaMenu : TMenuItem;VpaNomDiretorio : String); function MenuRaiz(VpaItemAtual: TMenuItem): TMenuItem; function IdentificadorRepetido(VpaItemMenu: TMenuItem; VpaIdentificador: string): boolean; function AdicionarSubItem(VpaItemMenu: TMenuItem; VpaPathDiretorio: string): TMenuItem; procedure SetarEventoImpressao(VpaItemMenu: TMenuItem; VpaPathArquivo: string;VpaModulo :TRBModulosRelatorio); procedure AdicionarArquivo(VpaItemMenu: TMenuItem; VpaPathArquivo: string;VpaModulo :TRBModulosRelatorio); public constructor cria(VpaBaseDados : TSQLConnection); destructor destroy;override; procedure CarregarMenuRel(VpaModuloAtual: TRBModulosRelatorio; VpaMenuRel: TMenuItem); end; implementation uses FunArquivos, ConstMsg, FunString, ARelPedido, constantes, FunSql; {******************************************************************************} procedure TImpressaoRelatorio.ImprimirFiltroPedido(Sender: TObject); var VpfPathRel, VpfNomeRel: string; begin VpfPathRel := TMenuItem(Sender).hint; TMenuItem(Sender).Caption := DeletaChars(TMenuItem(Sender).Caption,'&'); VpfNomeRel := TMenuItem(Sender).Caption; FRelPedido := TFRelPedido.CriarSDI(application,TMenuItem(Sender).Caption,true); FRelPedido.CarregarRelatorio(VpfPathRel, VpfNomeRel); end; {******************************************************************************} function TImpressaoRelatorio.RelatorioAutorizado(VpaNomRelatorio: string): boolean; begin VpaNomRelatorio := copy(VpaNomRelatorio,length(varia.PathRelatorios)+1,length(VpaNomRelatorio)); if copy(VpaNomRelatorio,1,1) = '\' then VpaNomRelatorio := copy(VpaNomRelatorio,2,length(VpaNomRelatorio)); AdicionaSQLAbreTabela(Aux,'Select * from GRUPOUSUARIORELATORIO ' + ' WHERE CODGRUPO = '+IntToStr(VARIA.GrupoUsuario)+ ' and NOMRELATORIO = '''+VpaNomRelatorio+''''); result := not Aux.Eof; Aux.Close; end; {******************************************************************************} function TImpressaoRelatorio.RelatorioModulo(VpaModulo : TRBModulosRelatorio;VpaNomArquivo : String) : Boolean; var VpfLetrasModulo : String; begin result := false; if VpaModulo = mrtodos then begin result := true; exit; end; VpaNomArquivo := copy(VpaNomArquivo, NPosicao('\', VpaNomArquivo,ContaLetra(VpaNomarquivo, '\')) + 1,70); VpaNomArquivo := CopiaAteChar(VpaNomArquivo,'_'); while length(VpaNomArquivo) > 1 do begin VpfLetrasModulo := UpperCase(Copy(VpaNomArquivo,1,2)); if (VpaModulo = mrEstoque) then begin if VpfLetrasModulo = 'ES' then result := true; end else if (VpaModulo = mrPontoLoja) then begin if VpfLetrasModulo = 'PL' then result := true; end else if (VpaModulo = mrFinanceiro) then begin if VpfLetrasModulo = 'FI' then result := true; end else if (VpaModulo = mrFaturamento) then begin if VpfLetrasModulo = 'FA' then result := true; end else if (VpaModulo = mrChamado) then begin if VpfLetrasModulo = 'CH' then result := true; end else if (VpaModulo = mrCRM) then begin if VpfLetrasModulo = 'CR' then result := true; end else if (VpaModulo = mrCaixa) then begin if VpfLetrasModulo = 'CA' then result := true; end; if result then exit; VpaNomArquivo := copy(VpaNomArquivo,3,length(VpaNomArquivo)-2); end; end; {******************************************************************************} function TImpressaoRelatorio.ExisteRelatorioModulo(VpaModulo : TRBModulosRelatorio;VpaDiretorio : String):Boolean; var VpfLaco : Integer; VpfArquivos,VpfDiretorios : TStringList; begin result := false; VpfDiretorios := RetornaListaDeSubDir(VpaDiretorio); for VpfLaco := 0 to VpfDiretorios.Count - 1 do begin result := ExisteRelatorioModulo(VpaModulo,VpfDiretorios.Strings[VpfLaco]); if result then exit; end; VpfDiretorios.free; VpfArquivos := RetornaListaDeArquivos(VpaDiretorio,'*.rav'); for VpfLaco := 0 to VpfArquivos.Count - 1 do begin if (puSomenteRelatoriosAutorizados in varia.PermissoesUsuario ) and (VpaModulo <> mrTodos) then begin if not RelatorioAutorizado(VpfArquivos.Strings[VpfLaco]) then continue; end; if RelatorioModulo(VpaModulo,VpfArquivos.Strings[VpfLaco]) then begin result := true; exit; end; end; end; {******************************************************************************} procedure TImpressaoRelatorio.AdicionaRelatoriosDiretorio(VpaModulo :TRBModulosRelatorio;VpaMenu : TMenuItem;VpaNomDiretorio : String); var VpfLaco : Integer; VpfArquivos,VpfDiretorios : TStringList; VpfItemMenu: TMenuItem; begin VpfDiretorios := RetornaListaDeSubDir(VpaNomDiretorio); for VpfLaco := 0 to VpfDiretorios.Count - 1 do begin if ExisteRelatorioModulo(VpaModulo,VpfDiretorios.Strings[VpfLaco]) then begin VpfItemMenu := AdicionarSubItem(VpaMenu, VpfDiretorios.Strings[VpfLaco]); AdicionaRelatoriosDiretorio(VpaModulo,VpfItemMenu,VpfDiretorios.Strings[VpfLaco]); end; end; VpfDiretorios.free; VpfArquivos := RetornaListaDeArquivos(VpaNomDiretorio,'*.rav'); for VpfLaco := 0 to VpfArquivos.Count - 1 do begin if (puSomenteRelatoriosAutorizados in varia.PermissoesUsuario ) and (VpaModulo <> mrTodos) then begin if not RelatorioAutorizado(VpfArquivos.Strings[VpfLaco]) then continue; end; if RelatorioModulo(VpaModulo,VpfArquivos.Strings[VpfLaco]) then begin AdicionarArquivo(VpaMenu,VpfArquivos.Strings[VpfLaco],VpaModulo); end; end; VpfArquivos.free; end; {******************************************************************************} procedure TImpressaoRelatorio.MarcaMenu(Sender: TObject); begin TMenuItem(Sender).Checked := not TMenuItem(Sender).Checked; // aviso(TMenuItem(Sender).Hint); end; {******************************************************************************} function TImpressaoRelatorio.MenuRaiz(VpaItemAtual: TMenuItem): TMenuItem; begin Result := VpaItemAtual; while Result.Parent <> nil do Result := Result.Parent; end; { ***** Verifica se ja existe um item de menu com o mesmo identificador ****** } function TImpressaoRelatorio.IdentificadorRepetido(VpaItemMenu: TMenuItem; VpaIdentificador: string): boolean; var VpfItemAux: TMenuItem; VpfLaco: integer; begin Result := false; VpfItemAux := VpaItemMenu; VpfLaco := 0; while (VpfLaco < VpfItemAux.Count) and (not Result) do begin Result := VpaIdentificador = copy(VpfItemAux.Items[VpfLaco].Caption, 0, 4); inc(VpfLaco); end; VpfLaco := 0; while (VpfLaco < VpfItemAux.Count) and (not Result) do begin if VpfItemAux.Items[VpfLaco].Count > 0 then Result := IdentificadorRepetido(VpfItemAux.Items[VpfLaco], VpaIdentificador); inc(VpfLaco); end; end; { Adiciona um item no menu que corresponde ao diretorio onde esta o relatorio } function TImpressaoRelatorio.AdicionarSubItem(VpaItemMenu: TMenuItem; VpaPathDiretorio: string): TMenuItem; begin Result := TMenuItem.Create(VpaItemMenu); Result.Caption := copy(VpaPathDiretorio, NPosicao('\', VpaPathDiretorio,ContaLetra(VpaPathDiretorio, '\')) + 1,30); VpaItemMenu.Add(Result); end; { *** Seta o evento de impressao para o relatorio conforme sua localização *** } procedure TImpressaoRelatorio.SetarEventoImpressao(VpaItemMenu: TMenuItem; VpaPathArquivo: string;VpaModulo :TRBModulosRelatorio); var VpfDirArquivo, VpfPathExe: string; begin VpfPathExe := ExtractFilePath(Application.ExeName); VpfDirArquivo := ExtractFilePath(VpaPathArquivo); if VpaModulo = mrTodos then VpaItemMenu.OnClick := MarcaMenu else VpaItemMenu.OnClick := ImprimirFiltroPedido; end; { ** Adiciona o relatório contido em "VpaPathArquivo" no menu "VpaItemMenu" ** } procedure TImpressaoRelatorio.AdicionarArquivo(VpaItemMenu: TMenuItem; VpaPathArquivo: string;VpaModulo :TRBModulosRelatorio); var VpfItemMenu: TMenuItem; VpfNomeRel, VpfIdentif: string; begin VpfNomeRel := CopiaAteChar(ExtractFileName(VpaPathArquivo), '.'); VpfIdentif := copy(VpfNomeRel, 1, 4); VpfItemMenu := TMenuItem.Create(VpaItemMenu); VpfItemMenu.Caption := DeleteAteChar(VpfNomeRel,'_'); VpfItemMenu.Hint := VpaPathArquivo; SetarEventoImpressao(VpfItemMenu, VpaPathArquivo,VpaModulo); if VpaModulo = mrTodos then begin if RelatorioAutorizado(VpaPathArquivo) then VpfItemMenu.Checked := true; end; VpaItemMenu.Add(VpfItemMenu); end; { **** Carrega os relatórios contidos em "VpaDiretorio", no "VpaMenuRel" ***** } procedure TImpressaoRelatorio.CarregarMenuRel(VpaModuloAtual: TRBModulosRelatorio; VpaMenuRel: TMenuItem); var VpfListaDiretorios : TStringList; VpfLaco: integer; VpfItemMenu: TMenuItem; VpfDiretorio : String; begin VpfDiretorio := varia.PathRelatorios; if ExisteDiretorio(VpfDiretorio) then begin VpfListaDiretorios := RetornaListaDeSubDir(VpfDiretorio); for VpfLaco := 0 to VpfListaDiretorios.Count -1 do begin if ExisteRelatorioModulo(VpaModuloAtual,VpfListaDiretorios.Strings[VpfLaco]) then begin VpfItemMenu := AdicionarSubItem(VpaMenuRel, VpfListaDiretorios.Strings[VpfLaco]); AdicionaRelatoriosDiretorio(VpaModuloAtual,VpfItemMenu,VpfListaDiretorios.Strings[VpfLaco]); end; end; VpfListaDiretorios.Free; end; end; {******************************************************************************} constructor TImpressaoRelatorio.cria(VpaBaseDados: TSQLConnection); begin inherited create; Aux := TSQl.Create(nil); Aux.ASQlConnection := VpaBaseDados; end; {******************************************************************************} destructor TImpressaoRelatorio.destroy; begin Aux.Free; inherited; end; end.
{Ejercicio 7 Se desea tener un programa que calcule el saldo de una cuenta. Suponga que los datos son leídos de la entrada estándar y que constan de renglones, cada uno de los cuales contiene una letra en la primera columna, seguida de un valor real. El último renglón contiene únicamente la letra X en la columna uno. El primer renglón contiene la letra A y el saldo anterior de una cuenta de cheques. Los demás renglones contienen la letra D y el importe de un depósito o la letra R y el importe de un retiro. Escriba un programa en PASCAL que determine el saldo exacto de la cuenta después de procesar las transacciones. Ejemplo: A 1200.35 D 64.12 R 390.00 R 289.67 D 13.02 R 51.07 X El saldo final es 546.75} program ejercicio7; var entrada : char; saldo, monto : real; begin saldo := 1200.35; writeln('A ',saldo:6:2); writeln('Ingrese datos.'); read(entrada); while (entrada <> 'X') do begin read(monto); if (entrada = 'D') then begin //read(monto); saldo := saldo + monto; //writeln(entrada, '----->', saldo:6:2); end; if (entrada = 'R') then begin //read(monto); saldo := saldo - monto; //writeln(entrada, '----->', saldo:6:2); end; //write('leer entrada ---->'); readln; //CERRAR EL READ read(entrada); //VOLVER A LEER LA ENTRADA end; writeln('El saldo final es ',saldo:6:2) end.
(* Name: Glossary Copyright: Copyright (C) SIL International. Documentation: Description: Create Date: 20 Jun 2006 Modified Date: 28 May 2014 Authors: mcdurdin Related Files: Dependencies: Bugs: Todo: Notes: History: 20 Jun 2006 - mcdurdin - Initial version 02 Aug 2006 - mcdurdin - Add HKLIsIME function (tests if IMM is installed before ImmIsIME) 23 Aug 2007 - mcdurdin - I981 - Fix ImmIsIME to be always ignored on Vista 03 May 2011 - mcdurdin - I2890 - Record diagnostic data when encountering registry errors 18 May 2012 - mcdurdin - I3306 - V9.0 - Remove TntControls + Win9x support 01 Jan 2013 - mcdurdin - I3724 - V9.0 - GetLanguageName function needs to be general 17 Jan 2013 - mcdurdin - I3763 - V9.0 - GetLanguageName refactor 23 Jan 2013 - mcdurdin - I3774 - V9.0 - Regression KMCOMAPI IKeymanLanguage returns region-free language name, incorrectly 16 Apr 2014 - mcdurdin - I4169 - V9.0 - Mnemonic layouts should be recompiled to positional based on user-selected base keyboard 28 May 2014 - mcdurdin - I4220 - V9.0 - Remove references to LoadKeyboardLayout, Preload, Substitutes, etc. and use only TSF *) unit Glossary; // I3306 interface uses System.Classes, System.SysUtils, Winapi.Imm, Winapi.Windows, ErrorControlledRegistry, RegistryKeys; type PHKL = ^HKL; function KeyboardIDToHKL(KeyboardID: DWord): HKL; deprecated; // I4220 function HKLToKeyboardID(ahkl: HKL): DWord; function HKLToLanguageID(ahkl: HKL): Word; function HKLToLayoutNumber(ahkl: HKL): Word; function HKLToLayoutID(ahkl: HKL): Word; function MAKELCID(lgid, srtid: Word): DWord; function MAKELANGID(prilangid, sublangid: Word): Word; function IsKeymanLayout(layout: DWord): Boolean; function IsKeymanHKL(ahkl: HKL): Boolean; function GetLanguageName(langid: Word; var LanguageName: string; IncludeRegion: Boolean = False): Boolean; // I3724 // I3763 // I3774 function GetKeyboardLayouts(var count: Integer): PHKL; // I4169 implementation uses GetOsVersion; function GetKeyboardLayouts(var count: Integer): PHKL; // I4169 begin Result := nil; count := GetKeyboardLayoutList(0, Result^); Result := AllocMem(count * SizeOf(HKL)); if Assigned(Result) then GetKeyboardLayoutList(count, Result^); end; function KeyboardIDToHKL(KeyboardID: DWord): HKL; var i, n: Integer; hp, hkls: PHKL; begin Result := 0; hkls := nil; n := GetKeyboardLayoutList(0, hkls^); hkls := AllocMem(n * SizeOf(HKL)); if not Assigned(hkls) then Exit; hp := hkls; GetKeyboardLayoutList(n, hkls^); for i := 0 to n-1 do if HKLToKeyboardID(hp^) = KeyboardID then begin Result := hp^; Break; end; FreeMem(hkls); end; function HKLToKeyboardID(ahkl: HKL): DWord; var i, LayoutID: Integer; str: TStringList; begin // Test for IME, and if IME return LanguageID //if((HIWORD(hkl) & 0xF000) == 0xE000) return (DWORD) hkl; // Test for standard layouts: 0409041D for instance // specialised layout is: F0020409 fr instance [find layout id:0002] if LOWORD(ahkl) = 0 then begin // Look up the HKL in the registry to get substitutes with TRegistryErrorControlled.Create do // I2890 try if OpenKeyReadOnly('\'+SRegKey_KeyboardLayoutSubstitutes) and ValueExists(IntToHex(HIWORD(ahkl), 8)) then begin Result := StrToIntDef('$'+ReadString(IntToHex(HIWORD(ahkl), 8)), 0); Exit; end; finally Free; end; end; LayoutID := HKLToLayoutID(ahkl); if LayoutID = 0 then begin Result := HIWORD(ahkl); Exit; end; // Find the KeyboardID associated with the LayoutID str := TStringList.Create; with TRegistryErrorControlled.Create do // I2890 try RootKey := HKEY_LOCAL_MACHINE; if not OpenKeyReadOnly(SRegKey_KeyboardLayouts) then begin Result := LOWORD(ahkl); Exit; end; GetKeyNames(str); for i := 0 to str.Count - 1 do if OpenKeyReadOnly('\'+SRegKey_KeyboardLayouts+'\'+str[i]) and ValueExists(SRegValue_KeyboardLayoutID) then begin if StrToIntDef('$'+ReadString(SRegValue_KeyboardLayoutID), 0) = LayoutID then begin Result := StrToIntDef('$'+str[i], 0); if Result = 0 then Result := LOWORD(ahkl); Exit; end; end; finally Free; str.Free; end; Result := LOWORD(ahkl); // should never happen end; function HKLToLanguageID(ahkl: HKL): Word; begin Result := LOWORD(ahkl); end; function HKLToLayoutNumber(ahkl: HKL): Word; var LayoutID: Word; i: Integer; str: TStringList; begin Result := 0; LayoutID := HKLToLayoutID(ahkl); if LayoutID = 0 then Exit; str := TStringList.Create; with TRegistryErrorControlled.Create do // I2890 try RootKey := HKEY_LOCAL_MACHINE; if not OpenKeyReadOnly(SRegKey_KeyboardLayouts) then Exit; GetKeyNames(str); for i := 0 to str.Count - 1 do if OpenKeyReadOnly('\'+SRegKey_KeyboardLayouts+'\'+str[i]) and ValueExists(SRegValue_KeyboardLayoutID) then if StrToIntDef('$' + ReadString(SRegValue_KeyboardLayoutID), 0) = LayoutID then begin Result := HIWORD(StrToIntDef('$'+str[i], 0)); Exit; end; finally Free; str.Free; end; end; function HKLToLayoutID(ahkl: HKL): Word; begin if (HIWORD(ahkl) and $F000) <> $F000 then Result := 0 else Result := HIWORD(ahkl) and $0FFF; end; function MAKELCID(lgid, srtid: Word): DWord; begin Result := (DWord(srtid) shl 16) or lgid; end; function IsKeymanHKL(ahkl: HKL): Boolean; begin Result := IsKeymanLayout(HKLToKeyboardID(ahkl)); end; function IsKeymanLayout(layout: DWord): Boolean; begin Result := LOWORD(layout) = $05FE; end; function MAKELANGID(prilangid, sublangid: Word): Word; begin Result := prilangid or (sublangid shl 10); end; const LOCALE_SLANGDISPLAYNAME = $6f; function GetLanguageName(langid: Word; var LanguageName: string; IncludeRegion: Boolean = False): Boolean; // I3724 // I3763 // I3774 var szLangName: array[0..MAX_PATH] of char; LCType: Cardinal; begin if IncludeRegion then LCType := LOCALE_SLANGUAGE // I3774 else LCType := LOCALE_SLANGDISPLAYNAME; Result := GetLocaleInfo(langid, LCType, szLangName, MAX_PATH) <> 0; if Result then LanguageName := Copy(szLangName, 0, MAX_PATH - 1) else LanguageName := 'Unknown '+IntToHex(langid, 8); end; end.
unit Fix.REST.Client; interface uses REST.Client; type TRESTClient = class(REST.Client.TRESTClient) function GetEntity<T: class, constructor>(const AResource: string): T; end; implementation uses REST.Json, REST.Types; { TRESTClient } function TRESTClient.GetEntity<T>(const AResource: string): T; var LRequest: TRESTRequest; begin LRequest := TRESTRequest.Create(Self); try LRequest.Method := rmGET; LRequest.Resource := AResource; LRequest.Execute; Result := TJson.JsonToObject<T>(LRequest.Response.JSONText); finally LRequest.Free; end; end; end.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------ //单元说明: // //主要实现: //-----------------------------------------------------------------------------} unit untEasyPlateMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, untEasyPlateBaseForm, Menus, untEasyMenus, untEasyMenuStylers, untEasyStatusBar, untEasyStatusBarStylers, untEasyToolBar, TypInfo, untEasyToolBarStylers, untEasyTabSet, untEasyOfficeTabSetStylers, untEasyPageControl, ExtCtrls, untEasyTrayIcon, ImgList, ComCtrls, untEasyTreeView, untEasyWaterImage, jpeg, StdCtrls, ActnList, Provider, DB, DBClient, xmldom, XMLIntf, msxmldom, XMLDoc, untEasyPlateDBBaseForm, AppEvnts, untEasyClassPluginDirectory, untEasyClasssysUser, untEasyClasshrEmployee; type TfrmEasyPlateMain = class(TfrmEasyPlateDBBaseForm) mmMain: TEasyMainMenu; pmMain: TEasyPopupMenu; mmstyleMain: TEasyMenuOfficeStyler; mmNew: TMenuItem; stbMain: TEasyStatusBar; stbStyleMain: TEasyStatusBarOfficeStyler; EasyDockPanel1: TEasyDockPanel; tlbMain: TEasyToolBar; tlbStyleMain: TEasyToolBarOfficeStyler; EasyMDITabSet1: TEasyMDITabSet; tbsStyleMain: TEasyTabSetOfficeStyler; EasyTrayIcon1: TEasyTrayIcon; pgcLeftNav: TEasyPageControl; Splitter1: TSplitter; tsbSysNav: TEasyTabSheet; tshWorkAssiant: TEasyTabSheet; tshEIM: TEasyTabSheet; imgNav: TImageList; tvNav: TEasyTreeView; actEasyMain: TActionList; img24: TImageList; actExit: TAction; EasyToolBarButton1: TEasyToolBarButton; img24_d: TImageList; EasyToolBarSeparator1: TEasyToolBarSeparator; File1: TMenuItem; Exit1: TMenuItem; N1: TMenuItem; PrintSetup1: TMenuItem; Help1: TMenuItem; About1: TMenuItem; EpResourceManage: TMenuItem; SearchforHelpOn1: TMenuItem; Contents1: TMenuItem; Window1: TMenuItem; Show1: TMenuItem; Hide1: TMenuItem; N3: TMenuItem; ArrangeAll1: TMenuItem; Cascade1: TMenuItem; ile1: TMenuItem; T1: TMenuItem; img16: TImageList; img16_d: TImageList; actVisibleNav: TAction; EasyToolBarButton2: TEasyToolBarButton; cdsMain: TClientDataSet; ppMenuTrayIcon: TEasyPopupMenu; N4: TMenuItem; N5: TMenuItem; imgtv: TImageList; tvNavPP: TEasyPopupMenu; N6: TMenuItem; N7: TMenuItem; N8: TMenuItem; N9: TMenuItem; N10: TMenuItem; ppTVRefresh: TMenuItem; actAbout: TAction; ppTabList: TEasyPopupMenu; EasyWaterImage1: TEasyWaterImage; ppMDITab: TEasyPopupMenu; N11: TMenuItem; cdsMainTV: TClientDataSet; actConnectDB: TAction; N2: TMenuItem; N12: TMenuItem; N13: TMenuItem; procedure FormDestroy(Sender: TObject); procedure actExitExecute(Sender: TObject); procedure actVisibleNavExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure tvNavExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean); procedure N6Click(Sender: TObject); procedure N7Click(Sender: TObject); procedure tvNavDblClick(Sender: TObject); procedure About1Click(Sender: TObject); procedure N11Click(Sender: TObject); procedure ppTVRefreshClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure EpResourceManageClick(Sender: TObject); procedure actConnectDBExecute(Sender: TObject); procedure ile1Click(Sender: TObject); procedure Cascade1Click(Sender: TObject); procedure ArrangeAll1Click(Sender: TObject); procedure N12Click(Sender: TObject); procedure N13Click(Sender: TObject); private { Private declarations } //不允许关闭的Tab列表 以Caption为准 NotCloseTab: TStrings; //传递到插件中的参数列表 FPluginParams: TStrings; //显示当前用户信息 procedure DisplayCurrUserInfo(UserID: string); //初始化状态栏 procedure InitStbMain; //导航树 procedure InitTreeViewNav; //主菜单 procedure InitMainMenu; //工具栏 procedure InitToolBar; //待办工作 procedure InitWorks; //即时通讯 procedure InitEIM; //初始化当前登录用户信息、员工信息 procedure InitCurrLoginUserInfo(ACds: TClientDataSet; ASysUser: TEasysysUser); //关闭子窗体时的事件 procedure ChildFormClose(Sender: TObject; var Action: TCloseAction); //初始化系统 全部入在Init_LoadPlugs统一进度窗体调用 function Init_LoadPlugs: Boolean; //加载指定的插件文件 function LoadPlugFile: Boolean; //显示用户登录窗体 procedure ShowCheckLoginUser(); //加载子节点 procedure LoadChildTreeNodes(ATreeView: TEasyTreeView; ADataList: TList; ParentNode: TTreeNode); //判断插件是否已经加载过,如果加载过则激活 function CheckHasLoaded(APluginFile: string): Boolean; public { Public declarations } EasyLoginUserID: string; //登录用户编号/名 end; var frmEasyPlateMain: TfrmEasyPlateMain; implementation {$R *.dfm} uses untEasyUtilInit, untEasyDBConnection, untEasyUtilDLL, untEasyUtilMethod, untEasyUtilClasses, untEasyPlateLoading, untEasyUtilConst, untEasyProgressBar, untEasyLoginMain, untEasyPlateResourceManage; const PluginDirectorySQL = 'SELECT * FROM vwSysPluginsDirectory ORDER BY IsDirectory, iOrder'; PluginParamSQL = 'SELECT * FROM vwSysPluginParams ORDER BY ParamName'; procedure TfrmEasyPlateMain.DisplayCurrUserInfo(UserID: string); begin //为空时按下的可能是取消 在按下取消时将登录用户名置空 if Trim(UserID) = '' then begin Application.Terminate; end; with cdsMain do begin cdsMain.Data := EasyRDMDisp.EasyGetRDMData('SELECT * FROM vw_inituser WHERE UserName = ' + QuotedStr(UserID)); if cdsMain.RecordCount = 1 then begin stbMain.Panels[0].Text := '<p color="clblue">' + EASY_DISPLAYUSERINFO_WELCOME + fieldbyname('EmployeeCName').AsString + '</p>'; stbMain.Panels[1].Text := '<p color="clblue">' + EASY_DISPLAYUSERINFO_DEPT + '</p>'; // Close; end else if cdsMain.RecordCount > 1 then begin //一个帐户对应多个员工系统,一般不会发生,防止更改数据库出错 Close; Application.MessageBox(PChar(EASY_DISPLAYUSERINFO_MORE), PChar(EASY_SYS_HINT), MB_OK + MB_ICONWARNING); Application.Terminate; end else begin //帐户不存在人员使用 Close; Application.MessageBox(PChar(EASY_DISPLAYUSERINFO_NULL), PChar(EASY_SYS_HINT), MB_OK + MB_ICONWARNING); Application.Terminate; end; //设置到DM DMEasyDBConnection.EasyCurrLoginUserID := UserID; with DMEasyDBConnection.EasyCurrLoginSysUser do begin //1 UserGUID UserGUID := cdsMain.FieldByName('UserGUID').AsString; //2 UserName UserName := cdsMain.FieldByName('UserName').AsString; //3 PassWord PassWord := cdsMain.FieldByName('PassWord').AsString; //4 EmployeeGUID EmployeeGUID := cdsMain.FieldByName('EmployeeGUID').AsString; //5 IsEnable IsEnable := cdsMain.FieldByName('IsEnable').AsBoolean; //6 EndDate EndDate := cdsMain.FieldByName('EndDate').AsDateTime; //7 RoleGUID RoleGUID := cdsMain.FieldByName('RoleGUID').AsString; //8 CreateTime CreateTime := cdsMain.FieldByName('CreateTime').AsDateTime; //9 CreaterGUID CreaterGUID := cdsMain.FieldByName('CreaterGUID').AsString; end; end; end; procedure TfrmEasyPlateMain.FormDestroy(Sender: TObject); begin FPluginParams.Free; //不允许关闭的子窗体列表 NotCloseTab.Free; inherited; end; procedure TfrmEasyPlateMain.InitEIM; begin end; procedure TfrmEasyPlateMain.InitMainMenu; var I : Integer; //在菜单上创建模块时使用 TmpMenuItem, DestMenuItem : TMenuItem; begin mmMain.BeginUpdate; for I := 0 to PluginDirectoryList.Count - 1 do begin with TEasysysPluginsDirectory(PluginDirectoryList[I]) do begin if ParentPluginGUID = EasyRootGUID then begin //创建模块菜单 TmpMenuItem := TMenuItem.Create(mmMain); with TmpMenuItem do begin Caption := PluginCName; end; DestMenuItem := mmMain.Items.Find('模块(&M)'); if DestMenuItem <> nil then begin DestMenuItem.Add(TmpMenuItem); end; end; end; //加载窗体的进度条 with frmEasyPlateLoading.EasyProgressBar1 do begin if Position > Max then Position := Max - 20; Position := Position + I*2; end; end; mmMain.EndUpdate; end; procedure TfrmEasyPlateMain.InitStbMain; begin //本地时间初始化 stbMain.Panels[2].Text:='<p color="clblue"> ' + GetChinaDay + ' ' + FormatDateTime('YYYY-MM-DD', Date) + '</p>'; //网络连接信息 with stbMain.Panels[7] do begin Width := 25; Style := psImage; Text := ''; if NetInternetConnected then ImageIndex := 7 else ImageIndex := 8; end; //服务器信息 stbMain.Panels[8].Text := '<p color="clblue">' + EASY_STATUBAR_APP + DMEasyDBConnection.EasyAppType + EASY_STATUBAR_DBHOST + DMEasyDBConnection.EasyDBHost + ':' + DMEasyDBConnection.EasyDBPort + '</p>'; end; procedure TfrmEasyPlateMain.InitToolBar; begin end; procedure TfrmEasyPlateMain.InitTreeViewNav; var I: Integer; ATmpNode: TTreeNode; AData: OleVariant; begin //清空树 tvNav.Items.Clear; AData := EasyRDMDisp.EasyGetRDMData(PluginDirectorySQL); TEasysysPluginsDirectory.GeneratePluginDirectory(AData); for I := 0 to PluginDirectoryList.Count - 1 do begin with TEasysysPluginsDirectory(PluginDirectoryList[I]) do begin //如果是是根节点 且为目录 此处可不判断,在程序输入目录时作限制 if (ParentPluginGUID = EasyRootGUID) and (IsDirectory = True) then begin ATmpNode := tvNav.Items.AddChildObject(nil, PluginCName, PluginDirectoryList[I]); ATmpNode.ImageIndex := ImageIndex; ATmpNode.SelectedIndex := SelectedImageIndex; //增加临时子节点 tvNav.Items.AddChildFirst(ATmpNode, 'ChildTest'); end; end; end; cdsMainTV.Close; end; procedure TfrmEasyPlateMain.InitWorks; begin end; procedure TfrmEasyPlateMain.actExitExecute(Sender: TObject); begin inherited; Close; end; procedure TfrmEasyPlateMain.actVisibleNavExecute(Sender: TObject); begin inherited; pgcLeftNav.Visible := not pgcLeftNav.Visible; end; procedure TfrmEasyPlateMain.FormShow(Sender: TObject); begin //弹出登录窗体 进行登录验证 ShowCheckLoginUser; if Trim(EasyLoginUserID) = '' then Application.Terminate else begin inherited; //显示进度窗体 CreatePG(Init_LoadPlugs, '系统初始化...'); //显示用户信息:当前登录用户、部门 DisplayCurrUserInfo(EasyLoginUserID); // // InitCurrLoginUserInfo(cdsMain, EasyCurrLoginUser); //补充状态栏位 InitStbMain; end; //限制窗体最小宽 870 高500 Self.Constraints.MinHeight := 500; Self.Constraints.MinWidth := 870; end; procedure TfrmEasyPlateMain.FormCreate(Sender: TObject); begin inherited; //加载导航树所需要的图像 imgtv.Assign(DMEasyDBConnection.img16); //打开双缓冲 Self.DoubleBuffered := True; FPluginParams := TStringList.Create; //初始化菜单和导航树统一放在Init_LoadPlugs中由进度窗体负责 //不充许关闭的Tab标题 NotCloseTab := TStringList.Create; with NotCloseTab do begin Add('主界面'); Add('桌面'); Add('工作台'); Add('工作区'); Add('主工作台'); Add('主工作区'); Add('首页'); end; end; procedure TfrmEasyPlateMain.tvNavExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean); begin inherited; if Node.HasChildren then begin if Node.Item[0].Text = 'ChildTest' then begin Node.Item[0].Delete; //调用之前TreeView已完成PluginDirectoryList的初始化 LoadChildTreeNodes(tvNav, PluginDirectoryList, Node); end; end; end; procedure TfrmEasyPlateMain.N6Click(Sender: TObject); begin inherited; tvNav.FullExpand; end; procedure TfrmEasyPlateMain.N7Click(Sender: TObject); begin inherited; tvNav.FullCollapse; end; procedure TfrmEasyPlateMain.tvNavDblClick(Sender: TObject); var TmpPlugFileName: string; begin inherited; if tvNav.Selected = nil then Exit; if not TEasysysPluginsDirectory(tvNav.Selected.Data).IsDirectory then begin TmpPlugFileName := TEasysysPluginsDirectory(tvNav.Selected.Data).PluginFileName; if not CheckHasLoaded(TmpPlugFileName) then begin if FileExists(EasyPlugPath + TmpPlugFileName) then CreatePG_Plug(LoadPlugFile, '正在加载插件,请稍后...', tvNav.Selected) else begin Application.MessageBox(PChar('插件文件【'+ TmpPlugFileName +'】未找到,请检查系统完整性或通知系统管理员!'), '提示', MB_OK + MB_ICONSTOP); Exit; end; end; end; end; procedure TfrmEasyPlateMain.About1Click(Sender: TObject); begin inherited; LoadPkg_Normal('pkEasyAboutUS.bpl', FPluginParams); end; procedure TfrmEasyPlateMain.ChildFormClose(Sender: TObject; var Action: TCloseAction); begin //判断当前要关闭的子窗体是否允许关闭 if NotCloseTab.IndexOf(TForm(Sender).Caption) = - 1 then begin tlbMain.RemoveMDIChildMenu(TForm(Sender), TForm(Sender).Caption); Action := caFree; end; end; function TfrmEasyPlateMain.Init_LoadPlugs: Boolean; begin frmEasyPlateLoading.EasyProgressBar1.Position := 10; //先初始化导航树 再初始化主菜单 //初始化导航树 InitTreeViewNav; //初始化主菜单 InitMainMenu; Result := True; //加载窗体的进度条 with frmEasyPlateLoading.EasyProgressBar1 do begin if Position < Max then Position := Max; end; frmEasyPlateLoading.Close; end; function TfrmEasyPlateMain.LoadPlugFile: Boolean; var TmpPluginFile: String; TmpNode : TTreeNode; begin TmpNode := frmEasyPlateLoading.ATmpNode_Loading; //进度窗体进度 frmEasyPlateLoading.EasyProgressBar1.Position := 10; TmpPluginFile := EasyPlugPath + TEasysysPluginsDirectory(TmpNode.Data).PluginFileName; if Pos('.bpl', TmpPluginFile) = 0 then TmpPluginFile := TmpPluginFile + '.bpl'; if (pos('.bpl', TmpPluginFile) > 0) and (FileExists(TmpPluginFile)) then begin try LoadPkg(TmpPluginFile, FPluginParams, EasyMDITabSet1, frmEasyPlateLoading.EasyProgressBar1, ChildFormClose, 1); except on E: Exception do begin raise Exception.Create(E.Message); Exit; end; end; end; Result := True; //进度窗体进度 frmEasyPlateLoading.EasyProgressBar1.Position := 100; frmEasyPlateLoading.Close; end; procedure TfrmEasyPlateMain.N11Click(Sender: TObject); var I: Integer; begin inherited; for I := 0 to EasyMDITabSet1.ComponentCount - 1 do EasyMDITabSet1.Components[I].Free; end; procedure TfrmEasyPlateMain.ShowCheckLoginUser(); begin try frmEasyLoginMain := TfrmEasyLoginMain.Create(Application); frmEasyLoginMain.ShowModal; finally frmEasyLoginMain.Free; end; end; procedure TfrmEasyPlateMain.LoadChildTreeNodes(ATreeView: TEasyTreeView; ADataList: TList; ParentNode: TTreeNode); var I : Integer; ATmpNode: TTreeNode; begin with ATreeView do begin for I := 0 to ADataList.Count - 1 do begin with TEasysysPluginsDirectory(ADataList[I]) do begin if ParentPluginGUID = TEasysysPluginsDirectory(ParentNode.Data).PluginGUID then begin ATmpNode := ATreeView.Items.AddChildObject(ParentNode, PluginCName, ADataList[I]); ATmpNode.ImageIndex := ImageIndex; ATmpNode.SelectedIndex := SelectedImageIndex; //生成临时节点 只有目录 if IsDirectory then ATreeView.Items.AddChildFirst(ATmpNode, 'ChildTest'); end; end; end; end; end; procedure TfrmEasyPlateMain.ppTVRefreshClick(Sender: TObject); begin inherited; InitTreeViewNav; end; procedure TfrmEasyPlateMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin inherited; if Application.MessageBox('确定要退出系统吗?', '提示', MB_OKCANCEL + MB_ICONQUESTION) = IDOK then Application.Terminate else CanClose := False; end; procedure TfrmEasyPlateMain.EpResourceManageClick(Sender: TObject); begin inherited; frmEasyPlateResourceManage := TfrmEasyPlateResourceManage.Create(Application); frmEasyPlateResourceManage.ShowModal; frmEasyPlateResourceManage.Free; // for I := 0 to Screen.Forms[1].ComponentCount - 1 do // begin // if GetPropInfo(Screen.Forms[1].Components[I], 'Caption') <> nil then // Memo1.Lines.Add(Screen.Forms[1].Components[I].Name +'.Caption='+ GetPropValue(Screen.Forms[1].Components[I], 'Caption')); // if GetPropInfo(Screen.Forms[1].Components[I], 'Text') <> nil then // Memo1.Lines.Add(Screen.Forms[1].Components[I].Name +'.Text='+ GetPropValue(Screen.Forms[1].Components[I], 'Text')); // if GetPropInfo(Screen.Forms[1].Components[I], 'Hint') <> nil then // Memo1.Lines.Add(Screen.Forms[1].Components[I].Name +'.Hint='+ GetPropValue(Screen.Forms[1].Components[I], 'Hint')); // end; // for I := 0 to Screen.FormCount - 1 do // begin // Memo1.Clear; // Memo1.Lines.Add(Screen.Forms[I].Caption + TfrmEasyPlateBaseForm(Screen.Forms[I]).FormId); // end; // ShowMessage(IntToStr(Screen.FormCount)); end; procedure TfrmEasyPlateMain.actConnectDBExecute(Sender: TObject); begin inherited; LoadPkg_Normal('pkEasyconnDB.bpl', FPluginParams); end; procedure TfrmEasyPlateMain.ile1Click(Sender: TObject); begin inherited; Self.Tile; end; procedure TfrmEasyPlateMain.Cascade1Click(Sender: TObject); begin inherited; Self.Cascade; end; procedure TfrmEasyPlateMain.ArrangeAll1Click(Sender: TObject); begin inherited; Self.ArrangeIcons; end; function TfrmEasyPlateMain.CheckHasLoaded(APluginFile: string): Boolean; var ATabCollectionItem: TOfficeTabCollectionItem; I : Integer; begin Result := False; //判断插件是否已经加载过,如果加载过则激活 for I := 0 to EasyMDITabSet1.EasyOfficeTabCount - 1 do begin ATabCollectionItem := EasyMDITabSet1.EasyOfficeTabs[I]; if ATabCollectionItem.OfficeHint.Title = APluginFile then begin EasyMDITabSet1.ActiveTabIndex := I; Result := True; Break; end; end; end; procedure TfrmEasyPlateMain.N12Click(Sender: TObject); begin inherited; if tvNav.Selected <> nil then tvNav.Selected.Expand(True); end; procedure TfrmEasyPlateMain.N13Click(Sender: TObject); begin inherited; if tvNav.Selected <> nil then tvNav.Selected.Collapse(True); end; // if E.ClassType.ClassName = 'ESocketConnectionError' then // Application.MessageBox('与服务器失去连接,请重新登录客户端!', '提示', MB_OK + // MB_ICONINFORMATION) // else // raise Exception.Create(E.Message); procedure TfrmEasyPlateMain.InitCurrLoginUserInfo(ACds: TClientDataSet; ASysUser: TEasysysUser); begin TEasysysUser.InitSingleSysUser(cdsMain, ASysUser); end; end.
unit ksTableViewTest; interface uses DUnitX.TestFramework, ksTypes, ksCommon, ksTableView; type [TestFixture] TksTableViewTest = class(TObject) private FTableView: TksTableView; FEventFired: Boolean; procedure Add100Items; procedure SearchFilterChanged(Sender: TObject; ASearchText: string); procedure DeletingItemEvent(Sender: TObject; AItem: TksTableViewItem; var ACanDelete: Boolean); procedure DeleteItemEvent(Sender: TObject; AItem: TksTableViewItem); public [Setup] procedure Setup; [TearDown] procedure TearDown; // tests... [Test] procedure TestGetCheckedCount; [Test] procedure Test1000Items; [Test] procedure TestFilteredItems; [Test] procedure TestClearItems; [Test] procedure TestScrollToLastItem; [Test] procedure TestAccessories; [Test] procedure TestGetItemFromPos; [Test] procedure BringSelectedIntoView; [Test] procedure TestTotalItemHeight; [Test] procedure TestTopItem; [Test] procedure TestTopItemFiltered; [Test] procedure TestEmbeddedButtons; [Test] procedure TestEmbeddedEdits; [Test] procedure TestEmbeddedSwitches; [Test] procedure TestChatBubbles; [Test] procedure TestItemHorzAlignments; [Test] procedure TestItemVertAlignments; [Test] procedure TestObjectAtPos; [Test] procedure TestTextWidth; [Test] procedure TestTextHeight; [Test] procedure TestTextHeightMultiLine; [Test] procedure TestGetScreenScale; [Test] procedure TestSearchFilterEvent; [Test] procedure TestDeletingItemEvent; [Test] procedure TestOnDeleteItemEvent; [Test] procedure TestDeleteItemEvent; end; implementation uses SysUtils, System.UITypes, System.UIConsts; //---------------------------------------------------------------------------------------------------- procedure TksTableViewTest.SearchFilterChanged(Sender: TObject; ASearchText: string); begin FEventFired := ASearchText = 'TEST'; end; procedure TksTableViewTest.Setup; begin FTableView := TksTableView.Create(nil); FEventFired := False; end; procedure TksTableViewTest.TearDown; begin //FTableView.Free; end; //---------------------------------------------------------------------------------------------------- procedure TksTableViewTest.Add100Items; var ICount: integer; begin // arrange // act FTableView.BeginUpdate; try for ICount := 1 to 100 do FTableView.Items.AddItem('Item '+IntToStr(ICount), 'a sub title', 'the detail', atNone); finally FTableView.EndUpdate; end; end; procedure TksTableViewTest.TestGetCheckedCount; var ICount: integer; begin FTableView.CheckMarkOptions.CheckMarks := TksTableViewCheckMarks.cmMultiSelect; Add100Items; for ICount := 1 to 100 do begin if ICount mod 2 = 0 then FTableView.Items[ICount-1].Checked := True; end; Assert.AreEqual(50, FTableView.Items.GetCheckedCount); end; procedure TksTableViewTest.TestGetItemFromPos; var AItem: TksTableViewItem; begin Add100Items; AItem := FTableView.GetItemFromPos(10, 600); Assert.AreEqual(13, AItem.Index); end; procedure TksTableViewTest.TestGetScreenScale; var AScale: Extended; begin AScale := GetScreenScale; Assert.AreEqual(1.0, AScale); end; procedure TksTableViewTest.TestItemHorzAlignments; var ICount: TksTableItemAlign; begin for ICount := Low(TksTableItemAlign) to High(TksTableItemAlign) do begin with FTableView.Items.AddItem('') do AddButton(30, 'TEST').Align := ICount; end; Assert.AreEqual(4, FTableView.Items.Count); end; procedure TksTableViewTest.TestItemVertAlignments; var ICount: TksTableItemAlign; begin for ICount := Low(TksTableItemAlign) to High(TksTableItemAlign) do begin with FTableView.Items.AddItem('') do AddButton(30, 'TEST', 0, ICount); end; Assert.AreEqual(4, FTableView.Items.Count); end; procedure TksTableViewTest.TestObjectAtPos; var AItem: TksTableViewItem; AObj1, AObj2: TksTableViewItemObject; begin Add100Items; AItem := FTableView.Items[0]; with AItem.DrawRect(50, 5, 30, 20, claBlack, claWhite) do begin VertAlign := TksTableItemAlign.Leading; ID := '1'; end; AObj1 := AItem.ObjectAtPos(55, 10); with AItem.DrawRect(100, 5, 30, 20, claBlack, claWhite) do begin VertAlign := TksTableItemAlign.Leading; ID := '2'; end; AObj2 := AItem.ObjectAtPos(105, 10); Assert.AreEqual('1,2', AObj1.ID+','+AObj2.ID); end; procedure TksTableViewTest.TestOnDeleteItemEvent; begin end; procedure TksTableViewTest.BringSelectedIntoView; begin Add100Items; FTableView.SelectionOptions.KeepSelectedInView := False; FTableView.SelectionOptions.KeepSelection := True; FTableView.ItemIndex := 15; FTableView.BringSelectedIntoView; Assert.AreEqual(404, Integer(Round(FTableView.ScrollViewPos))); end; procedure TksTableViewTest.DeleteItemEvent(Sender: TObject; AItem: TksTableViewItem); begin FEventFired := AItem.Index = 4; end; procedure TksTableViewTest.DeletingItemEvent(Sender: TObject; AItem: TksTableViewItem; var ACanDelete: Boolean); begin FEventFired := True; ACanDelete := False; end; procedure TksTableViewTest.Test1000Items; var ICount: integer; begin // arrange // act FTableView.BeginUpdate; try for ICount := 1 to 1000 do FTableView.Items.AddItem('Item '+IntToStr(ICount), 'a sub title', 'the detail', atNone); finally FTableView.EndUpdate; end; // assert Assert.AreEqual(1000, FTableView.Items.Count); end; procedure TksTableViewTest.TestAccessories; var ICount: TksAccessoryType; begin FTableView.BeginUpdate; for ICount := Low(TksAccessoryType) to High(TksAccessoryType) do FTableView.Items.AddItem('Item', ICount); FTableView.EndUpdate; end; procedure TksTableViewTest.TestClearItems; begin // arrange Add100Items; // act FTableView.ClearItems; // assert Assert.AreEqual(0, FTableView.Items.Count); end; procedure TksTableViewTest.TestDeleteItemEvent; begin Add100Items; FTableView.OnDeleteItem := DeleteItemEvent; FTableView.Items.Delete(4); Assert.AreEqual(True, FEventFired); end; procedure TksTableViewTest.TestDeletingItemEvent; begin Add100Items; FTableView.OnDeletingItem := DeletingItemEvent; FTableView.Items.Delete(4); Assert.AreEqual(True, (FEventFired) and (FTableView.Items.Count = 100)); end; procedure TksTableViewTest.TestEmbeddedButtons; var AItem: TksTableViewItem; ICount: integer; begin FTableView.BeginUpdate; for ICount := 1 to 20 do begin AItem := FTableView.Items.AddItem('Button'); AItem.AddButton(30, 'TEST'); end; FTableView.EndUpdate; Assert.AreEqual(20, FTableView.Items.Count); end; procedure TksTableViewTest.TestEmbeddedEdits; var AItem: TksTableViewItem; ICount: TksEmbeddedEditStyle; begin FTableView.BeginUpdate; try for ICount := Low(TksEmbeddedEditStyle) to High(TksEmbeddedEditStyle) do begin AItem := FTableView.Items.AddItem('Button'); AItem.AddEdit(0, 0, 100, 'TEST', ICount); end; finally FTableView.EndUpdate; end; Assert.AreEqual(4, FTableView.Items.Count); end; procedure TksTableViewTest.TestEmbeddedSwitches; var AItem: TksTableViewItem; ICount: integer; begin FTableView.BeginUpdate; try for ICount := 1 to 20 do begin AItem := FTableView.Items.AddItem('Switch'); AItem.AddSwitch(0, (ICount mod 2) = 0); end; finally FTableView.EndUpdate; end; Assert.AreEqual(20, FTableView.Items.Count); end; procedure TksTableViewTest.TestChatBubbles; var ICount: integer; AAlign: TksTableViewChatBubblePosition; AColor: TAlphaColor; ATextColor: TAlphaColor; begin FTableView.BeginUpdate; try for ICount := 1 to 100 do begin if ICount mod 2 = 1 then begin AAlign := ksCbpLeft; AColor := claDodgerblue; ATextColor := claWhite; end else begin AAlign := ksCbpRight; AColor := claSilver; ATextColor := claBlack; end; FTableView.Items.AddChatBubble('Chat Text '+IntToStr(ICount), AAlign, AColor, ATextColor, nil); end; Assert.AreEqual(100, FTableView.Items.Count); finally FTableView.EndUpdate; end; end; procedure TksTableViewTest.TestFilteredItems; begin // arrange FTableView.SearchVisible := True; Add100Items; // act FTableView.SearchText := 'Item 6'; // assert Assert.AreEqual(11, FTableView.FilteredItems.Count); end; procedure TksTableViewTest.TestScrollToLastItem; var AResult: Extended; begin // arrange Add100Items; // act FTableView.ScrollToItem(99); // assert AResult := FTableView.ScrollViewPos; Assert.AreEqual(4100.0, AResult); end; procedure TksTableViewTest.TestSearchFilterEvent; begin FTableView.SearchVisible := True; FTableView.OnSearchFilterChanged := SearchFilterChanged; FTableView.SearchText := 'TEST'; Assert.AreEqual(True, FEventFired); end; procedure TksTableViewTest.TestTextHeight; var AHeight: string; begin FTableView.Items.AddItem('This is a test'); AHeight := FormatFloat('0.00', FTableView.Items[0].Title.CalculateSize.Height); Assert.AreEqual('17.29', AHeight); end; procedure TksTableViewTest.TestTextHeightMultiLine; var AHeight: string; begin FTableView.Items.AddItem('This is a test'+#13+'This is the second line...'+#13+'And the third :-)'); AHeight := FormatFloat('0.00', FTableView.Items[0].Title.CalculateSize.Height); Assert.AreEqual('51.87', AHeight); end; procedure TksTableViewTest.TestTextWidth; var AWidth: string; begin FTableView.Items.AddItem('This is a test'); AWidth := FormatFloat('0.00', FTableView.Items[0].Title.CalculateSize.Width); Assert.AreEqual('69.92', AWidth); end; procedure TksTableViewTest.TestTopItem; begin Add100Items; Assert.AreEqual(0, FTableView.TopItem.Index); end; procedure TksTableViewTest.TestTopItemFiltered; begin Add100Items; FTableView.SearchText := 'Item 4'; Assert.AreEqual(3, FTableView.TopItem.AbsoluteIndex); end; procedure TksTableViewTest.TestTotalItemHeight; begin Add100Items; Assert.AreEqual(4400, Integer(Round(FTableView.TotalItemHeight))); end; initialization TDUnitX.RegisterTestFixture(TksTableViewTest); end.
unit uraycaster; {$mode objfpc}{$H+} {$MODESWITCH ADVANCEDRECORDS} interface uses Classes, SysUtils, Math, GraphMath, ugraphic, utexture, ugame, udoor, umap; const STACK_LOAD_MAX = 64; type RenderInfo = record CPerpWallDist, CWallX: double; CMapPos: TPoint; CSide: boolean; end; type TRaycaster = record private perpWallDist: double; MapPos: TPoint; side: boolean; Time,OldTime, FrameTime, WallX: double; RenderStack: array[0..STACK_LOAD_MAX] of RenderInfo; StackLoad: UInt8; public FOV : Int16; VPlane: TFloatPoint; ScreenWidth,ScreenHeight: integer; //VCameraX: double; procedure CalculateStripe(AScreenX: integer); procedure DrawStripe(AScreenX: integer); procedure DrawFrame; procedure DrawHud; procedure DrawFPS; procedure HandleInput;//move it to another place end; var Raycaster : TRaycaster; Textures : array[1..10] of TTexture; //TODO dynamic loading //Doors : array of TDoor; procedure InitTextures; implementation procedure InitTextures; begin //TODO Load textures from special list //loading manually for now Textures[1] := LoadTexture(renderer, 'greystone.bmp', false, true); Textures[2] := LoadTexture(renderer, 'colorstone.bmp', false, true); Textures[3] := LoadTexture(renderer, 'eagle.bmp', false, true); Textures[4] := LoadTexture(renderer, 'reallybig.bmp', false, true); Textures[5] := LoadTexture(renderer, 'door.bmp', true, false); Textures[6] := LoadTexture(renderer, 'fence.bmp', true, false); Textures[7] := LoadTexture(renderer, 'test.bmp', true, false); Textures[8] := LoadTexture(renderer, 'redbrick.bmp', false, true); Textures[9] := LoadTexture(renderer, 'bigtexture.bmp', false, true); end; //Doing ray casting calculations there. procedure TRaycaster.CalculateStripe(AScreenX: integer); var CameraX: double; RayPos, RayDir, DeltaDist, SideDist: TFloatPoint; Step: TPoint; hit: boolean; begin // Render stack elements count. StackLoad := 0; // X coordinate in camera space CameraX := 2.0*double(AScreenX)/double(ScreenWidth) - 1.0; // Starting point of ray RayPos := Game.VPlayer; RayDir.x := Game.VDirection.x + VPlane.x * CameraX; // Direction of ray (X) RayDir.y := Game.VDirection.y + VPlane.y * CameraX; // Direction of ray (Y) // Which box of the map we're in MapPos.x := floor(RayPos.x); MapPos.y := floor(RayPos.y); DeltaDist.x := sqrt(1 + (rayDir.Y * rayDir.Y) / (rayDir.X * rayDir.X)); if (RayDir.Y = 0) then RayDir.Y := 0.000001; //shitty hotfix! DeltaDist.y := sqrt(1 + (rayDir.X * rayDir.X) / (rayDir.Y * rayDir.Y)); hit := false; if (RayDir.x < 0) then begin Step.X := -1; SideDist.X := (RayPos.X - MapPos.X)*DeltaDist.X; end else begin Step.X := 1; SideDist.X := (MapPos.X + 1 - RayPos.X)*DeltaDist.X; end; if (RayDir.Y < 0) then begin Step.y := -1; SideDist.Y := (RayPos.Y - MapPos.Y)*DeltaDist.Y; end else begin Step.Y := 1; SideDist.Y := (MapPos.Y + 1 - RayPos.Y)*DeltaDist.Y; end; //perform DDA while (hit = false) do begin if (SideDist.X < SideDist.Y) then begin SideDist.X += DeltaDist.X; MapPos.X += Step.X; side := false; end else begin SideDist.Y += DeltaDist.Y; MapPos.Y += Step.Y; side := true; end; // checking on map borders if ((MapPos.x > 0) and (MapPos.x < Length(GameMap.Map)-1) and (MapPos.y > 0) and (MapPos.y < Length(GameMap.Map[MapPos.x])-1)) then begin // if we hit a wall if (GameMap.Map[MapPos.x][MapPos.y] > 0) then begin // check if it's a texture and it supports transparency if ( TextureExists(@Textures[GameMap.Map[MapPos.x][MapPos.y]]) and (Textures[GameMap.Map[MapPos.x][MapPos.y]].Transparent = true)) then begin //if it is, then we check on stack bounds if (StackLoad < STACK_LOAD_MAX) then begin inc(StackLoad); //doing calculations for stack elems RenderStack[StackLoad].CMapPos.X := MapPos.X; RenderStack[StackLoad].CMapPos.Y := MapPos.Y; RenderStack[StackLoad].CSide := side; // calculating perpWallDist if (RenderStack[StackLoad].CSide = false) then RenderStack[StackLoad].CPerpWallDist := (MapPos.X - RayPos.X + (1 - step.X) / 2) / RayDir.X else RenderStack[StackLoad].CPerpWallDist := (MapPos.Y - RayPos.Y + (1 - step.Y) / 2) / RayDir.Y; // and WallX too if side then RenderStack[StackLoad].CWallX := RayPos.X + ((MapPos.y - RayPos.Y + (1 - Step.y) / 2) / RayDir.Y) * RayDir.X else RenderStack[StackLoad].CWallX := RayPos.Y + ((MapPos.x - RayPos.X + (1 - Step.x) / 2) / RayDir.X) * RayDir.Y; RenderStack[StackLoad].CWallX := RenderStack[StackLoad].CWallX - floor(RenderStack[StackLoad].CWallX); end; end else hit := true; end; end else begin hit := true; end; end; if (side = false) then perpWallDist := (MapPos.X - RayPos.X + (1 - step.X) / 2) / RayDir.X else perpWallDist := (MapPos.Y - RayPos.Y + (1 - step.Y) / 2) / RayDir.Y; //calculate value of wallX in range 0.0 - 1.0 //where exactly the wall was hit if side then WallX := RayPos.X + ((MapPos.y - RayPos.Y + (1 - Step.y) / 2) / RayDir.Y) * RayDir.X else WallX := RayPos.Y + ((MapPos.x - RayPos.X + (1 - Step.x) / 2) / RayDir.X) * RayDir.Y; WallX := WallX - floor(WallX); end; procedure TRaycaster.DrawStripe(AScreenX: integer); var WallColor: TColorRGB; LineHeight,DrawStart,drawEnd, TexIndex, i: integer; begin //at first we draw the farthest objects... LineHeight := floor(ScreenHeight/perpWallDist); DrawStart := floor(-LineHeight / 2 + ScreenHeight / 2); DrawEnd := floor(LineHeight / 2 + ScreenHeight / 2); WallColor := RGB_Magenta; //default texture in case number doesn't exist if (side) then WallColor := WallColor / 2; if ((MapPos.x >= 0) and (MapPos.x < Length(GameMap.Map)) and (MapPos.y >= 0) and (MapPos.y < Length(GameMap.Map[MapPos.x]))) then begin TexIndex := GameMap.Map[MapPos.X][MapPos.Y]; if (TextureExists(@Textures[TexIndex])) then begin DrawTexStripe(AScreenX,DrawStart,DrawEnd,WallX,@Textures[TexIndex],side) end else verLine(AScreenX,DrawStart,DrawEnd,WallColor); end; //...and so on to nearest. for i:=StackLoad downto 1 do begin LineHeight := floor(ScreenHeight/RenderStack[i].CPerpWallDist); DrawStart := floor(-LineHeight / 2 + ScreenHeight / 2); DrawEnd := floor(LineHeight / 2 + ScreenHeight / 2); TexIndex := GameMap.Map[RenderStack[i].CMapPos.X][RenderStack[i].CMapPos.Y]; DrawTexStripe(AScreenX,DrawStart,DrawEnd,RenderStack[i].CWallX,@Textures[TexIndex],RenderStack[i].CSide); end; end; procedure TRaycaster.DrawFrame; var ScreenX: integer; begin drawRect(0, 0, ScreenWidth, ScreenHeight div 2, RGB_Gray); // ceiling drawRect(0, ScreenHeight div 2, ScreenWidth, ScreenHeight, RGB_Grey); //floor for ScreenX := 0 to ScreenWidth do begin CalculateStripe(ScreenX); DrawStripe(ScreenX); end; DrawHud; DrawFps; redraw; cls; HandleInput; end; procedure TRaycaster.DrawHud; begin writeText('Plane= '+FloatToStr(VPlane.X)+';'+FloatToStr(VPlane.Y),0,ScreenHeight-3*CHAR_SIZE-1); writeText('Player X='+FloatToStr(Game.VPlayer.X)+'; Y='+FloatToStr(Game.VPlayer.Y),0,ScreenHeight-2*CHAR_SIZE-1); writeText('Direction: ('+FloatToStr(Game.VDirection.X)+';'+FloatToStr(Game.VDirection.Y)+')',0,ScreenHeight-CHAR_SIZE-1); end; procedure TRaycaster.DrawFPS; begin writeText('by t1meshift & boriswinner',0,0); OldTime := Time; Time := getTicks; FrameTime := (time - oldTime) / 1000; writeText(FloatToStr(floor(1/FrameTime*100)/100)+' FPS',0,CHAR_SIZE+1); end; procedure TRaycaster.HandleInput; var MoveSpeed,RotSpeed: double; OldVDirection,OldVPlane: TFloatPoint; begin MoveSpeed := FrameTime*7; RotSpeed := FrameTime*3; readKeys; if keyDown(KEY_UP) then begin if ((GameMap.Map[Floor(Game.VPlayer.X+Game.VDirection.X*MoveSpeed)][Floor(Game.VPlayer.Y)] = 0) or (not Textures[GameMap.Map[Floor(Game.VPlayer.X+Game.VDirection.X*MoveSpeed)][Floor(Game.VPlayer.Y)]].Solid)) then Game.VPlayer.X += Game.VDirection.X*MoveSpeed; if ((GameMap.Map[Floor(Game.VPlayer.X)][Floor(Game.VPlayer.Y+Game.VDirection.Y*MoveSpeed)] = 0) or (not Textures[GameMap.Map[Floor(Game.VPlayer.X)][Floor(Game.VPlayer.Y+Game.VDirection.Y*MoveSpeed)]].Solid)) then Game.VPlayer.Y += Game.VDirection.Y*MoveSpeed; end; if keyDown(KEY_DOWN) then begin if ((GameMap.Map[Floor(Game.VPlayer.X-Game.VDirection.X*MoveSpeed)][Floor(Game.VPlayer.Y)] = 0) or (not Textures[GameMap.Map[Floor(Game.VPlayer.X-Game.VDirection.X*MoveSpeed)][Floor(Game.VPlayer.Y)]].Solid)) then Game.VPlayer.X -= Game.VDirection.X*MoveSpeed; if ((GameMap.Map[Floor(Game.VPlayer.X)][Floor(Game.VPlayer.Y-Game.VDirection.Y*MoveSpeed)] = 0) or (not Textures[GameMap.Map[Floor(Game.VPlayer.X)][Floor(Game.VPlayer.Y-Game.VDirection.Y*MoveSpeed)]].Solid)) then Game.VPlayer.Y -= Game.VDirection.Y*MoveSpeed; end; if keyDown(KEY_RIGHT) then begin OldVDirection.X := Game.VDirection.X; Game.VDirection.X := Game.VDirection.X * cos(-rotSpeed) - Game.VDirection.Y * sin(-rotSpeed); Game.VDirection.Y := OldVDirection.X * sin(-rotSpeed) + Game.VDirection.Y * cos(-rotSpeed); OldVPlane.X := VPlane.X; VPlane.X := VPlane.X * cos(-rotSpeed) - VPlane.Y * sin(-rotSpeed); VPlane.Y := OldVPlane.X * sin(-rotSpeed) + VPlane.Y * cos(-rotSpeed); end; if keyDown(KEY_LEFT) then begin OldVDirection.X := Game.VDirection.X; Game.VDirection.X := Game.VDirection.X * cos(rotSpeed) - Game.VDirection.Y * sin(rotSpeed); Game.VDirection.Y := OldVDirection.X * sin(rotSpeed) + Game.VDirection.Y * cos(rotSpeed); OldVPlane.X := VPlane.X; VPlane.X := VPlane.X * cos(rotSpeed) - VPlane.Y * sin(rotSpeed); VPlane.Y := OldVPlane.X * sin(rotSpeed) + VPlane.Y * cos(rotSpeed); end; end; initialization Raycaster.ScreenWidth := 1024; Raycaster.ScreenHeight:= 768; Raycaster.FOV := 66; Raycaster.VPlane := FloatPoint(Game.VDirection.Y*tan(degtorad(Raycaster.FOV/2)),-Game.VDirection.X*tan(degtorad(Raycaster.FOV/2))); Raycaster.Time := 0; end.
unit BiasDlg; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, Spin, ComCtrls, Mask; type TBiasDialog = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; Label1: TLabel; UpDown1: TUpDown; BiasSpin: TEdit; procedure BiasSpinExit(Sender: TObject); procedure BiasSpinChange(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var BiasDialog: TBiasDialog; implementation {$R *.dfm} procedure TBiasDialog.BiasSpinExit(Sender: TObject); begin if (StrToIntDef(BiasSpin.Text,-1) < 0 )then BiasSpin.Text := '0'; end; procedure TBiasDialog.BiasSpinChange(Sender: TObject); var n :integer; begin OKBtn.Enabled := TRUE; n := StrToIntDef(BiasSpin.Text,-MaxInt); if (BiasSpin.Text ='')then OKBtn.Enabled := FALSE else if (n<0) then begin BiasSpin.Clear; OKBtn.Enabled := FALSE; end else if (n>30) then BiasSpin.Text :='30'; if (n<1) then OKBtn.Enabled := FALSE end; procedure TBiasDialog.FormShow(Sender: TObject); begin if (StrToIntDef(BiasSpin.Text,-MaxInt) < 0 ) then BiasSpin.Text := '10'; BiasSpin.SetFocus; BiasSpin.SelectAll; end; end.
unit ActnFldReg; interface uses ActnFld, DispActnFld, WebComp, Classes, DesignIntf, DesignEditors, SiteComp, SysUtils,WebAdapt; procedure Register; implementation uses WebForm; type TAdapterDisplayActionFieldHelper = class(TWebComponentsEditorHelper) protected function ImplCanAddClassHelper(AEditor: TComponent; AParent: TComponent; AClass: TClass): Boolean; override; end; TAdapterActionFieldNameProperty = class(TStringProperty) function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; end; var AdapterDisplayActionFieldHelper: TAdapterDisplayActionFieldHelper; procedure Register; begin RegisterWebComponents([TAdapterDisplayActionField], AdapterDisplayActionFieldHelper); RegisterWebComponents([TDataSetAdapterDeleteRowField]); RegisterPropertyEditor(TypeInfo(string), TCustomAdapterDisplayActionField, 'FieldName', TAdapterActionFieldNameProperty); { do not localize } end; { TAdapterDisplayActionFieldHelper } function TAdapterDisplayActionFieldHelper.ImplCanAddClassHelper(AEditor, AParent: TComponent; AClass: TClass): Boolean; begin Result := AEditor.InheritsFrom(TCustomAdapterCommandColumn); end; { TAdapterActionFieldNameProperty } function TAdapterActionFieldNameProperty.GetAttributes: TPropertyAttributes; begin Result := inherited GetAttributes + [paValueList, paSortList]; end; procedure TAdapterActionFieldNameProperty.GetValues(Proc: TGetStrProc); var i: Integer; Component: TComponent; Intf: IWebDataFields; ComponentList: TWebComponentList; NameIntf: IWebGetFieldName; Temp: IUnknown; begin Component := GetComponent(0) as TComponent; Component := FindVariablesContainerInParent(Component); if Supports(IUnknown(Component), IWebDataFields, Intf) then begin ComponentList := Intf.GetVisibleFields; for i := 0 to ComponentList.Count - 1 do begin Component := ComponentList.WebComponents[I]; if Supports(IUnknown(Component), IExecuteValue, Temp) and Supports(IUnknown(Component), IWebGetFieldName, NameIntf) then Proc(NameIntf.FieldName); end; end else Assert(False); end; initialization AdapterDisplayActionFieldHelper := TAdapterDisplayActionFieldHelper.Create; finalization UnregisterWebComponents([TAdapterDisplayActionField]); UnregisterWebComponents([TDataSetAdapterDeleteRowField]); AdapterDisplayActionFieldHelper.Free; end.
unit myGraph; {$mode objfpc}{$H+} interface uses Classes, SysUtils;//, dialogs; type TMyGraphNode=class; TMyGraphEdge=class; TMyGraphLevel=class; FBeforeRemoveEdgeEvent=procedure(Sender:Tobject) of object; FBeforeRemoveLevelEvent=procedure(Sender:Tobject) of object; FBeforeRemoveNodeEvent=procedure(Sender:Tobject) of object; type { TMyGraph } TMyGraph=class(TObject) private FlistNodes:Tlist; FlistEdges:Tlist; FlistLevels:Tlist; function GetcountEdge: integer; function GetEdge(i: integer): TMyGraphEdge; function GetNodecount: integer; function GetNodes(index: integer): TMyGraphNode; function addNode(Node:TMyGraphNode):TMyGraphNode; //function FindPraRoditels(id_Node:integer):TList; //function CompareRoditels(id_Source, id_Target:integer):boolean; function GetcountLevel: integer; //function ExistCommonFather(Source, Target:TMyGraphNode;lev:integer):boolean; //procedure moveNodes(TargetBottom:TMyGraphNode;countLevel:integer;IdNode:integer=-1; moveTree:boolean=false);virtual; protected function CreatedNode(idNode:integer):TMyGraphNode;virtual; function CreatedEdge(SourceTop,TargetBottom:TObject):TMyGraphEdge; virtual; function CreatedLevel:TMyGraphLevel;virtual; function GetNodesIDNode(IDNode: integer): TMyGraphNode;virtual; function GetLevels(index: integer): TMyGraphLevel;virtual; function GetLevelNumber(Node:TObject):integer;overload; //function GetLevelNumber(Level:TObject):integer;overload; function GetNodeNumberInLevel(Node:TObject):integer; function addEdge(SourceTop,TargetBottom:TMyGraphNode):TMyGraphEdge;virtual; procedure AfterAddEdge(Sender:TObject);virtual;abstract; procedure AfterAddNode(Sender:TObject);virtual;abstract; procedure BeforeRemoveEdge(Sender:TObject);virtual; procedure BeforeRemoveNode(Sender:TObject);virtual; procedure BeforeRemoveLevel(Sender:TObject);virtual; procedure removeAllNodes;virtual; //procedure SortingNodeInLevel(Level:TMyGraphLevel;Compare: TListSortCompare); property countLevel:integer read GetcountLevel; property countEdge:integer read GetcountEdge; property Edges[i:integer]:TMyGraphEdge read GetEdge; public constructor Create;virtual; destructor Destroy;override; function addNode(idNode:integer):TMyGraphNode;virtual; function addEdge(idSourceTop,idTargetBottom:integer):TMyGraphEdge;virtual; function RemoveAllEdge:boolean;virtual; function RemoveAllEdgeAndNodeLevelNil:boolean;virtual; procedure removeEdge(idSource,idTarget:integer); procedure removeNodeIDNode(ID:integer); property Nodecount:integer read GetNodecount; property Nodes[i:integer]:TMyGraphNode read GetNodes; end; { TMyGraphLevel } TMyGraphLevel=class(TObject) private FlistNodes:TList; FOnBeforeRemoveLevel:FBeforeRemoveLevelEvent; function GetcountNode: integer; protected public constructor Create;virtual; destructor Destroy;override; function AddNode(Node:TMyGraphNode):integer; function IndexOfNode(Node:TMyGraphNode): integer; function GetNodes(index: integer): TMyGraphNode; procedure RemoveNode(Node:TObject); procedure MoveNode(oldIndex, newIndex:integer); procedure Sort(Compare: TListSortCompare);virtual; property countNode:integer read GetcountNode; property OnBeforeRemoveLevel:FBeforeRemoveLevelEvent read FOnBeforeRemoveLevel write FOnBeforeRemoveLevel; end; { TMyGraphNode } TMyGraphNode=class(TObject) private FidNode: integer; Flevel:TMyGraphlevel; FlistinEdges:Tlist; FlistoutEdges:Tlist; FOnBeforeRemoveNode: FBeforeRemoveNodeEvent; function GetinEdgecount: integer; function GetinEdges(index: integer): TMyGraphEdge; function GetLevel: TMyGraphLevel; function GetoutEdgecount: integer; function GetoutEdges(index: integer): TMyGraphEdge; procedure SetLevel(AValue: TMyGraphlevel); protected public constructor Create(idNode:integer);virtual; destructor Destroy;override; procedure removeinEdge(Edge:TMyGraphEdge); procedure removeoutEdge(Edge:TMyGraphEdge); property outEdgecount:integer read GetoutEdgecount; property outEdges[index:integer]:TMyGraphEdge read GetoutEdges; property inEdgecount:integer read GetinEdgecount; property inEdges[index:integer]:TMyGraphEdge read GetinEdges; property idNode:integer read FidNode write FidNode; property Level:TMyGraphlevel read GetLevel write SetLevel; property OnBeforeRemoveNode:FBeforeRemoveNodeEvent read FOnBeforeRemoveNode write FOnBeforeRemoveNode; end; { TMyGraphEdge } TMyGraphEdge=class(TObject) private FOnBeforeRemoveEdge: FBeforeRemoveEdgeEvent; FSourceTop: TMyGraphNode; FTargetBottom: TMyGraphNode; protected public constructor Create(SourceTop,TargetBottom:TObject);virtual; destructor Destroy;override; property SourceTop:TMyGraphNode read FSourceTop; property TargetBottom:TMyGraphNode read FTargetBottom; property OnBeforeRemoveEdge:FBeforeRemoveEdgeEvent read FOnBeforeRemoveEdge write FOnBeforeRemoveEdge; end; implementation { TMyGraphEdge } constructor TMyGraphEdge.Create(SourceTop, TargetBottom: TObject); begin inherited Create; FSourceTop:=(sourcetop as TMyGraphNode); FTargetBottom:=(targetbottom as TMyGraphNode); //добавим концы пути (sourcetop as TMyGraphNode).FlistoutEdges.Add(self); (TargetBottom as TMyGraphNode).FlistinEdges.Add(self); end; destructor TMyGraphEdge.Destroy; begin if assigned(FOnBeforeRemoveEdge) then FOnBeforeRemoveEdge(self); inherited Destroy; end; { TLevel } function TMyGraphLevel.GetNodes(index: integer): TMyGraphNode; begin if (FlistNodes=nil)or(FlistNodes.Count<index)or(index<0) then exit; result:=TMyGraphNode(FlistNodes.Items[index]); end; function TMyGraphLevel.GetcountNode: integer; begin result:=FlistNodes.Count; end; procedure TMyGraphLevel.RemoveNode(Node: TObject); begin FlistNodes.Remove(Node); if FlistNodes.Count=0 then FreeAndNil(self); end; function TMyGraphLevel.IndexOfNode(Node: TMyGraphNode): integer; begin result:=FlistNodes.IndexOf(Node); end; procedure TMyGraphLevel.MoveNode(oldIndex, newIndex: integer); begin FlistNodes.Move(oldIndex, newIndex); end; procedure TMyGraphLevel.Sort(Compare: TListSortCompare); begin FlistNodes.Sort(Compare); end; constructor TMyGraphLevel.Create; begin inherited Create; FlistNodes:=TList.Create; end; destructor TMyGraphLevel.Destroy; begin FlistNodes.Free; if assigned(FOnBeforeRemoveLevel) then FOnBeforeRemoveLevel(self); inherited Destroy; end; function TMyGraphLevel.AddNode(Node: TMyGraphNode): integer; begin result:=flistNodes.IndexOf(Node); if result=-1 then begin flistNodes.add(Node); result:=flistNodes.Count-1; end; end; { TNode } function TMyGraphNode.GetinEdges(index: integer): TMyGraphEdge; begin result:=TMyGraphEdge(flistinEdges.Items[index]); end; function TMyGraphNode.GetinEdgecount: integer; begin result:=FlistinEdges.Count; end; function TMyGraphNode.GetLevel: TMyGraphLevel; begin result:=nil; if FLevel=nil then exit; result:=FLevel; end; function TMyGraphNode.GetoutEdgecount: integer; begin result:=FlistoutEdges.Count; end; function TMyGraphNode.GetoutEdges(index: integer): TMyGraphEdge; begin result:=TMyGraphEdge(flistoutEdges.Items[index]); end; procedure TMyGraphNode.SetLevel(AValue: TMyGraphlevel); begin if FLevel=AValue then exit; if FLevel<>nil then begin FLevel.RemoveNode(self); end; Flevel:=AValue; if FLevel<>nil then FLevel.AddNode(self); end; constructor TMyGraphNode.Create(idNode: integer); begin inherited Create(); idNode:=idnode; FlistinEdges:=TList.Create; FlistoutEdges:=TList.Create; end; destructor TMyGraphNode.Destroy; begin if assigned(FOnBeforeRemoveNode) then FOnBeforeRemoveNode(self); FreeAndNil(FlistinEdges); FreeAndNil(FlistoutEdges); inherited Destroy; end; procedure TMyGraphNode.removeinEdge(Edge: TMyGraphEdge); begin //Удалим из списка FlistinEdges.Remove(Edge); end; procedure TMyGraphNode.removeoutEdge(Edge: TMyGraphEdge); begin //Удалим из списка FlistoutEdges.Remove(Edge); end; { TMyGraph } function TMyGraph.GetNodes(index: integer): TMyGraphNode; begin if ((index>(flistNodes.Count-1))or (index<0))then begin result:=nil; exit; end; result:=TMyGraphNode(flistNodes.Items[index]); end; function TMyGraph.GetNodecount: integer; begin if FlistNodes=nil then result:=0 else result:=FlistNodes.Count; end; function TMyGraph.GetcountEdge: integer; begin result:=FlistEdges.Count; end; function TMyGraph.GetEdge(i: integer): TMyGraphEdge; begin result:=TMyGraphEdge(FlistEdges.Items[i]); end; function TMyGraph.CreatedNode(idNode: integer): TMyGraphNode; begin result:=TMyGraphNode.Create(idnode); result.OnBeforeRemoveNode:=@BeforeRemoveNode; end; function TMyGraph.CreatedEdge(SourceTop, TargetBottom: TObject): TMyGraphEdge; begin result:=TMyGraphEdge.Create(SourceTop,TargetBottom); result.OnBeforeRemoveEdge:=@BeforeRemoveEdge; end; function TMyGraph.CreatedLevel: TMyGraphLevel; begin result:=TMyGraphLevel.Create; result.OnBeforeRemoveLevel:=@BeforeRemoveLevel; end; function TMyGraph.GetNodesIDNode(IDNode: integer): TMyGraphNode; var i:integer; begin for i:=0 to FlistNodes.Count-1 do begin if TMyGraphNode(FlistNodes.Items[i]).idNode=idnode then begin result:=TMyGraphNode(FlistNodes.Items[i]); exit; break; end; end; result:=nil; end; function TMyGraph.GetLevels(index: integer): TMyGraphLevel; begin if ((index>(flisTLevels.Count-1))or (index<0))then begin result:=nil; exit; end; result:=TMyGraphLevel(flisTLevels.Items[index]); end; function TMyGraph.GetLevelNumber(Node: TObject): integer; begin if (Node is TMyGraphNode) then result:=FlistLevels.IndexOf((node as TMyGraphNode).Level); if (Node is TMyGraphLevel) then result:=FlistLevels.IndexOf(Node); end; function TMyGraph.GetNodeNumberInLevel(Node: TObject): integer; begin result:=(Node as TMyGraphNode).Level.IndexOfNode(Node as TMyGraphNode); end; constructor TMyGraph.Create; begin inherited Create; FlistNodes:=TList.Create; FlisTLevels:=TList.Create; FlistEdges:=TList.Create; end; destructor TMyGraph.Destroy; var i:integer; begin //уничтожим все Node for i:=flistNodes.Count-1 downto 0 do begin removeNodeIDNode(TMyGraphNode(flistNodes.Items[i]).idNode); end; FlistNodes.Free; FlisTLevels.Free; FlistEdges.Free; inherited Destroy; end; function TMyGraph.addNode(idNode: integer): TMyGraphNode; var i:integer; begin i:=flistNodes.Count-1; //проверим может уже есть такой while (i>=0)and(TMyGraphNode(FlistNodes.Items[i]).idNode<>idnode) do dec(i); if i>-1 then begin //если есть, то //поместим на уровень 0, если без уровня if flisTLevels.Count<=0 then flisTLevels.Add(CreatedLevel); //вернем на него ссылку result:=TMyGraphNode(FlistNodes.Items[i]); result.Level:=GetLevels(0); exit; end else //если нет, то создадим result:=CreatedNode(idnode); result.idNode:=idNode; addNode(result); end; function TMyGraph.addNode(Node: TMyGraphNode): TMyGraphNode; begin //Добавим ссылку в список FlistNodes.Add(Node); //поместим на уровень 0 if flisTLevels.Count<=0 then flisTLevels.Add(CreatedLevel); node.Level:=GetLevels(0); //запомним на каком уровне Node result:=Node; AfterAddNode(result); end; function TMyGraph.addEdge(idSourceTop,idTargetBottom:integer): TMyGraphEdge; var i{, j, LevelMin}:integer; SourceNode,TargetNode:TMyGraphNode; Level:TMyGraphLevel; begin //проверим есть ли такой путь i:=flistEdges.Count-1; while (i>=0)and(not ((TMyGraphEdge(FlistEdges.Items[i]).SourceTop.idNode=idSourceTop)and (TMyGraphEdge(FlistEdges.Items[i]).TargetBottom.idNode=idTargetBottom))) do dec(i); if i>-1 then begin //если есть, то вернем на него ссылку result:=TMyGraphEdge(FlistEdges.Items[i]) ; AfterAddEdge(result); exit; end ; //если нет, то создадим, попутно при необходиомсти node-ы SourceNode:=GetNodesIDNode(idSourceTop); TargetNode:=GetNodesIDNode(idTargetBottom); if ((TargetNode=nil)) then begin if (SourceNode=nil) then SourceNode:=addNode(idSourceTop); if SourceNode.Level=nil then begin Level:=getlevels(0); if Level=nil then begin Level:=CreatedLevel; FlistLevels.Add(Level); end; SourceNode.Level:=Level; end; TargetNode:=addNode(idTargetBottom); i:=FlistLevels.IndexOf(SourceNode.Level); if FlistLevels.Count<(i+2) then FlistLevels.Add(CreatedLevel); TargetNode.Level:=TMyGraphLevel(FlistLevels.Items[i+1]); end else if ((SourceNode=nil)and(TargetNode<>nil))then begin if TargetNode.Level=nil then begin Level:=getlevels(0); if Level=nil then begin Level:=CreatedLevel; FlistLevels.Add(Level); end; TargetNode.Level:=Level; end; SourceNode:=addNode(idSourceTop); if FlistLevels.IndexOf(TargetNode.Level)=0 then FlistLevels.Insert(0,CreatedLevel); i:=FlistLevels.IndexOf(TargetNode.Level); SourceNode.Level:=getlevels(i-1); end else begin //Определим какой из двух Node безхозный, т.е. Level=nil if TargetNode.Level=nil then begin if SourceNode.Level=nil then begin Level:=getlevels(0); if Level=nil then begin Level:=CreatedLevel; FlistLevels.Add(Level); end; SourceNode.Level:=Level; end; i:=FlistLevels.IndexOf(SourceNode.Level)+1; Level:=getlevels(i); if Level=nil then begin Level:=CreatedLevel; FlistLevels.Add(Level); end; TargetNode.Level:=Level; end else begin i:=FlistLevels.IndexOf(TargetNode.Level)-1; if i<0 then begin FlistLevels.Insert(0,CreatedLevel); Level:=getlevels(0); end else Level:=getlevels(i);; SourceNode.Level:=Level; end; end; result:=addEdge(SourceNode,TargetNode); //Добавим в список Edge FlistEdges.Add(result); end; procedure TMyGraph.removeEdge(idSource, idTarget: integer); var Edge:TMyGraphEdge; begin Edge:=addEdge(idSource, idTarget); FreeAndNil(Edge); Edge.Free; end; function TMyGraph.RemoveAllEdge: boolean; var edg:integer; Edge:TMyGraphEdge; begin for edg:=countEdge-1 downto 0 do begin Edge:=Edges[edg]; FreeAndNil(Edge); end; result:=true; end; function TMyGraph.RemoveAllEdgeAndNodeLevelNil: boolean; var nod:integer; Node:TMyGraphNode; begin RemoveAllEdge; for nod:=0 to FlistNodes.Count-1 do begin Node:=Nodes[nod]; Node.Level:=nil; end; result:=true; end; procedure TMyGraph.removeAllNodes; var i:integer; Node:TMyGraphNode; begin for i:=FlistNodes.Count-1 downto 0 do begin TMyGraphNode(FlistNodes.Items[i]).Level.RemoveNode(TMyGraphNode(FlistNodes.Items[i])); Node:=TMyGraphNode(FlistNodes.Items[i]); FlistNodes.Remove(FlistNodes.Items[i]); TMyGraphNode(Node).Free; end; for i:=FlistLevels.Count-1 downto 0 do TMyGraphLevel(FlistLevels.Items[i]).Free; for i:=FlistLevels.Count-1 downto 0 do FlistLevels.Delete(i); end; function TMyGraph.GetcountLevel: integer; begin result:=FlistLevels.Count; end; procedure TMyGraph.removeNodeIDNode(ID: integer); var Node:TMyGraphNode; begin //получим Node по ID Node:=GetNodesIDNode(id); FreeAndNil(Node); end; function TMyGraph.addEdge(SourceTop, TargetBottom: TMyGraphNode): TMyGraphEdge; begin result:=CreatedEdge(SourceTop,TargetBottom); //функция после добавления пути AfterAddEdge(result); end; procedure TMyGraph.BeforeRemoveEdge(Sender: TObject); begin //Удалим у Node-ов указатели на этот Edge (Sender as TMyGraphEdge).SourceTop.removeoutEdge((Sender as TMyGraphEdge)); (Sender as TMyGraphEdge).TargetBottom.removeinEdge((Sender as TMyGraphEdge)); if ((Sender as TMyGraphEdge).SourceTop.inEdgecount<=0)and((Sender as TMyGraphEdge).SourceTop.outEdgecount<=0) then (Sender as TMyGraphEdge).SourceTop.Level:=GetLevels(0); if ((Sender as TMyGraphEdge).TargetBottom.inEdgecount<=0)and((Sender as TMyGraphEdge).TargetBottom.outEdgecount<=0) then (Sender as TMyGraphEdge).TargetBottom.Level:=GetLevels(0); //Удалим из списка FlistEdges.Remove(Sender); end; procedure TMyGraph.BeforeRemoveNode(Sender: TObject); var i:integer; Node:TMyGraphNode; begin Node:=(Sender as TMyGraphNode); //Удалим связанные с Node Edge for i:=Node.inEdgecount-1 downto 0 do begin //TMyGraphEdge(Node.inEdges[i]).SourceTop.removeoutEdge(TMyGraphEdge(Node.inEdges[i])); TMyGraphEdge(Node.inEdges[i]).Free; end; for i:= Node.outEdgecount-1 downto 0 do begin //TMyGraphEdge(Node.outEdges[i]).TargetBottom.removeinEdge(TMyGraphEdge(Node.outEdges[i])); TMyGraphEdge(Node.outEdges[i]).Free; end; //Удалим из списка FlistNodes.Remove(Sender as TMyGraphNode); //Удалим с уровня Node if (Sender as TMyGraphNode).Level<>nil then begin (Sender as TMyGraphNode).Level.RemoveNode(Sender as TMyGraphNode); end; end; procedure TMyGraph.BeforeRemoveLevel(Sender: TObject); begin //Удалим из списка FlistLevels.Remove(Sender); end; end.
unit IdTimeUDPServer; interface uses IdAssignedNumbers, IdSocketHandle, IdUDPBase, IdUDPServer, classes; type TIdTimeUDPServer = class(TIdUDPServer) protected FBaseDate : TDateTime; procedure DoUDPRead(AData: TStream; ABinding: TIdSocketHandle); override; public constructor Create(axOwner: TComponent); override; published property DefaultPort default IdPORT_TIME; {This property is used to set the Date the Time server bases it's calculations from. If both the server and client are based from the same date which is higher than the original date, you can extend it beyond the year 2035} property BaseDate : TDateTime read FBaseDate write FBaseDate; end; implementation uses IdGlobal, IdStack, SysUtils; const {This indicates that the default date is Jan 1, 1900 which was specified by RFC 868.} TIMEUDP_DEFBASEDATE = 2; { TIdTimeUDPServer } constructor TIdTimeUDPServer.Create(axOwner: TComponent); begin inherited Create(axOwner); DefaultPort := IdPORT_TIME; {This indicates that the default date is Jan 1, 1900 which was specified by RFC 868.} FBaseDate := TIMEUDP_DEFBASEDATE; end; procedure TIdTimeUDPServer.DoUDPRead(AData: TStream; ABinding: TIdSocketHandle); var s : String; LTime : Cardinal; begin inherited DoUDPRead(AData, ABinding); SetLength(s, AData.Size); AData.Read(s[1], AData.Size); LTime := Trunc(extended(Now + IdGlobal.TimeZoneBias - Int(FBaseDate)) * 24 * 60 * 60); LTime := GStack.WSHToNl(LTime); SendBuffer(ABinding.PeerIP,ABinding.PeerPort,LTime,SizeOf(LTime)); end; end.
unit TUsers_U; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ADODB; type TUsers = class private { Private declarations } // userName : string ; // password : string ; userType : string ; ado : TADOQuery ; public { Public declarations } Constructor Create; // Function GetUserName : string ; // Function GetPassword : string ; Function GetUserType : string ; Function CheckValidPassword(user, pass : string) : Boolean ; end; implementation { TUsers } {function TUsers.CheckValidPassword: Boolean; begin ado.Close; ado.SQL.Text := 'SELECT '; ado.Open ; {ado.SQL.Text := 'SELECT COUNT(*) as [batsmanCount] FROM Batsman;'; ado.ExecSQL; ado.Open; NoOfBatsman := ado.FieldByName('batsmanCount').AsInteger; end; } function TUsers.CheckValidPassword(user, pass: string): Boolean; begin ado.Close; ado.SQL.Text := 'SELECT * FROM tblUsers WHERE Username = "' + user + '"'; ado.Open; userType := ado.FieldValues['Type'] ; Result := false; if ado.FieldValues['Password'] = pass then Result := true end; constructor TUsers.Create; begin //userType := pUserType ; ado := TADOQuery.Create(nil); ado.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=PAT 2018.mdb;Persist Security Info=False'; userType := ''; end; function TUsers.GetUserType: string; begin Result := userType ; end; end.
{$MODE OBJFPC} program PermutationOrder; const InputFile = 'PERMUTATION.INP'; OutputFile = 'PERMUTATION.OUT'; max = 20; type TList = record items: array[1..max] of Integer; nitems: Integer; end; var p, q: array[1..max] of Integer; x, y: Int64; n: Integer; fac: array[0..max] of Int64; List: TList; procedure Enter; var f: TextFile; begin AssignFile(f, InputFile); Reset(f); try n := 0; while not SeekEoln(f) do begin Inc(n); Read(f, p[n]); end; ReadLn(f); ReadLn(f, y); finally CloseFile(f); end; end; procedure Init; var i: Integer; begin fac[0] := 1; for i := 1 to n do fac[i] := fac[i - 1] * i; end; procedure InitList; var i: Integer; begin with List do begin nitems := n; for i := 1 to nitems do items[i] := i; end; end; function Pop(id: Integer): Integer; //Lay phan tu thu id ra khoi list begin with List do begin Result := items[id]; if id < nitems then Move(items[id + 1], items[id], (nitems - id) * SizeOf(Items[1])); Dec(nitems); end; end; function Find(v: Integer): Integer; var L, M, H: Integer; begin with List do begin L := 1; H := nitems; while L <= H do //items[L - 1] < v <= items[H + 1]; begin M := (L + H) div 2; if items[M] < v then L := M + 1 else H := M - 1; end; end; Result := L; end; procedure Solve; var i, j: Integer; begin InitList; x := 1; for i := 1 to n do begin j := Find(p[i]); Pop(j); Inc(x, (j - 1) * Fac[n - i]); end; InitList; for i := 1 to n do begin j := (y - 1) div fac[n - i] + 1; q[i] := Pop(j); y := y - (j - 1) * fac[n - i]; end; end; procedure PrintResult; var f: TextFile; i: Integer; begin AssignFile(f, OutputFile); Rewrite(f); try WriteLn(f, x); for i := 1 to n do Write(f, q[i], ' '); finally CloseFile(f); end; end; begin Enter; Init; Solve; PrintResult; end.
{******************************************} { TeeChart Series DB Virtual DataSet } { Copyright (c) 1996-2004 by David Berneda } { All Rights Reserved } {******************************************} unit TeeData; {$I TeeDefs.inc} { This unit contains a VIRTUAL TDATASET component. The TSeriesDataSet component is an intermediary between a Series component and a TDataSource. You can show Series values in a DBGrid, for example: SeriesDataSet1.Series := Series1; DataSource1.DataSet := SeriesDataSet1; DBGrid1.DataSource := DataSource1; To refresh data: SeriesDataSet1.Close; Series1.Add(....) SeriesDataSet1.Open; Additional information under Delphi \Demos\TextData example project. NOTE: This component is not available in Delphi and C++ Builder STANDARD versions, because they do not include Database components. } interface uses DB, Classes, {$IFDEF CLX} QGraphics, {$ELSE} Graphics, {$ENDIF} TeEngine, TeeProcs; Const MaxLabelLen=128; type PFloat=^Double; PSeriesPoint=^TSeriesPoint; TSeriesPoint=packed record Color : TColor; { 4 bytes } X : Double; { 8 bytes } Values : Array[0..10] of Double; { 88 bytes } ALabel : String[MaxLabelLen]; { 128 bytes } end; PRecInfo = ^TRecInfo; TRecInfo = packed record Bookmark : Integer; BookmarkFlag : TBookmarkFlag; end; TSeriesDataSet = class(TDataSet,ITeeEventListener) private FSeries : TChartSeries; FBookMarks : TList; FCurRec : Integer; FLastBookmark : Integer; Procedure DoCreateField(Const AFieldName:String; AType:TFieldType; ASize:Integer); Function RecInfoOfs: Integer; Function RecBufSize: Integer; procedure TeeEvent(Event: TTeeEvent); protected { Overriden abstract methods (required) } function AllocRecordBuffer: {$IFDEF CLR}TRecordBuffer{$ELSE}PChar{$ENDIF}; override; procedure FreeRecordBuffer(var Buffer: {$IFDEF CLR}TRecordBuffer{$ELSE}PChar{$ENDIF}); override; {$IFDEF CLR} procedure GetBookmarkData(Buffer: TRecordBuffer; var Bookmark: TBookmark); override; {$ELSE} procedure GetBookmarkData(Buffer: PChar; Data: Pointer); override; {$ENDIF} function GetBookmarkFlag(Buffer: {$IFDEF CLR}TRecordBuffer{$ELSE}PChar{$ENDIF}): TBookmarkFlag; override; function GetRecord(Buffer: {$IFDEF CLR}TRecordBuffer{$ELSE}PChar{$ENDIF}; GetMode: TGetMode; DoCheck: Boolean): TGetResult; override; function GetRecordSize: Word; override; procedure InternalAddRecord(Buffer: {$IFDEF CLR}TRecordBuffer{$ELSE}Pointer{$ENDIF}; Append: Boolean); override; procedure InternalClose; override; procedure InternalDelete; override; procedure InternalFirst; override; procedure InternalGotoBookmark({$IFDEF CLR}const Bookmark:TBookmark{$ELSE}Bookmark: Pointer{$ENDIF}); override; procedure InternalHandleException; override; procedure InternalInitFieldDefs; override; procedure InternalInitRecord(Buffer: {$IFDEF CLR}TRecordBuffer{$ELSE}PChar{$ENDIF}); override; procedure InternalLast; override; procedure InternalOpen; override; procedure InternalPost; override; procedure InternalSetToRecord(Buffer: {$IFDEF CLR}TRecordBuffer{$ELSE}PChar{$ENDIF}); override; function IsCursorOpen: Boolean; override; procedure Notification( AComponent: TComponent; Operation: TOperation); override; procedure SetBookmarkFlag(Buffer: {$IFDEF CLR}TRecordBuffer{$ELSE}PChar{$ENDIF}; Value: TBookmarkFlag); override; {$IFDEF CLR} procedure SetBookmarkData(Buffer: TRecordBuffer; const Bookmark: TBookmark); override; {$ELSE} procedure SetBookmarkData(Buffer: PChar; Data: Pointer); override; {$ENDIF} procedure SetFieldData(Field: TField; Buffer: {$IFDEF CLR}TValueBuffer{$ELSE}Pointer{$ENDIF}); override; { Additional overrides (optional) } function GetRecordCount: Integer; override; function GetRecNo: Integer; override; procedure SetRecNo(Value: Integer); override; Procedure SetSeries(ASeries:TChartSeries); virtual; Procedure AddSeriesPoint(Buffer:{$IFDEF CLR}IntPtr{$ELSE}Pointer{$ENDIF}; ABookMark:Integer); virtual; public function GetFieldData(Field: TField; Buffer: {$IFDEF CLR}TValueBuffer{$ELSE}Pointer{$ENDIF}): Boolean; override; published property Series: TChartSeries read FSeries write SetSeries stored True; property Active; end; implementation uses {$IFNDEF LINUX} Windows, {$ENDIF} SysUtils, {$IFDEF CLX} QForms, {$ELSE} Forms, {$ENDIF} TeeConst, TeCanvas; { TSeriesDataSet } {$IFNDEF CLR} type TTeePanelAccess=class(TCustomTeePanel); {$ENDIF} Procedure TSeriesDataSet.SetSeries(ASeries:TChartSeries); Var WasActive : Boolean; begin WasActive:=Active; Active:=False; if Assigned(FSeries) then begin {$IFDEF D5} FSeries.RemoveFreeNotification(Self); {$ENDIF} if Assigned(FSeries.ParentChart) then {$IFNDEF CLR}TTeePanelAccess{$ENDIF}(FSeries.ParentChart).RemoveListener(Self); end; FSeries:=ASeries; if Assigned(FSeries) then begin FSeries.FreeNotification(Self); if Assigned(FSeries.ParentChart) then {$IFNDEF CLR}TTeePanelAccess{$ENDIF}(FSeries.ParentChart).Listeners.Add(Self); end; if Assigned(FSeries) and WasActive then Active:=True; end; procedure TSeriesDataSet.Notification( AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation=opRemove) and Assigned(FSeries) and (AComponent=FSeries) then Series:=nil; end; Function TSeriesDataSet.RecInfoOfs:Integer; begin result:= SizeOf(TSeriesPoint); end; Function TSeriesDataSet.RecBufSize: Integer; begin result:=RecInfoOfs + SizeOf(TRecInfo); end; procedure TSeriesDataSet.InternalOpen; var I: Integer; begin if not Assigned(FSeries) then Raise Exception.Create('Cannot open SeriesDataSet. No Series assigned.'); { Fabricate integral bookmark values } FBookMarks:=TList.Create; for I:=1 to FSeries.Count do FBookMarks.Add({$IFDEF CLR}TObject{$ELSE}Pointer{$ENDIF}(I)); FLastBookmark:=FSeries.Count; FCurRec:=-1; BookmarkSize := SizeOf(Integer); InternalInitFieldDefs; if DefaultFields then CreateFields; BindFields(True); end; procedure TSeriesDataSet.InternalClose; begin {$IFDEF D5} FreeAndNil(FBookMarks); {$ELSE} FBookMarks.Free; FBookMarks:=nil; {$ENDIF} if DefaultFields then DestroyFields; FLastBookmark := 0; FCurRec := -1; end; function TSeriesDataSet.IsCursorOpen: Boolean; begin Result:=Assigned(FSeries) and Assigned(FBookMarks); end; Procedure TSeriesDataSet.DoCreateField(Const AFieldName:String; AType:TFieldType; ASize:Integer); begin {$IFDEF C3D4} With TFieldDef.Create(FieldDefs) do begin Name := AFieldName; Size := ASize; Required := False; DataType := AType; end; {$ELSE} TFieldDef.Create(FieldDefs, AFieldName, AType, ASize, False, FieldDefs.Count+1) {$ENDIF} end; procedure TSeriesDataSet.InternalInitFieldDefs; Function GetFieldName(Const ADefault,AName:String):String; begin if AName='' then result:=ADefault else result:=AName; end; Procedure AddField(IsDateTime:Boolean; Const FieldName:String); begin if IsDateTime then DoCreateField(FieldName,ftDateTime,0) else DoCreateField(FieldName,ftFloat,0); end; var tmp:String; t:Integer; begin FieldDefs.Clear; if Assigned(FSeries) then begin {$IFDEF C3D4} With TFieldDef.Create(FieldDefs) do begin Name:='Color'; DataType:=ftInteger; Size:=0; Required:=False; FieldNo:=1; end; {$ELSE} TFieldDef.Create(FieldDefs, 'Color', ftInteger, 0, False, 1); {$ENDIF} With FSeries.XValues do AddField(DateTime,GetFieldName('X',Name)); With FSeries.YValues do AddField(DateTime,GetFieldName('Y',Name)); {$IFDEF C3D4} With TFieldDef.Create(FieldDefs) do begin Name:='Label'; DataType:=ftString; Size:=MaxLabelLen; Required:=False; FieldNo:=4; end; {$ELSE} TFieldDef.Create(FieldDefs, 'Label', ftString, MaxLabelLen, False, 4); {$ENDIF} for t:=2 to FSeries.ValuesList.Count-1 do With FSeries.ValuesList[t] do begin tmp:=Name; if Name='' then tmp:='Value'+TeeStr(t) else tmp:=Name; AddField(DateTime,tmp); end; end; end; procedure TSeriesDataSet.InternalHandleException; begin Application.HandleException(Self); end; procedure TSeriesDataSet.InternalGotoBookmark({$IFDEF CLR}const Bookmark:TBookmark{$ELSE}Bookmark: Pointer{$ENDIF}); var Index: Integer; begin Index := FBookMarks.IndexOf({$IFDEF CLR}Bookmark{$ELSE}Pointer(PInteger(Bookmark)^){$ENDIF}); if Index <> -1 then FCurRec := Index else DatabaseError('Bookmark not found'); end; procedure TSeriesDataSet.InternalSetToRecord(Buffer: {$IFDEF CLR}TRecordBuffer{$ELSE}PChar{$ENDIF}); begin {$IFDEF CLR} InternalGotoBookmark(TRecordBuffer(Longint(Buffer) + FBookmarkOfs)); {$ELSE} InternalGotoBookmark(@PRecInfo(Buffer + RecInfoOfs).Bookmark); {$ENDIF} end; function TSeriesDataSet.GetBookmarkFlag(Buffer: {$IFDEF CLR}TRecordBuffer{$ELSE}PChar{$ENDIF}): TBookmarkFlag; begin {$IFDEF CLR} with Marshal do Result := TBookmarkFlag(ReadByte(Buffer, FRecInfoOfs + 5)); // TRecInfo.BookmarkFlag {$ELSE} Result := PRecInfo(Buffer + RecInfoOfs).BookmarkFlag; {$ENDIF} end; procedure TSeriesDataSet.SetBookmarkFlag(Buffer: {$IFDEF CLR}TRecordBuffer{$ELSE}PChar{$ENDIF}; Value: TBookmarkFlag); begin {$IFDEF CLR} with Marshal do WriteByte(Buffer, FRecInfoOfs + 5, Byte(Value)); // TRecInfo.BookmarkFlag {$ELSE} PRecInfo(Buffer + RecInfoOfs).BookmarkFlag := Value; {$ENDIF} end; {$IFDEF CLR} procedure TSeriesDataSet.GetBookmarkData(Buffer: TRecordBuffer; var Bookmark: TBookmark); {$ELSE} procedure TSeriesDataSet.GetBookmarkData(Buffer: PChar; Data: Pointer); {$ENDIF} begin PInteger(Data)^ := PRecInfo(Buffer + RecInfoOfs).Bookmark; end; {$IFDEF CLR} procedure TSeriesDataSet.SetBookmarkData(Buffer: TRecordBuffer; const Bookmark: TBookmark); {$ELSE} procedure TSeriesDataSet.SetBookmarkData(Buffer: PChar; Data: Pointer); {$ENDIF} begin PRecInfo(Buffer + RecInfoOfs).Bookmark := PInteger(Data)^; end; function TSeriesDataSet.GetRecordSize: Word; begin if Assigned(FSeries) then result:=SizeOf(TSeriesPoint) else result:=0; end; function TSeriesDataSet.AllocRecordBuffer: {$IFDEF CLR}TRecordBuffer{$ELSE}PChar{$ENDIF}; begin GetMem(Result, RecBufSize); end; procedure TSeriesDataSet.FreeRecordBuffer(var Buffer: {$IFDEF CLR}TRecordBuffer{$ELSE}PChar{$ENDIF}); begin FreeMem(Buffer, RecBufSize); end; function TSeriesDataSet.GetRecord(Buffer: {$IFDEF CLR}TRecordBuffer{$ELSE}PChar{$ENDIF}; GetMode: TGetMode; DoCheck: Boolean): TGetResult; var t : Integer; begin result:=grError; if Assigned(FSeries) then begin if FSeries.Count < 1 then Result := grEOF else begin Result := grOK; case GetMode of gmNext: if FCurRec >= RecordCount - 1 then Result := grEOF else Inc(FCurRec); gmPrior: if FCurRec <= 0 then Result := grBOF else Dec(FCurRec); gmCurrent: if (FCurRec < 0) or (FCurRec >= RecordCount) then Result := grError; end; if Result = grOK then begin With PSeriesPoint(Buffer)^ do begin Color:=FSeries.ValueColor[FCurRec]; X:=FSeries.XValues.Value[FCurRec]; ALabel:=FSeries.Labels[FCurRec]; for t:=1 to FSeries.ValuesList.Count-1 do Values[t-1]:=FSeries.ValuesList[t].Value[FCurRec]; end; with PRecInfo(Buffer + RecInfoOfs)^ do begin BookmarkFlag := bfCurrent; if Assigned(FBookMarks) and (FBookMarks.Count>FCurRec) and Assigned(FBookMarks[FCurRec]) then Bookmark := Integer(FBookMarks[FCurRec]) else BookMark := -1; end; end else if (Result = grError) and DoCheck then DatabaseError('No Records'); end; end else if DoCheck then DatabaseError('No Records'); end; procedure TSeriesDataSet.InternalInitRecord(Buffer: {$IFDEF CLR}TRecordBuffer{$ELSE}PChar{$ENDIF}); begin FillChar(Buffer^, RecordSize, 0); end; function TSeriesDataSet.GetFieldData(Field: TField; Buffer: Pointer): Boolean; Function GetSeriesValue(AList:TChartValueList):Double; var t : Integer; begin if AList=FSeries.XValues then result:=PSeriesPoint(ActiveBuffer)^.X else begin result:=0; for t:=1 to FSeries.ValuesList.Count-1 do if AList=FSeries.ValuesList[t] then begin result:=PSeriesPoint(ActiveBuffer)^.Values[t-1]; break; end; end; if AList.DateTime then result:=TimeStampToMSecs(DateTimeToTimeStamp(result)); end; begin result:=(Series.Count>0) and (ActiveBuffer<>nil); { 5.01 , support for Null fields in DBChart } if result and Assigned(Buffer) then Case Field.FieldNo of 1: PInteger(Buffer)^:= PSeriesPoint(ActiveBuffer)^.Color; 2: PFloat(Buffer)^:=GetSeriesValue(FSeries.XValues); 3: PFloat(Buffer)^:=GetSeriesValue(FSeries.YValues); 4: begin StrPCopy(Buffer,PSeriesPoint(ActiveBuffer)^.ALabel); result := PChar(Buffer)^ <> #0; end; else begin PFloat(Buffer)^:=GetSeriesValue(FSeries.ValuesList[Field.FieldNo-3]); end; end; end; procedure TSeriesDataSet.SetFieldData(Field: TField; Buffer: Pointer); Function GetAValue(IsDateTime:Boolean):Double; begin result:=PFloat(Buffer)^; if IsDateTime then result:=TimeStampToDateTime(MSecsToTimeStamp(result)); end; begin if ActiveBuffer<>nil then Case Field.FieldNo of 1: PSeriesPoint(ActiveBuffer)^.Color:=PInteger(Buffer)^; 2: PSeriesPoint(ActiveBuffer)^.X:=GetAValue(FSeries.XValues.DateTime); 3: PSeriesPoint(ActiveBuffer)^.Values[0]:=GetAValue(FSeries.YValues.DateTime); 4: PSeriesPoint(ActiveBuffer)^.ALabel:=PChar(Buffer); else PSeriesPoint(ActiveBuffer)^.Values[Field.FieldNo-4]:=GetAValue(FSeries.ValuesList[Field.FieldNo-3].DateTime); end; DataEvent(deFieldChange, Integer(Field)); end; procedure TSeriesDataSet.InternalFirst; begin FCurRec := -1; end; procedure TSeriesDataSet.InternalLast; begin FCurRec := FSeries.Count; end; Procedure TSeriesDataSet.AddSeriesPoint(Buffer:Pointer; ABookMark:Integer); var t : Integer; begin With PSeriesPoint(Buffer)^ do begin for t:=2 to FSeries.ValuesList.Count-1 do FSeries.ValuesList[t].TempValue:=Values[t-1]; FSeries.AddXY(X,Values[0],ALabel,Color); end; FBookMarks.Add(Pointer(ABookMark)); end; procedure TSeriesDataSet.InternalPost; var t : Integer; begin if State = dsEdit then With PSeriesPoint(ActiveBuffer)^ do Begin FSeries.ValueColor[FCurRec]:=Color; FSeries.XValues.Value[FCurRec]:=X; FSeries.YValues.Value[FCurRec]:=Values[0]; FSeries.Labels[FCurRec]:=ALabel; for t:=2 to FSeries.ValuesList.Count-1 do FSeries.ValuesList[t].Value[FCurRec]:=Values[t-1]; end else begin Inc(FLastBookmark); AddSeriesPoint(ActiveBuffer,FLastBookMark); end; end; procedure TSeriesDataSet.InternalAddRecord(Buffer: Pointer; Append: Boolean); begin Inc(FLastBookmark); if Append then InternalLast; AddSeriesPoint(Buffer,FLastBookmark); end; procedure TSeriesDataSet.InternalDelete; begin FSeries.Delete(FCurRec); FBookMarks.Delete(FCurRec); if FCurRec >= RecordCount then Dec(FCurRec); end; function TSeriesDataSet.GetRecordCount: Integer; begin Result:=FSeries.Count; end; function TSeriesDataSet.GetRecNo: Integer; begin UpdateCursorPos; if (FCurRec = -1) and (RecordCount > 0) then Result := 1 else Result := FCurRec + 1; end; procedure TSeriesDataSet.SetRecNo(Value: Integer); begin if (Value >= 0) and (Value <= RecordCount) then begin FCurRec := Value - 1; Resync([]); end; end; procedure TSeriesDataSet.TeeEvent(Event: TTeeEvent); begin if Active and (Event is TTeeSeriesEvent) and (TTeeSeriesEvent(Event).Event=seDataChanged) then begin Close; Open; end; end; end.
unit Ex12Unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, MTUtils, ComCtrls, ExtCtrls, StrUtils, Contnrs, Generics.Collections; type TMyThread = class(TThread) private procedure LogEvent(EventText: string); protected procedure Execute; override; end; TForm1 = class(TForm) btnRunInParallelThread: TButton; Button1: TButton; ListBox1: TListBox; labLabLastThreadTime: TLabel; btnClearListBox: TButton; procedure btnRunInParallelThreadClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure btnClearListBoxClick(Sender: TObject); private { Private declarations } FList: TObjectList<TMyThread>; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btnClearListBoxClick(Sender: TObject); begin ListBox1.Clear; end; procedure TForm1.btnRunInParallelThreadClick(Sender: TObject); begin // Создаём и запускаем новый поток FList.Add(TMyThread.Create(False)); end; procedure TForm1.Button1Click(Sender: TObject); var t: TMyThread; begin for t in FList do t.Terminate; // Сообщаем потокам о необходимости завершаться FList.Clear; // Уничтожаем потоки end; procedure TForm1.FormCreate(Sender: TObject); begin FList := TObjectList<TMyThread>.Create; end; procedure TForm1.FormDestroy(Sender: TObject); begin FList.Free; end; { TMyThread } procedure TMyThread.Execute; var I: Integer; CurTime: TDateTime; begin CurTime := Now; // Запоминаем время ДО вызова Queue Queue( procedure begin Form1.labLabLastThreadTime.Caption := 'Последний поток был запущен: ' + DateTimeToStr(CurTime); end); LogEvent('Thread start'); I := 0; while not Terminated do begin Inc(I); LogEvent('Event #' + IntToStr(I)); ThreadWaitTimeout(Self, 500); end; LogEvent('Thread stop'); end; procedure TMyThread.LogEvent(EventText: string); var ThreadId: Cardinal; EventTime: TDateTime; begin // Запоминаем ID потока и текущее время ДО вызова Queue ThreadId := GetCurrentThreadId; EventTime := Now; TThread.Queue(nil, procedure begin Form1.ListBox1.Items.Add(Format('%s [T:%d] - %s', [FormatDateTime('hh:nn:ss.zzz', EventTime), ThreadId, EventText])); Form1.ListBox1.ItemIndex := Form1.ListBox1.Count - 1; end); end; end.
 //**************************************************************************// // Данный исходный код является составной частью системы МВТУ-4 // // Программисты: Тимофеев К.А., Ходаковский В.В. // //**************************************************************************// {$IFDEF FPC} {$MODE Delphi} {$ENDIF} unit Logs; //***************************************************************************// // Логические блоки // //***************************************************************************// interface uses Classes, MBTYArrays, DataTypes, SysUtils, abstract_im_interface, RunObjts, Math, mbty_std_consts; type //Произвольный логический блок TCustomLog = class(TRunObject) public inv_out: boolean; //Флаг инверсии выхода блока - если убрать старые блоки, можно выбросить T_In : double; //Значение, выше которого входы логических блоков считаются "Истина" true_val: double; false_val: double; constructor Create(Owner: TObject);override; destructor Destroy;override; function GetParamID(const ParamName:string;var DataType:TDataType;var IsConst: boolean):NativeInt;override; procedure SetTrueFalse(inv:Boolean); end; //Произвольная логическая операция TBool = class(TCustomLog) public what: NativeInt; //Тип второго входа log_type: NativeInt; //Тип логической операции function InfoFunc(Action: integer;aParameter: NativeInt):NativeInt;override; function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; function GetParamID(const ParamName:string;var DataType:TDataType;var IsConst: boolean):NativeInt;override; end; //Оператор логического отрицания TNot = class(TCustomLog) public function InfoFunc(Action: integer;aParameter: NativeInt):NativeInt;override; function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; end; //Оператор логического умножение (И) TAnd = class(TCustomLog) public function InfoFunc(Action: integer;aParameter: NativeInt):NativeInt;override; function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; end; //Оператор логического сложения (ИЛИ) TOr = class(TAnd) public function InfoFunc(Action: integer;aParameter: NativeInt):NativeInt;override; function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; end; //Оператор XOR (поэлементный) TXOR = class(TAnd) public function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; end; //Оператор not XOR (поэлементный) TNotXOR = class(TXOR) public function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; end; //Оператор векторного ИЛИ (сравнивает все элементы входного вектора) TVecOR = class(TAnd) public function InfoFunc(Action: integer;aParameter: NativeInt):NativeInt;override; function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; end; //Оператор векторного И TVecAnd = class(TVecOR) public function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; end; //Подтрверждение по количеству логических сигналов (векторное) TMN = class(TCustomLog) public m: NativeInt; function InfoFunc(Action: integer;aParameter: NativeInt):NativeInt;override; function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; function GetParamID(const ParamName:string;var DataType:TDataType;var IsConst: boolean):NativeInt;override; end; //Подтверждение по количеству логических сигналов (поэлементное) TMNByElement = class(TMN) public function InfoFunc(Action: integer;aParameter: NativeInt):NativeInt;override; function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; end; //Radio-button //Блок реализует работу группы логических сигналов по принципу //"Один из многих". На вход блока подается векторный логический сигнал TOne = class(TCustomLog) public n: integer; n_: NativeInt; //Эта переменная задаётся извне function InfoFunc(Action: integer;aParameter: NativeInt):NativeInt;override; function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; function GetParamID(const ParamName:string;var DataType:TDataType;var IsConst: boolean):NativeInt;override; procedure RestartSave(Stream: TStream);override; function RestartLoad(Stream: TStream;Count: integer;const TimeShift:double):boolean;override; end; // Radio-button //Блок реализует работу группы логических сигналов по принципу //"Один из многих". На вход блока подается номер активного элемента массива TOneVar = class(TCustomLog) public N: NativeInt; function GetParamID(const ParamName:string;var DataType:TDataType;var IsConst: boolean):NativeInt;override; function InfoFunc(Action: integer;aParameter: NativeInt):NativeInt;override; function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; end; //Счётчик импульсов TCounter = class(TRunObject) protected N : Integer; AX: array of double; public Ymin,Ymax : TExtArray; what : NativeInt; fResetType: NativeInt; constructor Create(Owner: TObject);override; destructor Destroy;override; function GetParamID(const ParamName:string;var DataType:TDataType;var IsConst: boolean):NativeInt;override; function InfoFunc(Action: integer;aParameter: NativeInt):NativeInt;override; function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; procedure RestartSave(Stream: TStream);override; function RestartLoad(Stream: TStream;Count: integer;const TimeShift:double):boolean;override; end; //Произвольная логическая операция TBitwizeOperations = class(TRunObject) public what: NativeInt; //Тип второго входа log_type: NativeInt; //Тип логической операции function InfoFunc(Action: integer;aParameter: NativeInt):NativeInt;override; function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; function GetParamID(const ParamName:string;var DataType:TDataType;var IsConst: boolean):NativeInt;override; end; //Побитовое логическое отрицание TBitwizeNot = class(TRunObject) public function InfoFunc(Action: integer;aParameter: NativeInt):NativeInt;override; function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; end; //Битовая упаковка в целое число TBitPack = class(TRunObject) public bit_nums: TIntArray; function InfoFunc(Action: integer;aParameter: NativeInt):NativeInt;override; function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; function GetParamID(const ParamName:string;var DataType:TDataType;var IsConst: boolean):NativeInt;override; constructor Create(Owner: TObject);override; destructor Destroy;override; end; //Битовая распаковка TBitUnPack = class(TBitPack) public function InfoFunc(Action: integer;aParameter: NativeInt):NativeInt;override; function RunFunc(var at,h : RealType;Action:Integer):NativeInt;override; end; implementation function TCustomLog.GetParamID; begin Result:=inherited GetParamId(ParamName,DataType,IsConst); if Result = -1 then begin if StrEqu(ParamName,'out_inv') then begin Result:=NativeInt(@inv_out); DataType:=dtBool; exit; end; if StrEqu(ParamName,'true_val') then begin Result:=NativeInt(@true_val); DataType:=dtDouble; exit; end; if StrEqu(ParamName,'false_val') then begin Result:=NativeInt(@false_val); DataType:=dtDouble; end; if StrEqu(ParamName,'t_in') then begin Result:=NativeInt(@t_in); DataType:=dtDouble; exit; end; end end; constructor TCustomLog.Create(Owner: TObject); begin inherited; T_in:=0.5; true_val:=1; false_val:=0; end; destructor TCustomLog.Destroy; begin u_inv:=nil; y_inv:=nil; inherited; end; procedure TCustomLog.SetTrueFalse(inv:Boolean); var tmp : Double; begin if inv then begin tmp:=true_val; true_val:=false_val; false_val:=tmp; end end; {******************************************************************************* Произвольная логическая операция *******************************************************************************} function TBool.GetParamID; begin Result:=inherited GetParamId(ParamName,DataType,IsConst); if Result = -1 then begin if StrEqu(ParamName,'what') then begin Result:=NativeInt(@what); DataType:=dtInteger; exit; end; if StrEqu(ParamName,'log_type') then begin Result:=NativeInt(@log_type); DataType:=dtInteger; end end end; function TBool.InfoFunc; begin Result:=0; case Action of i_GetCount: begin if what = 0 then CU.arr^[1]:=1 else CU.arr^[1]:=CU.arr^[0]; CY.arr^[0]:=CU.arr^[0]; end; else Result:=inherited InfoFunc(Action,aParameter); end; end; function TBool.RunFunc; var j: integer; x: RealType; u0,u1,f: Boolean; begin Result:=0; case Action of f_InitObjects:SetTrueFalse(y_inv[0]); f_RestoreOuts, f_UpdateOuts, f_UpdateJacoby, f_GoodStep, f_InitState: for j:=0 to Y[0].Count-1 do begin if what = 0 then x:=U[1].arr^[0] else x:=U[1].arr^[j]; case log_type of 0:begin u0:=U[0].arr^[j] >= T_In; if u_inv[0] then u0:=not u0; u1:=x >= T_In; if u_inv[1] then u1:=not u1; f:=u0 and u1; end; 1:begin u0:=U[0].arr^[j] >= T_In; if u_inv[0] then u0:=not u0; u1:=x >= T_In; if u_inv[1] then u1:=not u1; f:=u0 or u1; end; 2:f:=U[0].arr^[j] > x; 3:f:=U[0].arr^[j] < x; 4:f:=U[0].arr^[j] = x; 5:f:=U[0].arr^[j] <> x; 6:f:=U[0].arr^[j] >= x; 7:f:=U[0].arr^[j] <= x; 8:begin u0:=U[0].arr^[j] >= T_In; if u_inv[0] then u0:=not u0; u1:=x >= T_In; if u_inv[1] then u1:=not u1; f:=u0 xor u1; end; 9:begin u0:=U[0].arr^[j] >= T_In; if u_inv[0] then u0:=not u0; u1:=x >= T_In; if u_inv[1] then u1:=not u1; f:=not (u0 xor u1); end; else f:=false; end; if f then Y[0].arr^[j]:=true_val else Y[0].arr^[j]:=false_val; end; end end; {******************************************************************************* Операция логического отрицания *******************************************************************************} function TNot.InfoFunc; begin Result:=0; case Action of i_GetCount: CY.arr^[0]:=CU.arr^[0]; else Result:=inherited InfoFunc(Action,aParameter); end; end; function TNot.RunFunc; var j: integer; begin Result:=0; case Action of f_RestoreOuts, f_UpdateOuts, f_UpdateJacoby, f_GoodStep, f_InitState: for j:=0 to Y[0].Count-1 do if (U[0].arr^[j] < T_In) then Y[0].arr^[j]:=true_val else Y[0].arr^[j]:=false_val; end end; {******************************************************************************* Операция логического умножения *******************************************************************************} function TAnd.InfoFunc; var i: integer; begin Result:=0; case Action of i_GetCount: begin if CU.Count < 1 then begin ErrorEvent(txtAndErr,msError,VisualObject); Result:=r_Fail; exit; end; CY.arr^[0]:=CU.arr^[0]; for i:=1 to CU.Count - 1 do cU[i]:=cU[0]; end; else Result:=inherited InfoFunc(Action,aParameter); end; end; function TAnd.RunFunc; var j,i : integer; f,ui: boolean; begin Result:=0; case Action of f_InitObjects:SetTrueFalse(y_inv[0]); f_RestoreOuts, f_UpdateOuts, f_UpdateJacoby, f_GoodStep, f_InitState: for j:=0 to Y[0].Count-1 do begin f:=True; for i:=0 to cU.Count - 1 do begin ui:=U[i].Arr^[j] >= T_In; if u_inv[i] then ui:=not ui; f:=f and ui; end; if f then Y[0].Arr^[j]:=true_val else Y[0].Arr^[j]:=false_val; end end end; {******************************************************************************* Операция *******************************************************************************} function TOr.InfoFunc; var i: integer; begin Result:=0; case Action of i_GetCount: begin if CU.Count < 1 then begin ErrorEvent(txtOrErr,msError,VisualObject); Result:=r_Fail; exit; end; CY.arr^[0]:=CU.arr^[0]; for i:=1 to CU.Count - 1 do cU[i]:=cU[0]; end; else Result:=inherited InfoFunc(Action,aParameter); end; end; function TOr.RunFunc; var j,i : integer; f,ui : boolean; begin Result:=0; case Action of f_InitObjects:SetTrueFalse(y_inv[0]); f_RestoreOuts, f_UpdateOuts, f_UpdateJacoby, f_GoodStep, f_InitState: for j:=0 to Y[0].Count-1 do begin f:=False; for i:=0 to cU.Count - 1 do begin ui:=U[i].Arr^[j] >= T_In; if u_inv[i] then ui:=not ui; f:=f or ui; end; if f then Y[0].Arr^[j]:=true_val else Y[0].Arr^[j]:=false_val; end end end; {******************************************************************************* XOR *******************************************************************************} function TXOR.RunFunc; var i,j : integer; f,f1,f2: boolean; begin Result:=0; case Action of f_InitObjects:SetTrueFalse(y_inv[0]); f_RestoreOuts, f_UpdateOuts, f_UpdateJacoby, f_GoodStep, f_InitState: for j:=0 to Y[0].Count-1 do begin f:=False; f1:=(U[0].arr^[j] >= T_In); if u_inv[0] then f1:=not f1; for i:=1 to cU.Count - 1 do begin f:=false; f2:=U[i].Arr^[j] >= T_In; if u_inv[i] then f2:=not f2; if f1 or f2 then begin f:=true; if f1 and f2 then f:=false end; f1:=f end; if f then Y[0].Arr^[j]:=true_val else Y[0].Arr^[j]:=false_val; end end end; {******************************************************************************* Векторный OR *******************************************************************************} function TVecOr.InfoFunc; begin Result:=0; case Action of i_GetCount: begin if CU.Count < 1 then begin ErrorEvent(txtOrErr,msError,VisualObject); Result:=r_Fail; exit; end; CY.arr^[0]:=1; //Размерность выхода = 1 end; else Result:=inherited InfoFunc(Action,aParameter); end; end; function TVecOr.RunFunc; var j,i : integer; f,ui: boolean; begin Result:=0; case Action of f_InitObjects:SetTrueFalse(y_inv[0]); f_RestoreOuts, f_UpdateOuts, f_UpdateJacoby, f_GoodStep, f_InitState:begin f:=False; for I := 0 to cU.Count - 1 do for j := 0 to U[i].Count - 1 do begin ui:=U[i].Arr^[j] >= T_In; if u_inv[i] then ui:=not ui; f:=f or ui; end; if f then Y[0].Arr^[0]:=true_val else Y[0].Arr^[0]:=false_val; end; end end; function TVecAnd.RunFunc; var j,i : integer; f,ui: boolean; begin Result:=0; case Action of f_InitObjects:SetTrueFalse(y_inv[0]); f_RestoreOuts, f_UpdateOuts, f_UpdateJacoby, f_GoodStep, f_InitState:begin f:=True; for I := 0 to cU.Count - 1 do for j := 0 to U[i].Count - 1 do begin ui:=U[i].Arr^[j] >= T_In; if u_inv[i] then ui:=not ui; f:=f and ui; end; if f then Y[0].Arr^[0]:=true_val else Y[0].Arr^[0]:=false_val; end; end end; {******************************************************************************* Векторный not XOR *******************************************************************************} function TNotXOR.RunFunc; var i,j : integer; f,f1,f2: boolean; begin Result:=0; case Action of f_InitObjects:SetTrueFalse(y_inv[0]); f_RestoreOuts, f_UpdateOuts, f_UpdateJacoby, f_GoodStep, f_InitState: for j:=0 to Y[0].Count-1 do begin f:=False; f1:=(U[0].arr^[j] >= T_In); if u_inv[0] then f1:=not f1; for i:=1 to cU.Count - 1 do begin f:=false; f2:=U[i].Arr^[j] >= T_In; if u_inv[i] then f2:=not f2; if f1 or f2 then begin f:=true; if f1 and f2 then f:=false end; f:=not f; f1:=f end; if f then Y[0].Arr^[j]:=true_val else Y[0].Arr^[j]:=false_val; end end end; {******************************************************************************* Подтверждение по количеству сигналов *******************************************************************************} function TMN.GetParamID; begin Result:=inherited GetParamId(ParamName,DataType,IsConst); if Result = -1 then begin if StrEqu(ParamName,'m') then begin Result:=NativeInt(@m); DataType:=dtInteger; exit; end; end end; function TMN.InfoFunc; begin Result:=0; case Action of i_GetCount: CY.arr^[0]:=1; else Result:=inherited InfoFunc(Action,aParameter); end; end; function TMN.RunFunc; var i,j,k : Integer; f: boolean; begin Result:=0; case Action of f_InitObjects:SetTrueFalse(y_inv[0]); f_RestoreOuts, f_UpdateOuts, f_UpdateJacoby, f_GoodStep, f_InitState: begin k:=0; for i:=0 to cU.Count-1 do for j:=0 to U[i].Count-1 do begin f:=U[i].arr^[j] >= T_In; if u_inv[i] then f:=not f; if f then inc(k); end; f:= k >= m; if f then Y[0].arr^[0]:=true_val else Y[0].arr^[0]:=false_val; end; end end; //Тоже самое, но поэлементно function TMNByElement.InfoFunc; var i: integer; begin Result:=0; case Action of i_GetCount: begin if CU.Count < 1 then begin ErrorEvent(txtOrErr,msError,VisualObject); Result:=r_Fail; exit; end; CY.arr^[0]:=CU.arr^[0]; for i:=1 to CU.Count - 1 do cU[i]:=cU[0]; end; else Result:=inherited InfoFunc(Action,aParameter); end; end; function TMNByElement.RunFunc; var i,j,k : Integer; f: boolean; begin Result:=0; case Action of f_InitObjects:SetTrueFalse(y_inv[0]); f_RestoreOuts, f_UpdateOuts, f_UpdateJacoby, f_GoodStep, f_InitState: for j:=0 to Y[0].Count-1 do begin k:=0; for i:=0 to cU.Count - 1 do begin f:=U[i].Arr^[j] >= T_In; if u_inv[i] then f:=not f; if f then inc(k); end; f:= k >= m; if f then Y[0].Arr^[j]:=true_val else Y[0].Arr^[j]:=false_val; end; end end; {******************************************************************************* Выбор "один из многих" - радиогруппа *******************************************************************************} function TOne.GetParamID; begin Result:=inherited GetParamId(ParamName,DataType,IsConst); if Result = -1 then begin if StrEqu(ParamName,'n') then begin Result:=NativeInt(@n_); DataType:=dtInteger; end; end end; function TOne.InfoFunc; begin Result:=0; case Action of i_GetCount: begin CY.arr^[0]:=CU.arr^[0]; end; else Result:=inherited InfoFunc(Action,aParameter); end; end; function TOne.RunFunc; var j,k : Integer; begin Result:=0; case Action of f_GoodStep: begin k:=0; for j:=0 to Y[0].Count-1 do if (U[0].arr^[j] >= T_In) then begin N:=j+1; inc(k) end; if k <> 1 then exit; for j:=0 to Y[0].Count-1 do Y[0].arr^[j]:=false_val; Y[0].arr^[N-1]:=true_val; end; f_InitState: begin N:=N_; for j:=0 to Y[0].Count-1 do if j = N-1 then Y[0].arr^[j]:=true_val else Y[0].arr^[j]:=false_val; end; end end; procedure TOne.RestartSave(Stream: TStream); begin inherited; //Запись состояния для блока идеального запаздывания Stream.Write(N,SizeOfInt); end; function TOne.RestartLoad; begin Result:=inherited RestartLoad(Stream,Count,TimeShift); //Чтение состояния для блока идеального запаздывания if Result then if Count > 0 then try Stream.Read(N,SizeOfInt); finally end end; {******************************************************************************* Выбор "один из многих" с активным из порта *******************************************************************************} function TOneVar.GetParamID; begin Result:=inherited GetParamId(ParamName,DataType,IsConst); if Result = -1 then begin if StrEqu(ParamName,'n') then begin Result:=NativeInt(@n); DataType:=dtInteger; end; end end; function TOneVar.InfoFunc; begin Result:=0; case Action of i_GetCount: begin CY.arr^[0]:=N; CU.arr^[0]:=1; end; else Result:=inherited InfoFunc(Action,aParameter); end; end; function TOneVar.RunFunc; var j,k : Integer; begin Result:=0; case Action of f_InitState, f_RestoreOuts, f_GoodStep: begin k:=round(U[0].arr^[0]); for j:=0 to N-1 do if (j = k-1) then Y[0].arr^[j]:=true_val else Y[0].arr^[j]:=false_val end; end end; {******************************************************************************* Счётчик импульсов *******************************************************************************} constructor TCounter.Create; begin inherited; ymin:=TExtArray.Create(1); ymax:=TExtArray.Create(1); fResetType:=0; //0 - вход сброса - вектор, 1 - вход сброса - скаляр end; destructor TCounter.Destroy; begin inherited; ymin.Free; ymax.Free; end; function TCounter.GetParamID; begin Result:=inherited GetParamId(ParamName,DataType,IsConst); if Result = -1 then begin if StrEqu(ParamName,'what') then begin Result:=NativeInt(@what); DataType:=dtInteger; exit; end; if StrEqu(ParamName,'ymin') then begin Result:=NativeInt(ymin); DataType:=dtDoubleArray; exit; end; if StrEqu(ParamName,'resettype') then begin Result:=NativeInt(@fResetType); DataType:=dtInteger; exit; end; if StrEqu(ParamName,'ymax') then begin Result:=NativeInt(ymax); DataType:=dtDoubleArray; end; end end; function TCounter.InfoFunc; begin Result:=0; case Action of i_GetCount: begin CY.arr^[0]:=CU.arr^[0]; if cU.Count > 1 then if fResetType = 1 then cU.Arr^[1]:=1 else cU.Arr^[1]:=CU.arr^[0]; end else Result:=inherited InfoFunc(Action,aParameter); end; end; function TCounter.RunFunc; var j : Integer; x : RealType; begin Result:=0; case Action of f_InitObjects:begin N:=U[0].Count; SetLength(AX,2*N); //Добавляем переменную в список считывания данных if NeedRemoteData then if RemoteDataUnit <> nil then begin RemoteDataUnit.AddVectorToList(GetPortName(0),Y[0]); end; end; f_InitState: if not NeedRemoteData then for j:=0 to N-1 do begin AX[j]:=0; AX[j+N]:=1; x:=U[0].arr^[j]; case what of 0: if (x >= Ymin.arr^[j]) and (x <= Ymax.arr^[j]) then begin if AX[j+N] = 1.0 then begin AX[j]:=AX[j]+1.0; AX[j+N]:=0.0; end end else AX[j+N]:=1.0; 1: if (x <= Ymin.arr^[j]) or (x >= Ymax.arr^[j]) then begin if AX[j+N] = 1.0 then begin AX[j]:=AX[j]+1.0; AX[j+N]:=0.0 end end else AX[j+N]:=1.0; end; //Сброс по второму входу if (cU.Count > 1) and (U[1].Arr^[min(j,U[1].Count - 1)] > 0.5) then AX[j]:=0; Y[0].arr^[j]:=AX[j]; end; f_RestoreOuts: if not NeedRemoteData then for j:=0 to N-1 do Y[0].arr^[j]:=AX[j]; //ПРомежуточные шаги - не запоминаем состояние !!! f_UpdateOuts : if not NeedRemoteData then for j:=0 to N-1 do begin x:=U[0].arr^[j]; case what of 0: if (x >= Ymin.arr^[j]) and (x <= Ymax.arr^[j]) and (AX[j+N] = 1.0) then Y[0].arr^[j]:=AX[j]+1.0; 1: if (x <= Ymin.arr^[j]) or (x >= Ymax.arr^[j]) and (AX[j+N] = 1.0) then Y[0].arr^[j]:=AX[j]+1.0; end; //Сброс по второму входу if (cU.Count > 1) and (U[1].Arr^[min(j,U[1].Count - 1)] > 0.5) then Y[0].arr^[j]:=0; end; f_GoodStep : if not NeedRemoteData then for j:=0 to N-1 do begin x:=U[0].arr^[j]; case what of 0: if (x >= Ymin.arr^[j]) and (x <= Ymax.arr^[j]) then begin if AX[j+N] = 1.0 then begin AX[j]:=AX[j]+1.0; AX[j+N]:=0.0 end end else AX[j+N]:=1.0; 1: if (x <= Ymin.arr^[j]) or (x >= Ymax.arr^[j]) then begin if AX[j+N] = 1.0 then begin AX[j]:=AX[j]+1.0; AX[j+N]:=0.0 end end else AX[j+N]:=1.0; end; //Сброс по второму входу if (cU.Count > 1) and (U[1].Arr^[min(j,U[1].Count - 1)] > 0.5) then AX[j]:=0; Y[0].arr^[j]:=AX[j]; end; end end; procedure TCounter.RestartSave(Stream: TStream); begin inherited; Stream.Write(N,SizeOfInt); Stream.Write(AX[0],N*2*SizeOfDouble); end; function TCounter.RestartLoad; var c: integer; begin Result:=inherited RestartLoad(Stream,Count,TimeShift); if Result then if Count > 0 then try Stream.Read(c,SizeOfInt); Stream.Read(AX[0],min(N,c)*2*SizeOfDouble); finally end end; {******************************************************************************* Целочисленные логические операции *******************************************************************************} function TBitwizeOperations.GetParamID; begin Result:=inherited GetParamId(ParamName,DataType,IsConst); if Result = -1 then begin if StrEqu(ParamName,'what') then begin Result:=NativeInt(@what); DataType:=dtInteger; exit; end; if StrEqu(ParamName,'log_type') then begin Result:=NativeInt(@log_type); DataType:=dtInteger; end end end; function TBitwizeOperations.InfoFunc; begin Result:=0; case Action of i_GetCount: begin if what = 0 then CU.arr^[1]:=1 else CU.arr^[1]:=CU.arr^[0]; CY.arr^[0]:=CU.arr^[0]; end; else Result:=inherited InfoFunc(Action,aParameter); end; end; function TBitwizeOperations.RunFunc; var j: integer; u0,u1,res: integer; begin Result:=0; case Action of f_RestoreOuts, f_UpdateOuts, f_UpdateJacoby, f_GoodStep, f_InitState: for j:=0 to Y[0].Count-1 do begin //1-й операнд u0:=Trunc(U[0].arr^[j]); if u_inv[0] then u0:=not u0; //2-й операнд if what = 0 then u1:=Trunc(U[1].arr^[0]) else u1:=Trunc(U[1].arr^[j]); if u_inv[1] then u1:=not u1; case log_type of // & (И) 0: res:=u0 and u1; //1 (ИЛИ) 1: res:=u0 or u1; // (ИСКЛЮЧАЮЩЕЕ ИЛИ, XOR) 2: res:=u0 xor u1; // << (Битовый сдвиг влево) 3: res:=u0 shl u1; // >> (Битовый сдвиг вправо) 4: res:=u0 shr u1; // + (Сложение) 5: res:=u0 + u1; // - (Вычитание) 6: res:=u0 - u1; // * (Умножение) 7: res:=u0*u1; // / (Деление) 8: res:=u0 div u1; // % (Остаток от деления) 9: res:=u0 mod u1; else res:=0; end; //Инверсия выхода если надо if y_inv[0] then res:=not res; Y[0].arr^[j]:=res; end; end end; //Упаковка битов в число constructor TBitPack.Create(Owner: TObject); begin bit_nums:=TIntArray.Create(0); inherited; end; destructor TBitPack.Destroy; begin inherited; bit_nums.Free; end; function TBitPack.GetParamID; begin Result:=inherited GetParamId(ParamName,DataType,IsConst); if Result = -1 then begin if StrEqu(ParamName,'bit_nums') then begin Result:=NativeInt(bit_nums); DataType:=dtIntArray; end end end; function TBitPack.InfoFunc; var i: Integer; begin Result:=0; case Action of i_GetCount: begin if CU.Count > 0 then begin cY[0]:=cU[0]; for i := 1 to CU.Count - 1 do cU[i]:=cU[0]; end else cY[0]:=0; end; else Result:=inherited InfoFunc(Action,aParameter); end; end; function TBitPack.RunFunc; var i,j,res,inp_data: integer; begin Result:=0; case Action of f_RestoreOuts, f_UpdateOuts, f_UpdateJacoby, f_GoodStep, f_InitState: for j:=0 to Y[0].Count-1 do begin res:=0; for i := 0 to bit_nums.Count - 1 do begin inp_data:=Byte( ( U[i].Arr^[j] > 0.5 ) xor u_inv[i] ); res:=res or (inp_data shl bit_nums.Arr^[i]); end; //Инверсия выхода если надо if y_inv[0] then Y[0].arr^[j]:=not res else Y[0].arr^[j]:=res; end; end end; //Битовая распаковка function TBitUnPack.InfoFunc; var i: Integer; begin Result:=0; case Action of i_GetCount: begin for i := 0 to CY.Count - 1 do cY[i]:=cU[0]; end; else Result:=inherited InfoFunc(Action,aParameter); end; end; function TBitUnPack.RunFunc; var i,j,inp_data: integer; begin Result:=0; case Action of f_RestoreOuts, f_UpdateOuts, f_UpdateJacoby, f_GoodStep, f_InitState: for j:=0 to U[0].Count-1 do begin //Получение входа и инверсия если надо inp_data:=Trunc(U[0].Arr^[j]); if u_inv[0] then inp_data:=not inp_data; //Расстановка нужных битов выходов for i := 0 to bit_nums.Count - 1 do begin Y[i].arr^[j]:=Byte( ((inp_data and (1 shl bit_nums.Arr^[i])) <> 0) xor y_inv[i]); end; end; end end; // Побитовое логическое отрицание function TBitwizeNot.InfoFunc; begin Result:=0; case Action of i_GetCount: begin CY.arr^[0]:=CU.arr^[0]; end; else Result:=inherited InfoFunc(Action,aParameter); end; end; function TBitwizeNot.RunFunc; var j: integer; u0,res: integer; begin Result:=0; case Action of f_RestoreOuts, f_UpdateOuts, f_UpdateJacoby, f_GoodStep, f_InitState: for j:=0 to Y[0].Count-1 do begin u0:=Trunc(U[0].arr^[j]); if u_inv[0] then u0:=not u0; if y_inv[0] then res:=u0 else res:=not u0; Y[0].arr^[j]:=res; end; end end; end.
{$INCLUDE ..\cDefines.inc} unit cLinkedLists; { } { Data structures: Linked lists v3.03 } { } { This unit is copyright © 2000-2003 by David Butler (david@e.co.za) } { } { This unit is part of Delphi Fundamentals. } { Its original file name is cLinkedLists.pas } { It was generated 22 Jun 2003 09:29. } { The latest version is available from the Fundamentals home page } { http://fundementals.sourceforge.net/ } { } { I invite you to use this unit, free of charge. } { I invite you to distibute this unit, but it must be for free. } { I also invite you to contribute to its development, } { but do not distribute a modified copy of this file. } { } { A forum is available on SourceForge for general discussion } { http://sourceforge.net/forum/forum.php?forum_id=2117 } { } { } { Revision history: } { [ cUtils ] } { 2000/06/10 1.01 Added linked lists. } { [ cLinkedLists ] } { 2002/05/31 3.02 Created cLinkedLists from cUtils. } { 2002/11/02 3.03 Revision. } { } interface const UnitName = 'cLinkedLists'; UnitVersion = '3.03'; UnitDesc = 'Miscelleanous utility functions'; UnitCopyright = '(c) 2000-2003 David J Butler'; { } { Linked lists } { } type TDoublyLinkedItem = class protected FNext : TDoublyLinkedItem; FPrev : TDoublyLinkedItem; public destructor DestroyList; property Next: TDoublyLinkedItem read FNext write FNext; property Prev: TDoublyLinkedItem read FPrev write FPrev; function HasNext: Boolean; function HasPrev: Boolean; function Last: TDoublyLinkedItem; function First: TDoublyLinkedItem; function Count: Integer; procedure Remove; function RemoveNext: TDoublyLinkedItem; procedure DeleteNext; function RemovePrev: TDoublyLinkedItem; procedure DeletePrev; procedure InsertAfter(const Item: TDoublyLinkedItem); procedure InsertBefore(const Item: TDoublyLinkedItem); procedure Delete; end; TDoublyLinkedInteger = class(TDoublyLinkedItem) public Value : Integer; constructor Create(const V: Integer); procedure InsertAfter(const V: Integer); reintroduce; overload; procedure InsertBefore(const V: Integer); reintroduce; overload; procedure InsertFirst(const V: Integer); procedure Append(const V: Integer); function FindNext(const Find: Integer): TDoublyLinkedInteger; function FindPrev(const Find: Integer): TDoublyLinkedInteger; end; TDoublyLinkedExtended = class(TDoublyLinkedItem) public Value : Extended; constructor Create(const V: Extended); procedure InsertAfter(const V: Extended); reintroduce; overload; procedure InsertBefore(const V: Extended); reintroduce; overload; procedure InsertFirst(const V: Extended); procedure Append(const V: Extended); function FindNext(const Find: Extended): TDoublyLinkedExtended; function FindPrev(const Find: Extended): TDoublyLinkedExtended; end; TDoublyLinkedString = class(TDoublyLinkedItem) public Value : String; constructor Create(const V: String); procedure InsertAfter(const V: String); reintroduce; overload; procedure InsertBefore(const V: String); reintroduce; overload; procedure InsertFirst(const V: String); procedure Append(const V: String); function FindNext(const Find: String): TDoublyLinkedString; function FindPrev(const Find: String): TDoublyLinkedString; end; TDoublyLinkedObject = class(TDoublyLinkedItem) public Value : TObject; constructor Create(const V: TObject); procedure InsertAfter(const V: TObject); reintroduce; overload; procedure InsertBefore(const V: TObject); reintroduce; overload; procedure InsertFirst(const V: TObject); procedure Append(const V: TObject); function FindNext(const Find: TObject): TDoublyLinkedObject; function FindPrev(const Find: TObject): TDoublyLinkedObject; end; function AsDoublyLinkedIntegerList(const V: Array of Integer): TDoublyLinkedInteger; function AsDoublyLinkedExtendedList(const V: Array of Extended): TDoublyLinkedExtended; function AsDoublyLinkedStringList(const V: Array of String): TDoublyLinkedString; { } { TDoublyLinkedList } { } type TDoublyLinkedList = class protected FFirst : TDoublyLinkedItem; FLast : TDoublyLinkedItem; FCount : Integer; public destructor Destroy; override; property First: TDoublyLinkedItem read FFirst; property Last: TDoublyLinkedItem read FLast; function IsEmpty: Boolean; property Count: Integer read FCount; procedure Remove(const Item: TDoublyLinkedItem); function RemoveFirst: TDoublyLinkedItem; function RemoveLast: TDoublyLinkedItem; procedure Delete(const Item: TDoublyLinkedItem); procedure DeleteFirst; procedure DeleteLast; procedure DeleteList; procedure Append(const Item: TDoublyLinkedItem); procedure InsertFront(const Item: TDoublyLinkedItem); end; implementation { } { TDoublyLinkedItem } { } function TDoublyLinkedItem.HasNext: Boolean; begin Result := Assigned(Next); end; function TDoublyLinkedItem.Last: TDoublyLinkedItem; var P : TDoublyLinkedItem; begin P := self; Repeat Result := P; P := P.Next; Until not Assigned(P); end; function TDoublyLinkedItem.Count: Integer; var N : TDoublyLinkedItem; begin Result := 1; N := FNext; While Assigned(N) do begin Inc(Result); N := N.Next; end; end; function TDoublyLinkedItem.HasPrev: Boolean; begin Result := Assigned(FPrev); end; function TDoublyLinkedItem.First: TDoublyLinkedItem; var P : TDoublyLinkedItem; begin P := self; Repeat Result := P; P := P.Prev; Until not Assigned(P); end; procedure TDoublyLinkedItem.Delete; begin Remove; Free; end; procedure TDoublyLinkedItem.Remove; begin if Assigned(Next) then Next.Prev := FPrev; if Assigned(Prev) then Prev.Next := FNext; end; function TDoublyLinkedItem.RemoveNext: TDoublyLinkedItem; begin Result := FNext; if Assigned(Result) then begin FNext := Result.Next; if Assigned(FNext) then FNext.Prev := self; end; end; procedure TDoublyLinkedItem.DeleteNext; begin RemoveNext.Free; end; function TDoublyLinkedItem.RemovePrev: TDoublyLinkedItem; begin Result := FPrev; if Assigned(Result) then begin FPrev := Result.Prev; if Assigned(FPrev) then FPrev.Next := self; end; end; procedure TDoublyLinkedItem.DeletePrev; begin RemovePrev.Free; end; procedure TDoublyLinkedItem.InsertAfter(const Item: TDoublyLinkedItem); begin Item.Next := FNext; Item.Prev := self; FNext := Item; end; procedure TDoublyLinkedItem.InsertBefore(const Item: TDoublyLinkedItem); begin Item.Next := self; Item.Prev := FPrev; FPrev := Item; end; destructor TDoublyLinkedItem.DestroyList; var N : TDoublyLinkedItem; begin While Assigned(FNext) do begin N := FNext; FNext := N.Next; N.Free; end; inherited Destroy; end; { } { TDoublyLinkedInteger } { } constructor TDoublyLinkedInteger.Create(const V: Integer); begin inherited Create; Value := V; end; procedure TDoublyLinkedInteger.InsertAfter(const V: Integer); begin inherited InsertAfter(TDoublyLinkedInteger.Create(V)); end; procedure TDoublyLinkedInteger.InsertBefore(const V: Integer); begin inherited InsertBefore(TDoublyLinkedInteger.Create(V)); end; procedure TDoublyLinkedInteger.InsertFirst(const V: Integer); begin TDoublyLinkedInteger(First).InsertBefore(V); end; procedure TDoublyLinkedInteger.Append(const V: Integer); begin TDoublyLinkedInteger(Last).InsertAfter(V); end; function TDoublyLinkedInteger.FindNext(const Find: Integer): TDoublyLinkedInteger; begin Result := self; Repeat if Result.Value = Find then exit; Result := TDoublyLinkedInteger(Result.Next); Until not Assigned(Result); end; function TDoublyLinkedInteger.FindPrev(const Find: Integer): TDoublyLinkedInteger; begin Result := self; Repeat if Result.Value = Find then exit; Result := TDoublyLinkedInteger(Result.Prev); Until not Assigned(Result); end; { } { TDoublyLinkedExtended } { } constructor TDoublyLinkedExtended.Create(const V: Extended); begin inherited Create; Value := V; end; procedure TDoublyLinkedExtended.InsertAfter(const V: Extended); begin inherited InsertAfter(TDoublyLinkedExtended.Create(V)); end; procedure TDoublyLinkedExtended.InsertBefore(const V: Extended); begin inherited InsertBefore(TDoublyLinkedExtended.Create(V)); end; procedure TDoublyLinkedExtended.InsertFirst(const V: Extended); begin TDoublyLinkedExtended(First).InsertBefore(V); end; procedure TDoublyLinkedExtended.Append(const V: Extended); begin TDoublyLinkedExtended(Last).InsertAfter(V); end; function TDoublyLinkedExtended.FindNext(const Find: Extended): TDoublyLinkedExtended; begin Result := self; Repeat if Result.Value = Find then exit; Result := TDoublyLinkedExtended(Result.Next); Until not Assigned(Result); end; function TDoublyLinkedExtended.FindPrev(const Find: Extended): TDoublyLinkedExtended; begin Result := self; Repeat if Result.Value = Find then exit; Result := TDoublyLinkedExtended(Result.Prev); Until not Assigned(Result); end; { } { TDoublyLinkedString } { } constructor TDoublyLinkedString.Create(const V: String); begin inherited Create; Value := V; end; procedure TDoublyLinkedString.InsertAfter(const V: String); begin inherited InsertAfter(TDoublyLinkedString.Create(V)); end; procedure TDoublyLinkedString.InsertBefore(const V: String); begin inherited InsertBefore(TDoublyLinkedString.Create(V)); end; procedure TDoublyLinkedString.InsertFirst(const V: String); begin TDoublyLinkedString(First).InsertBefore(V); end; procedure TDoublyLinkedString.Append(const V: String); begin TDoublyLinkedString(Last).InsertAfter(V); end; function TDoublyLinkedString.FindNext(const Find: String): TDoublyLinkedString; begin Result := self; Repeat if Result.Value = Find then exit; Result := TDoublyLinkedString(Result.Next); Until not Assigned(Result); end; function TDoublyLinkedString.FindPrev(const Find: String): TDoublyLinkedString; begin Result := self; Repeat if Result.Value = Find then exit; Result := TDoublyLinkedString(Result.Prev); Until not Assigned(Result); end; { } { TDoublyLinkedObject } { } constructor TDoublyLinkedObject.Create(const V: TObject); begin inherited Create; Value := V; end; procedure TDoublyLinkedObject.InsertAfter(const V: TObject); begin inherited InsertAfter(TDoublyLinkedObject.Create(V)); end; procedure TDoublyLinkedObject.InsertBefore(const V: TObject); begin inherited InsertBefore(TDoublyLinkedObject.Create(V)); end; procedure TDoublyLinkedObject.InsertFirst(const V: TObject); begin TDoublyLinkedObject(First).InsertBefore(V); end; procedure TDoublyLinkedObject.Append(const V: TObject); begin TDoublyLinkedObject(Last).InsertAfter(V); end; function TDoublyLinkedObject.FindNext(const Find: TObject): TDoublyLinkedObject; begin Result := self; Repeat if Result.Value = Find then exit; Result := TDoublyLinkedObject(Result.Next); Until not Assigned(Result); end; function TDoublyLinkedObject.FindPrev(const Find: TObject): TDoublyLinkedObject; begin Result := self; Repeat if Result.Value = Find then exit; Result := TDoublyLinkedObject(Result.Prev); Until not Assigned(Result); end; { } { Open array to Linked list } { } function AsDoublyLinkedIntegerList(const V: Array of Integer): TDoublyLinkedInteger; var I, L : TDoublyLinkedInteger; F : Integer; begin Result := nil; L := nil; For F := 0 to High(V) do begin I := TDoublyLinkedInteger.Create(V [F]); if not Assigned(L) then begin L := I; Result := I; end else begin L.InsertAfter(I); L := I; end; end; end; function AsDoublyLinkedExtendedList(const V: Array of Extended): TDoublyLinkedExtended; var I, L : TDoublyLinkedExtended; F : Integer; begin Result := nil; L := nil; For F := 0 to High(V) do begin I := TDoublyLinkedExtended.Create(V [F]); if not Assigned(L) then begin L := I; Result := I; end else begin L.InsertAfter(I); L := I; end; end; end; function AsDoublyLinkedStringList(const V: Array of String): TDoublyLinkedString; var I, L : TDoublyLinkedString; F : Integer; begin Result := nil; L := nil; For F := 0 to High(V) do begin I := TDoublyLinkedString.Create(V [F]); if not Assigned(L) then begin L := I; Result := I; end else begin L.InsertAfter(I); L := I; end; end; end; { } { TDoublyLinkedList } { } Destructor TDoublyLinkedList.Destroy; begin DeleteList; inherited Destroy; end; function TDoublyLinkedList.IsEmpty: Boolean; begin Result := not Assigned(FFirst); end; procedure TDoublyLinkedList.Append(const Item: TDoublyLinkedItem); begin if not Assigned(Item) then exit; if not Assigned(FLast) then begin FFirst := Item; FLast := Item; Item.Prev := nil; Item.Next := nil; end else begin FLast.InsertAfter(Item); FLast := Item; end; Inc(FCount); end; procedure TDoublyLinkedList.InsertFront(const Item: TDoublyLinkedItem); begin if not Assigned(Item) then exit; if not Assigned(FFirst) then begin FFirst := Item; FLast := Item; Item.Prev := nil; Item.Next := nil; end else begin FFirst.InsertBefore(Item); FFirst := Item; end; Inc(FCount); end; procedure TDoublyLinkedList.Remove(const Item: TDoublyLinkedItem); begin if not Assigned(Item) then exit; if FFirst = Item then FFirst := Item.Next; if FLast = Item then FLast := Item.Prev; Item.Remove; Dec(FCount); end; function TDoublyLinkedList.RemoveFirst: TDoublyLinkedItem; begin Result := FFirst; if not Assigned(Result) then exit; if Result = FLast then begin FFirst := nil; FLast := nil; end else begin Result.Remove; FFirst := Result.Next; end; Dec(FCount); end; function TDoublyLinkedList.RemoveLast: TDoublyLinkedItem; begin Result := FLast; if not Assigned(Result) then exit; if Result = FFirst then begin FFirst := nil; FLast := nil; end else begin Result.Remove; FLast := Result.Prev; end; Dec(FCount); end; procedure TDoublyLinkedList.Delete(const Item: TDoublyLinkedItem); begin Remove(Item); Item.Free; end; procedure TDoublyLinkedList.DeleteFirst; begin RemoveFirst.Free; end; procedure TDoublyLinkedList.DeleteLast; begin RemoveLast.Free; end; procedure TDoublyLinkedList.DeleteList; begin if Assigned(FFirst) then FFirst.DestroyList; FFirst := nil; FLast := nil; end; end.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------} unit untEasyFormDesigner; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, untEasyPageControl, untEasyMenus, untEasyMenuStylers, untEasyToolBar, untEasyToolBarStylers, untEasyStatusBar, untFrmDsnEdit, untEasyStatusBarStylers, Menus, eddPaletteFrame, eddObjInspFrm, eddObjTreeFrame, edActns, ActnList, ImgList, ed_DsnBase, ed_Designer, ed_dsncont, untEasyPlateDBBaseForm, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, ComCtrls, ShlObj, cxShellCommon, cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox, cxShellComboBox, DB, ADODB, ecActns; //插件导出函数 function ShowBplForm(AParamList: TStrings): TForm; stdcall; exports ShowBplForm; type TfrmEasyFormDesigner = class(TfrmEasyPlateDBBaseForm) EasyDockPanel1: TEasyDockPanel; EasyToolBar1: TEasyToolBar; EasyToolBarOfficeStyler1: TEasyToolBarOfficeStyler; EasyMenuOfficeStyler1: TEasyMenuOfficeStyler; pgcLeft: TEasyPageControl; pgcRight: TEasyPageControl; Splitter1: TSplitter; Splitter2: TSplitter; tbsToolBox: TEasyTabSheet; tbsObjectTree: TEasyTabSheet; EasyMainMenu1: TEasyMainMenu; F1: TMenuItem; tbsInspector: TEasyTabSheet; ObjectTreeFrame1: TObjectTreeFrame; PaletteFrame1: TPaletteFrame; ObjectInspectorFrame1: TObjectInspectorFrame; ImageList1: TImageList; SD: TSaveDialog; OD: TOpenDialog; ActionList1: TActionList; FileNew: TAction; dsnAlignToGrid1: TdsnAlignToGrid; dsnBringToFront1: TdsnBringToFront; dsnSendToBack1: TdsnSendToBack; dsnAlignmentDlg1: TdsnAlignmentDlg; dsnSizeDlg1: TdsnSizeDlg; dsnScale1: TdsnScale; dsnTabOrderDlg1: TdsnTabOrderDlg; dsnCreationOrderDlg1: TdsnCreationOrderDlg; dsnFlipChildrenAll1: TdsnFlipChildrenAll; dsnFlipChildren1: TdsnFlipChildren; dsnCopy1: TdsnCopy; dsnCut1: TdsnCut; dsnDelete1: TdsnDelete; dsnPaste1: TdsnPaste; dsnLockControls1: TdsnLockControls; dsnSelectAll1: TdsnSelectAll; FileOpen: TAction; FileSave: TAction; FileExit: TAction; FileMerge: TAction; DesignMode: TAction; FileClose: TAction; FileCloseAll: TAction; actBDSStyle: TAction; actReadOnly: TAction; dsnUndo1: TdsnUndo; dsnRedo1: TdsnRedo; dsnTextEditMode1: TdsnTextEditMode; PopupMenu1: TPopupMenu; N2: TMenuItem; Copy2: TMenuItem; Cut2: TMenuItem; Paste2: TMenuItem; New1: TMenuItem; EasyToolBarButton1: TEasyToolBarButton; Open1: TMenuItem; EasyToolBarButton2: TEasyToolBarButton; EasyToolBarButton3: TEasyToolBarButton; Save1: TMenuItem; EasyToolBarSeparator1: TEasyToolBarSeparator; N1: TMenuItem; Mergewithcurrent1: TMenuItem; Close1: TMenuItem; CloseAll1: TMenuItem; N3: TMenuItem; Exit1: TMenuItem; EasyToolBarButton4: TEasyToolBarButton; pgcCenter: TEasyPageControl; E1: TMenuItem; Undo1: TMenuItem; Redo1: TMenuItem; N4: TMenuItem; EasyToolBarSeparator2: TEasyToolBarSeparator; EasyToolBarButton5: TEasyToolBarButton; EasyToolBarButton6: TEasyToolBarButton; EasyToolBarButton7: TEasyToolBarButton; EasyToolBarButton8: TEasyToolBarButton; EasyToolBarSeparator3: TEasyToolBarSeparator; EasyToolBarButton9: TEasyToolBarButton; EasyToolBarButton10: TEasyToolBarButton; EasyToolBarSeparator4: TEasyToolBarSeparator; EasyToolBarButton11: TEasyToolBarButton; Copy1: TMenuItem; Cut1: TMenuItem; Paste1: TMenuItem; Delete1: TMenuItem; N5: TMenuItem; SelectAll1: TMenuItem; D1: TMenuItem; EasyToolBar2: TEasyToolBar; EasyToolBarButton12: TEasyToolBarButton; EasyToolBarButton13: TEasyToolBarButton; EasyToolBarButton14: TEasyToolBarButton; Aligntogrid1: TMenuItem; Bringtofront1: TMenuItem; Sendtoback1: TMenuItem; Align1: TMenuItem; Size1: TMenuItem; Scale1: TMenuItem; EasyToolBarSeparator5: TEasyToolBarSeparator; EasyToolBarSeparator6: TEasyToolBarSeparator; EasyToolBarButton15: TEasyToolBarButton; EasyToolBarButton16: TEasyToolBarButton; EasyToolBarButton17: TEasyToolBarButton; N6: TMenuItem; N7: TMenuItem; N8: TMenuItem; aborder1: TMenuItem; CreationOrder1: TMenuItem; N9: TMenuItem; EasyToolBarSeparator7: TEasyToolBarSeparator; EasyToolBarButton18: TEasyToolBarButton; EasyToolBarButton19: TEasyToolBarButton; FlipChildren1: TMenuItem; Flipallchildren1: TMenuItem; Flipchildren2: TMenuItem; LockControls1: TMenuItem; N10: TMenuItem; ReadOnly1: TMenuItem; EditText1: TMenuItem; EasyToolBarSeparator8: TEasyToolBarSeparator; EasyToolBarButton20: TEasyToolBarButton; T1: TMenuItem; N11: TMenuItem; N12: TMenuItem; BDSStyle1: TMenuItem; EasyToolBarButton21: TEasyToolBarButton; dsnSaveAs: TAction; N13: TMenuItem; V1: TMenuItem; N14: TMenuItem; actRightPageControl: TAction; actLeftPageControl: TAction; N15: TMenuItem; N16: TMenuItem; EasyToolBar3: TEasyToolBar; EasyToolBarButton22: TEasyToolBarButton; ecCommandAction1: TecCommandAction; ecCopy1: TecCopy; ecCut1: TecCut; ecPaste1: TecPaste; ecClear1: TecClear; ecSelectAll1: TecSelectAll; ecUndo1: TecUndo; ecRedo1: TecRedo; ecCopyAsRTF1: TecCopyAsRTF; ecIndent1: TecIndent; ecUnindent1: TecUnindent; ecLowerCase1: TecLowerCase; ecUpperCase1: TecUpperCase; ecToggleCase1: TecToggleCase; ecSyntMemoAction1: TecSyntMemoAction; procedure FileNewExecute(Sender: TObject); procedure FileCloseExecute(Sender: TObject); procedure FileOpenExecute(Sender: TObject); procedure FileSaveExecute(Sender: TObject); procedure FileCloseAllExecute(Sender: TObject); procedure FileMergeExecute(Sender: TObject); procedure DesignModeExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FileCloseUpdate(Sender: TObject); procedure FileSaveUpdate(Sender: TObject); procedure N11Click(Sender: TObject); procedure pgcCenterDblClick(Sender: TObject); procedure actBDSStyleExecute(Sender: TObject); procedure actBDSStyleUpdate(Sender: TObject); procedure dsnLockControls1Update(Sender: TObject); procedure dsnSaveAsExecute(Sender: TObject); procedure dsnSaveAsUpdate(Sender: TObject); procedure FileExitExecute(Sender: TObject); procedure actRightPageControlExecute(Sender: TObject); procedure actRightPageControlUpdate(Sender: TObject); procedure actLeftPageControlExecute(Sender: TObject); procedure actLeftPageControlUpdate(Sender: TObject); procedure pgcCenterChange(Sender: TObject); private { Private declarations } FIgnoreAll: Boolean; function BindRoot(Form: TComponent; AFileName: string): TFrmDsnEdit; procedure ReadError(Reader: TReader; const Message: string; var Handled: Boolean); function GetCurDesigner: TzFormDesigner; public { Public declarations } property CurDesigner: TzFormDesigner read GetCurDesigner; end; var frmEasyFormDesigner: TfrmEasyFormDesigner; implementation uses ed_RegComps, edUtils, edManager, {untStdRegComps, }TypInfo, edIOUtils, DesignIntf, TreeIntf, edReg; {$R *.dfm} var Count: integer = 1; //窗体创建计数器 //引出函数实现 function ShowBplForm(AParamList: TStrings): TForm; begin frmEasyFormDesigner := TfrmEasyFormDesigner.Create(Application); if frmEasyFormDesigner.FormStyle <> fsMDIChild then frmEasyFormDesigner.FormStyle := fsMDIChild; if frmEasyFormDesigner.WindowState <> wsMaximized then frmEasyFormDesigner.WindowState := wsMaximized; frmEasyFormDesigner.FormId := '{5EDC78F7-3AD4-413B-AF8E-298CF3E8789A}'; Result := frmEasyFormDesigner; end; function TfrmEasyFormDesigner.BindRoot(Form: TComponent; AFileName: string): TFrmDsnEdit; var Page: TEasyTabSheet; begin if Form is TForm then // 只有Form窗体才能挂靠 begin Page := TEasyTabSheet.Create(Self); Page.Caption := Form.Name; Page.PageControl := pgcCenter; Page.Hint := AFileName; Result := TFrmDsnEdit.Create(nil); Result.Align := alClient; Result.Parent := Page; Result.AForm := TForm(Form); Result.FormDesigner.Target := Form; Result.FormDesigner.Active := True; pgcCenter.ActivePage := Page; end else Result := nil; end; procedure TfrmEasyFormDesigner.FileNewExecute(Sender: TObject); var fm: TForm; begin fm := TForm.Create(nil); fm.Name := 'Untitled' + IntToStr(Count); Inc(Count); BindRoot(fm, ''); end; procedure TfrmEasyFormDesigner.FileCloseExecute(Sender: TObject); var I, Count: Integer; begin Count := pgcCenter.PageCount; if pgcCenter.ActivePage <> nil then begin I := pgcCenter.ActivePageIndex; if dsnUndo1.Enabled then begin if Application.MessageBox('文件已更改,是否保存?', PChar('提示'), MB_OKCANCEL + MB_ICONQUESTION) = IDOK then FileSave.Execute; end; pgcCenter.ActivePage.Free; if I < (Count - 1) then pgcCenter.ActivePageIndex := I else pgcCenter.ActivePageIndex := I - 1; end; end; procedure TfrmEasyFormDesigner.FileOpenExecute(Sender: TObject); var fm : TForm; begin if OD.Execute then begin FIgnoreAll := False; fm := TForm.Create(nil); try zReadCmpFromFile(OD.FileName, fm, ReadError); except fm.Free; Exit; end; BindRoot(fm, OD.FileName); end; end; procedure TfrmEasyFormDesigner.ReadError(Reader: TReader; const Message: string; var Handled: Boolean); begin Handled := FIgnoreAll; if not Handled then case MessageDlg(Message + sLineBreak + '忽略此错误?', mtError, [mbYes, mbNo, mbAll], 0) of mrYes: Handled := True; mrAll: begin Handled := True; FIgnoreAll := True; end; end; end; procedure TfrmEasyFormDesigner.FileSaveExecute(Sender: TObject); begin if dsnUndo1.Enabled then begin if pgcCenter.ActivePage.Hint <> '' then DsnWriteToFile(pgcCenter.ActivePage.Hint, CurDesigner, True) else begin if SD.Execute then begin DsnWriteToFile(SD.FileName, CurDesigner, True); pgcCenter.ActivePage.Hint := SD.FileName; end else Exit; end; end; end; function TfrmEasyFormDesigner.GetCurDesigner: TzFormDesigner; begin if pgcCenter.ActivePage = nil then Result := nil else Result := TFrmDsnEdit(pgcCenter.ActivePage.Controls[0]).FormDesigner; end; procedure TfrmEasyFormDesigner.FileCloseAllExecute(Sender: TObject); var I: integer; begin for i := pgcCenter.PageCount - 1 downto 0 do pgcCenter.Pages[i].Free; end; procedure TfrmEasyFormDesigner.FileMergeExecute(Sender: TObject); begin if (CurDesigner <> nil) and OD.Execute then DsnReadFromFile(OD.FileName, CurDesigner, ReadError); end; procedure TfrmEasyFormDesigner.DesignModeExecute(Sender: TObject); var fm: TForm; Mem: TMemoryStream; begin if CurDesigner <> nil then if CurDesigner.Active then begin Mem := TMemoryStream.Create; try DsnWriteCmpToStream(Mem, CurDesigner, False); fm := TForm.Create(Self); fm.OnClose := FormClose; Mem.Position := 0; zReadCmpFromStream(Mem, fm); fm.Show; finally Mem.Free; end; end; end; procedure TfrmEasyFormDesigner.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfrmEasyFormDesigner.FileCloseUpdate(Sender: TObject); begin TAction(Sender).Enabled := CurDesigner <> nil; end; procedure TfrmEasyFormDesigner.FileSaveUpdate(Sender: TObject); begin FileSave.Enabled := CurDesigner <> nil; end; procedure TfrmEasyFormDesigner.N11Click(Sender: TObject); begin ObjectInspectorFrame1.Customize; end; procedure TfrmEasyFormDesigner.pgcCenterDblClick(Sender: TObject); begin FileClose.Execute; end; procedure TfrmEasyFormDesigner.actBDSStyleExecute(Sender: TObject); begin CurDesigner.BDSStyle := not CurDesigner.BDSStyle; end; procedure TfrmEasyFormDesigner.actBDSStyleUpdate(Sender: TObject); begin actBDSStyle.Enabled := CurDesigner <> nil; if actBDSStyle.Enabled then actBDSStyle.Checked := CurDesigner.BDSStyle; end; procedure TfrmEasyFormDesigner.dsnLockControls1Update(Sender: TObject); begin CurDesigner.LockControls := dsnLockControls1.Checked end; procedure TfrmEasyFormDesigner.dsnSaveAsExecute(Sender: TObject); begin if (CurDesigner <> nil) and SD.Execute then DsnWriteToFile(SD.FileName, CurDesigner, True) end; procedure TfrmEasyFormDesigner.dsnSaveAsUpdate(Sender: TObject); begin dsnSaveAs.Enabled := CurDesigner <> nil; end; procedure TfrmEasyFormDesigner.FileExitExecute(Sender: TObject); begin FileCloseAll.Execute; Close; // if CurDesigner.Modified then // begin // ShowMessage('Modified'); // end; end; procedure TfrmEasyFormDesigner.actRightPageControlExecute(Sender: TObject); begin pgcRight.Visible := not pgcRight.Visible; end; procedure TfrmEasyFormDesigner.actRightPageControlUpdate(Sender: TObject); begin actRightPageControl.Checked := pgcRight.Visible; end; procedure TfrmEasyFormDesigner.actLeftPageControlExecute(Sender: TObject); begin pgcLeft.Visible := not pgcLeft.Visible; end; procedure TfrmEasyFormDesigner.actLeftPageControlUpdate(Sender: TObject); begin actLeftPageControl.Checked := pgcLeft.Visible; end; procedure TfrmEasyFormDesigner.pgcCenterChange(Sender: TObject); begin if pgcCenter.ActivePage <> nil then begin TFrmDsnEdit(pgcCenter.ActivePage.Controls[0]).FormDesigner.Active := False; TFrmDsnEdit(pgcCenter.ActivePage.Controls[0]).FormDesigner.Target := TFrmDsnEdit(pgcCenter.ActivePage.Controls[0]).AForm; TFrmDsnEdit(pgcCenter.ActivePage.Controls[0]).FormDesigner.Active := True; end; end; end.
unit uUserInfo; interface uses System.Classes, system.SysUtils, xFunction; type /// <summary> /// 用户信息类 /// </summary> TUser = class private FGroupID: Integer; FID: Integer; FChangePwd: Boolean; FDescription: String; FFullName: String; FPassword: string; FDisabled: Boolean; FLoginName: String; FEmbedded: Boolean; public constructor Create; property ID : Integer read FID write FID; property GroupID : Integer read FGroupID write FGroupID ; property LoginName : String read FLoginName write FLoginName ; property Password : string read FPassword write FPassword ; property FullName : String read FFullName write FFullName ; property Description : String read FDescription write FDescription ; property ChangePwd : Boolean read FChangePwd write FChangePwd ; property Disabled : Boolean read FDisabled write FDisabled ; property Embedded : Boolean read FEmbedded write FEmbedded ; /// <summary> /// 克隆对象 /// </summary> procedure Assign(Source : TObject); end; type /// <summary> /// 用户权限 /// </summary> TUserRight = class private FRightName: String; FID: Integer; FDescription: String; public constructor Create; property ID : Integer read FID write FID; property RightName : String read FRightName write FRightName; property Description : String read FDescription write FDescription; /// <summary> /// 克隆对象 /// </summary> procedure Assign(Source : TObject); end; type /// <summary> /// 用户组 /// </summary> TUserGroup = class private FID: Integer; FDescription: String; FRights: TStringList; FEmbedded: Boolean; FGroupName: String; public property ID : Integer read FID write FID; property GroupName : String read FGroupName write FGroupName; property Description : String read FDescription write FDescription; property Embedded : Boolean read FEmbedded write FEmbedded; property Rights : TStringList read FRights write FRights; constructor Create; destructor Destroy;override; /// <summary> /// 克隆对象 /// </summary> procedure Assign(Source : TObject); end; implementation { TUserGroup } constructor TUserGroup.Create; begin FRights := TStringList.Create; FID := -1; FDescription:= EmptyStr; FEmbedded := False; FGroupName := EmptyStr; end; destructor TUserGroup.Destroy; begin ClearStringList(FRights); FRights.Free; inherited; end; procedure TUserGroup.Assign(Source: TObject); var i : integer; AUserRight : TUserRight; begin Assert(Source is TUserGroup); FID := TUserGroup(Source).ID ; FGroupName := TUserGroup(Source).GroupName ; FDescription := TUserGroup(Source).Description ; FEmbedded := TUserGroup(Source).Embedded ; ClearStringList(FRights); for i := 0 to TUserGroup(Source).Rights.Count - 1 do begin AUserRight := TUserRight.Create; AUserRight.Assign(TUserRight(TUserGroup(Source).Rights.Objects[i])); FRights.AddObject('', AUserRight); end; end; { TUser } procedure TUser.Assign(Source: TObject); begin Assert(Source is TUser); FID := TUser(Source).ID ; FGroupID := TUser(Source).GroupID ; FLoginName := TUser(Source).LoginName ; FPassword := TUser(Source).Password ; FFullName := TUser(Source).FullName ; FDescription := TUser(Source).Description ; FChangePwd := TUser(Source).ChangePwd ; FDisabled := TUser(Source).Disabled ; FEmbedded := TUser(Source).Embedded ; end; constructor TUser.Create; begin FGroupID := -1; FID := -1; FChangePwd := False; FDescription:= EmptyStr; FFullName := EmptyStr; FPassword := EmptyStr; FDisabled := False; FLoginName := EmptyStr; FEmbedded := False; end; { TUserRight } procedure TUserRight.Assign(Source: TObject); begin Assert(Source is TUserRight); FID := TUserRight(Source).ID ; FRightName := TUserRight(Source).RightName ; FDescription := TUserRight(Source).Description ; end; constructor TUserRight.Create; begin FRightName := EmptyStr; FID := -1; FDescription:= EmptyStr; end; end.
unit uOptions; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TfmOptions = class(TForm) laPollingInterval: TLabel; cmbPollingInterval: TComboBox; cbRunAtWinStartup: TCheckBox; btOk: TButton; btCancel: TButton; private public procedure ApplyPreferences; procedure ChangePreferences; end; var fmOptions: TfmOptions; implementation uses uPreferences, uStruct; {$R *.dfm} procedure TfmOptions.ApplyPreferences; begin cmbPollingInterval.ItemIndex:=Ord(PollingInterval); cbRunAtWinStartup.Checked:=CheckRunAtStartupOption; end; procedure TfmOptions.ChangePreferences; begin PollingInterval:=TPollingInterval(cmbPollingInterval.ItemIndex); SaveRunAtStartupOption(cbRunAtWinStartup.Checked); end; end.
unit MediaProcessing.Convertor.H264.RGB.Impl; interface uses Windows,SysUtils,Classes,MediaProcessing.Convertor.H264.RGB,MediaProcessing.Definitions,MediaProcessing.Global,AVC,Avc.avcodec, H264Def, MediaProcessing.Common.Processor.FPS; type TMediaProcessor_ConvertorH264_Rgb_Impl =class (TMediaProcessor_Convertor_H264_Rgb,IMediaProcessorImpl) private FDecoder: IVideoDecoder; FBmpInfoHeader: TBitmapInfoHeader; FPrevFrameImageWidth,FPrevFrameImageHeight: integer; FConsequtiveErrors: integer; FDibBuffer : TBytes; //FLastVideoFrameTimeStamp: cardinal; protected procedure Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal; out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal); override; public constructor Create; override; destructor Destroy; override; end; implementation uses uBaseClasses; { TMediaProcessor_ConvertorH264_Rgb_Impl } constructor TMediaProcessor_ConvertorH264_Rgb_Impl.Create; begin inherited; FBmpInfoHeader.biSize:=sizeof(FBmpInfoHeader); FBmpInfoHeader.biPlanes:=1; FBmpInfoHeader.biBitCount:=24; SetTraceIdentifier('h264-rgb'); end; destructor TMediaProcessor_ConvertorH264_Rgb_Impl.Destroy; begin FDecoder:=nil; inherited; end; procedure TMediaProcessor_ConvertorH264_Rgb_Impl.Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal; out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal); var //aMinDelta : cardinal; aNalUnitType: TNalUnitType; aTmp: integer; aNeedSize,aDecodedSize: integer; aParams: IVideoDecoderParams; aDecodeResult: FFMPEG_RESULT; begin CheckIfChannel0(aInFormat); aOutData:=nil; aOutDataSize:=0; aOutInfo:=nil; aOutInfoSize:=0; Assert(aInFormat.biStreamType=stH264); // //|0|1|2|3|4|5|6|7| //+-+-+-+-+-+-+-+-+ //|F|NRI| Type | //+---------------+ Assert(PDWORD(aInData)^=$1000000); //NAL_START_MARKER aTmp:=(PByte(aInData)+4)^; Assert(aTmp shr 7=0); aNalUnitType:=ExtractNalType(aTmp); Assert(integer(aNalUnitType) in [1..23]); //if not (aPayload in [1,5]) then // exit; //Только опорные кадры if (FChangeFPSMode = cfmVIFrameOnly) then if (aNalUnitType in [NAL_UT_SLICE_NON_IDR,NAL_UT_SLICE_DPA,NAL_UT_SLICE_DPB,NAL_UT_SLICE_DPC]) then exit; if (FPrevFrameImageWidth<>aInFormat.VideoWidth) or (FPrevFrameImageHeight<>aInFormat.VideoHeight) then begin if FDecoder<>nil then TraceLine('Изменился формат кадра, удаляем старый декодер'); FDecoder:=nil; end; if (FConsequtiveErrors>100) then begin if FDecoder<>nil then TraceLine('Декодер не в состоянии выполнить декодирование 100 фреймов подряд, удаляем декодер'); FConsequtiveErrors:=0; FDecoder:=nil; end; FPrevFrameImageWidth:=aInFormat.VideoWidth; FPrevFrameImageHeight:=aInFormat.VideoHeight; FBmpInfoHeader.biWidth:=aInFormat.VideoWidth; FBmpInfoHeader.biHeight:=aInFormat.VideoHeight; if FDecoder=nil then begin TraceLine('Создаем декодер...'); AvcCheck(CreateVideoDecoder(AV_CODEC_ID_H264, FDecoder)); AvcCheck(FDecoder.GetParams(aParams)); aParams.SetWidth(FBmpInfoHeader.biWidth); aParams.SetHeight(FBmpInfoHeader.biHeight); FDecoder.Open(false); TraceLine('Декодер успешно создан'); end; //FVideoDecoder.Lock; try aNeedSize:=aInFormat.VideoWidth*aInFormat.VideoHeight*3; if Length(FDibBuffer)<aNeedSize then SetLength(FDibBuffer,aNeedSize); aDecodeResult:=FDecoder.DecodeRGB24(aInData,aInDataSize, @FDibBuffer[0],aNeedSize,aDecodedSize); if (aDecodeResult=FR_SUCCESSFUL) and (aDecodedSize>0) then begin FConsequtiveErrors:=0; if not Process_Fps(aInFormat) then exit; Process_ImageSizeRGB(@FDibBuffer[0],FBmpInfoHeader.biWidth,FBmpInfoHeader.biHeight); FBmpInfoHeader.biSizeImage:=FBmpInfoHeader.biWidth*FBmpInfoHeader.biHeight*3; aOutData:=@FDibBuffer[0]; aOutDataSize:=FBmpInfoHeader.biSizeImage; aOutInfo:=@FBmpInfoHeader; aOutInfoSize:=sizeof(FBmpInfoHeader); aOutFormat.Assign(FBmpInfoHeader); aOutFormat.Channel:=aInFormat.Channel; aOutFormat.TimeStamp:=aInFormat.TimeStamp; aOutFormat.TimeKoeff:=aInFormat.TimeKoeff; aOutFormat.VideoReversedVertical:=true; //Декодер дает перевернутую картинку Include(aOutFormat.biFrameFlags,ffKeyFrame); end else begin inc(FConsequtiveErrors); SetLastError(AVC.GetErrorMessage(aDecodeResult)); if aDecodeResult<>FR_NO_PICTURE_DECOMPRESSED then TraceLine('Декодер вернул ошибку: '+AVC.GetErrorMessage(aDecodeResult)); end; finally //FVideoDecoder.Unlock; end; end; initialization MediaProceccorFactory.RegisterMediaProcessorImplementation(TMediaProcessor_ConvertorH264_Rgb_Impl); end.
unit Server.Connection; interface uses System.SysUtils, System.Classes, FireDAC.Comp.Client, //FDConnection FireDAC.Phys.FB, //DriverPhys do FireBird FireDAC.Stan.Def, //StanStorage SmartPoint; type TDriverFB = class(TFDPhysFBDriverLink) private constructor Create(Owner: TComponent);override; destructor Destroy;override; public property VendorLib; end; TConnectionData = class protected FDriverFB: TDriverFB; function GetDriverFB: TDriverFB; private FConnection : TFDConnection; procedure SetParams; public constructor Create; destructor Free; property Connection : TFDConnection read FConnection write FConnection; end; implementation Uses Server.Config; { TConnectionData } constructor TConnectionData.Create; begin if not Assigned(FConnection) then FConnection := TFDConnection.Create(nil); SetParams; end; destructor TConnectionData.Free; begin if Assigned(FDriverFB) then FDriverFB.Free; if Assigned(FConnection) then begin FConnection.Close; FConnection.Free; end; end; function TConnectionData.GetDriverFB: TDriverFB; begin if not Assigned(FDriverFB) then FDriverFB := TDriverFB.Create(nil); Result := FDriverFB; end; procedure TConnectionData.SetParams; begin TServerConfig.FileName := ExtractFilePath(ParamStr(0)) + 'Config.ini'; FConnection.DriverName := TServerConfig.DriverName; FConnection.Params.Values['Database'] := TServerConfig.Database; FConnection.Params.Values['User_Name'] := TServerConfig.UserName; FConnection.Params.Values['Password'] := TServerConfig.Password; FConnection.Params.Values['Server'] := TServerConfig.Server; FConnection.Params.Values['Port'] := IntToStr(TServerConfig.Port); end; { TDriverMySQL } constructor TDriverFB.Create(Owner: TComponent); begin inherited; end; destructor TDriverFB.Destroy; begin inherited; end; end.
unit Unit1; interface var G1: Int32; G2: Int32; G3: Int32; implementation procedure Test1; var i: Int32; begin G1 := 0; for i := 0 to 9 do G1 := G1 + 1; end; procedure Test2; const c = 100; begin G2 := 0; for var i := 0 to c - 1 do G2 := G2 + 1; end; procedure Test3; const c = 10; begin G3 := 0; for var i := 0 to c - 1 step 2 do begin G3 := G3 + 1; end; end; initialization Test1(); Test2(); Test3(); finalization Assert(G1 = 10); Assert(G2 = 100); Assert(G3 = 5); end.
unit fPrintList; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, fAutoSz, StdCtrls, ORCtrls, fConsult513Prt, VA508AccessibilityManager; type TfrmPrintList = class(TfrmAutoSz) lbIDParents: TORListBox; cmdOK: TButton; cmdCancel: TButton; lblListName: TLabel; procedure FormCreate(Sender: TObject); procedure cmdCancelClick(Sender: TObject); procedure cmdOKClick(Sender: TObject); private { Private declarations } FParentNode: string; public { Public declarations } function SelectParentFromList(ATree: TORTreeView; PageID: Integer): string; end; var frmPrintList: TfrmPrintList; HLDPageID: Integer; implementation {$R *.dfm} uses uTIU, rTIU, uConst, fNotes, fNotePrt, ORFn, fConsults, fDCSumm, fFrame; procedure TfrmPrintList.FormCreate(Sender: TObject); begin inherited; FParentNode := ''; end; procedure TfrmPrintList.cmdCancelClick(Sender: TObject); begin inherited; FParentNode := ''; Close; end; procedure TfrmPrintList.cmdOKClick(Sender: TObject); begin inherited; case HLDPageID of CT_NOTES: frmNotes.RequestMultiplePrint(Self); CT_CONSULTS: frmConsults.RequestMultiplePrint(Self); CT_DCSUMM: frmDCSumm.RequestMultiplePrint(Self); end; {case} FParentNode := lbIDParents.ItemID; Close; end; function TfrmPrintList.SelectParentFromList(ATree: TORTreeView; PageID: Integer): string; var frmPrintList: TfrmPrintList; i, AnImg: integer; x: string; tmpList: TStringList; //strObj: TStringList; begin HLDPageID := PageID; frmPrintList := TfrmPrintList.Create(Application); frmPrintList.Parent := Self; tmpList := TStringList.Create; try ResizeFormToFont(TForm(frmPrintList)); for i := 0 to ATree.Items.Count - 1 do begin AnImg := TORTreeNode(ATree.Items.Item[i]).ImageIndex; if AnImg in [IMG_SINGLE, IMG_PARENT,IMG_IDNOTE_SHUT, IMG_IDNOTE_OPEN, IMG_IDPAR_ADDENDA_SHUT, IMG_IDPAR_ADDENDA_OPEN] then begin x := TORTreeNode(ATree.Items.Item[i]).Stringdata; tmpList.Add(x); //strObj := TStringList.Create; //strObj.Insert(0,x); //tmpList.AddObject(x, strObj) // notes and dc/summs & Consults end; {if} end; {for} frmPrintList.lbIDParents.Sorted := FALSE; case PageID of CT_NOTES: begin SortByPiece(tmpList, U, 3); InvertStringList(tmpList); for i := 0 to tmpList.Count - 1 do begin x := tmpList[i]; tmpList[i] := Piece(x, U, 1) + U + (MakeNoteDisplayText(x)); end; frmPrintList.lblListName.Caption := 'Select Notes to be printed.'; end; CT_CONSULTS: begin SortByPiece(tmpList, U, 11); InvertStringList(tmpList); for i := 0 to tmpList.Count - 1 do begin x := tmpList[i]; tmpList[i] := Piece(x, U, 1) + U + (MakeConsultDisplayText(x)); end; frmPrintList.lblListName.Caption := 'Select Consults to be printed.'; end; CT_DCSUMM: begin SortByPiece(tmpList, U, 3); InvertStringList(tmpList); for i := 0 to tmpList.Count - 1 do begin x := tmpList[i]; tmpList[i] := Piece(x, U, 1) + U + (MakeNoteDisplayText(x)); end; frmPrintList.lblListName.Caption := 'Select Discharge Summaries to be printed.'; end; end; //case FastAssign(tmpList, frmPrintList.lbIDParents.Items); frmPrintList.ShowModal; Result := frmPrintList.FParentNode; finally tmpList.Free; frmPrintList.Release; end; end; end.
unit IdSNPP; interface uses Classes, IdException, IdGlobal, IdTCPConnection, IdMessage, IdComponent, IdTCPClient; { Simple Network Paging Protocol based on RFC 1861 Original Author: Mark Holmes I'll put the resource strings in later. } {Note that this only supports Level One SNPP} type TConnectionResult = (crCanPost, crNoPost, crAuthRequired, crTempUnavailable); TCheckResp = Record Code : SmallInt; Resp : String; end; TIdSNPP = class (TIdTCPClient) private function Pager(APagerId: String): Boolean; function SNPPMsg(AMsg: String): Boolean; public constructor Create(AOwner: TComponent); override; procedure Reset; procedure SendMessage(APagerId,AMsg: String); procedure Connect(const ATimeout: Integer = IdTimeoutDefault); override; procedure Disconnect; override; published property Port default 7777; end; EIdSNPPException = class(EIdException); EIdSNPPConnectionRefused = class (EIdProtocolReplyError); EIdSNPPProtocolError = class (EIdProtocolReplyError); EIdSNPPNoMultiLineMessages = class(EIdSNPPException); implementation uses IdResourceStrings; { TIdSNPP } constructor TIdSNPP.Create(AOwner: TComponent); begin inherited Create(AOwner); Port := 7777; end; procedure TIdSNPP.Connect(const ATimeout: Integer = IdTimeoutDefault); begin inherited Connect(ATimeout); try if GetResponse([]) = 220 then begin raise EIdSNPPConnectionRefused.CreateError(502, LastCmdResult.Text.Text); end; except Disconnect; Raise; end; end; procedure TIdSNPP.Disconnect; begin if Connected then begin SendCMD('QUIT'); end; inherited Disconnect; end; function TIdSNPP.Pager(APagerId: String): Boolean; begin Result := False; Writeln('PAGER ' + APagerID); {Do not Localize} if GetResponse([]) = 250 then begin Result := True end else begin DoStatus(hsStatusText, [LastCmdResult.Text[0]]); end; end; procedure TIdSNPP.Reset; begin Writeln('RESET'); {Do not Localize} end; procedure TIdSNPP.SendMessage(APagerId, AMsg : String); begin if (Pos(CR,AMsg)>0) or (Pos(LF,AMsg)>0) then begin EIdSNPPNoMultiLineMessages.Create(RSSNPPNoMultiLine); end; if (Length(APagerId) > 0) and (Length(AMsg) > 0) then begin if Pager(APagerID) then begin if SNPPMsg(AMsg) then begin WriteLn('SEND'); {Do not Localize} end; GetResponse([250]); end; end; end; function TIdSNPP.SNPPMsg(AMsg: String): Boolean; begin Result := False; Writeln('MESS ' + AMsg); {Do not Localize} if GetResponse([]) = 250 then begin Result := True end else begin DoStatus(hsStatusText, [LastCmdResult.Text.Text]); end; end; end.
unit uConfig; interface uses XMLIntf, XMLDoc, Classes; type TAppConfig = class (TObject) private fBackupFileCount: Integer; fBackupPath: String; fXMLFileName: String; fShortFileName: String; fAbsoluteBackupPath: String; fLoadedDoc: TXMLDocument; procedure SaveToXmlDoc(pDoc: TXMLDocument); function AreConfigurationsEqual(pN1, pN2: IXMLNode): Boolean; function AreNodesEqual(pN1, pN2: IXMLNode): Boolean; function AreNodesEqualByChildNode(pN1, pN2: IXMLNode; pChildNodeName: String): Boolean; procedure DebugLog(pMessage: String); public constructor Create(pOwner: TObject); destructor Destroy; override; procedure SaveToXml(pForceIfNotChanged: Boolean = false); procedure LoadFromXml; procedure SaveBackups(pDoc: TXMLDocument); function CheckBackupPath: boolean; property BackupFileCount: Integer read fBackupFileCount write fBackupFileCount; property BackupPath: String read fBackupPath write fBackupPath; property XMLFileName: String read fXMLFileName; property AbsoluteBackupPath: String read fAbsoluteBackupPath; end; implementation uses SysUtils, uGlobals, Forms, Windows, Dialogs, XmlDom; { TAppConfig } function IsDirectoryWriteable(const AName: string): Boolean; var FileName: String; H: THandle; begin FileName := IncludeTrailingPathDelimiter(AName) + 'chk.tmp'; H := CreateFile(PChar(FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_DELETE_ON_CLOSE, 0); Result := H <> INVALID_HANDLE_VALUE; if Result then CloseHandle(H); end; function TAppConfig.AreConfigurationsEqual(pN1, pN2: IXMLNode): Boolean; var I: Integer; lA1, lA2: IXMLNodeList; lN2: IXMLNode; lC1, lC2: Integer; begin Result := False; if (pN1 = nil) and (pN2 = nil) then begin Result := True; exit; end; if (pN1 = nil) or (pN2 = nil) then exit; // children lA1 := pN1.ChildNodes; lA2 := pN2.ChildNodes; lC1 := 0; lC2 := 0; if (lA1 <> nil) and (lA2 <> nil) then begin for I := 0 to lA1.Count - 1 do if lA1.Nodes[i].NodeName <> '#text' then begin Inc(lC1); lN2 := lA2.FindNode(lA1.Nodes[i].NodeName); if lN2 = nil then exit; if (UpperCase(lA1.Nodes[i].NodeName) = 'MACROS') or (UpperCase(lA1.Nodes[i].NodeName) = 'DEVICES') then begin if not AreNodesEqualByChildNode(lA1.Nodes[i], lN2, 'Name') then exit; end else if not AreNodesEqual(lA1.Nodes[i], lN2) then exit; end; for I := 0 to lA2.Count - 1 do if lA2.Nodes[i].NodeName <> '#text' then begin Inc(lC2); end; if (lC1 <> lC2) then begin DebugLog('Diff: Count children of ' + pN1.NodeName + ' (' + IntToStr(lC1) + ' <> ' + IntToStr(lC2) + ')'); end; end; Result := True; end; function TAppConfig.AreNodesEqual(pN1, pN2: IXMLNode): Boolean; var I: Integer; lA1, lA2: IXMLNodeList; lN2: IXMLNode; lC1, lC2: Integer; begin Result := False; lC1 := 0; lC2 := 0; if (pN1 = nil) and (pN2 = nil) then begin Result := True; exit; end; if (pN1 = nil) or (pN2 = nil) then exit; DebugLog('Comparing ' + pN1.LocalName + ' and ' + pN2.LocalName); // compare attribs lA1 := pN1.AttributeNodes; lA2 := pN2.AttributeNodes; if (lA1 <> nil) and (lA2 <> nil) then begin if lA1.Count <> lA2.Count then exit; for I := 0 to lA1.Count - 1 do if lA1.Nodes[I].Text <> lA2.Nodes[I].Text then Exit; end else if (lA1 <> nil) or (lA2 <> nil) then exit; // children lA1 := pN1.ChildNodes; lA2 := pN2.ChildNodes; if (lA1 <> nil) and (lA2 <> nil) then begin for I := 0 to lA1.Count - 1 do if lA1.Nodes[i].NodeName <> '#text' then begin Inc(lC1); lN2 := lA2.FindNode(lA1.Nodes[i].NodeName); if lN2 = nil then exit; if (lA1.Nodes[i].IsTextElement) and (lN2.IsTextElement) then begin if lA1.Nodes[I].Text <> lN2.Text then begin DebugLog('Diff: ' + lA1.Nodes[I].Text + ', ' + lN2.Text); Exit; end; end else if (lA1.Nodes[i].HasChildNodes) and (lN2.HasChildNodes) then begin Result := AreNodesEqual(lA1.Nodes[i], lN2); if (not Result) then exit; Result := False; end else exit; end; for I := 0 to lA2.Count - 1 do if lA2.Nodes[i].NodeName <> '#text' then begin Inc(lC2); end; if (lC1 <> lC2) then begin DebugLog('Diff: Count children of ' + pN1.NodeName + ' (' + IntToStr(lC1) + ' <> ' + IntToStr(lC2) + ')'); end; end else if (lA1 <> nil) or (lA2 <> nil) then exit; DebugLog('Comp: ' + pN1.NodeName + ' ' + pN2.NodeName + ' OK'); Result := True; end; function TAppConfig.AreNodesEqualByChildNode(pN1, pN2: IXMLNode; pChildNodeName: String): Boolean; var I, J: Integer; lA1, lA2, lA1s, lA2s: IXMLNodeList; lN1, lN2: IXMLNode; lC1, lC2: Integer; lNodeOK: Boolean; begin Result := False; lC1 := 0; lC2 := 0; if (pN1 = nil) and (pN2 = nil) then begin Result := True; exit; end; if (pN1 = nil) or (pN2 = nil) then exit; DebugLog('Comparing ' + pN1.LocalName + ' and ' + pN2.LocalName); // no need to compare attribs - not used in general parents // children lA1 := pN1.ChildNodes; lA2 := pN2.ChildNodes; if (lA1 <> nil) and (lA2 <> nil) then begin for I := 0 to lA1.Count - 1 do if lA1.Nodes[i].NodeName <> '#text' then begin Inc(lC1); // locate child content lA1s := lA1.Nodes[i].ChildNodes; if lA1s = nil then exit; lN1 := lA1s.FindNode(pChildNodeName); if lN1 = nil then exit; lNodeOK := False; // look for node with same name and same children content for J := 0 to lA2.Count - 1 do if lA2.Nodes[j].NodeName <> '#text' then begin if lA1.Nodes[i].NodeName = lA2.Nodes[j].NodeName then begin lA2s := lA2.Nodes[j].ChildNodes; if lA2s = nil then exit; lN2 := lA2s.FindNode(pChildNodeName); if lN2 = nil then exit; // now we have child node - supposed to be text node if (lN1.IsTextElement) and (lN2.IsTextElement) and (lN1.Text = lN2.Text) then begin // so they contain same child node (name), compare nodes lNodeOK := AreNodesEqual(lA1.Nodes[i], lA2.Nodes[j]); Break; end; end; end; if (not lNodeOK) then begin DebugLog('Diff on child compare: ' + pN1.NodeName + ' - ' + pChildNodeName + ' - ' + lN1.Text); exit; end; end; for I := 0 to lA2.Count - 1 do if lA2.Nodes[i].NodeName <> '#text' then begin Inc(lC2); end; if (lC1 <> lC2) then begin DebugLog('Diff: Count children of ' + pN1.NodeName + ' (' + IntToStr(lC1) + ' <> ' + IntToStr(lC2) + ')'); end; end; DebugLog('Comp: ' + pN1.NodeName + ' ' + pN2.NodeName + ' OK'); Result := True; end; function TAppConfig.CheckBackupPath: boolean; begin fBackupPath := Trim(fBackupPath); if ((Length(fBackupPath) > 1) and (fBackupPath[1] = '\')) or ((Length(fBackupPath) > 1) and (Copy(fBackupPath, 2, 2) = ':\')) then begin fAbsoluteBackupPath := fBackupPath; end else begin fAbsoluteBackupPath := ExtractFilePath(Application.ExeName)+'\'+fBackupPath; end; // check if exists and is writable Result := IsDirectoryWriteable(fAbsoluteBackupPath); end; constructor TAppConfig.Create(pOwner: TObject); var lDebugStr: String; begin fBackupFileCount := 0; fLoadedDoc := TXMLDocument.Create((pOwner as THDMGlobals).MainForm); fLoadedDoc.Options := [doNodeAutoIndent]; fLoadedDoc.Active := True; fBackupPath := 'backup'; fShortFileName := 'hidmacros'; if (ParamCount > 0) then begin lDebugStr := UpperCase(ParamStr(1)); if (Copy(lDebugStr, 1, 5) = 'DEBUG') then begin (pOwner as THDMGlobals).DebugGroups := Copy(lDebugStr, 7, 200); end else begin fShortFileName := Trim(ParamStr(1)); end; end; fXmlFileName := fShortFileName + '.xml'; end; procedure TAppConfig.DebugLog(pMessage: String); begin Glb.DebugLog(pMessage, 'XML'); end; destructor TAppConfig.Destroy; begin fLoadedDoc.Free; inherited; end; function ExtractNumberFromFileName(pFileName: String): Integer; var lPos: Integer; begin lPos := LastDelimiter('_', pFileName); Result := StrToInt(Copy(pFileName, lPos+1, Length(pFileName) - 4 - lPos)); end; function SortFilesByName(List: TStringList; Index1, Index2: Integer): Integer; begin Result := - ExtractNumberFromFileName(List[Index2]) + ExtractNumberFromFileName(List[Index1]); end; procedure TAppConfig.SaveBackups(pDoc: TXMLDocument); var lFiles: TStringList; lSR: TSearchRec; lNextNo: Integer; I: Integer; begin if (fBackupFileCount = 0) then Exit; lNextNo := 1; if (not CheckBackupPath) then begin DebugLog('Directory ' + fAbsoluteBackupPath + ' not writable, backup not stored'); exit; end; // get existing files lFiles := TStringList.Create; try if (FindFirst(fAbsoluteBackupPath + '\'+ fShortFileName + '_*.xml', faAnyFile and not faDirectory and not faHidden, lSR) = 0) then repeat lFiles.Add(lSR.Name) until FindNext(lSR) <> 0; SysUtils.FindClose(lSR); // sort them if lFiles.Count > 1 then lFiles.CustomSort(SortFilesByName); if lFiles.Count > 0 then lNextNo := ExtractNumberFromFileName(lFiles[lFiles.Count-1]) + 1; // delete old files for I := 0 to lFiles.Count - fBackupFileCount do SysUtils.DeleteFile(fAbsoluteBackupPath + '\'+lFiles[I]); finally lFiles.Free; end; // create new pDoc.SaveToFile(fAbsoluteBackupPath + '\'+ fShortFileName + '_' + IntToStr(lNextNo)+ '.xml'); end; procedure TAppConfig.SaveToXml(pForceIfNotChanged: Boolean = false); var fn : String; Xdoc, lTmp4Swap : TXMLDocument; lEquals: boolean; begin fn := ExtractFilePath(Application.ExeName)+'\'+fXmlFileName; Xdoc := TXMLDocument.Create(Glb.MainForm); try Xdoc.Options := [doNodeAutoIndent]; Xdoc.Active := True; SaveToXmlDoc(Xdoc); try lEquals := (fLoadedDoc = nil) or // when there was no xml - after install AreConfigurationsEqual(Xdoc.DocumentElement, fLoadedDoc.DocumentElement); except on EXMLDocError do begin lEquals := True; // no backup if previous file was kind of wrong pForceIfNotChanged := True; // but make sure current config is saved end; end; if (not lEquals) or pForceIfNotChanged then begin if (FileExists(fn)) then begin DebugLog('Deleting old XML file ' + fn); SysUtils.DeleteFile(fn); end; DebugLog('Saving to XML file ' + fn); Xdoc.SaveToFile(fn); end; if (not lEquals) then begin SaveBackups(Xdoc); end; // swap current xdoc and last loaded doc // as xdoc variable will be freed lTmp4Swap := fLoadedDoc; fLoadedDoc := Xdoc; Xdoc := lTmp4Swap; finally Xdoc.Free; end; end; procedure TAppConfig.SaveToXmlDoc(pDoc: TXMLDocument); var fn : String; RootNode, generalNode, aNode: IXMLNode; begin RootNode := pDoc.AddChild('Config'); generalNode := RootNode.AddChild('General'); Glb.MainForm.SaveToXml(RootNode, generalNode); // save my values aNode := generalNode.AddChild('BackupsCount'); aNode.Text := IntToStr(fBackupFileCount); aNode := generalNode.AddChild('BackupPath'); aNode.Text := fBackupPath; // save devices aNode := RootNode.AddChild('Devices'); Glb.HIDControl.SaveToXML(aNode); // save Map aNode := RootNode.AddChild('Map'); Glb.MapForm.SaveToXML(aNode); end; procedure TAppConfig.LoadFromXml; var RootNode, parentNode, aNode, devicesNode: IXMLNode; I, J, SysIDIndex, NameIndex:Integer; fn, tmpSysID, tmpName: String; lProcBegin, lProcEnd: String; begin // default values Glb.ScriptEngine.AllowGUI := False; Glb.ScriptEngine.ScriptTimeout := 10; fn := ExtractFilePath(Application.ExeName)+'\'+fXmlFileName; DebugLog('XML file name is ' + fn); if (not FileExists(fn)) then begin DebugLog('File ' + fn + 'does not exist.'); Exit; end; try fLoadedDoc.LoadFromFile(fn); fLoadedDoc.Active := True; RootNode := fLoadedDoc.DocumentElement.ChildNodes.First; if (RootNode = nil) then DebugLog('Can not parse XML ini file, no loading.'); parentNode := RootNode; while parentNode <> nil do begin if UpperCase(parentNode.NodeName) = 'GENERAL' then begin DebugLog('Loading General settings...'); aNode := parentNode.ChildNodes.First; while aNode <> nil do begin if UpperCase(aNode.NodeName) = 'BACKUPSCOUNT' then fBackupFileCount := StrToIntDef(aNode.Text, 0); if UpperCase(aNode.NodeName) = 'BACKUPPATH' then fBackupPath := aNode.Text; aNode := aNode.NextSibling; end; end; if UpperCase(parentNode.NodeName) = 'MAP' then begin DebugLog('Loading Map settings...'); Glb.MapForm.LoadFromXml(parentNode); end; if UpperCase(parentNode.NodeName) = 'DEVICES' then begin Glb.HIDControl.LoadFromXml(parentNode); end; parentNode := parentNode.NextSibling; end; except On E: EXMLDocError do begin ShowMessage(Format(Glb.MainForm.txt.Values['LoadErrorS'], [E.Message])); end; On E: EDOMParseError do begin ShowMessage(Format(Glb.MainForm.txt.Values['LoadErrorS'], [E.Message])); end; end; Glb.MainForm.LoadFromXml(RootNode); end; end.
unit BigWindowData; interface uses Windows, Classes, SysUtils, GMGlobals, ParamsForDiagram, ConfigXml, GMGenerics; type TBWNodeData = record UT1, UT2: LongWord; end; PBWNodeData = ^TBWNodeData; TBigWindow = class private FPFD: TParamForDrawList; FDiagramLenHrs: int; function ReadAppropriateDigitsAfterPoint(xml: IGMConfigConfigType; ID_Prm: int): int; public Caption: string; constructor Create(); destructor Destroy; override; property pfd: TParamForDrawList read FPFD; procedure LoadFromINI(xml: IGMConfigConfigType; xmlBw: IGMConfigBigwindowType); procedure DrawDiagram(); function AddValue(val: TValueFromBase; bArchive: bool): bool; property DiagramLenHrs: int read FDiagramLenHrs write FDiagramLenHrs; end; TBigWindows = class(TGMCollection<TBigWindow>) public function AddValue(val: TValueFromBase; bArchive: bool): bool; procedure Enlist(lst: TStrings); procedure RequestInitialDiagrams(Handle: Hwnd); procedure LoadFromINI(xml: IGMConfigConfigType); end; var BigWindowList: TBigWindows; implementation uses GMDBClasses; { TBigWindows } function TBigWindows.AddValue(val: TValueFromBase; bArchive: bool): bool; var i: int; begin Result := false; for i := 0 to Count - 1 do if Items[i].AddValue(val, bArchive) then Result := true; end; procedure TBigWindows.Enlist(lst: TStrings); var i: int; begin lst.Clear(); for i := 0 to Count - 1 do lst.AddObject(Items[i].Caption, TObject(i)); end; procedure TBigWindows.RequestInitialDiagrams(Handle: Hwnd); var i: int; begin for i := 0 to Count - 1 do Items[i].pfd.RequestInitialDiagrams(Handle, 1); end; procedure TBigWindows.LoadFromINI(xml: IGMConfigConfigType); var i: int; bw: TBigWindow; begin Clear(); for i := 0 to xml.Bigwindows.Count - 1 do begin bw := BigWindowList.Add(); bw.LoadFromINI(xml, xml.Bigwindows[i]); end; end; { TBigWindow } function TBigWindow.AddValue(val: TValueFromBase; bArchive: bool): bool; begin Result := pfd.AddValue(val, bArchive); end; constructor TBigWindow.Create(); begin inherited; FPFD := TParamForDrawList.Create(); end; destructor TBigWindow.Destroy; begin FPFD.Free(); inherited; end; procedure TBigWindow.DrawDiagram; var i: int; begin for i := 0 to pfd.Count - 1 do pfd.Params[i].DrawDiagram(int64(NowGM()) - FDiagramLenHrs * 3600, NowGM()) end; function TBigWindow.ReadAppropriateDigitsAfterPoint(xml: IGMConfigConfigType; ID_Prm: int): int; var i, j: int; begin Result := 0; for i := 0 to xml.Objects.Count - 1 do begin for j := 1 to xml.Objects[i].Channels.Count - 1 do // 0й(BAR) не нужен if xml.Objects[i].Channels[j].Id_prm = ID_Prm then begin Result := xml.Objects[i].Channels[j].Digits; Exit; end; end; end; procedure TBigWindow.LoadFromINI(xml: IGMConfigConfigType; xmlBw: IGMConfigBigwindowType); var i: int; p: TParamForDraw; begin Caption := xmlBw.Name; for i := 0 to xmlBw.Diagrams.Count - 1 do begin p := pfd.Add(); p.DiagramMin := xmlBw.Diagrams[i].Dmin; p.DiagramMax := xmlBw.Diagrams[i].Dmax; p.ColWidth := xmlBw.Diagrams[i].ColWidth; p.Title := xmlBw.Diagrams[i].Text; p.bDiagram := xmlBw.Diagrams[i].Diagram > 0; p.iDigitsAfterPoint := xmlBw.Diagrams[i].Precision + 1; p.prm := ParamOrNodeChannel(xmlBw.Diagrams[i].DataChnType, xmlBw.Diagrams[i].Id_prm); if (p.prm <> nil) and (p.iDigitsAfterPoint <= 0) then p.iDigitsAfterPoint := ReadAppropriateDigitsAfterPoint(xml, p.prm.ID_Prm); end; end; initialization BigWindowList := TBigWindows.Create(); finalization BigWindowList.Free(); end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC Data Adapter Layer API } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.DApt.Intf; interface uses System.SysUtils, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Column; type IFDDAptTableAdapter = interface; IFDDAptTableAdapters = interface; IFDDAptSchemaAdapter = interface; EFDDAptRowUpdateException = class; {-----------------------------------------------------------------------------} TFDDAptReconcileAction = (raSkip, raAbort, raMerge, raCorrect, raCancel, raRefresh); IFDDAptUpdateHandler = interface(IUnknown) ['{3E9B315B-F456-4175-A864-B2573C4A2301}'] procedure ReconcileRow(ARow: TFDDatSRow; var Action: TFDDAptReconcileAction); procedure UpdateRow(ARow: TFDDatSRow; ARequest: TFDUpdateRequest; AUpdRowOptions: TFDUpdateRowOptions; var AAction: TFDErrorAction); end; {-----------------------------------------------------------------------------} // DatSTable adapter. It maps SELECT command to DatSTable and back // to INSERT / UPDATE / DELETE commands. Major capabilities are: // - fetch data from SelectCommand into DatSTable // - post updates from DatSTable rows to database // - reconcile row post errors IFDDAptTableAdapter = interface(IUnknown) ['{3E9B315B-F456-4175-A864-B2573C4A2304}'] // private function GetSourceRecordSetID: Integer; procedure SetSourceRecordSetID(const AValue: Integer); function GetSourceRecordSetName: String; procedure SetSourceRecordSetName(const AValue: String); function GetUpdateTableName: String; procedure SetUpdateTableName(const AValue: String); function GetDatSTableName: String; procedure SetDatSTableName(const AValue: String); function GetDatSTable: TFDDatSTable; procedure SetDatSTable(AValue: TFDDatSTable); function GetColumnMappings: TFDDAptColumnMappings; function GetMetaInfoMergeMode: TFDPhysMetaInfoMergeMode; procedure SetMetaInfoMergeMode(const AValue: TFDPhysMetaInfoMergeMode); function GetTableMappings: IFDDAptTableAdapters; function GetDatSManager: TFDDatSManager; procedure SetDatSManager(AValue: TFDDatSManager); function GetSelectCommand: IFDPhysCommand; procedure SetSelectCommand(const ACmd: IFDPhysCommand); function GetInsertCommand: IFDPhysCommand; procedure SetInsertCommand(const ACmd: IFDPhysCommand); function GetUpdateCommand: IFDPhysCommand; procedure SetUpdateCommand(const ACmd: IFDPhysCommand); function GetDeleteCommand: IFDPhysCommand; procedure SetDeleteCommand(const ACmd: IFDPhysCommand); function GetLockCommand: IFDPhysCommand; procedure SetLockCommand(const ACmd: IFDPhysCommand); function GetUnLockCommand: IFDPhysCommand; procedure SetUnLockCommand(const ACmd: IFDPhysCommand); function GetFetchRowCommand: IFDPhysCommand; procedure SetFetchRowCommand(const ACmd: IFDPhysCommand); function GetTransaction: IFDPhysTransaction; procedure SetTransaction(const AValue: IFDPhysTransaction); function GetUpdateTransaction: IFDPhysTransaction; procedure SetUpdateTransaction(const AValue: IFDPhysTransaction); function GetOptions: IFDStanOptions; function GetErrorHandler: IFDStanErrorHandler; procedure SetErrorHandler(const AValue: IFDStanErrorHandler); function GetUpdateHandler: IFDDAptUpdateHandler; procedure SetUpdateHandler(const AValue: IFDDAptUpdateHandler); function GetObj: TObject; // public function Define: TFDDatSTable; procedure Fetch(AAll: Boolean = False; ABlocked: Boolean = False); overload; function Update(AMaxErrors: Integer = -1): Integer; overload; function Reconcile: Boolean; procedure Reset; procedure Fetch(ARow: TFDDatSRow; var AAction: TFDErrorAction; AColumn: Integer; ARowOptions: TFDPhysFillRowOptions); overload; procedure Update(ARow: TFDDatSRow; var AAction: TFDErrorAction; AUpdRowOptions: TFDUpdateRowOptions = []; AForceRequest: TFDActionRequest = arFromRow); overload; procedure Lock(ARow: TFDDatSRow; var AAction: TFDErrorAction; AUpdRowOptions: TFDUpdateRowOptions = []); procedure UnLock(ARow: TFDDatSRow; var AAction: TFDErrorAction; AUpdRowOptions: TFDUpdateRowOptions = []); procedure FetchGenerators(ARow: TFDDatSRow; var AAction: TFDErrorAction; AUpdRowOptions: TFDUpdateRowOptions = []); property SourceRecordSetID: Integer read GetSourceRecordSetID write SetSourceRecordSetID; property SourceRecordSetName: String read GetSourceRecordSetName write SetSourceRecordSetName; property UpdateTableName: String read GetUpdateTableName write SetUpdateTableName; property DatSTableName: String read GetDatSTableName write SetDatSTableName; property DatSTable: TFDDatSTable read GetDatSTable write SetDatSTable; property ColumnMappings: TFDDAptColumnMappings read GetColumnMappings; property MetaInfoMergeMode: TFDPhysMetaInfoMergeMode read GetMetaInfoMergeMode write SetMetaInfoMergeMode; property TableMappings: IFDDAptTableAdapters read GetTableMappings; property DatSManager: TFDDatSManager read GetDatSManager write SetDatSManager; property SelectCommand: IFDPhysCommand read GetSelectCommand write SetSelectCommand; property InsertCommand: IFDPhysCommand read GetInsertCommand write SetInsertCommand; property UpdateCommand: IFDPhysCommand read GetUpdateCommand write SetUpdateCommand; property DeleteCommand: IFDPhysCommand read GetDeleteCommand write SetDeleteCommand; property LockCommand: IFDPhysCommand read GetLockCommand write SetLockCommand; property UnLockCommand: IFDPhysCommand read GetUnLockCommand write SetUnLockCommand; property FetchRowCommand: IFDPhysCommand read GetFetchRowCommand write SetFetchRowCommand; property Options: IFDStanOptions read GetOptions; property Transaction: IFDPhysTransaction read GetTransaction write SetTransaction; property UpdateTransaction: IFDPhysTransaction read GetUpdateTransaction write SetUpdateTransaction; property ErrorHandler: IFDStanErrorHandler read GetErrorHandler write SetErrorHandler; property UpdateHandler: IFDDAptUpdateHandler read GetUpdateHandler write SetUpdateHandler; end; IFDDAptTableAdapters = interface(IUnknown) ['{3E9B315B-F456-4175-A864-B2573C4A2305}'] // private function GetItems(AIndex: Integer): IFDDAptTableAdapter; function GetCount: Integer; // public function Lookup(const ATable: TFDPhysMappingName): IFDDAptTableAdapter; function Add(const ASourceRecordSetName: String = ''; const ADatSTableName: String = ''; const AUpdateTableName: String = ''): IFDDAptTableAdapter; overload; procedure Add(const AAdapter: IFDDAptTableAdapter); overload; procedure Remove(const ATable: TFDPhysMappingName); overload; procedure Remove(const AAdapter: IFDDAptTableAdapter); overload; property Items[AIndex: Integer]: IFDDAptTableAdapter read GetItems; property Count: Integer read GetCount; end; {-----------------------------------------------------------------------------} // DatSManager adapter. It maps multiple result sets to IFDDAptTableAdapter's. // Major capabilities are: // - manage collection of IFDDAptTableAdapter // - manage updates posting from several IFDDAptTableAdapter's to database // - manage row post errors reconciling for several IFDDAptTableAdapter's IFDDAptSchemaAdapter = interface(IUnknown) ['{3E9B315B-F456-4175-A864-B2573C4A2306}'] // private function GetErrorHandler: IFDStanErrorHandler; procedure SetErrorHandler(const AValue: IFDStanErrorHandler); function GetDatSManager: TFDDatSManager; procedure SetDatSManager(AValue: TFDDatSManager); function GetTableAdapters: IFDDAptTableAdapters; function GetUpdateHandler: IFDDAptUpdateHandler; procedure SetUpdateHandler(const AValue: IFDDAptUpdateHandler); function GetTransaction: IFDPhysTransaction; procedure SetTransaction(const AValue: IFDPhysTransaction); function GetUpdateTransaction: IFDPhysTransaction; procedure SetUpdateTransaction(const AValue: IFDPhysTransaction); function GetOptions: IFDStanOptions; // public function Update(AMaxErrors: Integer = -1): Integer; function Reconcile: Boolean; property DatSManager: TFDDatSManager read GetDatSManager write SetDatSManager; property TableAdapters: IFDDAptTableAdapters read GetTableAdapters; property Options: IFDStanOptions read GetOptions; property Transaction: IFDPhysTransaction read GetTransaction write SetTransaction; property UpdateTransaction: IFDPhysTransaction read GetUpdateTransaction write SetUpdateTransaction; property ErrorHandler: IFDStanErrorHandler read GetErrorHandler write SetErrorHandler; property UpdateHandler: IFDDAptUpdateHandler read GetUpdateHandler write SetUpdateHandler; end; {-----------------------------------------------------------------------------} EFDDAptRowUpdateException = class(EFDException) private FAction: TFDErrorAction; FRequest: TFDUpdateRequest; FRow: TFDDatSRow; FException: Exception; public constructor Create(ARequest: TFDUpdateRequest; ARow: TFDDatSRow; AAction: TFDErrorAction; AException: Exception); overload; property Exception: Exception read FException; property Request: TFDUpdateRequest read FRequest; property Row: TFDDatSRow read FRow; property Action: TFDErrorAction read FAction write FAction; end; implementation {-------------------------------------------------------------------------------} { EFDDAptRowUpdateException } {-------------------------------------------------------------------------------} constructor EFDDAptRowUpdateException.Create(ARequest: TFDUpdateRequest; ARow: TFDDatSRow; AAction: TFDErrorAction; AException: Exception); begin inherited Create(0, ''); FRequest := ARequest; FRow := ARow; FAction := AAction; FException := AException; end; end.
(************************************************************************) (* *) (* Optimize- *) (* *) (* Randall L. Hyde *) (* 12/20/95 *) (* For use with "The Art of Assembly Language Programming." *) (* Copyright 1995, All Rights Reserved. *) (* *) (* This program lets the user enter a logic equation. The program will *) (* convert the logic equation to a truth table and its canonical sum of *) (* minterms form. The program will then optimize the equation (to pro- *) (* duce a minimal number of terms) using the carnot map method. *) (* *) (************************************************************************) unit Optimize; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Aboutu, ExtCtrls; type TEqnOptimize = class(TForm) PrintBtn: TButton; { Buttons appearing on the form } AboutBtn: TButton; ExitBtn: TButton; OptimizeBtn: TButton; CanonicalPanel: TGroupBox; OptimizedPanel: TGroupBox; PrintDialog: TPrintDialog; LogEqn: TEdit; {Logic equation input box and label } LogEqnLbl: TLabel; Eqn1: TLabel; { Strings that hold the canonical form } Eqn2: TLabel; Eqn3: TLabel; { Strings that hold the optimized form } Eqn4: TLabel; dc00: TLabel; { Labels around the truth map } dc01: TLabel; dc11: TLabel; dc10: TLabel; ba00: TLabel; ba01: TLabel; ba11: TLabel; ba10: TLabel; tt00: TPanel; { Rectangles in the truth map } tt01: TPanel; tt02: TPanel; tt03: TPanel; tt10: TPanel; tt11: TPanel; tt12: TPanel; tt13: TPanel; tt20: TPanel; tt21: TPanel; tt22: TPanel; tt23: TPanel; tt30: TPanel; tt31: TPanel; tt32: TPanel; tt33: TPanel; StepBtn: TButton; procedure PrintBtnClick(Sender: TObject); procedure ExitBtnClick(Sender: TObject); procedure AboutBtnClick(Sender: TObject); procedure LogEqnChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure OptimizeBtnClick(Sender: TObject); procedure StepBtnClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var EqnOptimize: TEqnOptimize; implementation { Set constants for the optimization operation. These sets group the } { cells in the truth map that combine to form simpler terms. } type TblSet = set of 0..15; const { If the truth table is equal to the "Full" set, then we have } { the logic function "F=1". } Full = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; { The TermSets list is a list of sets corresponding to the } { cells in the truth map that contain all ones for the terms } { that we can optimize away. } TermSets : array[0..79] of TblSet = ( { Terms containing a single variable, e.g., A, A', B, } { B', and so on. } [0,1,2,3,4,5,6,7], [4,5,6,7,8,9,10,11], [8,9,10,11,12,13,14,15], [12,13,14,15,0,1,2,3], [0,1,4,5,8,9,12,13], [1,2,5,6,9,10,13,14], [2,3,6,7,10,11,14,15], [3,0,7,4,11,8,15,12], { Terms containing two variables, e.g., AB, AB', A'B, } { and so on. This first set of eight values corres- } { ponds to the groups of four vertical or horizontal } { values. The next group of 16 sets corresponds to the } { groups of four values that form a 2x2 square in the } { truth map. } [0,1,2,3], [4,5,6,7], [8,9,10,11], [12,13,14,15], [0,4,8,12], [1,5,9,13], [2,6,10,14], [3,7,11,15], [0,1,4,5], [1,2,5,6], [2,3,6,7], [3,0,7,4], [4,5,8,9], [5,6,9,10], [6,7,10,11], [7,4,11,8], [8,9,12,13], [9,10,13,14], [10,11,14,15], [11,8,15,12], [12,13,0,1], [13,14,1,2], [14,15,2,3], [15,12,3,0], { Terms containing three variables, e.g., ABC, ABC', } { and so on. } [0,1], [1,2], [2,3], [3,0], [4,5], [5,6], [6,7], [7,4], [8,9], [9,10], [10,11], [11,8], [12,13], [13,14], [14,15], [15,12], [0,4], [4,8], [8,12], [12,0], [1,5], [5,9], [9,13], [13,1], [2,6], [6,10], [10,14], [14,2], [3,7], [7,11], [11,15], [15,3], { Minterms- Those terms containing four variables. } [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15] ); { Here are the corresponding strings we output for the patterns } { above. } TermStrs: array [0..79] of string[8] = ('D''', 'C', 'D', 'C''', 'B''', 'A', 'B', 'A''', 'D''C''', 'D''C', 'DC', 'DC''', 'B''A''', 'B''A', 'BA', 'BA''', 'D''B''', 'D''A', 'D''B', 'D''A''', 'CB''', 'CA', 'CB', 'CA''', 'DB''', 'DA', 'DB', 'DA''', 'C''B''', 'C''A', 'C''B', 'C''A''', 'D''C''B''', 'D''C''A', 'D''C''B', 'D''C''A''', 'D''CB''', 'D''CA', 'D''CB', 'D''CA''', 'DCB''', 'DCA', 'DCB', 'DCA''', 'DC''B''', 'DC''A', 'DC''B', 'DC''A''', 'B''A''D''', 'B''A''C', 'B''A''D', 'B''A''C''', 'B''AD''', 'B''AC', 'B''AD', 'B''AC''', 'BAD''', 'BAC', 'BAD', 'BAC''', 'BA''D''', 'BA''C', 'BA''D', 'BA''C''', 'D''C''B''A''','D''C''B''A', 'D''C''BA', 'D''C''BA''', 'D''CB''A''', 'D''CB''A', 'DC''BA', 'DC''BA''', 'DCB''A''', 'DCB''A', 'DCBA', 'DCBA''', 'DC''B''A''', 'DC''B''A', 'DC''BA', 'DC''BA''' ); { Transpose converts truth table indicies into truth map index- } { es. In reality, this converts binary numbers to a gray code. } Transpose : array [0..15] of integer = (0, 1, 3, 2, 4, 5, 7, 6, 12,13,15,14, 8, 9, 11, 10); var { Global, static, variables that the iterator uses to step } { through an optimization. } IterIndex: integer; FirstStep: boolean; StepSet, StepLeft, LastSet :TblSet; { The following array provides convenient access to the truth map } tt: array[0..1,0..1,0..1,0..1] of TPanel; {$R *.DFM} { ApndStr- item contains '0' or '1' -- the character in the} { current truth table cell. theStr is a string } { of characters to append to the equation if item } { is equal to '1'. } procedure ApndStr(item:char; const theStr:string; var Eqn1, Eqn2:TLabel); begin { To make everything fit on our form, we have to break } { the equation up into two lines. If the first line } { hits 66 characters, append the characters to the end } { of the second string. } if (length(eqn1.Caption) < 66) then begin { If we are appending to the end of EQN1, we have to } { check to see if the string's length is zero. If } { not, then we need to stick ' + ' between the } { existing string and the string we are appending. } { If the string length is zero, this is the first } { minterm so we don't prepend the ' + '. } if (item = '1') then if (length(eqn1.Caption) = 0) then eqn1.Caption := theStr else eqn1.Caption := eqn1.Caption + ' + ' + theStr; end else if (item = '1') then eqn2.Caption := eqn2.Caption + ' + ' + theStr; end; (* ComputeEqn- Computes the logic equation string from the current *) (* truth table entries. *) procedure ComputeEqn; begin with EqnOptimize do begin eqn1.Caption := ''; eqn2.Caption := ''; { Build the logic equation from all the squares } { in the truth table. } ApndStr(tt00.Caption[1],'D''C''B''A''',Eqn1, Eqn2); ApndStr(tt01.Caption[1],'D''C''B''A',Eqn1, Eqn2); ApndStr(tt02.Caption[1], 'D''C''BA',Eqn1, Eqn2); ApndStr(tt03.Caption[1], 'D''C''BA''',Eqn1, Eqn2); ApndStr(tt10.Caption[1],'D''CB''A''',Eqn1, Eqn2); ApndStr(tt11.Caption[1],'D''CB''A',Eqn1, Eqn2); ApndStr(tt12.Caption[1], 'D''CBA',Eqn1, Eqn2); ApndStr(tt13.Caption[1], 'D''CBA''',Eqn1, Eqn2); ApndStr(tt20.Caption[1],'DCB''A''',Eqn1, Eqn2); ApndStr(tt21.Caption[1],'DCB''A',Eqn1, Eqn2); ApndStr(tt22.Caption[1], 'DCBA',Eqn1, Eqn2); ApndStr(tt23.Caption[1], 'DCBA''',Eqn1, Eqn2); ApndStr(tt30.Caption[1],'DC''B''A''',Eqn1, Eqn2); ApndStr(tt31.Caption[1],'DC''B''A',Eqn1, Eqn2); ApndStr(tt32.Caption[1], 'DC''BA',Eqn1, Eqn2); ApndStr(tt33.Caption[1], 'DC''BA''',Eqn1, Eqn2); { If after all the above the string is empty, then we've got a } { truth table that contains all zeros. Handle that special } { case down here. } if (length(eqn1.Caption) = 0) then eqn1.Caption := '0'; Eqn1.Caption := 'F= ' + Eqn1.Caption; end; end; procedure RestoreMap; var a,b,c,d:integer; begin { Restore the colors on the truth map. } for d := 0 to 1 do for c := 0 to 1 do for b := 0 to 1 do for a := 0 to 1 do begin tt[d,c,b,a].Color := clBtnFace; end; end; { InitIter-Initializes the iterator for the first optimization step. } { This code enables the step button, sets all the truth table } { squares to gray, and sets up the global variables for the } { very first optimization operation. } procedure InitIter; var d,c,b,a:integer; begin with EqnOptimize do begin { Initialize global variables. } StepBtn.Enabled := true; IterIndex := 0; LastSet := []; { Restore the colors on the truth map. } RestoreMap; { Compute the set of values in the truth map } Eqn3.Caption := ''; Eqn4.Caption := ''; IterIndex := 0; StepSet := []; for d := 0 to 1 do for c := 0 to 1 do for b := 0 to 1 do for a := 0 to 1 do if (tt[d,c,b,a].Caption = '1') then StepSet := StepSet + [ ((b*2+a) xor b) + ((d*2+c) xor d)*4 ]; StepLeft := StepSet; { Check for two special cases: F=1 and F=0. The optimization } { algorithm cannot handle F=0 and this seems like the most } { appropriate place to handle F=1. So handle these two special } { cases here. } if (StepSet = Full) then begin Eqn3.Caption := 'F = 1'; StepSet := []; end else if (StepSet = []) then Eqn3.Caption := 'F = 0'; end; { Prevent a call to this routine the next time the user presses } { the "Step" button. } FirstStep := false; end; { StepBtnClick- This event does a single optimization operation. Each } { time the user presses the "Step" button, this code does a single } { optimization operation; that is, it locates a single unprocessed } { group of ones in the truth map and optimizes them to their appropri- } { ate term. It highlights the optimized group so the user can easily } { following the optimization process. This program must call InitIter } { prior to the first call of this routine. In general, that call } { occurs in the event handler for the "Optimize" button. } procedure TEqnOptimize.StepBtnClick(Sender: TObject); var a,b,c,d, i:integer; begin { On the first call to this event handler (after the user presses } { the "Optimize" button), we need to initialize the iterator. The } { FirstStep flag determines whether this is the first call after } { the user presses optimize. } if (FirstStep) then InitIter; with EqnOptimize do begin { The user actually has to press the "Step" button twice for } { each optimization step. On the second press, the following } { code turns the squares processed on the previous depression } { to dark green. This helps visually convey the process to } { the user. } if (LastSet <> []) then begin for i := 0 to 15 do if (Transpose[i] in LastSet) then tt[i shr 3, (i shr 2) and 1, (i shr 1) and 1, i and 1].Color := clgreen; LastSet := []; end { The following code executes on the first press of each pair } { of "Step" button depressions. It checks to see if there is } { any work left to do and if so, it does exactly one optimiza- } { tion step. } else if (StepLeft <> []) then begin { IterIndex should always be less than 80, this is just } { a sanity check. } while (IterIndex < 80) do begin { If the current set of unprocessed squares } { matches one of the patterns we need to process} { then add the appropriate term to our logic } { equation. } if ((TermSets[IterIndex] <= StepSet) and ((TermSets[IterIndex] * StepLeft) <> [])) then begin ApndStr('1',TermStrs[IterIndex],Eqn3,Eqn4); { On the first step, we need to prepend } { the string "F = " to our logic eqn. } { The following if statement handles } { this chore. } if (Eqn3.Caption[1] <> 'F') then Eqn3.Caption := 'F = ' + Eqn3.Caption; { Remove the group we just processed } { from the truth map cells we've still } { got to process. } StepLeft := StepLeft - TermSets[IterIndex]; { Turn the cells we just processed to } { a bright, light, blue color (aqua). } { This lets the user see which cells } { correspond to the term we just ap- } { pended to the end of the equation. } for i := 0 to 15 do if (Transpose[i] in TermSets[IterIndex]) then tt[i shr 3, (i shr 2) and 1, (i shr 1) and 1, i and 1].Color := claqua; { Save this group of cells so we can } { turn them dark green on the next call } { to this routine. } LastSet := TermSets[IterIndex]; break; end; inc(IterIndex); end; end { After the last valid depression of the "Step" button, clear } { the truth map and disable the "Step" button. } else begin RestoreMap; StepBtn.Enabled := false; end; end; end; { OptEqn- This routine optimizes a boolean expression. This code is } { roughly equivalent to the "Step" event handler above except it gener- } { ates the optimized equation in a single call rather than in several } { distinct calls. } procedure OptEqn; var a,b,c,d, i :integer; TTSet, TLeft :TblSet; begin with EqnOptimize do begin { Generate the set of minterms we need to process. } TTSet := []; for d := 0 to 1 do for c := 0 to 1 do for b := 0 to 1 do for a := 0 to 1 do if (tt[d,c,b,a].Caption = '1') then TTSet := TTSet + [ ((b*2+a) xor b) + ((d*2+c) xor d)*4 ]; { Special cases for F=1 and F=0 } if (TTSet = Full) then begin Eqn3.Caption := 'F = 1'; Eqn4.Caption := ''; end else if (TTSet = []) then begin Eqn3.Caption := 'F = 0'; Eqn4.Caption := ''; end { The following code handles all other equations. It steps } { through each of the possible patterns and if it finds a } { match it will add its corresponding term to the end of the } { optimized logic equation. } else begin TLeft := TTSet; Eqn3.Caption := ''; Eqn4.Caption := ''; for i := 0 to 79 do begin if ((TermSets [i] <= TTSet) and ((TermSets [i] * TLeft) <> [])) then begin ApndStr('1',TermStrs[i],Eqn3,Eqn4); TLeft := TLeft - TermSets[i]; end; end; end; Eqn3.Caption := 'F = ' + Eqn3.Caption; { Now that the user has pressed the optimize button, enable } { the "Step" button so they can single step through the opti- } { mization operation. } FirstStep := true; StepBtn.Enabled := true; end; end; { The following event handles "Print" button depressions. } procedure TEqnOptimize.PrintBtnClick(Sender: TObject); begin if (PrintDialog.Execute) then EqnOptimize.Print; end; { The following event handles "Exit" button depressions. } procedure TEqnOptimize.ExitBtnClick(Sender: TObject); begin Halt; end; { The following event handles "About" button depressions. } procedure TEqnOptimize.AboutBtnClick(Sender: TObject); begin AboutBox.Show; end; { Whenever the user changes the logic equation, we need to } { disable the step button. The following event does just that } { as well as making the "Optimize" button the default operation } { when the user presses the "Enter" key. } procedure TEqnOptimize.LogEqnChange(Sender: TObject); begin OptimizeBtn.Default := true; RestoreMap; StepBtn.Enabled := false; end; { Whenever the system starts up, the following procedure does } { some one-time initialization. } procedure TEqnOptimize.FormCreate(Sender: TObject); begin { Initialize the tt array so we can use to to access } { the Truth Map as a two-dimensional array. } tt[0,0,0,0] := tt00; tt[0,0,0,1] := tt01; tt[0,0,1,1] := tt02; tt[0,0,1,0] := tt03; tt[0,1,0,0] := tt10; tt[0,1,0,1] := tt11; tt[0,1,1,1] := tt12; tt[0,1,1,0] := tt13; tt[1,0,0,0] := tt30; tt[1,0,0,1] := tt31; tt[1,0,1,1] := tt32; tt[1,0,1,0] := tt33; tt[1,1,0,0] := tt20; tt[1,1,0,1] := tt21; tt[1,1,1,1] := tt22; tt[1,1,1,0] := tt23; end; { Whenever the user presses the optimize button, the following } { procedure parses the input logic equation, generates a truth } { map for it, and then generates the canonical and optimized } { equations. } procedure TEqnOptimize.OptimizeBtnClick(Sender: TObject); var CurChar:integer; Equation:string; { Parse- Parses the "Equation" string and evaluates it. } { Returns the equation's value if legal expression, returns } { -1 if the equation is syntactically incorrect. } { } { Grammar: } { S -> X + S | X } { X -> YX | Y } { Y -> Y' | Z } { Z -> a | b | c | d | ( S ) } function parse(D, C, B, A:integer):integer; function X(D,C,B,A:integer):integer; function Y(D,C,B,A:integer):integer; function Z(D,C,B,A:integer):integer; begin case (Equation[CurChar]) of '(': begin CurChar := CurChar + 1; Result := parse(D,C,B,A); if (Equation[CurChar] <> ')') then Result := -1 else CurChar := CurChar + 1; end; 'a': begin CurChar := CurChar + 1; Result := A; end; 'b': begin CurChar := CurChar + 1; Result := B; end; 'c': begin CurChar := CurChar + 1; Result := C; end; 'd': begin CurChar := CurChar + 1; Result := D; end; '0': begin CurChar := CurChar + 1; Result := 0; end; '1': begin CurChar := CurChar + 1; Result := 1; end; else Result := -1; end; end; begin {Y} { Note: This particular operation is left recursive } { and would require considerable grammar transform- } { ation to repair. However, a simple trick is to } { note that the result would have tail recursion } { which we can solve iteratively rather than recur- } { sively. Hence the while loop in the following } { code. } Result := Z(D,C,B,A); while (Result <> -1) and (Equation[CurChar] = '''') do begin Result := Result xor 1; CurChar := CurChar + 1; end; end; begin {X} Result := Y(D,C,B,A); if (Result <> -1) and (Equation[CurChar] in ['a'..'d', '0', '1', '(']) then Result := Result AND X(D,C,B,A); end; begin Result := X(D,C,B,A); if (Result <> -1) and (Equation[CurChar] = '+') then begin CurChar := CurChar + 1; Result := Result OR parse(D, C, B, A); end; end; var a, b, c, d:integer; dest:integer; i:integer; begin {ComputeBtnClick} Equation := LowerCase(LogEqn.Text) + chr(0); { Remove any spaces present in the string } dest := 1; for i := 1 to length(Equation) do if (Equation[i] <> ' ') then begin Equation[dest] := Equation[i]; dest := dest + 1; end; { Okay, see if this string is syntactically legal. } CurChar := 1; {Start at position 1 in string } if (Parse(0,0,0,0) <> -1) then if (Equation[CurChar] = chr(0)) then begin { Compute the values for each of the squares in } { the truth table. } for d := 0 to 1 do for c := 0 to 1 do for b := 0 to 1 do for a := 0 to 1 do begin CurChar := 1; if (parse(d,c,b,a) = 0) then tt[d,c,b,a].Caption := '0' else tt[d,c,b,a].Caption := '1'; end; ComputeEqn; OptEqn; LogEqn.Color := clWindow; RestoreMap; end else LogEqn.Color := clRed else LogEqn.Color := clRed; end; end.
unit ProgramVersion; interface function GetFileVersion(AFile: string): string; implementation uses Windows, SysUtils; function GetFileVersion(AFile: string): string; type PTranslate = ^TTranslate; TTranslate = record wLanguage: WORD; wCodePage: WORD; end; var len: Cardinal; Zero: Cardinal; lpData: array of byte; lpTranslate: PTranslate; strValPath: string; pFileVersion: pchar; begin result := ''; if Pos('{FB82C789-CAB9-4016-BBE5-9089DBADDD5E}', AFile) > 0 then begin result := '{FB82C789-CAB9-4016-BBE5-9089DBADDD5E}'; exit; end; try len := GetFileVersionInfoSize(pchar(AFile), Zero); if len <= 0 then exit; SetLength(lpData, len); if not GetFileVersionInfo(pchar(AFile), Zero, len, @lpData[0]) then exit; if not VerQueryValue(@lpData[0], '\VarFileInfo\Translation', Pointer(lpTranslate), len) then exit; strValPath := Format('\StringFileInfo\%.4x%.4x\FileVersion', [lpTranslate.wLanguage, lpTranslate.wCodePage]); if not VerQueryValue(@lpData[0], pchar(strValPath), Pointer(pFileVersion), len) then exit; result := pFileVersion; except end; end; end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 1024,0,0} { by Behdad Esfahbod Algorithmic Problems Book August '1999 Problem 6 O(N) Dynamic Method } program Soldiers; const MaxN = 200; var N : Integer; S : array [1 .. MaxN] of Boolean; D : array [0 .. MaxN] of Integer; I, L, LNum : Integer; Ch : Char; F : Text; begin Assign(F, 'input.txt'); Reset(F); Readln(F, N); for I := 1 to N do begin Read(F, Ch); if UpCase(Ch) = 'L' then S[I] := True else S[I] := False; end; Close(F); L := 0; D[0] := 0; for I := 1 to N do if S[I] then begin if D[L] + L < I - 1 then D[I] := 0 else D[I] := D[L] - I + L + 2; Inc(LNum); L := I; end; Assign(F, 'output.txt'); ReWrite(F); Writeln(F, 'Number of moves is equal to ', D[L] + L - LNum, '.'); Close(F); end.
unit TobyPascal; interface uses Classes, SysUtils, math, Windows; type TobyOnloadCB = procedure (isolate: Pointer); cdecl; TobyOnunloadCB = procedure (isolate: Pointer; exitCode: integer); cdecl; TobyHostcallCB = function (name, value: PAnsiChar):PAnsiChar; cdecl; TToby = class private started : boolean; H: HINST; constructor Init; public onLoad : TobyOnloadCB; onUnload : TobyOnunloadCB; onHostCall : TobyHostcallCB; InputPipeRead : THandle; InputPipeWrite : THandle; OutputPipeRead : THandle; OutputPipeWrite : THandle; ErrorPipeRead : THandle; ErrorPipeWrite : THandle; function start(processName, userScript: PAnsiChar) : boolean; function run(source: PAnsiChar) : PAnsiChar; procedure emit(name, value: PAnsiChar); class function Create: TToby; end; implementation var Singleton : TToby = nil; security : TSecurityAttributes; tobyInit:procedure (processName, userScript: PAnsiChar; tobyOnLoad: TobyOnloadCB; tobyOnUnload: TobyOnunloadCB; tobyHostCall: TobyHostcallCB); cdecl; tobyJSCompile:function (source, dest: PAnsiChar; n: integer):integer; cdecl; tobyJSCall:function (name, value, dest: PAnsiChar; n: integer):integer; cdecl; tobyJSEmit: function(name, value: PAnsiChar):integer; cdecl; procedure _OnLoad(isolate: Pointer); cdecl; begin //writeln(':: default tobyOnLoad called'); end; procedure _OnUnload(isolate: Pointer; exitCode: integer); cdecl; begin //writeln(':: default _OnUnload called'); end; function _OnHostCall(key,value: PAnsiChar):PAnsiChar; cdecl; begin //writeln(':: default tobyHostCall called. ', key, ' : ',value); exit(''); end; constructor TToby.Init; var stdout: THandle; begin // in case of 'git bash'(mingw) in windows stdout := GetStdHandle(Std_Output_Handle); Win32Check(stdout <> Invalid_Handle_Value); if (stdout = 0) then begin With security do begin nlength := SizeOf(TSecurityAttributes) ; binherithandle := true; lpsecuritydescriptor := nil; end; // FIXME : check returns CreatePipe(InputPipeRead, InputPipeWrite, @security, 0); CreatePipe(OutputPipeRead,OutputPipeWrite, @security, 0); CreatePipe(ErrorPipeRead, ErrorPipeWrite, @security, 0); SetStdHandle(Std_Input_Handle, InputPipeRead); SetStdHandle(Std_Output_Handle, OutputPipeWrite); SetStdHandle(Std_Error_Handle, ErrorPipeWrite); end; // dynamically load the dll. H := LoadLibrary('tobynode.dll'); if H<=0 then begin raise Exception.Create('tobynode.dll error!'); exit; end; @tobyInit := GetProcAddress(H, Pchar('tobyInit')); @tobyJSCompile := GetProcAddress(H, Pchar('tobyJSCompile')); @tobyJSCall := GetProcAddress(H, Pchar('tobyJSCall')); @tobyJSEmit := GetProcAddress(H, Pchar('tobyJSEmit')); started := false; // set default. onLoad := @_OnLoad; onUnload := @_OnUnload; onHostCall := @_OnHostCall; inherited Create; end; class function TToby.Create: TToby; begin if Singleton = nil then Singleton := TToby.Init; Result := Singleton; end; function TToby.start(processName, userScript: PAnsiChar) : boolean; begin if started = false then begin started := true; tobyInit(processName, userScript, onLoad, onUnload, onHostCall); exit(true); end; exit(false); end; procedure TToby.emit(name, value: PAnsiChar); begin tobyJSEmit(name, value); end; function TToby.run(source: PAnsiChar) : PAnsiChar; var dest: Array[0..1024] of AnsiChar; ret: integer; begin ret := tobyJSCompile(source, dest, Length(dest)); if (ret < 0) then writeln('** Error ', ret, ' ', dest); exit(dest); end; end.
{ Демонстрация: } { (1) операций, нестрогих по второму аргументу } { (отложенных вычислений); } { (2) энергичных вычислений } { --------------------------------------------- } PROGRAM Primer_1; Uses CRT; var x: Real; y: Integer; BEGIN x:=0; y:=1; { ------------------------------ } { Простые энергичные вычисления } { ------------------------------ } WriteLn('(1) ',TRUE OR (x=1/0.001)); if y>0 then WriteLn ('(2) ',y) else begin x:=1/0.001; WriteLn (x) end; Repeat until KeyPressed END.
unit adot.Collections.Rings; interface { TRingClass<T> } uses adot.Types, adot.Collections.Types, adot.Collections.Vectors, System.SysUtils, System.Generics.Collections, System.Generics.Defaults; type { Cyclic/circular buffer based on array. Add/delete items to head/tail. } TRingClass<T> = class(TEnumerableExt<T>) protected { FValues.Items is inner array, Items is property to access elements of the ring by index } FValues: TVector<T>; FHead: integer; FCount: integer; FOwnsValues: Boolean; function GetItemFromHead(n: integer): T; procedure SetItemFromHead(n: integer; const Value: T); function GetItemFromTail(n: integer): T; procedure SetItemFromTail(n: integer; const Value: T); function GetCapacity: integer; procedure SetCapacity(ANewCapacity: integer); function GetHead: T; procedure SetHead(const Value: T); function GetTail: T; procedure SetTail(const Value: T); function GetEmpty: boolean; procedure SetOwnsValues(const Value: Boolean); function DoGetEnumerator: TEnumerator<T>; override; function GetIsFull: boolean; type {# Enumerator for the ring (we inherit from TEnumerator to be comatible with TEnumerable) } TRingEnumerator = class(TEnumerator<T>) protected [Weak] FRing: TRingClass<T>; FPos: integer; function DoGetCurrent: T; override; function DoMoveNext: Boolean; override; public constructor Create(ARing: TRingClass<T>); end; public constructor Create(ACapacity: integer); destructor Destroy; override; procedure Clear; { add to head } procedure Add(const Value: T); overload; procedure Add(const Values: TArray<T>); overload; procedure Add(const AValues: TEnumerable<T>); overload; { add to tail } procedure AddToTail(const Value: T); overload; procedure AddToTail(const Values: TArray<T>); overload; procedure AddToTail(const AValues: TEnumerable<T>); overload; { from tail } function Extract: T; function ExtractTail: T; { from head } function ExtractHead: T; procedure Delete; procedure DeleteHead; property Capacity: integer read GetCapacity write SetCapacity; { should have Count=0 to resize } property Count: integer read FCount write FCount; property Empty: boolean read GetEmpty; property Head: T read GetHead write SetHead; property Tail: T read GetTail write SetTail; property ItemsFromHead[n: integer]:T read GetItemFromHead write SetItemFromHead; default; { from Head to Tail } property ItemsFromTail[n: integer]:T read GetItemFromTail write SetItemFromTail; { from Tail to Head } property OwnsValues: Boolean read FOwnsValues write SetOwnsValues; property IsFull: boolean read GetIsFull; end; implementation uses adot.Tools.RTTI; { TRingClass<T>.TRingEnumerator } constructor TRingClass<T>.TRingEnumerator.Create(ARing: TRingClass<T>); begin inherited Create; FRing := ARing; FPos := 0; end; function TRingClass<T>.TRingEnumerator.DoMoveNext: Boolean; begin result := FPos < FRing.Count; if result then Inc(FPos); end; function TRingClass<T>.TRingEnumerator.DoGetCurrent: T; begin result := FRing.ItemsFromHead[FPos-1]; end; { TRingClass<T> } constructor TRingClass<T>.Create(ACapacity: integer); begin Assert(ACapacity > 0); inherited Create; Capacity := ACapacity; end; destructor TRingClass<T>.Destroy; begin Clear; inherited; end; function TRingClass<T>.DoGetEnumerator: TEnumerator<T>; begin result := TRingEnumerator.Create(Self); end; function TRingClass<T>.GetCapacity: integer; begin result := FValues.Count; end; procedure TRingClass<T>.SetCapacity(ANewCapacity: integer); var Temp: TArray<T>; I: Integer; begin Assert((ANewCapacity >= Count) and (ANewCapacity>0)); if Capacity=ANewCapacity then Exit; SetLength(Temp, Count); for I := 0 to Count-1 do begin Temp[I] := ItemsFromHead[I]; ItemsFromHead[I] := Default(T); end; FValues.Count := ANewCapacity; FHead := 0; for I := 0 to Count-1 do FValues[I] := Temp[I]; end; procedure TRingClass<T>.Clear; var I: Integer; begin if FOwnsValues then for I := 0 to Count-1 do ItemsFromHead[I] := Default(T); FHead := 0; FCount := 0; end; function TRingClass<T>.GetIsFull: boolean; begin result := Count = Capacity; end; function TRingClass<T>.GetItemFromHead(n: integer): T; begin result := FValues.Items[(FHead + n) mod Capacity]; end; procedure TRingClass<T>.SetItemFromHead(n: integer; const Value: T); begin n := (FHead + n) mod Capacity; if FOwnsValues then PObject(@FValues.Items[n])^.DisposeOf; FValues.Items[n] := Value; end; function TRingClass<T>.GetItemFromTail(n: integer): T; begin result := FValues.Items[(FHead + FCount - n - 1) mod Capacity]; end; procedure TRingClass<T>.SetItemFromTail(n: integer; const Value: T); begin n := (FHead + FCount - n - 1) mod Capacity; if FOwnsValues then PObject(@FValues.Items[n])^.DisposeOf; FValues.Items[n] := Value; end; procedure TRingClass<T>.SetOwnsValues(const Value: Boolean); begin if Value and not TRttiUtils.IsInstance<T> then raise Exception.Create('Generic type is not a class.'); FOwnsValues := Value; end; function TRingClass<T>.GetHead: T; begin result := ItemsFromHead[0]; end; procedure TRingClass<T>.SetHead(const Value: T); begin ItemsFromHead[0] := Value; end; function TRingClass<T>.GetTail: T; begin result := ItemsFromTail[0]; end; procedure TRingClass<T>.SetTail(const Value: T); begin ItemsFromTail[0] := Value; end; procedure TRingClass<T>.Add(const Value: T); begin if FCount < Capacity then inc(FCount); Dec(FHead); if FHead < 0 then Inc(FHead, Capacity); if FOwnsValues then PObject(@FValues.Items[FHead])^.DisposeOf; FValues.Items[FHead] := Value; end; procedure TRingClass<T>.AddToTail(const Value: T); begin if FCount < Capacity then inc(FCount) else begin Inc(FHead); if FHead >= Capacity then FHead := 0; end; ItemsFromTail[0] := Value; end; procedure TRingClass<T>.Add(const Values: TArray<T>); var i: Integer; begin for i := 0 to High(Values) do Add(Values[i]); end; procedure TRingClass<T>.Add(const AValues: TEnumerable<T>); var Value: T; begin for Value in AValues do Add(Value); end; procedure TRingClass<T>.AddToTail(const Values: TArray<T>); var i: Integer; begin for i := 0 to High(Values) do AddToTail(Values[i]); end; procedure TRingClass<T>.AddToTail(const AValues: TEnumerable<T>); var Value: T; begin for Value in AValues do AddToTail(Value); end; function TRingClass<T>.GetEmpty: boolean; begin result := FCount=0; end; function TRingClass<T>.Extract: T; begin result := ItemsFromTail[0]; Delete; end; function TRingClass<T>.ExtractTail: T; begin result := ItemsFromTail[0]; Delete; end; function TRingClass<T>.ExtractHead: T; begin result := ItemsFromHead[0]; DeleteHead; end; procedure TRingClass<T>.Delete; begin ItemsFromTail[0] := Default(T); Dec(FCount); end; procedure TRingClass<T>.DeleteHead; begin ItemsFromHead[0] := Default(T); Dec(FCount); Inc(FHead); if (FHead >= Capacity) then FHead := 0; end; end.
{ LaKraven Studios Standard Library [LKSL] Copyright (c) 2014, LaKraven Studios Ltd, All Rights Reserved Original Source Location: https://github.com/LaKraven/LKSL License: - You may use this library as you see fit, including use within commercial applications. - You may modify this library to suit your needs, without the requirement of distributing modified versions. - You may redistribute this library (in part or whole) individually, or as part of any other works. - You must NOT charge a fee for the distribution of this library (compiled or in its source form). It MUST be distributed freely. - This license and the surrounding comment block MUST remain in place on all copies and modified versions of this source code. - Modified versions of this source MUST be clearly marked, including the name of the person(s) and/or organization(s) responsible for the changes, and a SEPARATE "changelog" detailing all additions/deletions/modifications made. Disclaimer: - Your use of this source constitutes your understanding and acceptance of this disclaimer. - LaKraven Studios Ltd and its employees (including but not limited to directors, programmers and clerical staff) cannot be held liable for your use of this source code. This includes any losses and/or damages resulting from your use of this source code, be they physical, financial, or psychological. - There is no warranty or guarantee (implicit or otherwise) provided with this source code. It is provided on an "AS-IS" basis. Donations: - While not mandatory, contributions are always appreciated. They help keep the coffee flowing during the long hours invested in this and all other Open Source projects we produce. - Donations can be made via PayPal to PayPal [at] LaKraven (dot) Com ^ Garbled to prevent spam! ^ } unit LKSL_Settings_Manager; { About this unit: (FPC/Lazarus) - This unit provides the components that manage in memory field/value pairs. Changelog (newest on top): 24th September 2014: - Initial Scaffolding } {$mode objfpc}{$H+} interface uses Classes, SysUtils, LKSL_Settings_Storage, LKSL_Settings_Groups, LKSL_Settings_Fields; type { TLKSettingsManager - Base class for the settings management. } TLKSettingsManager = class(TComponent) private protected FSettingsStorage: TLKSettingsStorage; FSettingsGroups: TLKSettingsGroups; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Storage: TLKSettingsStorage read FSettingsStorage write FSettingsStorage; // Need to assess which of these will enable array syntax: //property Groups[Index: Integer]: TLKSettingsGroup read GetSettingsGroup; property Groups: TLKSettingsGroups read FSettingsGroups; end; TLKSettingsManagerClass = class of TLKSettingsManager; { Register - Procedure to register component on the component bar } procedure Register; implementation procedure Register; begin RegisterComponents('LKSL',[TLKSettingsManager]); end; { TLKSettingsManager } constructor TLKSettingsManager.Create(AOwner: TComponent); begin inherited Create(AOwner); //FSettingsStorage:= TLKSettingsStorage.Create(Self); //FSettingsStorage.SetSubComponent(True); FSettingsGroups:= TLKSettingsGroups.Create(Self); FSettingsGroups.SetSubComponent(True); end; destructor TLKSettingsManager.Destroy; begin if Assigned(FSettingsStorage) then begin FSettingsStorage.Free; end; if Assigned(FSettingsGroups) then begin FSettingsGroups.Free; end; inherited Destroy; end; end.
unit testlaguerreunit; interface uses Math, Sysutils, Ap, laguerre; function TestLaguerreCalculate(Silent : Boolean):Boolean; function testlaguerreunit_test_silent():Boolean; function testlaguerreunit_test():Boolean; implementation function TestLaguerreCalculate(Silent : Boolean):Boolean; var Err : Double; SumErr : Double; CErr : Double; Threshold : Double; N : AlglibInteger; MaxN : AlglibInteger; I : AlglibInteger; J : AlglibInteger; Pass : AlglibInteger; C : TReal1DArray; X : Double; V : Double; WasErrors : Boolean; begin Err := 0; SumErr := 0; CErr := 0; Threshold := 1.0E-9; WasErrors := False; // // Testing Laguerre polynomials // N := 0; Err := Max(Err, AbsReal(LaguerreCalculate(N, 0.5)-1.0000000000)); N := 1; Err := Max(Err, AbsReal(LaguerreCalculate(N, 0.5)-0.5000000000)); N := 2; Err := Max(Err, AbsReal(LaguerreCalculate(N, 0.5)-0.1250000000)); N := 3; Err := Max(Err, AbsReal(LaguerreCalculate(N, 0.5)+0.1458333333)); N := 4; Err := Max(Err, AbsReal(LaguerreCalculate(N, 0.5)+0.3307291667)); N := 5; Err := Max(Err, AbsReal(LaguerreCalculate(N, 0.5)+0.4455729167)); N := 6; Err := Max(Err, AbsReal(LaguerreCalculate(N, 0.5)+0.5041449653)); N := 7; Err := Max(Err, AbsReal(LaguerreCalculate(N, 0.5)+0.5183392237)); N := 8; Err := Max(Err, AbsReal(LaguerreCalculate(N, 0.5)+0.4983629984)); N := 9; Err := Max(Err, AbsReal(LaguerreCalculate(N, 0.5)+0.4529195204)); N := 10; Err := Max(Err, AbsReal(LaguerreCalculate(N, 0.5)+0.3893744141)); N := 11; Err := Max(Err, AbsReal(LaguerreCalculate(N, 0.5)+0.3139072988)); N := 12; Err := Max(Err, AbsReal(LaguerreCalculate(N, 0.5)+0.2316496389)); // // Testing Clenshaw summation // MaxN := 20; SetLength(C, MaxN+1); Pass:=1; while Pass<=10 do begin X := 2*RandomReal-1; V := 0; N:=0; while N<=MaxN do begin C[N] := 2*RandomReal-1; V := V+LaguerreCalculate(N, X)*C[N]; SumErr := Max(SumErr, AbsReal(V-LaguerreSum(C, N, X))); Inc(N); end; Inc(Pass); end; // // Testing coefficients // LaguerreCoefficients(0, C); CErr := Max(CErr, AbsReal(C[0]-1)); LaguerreCoefficients(1, C); CErr := Max(CErr, AbsReal(C[0]-1)); CErr := Max(CErr, AbsReal(C[1]+1)); LaguerreCoefficients(2, C); CErr := Max(CErr, AbsReal(C[0]-AP_Double(2)/2)); CErr := Max(CErr, AbsReal(C[1]+AP_Double(4)/2)); CErr := Max(CErr, AbsReal(C[2]-AP_Double(1)/2)); LaguerreCoefficients(3, C); CErr := Max(CErr, AbsReal(C[0]-AP_Double(6)/6)); CErr := Max(CErr, AbsReal(C[1]+AP_Double(18)/6)); CErr := Max(CErr, AbsReal(C[2]-AP_Double(9)/6)); CErr := Max(CErr, AbsReal(C[3]+AP_Double(1)/6)); LaguerreCoefficients(4, C); CErr := Max(CErr, AbsReal(C[0]-AP_Double(24)/24)); CErr := Max(CErr, AbsReal(C[1]+AP_Double(96)/24)); CErr := Max(CErr, AbsReal(C[2]-AP_Double(72)/24)); CErr := Max(CErr, AbsReal(C[3]+AP_Double(16)/24)); CErr := Max(CErr, AbsReal(C[4]-AP_Double(1)/24)); LaguerreCoefficients(5, C); CErr := Max(CErr, AbsReal(C[0]-AP_Double(120)/120)); CErr := Max(CErr, AbsReal(C[1]+AP_Double(600)/120)); CErr := Max(CErr, AbsReal(C[2]-AP_Double(600)/120)); CErr := Max(CErr, AbsReal(C[3]+AP_Double(200)/120)); CErr := Max(CErr, AbsReal(C[4]-AP_Double(25)/120)); CErr := Max(CErr, AbsReal(C[5]+AP_Double(1)/120)); LaguerreCoefficients(6, C); CErr := Max(CErr, AbsReal(C[0]-AP_Double(720)/720)); CErr := Max(CErr, AbsReal(C[1]+AP_Double(4320)/720)); CErr := Max(CErr, AbsReal(C[2]-AP_Double(5400)/720)); CErr := Max(CErr, AbsReal(C[3]+AP_Double(2400)/720)); CErr := Max(CErr, AbsReal(C[4]-AP_Double(450)/720)); CErr := Max(CErr, AbsReal(C[5]+AP_Double(36)/720)); CErr := Max(CErr, AbsReal(C[6]-AP_Double(1)/720)); // // Reporting // WasErrors := AP_FP_Greater(Err,Threshold) or AP_FP_Greater(SumErr,Threshold) or AP_FP_Greater(CErr,Threshold); if not Silent then begin Write(Format('TESTING CALCULATION OF THE LAGUERRE POLYNOMIALS'#13#10'',[])); Write(Format('Max error %5.3e'#13#10'',[ Err])); Write(Format('Summation error %5.3e'#13#10'',[ SumErr])); Write(Format('Coefficients error %5.3e'#13#10'',[ CErr])); Write(Format('Threshold %5.3e'#13#10'',[ Threshold])); if not WasErrors then begin Write(Format('TEST PASSED'#13#10'',[])); end else begin Write(Format('TEST FAILED'#13#10'',[])); end; end; Result := not WasErrors; end; (************************************************************************* Silent unit test *************************************************************************) function testlaguerreunit_test_silent():Boolean; begin Result := TestLaguerreCalculate(True); end; (************************************************************************* Unit test *************************************************************************) function testlaguerreunit_test():Boolean; begin Result := TestLaguerreCalculate(False); end; end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, DBCtrls, Buttons, ToolWin, ExtCtrls, Grids, DBGrids, Math, DB, MemDS, VirtualDataSet; type TfmMain = class(TForm) pnDept: TPanel; Splitter: TSplitter; pnEmp: TPanel; btOpen: TSpeedButton; btClose: TSpeedButton; DBGridDept: TDBGrid; DBGridEmp: TDBGrid; DBNavigatorDept: TDBNavigator; DBNavigatorEmp: TDBNavigator; DeptDataSet: TVirtualDataSet; EmpDataSet: TVirtualDataSet; DeptDataSource: TDataSource; EmpDataSource: TDataSource; procedure btCloseClick(Sender: TObject); procedure btOpenClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure EmpDataSetGetFieldValue(Sender: TObject; Field: TField; RecNo: Integer; out Value: Variant); procedure DeptDataSetGetFieldValue(Sender: TObject; Field: TField; RecNo: Integer; out Value: Variant); procedure EmpDataSetGetRecordCount(Sender: TObject; out Count: Integer); procedure DeptDataSetGetRecordCount(Sender: TObject; out Count: Integer); procedure DeptDataSetInsertRecord(Sender: TObject; var RecNo: Integer); procedure EmpDataSetModifyRecord(Sender: TObject; var RecNo: Integer); procedure EmpDataSetDeleteRecord(Sender: TObject; RecNo: Integer); private { Private declarations } public { Public declarations } DeptList, EmpList : TList; end; TDept = class private FDeptNo: Integer; FDName: String; FLoc: String; public constructor Create(const DeptNo: Integer; const DName: string; const Loc: string); property DeptNo: Integer read FDeptNo write FDeptNo; property DName: string read FDName write FDName; property Loc: string read FLoc write FLoc; end; TEmp = class private FEmpNo: Integer; FEName: String; FJob: String; FMgr: Variant; FHireDate: TDateTime; FSal: Real; FComm: Variant; FDeptNo: Integer; public constructor Create(const EmpNo: Integer; const EName, Job: String; const Mgr: Variant; const HireDate: TDateTime; const Sal: Real; const Comm: Variant; DeptNo: Integer); property EmpNo: Integer read FEmpNo write FEmpNo; property EName: String read FEName write FEName; property Job: String read FJob write FJob; property Mgr: Variant read FMgr write FMgr; property HireDate: TDateTime read FHireDate write FHireDate; property Sal: Real read FSal write FSal; property Comm: Variant read FComm write FComm; property DeptNo: Integer read FDeptNo write FDeptNo; end; var fmMain: TfmMain; implementation {$R *.dfm} { TDept } constructor TDept.Create(const DeptNo: Integer; const DName, Loc: string); begin inherited Create; FDeptNo := DeptNo; FDName := DName; FLoc := Loc; end; { TEmp } constructor TEmp.Create(const EmpNo: Integer; const EName, Job: String; const Mgr: Variant; const HireDate: TDateTime; const Sal: Real; const Comm: Variant; DeptNo: Integer); begin inherited Create; FEmpNo := EmpNo; FEName := EName; FJob := Job; FMgr := Mgr; FHireDate := HireDate; FSal := Sal; FComm := Comm; FDeptNo := DeptNo; end; function CompareDeptByDeptNo(Item1, Item2 : Pointer): Integer; begin if TDept(Item1).DeptNo > TDept(Item2).DeptNo then Result := 1 else if TDept(Item1).DeptNo < TDept(Item2).DeptNo then Result := -1 else Result := 0; end; procedure TfmMain.FormCreate(Sender: TObject); var DateFormat: TFormatSettings; begin DeptList := TList.Create; DeptList.Add(TDept.Create(10, 'ACCOUNTING', 'NEW YORK')); DeptList.Add(TDept.Create(40, 'OPERATIONS', 'BOSTON')); DeptList.Add(TDept.Create(20, 'RESEARCH', 'DALLAS')); DeptList.Add(TDept.Create(30, 'SALES', 'CHICAGO')); DeptList.Sort(CompareDeptByDeptNo); DateFormat.DateSeparator := '-'; DateFormat.ShortDateFormat := 'dd-mm-yyyy'; EmpList := TList.Create; EmpList.Add(TEmp.Create(7369, 'SMITH', 'CLERK', 7902, StrToDateTime('17-12-1980', DateFormat), 800, NULL, 20)); EmpList.Add(TEmp.Create(7499, 'ALLEN','SALESMAN',7698, StrToDateTime('20-2-1981', DateFormat), 1600, 300, 30)); EmpList.Add(TEmp.Create(7521, 'WARD', 'SALESMAN', 7698, StrToDateTime('22-2-1981', DateFormat), 1250, 500, 30)); EmpList.Add(TEmp.Create(7566, 'JONES', 'MANAGER', 7839, StrToDateTime('2-4-1981', DateFormat), 2975, NULL, 20)); EmpList.Add(TEmp.Create(7654, 'MARTIN', 'SALESMAN', 7698, StrToDateTime('28-9-1981', DateFormat), 1250, 1400, 30)); EmpList.Add(TEmp.Create(7698, 'BLAKE', 'MANAGER',7839, StrToDateTime('1-5-1981', DateFormat), 2850, NULL, 30)); EmpList.Add(TEmp.Create(7782, 'CLARK', 'MANAGER', 7839, StrToDateTime('9-6-1981', DateFormat), 2450, NULL, 10)); EmpList.Add(TEmp.Create(7788, 'SCOTT', 'ANALYST', 7566, StrToDateTime('13-7-1987', DateFormat), 3000, NULL, 20)); EmpList.Add(TEmp.Create(7839, 'KING', 'PRESIDENT', NULL, StrToDateTime('17-11-1981', DateFormat), 5000, NULL, 10)); EmpList.Add(TEmp.Create(7844, 'TURNER', 'SALESMAN', 7698, StrToDateTime('8-9-1981', DateFormat), 1500, 0, 30)); EmpList.Add(TEmp.Create(7876, 'ADAMS', 'CLERK', 7788, StrToDateTime('13-7-1987', DateFormat), 1100, NULL, 20)); EmpList.Add(TEmp.Create(7900, 'JAMES', 'CLERK', 7698, StrToDateTime('3-12-1981', DateFormat), 950, NULL, 30)); EmpList.Add(TEmp.Create(7902, 'FORD', 'ANALYST', 7566, StrToDateTime('3-12-1981', DateFormat), 3000, NULL, 20)); EmpList.Add(TEmp.Create(7934, 'MILLER', 'CLERK', 7782, StrToDateTime('23-1-1982', DateFormat), 1300, NULL, 10)); DeptDataSet.FieldDefs.Add('DeptNo', ftInteger); DeptDataSet.FieldDefs.Add('DName', ftString, 14); DeptDataSet.FieldDefs.Add('Loc', ftString, 13); EmpDataSet.FieldDefs.Add('EmpNo', ftInteger); EmpDataSet.FieldDefs.Add('EName', ftString, 10); EmpDataSet.FieldDefs.Add('Job', ftString, 9); EmpDataSet.FieldDefs.Add('Mgr', ftInteger); EmpDataSet.FieldDefs.Add('HireDate', ftDate); EmpDataSet.FieldDefs.Add('Sal', ftFloat); EmpDataSet.FieldDefs.Add('Comm', ftFloat); EmpDataSet.FieldDefs.Add('DeptNo', ftInteger); EmpDataSet.MasterFields := 'DeptNo'; EmpDataSet.DetailFields := 'DeptNo'; EmpDataSet.MasterSource := DeptDataSource; end; procedure TfmMain.FormDestroy(Sender: TObject); var i: Integer; begin DeptDataSet.Close; DeptDataSet.FieldDefs.Clear; EmpDataSet.Close; EmpDataSet.FieldDefs.Clear; for i := DeptList.Count-1 downto 0 do TDept(DeptList.Items[i]).Free; DeptList.Free; for i := EmpList.Count-1 downto 0 do TEmp(EmpList.Items[i]).Free; EmpList.Free; end; procedure TfmMain.btCloseClick(Sender: TObject); begin Close; end; procedure TfmMain.btOpenClick(Sender: TObject); begin DeptDataSet.Open; EmpDataSet.Open; end; procedure TfmMain.DeptDataSetGetFieldValue(Sender: TObject; Field: TField; RecNo: Integer; out Value: Variant); var DeptItem: TDept; begin DeptItem := TDept(DeptList.Items[RecNo-1]); case Field.FieldNo of 1: Value := DeptItem.DeptNo; 2: Value := DeptItem.DName; 3: Value := DeptItem.Loc; end; end; procedure TfmMain.DeptDataSetGetRecordCount(Sender: TObject; out Count: Integer); begin Count := DeptList.Count; end; procedure TfmMain.DeptDataSetInsertRecord(Sender: TObject; var RecNo: Integer); var NewItem: TDept; begin NewItem := TDept.Create(DeptDataSet.FieldByName('DeptNo').AsInteger, DeptDataSet.FieldByName('DName').AsString, DeptDataSet.FieldByName('Loc').AsString); DeptList.Insert(0, NewItem); DeptList.Sort(CompareDeptByDeptNo); RecNo := DeptList.IndexOf(NewItem) + 1; end; procedure TfmMain.EmpDataSetDeleteRecord(Sender: TObject; RecNo: Integer); begin TEmp(EmpList.Items[RecNo-1]).Free; EmpList.Delete(RecNo-1); end; procedure TfmMain.EmpDataSetGetFieldValue(Sender: TObject; Field: TField; RecNo: Integer; out Value: Variant); var EmpItem: TEmp; begin EmpItem := TEmp(EmpList.Items[RecNo-1]); case Field.FieldNo of 1: Value := EmpItem.EmpNo; 2: Value := EmpItem.EName; 3: Value := EmpItem.Job; 4: Value := EmpItem.Mgr; 5: Value := EmpItem.HireDate; 6: Value := EmpItem.Sal; 7: Value := EmpItem.Comm; 8: Value := EmpItem.DeptNo; end; end; procedure TfmMain.EmpDataSetGetRecordCount(Sender: TObject; out Count: Integer); begin Count := EmpList.Count; end; procedure TfmMain.EmpDataSetModifyRecord(Sender: TObject; var RecNo: Integer); var Item: TEmp; begin Item := TEmp(EmpList.Items[RecNo-1]); Item.FEmpNo := EmpDataSet.FieldByName('EmpNo').AsInteger; Item.FEName := EmpDataSet.FieldByName('EName').AsString; Item.FJob := EmpDataSet.FieldByName('Job').AsString; Item.FMgr := EmpDataSet.FieldByName('Mgr').AsVariant; Item.FHireDate := EmpDataSet.FieldByName('HireDate').AsDateTime; Item.FSal := EmpDataSet.FieldByName('Sal').AsFloat; Item.FComm := EmpDataSet.FieldByName('Comm').AsVariant; Item.FDeptNo := EmpDataSet.FieldByName('DeptNo').AsInteger; end; end.
unit record_constructor_1; interface implementation type TRec = record x: int32; constructor Init; destructor Final; end; var G: Int32; constructor TRec.Init; begin G := 1; end; constructor TRec.Final; begin G := 2; end; procedure Test; var R: TRec; begin Assert(G = 1); R.x := 33; end; initialization Test(); finalization Assert(G = 2); end.
unit MediaProcessing.VideoAnalytics.Net.EventServer; interface uses Windows, Messages, SysUtils, Classes, SyncObjs, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPServer,IdContext,IdGlobal,IdIOHandler,IdThread, IdCustomTCPServer, IdStack, Generics.Collections, Collections.Map, MediaProcessing.VideoAnalytics.Net.EventDefinitions, MediaProcessing.Definitions,Collections.Lists, MediaProcessing.VideoAnalytics,IndyWrappers; type TVaepNotifies = class (TThreadSafeObjectListWrapper<TVaepNotify>) public procedure Add(const Item: TVaepNotify); end; TVaepServerSession = class private FNotifies: TVaepNotifies; public constructor Create; destructor Destroy; override; property Notifies: TVaepNotifies read FNotifies; end; TVaepServer = class private FServer : TTcpServer; FSuperUserPassword: string; FSessions: TThreadSafeObjectListWrapper<TVaepServerSession>; procedure OnServerExecute(AContext:TIdContext); public constructor Create(aPort: Word; const aSuperUserPassword: string); destructor Destroy; override; procedure OnEvent( const ConnectionUrl: string; const aProcessingResult: TVaProcessingResult); function Version: cardinal; function Port: Word; end; implementation uses IdSchedulerOfThreadDefault, dInterconnection,ThreadNames,CryptUtils, uBaseClasses,Patterns.Workspace; { TVaepServerContext } { TVaepServer } constructor TVaepServer.Create(aPort: Word; const aSuperUserPassword: string); begin FSuperUserPassword:=aSuperUserPassword; FSessions:=TThreadSafeObjectListWrapper<TVaepServerSession>.Create; FServer:=TTcpServer.Create(nil); // FClient.ConnectTimeout:=2000; Assert(aPort<>0); FServer.DefaultPort:=aPort; //FServer.Scheduler:=TIdSchedulerOfThreadDefault.Create(FServer); //TIdSchedulerOfThreadDefault(FServer.Scheduler).ThreadClass:=TNetStreamThread; //FServer.ContextClass:=TVaepServerContext; FServer.OnExecute:=OnServerExecute; FServer.Active:=true; end; //------------------------------------------------------------------------------ destructor TVaepServer.Destroy; begin inherited; FServer.Free; //Не использовать FreeAndNil! Не тот порядок! FServer:=nil; try if FSessions<>nil then Assert(FSessions.Count=0); except end; FreeAndNil(FSessions); end; //------------------------------------------------------------------------------ procedure TVaepServer.OnEvent(const ConnectionUrl: string; const aProcessingResult: TVaProcessingResult); var i: integer; aList: TList<TVaepServerSession>; aProcessingResult_: TVaProcessingResult; begin aList:=FSessions.LockList; try if aList.Count>0 then begin //Копируем к себе, так как это будет переложено в отдельный поток aProcessingResult_.Objects:=Copy(aProcessingResult.Objects,0,Length(aProcessingResult.Objects)); aProcessingResult_.Events:=Copy(aProcessingResult.Events,0,Length(aProcessingResult.Events)); for i := 0 to aList.Count - 1 do begin aList[i].Notifies.Add( TVaepEventNotify.Create(ConnectionUrl,aProcessingResult_)); end; end; finally FSessions.UnlockList; end; end; //------------------------------------------------------------------------------ procedure TVaepServer.OnServerExecute(AContext: TIdContext); var IO: TIdIOHandler; aCount: integer; aData: TBytes; aLoginParams: TVaepLoginParams; aLoginResult: TVaepLoginResult; aLoginResultCode: TVaepLoginResultCode; aHash: string; aSession: TVaepServerSession; aNotify: TVaepNotify; begin SetCurrentThreadName(ClassName); IO:=AContext.Connection.IOHandler; aCount:=IO.ReadLongInt(); aData:=nil; IO.ReadBytes(aData,aCount); aLoginResultCode:=iceOK; aLoginParams:=TVaepLoginParams.Create(aData); try if aLoginParams.ProtocolVersion<>VaepProtocolVerion then aLoginResultCode:=iceWrongProtocolVersion; if aLoginResultCode=iceOK then if aLoginParams.UserName<>VaepSuperUserName then aLoginResultCode:=iceWrongUserNameOrPassword; if aLoginResultCode=iceOK then begin aHash:=MD5Encode(Format('%s:%s',[aLoginParams.UserName,FSuperUserPassword])); if aHash<>aLoginParams.UserPasswordDigest then aLoginResultCode:=iceWrongUserNameOrPassword; end; finally aLoginParams.Free; end; aLoginResult:=TVaepLoginResult.Create(aLoginResultCode,TWorkspaceBase.Current.ApplicationGUID); aLoginResult.SaveToBytes(aData); IO.Write(Length(aData)); IO.Write(aData); if aLoginResultCode<>iceOK then abort; aSession:=TVaepServerSession.Create; FSessions.Add(aSession); try while IO.Connected do begin while true do begin try aNotify:=aSession.Notifies.ExtractFirstOrDefault; if aNotify=nil then break; aNotify.SaveToBytes(aData); IO.Write(VaepFrameBeginMarker); IO.Write(integer(aNotify.NotifyType)); IO.Write(integer(Length(aData))); IO.Write(aData); IO.Write(VaepFrameEndMarker); finally FreeAndNil(aNotify); end; end; sleep(10); end; finally FSessions.Remove(aSession); end; end; //------------------------------------------------------------------------------ function TVaepServer.Port: Word; begin result:=FServer.DefaultPort; end; function TVaepServer.Version: cardinal; begin result:=VaepProtocolVerion; end; { TVaepServerSession } constructor TVaepServerSession.Create; begin FNotifies:=TVaepNotifies.Create; end; destructor TVaepServerSession.Destroy; begin inherited; FreeAndNil(FNotifies); end; { TVaepNotifies } procedure TVaepNotifies.Add(const Item: TVaepNotify); begin self.LockList; try if Count>VaepMaxQueue then self.Delete(0); inherited Add(Item); finally self.UnlockList; end; end; end.
unit Settings; interface uses Vcl.Graphics, System.Win.Registry, Generics.Defaults; type TSavepathRelativeTo = (sprApplication, sprImage); ISettingsReader = interface function GetDotMarkerColor(const Deafult: TColor = clRed): TColor; function GetDotMarkerStrokeWidth(const Default: integer = 2): integer; function GetDotMarkerStrokeLength(const Deafult: integer = 10): integer; function GetSavepathRelativeTo(const Default: TSavepathRelativeTo = sprApplication): TSavepathRelativeTo; function GetSavePathForMarkers(const Default: string = 'markers\'): string; function GetSavePathForMasks(const Default: string = 'masks\'): string; end; ISettings = interface(ISettingsReader) procedure SetDotMarkerColor(const Value: TColor); procedure SetDotMarkerStrokeWidth(const Value: integer); procedure SetDotMarkerStrokeLength(const Value: integer); procedure SetSavepathRelativeTo(const Value: TSavepathRelativeTo); procedure SetSavePathForMarkers(const Value: string); procedure SetSavePathForMasks(const Value: string); end; TRegistryReadMethod<T> = function(const Name: string): T of object; TRegistryWriteMethod<T> = procedure(const Name: string; Value: T) of object; TSettingsRegistry = class(TInterfacedObject, ISettings) private FReg: TRegistry; FApplicationKey: string; function ReadKeyValue<T>(const KeyName: string; const ValueName: string; const Default: T; ReadMethod: TRegistryReadMethod<T>): T; procedure WriteKeyValue<T>(const KeyName: string; const ValueName: string; const Value: T; WriteMethod: TRegistryWriteMethod<T>); // procedure WriteStringToReg(const Name: string; Value: string); public constructor Create(const ApplicationKey: string); destructor Destroy; override; // Getters function GetDotMarkerColor(const Default: TColor): TColor; function GetDotMarkerStrokeWidth(const Default: integer): integer; function GetDotMarkerStrokeLength(const Default: integer): integer; function GetSavepathRelativeTo(const Default: TSavepathRelativeTo = sprApplication): TSavepathRelativeTo; function GetSavePathForMarkers(const Default: string = 'markers\'): string; function GetSavePathForMasks(const Default: string = 'masks\'): string; // Setters procedure SetDotMarkerColor(const Value: TColor); procedure SetDotMarkerStrokeWidth(const Value: integer); procedure SetDotMarkerStrokeLength(const Value: integer); procedure SetSavepathRelativeTo(const Value: TSavepathRelativeTo); procedure SetSavePathForMarkers(const Value: string); procedure SetSavePathForMasks(const Value: string); end; implementation uses Windows; { TSettingsRegistry } constructor TSettingsRegistry.Create(const ApplicationKey: string); begin inherited Create; FApplicationKey:= ApplicationKey; FReg:= TRegistry.Create; // Default values end; destructor TSettingsRegistry.Destroy; begin FReg.Free; inherited; end; function TSettingsRegistry.GetDotMarkerColor(const Default: TColor): TColor; begin Result:= ReadKeyValue<integer>(FApplicationKey + 'DotMarker\', 'Color', Default, FReg.ReadInteger); end; function TSettingsRegistry.GetDotMarkerStrokeLength(const Default: integer): integer; begin Result:= ReadKeyValue<integer>(FApplicationKey + 'DotMarker\', 'StrokeLength', Default, FReg.ReadInteger); end; function TSettingsRegistry.GetDotMarkerStrokeWidth(const Default: integer): integer; begin Result:= ReadKeyValue<integer>(FApplicationKey + 'DotMarker\', 'StrokeWidth', Default, FReg.ReadInteger); end; function TSettingsRegistry.GetSavePathForMarkers(const Default: string): string; begin Result:= ReadKeyValue<string>(FApplicationKey + 'SavePaths\', 'Markers', Default, FReg.ReadString); end; function TSettingsRegistry.GetSavePathForMasks(const Default: string): string; begin Result:= ReadKeyValue<string>(FApplicationKey + 'SavePaths\', 'Masks', Default, FReg.ReadString); end; function TSettingsRegistry.GetSavepathRelativeTo( const Default: TSavepathRelativeTo): TSavepathRelativeTo; begin Result:= TSavepathRelativeTo(ReadKeyValue<integer>(FApplicationKey + 'SavePaths\', 'RelativeTo', integer(Default), FReg.ReadInteger)); end; function TSettingsRegistry.ReadKeyValue<T>(const KeyName: string; const ValueName: string; const Default: T; ReadMethod: TRegistryReadMethod<T>): T; var OpenResult: boolean; begin Result:= Default; FReg.Access:= KEY_READ; OpenResult:= Freg.OpenKeyReadOnly(KeyName); if not OpenResult then Exit; try Result:= ReadMethod(ValueName); finally FReg.CloseKey; end; end; procedure TSettingsRegistry.SetDotMarkerStrokeLength(const Value: integer); begin WriteKeyValue<integer>(FApplicationKey + 'DotMarker\', 'StrokeLength', Value, FReg.WriteInteger); end; procedure TSettingsRegistry.SetDotMarkerColor(const Value: TColor); begin WriteKeyValue<integer>(FApplicationKey + 'DotMarker\', 'Color', Value, FReg.WriteInteger); end; procedure TSettingsRegistry.SetDotMarkerStrokeWidth(const Value: integer); begin WriteKeyValue<integer>(FApplicationKey + 'DotMarker\', 'StrokeWidth', Value, FReg.WriteInteger); end; procedure TSettingsRegistry.SetSavePathForMarkers(const Value: string); begin WriteKeyValue<string>(FApplicationKey + 'SavePaths\', 'Markers', Value, WriteStringToReg); end; procedure TSettingsRegistry.SetSavePathForMasks(const Value: string); begin WriteKeyValue<string>(FApplicationKey + 'SavePaths\', 'Masks', Value, WriteStringToReg); end; procedure TSettingsRegistry.SetSavepathRelativeTo( const Value: TSavepathRelativeTo); begin WriteKeyValue<integer>(FApplicationKey + 'SavePaths\', 'RelativeTo', integer(Value), FReg.WriteInteger); end; procedure TSettingsRegistry.WriteKeyValue<T>(const KeyName, ValueName: string; const Value: T; WriteMethod: TRegistryWriteMethod<T>); var OpenResult: boolean; begin FReg.Access:= KEY_WRITE; OpenResult:= Freg.OpenKey(KeyName, true); if not OpenResult then Exit; try WriteMethod(ValueName, Value); finally FReg.CloseKey; end; end; procedure TSettingsRegistry.WriteStringToReg(const Name: string; Value: string); begin FReg.WriteString(Name, Value); end; end.
{***********************************<_INFO>************************************} { <Проект> Медиа-сервер } { } { <Область> 16:Медиа-контроль } { } { <Задача> Медиа-источник, предоставляющий чтение данных из источника, } { поддерживающего протокол 3S MediaServer } { } { <Автор> Фадеев Р.В. } { } { <Дата> 14.01.2011 } { } { <Примечание> Нет примечаний. } { } { <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" } { } {***********************************</_INFO>***********************************} unit MediaServer.Stream.Source.MediaServer; interface uses Windows, SysUtils, SyncObjs, Classes, ExtCtrls, MediaServer.Stream.Source, MediaServer.Net.Ms3s.Stream,MediaServer.Net.Ms3s.Login, MediaProcessing.Definitions; type //Класс, выполняющий непосредственно получение данных (видеопотока) из камеры TMediaServerSourceMediaServer = class (TMediaServerSource) private FLock : TCriticalSection; FStream : TMediaServerStream; FConnectParams_Ip: string; FConnectParams_Port: Word; FConnectParams_UserName: string; FConnectParams_UserPassword: string; FConnectParams_SourceName: string; FConnectParams_BandWidth: cardinal; FConnect_Lock: TCriticalSection; FLastStreamTypes : TAllMediaStreamTypes; FTransmitAudio : boolean; //Записывать ли аудио FConnect_ThreadHandle: THandle; procedure OnStreamDataReceived(aSender: TMediaServerStream; const aFormat: TMediaStreamDataHeader; const aData,aInfo: TBytes); procedure OnConnectionOKSync(aParams: pointer); procedure OnConnectionFailedSync(aParams: pointer); procedure PtzInit; protected function GetStreamType(aMediaType: TMediaType): TStreamType; override; public constructor Create(const aIP: string; aPort: Word; const aSourceName: string; const aProtocol: {3S, reserved} cardinal; const aUserName, aUserPassword: string; aTransmitAudio: boolean; //Записывать ли аудио aDataReceiveTimeout: integer //таймаут получения данных от канала ); overload; destructor Destroy; override; procedure OnFrameReceived(const aFormat: TMediaStreamDataHeader; const aData,aInfo: TBytes); procedure DoOpen(aSync: boolean); override; procedure DoClose; override; procedure WaitWhileConnecting(aTimeout: integer); override; function Opened: Boolean; override; // property ConnectParams: THHNetChannelConnectionParams read FConnectParams; //property AVInfo: HHAV_INFO read GetChannelAVInfo; function Name: string; override; function DeviceType: string; override; function ConnectionString: string; override; function StreamInfo: TBytes; override; function PtzSupported: boolean; override; procedure PtzApertureDecrease; override; procedure PtzApertureDecreaseStop; override; procedure PtzApertureIncrease; override; procedure PtzApertureIncreaseStop; override; procedure PtzFocusIn; override; procedure PtzFocusInStop; override; procedure PtzFocusOut; override; procedure PtzFocusOutStop; override; procedure PtzMoveDown(aSpeed: byte); override; procedure PtzMoveDownStop; override; procedure PtzMoveLeft(aSpeed: byte); override; procedure PtzMoveLeftStop; override; procedure PtzMoveRight(aSpeed: byte); override; procedure PtzMoveRightStop; override; procedure PtzMoveUp(aSpeed: byte); override; procedure PtzMoveUpStop; override; procedure PtzZoomIn; override; procedure PtzZoomInStop; override; procedure PtzZoomOut; override; procedure PtzZoomOutStop; override; //===== Перемещение на заданную позицию //Пресет procedure PtzMoveToPoint(aId: cardinal);override; //Движение в указанную позицию. Позиция указывается по оси X и Y в градусах procedure PtzMoveToPosition(const aPositionPan,aPositionTilt: double); override; end; TBewardThreadExceptionEvent = procedure (aExceptionSender: TObject; E:Exception) of object; TBewardTraceEvent = procedure (aSender: TObject; const aTraceMessage: string) of object; implementation uses Math,Forms,MediaStream.UrlFormats, MediaServer.Workspace,ThreadNames, uTrace,uSync; type TOpenConnectionOkParams = record Channel: TMediaServerStream; end; POpenConnectionOkParams = ^TOpenConnectionOkParams; TOpenConnectionFailedParams = record E: Exception; end; POpenConnectionFailedParams = ^TOpenConnectionFailedParams; { TMediaServerSourceMediaServer } constructor TMediaServerSourceMediaServer.Create( const aIP: string; aPort: Word; const aSourceName: string; const aProtocol: {THHNetProtocol} cardinal; const aUserName, aUserPassword: string; aTransmitAudio: boolean; //Записывать ли аудио aDataReceiveTimeout: integer //таймаут получения данных от канала ); var i: TMediaType; begin Create(aDataReceiveTimeout); FLock:=TCriticalSection.Create; FConnect_Lock:=TCriticalSection.Create; FConnectParams_Ip:=aIP; FConnectParams_Port:=aPort; FConnectParams_UserName:=aUserName; FConnectParams_UserPassword:=aUserPassword; FConnectParams_SourceName:=aSourceName; FConnectParams_BandWidth:=INFINITE; //TODO FTransmitAudio:=aTransmitAudio; for i := Low(TMediaType) to High(TMediaType) do FLastStreamTypes[i]:=stUNIV; end; destructor TMediaServerSourceMediaServer.Destroy; begin inherited; FreeAndNil(FLock); FreeAndNil(FConnect_Lock); end; function TMediaServerSourceMediaServer.DeviceType: string; begin result:='Медиа-сервер'; end; function TMediaServerSourceMediaServer.Name: string; begin Result := MakeMs3sUrl(FConnectParams_Ip, FConnectParams_Port, FConnectParams_SourceName); end; procedure TMediaServerSourceMediaServer.OnFrameReceived(const aFormat: TMediaStreamDataHeader; const aData,aInfo: TBytes); begin //Если не нужно записывать аудио данные, то выходим if not FTransmitAudio and (aFormat.biMediaType=mtAudio) then exit; LockStream; try FLastStreamTypes[aFormat.biMediaType]:=aFormat.biStreamType; finally UnlockStream; end; DoDataReceived(aFormat, @aData[0],Length(aData),@aInfo[0],Length(aInfo)); end; procedure TMediaServerSourceMediaServer.OnStreamDataReceived( aSender: TMediaServerStream; const aFormat: TMediaStreamDataHeader; const aData, aInfo: TBytes); begin Assert(self<>nil); OnFrameReceived(aFormat,aData,aInfo); end; procedure TMediaServerSourceMediaServer.OnConnectionFailedSync(aParams: pointer); begin //Добавим себя в список очередников на повторное соединение StartReconnect; if Assigned(OnConnectionFailed) then OnConnectionFailed(self,POpenConnectionFailedParams(aParams).E); end; procedure TMediaServerSourceMediaServer.OnConnectionOKSync(aParams: pointer); begin FreeAndNil(FStream); //На всякий случай надо убедиться что нет текущего подключения FStream:=POpenConnectionOkParams(aParams).Channel; DoConnectionOK; Assert(FStream<>nil); //Если все успешно открылось, привешиваем обработчик на данные из канала //Это нужно делать только после инициализации всего, чтобы данные поступали к нам, когда //мы целиком инициализированы FStream.OnDataReceived.Add(OnStreamDataReceived); end; function ThreadConnectionProc(aRecordSource: TMediaServerSourceMediaServer): Integer; var aOpenOk : TOpenConnectionOkParams; aOpenFailed: TOpenConnectionFailedParams; aLogin : TMediaServerLogin; begin SetCurrentThreadName('MediaServer.Stream.Source.MediaServer.ThreadConnectionProc'); result:=-1; if not (aRecordSource.Destroying or aRecordSource.Closing) then if (gLastCommand=rslcStart) then if not Application.Terminated then begin result:=0; end; if result<>0 then exit; ZeroMemory(@aOpenOk,sizeof(aOpenOk)); //Одновременно может выполняться только одно подключение, поэтому блокируем //повторные запросы aRecordSource.FConnect_Lock.Enter; try //открываемся try // открываем канал aLogin:=TMediaServerLogin.Create(aRecordSource.FConnectParams_IP,aRecordSource.FConnectParams_Port); try //Это мы же сами if IsEqualGUID(aLogin.ServerID,Workspace.ApplicationGUID) then raise Exception.Create('Подключение источника к собственному медиа-серверу запрещено'); aOpenOk.Channel:= aLogin.CreateStream(aRecordSource.FConnectParams_SourceName,aRecordSource.FConnectParams_UserName,aRecordSource.FConnectParams_UserPassword,nil,aRecordSource.FConnectParams_BandWidth); finally aLogin.Free; end; except on E:Exception do begin FreeAndNil(aOpenOk.Channel); aOpenFailed.E:=E; Sync.Synchronize(aRecordSource.OnConnectionFailedSync,@aOpenFailed); end; end; if aOpenOk.Channel<>nil then Sync.Synchronize(aRecordSource.OnConnectionOkSync,@aOpenOk); finally aRecordSource.FConnect_ThreadHandle:=0; aRecordSource.FConnect_Lock.Leave; end; end; procedure TMediaServerSourceMediaServer.DoOpen(aSync: boolean); var aThreadID: cardinal; begin if Opened or (FConnect_ThreadHandle <> 0) then exit; if aSync then ThreadConnectionProc(self) else begin if FConnect_ThreadHandle=0 then //Если <>0, значит, уже выполняется подключение FConnect_ThreadHandle:=BeginThread(nil, 0, @ThreadConnectionProc, self, 0, aThreadID); end; end; procedure TMediaServerSourceMediaServer.DoClose; var i: TMediaType; begin FLock.Enter; try //Вычистим очередь if FConnect_ThreadHandle<>0 then begin Sync.PeekSynchronizationMessages; Sync.WaitWhileSynchronizationMessagesProcessed(FConnect_ThreadHandle); FConnect_ThreadHandle:=0; end; FreeAndNil(FStream); for i := Low(TMediaType) to High(TMediaType) do FLastStreamTypes[i]:=stUNIV; finally FLock.Leave; end; end; function TMediaServerSourceMediaServer.ConnectionString: string; begin result:=MakeMs3sUrl(FConnectParams_Ip,FConnectParams_Port,FConnectParams_SourceName); end; function TMediaServerSourceMediaServer.Opened: Boolean; begin FLock.Enter; try result:=(FStream<>nil) and (FStream.Opened) finally FLock.Leave; end; end; function TMediaServerSourceMediaServer.StreamInfo: TBytes; begin result:=nil; end; function TMediaServerSourceMediaServer.GetStreamType(aMediaType: TMediaType): TStreamType; begin result:=FLastStreamTypes[aMediaType]; end; procedure TMediaServerSourceMediaServer.PtzApertureDecrease; begin FLock.Enter; try inherited; PtzInit; FStream.PtzApertureDecrease(0); finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzApertureDecreaseStop; begin FLock.Enter; try inherited; PtzInit; FStream.PtzApertureDecreaseStop; finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzApertureIncrease; begin FLock.Enter; try inherited; PtzInit; FStream.PtzApertureIncrease(0); finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzApertureIncreaseStop; begin FLock.Enter; try inherited; PtzInit; FStream.PtzApertureIncreaseStop; finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzFocusIn; begin FLock.Enter; try inherited; PtzInit; FStream.PtzFocusIn(0); finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzFocusInStop; begin FLock.Enter; try inherited; PtzInit; FStream.PtzFocusInStop; finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzFocusOut; begin FLock.Enter; try inherited; PtzInit; FStream.PtzFocusOut(0); finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzFocusOutStop; begin FLock.Enter; try inherited; PtzInit; FStream.PtzFocusOutStop; finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzInit; begin CheckConnected; FLock.Enter; try //FStream.Ptz finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzMoveDown(aSpeed: byte); begin FLock.Enter; try inherited; PtzInit; FStream.PtzMoveDown(0,aSpeed); finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzMoveDownStop; begin FLock.Enter; try inherited; PtzInit; FStream.PtzMoveDownStop; finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzMoveLeft(aSpeed: byte); begin FLock.Enter; try inherited; PtzInit; FStream.PtzMoveLeft(0,aSpeed); finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzMoveLeftStop; begin FLock.Enter; try inherited; PtzInit; FStream.PtzMoveLeftStop; finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzMoveRight(aSpeed: byte); begin FLock.Enter; try inherited; PtzInit; FStream.PtzMoveRight(0,aSpeed); finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzMoveRightStop; begin FLock.Enter; try inherited; PtzInit; FStream.PtzMoveRightStop; finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzMoveToPoint(aId: cardinal); begin FLock.Enter; try inherited; PtzInit; FStream.PtzMoveToPoint(aId); finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzMoveToPosition(const aPositionPan,aPositionTilt: double); begin FLock.Enter; try inherited; PtzInit; FStream.PtzMoveToPosition(aPositionPan,aPositionTilt); finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzMoveUp(aSpeed: byte); begin FLock.Enter; try inherited; PtzInit; FStream.PtzMoveUp(0,aSpeed); finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzMoveUpStop; begin FLock.Enter; try inherited; PtzInit; FStream.PtzMoveUpStop; finally FLock.Leave; end; end; function TMediaServerSourceMediaServer.PtzSupported: boolean; begin FLock.Enter; try result:=true; finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzZoomIn; begin FLock.Enter; try inherited; PtzInit; FStream.PtzZoomIn(0); finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzZoomInStop; begin FLock.Enter; try inherited; PtzInit; FStream.PtzZoomInStop; finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzZoomOut; begin FLock.Enter; try inherited; PtzInit; FStream.PtzZoomOut(0); finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.PtzZoomOutStop; begin FLock.Enter; try inherited; PtzInit; FStream.PtzZoomOutStop; finally FLock.Leave; end; end; procedure TMediaServerSourceMediaServer.WaitWhileConnecting(aTimeout: integer); begin inherited; WaitForSingleObject(FConnect_ThreadHandle,aTimeout); end; end.
unit UMutiTrackBar; interface uses System.SysUtils, System.Classes, Vcl.Controls, Vcl.ComCtrls, WinApi.Messages; type TMutiTrackBar = class(TTrackBar) private MouseUp: TNotifyEvent; { Private declarations } procedure MouseUpProc(var mes:TWMLBUTTONUP); message WM_LBUTTONUP; protected { Protected declarations } public { Public declarations } published { Published declarations } property OnMouseUp:TNotifyEvent read mouseup write mouseup; end; procedure Register; implementation procedure Register; begin RegisterComponents('Standard', [TMutiTrackBar]); end; procedure TMutiTrackBar.MouseUpProc(var mes:TWMLBUTTONUP); begin inherited; if(assigned(mouseup))then OnMouseUp(Self); end; end.
unit uIP; {$i xPL.inc} interface uses Classes , SysUtils , IdIPAddress , fgl ; type // TIPAddress ============================================================ TIPAddress = class(TObject) fIntName : string; // interface name eth0, lo, wlan0... fHWAddr : string; // Hardware address fIdIPAddress : TIdIPAddress; fNetMask : string; // Netmask fBroadCast : string; // broadcast address private fPrefix: integer; function GetAddress: string; procedure SetAddress(const aValue: string); public constructor Create(const aIP : string); overload; destructor Destroy; override; function IsValid : boolean; published property Address : string read GetAddress write SetAddress; property BroadCast : string read fBroadCast write fBroadCast; property NetMask : string read fNetMask write fNetMask; property Prefix : integer read fPrefix write fPrefix; property IntName : string read fIntName write fIntName; property HWAddr : string read fHWAddr write fHWAddr; end; // TIPAddresses ========================================================== TSpecIPAddresses = specialize TFPGObjectList<TIPAddress>; TIPAddresses = class(TSpecIPAddresses) private procedure BuildList; public constructor Create; function GetByIP(const aIP : string) : TIPAddress; function GetByIntName(const aInterface : string) : TIPAddress; end; function LocalIPAddresses : TIPAddresses; // ============================================================================ implementation uses Process , RegExpr ; var fLocalAddresses : TIPAddresses; // ============================================================================ function LocalIPAddresses: TIPAddresses; begin if not Assigned(fLocalAddresses) then begin fLocalAddresses := TIPAddresses.Create; end; Result := fLocalAddresses; end; // TIPAddress ================================================================= constructor TIPAddress.Create(const aIP : string); begin inherited Create; fIdIPAddress := TIdIPAddress.MakeAddressObject(aIP); end; destructor TIPAddress.Destroy; begin fIdIPAddress.Free; inherited; end; function TIPAddress.IsValid: boolean; begin Result := (length(Address) * length(BroadCast)) <> 0 end; function TIPAddress.GetAddress: string; begin Result := ''; if Assigned(fIdIPAddress) then Result := fIdIPAddress.IPAsString; end; procedure TIPAddress.SetAddress(const aValue: string); begin if not Assigned(fIdIPAddress) then fIdIPAddress := TIdIPAddress.MakeAddressObject(aValue); end; // TIPAddresses =============================================================== constructor TIPAddresses.Create; begin inherited Create; FreeObjects := True; BuildList; end; function TIPAddresses.GetByIP(const aIP: string): TIPAddress; var o : TIPAddress; begin Result := nil; for o in Self do if o.Address = aIP then Result := o; end; function TIPAddresses.GetByIntName(const aInterface: string): TIPAddress; var o : TIPAddress; begin Result := nil; for o in Self do if o.IntName = aInterface then Result := o; end; procedure TIPAddresses.BuildList; {$ifndef mswindows} var proc : TProcess; slOutput : TStringList; re : TRegExpr; s : string; address : TIPAddress; {$endif} begin {$ifdef mswindows} TIdStack.IncUsage; // as of now, this has to be adapted under windows aStringList.Assign(GStack.LocalAddresses); {$else} proc := TProcess.Create(nil); slOutput := TStringList.Create; re := TRegExpr.Create; proc.Executable := 'ifconfig'; proc.Options := proc.Options + [poWaitOnExit, poUsePipes, poNoConsole,poStderrToOutput]; try proc.Execute; // collect all network interfaces and hardware addresses slOutput.LoadFromStream(proc.Output); re.Expression := '(.*?) .*?HWaddr (.*?) '; for s in slOutput do if re.Exec(s) then begin address := TIPAddress.Create; address.HWAddr := re.Match[2]; address.IntName:= re.Match[1]; Add(address); end; for address in Self do begin proc.Parameters.Text:=Address.IntName; proc.Execute; slOutput.LoadFromStream(proc.Output); re.Expression := ' (.*?):([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}) (.*?):([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}) (.*?):([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})'; if re.Exec(slOutput.Text) then begin Address.Address :=re.Match[2]; Address.NetMask := re.Match[6]; Address.BroadCast := re.Match[4]; end; end; finally re.Free; slOutput.Free; proc.Free; end; {$endif} end; // ============================================================================ finalization if Assigned(fLocalAddresses) then LocalIPAddresses.Free; end.
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Copyright (c) 2020-2020 Skybuck Flying // Copyright (c) 2020-2020 The Delphicoin Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Bitcoin file: src/coins.h // Bitcoin file: src/coins.cpp // Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c unit Unit_TCoin; interface // /** // * A UTXO entry. // * // * Serialized format: // * - VARINT((coinbase ? 1 : 0) | (height << 1)) // * - the non-spent CTxOut (via TxOutCompression) // */ class Coin { public: //! unspent transaction output CTxOut out; //! whether containing transaction was a coinbase unsigned int fCoinBase : 1; //! at which height this containing transaction was included in the active block chain uint32_t nHeight : 31; //! construct a Coin from a CTxOut and height/coinbase information. Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {} Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {} void Clear() { out.SetNull(); fCoinBase = false; nHeight = 0; } //! empty constructor Coin() : fCoinBase(false), nHeight(0) { } bool IsCoinBase() const { return fCoinBase; } template<typename Stream> void Serialize(Stream &s) const { assert(!IsSpent()); uint32_t code = nHeight * uint32_t{2} + fCoinBase; ::Serialize(s, VARINT(code)); ::Serialize(s, Using<TxOutCompression>(out)); } template<typename Stream> void Unserialize(Stream &s) { uint32_t code = 0; ::Unserialize(s, VARINT(code)); nHeight = code >> 1; fCoinBase = code & 1; ::Unserialize(s, Using<TxOutCompression>(out)); } bool IsSpent() const { return out.IsNull(); } size_t DynamicMemoryUsage() const { return memusage::DynamicUsage(out.scriptPubKey); } }; implementation end.
unit ErrForm; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, DB, DBTables; type TUpdateErrorForm = class(TForm) ErrorText: TLabel; UpdateType: TLabel; UpdateData: TStringGrid; SkipButton: TButton; RetryButton: TButton; AbortButton: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure UpdateDataSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: string); private FDataFields: TStringList; procedure GetFieldValues(DataSet: TDataSet); procedure SetFieldValues(DataSet: TDataSet); public function HandleError(DataSet: TDataSet; E: EDatabaseError; UpdateKind: TUpdateKind): TUpdateAction; end; var UpdateErrorForm: TUpdateErrorForm; implementation {$R *.DFM} { Public and Private Methods } { This method handles the error by displaying a dialog with information about the error and then allowing the user to decide what course of action to take } function TUpdateErrorForm.HandleError(DataSet: TDataSet; E: EDatabaseError; UpdateKind: TUpdateKind): TUpdateAction; const UpdateKindStr: array[TUpdateKind] of string = ('Modified', 'Inserted', 'Deleted'); begin { Put the error context information into the labels on the form } UpdateType.Caption := UpdateKindStr[UpdateKind]; ErrorText.Caption := E.Message; { Fill the string grid with the update field values } GetFieldValues(DataSet); ShowModal; case ModalResult of mrRetry: begin { If user wants to retry, then put any changed values from the string grid back into the associated field's NewValue property } SetFieldValues(DataSet); Result := uaRetry; end; mrIgnore: Result := uaSkip; else Result := uaAbort; end; end; { This fills in the string grid with data from the record being updated } procedure TUpdateErrorForm.GetFieldValues(DataSet: TDataSet); var I: Integer; F: TField; begin { Create a list of the data fields in the dataset, and store them in a stringlist which we can use to determine which values the user has edited } FDataFields.Clear; for I := 0 to DataSet.FieldCount - 1 do with Dataset.Fields[I] do if (FieldKind = fkData) then FDataFields.AddObject('', DataSet.Fields[I]); { Now fill up the string grid with the Old and New values of each field. OldValue and NewValue are public properties of TDataSet which are used from within the OnUpdateError event handler to determine what data a user has updated. We use the VarToStr RTL function to ensure that null fields are displayed as blank strings } UpdateData.RowCount := FDataFields.Count + 1; for I := 0 to FDataFields.Count - 1 do begin F := TField(FDataFields.Objects[I]); UpdateData.Cells[0, I + 1] := VarToStr(F.NewValue); UpdateData.Cells[1, I + 1] := VarToStr(F.OldValue); end; end; procedure TUpdateErrorForm.SetFieldValues(DataSet: TDataSet); var I: Integer; F: TField; begin for I := 0 to FDataFields.Count - 1 do { We set the string in the data field list to '*' for any fields the user edited in the string grid. Those are the only fields we need to write back into the associated TField's NewValue property } if FDataFields[I] = '*' then begin F := TField(FDataFields.Objects[I]); F.NewValue := UpdateData.Cells[0, I + 1]; end; end; { Event handlers } procedure TUpdateErrorForm.FormCreate(Sender: TObject); begin FDataFields := TStringList.Create; { Fill in the titles of the string grid } UpdateData.Cells[0,0] := 'New Value'; UpdateData.Cells[1,0] := 'Old Value'; end; procedure TUpdateErrorForm.FormDestroy(Sender: TObject); begin FDataFields.Free; end; procedure TUpdateErrorForm.UpdateDataSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: string); begin { Set a flag in the list of datafields indicating that this value was changed. } FDataFields[ARow - 1] := '*'; end; end.
(* CheckStyle: MM, 2020-04-18 *) (* ------ *) (* Program to check consistency of coding style in pascal codes *) (* ========================================================================= *) PROGRAM CheckStyle; USES Multiset; VAR skipChars: StrMSet; PROCEDURE InsertWord(VAR ms: StrMSet; VAR w: STRING); VAR i: INTEGER; toDel: BOOLEAN; BEGIN (* InsertWord *) toDel := TRUE; FOR i := 1 TO Length(w) DO BEGIN IF (NOT (w[i] in ['0'..'9'])) THEN BEGIN toDel := FALSE; END; (* IF *) END; (* FOR *) IF (NOT toDel) THEN BEGIN Insert(ms, w); END; (* IF *) w := ''; END; (* InsertWord *) PROCEDURE GetWordsFromLine(line: STRING; VAR ms: StrMSet); VAR i: INTEGER; skipLine: BOOLEAN; currWord: STRING; BEGIN (* GetWordsFromLine *) skipLine := FALSE; currWord := ''; FOR i := 1 TO Length(line) DO BEGIN IF (NOT skipLine) THEN BEGIN IF (line[i] = '/') THEN BEGIN IF (line[i + 1] = '/') THEN BEGIN //Checks for Line comments skipLine := TRUE; //rest of line can be ignored END; (* IF *) END ELSE BEGIN IF (NOT Contains(skipChars, line[i])) THEN BEGIN IF (line[i] = ' ') THEN BEGIN IF (currWord <> '') THEN BEGIN InsertWord(ms, currWord); END; (* IF *) END ELSE BEGIN currWord := currWord + line[i]; END; (* IF *) END ELSE BEGIN IF (currWord <> '') THEN BEGIN InsertWord(ms, currWord); END; (* IF *) END; (* IF *) END; (* IF *) END ELSE BEGIN IF (currWord <> '') THEN BEGIN InsertWord(ms, currWord); END; (* IF *) END; (* IF *) END; (* FOR *) IF (currWord <> '') THEN BEGIN InsertWord(ms, currWord); END; (* IF *) END; (* GetWordsFromLine *) PROCEDURE CheckIOError(message: STRING); VAR error: INTEGER; BEGIN (* CheckIOError *) error := IOResult; IF (error <> 0) THEN BEGIN WriteLn('ERROR: ', message, '(Code: ', error, ')'); HALT; END; (* IF *) END; (* CheckIOError *) PROCEDURE InitSkipChars(ms: StrMSet); VAR skipFile: TEXT; line: STRING; BEGIN (* GetSkipChars *) Assign(skipFile, 'skipChars.txt'); {$I-} Reset(skipFile); CheckIOError('Cannot open skipChars.txt File. Does it exist?'); {$I+} NewStrMSet(skipChars); REPEAT ReadLn(skipFile, line); Insert(skipChars, line); UNTIL (Eof(skipFile)); (* REPEAT *) END; (* GetSkipChars *) VAR inputFileName: STRING; line: STRING; asTyped, normalized: StrMSet; keys: ARRAY [1..255] OF STRING; keysCount: INTEGER; isCount, shouldCount, i: INTEGER; BEGIN (* CheckStyle *) InitSkipChars(skipChars); IF (ParamCount <> 1) THEN BEGIN WriteLn('Error: Unknown number of Parameters.'); WriteLn('Usage: CheckStyle.exe <input.pas>'); HALT; END ELSE BEGIN inputFileName := ParamStr(1); Assign(input, inputFileName); {$I-} Reset(input); CheckIOError('Cannot open input file'); {$I+} END; (* IF *) NewStrMSet(asTyped); NewStrMSet(normalized); REPEAT ReadLn(input, line); GetWordsFromLine(line, asTyped); GetWordsFromLine(UpCase(line), normalized); UNTIL (Eof(input)); (* REPEAT *) WriteLn('Cardinality':25, 'Unique':10); WriteLn('AsTyped: ', Cardinality(asTyped):14, CountUnique(asTyped):10); WriteLn('Normalized: ', Cardinality(normalized):11, CountUnique(normalized):10); keysCount := 1; ToArray(asTyped, keys, keysCount); FOR i := 1 TO keysCount DO BEGIN isCount := Count(asTyped, keys[i]); shouldCount := Count(normalized, UpCase(keys[i])); IF (isCount <> shouldCount) THEN BEGIN WriteLn(keys[i], ' ', isCount, ' ', shouldCount); END; (* IF *) END; (* FOR *) END. (* CheckStyle *)