text
stringlengths
14
6.51M
unit uOptimizers; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} //**************************************************************************// // Данный исходный код является составной частью системы МВТУ-4 // // Программисты: Тимофеев К.А., Ходаковский В.В. // //**************************************************************************// interface //***************************************************************************// // Блоки для оптимизации параметров модели по зпдпнным критериям // //***************************************************************************// uses Classes, MBTYArrays, DataTypes, SysUtils, abstract_im_interface, RunObjts, Math, mbty_std_consts, OptType, InterfaceUnit; const {$IFDEF ENG} txtOptParametersValue = 'Optimized parameters = '; txtOptCriteria = ' , optimization criteries = '; txtYMinDefineError = 'Parameter ymin has dimension lower than x0'; txtYMaxDefineError = 'Parameter ymax has dimension lower than x0'; txtYAbsErrorDefineError = 'Parameter yabserror has dimension lower than x0'; txtUMaxErrorDefineError = 'Parameter umax has dimension lower than umin'; txt_opt_MaxFunEval = 'Exceeded the maximum number of function evaluations'; txt_Opt_InitVal = 'Error initializing the optimization algorithm'; txt_opt_Eps = 'Error optimization convergence'; {$ELSE} txtOptParametersValue = 'Параметры = '; txtOptCriteria = ' , Критерии = '; txtYMinDefineError = 'Параметр ymin имеет размерность меньше чем x0'; txtYMaxDefineError = 'Параметр ymax имеет размерность меньше чем x0'; txtYAbsErrorDefineError = 'Параметр yabserror имеет размерность меньше чем x0'; txtUMaxErrorDefineError = 'Параметр umax имеет размерность меньше чем umin'; txt_opt_MaxFunEval = 'Превышено максимальное число вычислений функции'; txt_Opt_InitVal = 'Ошибка инициализации алгоритма оптимизации'; txt_opt_Eps = 'Ошибка оптимизаци по сходимости'; {$ENDIF} //------------------------------------------------------------------------------------------------- type // Оптимизация модели TOptimize_new = class(TRunObject) protected // ВХОДНЫЕ ДАННЫЕ // Тип суммарного критерия оптимизации (Аддитивный, квадратичный, минимаксный, мультипликативный) usumtype : integer; // Максимальное к-во итераций при оптимизации (задается) maxiter : NativeInt; // Метод оптимизации (Поиск-2, Поиск-4, Симплекс) optmethod : NativeInt; // Режим оптимизации параметров (по полному перех. проц., в динамике с ост., в динамике непр.) optmode : NativeInt; // Периодичность анализа критериев оптимизации при расчёте в динамике (задается, с) optstep : double; // Начальные приближения выходов блоков (задается) x0 : TExtArray; // Минимальные значения выходов блока (задается) ymin : TExtArray; // Максимальные значения выходов блока (задается) ymax : TExtArray; // Абсолютная точность подбора выходов блока (задается) yabserror : TExtArray; // Начальные приращения выходов блока (задается) dparams : TExtArray; // Минимальные значения входных критериев оптимизации (задается) umin : TExtArray; // Максимальные значения входных критериев оптимизации (задается) umax : TExtArray; // ПЕРЕМЕННЫЕ МОДУЛЯ // Код ошибки ErrorNum : NativeInt; // Количество выходов блока (параметров оптимизации) NParam : integer; // Количество входов блока (критериев оптимизации) NQual : integer; // Локальное время ??? localtime : double; // Массив выходов блока (параметров оптимизации) yparams : array of realtype; // Массив входов блока (критериев оптимизации) uinputs : array of realtype; // Текущее приращение выходов блока (параметров оптимизации) dPar : array of realtype; // Класс метода оптимизации OptimizeMethod : TOptMethod; // Флаг текущего состояния алгоритма оптимизации otp_step_position : integer; // Флаг остановки оптимизации StopOpt : integer; oldstopopt : integer; oldoldStopOpt : NativeInt; // Ограничения выходов блока PROCEDURE DOSETOUTS(X, FX : PExtArr; var ner : NativeInt); // Получаем качество ??? PROCEDURE DOGETQUAL(X, FX : PExtArr; var ner : NativeInt); // Вывод информации о подобранных параметрах оптимизации и текущих значениях критериев оптимизации PROCEDURE DOOUT(X, FX : PExtArr; N, M, NFE : integer; var stepout : integer); // Сравнение F(X1) и F(X2) PROCEDURE DOCOMPQUAL(X, Y, FX, FY : PExtArr; N : integer; M : integer; var IC : integer); public // Конструктор constructor Create(Owner : TObject); override; // Деструктор destructor Destroy; override; // Информационная функция блока (Как блок должен сортироваться) 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; // Чтение точки рестарта блока function RestartLoad(Stream : TStream; Count : integer; const TimeShift : double) : boolean; override; // Запись точки рестарта блока procedure RestartSave(Stream : TStream); override; end; //############################################################################## implementation //############################################################################## uses UPoisk2, UPoisk4, USimp, UGradients, UGradients2; //------------------------------------------------------------------------------------------------- constructor TOptimize_new.Create; begin inherited; x0:=TExtArray.Create(1); ymin:=TExtArray.Create(1); ymax:=TExtArray.Create(1); yabserror:=TExtArray.Create(1); dparams:=TExtArray.Create(1); umin:=TExtArray.Create(1); umax:=TExtArray.Create(1); end; //------------------------------------------------------------------------------------------------- destructor TOptimize_new.Destroy; begin inherited; x0.Free; ymin.Free; ymax.Free; yabserror.Free; dparams.Free; umin.Free; umax.Free; end; //------------------------------------------------------------------------------------------------- function TOptimize_new.GetParamID; begin Result:=inherited GetParamId(ParamName, DataType, IsConst); if Result = -1 then begin if StrEqu(ParamName,'x0') then begin // Начальное приближение выходов блоков Result:=NativeInt(x0); DataType:=dtDoubleArray; end else if StrEqu(ParamName,'ymin') then begin // Минимальное значение выходов блока Result:=NativeInt(ymin); DataType:=dtDoubleArray; end else if StrEqu(ParamName,'ymax') then begin // Максимальное значение выходов блока Result:=NativeInt(ymax); DataType:=dtDoubleArray; end else if StrEqu(ParamName,'yabserror') then begin // Абсолютная точность подбора значений выходов Result:=NativeInt(yabserror); DataType:=dtDoubleArray; end else if StrEqu(ParamName,'dparams') then begin // Начальное приращение выходов Result:=NativeInt(dparams); DataType:=dtDoubleArray; end else if StrEqu(ParamName,'umin') then begin // Минимальные значения входных критериев оптимизации Result:=NativeInt(umin); DataType:=dtDoubleArray; end else if StrEqu(ParamName,'umax') then begin // Максимальные значения входных критериев оптимизации Result:=NativeInt(umax); DataType:=dtDoubleArray; end else if StrEqu(ParamName,'usumtype') then begin // Тип суммарного критерия оптимизации Result:=NativeInt(@usumtype); DataType:=dtInteger; end else if StrEqu(ParamName,'maxiter') then begin // Максимальное количество повторных моделирований при расчёте по полному переходному процессу Result:=NativeInt(@maxiter); DataType:=dtInteger; end else if StrEqu(ParamName,'optmethod') then begin // Метод оптимизации Result:=NativeInt(@optmethod); DataType:=dtInteger; end else if StrEqu(ParamName,'optmode') then begin // Режим оптимизации параметров Result:=NativeInt(@optmode); DataType:=dtInteger; end else if StrEqu(ParamName,'optstep') then begin // Периодичность анализа критериев оптимизации при расчёте в динамике, сек Result:=NativeInt(@optstep); DataType:=dtDouble; end end end; //------------------------------------------------------------------------------------------------- function TOptimize_new.InfoFunc; begin Result:=0; case Action of i_GetInit: Result:=1; i_GetCount: begin cY[0]:=x0.Count; cU[0]:=umin.Count; end; i_GetBlockType: Result := t_fun; // Функциональный блок i_GetPropErr: begin // Проверка размерностей if ymin.Count < x0.Count then begin // Ошибка 'Параметр ymin имеет размерность меньше чем x0' ErrorEvent(txtYMinDefineError, msError, VisualObject); Result:=r_Fail; end; if ymax.Count < x0.Count then begin // Ошибка 'Параметр ymax имеет размерность меньше чем x0' ErrorEvent(txtYMaxDefineError, msError, VisualObject); Result:=r_Fail; end; if yabserror.Count < x0.Count then begin // Ошибка 'Параметр yabserror имеет размерность меньше чем x0' ErrorEvent(txtYAbsErrorDefineError, msError, VisualObject); Result:=r_Fail; end; if umax.Count < umin.Count then begin // Ошибка 'Параметр umax имеет размерность меньше чем umin' ErrorEvent(txtUMaxErrorDefineError, msError, VisualObject); Result:=r_Fail; end; end; else Result := inherited InfoFunc(Action, aParameter); end; end; //------------------------------------------------------------------------------------------------- function TOptimize_new.RunFunc(var at,h : RealType;Action:Integer):NativeInt; var i : Integer; tmp_time,tmpx: double; label do_opt_step,precise_step; begin Result:=0; case Action of f_InitObjects: begin NParam:=cY[0]; NQual:=cU[0]; SetLength(dPar,NParam); SetLength(yparams, NParam); SetLength(uinputs, NQual + 1); ErrorNum:=0; StopOpt:=0; oldstopopt:=0; oldoldStopOpt:=0; otp_step_position:=0; if OptimizeMethod <> nil then OptimizeMethod.Free; case optmethod of // ПОИСК-2 0: OptimizeMethod:=TPOISK2.Create; // ПОИСК-4 1: OptimizeMethod:=TPOISK4.Create; // Симплекс 2: OptimizeMethod:=TSIMPS.Create; // Метод наискорейшего спуска 3: OptimizeMethod:=TGradients.Create; // Метод сопряженных градиентов 4: OptimizeMethod:=TGradients2.Create; end; OptimizeMethod.SETOUTS:=DOSETOUTS; OptimizeMethod.GETQUAL:=DOGETQUAL; OptimizeMethod.OUT2:=DOOUT; OptimizeMethod.COMPQUAL:=DOCOMPQUAL; OptimizeMethod.InitMem(NParam,NQual); end; f_Stop: begin if OptimizeMethod <> nil then OptimizeMethod.Free; OptimizeMethod:=nil; end; f_InitState: begin tmp_time:=0; // Установка начальных значений параметров оптимизации задачи tmpx:=0; for i:=0 to NParam-1 do begin // Начальные значения yparams[i]:=x0.Arr^[i]; Y[0].Arr^[i]:=x0.Arr^[i]; // Начальные приращения (по умолчанию = 0.1*допустимый интервал) if i < dparams.Count then tmpx:=dparams.Arr^[i]; if tmpx = 0 then dPar[i]:=0.1*(ymax.Arr^[i]-ymin.Arr^[i]) else dPar[i]:=tmpx; end; //Начальные критерии качества for i:=0 to NQual-1 do uinputs[i]:=U[0].Arr^[i]; //Если стоит режим работы по полной выборке, то выставляем флаг, что нам надо запомнить стартовое состояние if optmode = 0 then begin ModelODEVars.fSaveModelState:=True; goto do_opt_step; end; //Уточнение шага дискретизации if (optmode <> 0) and ModelODEVars.fPreciseSrcStep and (optstep > 0) then begin ModelODEVars.fsetstep:=True; ModelODEVars.newstep:=min(ModelODEVars.newstep,optstep); end; end; f_EndTimeTask: if optmode = 0 then begin //В режиме оптимизации по полному времени процесса, мы делаем следующий вызов конечного автомата оптимизации тут goto do_opt_step; end; f_GoodStep: if optmode <> 0 then begin //Блок срабатывания с заданным шагом tmp_time:=localtime + h; if tmp_time > optstep then begin if optstep > 0 then tmp_time:=tmp_time - Int(tmp_time/optstep)*optstep else tmp_time:=0; // ---- //############################################################################## do_opt_step: // Принудительное завершение оптимизации if (optmode = 0) and (StopOpt = 1) then exit; //Вызов собственно оптимизации OptimizeMethod.ExecuteStep( @yparams[0], // Массив параметров @uinputs[0], // Массив критериев NParam, // Количество параметров NQual, // Количество критериев @dPar[0], // Текущее приращение параметра оптимизации yabserror.Arr, // Точность подбора выходных параметров оптимизации maxiter, // Максимальное к-во итераций при оптимизации ymin.Arr, // Минимальное значение параметра оптимизации ymax.Arr, // Максимальное значение параметра оптимизации ErrorNum, // Код ошибки StopOpt, // Флаг конца оптимизации otp_step_position); // Состояние алгоритма оптимизации //Выдаём диагностические сообщения об ошибках оптимизации if ErrorNum <> 0 then case ErrorNum of // Ошибка 'Превышено максимальное число вычислений функции' er_opt_MaxFunEval: ErrorEvent(txt_opt_MaxFunEval + ' (' + IntToStr(maxiter) + ') time='+FloatToStr(at),msError,VisualObject); // превышено максимальное число вычислений функции // Ошибка 'Ошибка инициализации алгоритма оптимизации' er_Opt_InitVal: ErrorEvent(txt_Opt_InitVal+' time='+FloatToStr(at),msError,VisualObject); // Ошибка инициализации алгоритма оптимизации // Ошибка 'Ошибка оптимизаци по сходимости' er_opt_Eps: ErrorEvent(txt_opt_Eps+' time='+FloatToStr(at),msError,VisualObject); // Ошибка оптимизаци по сходимости end; //В режиме непрерывной динамической оптимизации сбрасываем флаг //остановки оптимизации если мы остановились и сделали ещё один шаг !!! if optmode = 2 then begin if (StopOpt = 1) and (oldstopopt = 1) and (oldoldStopOpt = 1) then StopOpt:=0; oldoldStopOpt:=oldstopopt; oldstopopt:=StopOpt; end else //В полнои режиме оптимизации - выставляем флаг повтора модели, пока она у нас не уложится if optmode = 0 then begin //Если в процессе есть ошибки - то остановка процесса оптимизации, чтобы остановить процесс if ErrorNum <> 0 then StopOpt:=1; //Выставляем флаг остановки ModelODEVars.fStartAgain:=StopOpt = 0; exit; end; end; //Блок срабатывания с заданным шагом //Запоминание счётчика времени localtime:=tmp_time; //-------- goto precise_step; end; //############################################################################## //Уточнение шага для более точного выставления времени оптимизации f_UpdateOuts: if (optmode <> 0) then begin precise_step: if ModelODEVars.fPreciseSrcStep and (optstep > 0) and (optstep > localtime) then begin ModelODEVars.fsetstep:=True; ModelODEVars.newstep:=min(min(ModelODEVars.newstep,optstep - localtime),optstep); end; end; end end; //------------------------------------------------------------------------------------------------- function TOptimize_new.RestartLoad(Stream: TStream;Count: integer;const TimeShift:double):boolean; var oldoptmode, oldoptmethod, oldUCount, oldYCount: integer; begin //Для режима работы 0 (с циклическим перезапуском модели) не загружаем рестарт !!! if optmode = 0 then begin Result:=True; exit; end else begin //Загружаем входы-выходы Result:=inherited RestartLoad(Stream,Count,TimeShift); //Загружаем состояние алгоритма оптимизации Stream.Read(oldoptmode,SizeOfInt); Stream.Read(oldoptmethod,SizeOfInt); Stream.Read(oldUCount,SizeOfInt); Stream.Read(oldYCount,SizeOfInt); Stream.Read(StopOpt,SizeOfInt); Stream.Read(localtime,SizeOfDouble); //Проверяем не изменились ли настройки так, что состояние алгоритма оптимизации нельзя загрузить if (oldoptmode = optmode) and (oldoptmethod = optmethod) and (oldUCount = U[0].Count) and (oldYCount = Y[0].Count) then begin Stream.Read(otp_step_position,SizeOfInt); Stream.Read(yparams[0],Length(yparams)*SizeOfDouble); Stream.Read(uinputs[0],Length(uinputs)*SizeOfDouble); Stream.Read(dPar[0],Length(dPar)*SizeOfDouble); Result:=OptimizeMethod.RestartLoad(Stream,Count,TimeShift); end; end; end; //------------------------------------------------------------------------------------------------- procedure TOptimize_new.RestartSave(Stream: TStream); begin //Для режима работы 0 (с циклическим перезапуском модели) не сохраняем рестарт !!! if optmode <> 0 then begin //Сохраняем входы-выходы inherited RestartSave(Stream); //Сохраняем состояние алгоритма оптимизации Stream.Write(optmode,SizeOfInt); Stream.Write(optmethod,SizeOfInt); Stream.Write(U[0].Count,SizeOfInt); Stream.Write(Y[0].Count,SizeOfInt); Stream.Write(StopOpt,SizeOfInt); Stream.Write(otp_step_position,SizeOfInt); Stream.Write(yparams[0],Length(yparams)*SizeOfDouble); Stream.Write(uinputs[0],Length(uinputs)*SizeOfDouble); Stream.Write(dPar[0],Length(dPar)*SizeOfDouble); Stream.Write(localtime,SizeOfDouble); //Сохраняем внутреннее состояние алгоритма оптимизации OptimizeMethod.RestartSave(Stream); end; end; //------------------------------------------------------------------------------------------------- PROCEDURE TOptimize_new.DOSETOUTS; var i: integer; begin //Выставляем выходы for i:=0 to NParam-1 do begin if (X[i] < ymin.Arr^[i]) then X[i]:=ymin.Arr^[i]; if (X[i] > ymax.Arr^[i]) then X[i]:=ymax.Arr^[i]; Y[0].Arr^[i]:=X[i]; end; end; //------------------------------------------------------------------------------------------------- PROCEDURE TOptimize_new.DOGETQUAL; const fmax=1.0e30; var // Номер параметра i : integer; // Суммарное качество s : realtype; // Качество q : realtype; label finish; begin //Получаем качество if StopOpt = 1 then begin FX[NQual]:=0; ///fmax; - вообще странная это цифра... С ней алгоритм ПОИСК-2 не останавливается в принципе... exit end; ner:=0; if ner > 0 then goto finish; // Процедура сворачивания векторного критерия в скалярный (FX[NParam]) } for i:=0 to NQual-1 do FX[i]:=U[0].Arr^[i]; s:=0; for i:=0 to NQual-1 do begin if FX[i]>umax.Arr^[i] then q:=(FX[i]-umax.Arr^[i])/(umax.Arr^[i]-umin.Arr^[i]) else if FX[i] < umin.Arr^[i] then q:=(umin.Arr^[i]-FX[i])/(umax.Arr^[i]-umin.Arr^[i]) else q:=0; case usumtype of 0: s:=s+q; // Аддитивный 1: s:=s+q*q; // Квадратичный 2: if q>s then s:=q; // Минимаксный 3: s:=s+ln(q+1); // Мультипликативный end; end; case usumtype of 0: FX[NQual]:=s/NQual; // Аддитивный 1: FX[NQual]:=sqrt(s/NQual); // Квадратичный 2: FX[NQual]:=s; // Минимаксный 3: FX[NQual]:=exp(s/NQual)-1; // Мультипликативный end; finish: if (ner>0) and (ner<1000) then begin FX[NQual] := 0; /// fmax; Это работает странно ... поэтому поставил 0 тут if (StopOpt = -1) then StopOpt:=1 end; { else if tOptAlg = 3 then SHTRAF(X,FX); // Это я не знаю откуда осталось. В 3.7 оно было забанено } end; //------------------------------------------------------------------------------------------------- PROCEDURE TOptimize_new.DOOUT; begin //Выводим информацию о подобранных параметрах оптимизации и текущих значениях критериев оптимизации ErrorEvent(txtOptParametersValue + GetStrValue(Y[0], dtDoubleArray) + txtOptCriteria + GetStrValue(U[0], dtDoubleArray) + ' Качество: ' + FloatToStr(FX[M]) + ' Состояние: ' + IntToStr(stepout) + ' Итерация: ' + IntToStr(NFE), msInfo, VisualObject); end; //------------------------------------------------------------------------------------------------- PROCEDURE TOptimize_new.DOCOMPQUAL; begin if (StopOpt = 1) then IC:=3 else if FY[NQual] < FX[NQual] then IC:=2 // F(X2) < F(X1) else IC:=1; // F(X2) >= F(X1) // TODO: Никогда не сработает??? if (FY[NQual]=0) then StopOpt := 1; end; //------------------------------------------------------------------------------------------------- end.
unit cPedidoDeCompra; interface type PedidodeCompra = class (TObject) protected codPedCompra : integer; dataPedCompra : TDateTime; valTotPedCompra : real; statusCompra : string; public Constructor Create (codPedCompra : integer; dataPedCompra : TDateTime; valTotPedCompra : real; statusCompra:string); Procedure setcodPedCompra (codPedCompra:integer); Function getcodPedCompra:integer; Procedure setdataPedCompra(dataPedCompra:TDateTime); Function getdataPedCompra:TDateTime; Procedure setvalTotPedCompra (valTotPedCompra:real); Function getValTotPedCompra:real; Procedure setstatusCompra (statusCompra:string); Function getstatusCompra:string; end; implementation Constructor PedidodeCompra.Create(codPedCompra:integer; dataPedCompra:TDateTime; valTotPedCompra:real; statusCompra:string); begin self.codPedCompra := codPedCompra; self.dataPedCompra := dataPedCompra; self.valTotPedCompra := valTotPedCompra; self.statusCompra := statusCompra; end; Procedure PedidodeCompra.setcodPedCompra(codPedCompra:integer); begin self.codPedCompra := codPedCompra; end; Function PedidodeCompra.getcodPedCompra:integer; begin result := codPedCompra; end; Procedure PedidodeCompra.setdataPedCompra(dataPedCompra:TDateTime); begin self.dataPedCompra := dataPedCompra; end; Function PedidodeCompra.getdataPedCompra:TDateTime; begin result := dataPedCompra; end; Procedure PedidodeCompra.setvalTotPedCompra(valTotPedCompra:real); begin self.valTotPedCompra := valTotPedCompra; end; Function PedidodeCompra.getValTotPedCompra:real; begin result := valTotPedCompra; end; Procedure PedidodeCompra.setstatusCompra(statusCompra:string); begin self.statusCompra := statusCompra; end; Function PedidodeCompra.getstatusCompra:string; begin result := statusCompra; 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 8 O(N2) Dfs Method } program ClosedSet; const MaxN = 50; var N : Integer; A : array [1 .. MaxN, 1 .. MaxN] of Integer; M : array [1 .. MaxN] of Boolean; I, J : Integer; F : Text; procedure Add (X : Integer); var I : Integer; begin M[X] := True; for I := 1 to N do if M[I] then begin if not M[A[X, I]] then Add(A[X, I]); if not M[A[I, X]] then Add(A[I, X]); end; end; begin Assign(F, 'input.txt'); Reset(F); Readln(F, N); for I := 1 to N do begin for J := 1 to N do Read(F, A[I, J]); Readln(F); end; Read(F, I); while I <> 0 do begin Add(I); Read(F, I); end; Close(F); Assign(F, 'output.txt'); ReWrite(F); for I := 1 to N do if M[I] then Writeln(F, I); Close(F); end.
PROGRAM Penney; TYPE CoinToss = (heads, tails); Sequence = array [1..3] of CoinToss; Player = record bet: Sequence; score: integer; end; VAR Human, Computer: Player; Rounds, Count: integer; Function TossCoin: CoinToss; { Returns heads or tails at random } Begin if random(2) = 1 then TossCoin := Heads else TossCoin := tails End; Procedure PutToss(toss: CoinToss); { Outputs heads or tails as a letter } Begin if toss = heads then write('H') else write('T') End; Function GetToss: CoinToss; { Reads H or T from the keyboard in either lettercase } var c: char; Begin { Keep reading characters until we get an appropriate letter } repeat read(c) until c in ['H', 'h', 'T', 't']; { Interpret the letter } if c in ['H', 'h'] then GetToss := heads else GetToss := tails End; Procedure ShowSequence(tosses: Sequence); { Outputs three coin tosses at once } Var i: integer; Begin for i := 1 to 3 do PutToss(tosses[i]) End; Procedure ReadSequence(var tosses: Sequence); { Accepts three coin tosses from the keyboard } Var i: integer; Begin { Get the 3 letters } for i := 1 to 3 do tosses[i] := GetToss; { Ignore the rest of the line } readln End; Function Optimum(opponent: Sequence): Sequence; { Generates the optimum sequence against an opponent } Begin case opponent[2] of heads: Optimum[1] := tails; tails: Optimum[1] := heads end; Optimum[2] := opponent[1]; Optimum[3] := opponent[2] End; Function RandomSequence: Sequence; { Generates three random coin tosses } Var i: integer; Begin for i := 1 to 3 do RandomSequence[i] := TossCoin End; Function Match(first, second: Sequence): Boolean; { Detects whether a sequence of tosses matches another } Var different: boolean; i: integer; Begin different := false; i := 1; while (i <= 3) and not different do begin if not (first[i] = second[i]) then different := true; i := i + 1 end; Match := not different End; Procedure PlayRound(var human, computer: Player); { Shows coin tosses and announces the winner } Var { We only ever need to store the 3 most recent tosses in memory. } tosses: Sequence; Begin { Start with the first three tosses } write('Tossing the coin: '); tosses := RandomSequence; ShowSequence(tosses); { Keep tossing the coin until there is a winner. } while not (Match(human.bet, tosses) or Match(computer.bet, tosses)) do begin tosses[1] := tosses[2]; tosses[2] := tosses[3]; tosses[3] := TossCoin; PutToss(tosses[3]) end; { Update the winner's score and announce the winner } writeln; writeln; if Match(human.bet, tosses) then begin writeln('Congratulations! You won this round.'); human.score := human.score + 1; writeln('Your new score is ', human.score, '.') end else begin writeln('Yay, I won this round!'); computer.score := computer.score + 1; writeln('My new score is ', computer.score, '.') end End; { Main Algorithm } BEGIN { Welcome the player } writeln('Welcome to Penney''s game!'); writeln; write('How many rounds would you like to play? '); readln(Rounds); writeln; writeln('Ok, let''s play ', Rounds, ' rounds.'); { Start the game } randomize; Human.score := 0; Computer.score := 0; for Count := 1 to Rounds do begin writeln; writeln('*** Round #', Count, ' ***'); writeln; { Choose someone randomly to pick the first sequence } if TossCoin = heads then begin write('I''ll pick first this time.'); Computer.bet := RandomSequence; write(' My sequence is '); ShowSequence(Computer.bet); writeln('.'); repeat write('What sequence do you want? '); ReadSequence(Human.bet); if Match(Human.bet, Computer.bet) then writeln('Hey, that''s my sequence! Think for yourself!') until not Match(Human.bet, Computer.bet); ShowSequence(Human.bet); writeln(', huh? Sounds ok to me.') end else begin write('You pick first this time. Enter 3 letters H or T: '); ReadSequence(Human.bet); Computer.bet := Optimum(Human.bet); write('Ok, so you picked '); ShowSequence(Human.bet); writeln; write('My sequence will be '); ShowSequence(Computer.bet); writeln end; { Then we can actually play the round } writeln('Let''s go!'); writeln; PlayRound(Human, Computer); writeln; writeln('Press ENTER to go on...'); readln end; { All the rounds are finished; time to decide who won } writeln; writeln('*** End Result ***'); writeln; if Human.score > Computer.score then writeln('Congratulations! You won!') else if Computer.score > Human.score then writeln('Hooray! I won') else writeln('Cool, we tied.'); writeln; writeln('Press ENTER to finish.'); readln END.
//****************************************************************************** //*** LUA SCRIPT DELPHI UTILITIES *** //*** *** //*** (c) 2006 Jean-Fran輟is Goulet, Massimo Magnano, Kuma *** //*** *** //*** *** //****************************************************************************** // File : LuaUtils.pas // // Description : Useful functions to work with Lua in Delphi. // //****************************************************************************** //** See Copyright Notice in lua.h //Revision 1.2 // MaxM Adds : // GetCurrentFuncName, LuaSetTablePropertyFuncs // //Revision 1.1 // MaxM Adds : // LuaPCallFunction // //Revision 1.0 // MaxM Adds : // LuaPushVariant // LuaToVariant // LuaGetTableInteger, LuaGet\SetTableTMethod // LuaLoadBufferFromFile // Solved Bugs : Stack problem in LuaProcessTableName // LuaToInteger why Round?, Trunc is better unit LuaUtils; interface uses SysUtils, Classes, ComCtrls, luaconf, lua, lualib, lauxlib, Variants; const ERR_Script ='Script Error : '; type TOnLuaStdout = procedure (S: PChar; N: Integer); TOnLuaStdoutEx = procedure (F, S: PChar; L, N: Integer); ELuaException = class(Exception) Title: string; Line: Integer; Msg: string; constructor Create(Title: string; Line: Integer; Msg: string); end; TVariantArray =array of Variant; PVariantArray =^TVariantArray; function Quote(const Str: string): string; function Dequote(const QuotedStr: string): string; function lua_print(L: Plua_State): Integer; cdecl; function lua_printex(L: Plua_State): Integer; cdecl; function lua_io_write(L: Plua_State): Integer; cdecl; function lua_io_writeex(L: Plua_State): Integer; cdecl; function LuaToBoolean(L: PLua_State; Index: Integer): Boolean; procedure LuaPushBoolean(L: PLua_State; B: Boolean); function LuaToInteger(L: PLua_State; Index: Integer): Integer; procedure LuaPushInteger(L: PLua_State; N: Integer); function LuaToVariant(L: Plua_State; Index: Integer): Variant; procedure LuaPushVariant(L: Plua_State; N: Variant); function LuaToString(L: PLua_State; Index: Integer): string; procedure LuaPushString(L: PLua_State; const S: string); function LuaIncIndex(L: Plua_State; Index: Integer): Integer; function LuaAbsIndex(L: Plua_State; Index: Integer): Integer; procedure LuaGetTable(L: Plua_State; TableIndex: Integer; const Key: string); function LuaGetTableBoolean(L: Plua_State; TableIndex: Integer; const Key: string): Boolean; function LuaGetTableNumber(L: Plua_State; TableIndex: Integer; const Key: string): Double; function LuaGetTableInteger(L: Plua_State; TableIndex: Integer; const Key: string): Integer; function LuaGetTableString(L: Plua_State; TableIndex: Integer; const Key: string): string; function LuaGetTableFunction(L: Plua_State; TableIndex: Integer; const Key: string): lua_CFunction; function LuaGetTableLightUserData(L: Plua_State; TableIndex: Integer; const Key: string): Pointer; function LuaGetTableTMethod(L: Plua_State; TableIndex: Integer; const Key: string): TMethod; procedure LuaRawGetTable(L: Plua_State; TableIndex: Integer; const Key: string); function LuaRawGetTableBoolean(L: Plua_State; TableIndex: Integer; const Key: string): Boolean; function LuaRawGetTableNumber(L: Plua_State; TableIndex: Integer; const Key: string): Double; function LuaRawGetTableString(L: Plua_State; TableIndex: Integer; const Key: string): string; function LuaRawGetTableFunction(L: Plua_State; TableIndex: Integer; const Key: string): lua_CFunction; function LuaRawGetTableLightUserData(L: Plua_State; TableIndex: Integer; const Key: string): Pointer; procedure LuaSetTableValue(L: PLua_State; TableIndex: Integer; const Key: string; ValueIndex: Integer); procedure LuaSetTableNil(L: Plua_State; TableIndex: Integer; const Key: string); procedure LuaSetTableBoolean(L: Plua_State; TableIndex: Integer; const Key: string; B: Boolean); procedure LuaSetTableNumber(L: Plua_State; TableIndex: Integer; const Key: string; N: Double); procedure LuaSetTableString(L: Plua_State; TableIndex: Integer; const Key: string; S: string); procedure LuaSetTableFunction(L: Plua_State; TableIndex: Integer; const Key: string; F: lua_CFunction); procedure LuaSetTableLightUserData(L: Plua_State; TableIndex: Integer; const Key: string; P: Pointer); procedure LuaSetTableTMethod(L: Plua_State; TableIndex: Integer; const Key: string; M: TMethod); procedure LuaSetTableClear(L: Plua_State; TableIndex: Integer); procedure LuaSetTablePropertyFuncs(L: PLua_State; TableIndex: Integer; ReadFunc: lua_CFunction; WriteFunc: lua_CFunction =nil); procedure LuaRawSetTableValue(L: PLua_State; TableIndex: Integer; const Key: string; ValueIndex: Integer); procedure LuaRawSetTableNil(L: Plua_State; TableIndex: Integer; const Key: string); procedure LuaRawSetTableBoolean(L: Plua_State; TableIndex: Integer; const Key: string; B: Boolean); procedure LuaRawSetTableNumber(L: Plua_State; TableIndex: Integer; const Key: string; N: Double); procedure LuaRawSetTableString(L: Plua_State; TableIndex: Integer; const Key: string; S: string); procedure LuaRawSetTableFunction(L: Plua_State; TableIndex: Integer; const Key: string; F: lua_CFunction); procedure LuaRawSetTableLightUserData(L: Plua_State; TableIndex: Integer; const Key: string; P: Pointer); procedure LuaRawSetTableClear(L: Plua_State; TableIndex: Integer); function LuaGetMetaFunction(L: Plua_State; Index: Integer; Key: string): lua_CFunction; procedure LuaSetMetaFunction(L: Plua_State; Index: Integer; Key: string; F: lua_CFunction); procedure LuaShowStack(L: Plua_State; Caption: string = ''); function LuaStackToStr(L: Plua_State; Index: Integer; MaxTable: Integer = -1; SubTableMax: Integer = 99): string; procedure LuaRegisterCustom(L: PLua_State; TableIndex: Integer; const Name: PChar; F: lua_CFunction); procedure LuaRegister(L: Plua_State; const Name: PChar; F: lua_CFunction); procedure LuaRegisterMetatable(L: Plua_State; const Name: PChar; F: lua_CFunction); procedure LuaRegisterProperty(L: PLua_State; const Name: PChar; ReadFunc, WriteFunc: lua_CFunction); procedure LuaStackToStrings(L: Plua_State; Lines: TStrings; MaxTable: Integer = -1; SubTableMax: Integer = 99); procedure LuaLocalToStrings(L: Plua_State; Lines: TStrings; MaxTable: Integer = -1; Level: Integer = 0; SubTableMax: Integer = 99); procedure LuaGlobalToStrings(L: PLua_State; Lines: TStrings; MaxTable: Integer = -1; SubTableMax: Integer = 99); procedure LuaTableToStrings(L: Plua_State; Index: Integer; Lines: TStrings; MaxTable: Integer = -1; SubTableMax: Integer = 99); procedure LuaTableToTreeView(L: Plua_State; Index: Integer; TV: TTreeView; MaxTable: Integer = -1; SubTableMax: Integer = 99); function LuaGetIdentValue(L: Plua_State; Ident: string; MaxTable: Integer = -1): string; procedure LuaSetIdentValue(L: Plua_State; Ident, Value: string; MaxTable: Integer = -1); procedure LuaLoadBuffer(L: Plua_State; const Code: string; const Name: string); procedure LuaLoadBufferFromFile(L: Plua_State; const Filename: string; const Name: string); procedure LuaPCall(L: Plua_State; NArgs, NResults, ErrFunc: Integer); function LuaPCallFunction(L: Plua_State; FunctionName :String; const Args: array of Variant; Results : PVariantArray; ErrFunc: Integer=0; NResults :Integer=LUA_MULTRET):Integer; procedure LuaError(L: Plua_State; const Msg: string); procedure LuaErrorFmt(L: Plua_State; const Fmt: string; const Args: array of Const); function LuaDataStrToStrings(const TableStr: string; Strings: TStrings): string; function LuaDoFile(L: Plua_State): Integer; cdecl; function LuaGetCurrentFuncName(L: Plua_State) :String; function Lua_VoidFunc(L: Plua_State): Integer; cdecl; const LuaGlobalVariableStr = '[LUA_GLOBALSINDEX]'; var OnLuaStdoutEx: TOnLuaStdoutEx; OnLuaStdout: TOnLuaStdout; DefaultMaxTable: Integer; SubTableCount: Integer; implementation uses Dialogs; const QuoteStr = '"'; CR = #$0D; LF = #$0A; CRLF = CR + LF; function Quote(const Str: string): string; begin Result := AnsiQuotedStr(Str, QuoteStr); end; function Dequote(const QuotedStr: string): string; begin Result := AnsiDequotedStr(QuotedStr, QuoteStr); end; function fwriteex(F, S: PChar; Un, Len: Integer; L, Dummy: Integer): Integer; var Size: Integer; begin Size := Un * Len; if (Assigned(OnLuaStdoutEx)) then OnLuaStdoutEx(F, S, L, Size); Result := Size; end; function fwrite(S: PChar; Un, Len: Integer; Dummy: Integer): Integer; var Size: Integer; begin Size := Un * Len; if (Assigned(OnLuaStdout)) then OnLuaStdout(S, Size); Result := Size; end; function fputsex(const F, S: String; L, Dummy: Integer): Integer; begin Result := fwriteex(PChar(F), PChar(S), SizeOf(Char), L, Length(S), Dummy); end; function fputs(const S: string; Dummy: Integer): Integer; begin Result := fwrite(PChar(S), SizeOf(Char), Length(S), Dummy); end; function lua_printex(L: Plua_State): Integer; cdecl; const TAB = #$08; NL = #$0A; stdout = 0; var N, I: Integer; S: PChar; Debug: lua_Debug; AR: Plua_Debug; begin AR := @Debug; lua_getstack(L, 1, AR); {* stack informations *} lua_getinfo(L, 'Snlu', AR); {* debug informations *} N := lua_gettop(L); (* number of arguments *) lua_getglobal(L, 'tostring'); for I := 1 to N do begin lua_pushvalue(L, -1); (* function to be called *) lua_pushvalue(L, i); (* value to print *) lua_call(L, 1, 1); S := lua_tostring(L, -1); (* get result *) if (S = nil) then begin Result := luaL_error(L, '`tostring'' must return a string to `print'''); Exit; end; if (I > 1) then fputs(TAB, stdout); fputsex(AR.source, S, AR.currentline, stdout); lua_pop(L, 1); (* pop result *) end; fputsex(AR.source, NL, AR.currentline, stdout); Result := 0; end; function lua_print(L: Plua_State): Integer; cdecl; const TAB = #$08; NL = #$0A; stdout = 0; var N, I: Integer; S: PChar; begin N := lua_gettop(L); (* number of arguments *) lua_getglobal(L, 'tostring'); for I := 1 to N do begin lua_pushvalue(L, -1); (* function to be called *) lua_pushvalue(L, i); (* value to print *) lua_call(L, 1, 1); S := lua_tostring(L, -1); (* get result *) if (S = nil) then begin Result := luaL_error(L, '`tostring'' must return a string to `print'''); Exit; end; if (I > 1) then fputs(TAB, stdout); fputs(S, stdout); lua_pop(L, 1); (* pop result *) end; fputs(NL, stdout); Result := 0; end; function lua_io_writeex(L: Plua_State): Integer; cdecl; function pushresult(L: Plua_State; I: Boolean; FileName: PChar): Integer; begin lua_pushboolean(L, 1); Result := 1; end; const F = 0; var NArgs: Integer; Status: Boolean; Arg: Integer; Len: Integer; S: PChar; Debug: lua_Debug; AR: Plua_Debug; begin AR := @Debug; lua_getstack(L, 1, AR); {* stack informations *} lua_getinfo(L, 'Snlu', AR); {* debug informations *} Arg := 1; NArgs := lua_gettop(L); Status := True; while (NArgs > 0) do begin Dec(NArgs); if (lua_type(L, Arg) = LUA_TNUMBER) then begin (* optimization: could be done exactly as for strings *) Status := Status and (fputsex(AR.source, Format(LUA_NUMBER_FMT, [lua_tonumber(L, Arg)]), AR.currentline, 0) > 0); end else begin S := luaL_checklstring(L, Arg, @Len); Status := Status and (fwriteex(AR.source, S, SizeOf(Char), Len, AR.currentline, F) = Len); end; Inc(Arg); end; Result := pushresult(L, Status, nil); end; function lua_io_write(L: Plua_State): Integer; cdecl; function pushresult(L: Plua_State; I: Boolean; FileName: PChar): Integer; begin lua_pushboolean(L, 1); Result := 1; end; const F = 0; var NArgs: Integer; Status: Boolean; Arg: Integer; Len: Integer; S: PChar; begin Arg := 1; NArgs := lua_gettop(L); Status := True; while (NArgs > 0) do begin Dec(NArgs); if (lua_type(L, Arg) = LUA_TNUMBER) then begin (* optimization: could be done exactly as for strings *) Status := Status and (fputs(Format(LUA_NUMBER_FMT, [lua_tonumber(L, Arg)]), 0) > 0); end else begin S := luaL_checklstring(L, Arg, @Len); Status := Status and (fwrite(S, SizeOf(Char), Len, F) = Len); end; Inc(Arg); end; Result := pushresult(L, Status, nil); end; function LuaToBoolean(L: PLua_State; Index: Integer): Boolean; begin Result := (lua_toboolean(L, Index) <> 0); end; procedure LuaPushBoolean(L: PLua_State; B: Boolean); begin lua_pushboolean(L, Integer(B)); end; function LuaToInteger(L: PLua_State; Index: Integer): Integer; begin Result := Trunc(lua_tonumber(L, Index)); //Round(lua_tonumber(L, Index)); end; procedure LuaPushInteger(L: PLua_State; N: Integer); begin lua_pushnumber(L, N); end; function LuaToVariant(L: Plua_State; Index: Integer): Variant; Var dataType :Integer; dataNum :Double; begin dataType :=lua_type(L, Index); Case dataType of LUA_TSTRING : Result := VarAsType(LuaToString(L, Index), varString); LUA_TUSERDATA, LUA_TLIGHTUSERDATA : Result := VarAsType(Integer(lua_touserdata(L, Index)), varInteger); LUA_TNONE, LUA_TNIL : Result := NULL; LUA_TBOOLEAN : Result := VarAsType(LuaToBoolean(L, Index), varBoolean); LUA_TNUMBER : begin dataNum :=lua_tonumber(L, Index); if (Abs(dataNum)>MAXINT) then Result :=VarAsType(dataNum, varDouble) else begin if (Frac(dataNum)<>0) then Result :=VarAsType(dataNum, varDouble) else Result :=VarAsType(dataNum, varInteger) end; end; end; end; procedure LuaPushVariant(L: Plua_State; N: Variant); begin case VarType(N) of varEmpty, varNull :lua_pushnil(L); varBoolean :LuaPushBoolean(L, N); varStrArg, varOleStr, varString :LuaPushString(L, N); varDate :LuaPushString(L, DateTimeToStr(VarToDateTime(N))); else lua_pushnumber(L, N); end; end; function LuaToString(L: PLua_State; Index: Integer): string; var Size: Integer; begin Size := lua_strlen(L, Index); SetLength(Result, Size); if (Size > 0) then Move(lua_tostring(L, Index)^, Result[1], Size); end; procedure LuaPushString(L: PLua_State; const S: string); begin lua_pushstring(L, PChar(S)); end; function LuaIncIndex(L: Plua_State; Index: Integer): Integer; // 相対インデックス -1 〜 -N へ変換 begin if ((Index = LUA_GLOBALSINDEX) or (Index = LUA_REGISTRYINDEX)) then begin Result := Index; Exit; end; Result := LuaAbsIndex(L, Index) - lua_gettop(L) - 1; end; function LuaAbsIndex(L: Plua_State; Index: Integer): Integer; // 絶対インデックス 1 〜 N へ変換 begin if ((Index = LUA_GLOBALSINDEX) or (Index = LUA_REGISTRYINDEX)) then begin Result := Index; Exit; end; if (Index < 0) then Result := Index + lua_gettop(L) + 1 else Result := Index; end; procedure LuaPushKeyString(L: PLua_State; var Index: Integer; const Key: string); begin Index := LuaAbsIndex(L, Index); lua_pushstring(L, PChar(Key)); end; procedure LuaGetTable(L: Plua_State; TableIndex: Integer; const Key: string); begin LuaPushKeyString(L, TableIndex, Key); lua_gettable(L, TableIndex); end; function LuaGetTableBoolean(L: Plua_State; TableIndex: Integer; const Key: string): Boolean; begin LuaGetTable(L, TableIndex, Key); Result := (lua_toboolean(L, -1) <> 0); lua_pop(L, 1); end; function LuaGetTableNumber(L: Plua_State; TableIndex: Integer; const Key: string): Double; begin LuaGetTable(L, TableIndex, Key); Result := lua_tonumber(L, -1); lua_pop(L, 1); end; function LuaGetTableInteger(L: Plua_State; TableIndex: Integer; const Key: string): Integer; begin LuaGetTable(L, TableIndex, Key); Result := LuaToInteger(L, -1); lua_pop(L, 1); end; function LuaGetTableString(L: Plua_State; TableIndex: Integer; const Key: string): string; begin LuaGetTable(L, TableIndex, Key); Result := lua_tostring(L, -1); lua_pop(L, 1); end; function LuaGetTableFunction(L: Plua_State; TableIndex: Integer; const Key: string): lua_CFunction; begin LuaGetTable(L, TableIndex, Key); Result := lua_tocfunction(L, -1); lua_pop(L, 1); end; function LuaGetTableLightUserData(L: Plua_State; TableIndex: Integer; const Key: string): Pointer; begin LuaGetTable(L, TableIndex, Key); Result := lua_touserdata(L, -1); lua_pop(L, 1); end; function LuaGetTableTMethod(L: Plua_State; TableIndex: Integer; const Key: string): TMethod; begin Result.Code :=LuaGetTableLightUserData(L, TableIndex, Key+'_Code'); //Code is the Method Pointer Result.Data :=LuaGetTableLightUserData(L, TableIndex, Key+'_Data'); //Data is the object Pointer end; procedure LuaRawGetTable(L: Plua_State; TableIndex: Integer; const Key: string); begin LuaPushKeyString(L, TableIndex, Key); lua_rawget(L, TableIndex); end; function LuaRawGetTableBoolean(L: Plua_State; TableIndex: Integer; const Key: string): Boolean; begin LuaRawGetTable(L, TableIndex, Key); Result := (lua_toboolean(L, -1) <> 0); lua_pop(L, 1); end; function LuaRawGetTableNumber(L: Plua_State; TableIndex: Integer; const Key: string): Double; begin LuaRawGetTable(L, TableIndex, Key); Result := lua_tonumber(L, -1); lua_pop(L, 1); end; function LuaRawGetTableString(L: Plua_State; TableIndex: Integer; const Key: string): string; begin LuaRawGetTable(L, TableIndex, Key); Result := lua_tostring(L, -1); lua_pop(L, 1); end; function LuaRawGetTableFunction(L: Plua_State; TableIndex: Integer; const Key: string): lua_CFunction; begin LuaRawGetTable(L, TableIndex, Key); Result := lua_tocfunction(L, -1); lua_pop(L, 1); end; function LuaRawGetTableLightUserData(L: Plua_State; TableIndex: Integer; const Key: string): Pointer; begin LuaRawGetTable(L, TableIndex, Key); Result := lua_touserdata(L, -1); lua_pop(L, 1); end; procedure LuaSetTableValue(L: PLua_State; TableIndex: Integer; const Key: string; ValueIndex: Integer); begin TableIndex := LuaAbsIndex(L, TableIndex); ValueIndex := LuaAbsIndex(L, ValueIndex); lua_pushstring(L, PChar(Key)); lua_pushvalue(L, ValueIndex); lua_settable(L, TableIndex); end; procedure LuaSetTableNil(L: Plua_State; TableIndex: Integer; const Key: string); begin LuaPushKeyString(L, TableIndex, Key); lua_pushnil(L); lua_settable(L, TableIndex); end; procedure LuaSetTableBoolean(L: Plua_State; TableIndex: Integer; const Key: string; B: Boolean); begin LuaPushKeyString(L, TableIndex, Key); lua_pushboolean(L, Integer(B)); lua_settable(L, TableIndex); end; procedure LuaSetTableNumber(L: Plua_State; TableIndex: Integer; const Key: string; N: Double); begin LuaPushKeyString(L, TableIndex, Key); lua_pushnumber(L, N); lua_settable(L, TableIndex); end; procedure LuaSetTableString(L: Plua_State; TableIndex: Integer; const Key: string; S: string); begin LuaPushKeyString(L, TableIndex, Key); lua_pushstring(L, PChar(S)); lua_settable(L, TableIndex); end; procedure LuaSetTableFunction(L: Plua_State; TableIndex: Integer; const Key: string; F: lua_CFunction); begin LuaPushKeyString(L, TableIndex, Key); lua_pushcfunction(L, F); lua_settable(L, TableIndex); end; procedure LuaSetTableLightUserData(L: Plua_State; TableIndex: Integer; const Key: string; P: Pointer); begin LuaPushKeyString(L, TableIndex, Key); lua_pushlightuserdata(L, P); lua_settable(L, TableIndex); end; procedure LuaSetTableTMethod(L: Plua_State; TableIndex: Integer; const Key: string; M: TMethod); begin LuaSetTableLightUserData(L, TableIndex, Key+'_Code', M.Code); LuaSetTableLightUserData(L, TableIndex, Key+'_Data', M.Data); end; procedure LuaSetTableClear(L: Plua_State; TableIndex: Integer); begin TableIndex := LuaAbsIndex(L, TableIndex); lua_pushnil(L); while (lua_next(L, TableIndex) <> 0) do begin lua_pushnil(L); lua_replace(L, -1 - 1); lua_settable(L, TableIndex); lua_pushnil(L); end; end; procedure LuaSetTablePropertyFuncs(L: PLua_State; TableIndex: Integer; ReadFunc: lua_CFunction; WriteFunc: lua_CFunction =nil); begin if assigned(ReadFunc) then LuaSetMetaFunction(L, TableIndex, '__index', ReadFunc); if assigned(WriteFunc) then LuaSetMetaFunction(L, TableIndex, '__newindex', WriteFunc); end; procedure LuaRawSetTableValue(L: PLua_State; TableIndex: Integer; const Key: string; ValueIndex: Integer); begin TableIndex := LuaAbsIndex(L, TableIndex); ValueIndex := LuaAbsIndex(L, ValueIndex); lua_pushstring(L, PChar(Key)); lua_pushvalue(L, ValueIndex); lua_rawset(L, TableIndex); end; procedure LuaRawSetTableNil(L: Plua_State; TableIndex: Integer; const Key: string); begin LuaPushKeyString(L, TableIndex, Key); lua_pushnil(L); lua_rawset(L, TableIndex); end; procedure LuaRawSetTableBoolean(L: Plua_State; TableIndex: Integer; const Key: string; B: Boolean); begin LuaPushKeyString(L, TableIndex, Key); lua_pushboolean(L, Integer(B)); lua_rawset(L, TableIndex); end; procedure LuaRawSetTableNumber(L: Plua_State; TableIndex: Integer; const Key: string; N: Double); begin LuaPushKeyString(L, TableIndex, Key); lua_pushnumber(L, N); lua_rawset(L, TableIndex); end; procedure LuaRawSetTableString(L: Plua_State; TableIndex: Integer; const Key: string; S: string); begin LuaPushKeyString(L, TableIndex, Key); lua_pushstring(L, PChar(S)); lua_rawset(L, TableIndex); end; procedure LuaRawSetTableFunction(L: Plua_State; TableIndex: Integer; const Key: string; F: lua_CFunction); begin LuaPushKeyString(L, TableIndex, Key); lua_pushcfunction(L, F); lua_rawset(L, TableIndex); end; procedure LuaRawSetTableLightUserData(L: Plua_State; TableIndex: Integer; const Key: string; P: Pointer); begin LuaPushKeyString(L, TableIndex, Key); lua_pushlightuserdata(L, P); lua_rawset(L, TableIndex); end; procedure LuaRawSetTableClear(L: Plua_State; TableIndex: Integer); begin TableIndex := LuaAbsIndex(L, TableIndex); lua_pushnil(L); while (lua_next(L, TableIndex) <> 0) do begin lua_pushnil(L); lua_replace(L, -1 - 1); lua_rawset(L, TableIndex); lua_pushnil(L); end; end; function LuaGetMetaFunction(L: Plua_State; Index: Integer; Key: string): lua_CFunction; // メタ関数の取得 begin Result := nil; Index := LuaAbsIndex(L, Index); if (lua_getmetatable(L, Index) = 0) then Exit; LuaGetTable(L, -1, Key); if (lua_iscfunction(L, -1) <> 0) then Result := lua_tocfunction(L, -1); lua_pop(L, 2); end; procedure LuaSetMetaFunction(L: Plua_State; Index: Integer; Key: string; F: lua_CFunction); // メタ関数の設定 // Key = __add, __sub, __mul, __div, __pow, __unm, __concat, // __eq, __lt, __le, __index, __newindex, __call // [メモ] // __newindex は 新規代入時しか呼ばれないので注意 // table をグローバル変数とするとこうなる。 // // a=1 -- (a=nilなので)メタ関数呼び出される // a=2 -- メタ関数は呼び出されない // a=3 -- メタ関数は呼び出されない // a=nil // a=4 -- (a=nilなので)メタ関数呼び出される // // lua 付属の trace-globals では__newindex と __index をセットで上書きして // グローバル変数へのアクセスをローカル変数へのアクセスに切り替えてグロー // バル変数の実体は常に table[key] = nil を保たせて __newindex イベントを // 発生させている。 begin Index := LuaAbsIndex(L, Index); if (lua_getmetatable(L, Index) = 0) then lua_newtable(L); LuaRawSetTableFunction(L, -1, Key, F); lua_setmetatable(L, Index); end; // Convert the last item at 'Index' from the stack to a string // nil : nil // Number : FloatToStr // Boolean: True/False // stirng : "..." // Table : { Key1=Value Key2=Value } function LuaStackToStr(L: Plua_State; Index: Integer; MaxTable: Integer; SubTableMax: Integer): string; var pGLobalsIndexPtr: Pointer; function TableToStr(Index: Integer): string; var Key, Value: string; Count: Integer; begin Result := '{ '; Count := 0; lua_pushnil(L); // Go through the current table while (lua_next(L, Index) <> 0) do begin Inc(Count); if (Count > MaxTable) then begin Result := Result + '... '; lua_pop(L, 2); Break; end; // Key to string if lua_type(L, -2) = LUA_TNUMBER then Key := '[' + Dequote(LuaStackToStr(L, -2, MaxTable, SubTableMax)) + ']' else Key := Dequote(LuaStackToStr(L, -2, MaxTable, SubTableMax)); // Value to string... if ((Key = '_G') or (lua_topointer(L, -1) = pGLobalsIndexPtr)) then Value := LuaGlobalVariableStr else Value := LuaStackToStr(L, -1, MaxTable, SubTableMax); if (lua_type(L, -1) = LUA_TFUNCTION) then Result := Result + Format('%s()=%p ', [Key, lua_topointer(L, -1)]) else Result := Result + Format('%s=%s ', [Key, Value]); // Pop current value from stack leaving current key on top of the stack for lua_next lua_pop(L, 1); end; Result := Result + '}'; end; begin if (MaxTable < 0) then MaxTable := DefaultMaxTable; pGLobalsIndexPtr := lua_topointer(L, LUA_GLOBALSINDEX); // Retrieve globals index poiner for later conditions lua_checkstack(L, SubTableMax * 3); // Ensure there is enough space on stack to work with according to user's setting Index := LuaAbsIndex(L, Index); case (lua_type(L, Index)) of LUA_TNIL: Result := 'nil'; LUA_TNUMBER: Result := Format('%g', [lua_tonumber(L, Index)]); LUA_TBOOLEAN: Result := BoolToStr(lua_toboolean(L, Index) <> 0, True); LUA_TSTRING: Result := '"'+lua_tostring(L, Index)+'"'; LUA_TTABLE: begin if SubTableCount < SubTableMax then begin SubTableCount := SubTableCount + 1; Result := TableToStr(Index); SubTableCount := SubTableCount - 1; end else Result := '[SUB_TABLE_MAX_LEVEL_HAS_BEEN_REACHED]'; end; LUA_TFUNCTION: if (lua_iscfunction(L, Index) <> 0) then Result := Format('CFUNC:%p', [Pointer(lua_tocfunction(L, Index))]) else Result := Format('FUNC:%p', [lua_topointer(L, Index)]); LUA_TUSERDATA: Result := Format('USERDATA:%p', [lua_touserdata(L, Index)]); LUA_TTHREAD: Result := Format('THREAD:%p', [lua_tothread(L, Index)]); LUA_TLIGHTUSERDATA: Result := Format('LIGHTUSERDATA:%p', [lua_touserdata(L, Index)]); else Assert(False); end; end; procedure LuaShowStack(L: Plua_State; Caption: string); var I, N: Integer; S: string; begin N := lua_gettop(L); S := '[' + Caption + ']'; for I := N downto 1 do begin S := S + CRLF + Format('%3d,%3d:%s', [LuaAbsIndex(L, I), LuaIncIndex(L, I), LuaStackToStr(L, I, -1)]); end; ShowMessage(S); end; procedure LuaProcessTableName(L: Plua_State; const Name: PChar; var LastName: string; var TableIndex, Count: Integer); // Name のテーブル要素をスタックに積んで、 // スタックに積んだ数と Name の最終要素の名前とその親テーブルのインデックスを返す // テーブルが無い場合は作成する // LuaProcessTableName(L, 'print', S, TI, Count) → S = print, TI = LUA_GLOBALSINDEX, Count = 0 // LuaProcessTableName(L, 'io.write', S, TI, Count) → S = write, TI -> io, Count = 1 // LuaProcessTableName(L, 'a.b.c.func', S, TI, Count) → S = func, TI -> a.b.c, Count = 3 var S: string; function GetToken: string; var Index: Integer; begin Index := Pos('.', S); if (Index = 0) then begin Result := S; S := ''; Exit; end; Result := Copy(S, 1, Index - 1); S := Copy(S, Index + 1, Length(S)); end; begin S := Name; Count := 0; LastName := GetToken; while (S <> '') do begin Inc(Count); TableIndex := LuaAbsIndex(L, TableIndex); LuaGetTable(L, TableIndex, LastName); if (lua_type(L, -1) <> LUA_TTABLE) then begin lua_pop(L, 1); lua_pushstring(L, PChar(LastName)); lua_newtable(L); lua_rawset(L, TableIndex); LuaGetTable(L, TableIndex, LastName); end; TableIndex := -1; LastName := GetToken; end; end; procedure LuaRegisterCustom(L: PLua_State; TableIndex: Integer; const Name: PChar; F: lua_CFunction); var Count: Integer; S: string; begin LuaProcessTableName(L, Name, S, TableIndex, Count); LuaRawSetTableFunction(L, TableIndex, S, F); lua_pop(L, Count); end; procedure LuaRegister(L: Plua_State; const Name: PChar; F: lua_CFunction); // 関数の登録 // LuaRegister(L, 'print', lua_print); // LuaRegister(L, 'io.write', lua_io_write); // テーブル io が無い場合は作成 // LuaRegister(L, 'a.b.c.func', a_b_c_func); // テーブル a.b.c が無い場合は作成 begin LuaRegisterCustom(L, LUA_GLOBALSINDEX, Name, F); end; procedure LuaRegisterMetatable(L: Plua_State; const Name: PChar; F: lua_CFunction); begin LuaRegisterCustom(L, LUA_REGISTRYINDEX, Name, F); end; procedure LuaRegisterProperty(L: PLua_State; const Name: PChar; ReadFunc, WriteFunc: lua_CFunction); var Count: Integer; TI: Integer; S: string; begin TI := LUA_GLOBALSINDEX; LuaProcessTableName(L, Name, S, TI, Count); TI := LuaAbsIndex(L, TI); LuaGetTable(L, TI, S); if (lua_type(L, -1) <> LUA_TTABLE) then begin lua_pop(L, 1); lua_pushstring(L, PChar(S)); lua_newtable(L); lua_settable(L, TI); LuaGetTable(L, TI, S); end; if (Assigned(ReadFunc)) then LuaSetMetaFunction(L, -1, '__index', ReadFunc); if (Assigned(WriteFunc)) then LuaSetMetaFunction(L, -1, '__newindex', WriteFunc); lua_pop(L, Count + 1); end; procedure LuaStackToStrings(L: Plua_State; Lines: TStrings; MaxTable: Integer = -1; SubTableMax: Integer = 99); var I: Integer; begin Lines.Clear; for I := lua_gettop(L) downto 1 do Lines.Add(LuaStackToStr(L, I, MaxTable, SubTableMax)); end; procedure LuaLocalToStrings(L: Plua_State; Lines: TStrings; MaxTable: Integer; Level: Integer; SubTableMax: Integer); var Name: PChar; Index: Integer; Debug: lua_Debug; AR: Plua_Debug; begin AR := @Debug; Lines.Clear; Index := 1; if (lua_getstack(L, Level, AR) = 0) then Exit; Name := lua_getlocal(L, AR, Index); while (Name <> nil) do begin Lines.Values[Name] := LuaStackToStr(L, -1, MaxTable, SubTableMax); lua_pop(L, 1); Inc(Index); Name := lua_getlocal(L, AR, Index); end; end; procedure LuaGlobalToStrings(L: PLua_State; Lines: TStrings; MaxTable: Integer; SubTableMax: Integer); begin lua_pushvalue(L, LUA_GLOBALSINDEX); LuaTableToStrings(L, -1, Lines, MaxTable, SubTableMax); lua_pop(L, 1); end; procedure LuaTableToStrings(L: Plua_State; Index: Integer; Lines: TStrings; MaxTable: Integer; SubTableMax: Integer); var Key, Value: string; begin Index := LuaAbsIndex(L, Index); Lines.Clear; lua_pushnil(L); while (lua_next(L, Index) <> 0) do begin Key := Dequote(LuaStackToStr(L, -2, MaxTable, SubTableMax)); Value := LuaStackToStr(L, -1, MaxTable, SubTableMax); Lines.Values[Key] := Value; lua_pop(L, 1); end; end; procedure LuaTableToTreeView(L: Plua_State; Index: Integer; TV: TTreeView; MaxTable: Integer; SubTableMax: Integer); var pGLobalsIndexPtr: Pointer; // Go through all child of current table and create nodes procedure ParseTreeNode(TreeNode: TTreeNode; Index: Integer); var Key: string; begin Index := LuaAbsIndex(L, Index); lua_pushnil(L); while (lua_next(L, Index) <> 0) do begin Key := Dequote(LuaStackToStr(L, -2, MaxTable, SubTableMax)); if (lua_type(L, -1) <> LUA_TTABLE) then TV.Items.AddChild(TreeNode, Key + '=' + LuaStackToStr(L, -1, MaxTable, SubTableMax)) else begin if ((Key = '_G') or (lua_topointer(L, -1) = pGLobalsIndexPtr)) then begin TV.Items.AddChild(TreeNode, Key + '=[LUA_GLOBALSINDEX]') end else begin if SubTableCount < SubTableMax then begin SubTableCount := SubTableCount + 1; ParseTreeNode(TV.Items.AddChild(TreeNode, Key), -1); SubTableCount := SubTableCount - 1; end; end; end; lua_pop(L, 1); end; end; begin Assert(lua_type(L, Index) = LUA_TTABLE); TV.Items.BeginUpdate; TV.Items.Clear; try ParseTreeNode(nil, Index); finally TV.Items.EndUpdate; end; end; function LuaGetIdentValue(L: Plua_State; Ident: string; MaxTable: Integer): string; const DebugValue = '___DEBUG_VALUE___'; var Local: TStrings; Code: string; Hook: lua_Hook; Mask: Integer; Count: Integer; begin if (Ident = '') then begin Result := ''; Exit; end; Local := TStringList.Create; try LuaLocalToStrings(L, Local, MaxTable); Result := Local.Values[Ident]; if (Result <> '') then Exit; finally Local.Free; end; Code := DebugValue + '=' + Ident; luaL_loadbuffer(L, PChar(Code), Length(Code), 'debug'); Hook := lua_gethook(L); Mask := lua_gethookmask(L); Count := lua_gethookcount(L); lua_sethook(L, Hook, 0, Count); if (lua_pcall(L, 0, 0, 0) = 0) then LuaRawGetTable(L, LUA_GLOBALSINDEX, DebugValue); Result := LuaStackToStr(L, -1, MaxTable); lua_remove(L, -1); lua_dostring(L, DebugValue + '=nil'); lua_sethook(L, Hook, Mask, Count); end; procedure LuaSetIdentValue(L: Plua_State; Ident, Value: string; MaxTable: Integer); var Local: TStrings; Code: string; Index: Integer; Debug: lua_Debug; AR: Plua_Debug; begin Local := TStringList.Create; try AR := @Debug; LuaLocalToStrings(L, Local, MaxTable); Index := Local.IndexOf(Ident); if (Index >= 0) then begin try lua_pushnumber(L, StrToFloat(Value)); except lua_pushstring(L, PChar(Dequote(Value))); end; lua_getstack(L, 0, AR); lua_getinfo(L, 'Snlu', AR); lua_setlocal(L, AR, Index + 1); end else begin Code := Ident + '=' + Value; luaL_loadbuffer(L, PChar(Code), Length(Code), 'debug'); if (lua_pcall(L, 0, 0, 0) <> 0) then lua_remove(L, -1); end; finally Local.Free; end; end; procedure LuaProcessErrorMessage(const ErrMsg: string; var Title: string; var Line: Integer; var Msg: string); const Term = #$00; function S(Index: Integer): Char; begin if (Index <= Length(ErrMsg)) then Result := ErrMsg[Index] else Result := Term; end; function IsDigit(C: Char): Boolean; begin Result := ('0' <= C) and (C <= '9'); end; function PP(var Index: Integer): Integer; begin Inc(Index); Result := Index; end; var I, Start, Stop: Integer; LS: string; Find: Boolean; begin // ErrMsg = Title:Line:Message Title := ''; Line := 0; Msg := ErrMsg; Find := False; I := 1 - 1; Stop := 0; // :数値: を探す repeat while (S(PP(I)) <> ':') do if (S(I) = Term) then Exit; Start := I; if (not IsDigit(S(PP(I)))) then Continue; while (IsDigit(S(PP(I)))) do if (S(I - 1) = Term) then Exit; Stop := I; if (S(I) = ':') then Find := True; until (Find); Title := Copy(ErrMsg, 1, Start - 1); LS := Copy(ErrMsg, Start + 1, Stop - Start - 1); Line := StrToIntDef(LS, 0); Msg := Copy(ErrMsg, Stop + 1, Length(ErrMsg)); end; procedure LuaLoadBuffer(L: Plua_State; const Code: string; const Name: string); var Title, Msg: string; Line: Integer; begin if (luaL_loadbuffer(L, PChar(Code), Length(Code), PChar(Name)) = 0) then Exit; LuaProcessErrorMessage(LuaStackToStr(L, -1, -1), Title, Line, Msg); raise ELuaException.Create(Title, Line, Msg); end; procedure LuaLoadBufferFromFile(L: Plua_State; const Filename: string; const Name: string); Var xCode :String; xFile :TStringList; begin xFile := TStringList.Create; xFile.LoadFromFile(FileName); xCode := xFile.Text; xFile.Free; LuaLoadBuffer(L, xCode, Name); end; procedure LuaPCall(L: Plua_State; NArgs, NResults, ErrFunc: Integer); var Title, Msg: string; Line: Integer; begin if (lua_pcall(L, NArgs, NResults, ErrFunc) = 0) then Exit; LuaProcessErrorMessage(Dequote(LuaStackToStr(L, -1, -1)), Title, Line, Msg); raise ELuaException.Create(Title, Line, Msg); end; function LuaPCallFunction(L: Plua_State; FunctionName :String; const Args: array of Variant; Results : PVariantArray; ErrFunc: Integer=0; NResults :Integer=LUA_MULTRET):Integer; var NArgs, i: Integer; begin //Put Function To Call on the Stack luaPushString(L, FunctionName); lua_gettable(L, LUA_GLOBALSINDEX); //Put Parameters on the Stack NArgs := High(Args)+1; for i:=0 to (NArgs-1) do LuaPushVariant(L, Args[i]); //Call the Function LuaPcall(L, NArgs, NResults, ErrFunc); Result :=lua_gettop(L); //Get Number of Results if (Results<>Nil) then begin //Get Results in the right order SetLength(Results^, Result); for i:=0 to Result-1 do begin Results^[Result-(i+1)] :=LuaToVariant(L, -(i+1)); end; end; end; procedure LuaError(L: Plua_State; const Msg: string); begin luaL_error(L, PChar(Msg)); end; procedure LuaErrorFmt(L: Plua_State; const Fmt: string; const Args: array of Const); begin LuaError(L, Format(Fmt, Args)); end; { ELuaException } constructor ELuaException.Create(Title: string; Line: Integer; Msg: string); var LS: string; begin if (Line > 0) then LS := Format('(%d)', [Line]) else LS := ''; inherited Create(Title + LS + Msg); Self.Title := Title; Self.Line := Line; Self.Msg := Msg; end; function LuaDataStrToStrings(const TableStr: string; Strings: TStrings): string; (* LuaStackToStr 形式から Strings.Values[Name] 構造へ変換 TableStr { Name = "Lua" Version = 5.0 } ↓ Strings Name="Lua" Version=5.0 DataList : Data DataList | Data : Table | {グローバル変数} | Ident ( ) | Ident = Value | Ident | Table : { DataList } | Value : "..." | Data *) const EOF = #$00; var Index: Integer; Text: string; Token: Char; function S(Index: Integer): Char; begin if (Index <= Length(TableStr)) then Result := TableStr[Index] else Result := EOF; end; function GetString: string; var SI: Integer; begin Dec(Index); Result := ''; repeat Assert(S(Index) = '"'); SI := Index; Inc(Index); while (S(Index) <> '"') do Inc(Index); Result := Result + Copy(TableStr, SI, Index - SI + 1); Inc(Index); until (S(Index) <> '"'); end; function GetValue: string; function IsIdent(C: Char): Boolean; const S = ' =(){}' + CR + LF; begin Result := (Pos(C, S) = 0); end; var SI: Integer; begin Dec(Index); SI := Index; while (IsIdent(S(Index))) do Inc(Index); Result := Copy(TableStr, SI, Index - SI); end; function GetToken: Char; function SkipSpace(var Index: Integer): Integer; const TAB = #$09; CR = #$0D; LF = #$0A; begin while (S(Index) in [' ', TAB, CR, LF]) do Inc(Index); Result := Index; end; begin SkipSpace(Index); Token := S(Index); Inc(Index); Text := Token; case (Token) of EOF: ; '"': Text := GetString; '{': if (Copy(TableStr, Index - 1, Length(LuaGlobalVariableStr)) = LuaGlobalVariableStr) then begin Token := 'G'; Text := LuaGlobalVariableStr; Inc(Index, Length(LuaGlobalVariableStr) - 1); end; '}': ; '(': ; ')': ; '=': ; else Text := GetValue end; Result := Token; end; procedure Check(S: string); begin if (Pos(Token, S) = -1) then raise Exception.CreateFmt('Error %s is required :%s', [Copy(TableStr, Index - 1, Length(TableStr))]); end; function CheckGetToken(S: string): Char; begin Result := GetToken; Check(S); end; function ParseData: string; forward; function ParseTable: string; forward; function ParseValue: string; forward; function ParseDataList: string; begin with (TStringList.Create) do try while not (Token in [EOF, '}']) do Add(ParseData); Result := Text; finally Free; end; end; function ParseData: string; begin if (Token = EOF) then begin Result := ''; Exit; end; case (Token) of '{': Result := ParseTable; 'G': begin Result := Text; GetToken; end; else begin Result := Text; case (GetToken) of '(': begin CheckGetToken(')'); Result := Format('%s=()', [Result]); GetToken; end; '=': begin GetToken; Result := Format('%s=%s', [Result, ParseValue]); end; end; end; end; end; function ParseTable: string; begin if (Token in [EOF]) then begin Result := ''; Exit; end; Check('{'); GetToken; with (TStringList.Create) do try Text := ParseDataList; Result := CommaText; finally Free; end; Check('}'); GetToken; end; function ParseValue: string; begin if (Token = EOF) then begin Result := ''; Exit; end; case (Token) of '"': begin Result := Text; GetToken; end; else Result := ParseData; end; end; begin Index := 1; GetToken; Strings.Text := ParseDataList; end; function LuaDoFile(L: Plua_State): Integer; cdecl; // dofile 引数(arg)戻り値付き // Lua: DoFile(FileName, Args...) const ArgIdent = 'arg'; var FileName: PChar; I, N, R: Integer; ArgTable, ArgBackup: Integer; begin N := lua_gettop(L); // arg, result の保存 lua_getglobal(L, ArgIdent); ArgBackup := lua_gettop(L); FileName := luaL_checkstring(L, 1); lua_newtable(L); ArgTable := lua_gettop(L); for I := 2 to N do begin lua_pushvalue(L, I); lua_rawseti(L, ArgTable, I - 1); end; lua_setglobal(L, ArgIdent); Result := lua_gettop(L); luaL_loadfile(L, PChar(FileName)); R := lua_pcall(L, 0, LUA_MULTRET, 0); Result := lua_gettop(L) - Result; LuaRawSetTableValue(L, LUA_GLOBALSINDEX, ArgIdent, ArgBackup); lua_remove(L, ArgBackup); if (R <> 0) then lua_error(L); end; function LuaGetCurrentFuncName(L: Plua_State) :String; var ar :lua_Debug; begin FillChar(ar, sizeof(ar), 0); Result :=''; if (lua_getStack(L, 0, @ar) = 1) then begin lua_getinfo(L, 'n', @ar); Result :=ar.name; end; end; function Lua_VoidFunc(L: Plua_State): Integer; cdecl; begin Result := 0; end; initialization DefaultMaxTable := 256; end.
unit Threads.Base; interface uses Windows, Classes, SysUtils, GMGlobals, Math, Generics.Collections, SyncObjs; type TGMThread = class(TThread) private FTag: NativeInt; FRestartOnError: bool; FTermEvent: TEvent; protected procedure SleepThread(TimeoutMs: int); procedure SafeExecute(); virtual; abstract; procedure Execute(); override; function GetTerminated: bool; function GetDescription: string; virtual; procedure TerminatedSet; override; public property Description: string read GetDescription; property Tag: NativeInt read FTag write FTag; property RestartOnError: bool read FRestartOnError write FRestartOnError; function WaitForTimeout(TimeOut: int; KillUnterminated: bool = true): int; virtual; constructor Create(createSuspended: bool = false); destructor Destroy; override; end; TGMThreadPool<T: TGMThread> = class(TList<T>) private FTimeOut: int; public property TimeOut: int read FTimeOut write FTimeOut; constructor Create(); destructor Destroy(); override; procedure Terminate(); procedure WaitFor(timeoutMs: int = -1; killUnfinished: bool = true); procedure DropThread(Index: int); end; implementation uses ProgramLogFile, GMConst{$ifdef SQL_APP}, GMSqlQuery{$endif}, EsLogging; { TGMThread } constructor TGMThread.Create(createSuspended: bool); begin inherited Create(createSuspended); FTermEvent := TEvent.Create(nil, True, False, ''); end; destructor TGMThread.Destroy; begin inherited; //inherited calls TerminatedSet where FTermEvent should not be freed yet FTermEvent.Free(); {$ifdef SQL_APP} DropThreadConnection(ThreadID); {$endif} end; procedure TGMThread.Execute; begin var done := false; var error := false; repeat try if ProgramLog <> nil then ProgramLog.AddMessage(ClassName() + '.SafeExecute'); error := false; SafeExecute(); done := true; except on e: Exception do begin error := true; GMPostMessage(WM_THREAD_EXCEPTION, IfThen(FreeOnTerminate, 0, WParam(self)), WParam(ClassType), DefaultLogger); ProgramLog.AddException('TGMThread(' + ClassName() + ').Execute - ' + e.ToString()); end; end; until Terminated or done or (error and not FRestartOnError); end; procedure TGMThread.TerminatedSet; begin FTermEvent.SetEvent; end; function TGMThread.GetDescription: string; begin Result := ClassName(); end; function TGMThread.GetTerminated: bool; begin Result := Terminated; end; procedure TGMThread.SleepThread(TimeoutMs: int); begin if TimeoutMs <= 0 then Exit; FTermEvent.WaitFor(TimeoutMs); end; function TGMThread.WaitForTimeout(TimeOut: int; KillUnterminated: bool = true): int; begin if Finished then begin Result := WAIT_OBJECT_0; Exit; end; if TimeOut > 0 then Result := WaitForSingleObject(Handle, TimeOut) else Result := WaitForSingleObject(Handle, INFINITE); if (Result <> WAIT_OBJECT_0) and KillUnterminated then TerminateThread(Handle, 0); end; { TGMThreadPool } constructor TGMThreadPool<T>.Create; begin inherited; FTimeOut := 30000; end; destructor TGMThreadPool<T>.Destroy; var thr: TGMThread; begin Terminate(); WaitFor(); for thr in self do thr.Free(); inherited; end; procedure TGMThreadPool<T>.DropThread(Index: int); begin try Items[Index].Terminate(); Items[Index].WaitForTimeout(FTimeOut); Items[Index].Free(); except end; Delete(Index); end; procedure TGMThreadPool<T>.Terminate; var thr: TGMThread; begin for thr in self do thr.Terminate(); end; procedure TGMThreadPool<T>.WaitFor(timeoutMs: int = -1; killUnfinished: bool = true); var H: TWOHandleArray; begin var n := 0; for var i := 0 to Count - 1 do if not Items[i].Finished then begin H[n] := Items[i].Handle; inc(n); if n > High(H) then break; end; if n = 0 then Exit; // ограничение на ожидание - 64 неостановленных потока, используем первые 64 в списке, веруя, // что потоков или меньше, а остальные будут останавливаться быстрее первых или не остановятся совсем var res: DWORD := WaitForMultipleObjects(n, @H, true, IfThen(timeoutMs > 0, timeoutMs, FTimeout)); if res = WAIT_FAILED then ProgramLog().AddError(ClassName() + '.WaitFor.WaitForMultipleObjects: ' + GetGoodLastError()); for var thr in self do thr.WaitForTimeout(1); end; end.
(**********************************************************************************) (* Code generated with NexusDB Enterprise Manager Data Dictionary Code Generator *) (* *) (* Version: 3,0101 *) (* *) (**********************************************************************************) unit ncTableDefs; interface uses Classes, nxdb, nxsdTypes, nxsdKeyFieldEngineBase, nxsdDataDictionary; type TnxcgProgressCallback = procedure(const aTableName : String; var aStatus : TnxTaskStatus; var aCancel : Boolean) of object; procedure BuildAndEvolveDatabase(aDatabase : TnxDatabase; aProgressCallback : TnxcgProgressCallback = nil; const aPassword : String = ''); procedure RestructureDatabase(aDatabase : TnxDatabase; aProgressCallback : TnxcgProgressCallback = nil; const aPassword : String = ''); procedure PackDatabase(aDatabase : TnxDatabase; aProgressCallback : TnxcgProgressCallback = nil; const aPassword : String = ''); function TableCount: Integer; function DatabaseVersion: Cardinal; function DatabaseVersionStr: String; function GetTableDictionary(aDatabase : TnxDatabase; const aTableName : String): TnxDataDictionary; procedure GetTableNames(aSL: TStrings); function GetTablePrimaryKey(aTable: String): String; function GetTableID(aTable: String): Integer; const sEncPass = 'CEWk4jhsad3f'; var gTableNames : TStrings; gEvolvingTables : Boolean = False; gEvolvingTableName : String = ''; implementation uses {$IFDEF NXWINAPI}nxWinAPI{$ELSE}Windows{$ENDIF}, Math, SysUtils, StrUtils, Variants, DBCommon, nxllTypes, nxllBde, nxllException, nxllWideString, nxsdConst, nxsdDataDictionaryStrings, nxsdDataDictionaryRefInt, nxsdDataDictionaryFulltext, nxsdFilterEngineSimpleExpression, nxsdFilterEngineSql, nxsdServerEngine, nxsdTableMapperDescriptor, ncClassesBase, kwicDescriptor, kwicEngine, ncVersionInfo, ncsFrmBackup; type TnxcgCreateDictCallback = function(aDatabase : TnxDatabase): TnxDataDictionary; threadvar aCopiouArqs : Boolean; // ConvUnid function __ConvUnid(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin with AddField('UID', '', nxtGUID, 0, 0, False) do AddDefaultValue(TnxAutoGuidDefaultValueDescriptor); AddField('A', '', nxtNullString, 10, 0, False); AddField('B', '', nxtNullString, 10, 0, False); AddField('Fator', '', nxtExtended, 0, 0, False); AddField('Mult', '', nxtBoolean, 0, 0, False); AddField('Universal', '', nxtBoolean, 0, 0, False); AddField('Produto', '', nxtWord32, 10, 0, False); end; with EnsureIndicesDescriptor do with AddIndex('IABUniv', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('A')); Add(GetFieldFromName('B')); Add(GetFieldFromName('Universal')); Add(GetFieldFromName('Produto')); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // ProdFor function __ProdFor(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin with AddField('UID', '', nxtGUID, 0, 0, False) do AddDefaultValue(TnxAutoGuidDefaultValueDescriptor); AddField('Produto', '', nxtWord32, 10, 0, False); AddField('Fornecedor', '', nxtWord32, 10, 0, False); AddField('Pos', '', nxtWord16, 5, 0, False); AddField('Ref', '', nxtNullString, 20, 0, False); end; with EnsureIndicesDescriptor do begin with AddIndex('IProdFor', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Produto')); Add(GetFieldFromName('Fornecedor')); end; with AddIndex('IForRef', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Fornecedor')); Add(GetFieldFromName('Ref')); end; with AddIndex('IProdPos', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Produto')); Add(GetFieldFromName('Pos')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // LinkXML function __LinkXML(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin with AddField('UID', '', nxtGUID, 0, 0, False) do AddDefaultValue(TnxAutoGuidDefaultValueDescriptor); AddField('Produto', '', nxtWord32, 10, 0, False); AddField('Fornecedor', '', nxtWord32, 10, 0, False); AddField('Link', '', nxtNullString, 20, 0, False); end; with EnsureIndicesDescriptor do begin with AddIndex('IForLink', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Fornecedor')); Add(GetFieldFromName('Link')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // brtrib function __brtrib(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtWord16, 5, 0, False); AddField('Nome', '', nxtNullString, 50, 0, False); AddField('Origem', '', nxtByte, 2, 0, False); AddField('CST', '', nxtWord16, 3, 0, False); AddField('CSOSN', '', nxtWord16, 5, 0, False); AddField('ICMS', '', nxtDouble, 5, 5, False); AddField('Padrao', '', nxtBoolean, 0, 0, False); AddField('CFOP_nfce', '', nxtWord16, 5, 0, False); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('INome', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Nome')); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // CFOP function __CFOP(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('Codigo', '', nxtWord16, 5, 0, False); AddField('Descricao', '', nxtBLOBMemo, 0, 0, False); AddField('Entrada', '', nxtBoolean, 0, 0, False); AddField('Tipo', '', nxtByte, 3, 0, False); AddField('NFCe', '', nxtBoolean, 0, 0, False); with AddField('Ordem', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 255; AddField('CSOSN', '', nxtWord16, 5, 0, False); end; with EnsureIndicesDescriptor do begin with AddIndex('ICodigo', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Codigo')); with AddIndex('ITipoCodigo', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Tipo')); Add(GetFieldFromName('Codigo')); end; with AddIndex('IOrdemCodigo', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Ordem')); Add(GetFieldFromName('Codigo')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // CSOSN function __CSOSN(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('Codigo', '', nxtWord16, 5, 0, False); AddField('Descricao', '', nxtNullString, 100, 0, False); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // CST function __CST(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('Codigo', '', nxtWord16, 5, 0, False); AddField('Descricao', '', nxtNullString, 100, 0, False); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // MunBr function __MunBr(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('UF', '', nxtNullString, 2, 0, False); AddField('Nome', '', nxtNullString, 40, 0, False); AddField('Codigo', '', nxtNullString, 7, 0, False); end; with EnsureIndicesDescriptor do begin with AddIndex('IUFNome', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('UF')); with Add(GetFieldFromName('Nome'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; Flags := $00001000; UseStringSort := True; end; end; end; with AddIndex('IUFCodigo', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('UF')); Add(GetFieldFromName('Codigo')); end; with AddIndex('ICodigo', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Codigo')); with AddIndex('INome', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Nome'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; Flags := $00001000; UseStringSort := True; end; end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // NFCONFIG function __NFCONFIG(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin with AddField('EmitirNFCe', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('Tipo', '', nxtByte, 5, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := nfcfg_nfce; with AddField('RemoverNFCe', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('EmitirNFE', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('CertificadoDig', '', nxtNullString, 300, 0, False); AddField('PinCert', '', nxtNullString, 50, 0, False); with AddField('DependNFCEOk', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('DependSATOk', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('TipoCert', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; AddField('AutoPrintNFCe', '', nxtBoolean, 0, 0, False); with AddField('CRT', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 1; AddField('NCM_Padrao', '', nxtNullString, 8, 0, False); AddField('Trib_Padrao', '', nxtWord16, 0, 0, False); AddField('MostrarDadosNFE', '', nxtBoolean, 0, 0, False); AddField('ModeloNFE', '', nxtNullString, 5, 0, False); AddField('ModeloNFCe', '', nxtNullString, 5, 0, False); with AddField('SerieNFCe', '', nxtNullString, 5, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := '1'; with AddField('SerieNFe', '', nxtNullString, 5, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := '1'; AddField('NomeDllSat', '', nxtNullString, 200, 0, False); AddField('SignACSat', '', nxtNullString, 344, 0, False); AddField('CodigoAtivacao', '', nxtNullString, 50, 0, False); with AddField('AssociarSignAC', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('InicioNFe', '', nxtWord32, 10, 0, False); AddField('InicioNFCe', '', nxtWord32, 10, 0, False); AddField('RazaoSocial', '', nxtNullString, 100, 0, False); AddField('NomeFantasia', '', nxtNullString, 50, 0, False); AddField('CNPJ', '', nxtNullString, 20, 0, False); AddField('IE', '', nxtNullString, 20, 0, False); AddField('End_Logradouro', '', nxtNullString, 100, 0, False); AddField('End_Numero', '', nxtNullString, 10, 0, False); AddField('End_Complemento', '', nxtNullString, 20, 0, False); AddField('End_Bairro', '', nxtNullString, 40, 0, False); AddField('End_UF', '', nxtNullString, 2, 0, False); AddField('End_CEP', '', nxtNullString, 9, 0, False); AddField('End_Municipio', '', nxtNullString, 50, 0, False); AddField('End_CodMun', '', nxtNullString, 7, 0, False); AddField('End_CodUF', '', nxtByte, 3, 0, False); AddField('Telefone', '', nxtNullString, 20, 0, False); with AddField('tpAmb', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 2; AddField('CSC', '', nxtNullString, 100, 0, False); AddField('IdCSC', '', nxtNullString, 10, 0, False); with AddField('PedirEmail', '', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 1; with AddField('PedirCPF', '', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 1; AddField('FromEmail', '', nxtNullString, 100, 0, False); AddField('AssuntoEmail', '', nxtNullString, 100, 0, False); AddField('FromName', '', nxtNullString, 50, 0, False); AddField('CorpoEmail', '', nxtBlobMemo, 0, 0, False); AddField('ModeloNFCe_Email', '', nxtGuid, 0, 0, False); AddField('ModeloSAT_Email', '', nxtGuid, 0, 0, False); AddField('urls_qrcode_hom', '', nxtBLOBMemo, 0, 0, False); AddField('urls_qrcode_prod', '', nxtBLOBMemo, 0, 0, False); AddField('urls_consulta', '', nxtBLOBMemo, 0, 0, False); AddField('ObsFisco', '', nxtBLOBMemo, 0, 0, False); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // NFE function __NFE(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin with AddField('UID', '', nxtGUID, 0, 0, False) do with AddDefaultValue(TnxAutoGuidDefaultValueDescriptor) as TnxAutoGuidDefaultValueDescriptor do ApplyAt := [aaClient, aaServer]; AddField('NumSeq', '', nxtAutoInc, 10, 0, False); AddField('Modelo', '', nxtNullString, 5, 0, False); AddField('Serie', '', nxtNullString, 5, 0, False); AddField('Numero', '', nxtWord32, 4, 0, False); AddField('Chave', '', nxtNullString, 44, 0, False); AddField('ChaveCont', '', nxtNullString, 44, 0, False); with AddField('ConsultouChave', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('Entrada', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('TipoDoc', 'NFCe=0 ou NFe=1', nxtByte, 2, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; with AddField('DataHora', '', nxtDateTime, 0, 0, False) do AddDefaultValue(TnxCurrentDateTimeDefaultValueDescriptor); AddField('CFOP', '', nxtWord16, 4, 0, False); AddField('Tran', '', nxtGUID, 0, 0, False); AddField('Recibo', '', nxtNullString, 20, 0, False); AddField('Protocolo', '', nxtNullString, 20, 0, False); AddField('Contingencia', '', nxtBoolean, 0, 0, False); AddField('Status', '', nxtByte, 3, 0, False); AddField('tpAmb', '', nxtByte, 3, 0, False); AddField('StatusNF', '', nxtInt32, 5, 0, False); AddField('XMLdest', '', nxtBLOBMemo, 0, 0, False); AddField('XMLret', '', nxtBLOBMemo, 0, 0, False); AddField('XMLtrans', '', nxtBlobMemo, 0, 0, False); AddField('XMLtransCont', '', nxtBlobMemo, 0, 0, False); AddField('xMotivo', '', nxtBlobMemo, 0, 0, False); AddField('LogEnvio', '', nxtBlobMemo, 0, 0, False); AddField('LogRec', '', nxtBlobMemo, 0, 0, False); AddField('ProtocoloCanc', '', nxtNullString, 20, 0, False); AddField('StatusCanc', '', nxtByte, 0, 0, False); AddField('StatusCancNF', '', nxtInt32, 0, 0, False); AddField('JustCanc', '', nxtBlobMemo, 0, 0, False); AddField('xMotivoCanc', '', nxtBlobMemo, 0, 0, False); AddField('xmlRetCanc', '', nxtBlobMemo, 0, 0, False); AddField('CanceladoPor', '', nxtNullString, 30, 0, False); AddField('CanceladoEm', '', nxtDateTime, 0, 0, False); AddField('StatusInut', '', nxtByte, 0, 0, False); AddField('StatusInutNF', '', nxtInt32, 0, 0, False); AddField('ProtocoloInut', '', nxtNullString, 20, 0, False); AddField('xMotivoInut', '', nxtBlobMemo, 0, 0, False); AddField('xmlRetInut', '', nxtBlobMemo, 0, 0, False); AddField('CPF', '', nxtNullString, 14, 0, False); AddField('Email', '', nxtNullString, 100, 0, False); AddField('IncluidoEm', '', nxtDateTime, 0, 0, False); AddField('EmitidoEm', '', nxtDateTime, 0, 0, False); AddField('ContingenciaEM', '', nxtDateTime, 0, 0, False); AddField('Valor', '', nxtCurrency, 20, 4, False); end; with EnsureIndicesDescriptor do begin with AddIndex('IUID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('UID')); with AddIndex('IChave', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Chave')); with AddIndex('ITran', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Tran')); with AddIndex('IIncluidoEm', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('IncluidoEm')); with AddIndex('ItpAmbStatusInut', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('tpAmb')); Add(GetFieldFromName('StatusInut')); end; with AddIndex('IConsulta', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('tpAmb')); Add(GetFieldFromName('ConsultouChave')); Add(GetFieldFromName('StatusNF')); end; with AddIndex('IStatusCancNumSeq', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('StatusCanc')); Add(GetFieldFromName('NumSeq')); end; with AddIndex('INumSeq', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('NumSeq')); with AddIndex('ItpAmbModeloSerieNumero', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('tpAmb')); Add(GetFieldFromName('Modelo')); Add(GetFieldFromName('Serie')); Add(GetFieldFromName('Numero')); end; with AddIndex('ItpAmbStatus', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('tpAmb')); Add(GetFieldFromName('Status')); end; with AddIndex('IStatusNumSeq', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Status')); Add(GetFieldFromName('NumSeq')); end; with AddIndex('ItpAmbDataHora', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('tpAmb')); Add(GetFieldFromName('DataHora')); end; with AddIndex('IDataHora', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('DataHora')); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // TipoME function __TipoME(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('Tipo', '', nxtWord16, 5, 0, False); AddField('Nome', '', nxtNullString, 3, 0, False); AddField('Entrada', '', nxtBoolean, 0, 0, False); AddField('CliFor', '', nxtByte, 3, 0, False); AddField('ExigirCliFor', '', nxtByte, 3, 0, False); AddField('EmitirNF', '', nxtByte, 3, 0, False); AddField('CFOP1', '', nxtWord16, 5, 0, False); AddField('CFOP2', '', nxtWord16, 5, 0, False); AddField('CFOP3', '', nxtWord16, 5, 0, False); AddField('TipoNF1', '', nxtByte, 3, 0, False); AddField('TipoNF2', '', nxtByte, 3, 0, False); AddField('TipoNF3', '', nxtByte, 3, 0, False); AddField('EmitirAuto1', '', nxtBoolean, 0, 0, False); AddField('EmitirAuto2', '', nxtBoolean, 0, 0, False); AddField('EmitirAuto3', '', nxtBoolean, 0, 0, False); end; with EnsureIndicesDescriptor do with AddIndex('ITipo', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Tipo')); CheckValid(False); end; except FreeAndNil(Result); raise; end; end; function __Terminal(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('TermID', '', nxtGUID, 0, 0, False); AddField('Nome', '', nxtNullString, 50, 0, False); AddField('Opcoes', '', nxtBLOBMemo, 0, 0, False); AddField('RECVER', '', nxtWord32, 9, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('ITermID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('TermID')); with AddIndex('INome', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Nome')); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // NCM function __NCM(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('NCM', '', nxtNullString, 8, 0, False); AddField('Ex', '', nxtNullString, 2, 0, False); AddField('Descricao', '', nxtNullString, 100, 0, False); AddField('ImpostoFed_Imp', '', nxtDouble, 0, 0, False); AddField('ImpostoFed_Nac', '', nxtDouble, 0, 0, False); AddField('ImpostoEst', '', nxtDouble, 0, 0, False); AddField('ImpostoMun', '', nxtDouble, 0, 0, False); AddField('RECVER', '', nxtWord32, 9, 0, False); end; with EnsureIndicesDescriptor do with AddIndex('IID', 0, idNull), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with IndicesDescriptor.AddIndex('ISuperBusca', 0, True, '', TnxMainIndexTokenKeyDescriptor) do with (KeyDescriptor as TnxMainIndexTokenKeyDescriptor) do MaxTokenSize := 50; // set max key length here with EnsureFulltextDescriptor(Result) do with AddFullTextIndex('full_superbusca') do begin // N.B. you can add extractors for as many fields as you like here: AddFieldTokenExtractor(FieldsDescriptor.GetFieldFromName('Descricao'), '', TnxKwicTokenExtractorDescriptor); with TnxMainIndexTokenIndexDescriptor(AddTokenIndex('ISuperBusca', TnxMainIndexTokenIndexDescriptor)) do begin MainIndexNumber := 2; IgnoreCase := True; { with AddLocaleDescriptor do begin Locale := $00000416; Flags := $00001000; UseStringSort := True; end; } end; end; with EnsureIndicesDescriptor do begin with AddIndex('IDescricao', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Descricao'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; Flags := $00001000; UseStringSort := True; end; end; with AddIndex('INCM', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('NCM')); Add(GetFieldFromName('Ex')); end; with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; function __Doc(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); AddLocaleDescriptor; with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); with AddField('UID', '', nxtGUID, 0, 0, False) do with AddDefaultValue(TnxAutoGuidDefaultValueDescriptor) as TnxAutoGuidDefaultValueDescriptor do ApplyAt := [aaClient]; AddField('Tipo', '0-Recibo venda, 1-orçamento, 2-etiqueta, 3-pg.débito', nxtByte, 1, 0, False); AddField('Bobina', '', nxtBoolean, 0, 0, False); AddField('Free', '', nxtBoolean, 0, 0, False); AddField('TextOnly', '', nxtBoolean, 0, 0, False); AddField('Tamanho', '', nxtNullString, 20, 0, False); AddField('Nome', '', nxtNullString, 100, 0, False); AddField('Obs', '', nxtBLOBMemo, 0, 0, False); AddField('Params', '', nxtBLOBMemo, 0, 0, False); AddField('Doc', '', nxtBLOB, 0, 0, False); AddField('Img', '', nxtBLOBGraphic, 0, 0, False); AddField('Custom', '', nxtBoolean, 0, 0, False); with AddField('MinVer', '', nxtWord16, 9, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; AddField('SRECVER', '', nxtWord32, 9, 0, False); AddField('RECVER', '', nxtWord32, 9, 0, False); end; with EnsureIndicesDescriptor do with AddIndex('IID', 0, idNone), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with IndicesDescriptor.AddIndex('ISuperBuscaDoc', 0, True, '', TnxMainIndexTokenKeyDescriptor) do with (KeyDescriptor as TnxMainIndexTokenKeyDescriptor) do MaxTokenSize := 50; // set max key length here with EnsureFulltextDescriptor(Result) do with AddFullTextIndex('full_superbuscadoc') do begin // N.B. you can add extractors for as many fields as you like here: AddFieldTokenExtractor(FieldsDescriptor.GetFieldFromName('Nome'), '', TnxKwicTokenExtractorDescriptor); AddFieldTokenExtractor(FieldsDescriptor.GetFieldFromName('Obs'), '', TnxKwicTokenExtractorDescriptor); with TnxMainIndexTokenIndexDescriptor(AddTokenIndex('ISuperBuscaDoc', TnxMainIndexTokenIndexDescriptor)) do begin MainIndexNumber := 2; IgnoreCase := True; end; end; with EnsureIndicesDescriptor do with AddIndex('IUID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('UID')); with EnsureIndicesDescriptor do begin with AddIndex('ITipoBobinaNome', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Tipo')); Add(GetFieldFromName('Bobina')); Add(GetFieldFromName('Nome')); end; with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); with AddIndex('ISRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('SRecVer')); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; function __syslog(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); with AddField('DataHora', '', nxtDateTime, 0, 0, False) do with AddDefaultValue(TnxCurrentDateTimeDefaultValueDescriptor) as TnxCurrentDateTimeDefaultValueDescriptor do ApplyAt := [aaServer]; AddField('Info', '', nxtNullString, 30, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idNull), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('IInfo', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Info')); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // IOrcamento function __IOrcamento(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('Orcamento_UID', '', nxtGUID, 0, 0, False); with AddField('UID', '', nxtGUID, 0, 0, False) do AddDefaultValue(TnxAutoGuidDefaultValueDescriptor); AddField('Item', '', nxtWord16, 5, 0, False); AddField('Produto', '', nxtWord32, 5, 0, False); AddField('Descr', '', nxtBLOBMemo, 0, 0, False); AddField('Unitario', '', nxtCurrency, 16, 0, False); AddField('Quant', '', nxtExtended, 0, 0, False); AddField('Total', '', nxtCurrency, 16, 0, False); AddField('Desconto', '', nxtCurrency, 16, 0, False); AddField('TotalFinal', '', nxtCurrency, 16, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IOrcamento_UID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Orcamento_UID')); Add(GetFieldFromName('Item')); end; with AddIndex('IUID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('UID')); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Orcamento function __Orcamento(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin with AddField('UID', '', nxtGUID, 0, 0, False) do with AddDefaultValue(TnxAutoGuidDefaultValueDescriptor) as TnxAutoGuidDefaultValueDescriptor do ApplyOnInsert := False; AddField('IDSeq', '', nxtAutoInc, 10, 0, False); AddField('RecVer', '', nxtWord32, 10, 0, False); with AddField('CriadoEm', '', nxtDateTime, 0, 0, False) do with AddDefaultValue(TnxCurrentDateTimeDefaultValueDescriptor) as TnxCurrentDateTimeDefaultValueDescriptor do begin ApplyOnModify := True; ApplyAt := [aaServer]; end; with AddField('Status', '0-Pendente, 1-Aprovado, 2-Recusado, 3-Vendido, 4-Expirado', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; AddField('AtualizadoEm', '', nxtDateTime, 0, 0, False); AddField('AprovadoEm', '', nxtDateTime, 0, 0, False); AddField('RecusadoEm', '', nxtDateTime, 0, 0, False); AddField('VendidoEm', '', nxtDateTime, 0, 0, False); AddField('ExpiradoEm', '', nxtDateTime, 0, 0, False); AddField('StatusAlteradoEm', '', nxtDateTime, 0, 0, False); AddField('Func', '', nxtNullString, 20, 0, False); AddField('IDVenda', '', nxtWord32, 10, 0, False); AddField('Cliente', '', nxtWord32, 10, 0, False); AddField('Total', '', nxtCurrency, 10, 0, False); AddField('Desconto', '', nxtCurrency, 10, 0, False); AddField('TotalFinal', '', nxtCurrency, 16, 0, False); AddField('Vendido', '', nxtBoolean, 0, 0, False); AddField('ValData', '', nxtDateTime, 0, 0, False); AddField('ValModo', '', nxtByte, 0, 0, False); AddField('ValTempo', '', nxtWord16, 0, 0, False); AddField('ValUTempo', '', nxtByte, 0, 0, False); AddField('Obs', '', nxtBLOBMemo, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IUID', 0, idNone), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('UID')); with AddIndex('IIDSeq', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('IDSeq')); with AddIndex('ICriadoEm', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('CriadoEm')); with AddIndex('IAtualizadoEm', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('AtualizadoEm')); with AddIndex('IClienteCriadoEm', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('CriadoEm')); end; with AddIndex('IStatusEm', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Status')); Add(GetFieldFromName('StatusAlteradoEm')); end; with AddIndex('IStatusValData', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Status')); Add(GetFieldFromName('ValData')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Biometria function __Biometria(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); { with AddField('uuid', '', nxtGUID, 0, 0, False) do AddDefaultValue(TnxAutoGuidDefaultValueDescriptor); AddField('Cliente_uuid', '', nxtGUID, 0, 0, False); } AddField('Cliente', '', nxtWord32, 10, 0, False); AddField('Template', '', nxtBLOB, 0, 0, False); AddField('UAcesso', '', nxtDateTime, 0, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin { with AddIndex('Iuuid', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('uuid'));} with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('ID'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; with AddIndex('IClienteID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Cliente'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; with AddIndex('IUAcesso', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('UAcesso'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin Ascend := False; IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Caixa function __Caixa(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('IDLivre', '', nxtNulLString, 10, 0, False); AddField('Aberto', '', nxtBoolean, 0, 0, False); AddField('Usuario', '', nxtNullString, 20, 0, False); AddField('Abertura', '', nxtDateTime, 0, 0, False); AddField('Fechamento', '', nxtDateTime, 0, 0, False); AddField('Reproc', '', nxtDateTime, 0, 0, False); AddField('TotalFinal', '', nxtCurrency, 16, 0, False); AddField('Descontos', '', nxtCurrency, 16, 0, False); AddField('Cancelamentos', '', nxtCurrency, 16, 0, False); AddField('Sangria', '', nxtCurrency, 16, 0, False); AddField('Supr', '', nxtCurrency, 16, 0, False); AddField('SaldoAnt', '', nxtCurrency, 16, 0, False); AddField('Obs', '', nxtBLOBMemo, 0, 0, False); AddField('EstSessoesQtd', '', nxtInt32, 10, 0, False); AddField('EstSessoesTempo', '', nxtDouble, 0, 0, False); AddField('EstUrls', '', nxtInt32, 10, 0, False); AddField('EstSyncOk', '', nxtBoolean, 0, 0, False); AddField('EstBuscasEng', '', nxtBLOBMemo, 0, 0, False); AddField('EstRes', '', nxtBLOBMemo, 0, 0, False); AddField('SaldoF', '', nxtCurrency, 16, 0, False); AddField('Quebra', '', nxtCurrency, 16, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('IUsuario', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin with Add(GetFieldFromName('Usuario'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00030002; IgnoreKanaType := True; IgnoreNonSpace := True; Ignorewidth := True; end; end; Add(GetFieldFromName('Abertura')); end; with AddIndex('IAbertura', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Abertura')); with AddIndex('IAberto', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Aberto')); Add(GetFieldFromName('Abertura')); end; with AddIndex('IAbertoEstSyncOk', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Aberto')); Add(GetFieldFromName('EstSyncOk')); end; with AddIndex('IIDLivre', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('IDLivre')); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Categoria function __Categoria(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('Descricao', '', nxtNullString, 35, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do with AddIndex('uq_Categoria', 0, idNone), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Descricao'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; DefaultIndex := GetIndexFromName('uq_Categoria'); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; function __CC(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Cliente', '', nxtNulLString, 10, 0, False); AddField('DataHora', '', nxtDateTime, 0, 0, False); AddField('Caixa', '', nxtWord32, 0, 0, False); AddField('Open', '', nxtWord16, 0, 0, False); AddField('Tran', '', nxtWord32, 20, 0, False); AddField('Valor', '', nxtCurrency, 0, 0, False); AddField('Descr', '', nxtBlobMemo, 0, 0, False); AddField('ValorAnt', '', nxtCurrency, 0, 0, False); AddField('Func', '', nxtNullString, 30, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IClienteID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('ID')); end; with AddIndex('IClienteDH', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('DataHora')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Unidade function __Unidade(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('Descricao', '', nxtNullString, 5, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do with AddIndex('uq_Unidade', 0, idNone), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Descricao'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; DefaultIndex := GetIndexFromName('uq_Unidade'); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Cliente function __Cliente(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); AddLocaleDescriptor; with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Codigo', '', nxtNullString, 15, 0, False); AddField('CodigoKey', '', nxtNullString, 15, 0, False); AddField('Nome', '', nxtNullString, 40, 0, False); AddField('Endereco', '', nxtNullString, 50, 0, False); AddField('Bairro', '', nxtNullString, 20, 0, False); AddField('Cidade', '', nxtNullString, 30, 0, False); AddField('UF', '', nxtNullString, 30, 0, False); AddField('CEP', '', nxtNullString, 10, 0, False); AddField('Sexo', 'M=Masculo, F=Feminino', nxtChar, 1, 0, False); AddField('Obs', '', nxtBLOBMemo, 0, 0, False); AddField('Cpf', '', nxtNullString, 20, 0, False); AddField('Rg', '', nxtNullString, 20, 0, False); AddField('Telefone', '', nxtNullString, 15, 0, False); AddField('Email', '', nxtBLOBMemo, 0, 0, False); AddField('Passaportes', '', nxtDouble, 10, 0, False); AddField('Pai', '', nxtNullString, 40, 0, False); AddField('Mae', '', nxtNullString, 40, 0, False); AddField('Senha', '', nxtNullString, 20, 0, False); AddField('UltVisita', '', nxtDateTime, 0, 0, False); AddField('Debito', '', nxtCurrency, 16, 0, False); AddField('Escola', '', nxtNullString, 40, 0, False); AddField('NickName', '', nxtNullString, 30, 0, False); AddField('DataNasc', '', nxtDateTime, 0, 0, False); AddField('Celular', '', nxtNullString, 15, 0, False); AddField('TemDebito', '', nxtBoolean, 0, 0, False); AddField('LimiteDebito', '', nxtCurrency, 16, 0, False); AddField('Foto', '', nxtBLOBGraphic, 0, 0, False); AddField('IncluidoEm', '', nxtDateTime, 0, 0, False); AddField('AlteradoEm', '', nxtDateTime, 0, 0, False); AddField('IncluidoPor', '', nxtNullString, 10, 0, False); AddField('AlteradoPor', '', nxtNullString, 10, 0, False); AddField('TitEleitor', '', nxtNullString, 13, 0, False); AddField('FidPontos', '', nxtDouble, 10, 0, False); AddField('FidTotal', '', nxtDouble, 10, 0, False); AddField('FidResg', '', nxtDouble, 10, 0, False); AddField('Aniversario', '', nxtNullString, 4, 0, False); AddField('SemFidelidade', '', nxtBoolean, 0, 0, False); AddField('TemCredito', '', nxtBoolean, 0, 0, False); with AddField('PJuridica', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('Inativo', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('Fornecedor', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('ValorCred', '', nxtCurrency, 16, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); end; with EnsureIndicesDescriptor do with AddIndex('IID', 0, idNone), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with IndicesDescriptor.AddIndex('ISuperBusca', 0, True, '', TnxMainIndexTokenKeyDescriptor) do with (KeyDescriptor as TnxMainIndexTokenKeyDescriptor) do MaxTokenSize := 50; // set max key length here with EnsureFulltextDescriptor(Result) do with AddFullTextIndex('full_superbusca') do begin // N.B. you can add extractors for as many fields as you like here: AddFieldTokenExtractor(FieldsDescriptor.GetFieldFromName('Nome'), '', TnxKwicTokenExtractorDescriptor); with TnxMainIndexTokenIndexDescriptor(AddTokenIndex('ISuperBusca', TnxMainIndexTokenIndexDescriptor)) do begin MainIndexNumber := 2; IgnoreCase := True; { with AddLocaleDescriptor do begin Locale := $00000416; Flags := $00001000; UseStringSort := True; end; } end; end; with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); with EnsureIndicesDescriptor do begin with AddIndex('ICodigoKey', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('CodigoKey')); with AddIndex('IUltVisita', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('UltVisita')); with AddIndex('IAniversario', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Aniversario'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; with AddIndex('INome', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Nome'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; with AddIndex('IFornecedorNome', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Fornecedor')); with Add(GetFieldFromName('Nome'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; end; with AddIndex('IFornecedorID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Fornecedor')); Add(GetFieldFromName('ID')); end; with AddIndex('IFornecedorCodigoKey', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Fornecedor')); Add(GetFieldFromName('CodigoKey')); end; with AddIndex('IRg', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Rg'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; with AddIndex('ICPF', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('CPF'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; with AddIndex('IDebito', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('TemDebito')); with Add(GetFieldFromName('Nome'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00030002; IgnoreKanaType := True; IgnoreNonSpace := True; Ignorewidth := True; end; end; end; with AddIndex('ICredito', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('TemCredito')); with Add(GetFieldFromName('Nome'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00030002; IgnoreKanaType := True; IgnoreNonSpace := True; Ignorewidth := True; end; end; end; with AddIndex('IFidPontos', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('FidPontos')); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Config function __Config(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('NumSeq', '', nxtAutoInc, 10, 0, False); AddField('FecharProgramas', '', nxtBoolean, 0, 0, False); AddField('AutoExecutar', '', nxtNullString, 200, 0, False); AddField('LimiteTempoPadrao', '', nxtDateTime, 0, 0, False); AddField('PacoteTempoReal', '', nxtBoolean, 0, 0, False); AddField('PermiteLoginSemCred', '', nxtBoolean, 0, 0, False); with AddField('AlteraLoginSemCred', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('EncerramentoPrePago', '', nxtByte, 3, 0, False); with AddField('EncerramentoCartao', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 1; with AddField('MeioPagto', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; with AddField('TempoEPrePago', '', nxtWord16, 5, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 60; with AddField('TempoECartao', '', nxtWord16, 5, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 60; AddField('PermiteCapturaTela', '', nxtBoolean, 0, 0, False); with AddField('VariosTiposAcesso', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('ModoPagtoAcesso', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; with AddField('MostraPrePagoDec', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('MostraNomeMaq', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('AutoCad', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('QuickCad', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('CodProdutoDuplicados', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('TempoMaxAlerta', '', nxtDateTime, 0, 0, False); AddField('Abre1', '', nxtDateTime, 0, 0, False); AddField('Abre2', '', nxtDateTime, 0, 0, False); AddField('Abre3', '', nxtDateTime, 0, 0, False); AddField('Abre4', '', nxtDateTime, 0, 0, False); AddField('Abre5', '', nxtDateTime, 0, 0, False); AddField('Abre6', '', nxtDateTime, 0, 0, False); AddField('Abre7', '', nxtDateTime, 0, 0, False); AddField('Fecha1', '', nxtDateTime, 0, 0, False); AddField('Fecha2', '', nxtDateTime, 0, 0, False); AddField('Fecha3', '', nxtDateTime, 0, 0, False); AddField('Fecha4', '', nxtDateTime, 0, 0, False); AddField('Fecha5', '', nxtDateTime, 0, 0, False); AddField('Fecha6', '', nxtDateTime, 0, 0, False); AddField('Fecha7', '', nxtDateTime, 0, 0, False); AddField('CorLivre', '', nxtInt32, 10, 0, False); AddField('CorFLivre', '', nxtInt32, 10, 0, False); AddField('CorUsoPrePago', '', nxtInt32, 10, 0, False); AddField('CorFUsoPrePago', '', nxtInt32, 10, 0, False); AddField('CorUsoPosPago', '', nxtInt32, 10, 0, False); AddField('CorFUsoPosPago', '', nxtInt32, 10, 0, False); AddField('CorAguardaPagto', '', nxtInt32, 10, 0, False); AddField('CorFAguardaPagto', '', nxtInt32, 10, 0, False); AddField('CorManutencao', '', nxtInt32, 10, 0, False); AddField('CorFManutencao', '', nxtInt32, 10, 0, False); AddField('CorPausado', '', nxtInt32, 10, 0, False); AddField('CorFPausado', '', nxtInt32, 10, 0, False); AddField('CorDesktop', '', nxtInt32, 10, 0, False); AddField('CorFDesktop', '', nxtInt32, 10, 0, False); with AddField('CorMaqManut', '', nxtInt32, 10, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; with AddField('CorFMaqManut', '', nxtInt32, 10, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 12632256; with AddField('CorPrevisao', '', nxtInt32, 10, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 255; with AddField('CorFPrevisao', '', nxtInt32, 10, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 16777215; AddField('CampoLocalizaCli', '0=nome, 1=username, 2=código', nxtByte, 3, 0, False); AddField('ManterSaldoCaixa', '', nxtBoolean, 0, 0, False); AddField('NaoMostrarMsgDebito', '', nxtBoolean, 0, 0, False); with AddField('NaoCobrarImpFunc', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('Tolerancia', '', nxtDateTime, 0, 0, False); AddField('RegImp98', '', nxtBoolean, 0, 0, False); AddField('LimitePadraoDebito', '', nxtCurrency, 16, 0, False); AddField('RecPorta', '', nxtNullString, 100, 0, False); AddField('RecSalto', '', nxtWord16, 5, 0, False); AddField('RecLargura', '', nxtWord16, 5, 0, False); AddField('RecRodape', '', nxtBLOBMemo, 0, 0, False); AddField('RecImprimir', '', nxtByte, 3, 0, False); AddField('RecMatricial', '', nxtBoolean, 0, 0, False); AddField('RecTipoImpressora', '', nxtNullString, 32, 0, False); AddField('RecNomeLoja', '', nxtNullString, 40, 0, False); AddField('RecCortaFolha', '', nxtBoolean, 0, 0, False); with AddField('RecImprimeMeioPagto', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('RecPrefixoMeioPagto', '', nxtNullString, 30, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 'Pg.'; with AddField('MostraProgAtual', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; AddField('MostraObs', '', nxtBoolean, 0, 0, False); AddField('EscondeTextoBotoes', '', nxtBoolean, 0, 0, False); AddField('EscondeTipoAcesso', '', nxtBoolean, 0, 0, False); AddField('ExigirRG', '', nxtBoolean, 0, 0, False); AddField('TipoFDesktop', '', nxtNullString, 3, 0, False); AddField('TipoFLogin', '', nxtNullString, 3, 0, False); AddField('NumFDesktop', '', nxtInt32, 10, 0, False); AddField('NumFLogin', '', nxtInt32, 10, 0, False); AddField('FundoWeb', '', nxtBoolean, 0, 0, False); AddField('FundoWebURL', '', nxtBLOBMemo, 0, 0, False); AddField('MostrarApenasPIN', '', nxtBoolean, 0, 0, False); AddField('TextoPIN', '', nxtNullString, 30, 0, False); AddField('AlterarSenhaCli', '', nxtBoolean, 0, 0, False); AddField('VerSenhaCli', '', nxtBoolean, 0, 0, False); AddField('CliCadPadrao', '', nxtBoolean, 0, 0, False); with AddField('ControlaImp', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; AddField('FiltrarWEB', '', nxtBoolean, 0, 0, False); AddField('SiteRedirFiltro', '', nxtNullString, 80, 0, False); AddField('PastaDownload', '', nxtNullString, 1024, 0, False); with AddField('MinutosDesligaMaq', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; with AddField('MinutosDesligaMon', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; with AddField('BloqDownload', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('BloqDownloadExe', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('BloqMenuIniciar', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('BloqPainelCtrl', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('BloqCtrlAltDel', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('BloqExecutar', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('BloqMeusLocaisRede', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('BloqMeuComputador', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('BloqLixeira', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('BloqMeusDocumentos', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('ClassicStartMenu', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('BloqTray', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('BloqBotaoDir', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('BloqToolbars', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('BloqPosPago', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('FiltrarDesktop', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('FiltrarMenuIniciar', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('TempoB1', '', nxtWord16, 5, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 10; with AddField('TempoB2', '', nxtWord16, 5, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 15; with AddField('TempoB3', '', nxtWord16, 5, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 30; with AddField('TempoB4', '', nxtWord16, 5, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 60; with AddField('TempoB5', '', nxtWord16, 5, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 120; with AddField('TempoB6', '', nxtWord16, 5, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 180; AddField('PaginaInicial', '', nxtNullString, 200, 0, False); AddField('EsconderCronometro', '', nxtBoolean, 0, 0, False); AddField('AposEncerrar', '', nxtByte, 3, 0, False); AddField('AlinhaBarraGuard', '', nxtByte, 3, 0, False); AddField('NoNet', '', nxtByte, 3, 0, False); AddField('TempoSumirLogin', '', nxtWord16, 5, 0, False); AddField('EsconderDrives', '', nxtNullString, 30, 0, False); with AddField('EmailMetodo', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; AddField('EmailServ', '', nxtNullString, 50, 0, False); AddField('EmailUsername', '', nxtNullString, 50, 0, False); AddField('EmailSenha', '', nxtNullString, 50, 0, False); AddField('EmailDestino', '', nxtBLOBMemo, 0, 0, False); AddField('EmailIdent', '', nxtNullString, 20, 0, False); AddField('Flags', '', nxtBLOBMemo, 0, 0, False); with AddField('EmailEnviarCaixa', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('EmailConteudo', '', nxtNullString, 20, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := '11111111111111111111'; with AddField('AlertaAssinatura', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('CredPadraoTipo', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 1; with AddField('CredPadraoCod', '', nxtInt32, 10, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; with AddField('PgVendas', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('PgVendaAvulsa', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('PgAcesso', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('PgTempo', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('PgImp', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('BloquearUsoEmHorarioNP', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('OpcaoChat', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; with AddField('SalvarCodUsername', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('ContinuarCredTempo', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('NaoGuardarCreditoCli', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('RelCaixaAuto', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('SincronizarHorarios', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('MostrarDebitoNoGuard', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('BloquearLoginAlemMaxDeb', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('ClienteNaoAlteraSenha', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('NaoObrigarSenhaCliente', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('NaoVenderAlemEstoque', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('CreditoComoValor', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('CliAvulsoNaoEncerra', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('AutoSortGridCaixa', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('AvisoFimTempoAdminS', '', nxtByte, 3, 0, False); with AddField('DetectarImpServ', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('AvisoCreditos', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('ClientePodeVerCred', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('ChatAlertaSonoro', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('ChatMostraNotificacao', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('ModoCredGuard', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; with AddField('MsgFimCred', '', nxtNullString, 150, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 'Você possui outros créditos que não podem ser utilizados no momento. Para maiores informações consulte o atendente.'; with AddField('SemLogin', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('AutoObsAoCancelar', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('FidAtivo', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('FidVendaValor', '', nxtCurrency, 16, 0, False); AddField('FidVendaPontos', '', nxtInt32, 10, 0, False); with AddField('FidParcial', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('FidAutoPremiar', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('FidAutoPremiarValor', '', nxtCurrency, 16, 0, False); AddField('FidAutoPremiarPontos', '', nxtInt32, 10, 0, False); with AddField('FidMostrarSaldoAdmin', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('FidMsg', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('FidMsgTitulo', '', nxtNullString, 50, 0, False); AddField('FidMsgTexto', '', nxtBlobMemo, 0, 0, False); with AddField('CliCadNaoEncerra', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('ImpedirPosPago', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('AutoLigarMaqCli', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('Biometria', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('PMPausaAutomatica', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('PMConfirmaImpCliente', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('PMConfirmaImpAdmin', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('PMMostrarPaginasCli', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('PMMostrarValorCli', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('PMCalcValorCli', '', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; with AddField('PMPromptValorCli', '', nxtNullString, 100, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 'Custo da Impressão: '; with AddField('PMObsValorCli', '', nxtNullString, 300, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := '* O custo pode variar dependendo do tipo da impressão (preto e branco/colorida)'; AddField('PMPausarServ', '', nxtBoolean, 0, 0, False); AddField('PMNaoPausar', '', nxtBlobMemo, 0, 0, False); AddField('PMCotas', '', nxtBoolean, 0, 0, False); AddField('PMCotasMaxPagDia', '', nxtWord32, 10, 0, False); AddField('PMCotasMaxPagMes', '', nxtWord32, 10, 0, False); with AddField('PMCotasOpCota', '0-confirmar impressao, 1-liberar automaticamente', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; with AddField('PMCotasOpExcesso', '0-atendente pode liberar, 1-cancelar imp, 2-cobrar', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; AddField('PMCotasMaxExcesso', '', nxtWord32, 10, 0, False); AddField('PMCotasPorCli', '', nxtBoolean, 0, 0, False); with AddField('PMPDF', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('PMPDFPrintEng', '', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := printeng_clprint; with AddField('PMReviewCli', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('PMReviewAdmin', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('PubHomePage', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('PubAd', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('PubToolbar', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('MaxTempoSessao', '', nxtWord16, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; AddField('TarifaPadrao', '', nxtInt32, 0, 0, False); with AddField('TarifaPorHorario', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('BloqueiaCliAvulso', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('ExigeDadosMinimos', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('DadosMinimos', '', nxtNullString, 300, 0, False); AddField('CidadePadrao', '', nxtNullString, 50, 0, False); AddField('UFPadrao', '', nxtNullString, 2, 0, False); with AddField('PedirSaldoI', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('PedirSaldoF', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('BRT', '', nxtWord16, 5, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 60; with AddField('DTol', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 5; AddField('DVA', '', nxtDateTime, 0, 0, False); AddField('ProxAvisoAss', '', nxtDateTime, 0, 0, False); with AddField('PreLib', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('ExCookie', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('HPOpenBef', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('CamposCliCC', '', nxtBLOBMemo, 0, 0, False); with AddField('CliCongelado', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('SenhaAdminOk', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('QtdMaqOk', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('PosLogin', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := poslogin_centro; with AddField('HomePage_AddConta', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('HomePage_Tab', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; AddField('HomePage_LastURL', '', nxtDateTime, 0, 0, False); AddField('HomePage_URL', '', nxtNullString, 300, 0, False); AddField('HomePage_Params', '', nxtNullString, 300, 0, False); AddField('Sky_Params', '', nxtNullString, 300, 0, False); AddField('Banners', '', nxtBlobMemo, 0, 0, False); AddField('Botoes', '', nxtBlobMemo, 0, 0, False); AddField('FaixaComanda', '', nxtNullString, 100, 0, False); AddField('Recursos', '', nxtNullString, 30, 0, False); AddField('PrecoAuto', '', nxtBoolean, 0, 0, False); AddField('Margem', '', nxtDouble, 0, 0, False); AddField('ComissaoPerc', '', nxtDouble, 0, 0, False); AddField('ValOrc_Tempo', '', nxtWord16, 0, 0, False); AddField('ValOrc_UTempo', '', nxtByte, 0, 0, False); with AddField('EmailOrc_Enviar', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; AddField('EmailOrc_FromName', '', nxtNullString, 100, 0, False); AddField('EmailOrc_FromEmail', '', nxtNullString, 100, 0, False); with AddField('EmailOrc_Subject', '', nxtNullString, 100, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 'Orçamento #[numero]'; AddField('EmailOrc_Body', '', nxtBlobMemo, 0, 0, False); with AddField('DocOrc_Imprimir', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; AddField('DocOrc_NomeLoja', '', nxtNullString, 50, 0, False); AddField('ObsPadraoOrcamento', '', nxtBLOBMemo, 0, 0, False); with AddField('ComissaoLucro', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('CodBarBal', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('CodBarBalTam', '', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 13; with AddField('CodBarBalIdent', '', nxtNullString, 5, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := '2'; with AddField('CodBarBalInicioCod', '', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 2; with AddField('CodBarBalTamCod', '', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 5; with AddField('CodBarBalValor', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('CodBarBalPPInicio', '', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 7; with AddField('CodBarBalPPTam', '', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 6; with AddField('CodBarBalPPDig', '', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 2; with AddField('CodBarMaxQtdDig', '', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 3; with AddField('CodBarArredondar', '', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 4; with AddField('ComandaOff', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('MesasOff', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('ConsumoAvulsoOff', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('ConfirmarDebito', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('TelaPosVenda_Mostrar', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('ExigirVendedor', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('TelaPosVenda_BtnDef', '', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 1; AddField('RecVer', '', nxtWord32, 0, 0, False); with AddField('TrocoMax', '', nxtCurrency, 16, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 1000; AddField('DocParam_Email', '', nxtNullString, 100, 0, False); AddField('DocParam_Tel', '', nxtNullString, 15, 0, False); AddField('DocParam_Tel2', '', nxtNullString, 15, 0, False); AddField('DocParam_Cidade', '', nxtNullString, 50, 0, False); AddField('DocParam_End', '', nxtNullString, 100, 0, False); AddField('DocParam_CEP', '', nxtNullString, 9, 0, False); AddField('DocParam_CNPJ', '', nxtNullString, 19, 0, False); AddField('DocParam_IE', '', nxtNullString, 19, 0, False); AddField('DocParam_Site', '', nxtNullString, 50, 0, False); AddField('DocParam_Facebook', '', nxtNullString, 100, 0, False); AddField('DocParam_Instagram', '', nxtNullString, 50, 0, False); AddField('DocParam_Whats', '', nxtNullString, 15, 0, False); AddField('DocParam_Whats2', '', nxtNullString, 15, 0, False); AddField('DocParam_InfoExtra', '', nxtNullString, 100, 0, False); AddField('DocParam_Logo', '', nxtBLOBGraphic, 0, 0, False); AddField('DocParam_Logo2', '', nxtBLOBGraphic, 0, 0, False); AddField('Urls', '', nxtBLOBMemo, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do with AddIndex('INumSeq', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('NumSeq')); CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Debito function __Debito(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('Data', '', nxtDateTime, 0, 0, False); AddField('Cliente', '', nxtWord32, 10, 0, False); AddField('Valor', '', nxtCurrency, 16, 0, False); with AddField('Tipo', '0=Sessao, 1=Credito Tempo, 2=Produto', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; AddField('ID', '', nxtWord32, 10, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('ICliData', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('Data')); end; with AddIndex('ITipoID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Tipo')); Add(GetFieldFromName('ID')); Add(GetFieldFromName('Cliente')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // EmailCorpo function __EmailCorpo(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Corpo', '', nxtBLOBMemo, 0, 0, False); AddField('Destino', '', nxtBLOBMemo, 0, 0, False); AddField('Anexos', '', nxtBLOBMemo, 0, 0, False); AddField('Assunto', '', nxtNullString, 100, 0, False); AddField('Inclusao', '', nxtDateTime, 0, 0, False); AddField('Restam', '', nxtInt32, 10, 0, False); AddField('EnviarEm', '', nxtDateTime, 0, 0, False); AddField('Processou', '', nxtBoolean, 0, 0, False); AddField('ApagarAnexosAposEnvio', '', nxtBoolean, 0, 0, False); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('IProcessou', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Processou')); Add(GetFieldFromName('EnviarEm')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // EmailCriar function __EmailCriar(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Tipo', '', nxtInt32, 10, 0, False); AddField('Parametros', '', nxtBLOBMemo, 0, 0, False); AddField('Destino', '', nxtBLOBMemo, 0, 0, False); end; with EnsureIndicesDescriptor do with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // EmailEnvio function __EmailEnvio(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Corpo', '', nxtInt32, 10, 0, False); AddField('Destino', '', nxtBLOBMemo, 0, 0, False); AddField('Inclusao', '', nxtDateTime, 0, 0, False); AddField('Envio', '', nxtDateTime, 0, 0, False); AddField('Tentativas', '', nxtWord16, 5, 0, False); AddField('Enviar', '', nxtBoolean, 0, 0, False); AddField('MsgErro', '', nxtBLOBMemo, 0, 0, False); AddField('OK', '', nxtBoolean, 0, 0, False); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('ICorpo', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Corpo')); Add(GetFieldFromName('ID')); end; with AddIndex('IEnviar', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Enviar')); Add(GetFieldFromName('OK')); Add(GetFieldFromName('ID')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; function __Post(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Parametros', '', nxtBLOBMemo, 0, 0, False); AddField('Host', '', nxtNullString, 255, 0, False); AddField('URL', '', nxtNullString, 255, 0, False); AddField('ApagarArq', '', nxtBoolean, 0, 0, False); AddField('Arq', '', nxtNullString, 255, 0, False); AddField('Inclusao', '', nxtDateTime, 0, 0, False); AddField('Envio', '', nxtDateTime, 0, 0, False); AddField('Tentativas', '', nxtWord16, 5, 0, False); AddField('Enviar', '', nxtBoolean, 0, 0, False); AddField('MsgErro', '', nxtBLOBMemo, 0, 0, False); AddField('OK', '', nxtBoolean, 0, 0, False); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('IEnviar', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Enviar')); Add(GetFieldFromName('OK')); Add(GetFieldFromName('ID')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; function __PostMS(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('MS', '', nxtBLOB, 0, 0, False); AddField('URL', '', nxtNullString, 255, 0, False); AddField('Inclusao', '', nxtDateTime, 0, 0, False); AddField('Envio', '', nxtDateTime, 0, 0, False); AddField('Tries', '', nxtWord16, 5, 0, False); AddField('Max', '', nxtWord16, 0, 0, False); AddField('NextTry', '', nxtWord32, 0, 0, False); end; with EnsureIndicesDescriptor do begin with AddIndex('INextTryID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('NextTry')); Add(GetFieldFromName('ID')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Espera function __Espera(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Pos', '', nxtInt32, 10, 0, False); AddField('Cliente', '', nxtInt32, 10, 0, False); AddField('NomeCliente', '', nxtNullString, 50, 0, False); AddField('DataHora', '', nxtDateTime, 0, 0, False); AddField('Previsao', '', nxtDateTime, 0, 0, False); AddField('PrevMaq', '', nxtWord16, 5, 0, False); AddField('PrevSessao', '', nxtInt32, 10, 0, False); AddField('Obs', '', nxtNullString, 50, 0, False); AddField('Cartao', '', nxtNullString, 20, 0, False); end; with EnsureIndicesDescriptor do begin with AddIndex('IPos', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Pos')); with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('IMaqSessao', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('PrevMaq')); Add(GetFieldFromName('PrevSessao')); end; with AddIndex('ICartao', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Cartao'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00030002; IgnoreKanaType := True; IgnoreNonSpace := True; Ignorewidth := True; end; end; with AddIndex('ICliente', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Cliente')); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Label {function __Label(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtGUID, 0, 0, False); AddField('RECVER', '', nxtWord32, 10, 0, False); AddField('Nome', '', nxtNullString, 40, 0, False); AddField('Obs', '', nxtBlobMemo, 0, 0, False); AddField('Report', '', nxtBLOB, 0, 0, False); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RECVER')); with AddIndex('INome', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Nome'), TnxTextKeyFieldDescriptor) as TnxTextKeyFieldDescriptor do IgnoreCase := True; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end;} // HCred function __HCred(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('DataHora', '', nxtDateTime, 0, 0, False); AddField('Tipo', '0=tempo, 1=valor', nxtByte, 3, 0, False); AddField('Cliente', '', nxtWord32, 10, 0, False); AddField('Sessao', '', nxtWord32, 10, 0, False); AddField('Tran', '', nxtWord32, 10, 0, False); AddField('SaldoAnt', '', nxtDouble, 0, 0, False); AddField('Quant', '', nxtDouble, 0, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('ICliTipoID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('Tipo')); Add(GetFieldFromName('ID')); end; with AddIndex('ICliTipoDH', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('Tipo')); Add(GetFieldFromName('DataHora')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // HPass function __HPass(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Passaporte', '', nxtWord32, 10, 0, False); AddField('Sessao', '', nxtWord32, 10, 0, False); AddField('DataHora', '', nxtDateTime, 0, 0, False); with AddField('Cancelado', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('MinutosAnt', '', nxtDouble, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; AddField('MinutosUsados', '', nxtDouble, 0, 0, False); with AddField('Expirou', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('IPassSessao', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Passaporte')); Add(GetFieldFromName('Sessao')); end; with AddIndex('ISessaoPass', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Sessao')); Add(GetFieldFromName('Passaporte')); end; with AddIndex('IPassData', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Passaporte')); Add(GetFieldFromName('DataHora')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // ITran function __ITran(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Tran', '', nxtWord32, 10, 0, False); AddField('Caixa', '', nxtWord32, 10, 0, False); AddField('CaixaPag', '', nxtWord32, 10, 0, False); AddField('Cliente', '', nxtWord32, 10, 0, False); AddField('Sessao', '', nxtWord32, 10, 0, False); AddField('DataHora', '', nxtDateTime, 0, 0, False); AddField('IncluidoEm', '', nxtDateTime, 0, 0, False); AddField('TipoTran', '', nxtByte, 3, 0, False); AddField('TipoItem', 'Sessao, Credito, MovEst, Transação', nxtByte, 3, 0, False); AddField('SubTipo', '', nxtByte, 3, 0, False); AddField('ItemID', '', nxtWord32, 10, 0, False); AddField('SubItemID', '', nxtWord32, 10, 0, False); AddField('ItemPos', '', nxtByte, 3, 0, False); AddField('Total', '', nxtCurrency, 16, 0, False); AddField('Desconto', '', nxtCurrency, 16, 0, False); AddField('TotLiq', '', nxtCurrency, 16, 0, False); AddField('Debito', '', nxtCurrency, 16, 0, False); AddField('Pago', '', nxtCurrency, 16, 0, False); AddField('Cancelado', '', nxtBoolean, 0, 0, False); AddField('PagPend', '', nxtBoolean, 0, 0, False); AddField('FidFator', '', nxtInt8, 3, 0, False); AddField('FidPontos', '', nxtDouble, 0, 0, False); AddField('FidMov', '', nxtBoolean, 0, 0, False); with AddField('FidOpe', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('ITipoItemDH', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('TipoItem')); Add(GetFieldFromName('ItemID')); Add(GetFieldFromName('DataHora')); end; with AddIndex('ITranID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Tran')); Add(GetFieldFromName('ID')); end; with AddIndex('IClienteID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('ID')); end; with AddIndex('ICaixaCancelado', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Caixa')); Add(GetFieldFromName('Cancelado')); Add(GetFieldFromName('TipoTran')); Add(GetFieldFromName('TipoItem')); end; with AddIndex('ICaixaPagCancelado', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('CaixaPag')); Add(GetFieldFromName('Cancelado')); Add(GetFieldFromName('TipoTran')); Add(GetFieldFromName('TipoItem')); end; with AddIndex('ITipoItemTran', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('TipoItem')); Add(GetFieldFromName('ItemID')); Add(GetFieldFromName('Tran')); end; with AddIndex('IFidMovClienteDH', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('FidMov')); Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('DataHora')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Layout function __Layout(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('Usuario', '', nxtNullString, 20, 0, False); AddField('Grid', '', nxtNullString, 40, 0, False); AddField('Nome', '', nxtNullString, 100, 0, False); AddField('Publico', '', nxtBoolean, 0, 0, False); AddField('Layout', '', nxtBLOB, 0, 0, False); AddField('Filtro', '', nxtBLOB, 0, 0, False); AddField('Usuarios', '', nxtBLOBMemo, 0, 0, False); end; with EnsureIndicesDescriptor do with AddIndex('IPubGridUsuario', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Publico')); with Add(GetFieldFromName('Grid'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; with Add(GetFieldFromName('Usuario'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; with Add(GetFieldFromName('Nome'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Log function __Log(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('DiaHora', '', nxtDateTime, 0, 0, False); AddField('Maquina', '', nxtWord16, 5, 0, False); AddField('Usuario', '', nxtNullString, 20, 0, False); AddField('Programa', '0=nenhum, 1=ncguard, 2=ncadmin, 3=ncserver', nxtByte, 3, 0, False); AddField('Operacao', '', nxtNullString, 70, 0, False); AddField('Horas', '', nxtDateTime, 0, 0, False); AddField('Dias', '', nxtWord16, 5, 0, False); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('IDiaHora', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('DiaHora')); with AddIndex('IUsuarioNumSeq', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('IUsuarioDiaHora', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin with Add(GetFieldFromName('Usuario'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; Add(GetFieldFromName('DiaHora')); end; with AddIndex('IProgramaMaq', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Programa')); Add(GetFieldFromName('Maquina')); Add(GetFieldFromName('ID')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Maq function __Maq(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('Numero', '', nxtWord16, 5, 0, False); AddField('Nome', '', nxtNullString, 30, 0, False); AddField('Menu', '', nxtBLOBMemo, 0, 0, False); AddField('Recursos', '', nxtBLOBMemo, 0, 0, False); AddField('ComputerName', '', nxtNullString, 200, 0, False); with AddField('TipoAcesso', '', nxtInt32, 10, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := -1; with AddField('EmManutencao', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('Obs', '', nxtBLOBMemo, 0, 0, False); AddField('IP', '', nxtNullString, 15, 0, False); AddField('MacAddress', '', nxtNullString, 20, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do with AddIndex('INumero', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Numero')); CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Maquina function __Maquina(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('Numero', '', nxtWord16, 5, 0, False); AddField('Nome', '', nxtNullString, 30, 0, False); AddField('Menu', '', nxtBLOBMemo, 0, 0, False); AddField('Recursos', '', nxtBLOBMemo, 0, 0, False); AddField('ComputerName', '', nxtNullString, 200, 0, False); with AddField('TipoAcesso', '', nxtInt32, 10, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := -1; with AddField('EmManutencao', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('Obs', '', nxtBLOBMemo, 0, 0, False); AddField('URLLogin', '', nxtBLOBMemo, 0, 0, False); AddField('ProgramaAtual', '', nxtBLOBMemo, 0, 0, False); AddField('SiteAtual', '', nxtBLOBMemo, 0, 0, False); AddField('IPConfig', '', nxtBLOBMemo, 0, 0, False); AddField('IP', '', nxtNullString, 30, 0, False); AddField('MacAddress', '', nxtNullString, 20, 0, False); AddField('RAM', '', nxtWord32, 10, 0, False); AddField('CPU', '', nxtNullString, 50, 0, False); AddField('OS', '', nxtNullString, 50, 0, False); AddField('Printers', '', nxtBlobMemo, 0, 0, False); AddField('Drives', '', nxtNullString, 25, 0, False); AddField('HDTotal', '', nxtWord32, 10, 0, False); AddField('HDFree', '', nxtWord32, 10, 0, False); AddField('Patrocinio', '', nxtNullString, 20, 0, False); AddField('DisplayH', '', nxtWord16, 5, 0, False); AddField('DisplayW', '', nxtWord16, 5, 0, False); AddField('DisplayWH', '', nxtNullString, 10, 0, False); AddField('LastScan', '', nxtDateTime, 0, 0, False); AddField('SessionID', '', nxtWord32, 0, 0, False); AddField('ConnectTime', '', nxtDateTime, 0, 0, False); with AddField('AvisaFimTempo', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do with AddIndex('INumero', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Numero')); CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // MovEst function __MovEst(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('ID_ref', '', nxtWord32, 0, 0, False); AddField('Tran', '', nxtWord32, 10, 0, False); AddField('Produto', '', nxtWord32, 10, 0, False); AddField('Quant', '', nxtDouble, 0, 0, False); AddField('Unitario', '', nxtCurrency, 16, 0, False); AddField('Total', '', nxtCurrency, 16, 0, False); AddField('CustoU', '', nxtCurrency, 16, 0, False); AddField('Item', '', nxtByte, 3, 0, False); AddField('Desconto', '', nxtCurrency, 16, 0, False); AddField('Pago', '', nxtCurrency, 16, 0, False); AddField('PagoPost', '', nxtCurrency, 16, 0, False); AddField('DescPost', '', nxtCurrency, 16, 0, False); AddField('DataHora', '', nxtDateTime, 0, 0, False); AddField('Pend', '', nxtBoolean, 0, 0, False); AddField('IncluidoEm', '', nxtDateTime, 0, 0, False); AddField('Entrada', '', nxtBoolean, 0, 0, False); AddField('Cancelado', '', nxtBoolean, 0, 0, False); AddField('AjustaCusto', '', nxtBoolean, 0, 0, False); AddField('EstoqueAnt', '', nxtDouble, 0, 0, False); AddField('Cliente', '', nxtWord32, 10, 0, False); AddField('Caixa', '', nxtInt32, 10, 0, False); AddField('Categoria', '', nxtNullString, 20, 0, False); AddField('NaoControlaEstoque', '', nxtBoolean, 0, 0, False); AddField('ITran', '', nxtInt32, 10, 0, False); AddField('TipoTran', '', nxtByte, 3, 0, False); AddField('Sessao', '', nxtInt32, 10, 0, False); AddField('Comissao', '', nxtCurrency, 0, 0, False); AddField('ComissaoPerc', '', nxtDouble, 0, 0, False); AddField('ComissaoLucro', '', nxtBoolean, 0, 0, False); with AddField('PermSemEstoque', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('FidResgate', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('FidPontos', '', nxtDouble, 0, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('IID_ref', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('ID_ref')); Add(GetFieldFromName('TipoTran')); Add(GetFieldFromName('Cancelado')); end; with AddIndex('IProduto', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Produto')); Add(GetFieldFromName('DataHora')); Add(GetFieldFromName('ID')); end; with AddIndex('IContato', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('DataHora')); end; with AddIndex('ITipoTranCaixa', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('TipoTran')); Add(GetFieldFromName('Caixa')); end; with AddIndex('ICaixaMov', 0, idAll, 'M'), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Caixa')); Add(GetFieldFromName('ID')); end; with AddIndex('ITranItem', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Tran')); Add(GetFieldFromName('Item')); end; with AddIndex('IProdCxMov', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin with Add(GetFieldFromName('Produto'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00030002; IgnoreKanaType := True; IgnoreNonSpace := True; Ignorewidth := True; end; end; Add(GetFieldFromName('Caixa')); Add(GetFieldFromName('ID')); end; with AddIndex('ISessaoID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Sessao')); Add(GetFieldFromName('ID')); end; with AddIndex('IProdAjustaCustoTran', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Produto')); Add(GetFieldFromName('AjustaCusto')); Add(GetFieldFromName('Tran')); end; with AddIndex('IProdAjustaCustoData', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Produto')); Add(GetFieldFromName('AjustaCusto')); Add(GetFieldFromName('DataHora')); end; with AddIndex('IProdPendCancelado', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Produto')); Add(GetFieldFromName('Pend')); Add(GetFieldFromName('Cancelado')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Mensagem para clientes function __MsgCli(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Cliente', '', nxtWord32, 10, 0, False); AddField('Titulo', '', nxtNullString, 50, 0, False); AddField('Texto', '', nxtBLOBMemo, 0, 0, False); AddField('Ref', '', nxtWord32, 10, 0, False); end; with EnsureIndicesDescriptor do begin with AddIndex('IClienteID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('ID')); end; with AddIndex('IRef', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Ref')); with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Ocupacao function __Ocupacao(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Sessao', '', nxtWord32, 10, 0, False); AddField('Maq', '', nxtWord32, 10, 0, False); AddField('Data', '', nxtDate, 0, 0, False); AddField('Hora', '', nxtByte, 3, 0, False); AddField('Cliente', '', nxtWord32, 10, 0, False); AddField('Func', '', nxtNullString, 20, 0, False); with AddField('TipoCli', '', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; AddField('MinutosU', '', nxtDouble, 0, 0, False); AddField('MinutosP', '', nxtDouble, 0, 0, False); AddField('Caixa', '', nxtWord32, 10, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('ISessao', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Sessao')); Add(GetFieldFromName('Hora')); end; with AddIndex('IData', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Data')); Add(GetFieldFromName('Hora')); end; with AddIndex('ICaixa', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Caixa')); Add(GetFieldFromName('Hora')); end; with AddIndex('ITipoCliCaixa', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('TipoCli')); Add(GetFieldFromName('Caixa')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Passaporte function __Passaporte(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Nome', '', nxtNullString, 50, 0, False); AddField('TipoPass', '', nxtInt32, 10, 0, False); AddField('Cliente', '', nxtInt32, 10, 0, False); AddField('Expirou', '', nxtBoolean, 0, 0, False); AddField('Senha', '', nxtNullString, 20, 0, False); AddField('PrimeiroUso', '', nxtDateTime, 0, 0, False); AddField('TipoAcesso', '', nxtInt32, 10, 0, False); AddField('TipoExp', '', nxtByte, 1, 0, False); AddField('ExpirarEm', '', nxtDateTime, 0, 0, False); AddField('MaxSegundos', '', nxtWord32, 10, 0, False); AddField('Segundos', '', nxtWord32, 10, 0, False); AddField('Acessos', '', nxtWord32, 10, 0, False); AddField('Dia1', '', nxtWord32, 10, 0, False); AddField('Dia2', '', nxtWord32, 10, 0, False); AddField('Dia3', '', nxtWord32, 10, 0, False); AddField('Dia4', '', nxtWord32, 10, 0, False); AddField('Dia5', '', nxtWord32, 10, 0, False); AddField('Dia6', '', nxtWord32, 10, 0, False); AddField('Dia7', '', nxtWord32, 10, 0, False); AddField('Tran', '', nxtWord32, 10, 0, False); AddField('DataCompra', '', nxtDateTime, 0, 0, False); AddField('Cartao', '', nxtBoolean, 0, 0, False); with AddField('Valido', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; AddField('Valor', '', nxtCurrency, 16, 0, False); AddField('Sessao', '', nxtWord32, 10, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll, 'Exp'), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('ICliExpID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('Expirou')); Add(GetFieldFromName('ID')); end; with AddIndex('ITransacao', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Tran')); with AddIndex('ICliDataCompra', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('DataCompra')); end; with AddIndex('IExpID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Expirou')); Add(GetFieldFromName('ID')); end; with AddIndex('ICartaoExpID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cartao')); Add(GetFieldFromName('Expirou')); Add(GetFieldFromName('ID')); end; with AddIndex('ICartaoID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cartao')); Add(GetFieldFromName('ID')); end; with AddIndex('ISenha', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Senha'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00030002; IgnoreKanaType := True; IgnoreNonSpace := True; Ignorewidth := True; end; end; with AddIndex('ISessao', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Sessao')); Add(GetFieldFromName('ID')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Produto function __Produto(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); AddLocaleDescriptor; with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Codigo', '', nxtNullString, 30, 0, False); AddField('Descricao', '', nxtNullString, 100, 0, False); AddField('Unid', '', nxtNullString, 5, 0, False); AddField('Preco', '', nxtCurrency, 5, 0, False); AddField('PrecoAuto', '', nxtBoolean, 0, 0, False); AddField('Margem', '', nxtDouble, 0, 0, False); AddField('Obs', '', nxtBLOBMemo, 0, 0, False); AddField('Imagem', '', nxtBLOBGraphic, 0, 0, False); AddField('Categoria', '', nxtNullString, 35, 0, False); AddField('Fornecedor', '', nxtWord32, 10, 0, False); AddField('SubCateg', '', nxtNullString, 35, 0, False); AddField('EstoqueAtual', '', nxtExtended, 0, 0, False); AddField('EstoquePend', '', nxtExtended, 0, 0, False); AddField('EstoqueTot', '', nxtExtended, 0, 0, False); AddField('brtrib', '', nxtWord16, 0, 0, False); AddField('CustoUnitario', '', nxtCurrency, 16, 0, False); AddField('PodeAlterarPreco', '', nxtBoolean, 0, 0, False); AddField('PermiteVendaFracionada', '', nxtBoolean, 0, 0, False); AddField('NaoControlaEstoque', '', nxtBoolean, 0, 0, False); AddField('EstoqueMin', '', nxtExtended, 0, 0, False); AddField('EstoqueMax', '', nxtExtended, 0, 0, False); AddField('AbaixoMin', '', nxtBoolean, 0, 0, False); AddField('AbaixoMinDesde', '', nxtDateTime, 0, 0, False); AddField('EstoqueRepor', '', nxtExtended, 0, 0, False); AddField('ComissaoPerc', '', nxtDouble, 0, 0, False); AddField('ComissaoLucro', '', nxtBoolean, 0, 0, False); with AddField('Ativo', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('Fidelidade', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('FidPontos', '', nxtInt32, 10, 0, False); AddField('NCM', '', nxtNullString, 8, 0, False); AddField('NCM_Ex', '', nxtNullString, 2, 0, False); with AddField('CadastroRapido', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('IncluidoEm', '', nxtDateTime, 0, 0, False) do AddDefaultValue(TnxCurrentDateTimeDefaultValueDescriptor); AddField('RecVer', '', nxtWord32, 0, 0, False); end; with EnsureIndicesDescriptor do with AddIndex('IID', 0, idNull), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with IndicesDescriptor.AddIndex('ISuperBusca', 0, True, '', TnxMainIndexTokenKeyDescriptor) do with (KeyDescriptor as TnxMainIndexTokenKeyDescriptor) do MaxTokenSize := 50; // set max key length here with EnsureFulltextDescriptor(Result) do with AddFullTextIndex('full_superbusca') do begin // N.B. you can add extractors for as many fields as you like here: AddFieldTokenExtractor(FieldsDescriptor.GetFieldFromName('Descricao'), '', TnxKwicTokenExtractorDescriptor); with TnxMainIndexTokenIndexDescriptor(AddTokenIndex('ISuperBusca', TnxMainIndexTokenIndexDescriptor)) do begin MainIndexNumber := 2; IgnoreCase := True; { with AddLocaleDescriptor do begin Locale := $00000416; Flags := $00001000; UseStringSort := True; end; } end; end; with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); with EnsureIndicesDescriptor do begin with AddIndex('ICodigo', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Codigo'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; with AddIndex('IDescricao', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Descricao'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; Flags := $00001000; UseStringSort := True; end; end; with AddIndex('IAbaixoMin', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('AbaixoMin')); Add(GetFieldFromName('AbaixoMinDesde')); end; with AddIndex('IPrecoAutoMargem', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('PrecoAuto')); Add(GetFieldFromName('Margem')); end; with AddIndex('ICadastroRapido', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin with Add(GetFieldFromName('CadastroRapido')) do Ascend := False; with Add(GetFieldFromName('IncluidoEm')) do Ascend := False; end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Sessao function __Sessao(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Inicio', '', nxtDateTime, 0, 0, False); AddField('Termino', '', nxtDateTime, 0, 0, False); AddField('MinutosR', 'Em minutos', nxtDouble, 0, 0, False); AddField('MinutosC', 'Em minutos', nxtDouble, 0, 0, False); AddField('Maq', '', nxtWord16, 5, 0, False); AddField('MaqI', '', nxtWord16, 5, 0, False); with AddField('Encerrou', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; AddField('Cliente', '', nxtWord32, 10, 0, False); AddField('TransfMaq', 'Houve transferencia de maquina', nxtBoolean, 0, 0, False); with AddField('TipoCli', '0=normal, 1=gratis, 2=manutencao', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; with AddField('Cancelado', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('Total', '', nxtCurrency, 16, 0, False); AddField('Desconto', '', nxtCurrency, 16, 0, False); AddField('PagoPost', '', nxtCurrency, 16, 0, False); AddField('DescPost', '', nxtCurrency, 16, 0, False); AddField('Pago', '', nxtCurrency, 16, 0, False); AddField('NomeCliente', '', nxtNullString, 50, 0, False); AddField('FuncI', '', nxtNullString, 30, 0, False); AddField('FuncF', '', nxtNullString, 30, 0, False); AddField('Obs', '', nxtBLOBMemo, 0, 0, False); AddField('TipoAcesso', '', nxtInt32, 10, 0, False); AddField('CaixaI', '', nxtWord32, 10, 0, False); AddField('CaixaF', '', nxtWord32, 10, 0, False); AddField('TicksI', '', nxtInt32, 10, 0, False); AddField('Pausado', '', nxtBoolean, 0, 0, False); AddField('InicioPausa', '', nxtWord32, 10, 0, False); AddField('MinTicksUsados', '', nxtWord32, 10, 0, False); AddField('MinTicksTotal', '', nxtWord32, 10, 0, False); AddField('FimTicksUsados', '', nxtWord32, 10, 0, False); AddField('FimTicksTotal', '', nxtWord32, 10, 0, False); AddField('StrPausas', '', nxtBLOBMemo, 0, 0, False); AddField('StrTransfMaq', '', nxtBLOBMemo, 0, 0, False); AddField('StrFechamentoCaixa', '', nxtBLOBMemo, 0, 0, False); AddField('MinutosCli', '', nxtExtended, 0, 0, False); AddField('MinutosPrev', '', nxtExtended, 0, 0, False); AddField('MinutosMax', '', nxtExtended, 0, 0, False); AddField('MinutosCliU', '', nxtExtended, 0, 0, False); AddField('ValorCli', '', nxtCurrency, 16, 0, False); AddField('ValorCliU', '', nxtExtended, 0, 0, False); AddField('TranI', '', nxtInt32, 10, 0, False); AddField('TranF', '', nxtInt32, 10, 0, False); AddField('PermitirDownload', '', nxtBoolean, 0, 0, False); AddField('PermitirDownloadExe', '', nxtBoolean, 0, 0, False); AddField('FiltrarWEB', '', nxtBoolean, 0, 0, False); AddField('VersaoRegistro', '', nxtWord32, 10, 0, False); AddField('IPs', '', nxtBlobMemo, 0, 0, False); with AddField('DesktopSinc', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := True; with AddField('CartaoTempo', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; with AddField('HP1', '', nxtInt32, 10, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 2147483647; with AddField('HP2', '', nxtInt32, 10, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 2147483647; with AddField('HP3', '', nxtInt32, 10, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 2147483647; with AddField('HP4', '', nxtInt32, 10, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 2147483647; with AddField('HP5', '', nxtInt32, 10, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 2147483647; with AddField('HP6', '', nxtInt32, 10, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 2147483647; with AddField('HP7', '', nxtInt32, 10, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 2147483647; with AddField('DisableAD', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('JobID', '', nxtWord32, 0, 0, False); AddField('JobPages', '', nxtWord16, 0, 0, False); with AddField('TipoMaq', '0=Maq/Mesa, 1=Comanda, 2=Avulso', nxtByte, 3, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('IClienteInicio', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('Inicio')); end; with AddIndex('IEncerrou', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Encerrou')); Add(GetFieldFromName('CaixaF')); end; with AddIndex('IEncerrouCli', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Encerrou')); Add(GetFieldFromName('Cliente')); end; with AddIndex('ICaixaF', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('CaixaF')); Add(GetFieldFromName('TipoCli')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Tempo function __Credito(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('DataHora', '', nxtDateTime, 0, 0, False); AddField('Func', '', nxtNullString, 20, 0, False); AddField('Adicionar', '', nxtBoolean, 0, 0, False); AddField('Tran', '', nxtWord32, 10, 0, False); AddField('Caixa', '', nxtWord32, 10, 0, False); AddField('Cliente', '', nxtWord32, 10, 0, False); AddField('Cancelado', '', nxtBoolean, 0, 0, False); AddField('Valor', '', nxtCurrency, 16, 0, False); with AddField('FidResgate', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('FidPontos', '', nxtDouble, 0, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('ICliente', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('ID')); end; with AddIndex('ITran', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Tran')); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // TipoAcesso function __TipoAcesso(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtWord16, 5, 0, False); AddField('Nome', '', nxtNullString, 30, 0, False); AddField('TarifaPadrao', '', nxtInt32, 10, 0, False); AddField('HoraTarifaStr', '', nxtBlobMemo, 0, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idNone), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('INome', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Nome'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // TipoPass function __TipoPass(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Nome', '', nxtNullString, 50, 0, False); AddField('Valor', '', nxtCurrency, 16, 0, False); AddField('TipoAcesso', '', nxtInt32, 10, 0, False); AddField('TipoExp', '', nxtByte, 1, 0, False); AddField('ExpirarEm', '', nxtDateTime, 0, 0, False); AddField('MaxSegundos', '', nxtWord32, 10, 0, False); AddField('Obs', '', nxtBLOBMemo, 0, 0, False); AddField('Dia1', '', nxtWord32, 10, 0, False); AddField('Dia2', '', nxtWord32, 10, 0, False); AddField('Dia3', '', nxtWord32, 10, 0, False); AddField('Dia4', '', nxtWord32, 10, 0, False); AddField('Dia5', '', nxtWord32, 10, 0, False); AddField('Dia6', '', nxtWord32, 10, 0, False); AddField('Dia7', '', nxtWord32, 10, 0, False); with AddField('Fidelidade', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('FidPontos', '', nxtInt32, 10, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Tran function __Tran(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('UID', '', nxtGUID, 0, 0, False); AddField('UID_ref', '', nxtGUID, 0, 0, False); with AddField('StatusNFE', '', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := nfetran_naoemitir; AddField('ChaveNFE', '', nxtNullString, 44, 0, False); with AddField('TipoNFE', '', nxtByte, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := tiponfe_nenhum; AddField('DataHora', '', nxtDateTime, 0, 0, False); AddField('IncluidoEm', '', nxtDateTime, 0, 0, False); AddField('Cliente', '', nxtWord32, 10, 0, False); AddField('Tipo', '', nxtByte, 3, 0, False); AddField('OpDevValor', '', nxtByte, 3, 0, False); AddField('Func', '', nxtNullString, 20, 0, False); AddField('Total', '', nxtCurrency, 16, 0, False); AddField('Desconto', '', nxtCurrency, 16, 0, False); AddField('DescPerc', '', nxtDouble, 16, 0, False); with AddField('DescPorPerc', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('TotLiq', '', nxtCurrency, 16, 0, False); with AddField('PagEsp', '', nxtWord16, 5, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := 0; AddField('Pago', '', nxtCurrency, 16, 0, False); AddField('DebitoAnt', '', nxtCurrency, 16, 0, False); AddField('Debito', '', nxtCurrency, 16, 0, False); AddField('DebitoPago', '', nxtCurrency, 16, 0, False); AddField('CreditoAnt', '', nxtCurrency, 16, 0, False); AddField('Credito', '', nxtCurrency, 16, 0, False); AddField('CreditoUsado', '', nxtCurrency, 16, 0, False); AddField('Troco', '', nxtCurrency, 16, 0, False); AddField('Obs', '', nxtBLOBMemo, 0, 0, False); AddField('Cancelado', '', nxtBoolean, 0, 0, False); AddField('CanceladoPor', '', nxtNullString, 30, 0, False); AddField('CanceladoEm', '', nxtDateTime, 0, 0, False); AddField('Caixa', '', nxtWord32, 10, 0, False); AddField('CaixaPag', '', nxtWord32, 10, 0, False); AddField('Maq', '', nxtWord16, 5, 0, False); AddField('NomeCliente', '', nxtNullString, 50, 0, False); AddField('Sessao', '', nxtWord32, 10, 0, False); AddField('Descr', '', nxtNullString, 100, 0, False); AddField('QtdTempo', '', nxtDouble, 0, 0, False); AddField('CredValor', '', nxtBoolean, 0, 0, False); AddField('FidResgate', '', nxtBoolean, 0, 0, False); AddField('AmbNFe', '', nxtByte, 0, 0, False); AddField('StatusCanc', '', nxtByte, 0, 0, False); AddField('Extra', '', nxtBlobMemo, 0, 0, False); AddField('PagFunc', '', nxtNullString, 20, 0, False); with AddField('PagPend', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('IUID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('UID')); with AddIndex('ICliDH', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('DataHora')); end; with AddIndex('ICliID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cliente')); Add(GetFieldFromName('ID')); end; with AddIndex('ICaixaID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Caixa')); Add(GetFieldFromName('ID')); end; with AddIndex('ICaixaPagID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('CaixaPag')); Add(GetFieldFromName('ID')); end; with AddIndex('IPagPendID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('PagPend')); Add(GetFieldFromName('ID')); end; with AddIndex('IDH', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('DataHora')); with AddIndex('ITipoDH', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Tipo')); Add(GetFieldFromName('DataHora')); end; with AddIndex('ITipoCaixaID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Tipo')); Add(GetFieldFromName('Caixa')); Add(GetFieldFromName('ID')); end; with AddIndex('ITipoID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Tipo')); Add(GetFieldFromName('Caixa')); Add(GetFieldFromName('ID')); end; with AddIndex('ISessao', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Sessao')); Add(GetFieldFromName('ID')); end; with AddIndex('IUID_ref', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('UID_ref')); Add(GetFieldFromName('Tipo')); Add(GetFieldFromName('Cancelado')); end; with AddIndex('IStatusNFE', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('StatusNFE')); Add(GetFieldFromName('ID')); end; with AddIndex('ICanceladoStatusNFE', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cancelado')); Add(GetFieldFromName('StatusNFE')); Add(GetFieldFromName('ID')); end; with AddIndex('ICanceladoAmbStatusNFE', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Cancelado')); Add(GetFieldFromName('AmbNFe')); Add(GetFieldFromName('StatusNFE')); Add(GetFieldFromName('ID')); end; with AddIndex('IChaveNFE', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ChaveNFE')); with AddIndex('IStatusCanc', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('StatusCanc')); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Usuario function __Usuario(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin Result.EncryptionEngine := 'nx1xDefault'; AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('Username', '', nxtNullString, 20, 0, False); AddField('Nome', '', nxtNullString, 40, 0, False); AddField('Admin', '', nxtBoolean, 0, 0, False); AddField('Senha', '', nxtNullString, 30, 0, False); AddField('Grupos', '', nxtBLOBMemo, 0, 0, False); AddField('Direitos', '', nxtBLOBMemo, 0, 0, False); AddField('MaxTempoManut', '', nxtInt32, 10, 0, False); AddField('MaxMaqManut', '', nxtInt32, 10, 0, False); AddField('LimiteDesc', '', nxtDouble, 16, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IUsername', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Username'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; with AddIndex('INome', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do with Add(GetFieldFromName('Nome'), TnxExtTextKeyFieldDescriptor) as TnxExtTextKeyFieldDescriptor do begin IgnoreCase := True; with AddLocaleDescriptor do begin Locale := $00000416; { Portuguese } Flags := $00001000; UseStringSort := True; end; end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; function __infocampanha(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('IP', '', nxtNullString, 15, 0, False); AddField('campanha', '', nxtNullString, 50, 0, False); AddField('utmccn', '', nxtNullString, 250, 0, False); AddField('utmctr', '', nxtNullString, 250, 0, False); AddField('utmcct', '', nxtNullString, 250, 0, False); AddField('utmcmd', '', nxtNullString, 250, 0, False); AddField('utmcsr', '', nxtNullString, 250, 0, False); end; with EnsureIndicesDescriptor do with AddIndex('IIP', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('IP')); CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // temp function __temp(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do AddField('last_upd_cmds', '', nxtInt32, 10, 0, False); CheckValid(False); end; except FreeAndNil(Result); raise; end; end; // Usuario function __Especies(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtWord16, 5, 0, False); AddField('Tipo', '', nxtByte, 3, 0, False); AddField('Nome', '', nxtNullString, 40, 0, False); AddField('PermiteTroco', '', nxtBoolean, 0, 0, False); AddField('PermiteVarios', '', nxtBoolean, 0, 0, False); AddField('PermiteCred', '', nxtBoolean, 0, 0, False); AddField('Img', '', nxtWord16, 5, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); AddField('TipoPagNFE', '', nxtByte, 3, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); CheckValid(False); end; except FreeAndNil(Result); raise; end; end; function __PagEspecies(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Caixa', '', nxtWord32, 10, 0, False); AddField('DataHora', '', nxtDateTime, 0, 0, False); AddField('Tran', '', nxtWord32, 10, 0, False); AddField('Especie', '', nxtWord16, 5, 0, False); AddField('Tipo', '', nxtByte, 3, 0, False); AddField('Valor', '', nxtCurrency, 16, 0, False); AddField('Troco', '', nxtCurrency, 16, 0, False); AddField('Doc', '', nxtNullString, 50, 0, False); AddField('Cancelado', '', nxtBoolean, 0, 0, False); with AddField('Devolucao', '', nxtBoolean, 0, 0, False) do with AddDefaultValue(TnxConstDefaultValueDescriptor) as TnxConstDefaultValueDescriptor do AsVariant := False; AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); with AddIndex('IDoc', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('Doc')); with AddIndex('ITranID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Tran')); Add(GetFieldFromName('ID')); end; with AddIndex('ICaixaID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do begin Add(GetFieldFromName('Caixa')); Add(GetFieldFromName('ID')); end; end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; function __RecDel(aDatabase : TnxDatabase): TnxDataDictionary; begin Result := TnxDataDictionary.Create; try with Result do begin AddRecordDescriptor(TnxBaseRecordDescriptor); with FieldsDescriptor do begin AddField('ID', '', nxtAutoInc, 10, 0, False); AddField('Tab', '', nxtWord16, 5, 0, False); AddField('Key', '', nxtNullString, 40, 0, False); AddField('RecVer', '', nxtWord32, 0, 0, False); with EnsureIndicesDescriptor do with AddIndex('IRecVer', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('RecVer')); end; with EnsureIndicesDescriptor do begin with AddIndex('IID', 0, idAll), KeyDescriptor as TnxCompKeyDescriptor do Add(GetFieldFromName('ID')); end; CheckValid(False); end; except FreeAndNil(Result); raise; end; end; type TnxcgTableInfo = record TableName : String; Callback : TnxcgCreateDictCallback; end; const TableInfos : array[0..53] of TnxcgTableInfo = ((TableName : 'Biometria'; Callback : __Biometria), (TableName : 'Caixa'; Callback : __Caixa), (TableName : 'Categoria'; Callback : __Categoria), (TableName : 'CC'; Callback : __CC), (TableName : 'Cliente'; Callback : __Cliente), (TableName : 'Config'; Callback : __Config), (TableName : 'Debito'; Callback : __Debito), (TableName : 'EmailCorpo'; Callback : __EmailCorpo), (TableName : 'EmailCriar'; Callback : __EmailCriar), (TableName : 'EmailEnvio'; Callback : __EmailEnvio), (TableName : 'Espera'; Callback : __Espera), (TableName : 'HCred'; Callback : __HCred), (TableName : 'HPass'; Callback : __HPass), (TableName : 'ITran'; Callback : __ITran), (TableName : 'Layout'; Callback : __Layout), (TableName : 'Log'; Callback : __Log), (TableName : 'Maq'; Callback : __Maq), (TableName : 'Maquina'; Callback : __Maquina), (TableName : 'MovEst'; Callback : __MovEst), (TableName : 'MsgCli'; Callback : __MsgCli), (TableName : 'NCM'; Callback : __NCM), (TableName : 'Ocupacao'; Callback : __Ocupacao), (TableName : 'Passaporte'; Callback : __Passaporte), (TableName : 'Produto'; Callback : __Produto), (TableName : 'Sessao'; Callback : __Sessao), (TableName : 'Credito'; Callback : __Credito), (TableName : 'TipoAcesso'; Callback : __TipoAcesso), (TableName : 'TipoPass'; Callback : __TipoPass), (TableName : 'Tran'; Callback : __Tran), (TableName : 'Usuario'; Callback : __Usuario), (TableName : 'infoCampanha'; Callback: __infoCampanha), (TableName : 'temp'; Callback: __temp), (TableName : 'Post'; Callback: __Post), (TableName : 'PostMS'; Callback: __PostMS), (TableName : 'Unidade'; Callback: __Unidade), (TableName : 'Especie'; Callback: __Especies), (TableName : 'PagEspecies'; Callback: __PagEspecies), (TableName : 'IOrcamento'; Callback: __IOrcamento), (TableName : 'Orcamento'; Callback: __Orcamento), (TableName : 'syslog'; Callback: __syslog), (TableName : 'Doc'; Callback: __Doc), (TableName : 'Terminal'; Callback: __Terminal), (TableName : 'RecDel'; Callback: __RecDel), (TableName : 'CFOP'; Callback : __CFOP), (TableName : 'CSOSN'; Callback : __CSOSN), (TableName : 'CST'; Callback : __CST), (TableName : 'MunBr'; Callback : __MunBr), (TableName : 'NFCONFIG'; Callback : __NFCONFIG), (TableName : 'NFE'; Callback : __NFE), (TableName : 'BRTrib'; Callback : __BRTrib), (TableName : 'ConvUnid'; Callback : __ConvUnid), (TableName : 'ProdFor'; Callback : __ProdFor), (TableName : 'LinkXML'; Callback : __LinkXML), (TableName : 'TipoME'; Callback : __TipoME)); function TableCount: Integer; begin Result := Length(TableInfos); end; function DatabaseVersion: Cardinal; begin Result := Cardinal($04000000); end; function DatabaseVersionStr: String; begin Result := Format('%d.%d.%d.%d', [(DatabaseVersion and $ff000000) shr 24, (DatabaseVersion and $00ff0000) shr 16, (DatabaseVersion and $0000ff00) shr 8, (DatabaseVersion and $000000ff)]); end; function GetTableID(aTable: String): Integer; var I : Integer; begin for I := Low(TableInfos) to High(TableInfos) do if SameText(TableInfos[I].TableName, aTable) then begin Result := I; Exit; end; Result := -1; end; function GetTablePrimaryKey(aTable: String): String; begin if SameText(aTable, 'usuario') then Result := 'Username' else if SameText(aTable, 'categoria') then Result := 'Descricao' else if SameText(aTable, 'unidade') then Result := 'Descricao' else if SameText(aTable, 'Aviso') then Result := 'Minutos' else if SameText(aTable, 'Config') then Result := 'NumSeq' else if SameText(aTable, 'Maq') or SameText(aTable, 'Maquina') then Result := 'Numero' else if SameText(aTable, 'Orcamento') or SameText(aTable, 'IOrcamento') or SameText(aTable, 'Doc') then Result := 'UID'; end; procedure GetTableNames(aSL: TStrings); var I : Integer; begin aSL.Clear; for I := Low(TableInfos) to High(TableInfos) do aSL.Add(TableInfos[I].TableName); end; function GetTableDictionary(aDatabase : TnxDatabase; const aTableName : String): TnxDataDictionary; var I : Integer; begin Result := nil; for I := Low(TableInfos) to High(TableInfos) do if SameText(aTableName, TableInfos[I].TableName) then begin Result := TableInfos[I].Callback(aDatabase); break; end; end; procedure RestructureTable(aDatabase : TnxDatabase; const aTableName, aPassword : String; aNewDict : TnxDataDictionary; aProgressCallback : TnxcgProgressCallback; var aCancelTask : Boolean; aFreeDict : Boolean = False); var OldDict : TnxDataDictionary; Mapper : TnxTableMapperDescriptor; TaskInfo : TnxAbstractTaskInfo; Completed : Boolean; TaskStatus : TnxTaskStatus; begin try OldDict := TnxDataDictionary.Create; try nxCheck(aDatabase.GetDataDictionaryEx(aTableName, aPassword, OldDict)); if (aPassword <> '') and (aNewDict.EncryptionEngine = '') then aNewDict.EncryptionEngine := OldDict.EncryptionEngine; if OldDict.IsEqual(aNewDict) then Exit; if (not aCopiouArqs) and (not SameText(aTableName, 'config')) then begin aCopiouArqs := True; FrmCopia.CopiaDados('_ver'+SelfShortVer, 'config.nx1'); end; Mapper := TnxTableMapperDescriptor.Create; try Mapper.MapAllTablesAndFieldsByName(OldDict, aNewDict); nxCheck(aDatabase.RestructureTableEx(aTableName, aPassword, aNewDict, Mapper, TaskInfo)); if Assigned(TaskInfo) then try repeat if not aCancelTask then TaskInfo.GetStatus(Completed, TaskStatus); if not Completed then begin if Assigned(aProgressCallback) then aProgressCallback(aTableName, TaskStatus, aCancelTask); if not aCancelTask then Sleep(100) else nxCheck(TaskInfo.Cancel); end; until Completed or aCancelTask; nxCheck(TaskStatus.tsErrorCode); finally TaskInfo.Free; end; finally Mapper.Free; end; finally OldDict.Free; end; finally if aFreeDict then aNewDict.Free; end; end; procedure PackTable(aDatabase : TnxDatabase; const aTableName, aPassword : String; aProgressCallback : TnxcgProgressCallback; var aCancelTask : Boolean); var TaskInfo : TnxAbstractTaskInfo; Completed : Boolean; TaskStatus : TnxTaskStatus; begin nxCheck(aDatabase.PackTableEx(aTableName, aPassword, TaskInfo)); if Assigned(TaskInfo) then try while True do begin TaskInfo.GetStatus(Completed, TaskStatus); if Assigned(aProgressCallback) then aProgressCallback(aTableName, TaskStatus, aCancelTask); if Completed then break; if aCancelTask then nxCheck(TaskInfo.Cancel); end; finally TaskInfo.Free; end; end; procedure BuildAndEvolveTable(aDatabase : TnxDatabase; const aTableName, aPassword : String; aCreateDictCallback : TnxcgCreateDictCallback; aProgressCallback : TnxcgProgressCallback; var aCancelTask : Boolean); var Dict : TnxDataDictionary; aPass: String; begin Dict := aCreateDictCallback(aDatabase); if Assigned(Dict) then try aPass := ''; if not aDatabase.TableExists(aTableName, aPassword) then aDatabase.CreateTable(False, aTableName, aPass, Dict) else RestructureTable(aDatabase, aTableName, aPass, Dict, aProgressCallback, aCancelTask); finally Dict.Free; end; end; procedure BuildAndEvolveDatabase(aDatabase : TnxDatabase; aProgressCallback : TnxcgProgressCallback; const aPassword : String); var I : Integer; CancelTask : Boolean; begin gEvolvingTables := True; aCopiouArqs := False; try CancelTask := False; for I := Low(TableInfos) to High(TableInfos) do begin gEvolvingTableName := TableInfos[I].TableName; BuildAndEvolveTable(aDatabase, TableInfos[I].TableName, aPassword, TableInfos[I].Callback, aProgressCallback, CancelTask); if CancelTask then Exit; end; finally gEvolvingTables := False; end; end; procedure RestructureDatabase(aDatabase : TnxDatabase; aProgressCallback : TnxcgProgressCallback; const aPassword : String); var I : Integer; CancelTask : Boolean; begin CancelTask := False; for I := Low(TableInfos) to High(TableInfos) do begin RestructureTable(aDatabase, TableInfos[I].TableName, aPassword, TableInfos[I].Callback(aDatabase), aProgressCallback, CancelTask, True); if CancelTask then Exit; end; end; procedure PackDatabase(aDatabase : TnxDatabase; aProgressCallback : TnxcgProgressCallback; const aPassword : String); var I : Integer; CancelTask : Boolean; begin CancelTask := False; for I := Low(TableInfos) to High(TableInfos) do begin PackTable(aDatabase, TableInfos[I].TableName, aPassword, aProgressCallback, CancelTask); if CancelTask then Exit; end; end; var i: integer; initialization gTableNames := TStringList.Create; for I := Low(TableInfos) to High(TableInfos) do gTableNames.Add(UpperCase(TableInfos[i].TableName)); finalization gTableNames.Free; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { Dataset Designer } { } { Copyright (c) 1997,99 Inprise Corporation } { } {*******************************************************} unit DSDesign; interface uses Windows, SysUtils, Messages, Classes, Graphics, Controls, Forms, StdCtrls, ExtCtrls, DB, DBCtrls, DsgnIntf, LibIntf, DsnDBCst, DsgnWnds, Menus, DrpCtrls; type TSelectionProc = function(Field: TField): Boolean of object; TDSDesigner = class; TDSDesignerClass = class of TDSDesigner; TFieldsEditor = class(TDesignWindow) Panel1: TPanel; DataSource: TDataSource; LocalMenu: TPopupMenu; AddItem: TMenuItem; NewItem: TMenuItem; N1: TMenuItem; CutItem: TMenuItem; CopyItem: TMenuItem; PasteItem: TMenuItem; DeleteItem: TMenuItem; SelectAllItem: TMenuItem; FieldListBox: TListBox; DBNavigator: TDBNavigator; Addallfields1: TMenuItem; AggListBox: TListBox; Splitter1: TSplitter; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure AddItemClick(Sender: TObject); procedure DeleteItemClick(Sender: TObject); procedure FieldListBoxDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure FieldListBoxDragDrop(Sender, Source: TObject; X, Y: Integer); procedure AListBoxKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure NewItemClick(Sender: TObject); procedure SelectTable(Sender: TObject); procedure AListBoxClick(Sender: TObject); procedure AListBoxKeyPress(Sender: TObject; var Key: Char); procedure ClearAllClick(Sender: TObject); procedure FieldListBoxStartDrag(Sender: TObject; var DragObject: TDragObject); procedure SelectAllItemClick(Sender: TObject); procedure CutItemClick(Sender: TObject); procedure CopyItemClick(Sender: TObject); procedure PasteItemClick(Sender: TObject); procedure LocalMenuPopup(Sender: TObject); procedure AddAllFields(Sender: TObject); private FDSDesignerClass: TDSDesignerClass; FDragObject: TDragObject; FDSDesigner: TDSDesigner; FForm: TCustomForm; FDataset: TDataset; FFocusRectItem: Integer; FMinWidth, FMinHeight: Integer; procedure AddFields(All: Boolean); procedure Copy; function CreateFields(FieldsList: TListBox): TField; procedure Cut; procedure MoveFields(MoveOffset: Integer); procedure Paste; procedure RemoveFields(Listbox: TListbox); procedure SelectAll; procedure RestoreSelection(List: TListBox; var Selection: TStringList; ItemIndex, TopIndex: Integer; RestoreUpdate: Boolean); procedure SaveSelection(List: TListBox; var Selection: TStringList; var ItemIndex, TopIndex: Integer; NoUpdate: Boolean); procedure SetDataset(Value: TDataset); procedure UpdateDisplay; procedure UpdateCaption; procedure UpdateFieldList; procedure UpdateSelection; procedure WMGetMinMaxInfo(var Message: TWMGetMinMaxInfo); message WM_GETMINMAXINFO; function GetActiveListbox: TListbox; protected procedure Activated; override; procedure CheckFieldDelete; procedure CheckFieldAdd; function UniqueName(Component: TComponent): string; override; public destructor Destroy; override; procedure ComponentDeleted(Component: IPersistent); override; function GetEditState: TEditState; override; procedure EditAction(Action: TEditAction); override; function ForEachSelection(Proc: TSelectionProc): Boolean; procedure FormModified; override; procedure SelectionChanged(ASelection: TDesignerSelectionList); override; function DoNewField: TField; function DoNewLookupField(const ADataSet, AKey, ALookup, AResult, AType: string; ASize: Word): TField; function DoAddFields(All: Boolean): TField; property Form: TCustomForm read FForm write FForm; property Dataset: TDataset read FDataset write SetDataset; property DSDesignerClass: TDSDesignerClass read FDSDesignerClass write FDSDesignerClass; property DSDesigner: TDSDesigner read FDSDesigner; end; { TDSDesigner } TDSDesigner = class(TDatasetDesigner) private FFieldsEditor: TFieldsEditor; public destructor Destroy; override; procedure DataEvent(Event: TDataEvent; Info: Longint); override; procedure BeginCreateFields; virtual; procedure BeginUpdateFieldDefs; virtual; function DoCreateField(const FieldName: string; Origin: string): TField; virtual; procedure EndCreateFields; virtual; procedure EndUpdateFieldDefs; virtual; function GetControlClass(Field: TField): string; virtual; procedure InitializeMenu(Menu: TPopupMenu); virtual; function SupportsAggregates: Boolean; virtual; function SupportsInternalCalc: Boolean; virtual; procedure UpdateMenus(Menu: TPopupMenu; EditState: TEditState); virtual; property FieldsEditor: TFieldsEditor read FFieldsEditor; end; procedure ShowFieldsEditor(Designer: IFormDesigner; ADataset: TDataset; DesignerClass: TDSDesignerClass); function CreateFieldsEditor(Designer: IFormDesigner; ADataset: TDataset; DesignerClass: TDSDesignerClass; var Shared: Boolean): TFieldsEditor; function CreateUniqueName(Dataset: TDataset; const FieldName: string; FieldClass: TFieldClass; Component: TComponent): string; var DesignerCount: Integer; implementation uses Dialogs, TypInfo, Math, LibHelp, DSAdd, DSDefine, DesignConst; { TDSDesigner } destructor TDSDesigner.Destroy; begin if FFieldsEditor <> nil then begin FFieldsEditor.FDSDesigner := nil; FFieldsEditor.Release; end; inherited Destroy; end; procedure TDSDesigner.DataEvent(Event: TDataEvent; Info: Longint); begin if Event = deFieldListChange then FFieldsEditor.UpdateFieldList; end; function TDSDesigner.GetControlClass(Field: TField): string; begin Result := ''; end; function TDSDesigner.SupportsAggregates: Boolean; begin Result := False; end; function TDSDesigner.SupportsInternalCalc: Boolean; begin Result := False; end; procedure TDSDesigner.BeginUpdateFieldDefs; begin end; procedure TDSDesigner.EndUpdateFieldDefs; begin end; procedure TDSDesigner.BeginCreateFields; begin end; procedure TDSDesigner.EndCreateFields; begin end; procedure TDSDesigner.InitializeMenu(Menu: TPopupMenu); begin end; procedure TDSDesigner.UpdateMenus(Menu: TPopupMenu; EditState: TEditState); begin end; function TDSDesigner.DoCreateField(const FieldName: string; Origin: string): TField; var FieldDef: TFieldDef; ParentField: TField; SubScript, ShortName, ParentFullName: String; begin FieldDef := Dataset.FieldDefList.FieldByName(FieldName); ParentField := nil; if Dataset.ObjectView then begin if FieldDef.ParentDef <> nil then begin if FieldDef.ParentDef.DataType = ftArray then begin { Strip off the subscript to determine the parent's full name } SubScript := Copy(FieldName, AnsiPos('[', FieldName), MaxInt); ParentFullName := Copy(FieldName, 1, Length(FieldName) - Length(SubScript)); ShortName := FieldDef.ParentDef.Name + SubScript; end else begin if faUnNamed in FieldDef.ParentDef.Attributes then ParentFullName := FieldDef.ParentDef.Name else ParentFullName := ChangeFileExt(FieldName, ''); ShortName := FieldDef.Name; end; ParentField := Dataset.FieldList.Find(ParentFullName); if ParentField = nil then ParentField := DoCreateField(ParentFullName, Origin); end else ShortName := FieldDef.Name; end else ShortName := FieldName; Result := FieldDef.CreateField(DataSet.Owner, ParentField as TObjectField, ShortName, False); try Result.Origin := Origin; Result.Name := CreateUniqueName(Dataset, FieldName, TFieldClass(ClassType), nil); except Result.Free; raise; end; end; { Utility functions } procedure ShowFieldsEditor(Designer: IFormDesigner; ADataset: TDataset; DesignerClass: TDSDesignerClass); var FieldsEditor: TFieldsEditor; vShared: Boolean; begin FieldsEditor := CreateFieldsEditor(Designer, ADataSet, DesignerClass, vShared); if FieldsEditor <> nil then FieldsEditor.Show; end; function CreateFieldsEditor(Designer: IFormDesigner; ADataset: TDataset; DesignerClass: TDSDesignerClass; var Shared: Boolean): TFieldsEditor; begin Shared := True; if ADataset.Designer <> nil then Result := (ADataset.Designer as TDSDesigner).FFieldsEditor else begin Result := TFieldsEditor.Create(Application); Result.DSDesignerClass := DesignerClass; Result.Designer := Designer; Result.Form := Designer.Form; Result.Dataset := ADataset; Shared := False; end; end; function GenerateName(Dataset: TDataset; FieldName: string; FieldClass: TFieldClass; Number: Integer): string; var Fmt: string; procedure CrunchFieldName; var I: Integer; begin I := 1; while I <= Length(FieldName) do begin if FieldName[I] in ['A'..'Z','a'..'z','_','0'..'9'] then Inc(I) else if FieldName[I] in LeadBytes then Delete(FieldName, I, 2) else Delete(FieldName, I, 1); end; end; begin CrunchFieldName; if (FieldName = '') or (FieldName[1] in ['0'..'9']) then begin if FieldClass <> nil then FieldName := FieldClass.ClassName + FieldName else FieldName := 'Field' + FieldName; if FieldName[1] = 'T' then Delete(FieldName, 1, 1); CrunchFieldName; end; Fmt := '%s%s%d'; if Number < 2 then Fmt := '%s%s'; Result := Format(Fmt, [Dataset.Name, FieldName, Number]); end; function CreateUniqueName(Dataset: TDataset; const FieldName: string; FieldClass: TFieldClass; Component: TComponent): string; var I: Integer; function IsUnique(const AName: string): Boolean; var I: Integer; begin Result := False; with Dataset.Owner do for I := 0 to ComponentCount - 1 do if (Component <> Components[i]) and (CompareText(AName, Components[I].Name) = 0) then Exit; Result := True; end; begin for I := 1 to MaxInt do begin Result := Generatename(Dataset, FieldName, FieldClass, I); if IsUnique(Result) then Exit; end; end; { TDragFields } type TDragFields = class(TDragControlObject) private FEditor: TFieldsEditor; public constructor Create(AControl: TControl; AEditor: TFieldsEditor); reintroduce; property Editor: TFieldsEditor read FEditor; end; constructor TDragFields.Create(AControl: TControl; AEditor: TFieldsEditor); begin inherited Create(AControl); FEditor := AEditor; end; { TFieldsTarget } type TFieldsTarget = class(TDragTarget) public function DragOver(Target, Source: TObject; X, Y: Integer; State: TDragState): Boolean; override; procedure DragDrop(Target, Source: TObject; X, Y: Integer); override; end; function TFieldsTarget.DragOver(Target, Source: TObject; X, Y: Integer; State: TDragState): Boolean; begin Result := True; end; procedure TFieldsTarget.DragDrop(Target, Source: TObject; X, Y: Integer); var SourceRoot: TComponent; Control: TControl; I: Integer; Editor: TFieldsEditor; FieldList: TList; Field: TField; begin SourceRoot := TDragFields(Source).Editor.Designer.GetRoot; if not Designer.IsComponentLinkable(SourceRoot) then if MessageDlg(Format(SDSLinkForms, [Designer.GetRoot.Name, SourceRoot.Name]), mtConfirmation, mbYesNoCancel, 0) <> idYes then Exit else Designer.MakeComponentLinkable(SourceRoot); FieldList := TList.Create; try { Collect the fields before creating the controls since creating the first control will remove all the sections } Editor := TDragFields(Source).Editor; with Editor do begin for I := 0 to FieldListBox.Items.Count - 1 do if FieldListBox.Selected[I] then FieldList.Add(FieldListBox.Items.Objects[I]{Dataset.FieldByName(FieldListBox.Items[I])}); end; Screen.Cursor := crHourGlass; try for I := 0 to FieldList.Count - 1 do begin Field := TField(FieldList[I]); Control := CreateFieldControl(Designer, Field, Editor.DSDesigner.GetControlClass(Field), TComponent(Target), X, Y, True); Y := Control.Top + Control.Height + 5; end; finally Screen.Cursor := crDefault; end; finally FieldList.Free; end; end; {$R *.DFM} { TFieldsEditor } destructor TFieldsEditor.Destroy; begin FDragObject.Free; FDragObject := nil; inherited Destroy; end; procedure TFieldsEditor.UpdateDisplay; begin UpdateFieldList; UpdateCaption; UpdateSelection; end; procedure TFieldsEditor.SaveSelection(List: TListBox; var Selection: TStringList; var ItemIndex, TopIndex: Integer; NoUpdate: Boolean); var I: Integer; begin Selection := TStringList.Create; try ItemIndex := List.ItemIndex; TopIndex := List.TopIndex; with List do for I := 0 to Items.Count - 1 do if Selected[I] then Selection.Add(Items[I]); if NoUpdate then List.Items.BeginUpdate; except Selection.Free; Selection := nil; end; end; procedure TFieldsEditor.RestoreSelection(List: TListBox; var Selection: TStringList; ItemIndex, TopIndex: Integer; RestoreUpdate: Boolean); var I: Integer; begin try with List do for I := 0 to Items.Count - 1 do Selected[I] := Selection.IndexOf(Items[I]) <> -1; if TopIndex <> -1 then List.TopIndex := TopIndex; if ItemIndex <> -1 then List.ItemIndex := ItemIndex; finally if RestoreUpdate then List.Items.EndUpdate; List.Invalidate; Selection.Free; Selection := nil; UpdateSelection; end; end; procedure TFieldsEditor.UpdateCaption; var NewCaption: string; begin if (Dataset <> nil) and (Dataset.Owner <> nil) then NewCaption := Format(SDatasetEditor, [Dataset.Owner.Name, DotSep, Dataset.Name]); if Caption <> NewCaption then Caption := NewCaption; end; procedure TFieldsEditor.UpdateFieldList; var ItemIndex, TopIndex: Integer; Selection: TStringList; EnableList: Boolean; I: Integer; Field: TField; FieldName: string; ActiveListbox: TListbox; begin ActiveListbox := GetActiveListbox; SaveSelection(ActiveListBox, Selection, ItemIndex, TopIndex, True); try FieldListBox.Clear; AggListBox.Clear; EnableList := False; try if Dataset = nil then Exit; for I := 0 to Dataset.FieldList.Count - 1 do begin Field := Dataset.FieldList[I]; if not (csDestroying in Field.ComponentState) and (Field.Owner = Dataset.Owner) then begin FieldName := Field.FullName; if FieldName = '' then FieldName := Format('<%s>', [Dataset.FieldList[I].Name]); FieldListbox.Items.AddObject(FieldName, Field); end; end; for I := 0 to Dataset.AggFields.Count - 1 do begin Field := Dataset.AggFields[I]; if not (csDestroying in Field.ComponentState) and (Field.Owner = Dataset.Owner) then begin FieldName := Field.FullName; if FieldName = '' then FieldName := Format('<%s>', [Dataset.AggFields[I].Name]); AggListbox.Items.AddObject(FieldName, Field); end; end; with AggListbox do if Items.Count > 0 then begin Visible := True; Splitter1.Visible := True; end else begin Visible := False; Splitter1.Visible := False; end; EnableList := True; finally FieldListBox.Enabled := EnableList; AggListBox.Enabled := EnableList and (AggListBox.Items.Count > 0); end; finally if ActiveListBox.Visible then RestoreSelection(ActiveListBox, Selection, ItemIndex, TopIndex, True) else if ActiveListBox = AggListbox then ActiveListBox.Items.EndUpdate; end; end; procedure TFieldsEditor.UpdateSelection; var I: Integer; Field: TField; ComponentList: TDesignerSelectionList; begin if Active then begin ComponentList := TDesignerSelectionList.Create; try with GetActiveListBox do for I := 0 to Items.Count - 1 do if Selected[I] then begin Field := TField(Items.Objects[I]){Dataset.FindField(Items[I])}; if Field <> nil then ComponentList.Add(Field); end; if ComponentList.Count = 0 then ComponentList.Add(Dataset); except ComponentList.Free; raise; end; SetSelection(ComponentList); end; end; function TFieldsEditor.CreateFields(FieldsList: TListBox): TField; var I: Integer; ItemIndex, TopIndex: Integer; Selection: TStringList; FocusedListbox: TListbox; Fields: TStringList; begin Result := nil; FocusedListbox := nil; if Visible then begin FocusedListBox := GetActiveListBox; SaveSelection(FocusedListbox, Selection, ItemIndex, TopIndex, False); end; try Screen.Cursor := crHourGlass; try FDSDesigner.BeginDesign; try Fields := TStringList.Create; try for i := 0 to FieldsList.Items.Count - 1 do if FieldsList.Selected[i] then Fields.Add(FieldsList.Items[i]); DSDesigner.BeginCreateFields; try for I := 0 to Fields.Count - 1 do Result := DSDesigner.DoCreateField(Fields[I], ''); Designer.Modified; finally DSDesigner.EndCreateFields; end; finally Fields.Free; end; finally FDSDesigner.EndDesign; end; finally Screen.Cursor := crDefault; end; finally if FocusedListbox <> nil then begin UpdateDisplay; RestoreSelection(FocusedListBox, Selection, -1, -1, False); end; end; end; procedure TFieldsEditor.SelectAll; var I: Integer; begin with FieldListBox do for I := 0 to Items.Count - 1 do Selected[I] := True; end; procedure TFieldsEditor.RemoveFields(Listbox: TListbox); var I, Focused: Integer; begin CheckFieldDelete; try FDSDesigner.BeginDesign; try Focused := ListBox.ItemIndex; with ListBox do for I := Items.Count - 1 downto 0 do if Selected[I] then TField(Items.Objects[I]).Free; //Dataset.FindField(Items[I]).Free; Designer.Modified; finally FDSDesigner.EndDesign; end; finally UpdateDisplay; end; if Focused <> -1 then begin Focused := Min(Focused, ListBox.Items.Count - 1); ListBox.ItemIndex := Focused; ListBox.Selected[Focused] := True; UpdateSelection; end; if (ListBox = AggListBox) and (ListBox.Items.Count = 0) then FieldListBox.SetFocus else ListBox.SetFocus; end; procedure TFieldsEditor.MoveFields(MoveOffset: Integer); var I, E: Integer; begin try DataSet.DisableControls; try with FieldListBox do begin I := 0; E := Items.Count; if MoveOffset > 0 then begin I := E - 1; E := -1; end; while I <> E do begin if Selected[I] then with TField(Items.Objects[I]){Dataset.FieldByName(Items[I])} do Index := Index + MoveOffset; Inc(I, -MoveOffset); end; end; finally DataSet.EnableControls; end; finally UpdateDisplay; Designer.Modified; end; end; procedure TFieldsEditor.SetDataset(Value: TDataset); begin if FDataSet <> Value then begin if FDataSet <> nil then begin FreeAndNil(FDSDesigner); DataSource.DataSet := nil; end; FDataset := Value; if FDataSet <> nil then begin FDSDesigner := DSDesignerClass.Create(Value); FDSDesigner.FFieldsEditor := Self; FDSDesigner.InitializeMenu(LocalMenu); DataSource.DataSet := Value; UpdateDisplay; end else Release; end; end; procedure TFieldsEditor.FormCreate(Sender: TObject); begin Inc(DesignerCount); FMinWidth := Width; FMinHeight := Height; HelpContext := hcDataSetDesigner; end; procedure TFieldsEditor.FormDestroy(Sender: TObject); begin if FDSDesigner <> nil then begin { Destroy the designer if the editor is destroyed } FDSDesigner.FFieldsEditor := nil; FDSDesigner.Free; end; Dec(DesignerCount); end; procedure TFieldsEditor.AddFields(All: Boolean); begin DoAddFields(All); FieldListBox.SetFocus; end; function TFieldsEditor.DoAddFields(All: Boolean): TField; var AddFields: TAddFields; I: Integer; FieldName: string; Field: TField; begin CheckFieldAdd; Result := nil; try DSDesigner.BeginUpdateFieldDefs; DataSet.FieldDefs.Update; finally DSDesigner.EndUpdateFieldDefs; end; AddFields := TAddFields.Create(Application); try { Add physical fields not already represented by TField components to the to the list of available fields } for I := 0 to DataSet.FieldDefList.Count - 1 do with Dataset.FieldDefList[I] do if (FieldClass <> nil) and not (faHiddenCol in Attributes) then begin FieldName := DataSet.FieldDefList.Strings[I]; Field := DataSet.FindField(FieldName); if (Field = nil) or (Field.Owner <> Dataset.Owner) then AddFields.FieldsList.Items.Add(FieldName); end; { Show the dialog } AddFields.SelectAll; AddFields.FieldsList.ItemIndex := 0; if All or (AddFields.ShowModal <> mrCancel) then Result := CreateFields(AddFields.FieldsList); finally AddFields.Release; end; end; procedure TFieldsEditor.AddItemClick(Sender: TObject); begin AddFields(False); end; procedure TFieldsEditor.DeleteItemClick(Sender: TObject); begin RemoveFields(GetActiveListbox); end; procedure TFieldsEditor.FieldListBoxDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var Item: Integer; procedure DrawRect(Item: Integer); begin if Item <> -1 then with FieldlistBox do Canvas.DrawFocusRect(ItemRect(Item)); FFocusRectItem := Item; end; begin Item := FieldListBox.ItemAtPos(Point(X, Y), False); Accept := (Source is TDragFields) and (TDragFields(Source).Control = FieldListBox) and (Item >= 0) and (Item < FieldListBox.Items.Count) and not FieldListBox.Selected[Item]; if State = dsDragEnter then FFocusRectItem := -1; if (State = dsDragLeave) or not Accept then Item := -1; DrawRect(FFocusRectItem); DrawRect(Item); end; procedure TFieldsEditor.FieldListBoxDragDrop(Sender, Source: TObject; X, Y: Integer); var F: TField; I: Integer; begin if (Source is TDragFields) and (TDragFields(Source).Control = FieldListBox) then begin try DataSet.DisableControls; try with FieldListBox do begin F := TField(Items.Objects[ItemAtPos(Point(X, Y), True)]){Dataset.FieldByName(Items[ItemAtPos(Point(X, Y), True)])}; for I := 0 to Items.Count - 1 do if Selected[I] then TField(Items.Objects[I]).Index{Dataset.FieldByName(Items[I]).Index} := F.Index; end; finally DataSet.EnableControls; end; finally UpdateDisplay; Designer.Modified; end; end; end; procedure TFieldsEditor.WMGetMinMaxInfo(var Message: TWMGetMinMaxInfo); begin inherited; with Message.MinMaxInfo^.ptMinTrackSize do begin X := FMinWidth; Y := FMinHeight; end; end; procedure TFieldsEditor.AListBoxKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_INSERT: NewItemClick(Self); VK_DELETE: RemoveFields(Sender as TListbox); VK_UP: if (ssCtrl in Shift) and (Sender = FieldListBox) then MoveFields(-1) else Exit; VK_DOWN: if (ssCtrl in Shift) and (Sender = FieldListBox) then MoveFields(1) else Exit; else Exit; end; Key := 0; end; procedure TFieldsEditor.NewItemClick(Sender: TObject); var //DefineField: TDefineField; Selection: TStringList; //Columns: Integer; Field: TField; begin CheckFieldAdd; Field := DoNewField; if Field <> nil then begin Selection := TStringList.Create; try Selection.Add(Field.FieldName); finally RestoreSelection(FieldListBox, Selection, -1, -1, False); end; end; FieldListBox.SetFocus; {DefineField := TDefineField.Create(Application); try DefineField.DSDesigner := FDSDesigner; DefineField.Designer := Designer; DefineField.Dataset := Dataset; Columns := 3; if DSDesigner.SupportsInternalCalc then begin DefineField.FieldKind.Items.Add(SFKInternalCalc); Inc(Columns); end; if DSDesigner.SupportsAggregates then begin DefineField.FieldKind.Items.Add(SFKAggregate); Inc(Columns); end; DefineField.FieldKind.Columns := Columns; with DefineField do if ShowModal = mrOK then begin Self.Designer.Modified; Self.UpdateDisplay; Selection := TStringList.Create; try Selection.Add(FieldName); finally RestoreSelection(FieldListBox, Selection, -1, -1, False); end; end; finally DefineField.Release; end; FieldListBox.SetFocus;} end; function TFieldsEditor.DoNewField: TField; var DefineField: TDefineField; //Selection: TStringList; Columns: Integer; begin Result := nil; DefineField := TDefineField.Create(Application); try DefineField.DSDesigner := FDSDesigner; DefineField.Designer := Designer; DefineField.Dataset := Dataset; Columns := 3; if DSDesigner.SupportsInternalCalc then begin DefineField.FieldKind.Items.Add(SFKInternalCalc); Inc(Columns); end; if DSDesigner.SupportsAggregates then begin DefineField.FieldKind.Items.Add(SFKAggregate); Inc(Columns); end; DefineField.FieldKind.Columns := Columns; if DefineField.ShowModal = mrOk then begin Result := DefineField.Field; Designer.Modified; if Visible then UpdateDisplay; end; finally DefineField.Release; end; end; function TFieldsEditor.DoNewLookupField(const ADataSet, AKey, ALookup, AResult, AType: string; ASize: Word): TField; var DefineField: TDefineField; //Selection: TStringList; //Columns: Integer; begin CheckFieldAdd; Result := nil; DefineField := TDefineField.Create(Application); try DefineField.DSDesigner := FDSDesigner; DefineField.Designer := Designer; DefineField.Dataset := Dataset; DefineField.ConfigureForLookupOnly(ADataSet, AKey, ALookup, AResult, AType, ASize); if DefineField.ShowModal = mrOk then begin Result := DefineField.Field; Designer.Modified; if Visible then UpdateDisplay; end; finally DefineField.Release; end; end; procedure TFieldsEditor.Activated; begin try UpdateSelection; except FieldListBox.Items.Clear; end; end; function TFieldsEditor.UniqueName(Component: TComponent): string; begin Result := CreateUniqueName(Dataset, TField(Component).FullName, TFieldClass(Component.ClassType), Component); end; procedure TFieldsEditor.ComponentDeleted(Component: IPersistent); var vItem: TPersistent; begin vItem := ExtractPersistent(Component); if vItem = DataSet then DataSet := nil else if (vItem is TField) and (TField(vItem).DataSet = DataSet) then UpdateDisplay; end; function TFieldsEditor.GetEditState: TEditState; function FieldsSelected(Listbox: TListbox): Boolean; var I: Integer; begin Result := True; with ListBox do for I := 0 to Items.Count - 1 do if Selected[I] then Exit; Result := False; end; begin Result := []; if ClipboardComponents then Result := [esCanPaste]; if FieldsSelected(FieldListbox) or FieldsSelected(AggListBox) then Result := Result + [esCanCopy, esCanCut, esCanDelete]; end; procedure TFieldsEditor.EditAction(Action: TEditAction); begin case Action of eaCut: Cut; eaCopy: Copy; eaPaste: Paste; eaDelete: RemoveFields(GetActiveListbox); eaSelectAll: begin SelectAll; UpdateSelection; end; end; end; procedure TFieldsEditor.Cut; begin CheckFieldDelete; Copy; RemoveFields(GetActiveListbox); end; procedure TFieldsEditor.Copy; var I: Integer; ComponentList: TDesignerSelectionList; begin ComponentList := TDesignerSelectionList.Create; try with GetActiveListBox do for I := 0 to Items.Count - 1 do if Selected[I] then ComponentList.Add(TComponent(Items.Objects[I]){Dataset.FieldByName(Items[I])}); CopyComponents(Dataset.Owner, ComponentList); finally ComponentList.Free; end; end; procedure TFieldsEditor.Paste; var I, Index: Integer; ComponentList: TDesignerSelectionList; Field, F: TField; begin ComponentList := TDesignerSelectionList.Create; try F := nil; with FieldListBox do if (ItemIndex <> -1) and (Items.Count > 0) then F := TField(Items.Objects[ItemIndex]){Dataset.FieldByName(Items[ItemIndex])}; try FDSDesigner.BeginDesign; try PasteComponents(Dataset.Owner, Dataset, ComponentList); finally FDSDesigner.EndDesign; end; finally UpdateDisplay; end; try with FieldListBox do for I := 0 to Items.Count - 1 do Selected[I] := False; for I := 0 to ComponentList.Count - 1 do if ComponentList[I] is TField then begin Field := TField(ComponentList[I]); Field.Name := UniqueName(Field); Index := FieldListBox.Items.IndexOf(Field.FullName); if Index <> -1 then FieldListBox.Selected[Index] := True; if F <> nil then Field.Index := F.Index; end; finally UpdateDisplay; end; finally ComponentList.Free; end; end; procedure TFieldsEditor.FormModified; begin UpdateCaption; end; procedure TFieldsEditor.SelectionChanged(ASelection: TDesignerSelectionList); var I: Integer; S: Boolean; function InSelection(Component: TComponent): Boolean; var I: Integer; begin Result := True; if ASelection <> nil then with ASelection do for I := 0 to Count - 1 do if Component = Items[I] then Exit; Result := False; end; begin with FieldListBox do for I := 0 to Items.Count - 1 do begin S := InSelection(TComponent(Items.Objects[I]){Dataset.FieldList[I]}); if Selected[I] <> S then Selected[I] := S; end; with AggListBox do for I := 0 to Items.Count - 1 do begin S := InSelection(TComponent(Items.Objects[I]){Dataset.AggFields[I]}); if Selected[I] <> S then Selected[I] := S; end; end; procedure TFieldsEditor.SelectTable(Sender: TObject); var I: Integer; begin FieldListBox.ItemIndex := 0; with FieldListBox do for I := 0 to Items.Count - 1 do if Selected[I] then Selected[I] := False; UpdateSelection; FieldListBox.SetFocus; end; procedure TFieldsEditor.AListBoxClick(Sender: TObject); begin UpdateSelection; end; procedure TFieldsEditor.AListBoxKeyPress(Sender: TObject; var Key: Char); begin case Key of #13, #33..#126: begin if Key = #13 then Key := #0; ActivateInspector(Key); Key := #0; end; #27: begin SelectTable(Self); Key := #0; end; end; end; procedure TFieldsEditor.ClearAllClick(Sender: TObject); begin CheckFieldDelete; if MessageDlg(SDSConfirmDeleteAll, mtConfirmation, mbOKCancel, 0) <> idCancel then begin SelectAll; RemoveFields(GetActiveListbox); end; end; procedure TFieldsEditor.FieldListBoxStartDrag(Sender: TObject; var DragObject: TDragObject); begin if FieldListBox.Items.Count > 0 then begin if FDragObject = nil then FDragObject := TDragFields.Create(FieldListBox, Self); DragObject := FDragObject; end; end; procedure TFieldsEditor.SelectAllItemClick(Sender: TObject); begin SelectAll; UpdateSelection; end; procedure TFieldsEditor.CutItemClick(Sender: TObject); begin Cut; end; procedure TFieldsEditor.CopyItemClick(Sender: TObject); begin Copy; end; procedure TFieldsEditor.PasteItemClick(Sender: TObject); begin Paste; end; procedure TFieldsEditor.LocalMenuPopup(Sender: TObject); var EditState: TEditState; begin EditState := GetEditState; CopyItem.Enabled := esCanCopy in EditState; PasteItem.Enabled := esCanPaste in EditState; CutItem.Enabled := esCanCut in EditState; DeleteItem.Enabled := esCanDelete in EditState; SelectAllItem.Enabled := FieldListBox.Items.Count > 0; DSDesigner.UpdateMenus(LocalMenu, EditState); end; function TFieldsEditor.ForEachSelection(Proc: TSelectionProc): Boolean; var Field: TField; I: Integer; begin Result := False; with FieldListBox do for I := 0 to Items.Count - 1 do if Selected[I] then begin Field := TField(Items.Objects[I]){Dataset.FindField(Items[I])}; if (Field <> nil) and not Proc(Field) then Exit; end; Result := True; end; procedure TFieldsEditor.AddAllFields(Sender: TObject); begin AddFields(True); end; function TFieldsEditor.GetActiveListbox: TListbox; begin if ActiveControl = AggListbox then Result := AggListbox else Result := FieldListBox; end; procedure TFieldsEditor.CheckFieldDelete; var I: Integer; begin with GetActiveListBox do for I := 0 to Items.Count-1 do if Selected[I] and (csAncestor in TField(Items.Objects[I]).ComponentState) then raise Exception.CreateRes(@SCantDeleteAncestor); end; procedure TFieldsEditor.CheckFieldAdd; begin if (FDataset <> nil) and (FDataset.Owner <> nil) and (csInline in FDataset.Owner.ComponentState) then raise Exception.CreateRes(@SCantAddToFrame); end; initialization if Assigned(CompLib) then CompLib.RegisterDragTarget(TDragFields.ClassName, TFieldsTarget); end.
unit watermark; interface uses {$IFNDEF FPC} jpeg, pngimage,{$ENDIF} sysutils,graphics,dglOpenGL,define_types, textfx; Type TWatermark = record X,Y,Ht,Wid: integer; Texture2D: TGLuint; Filename: string; end; procedure LoadWatermark(var W: TWatermark); procedure DrawWatermark ( lX,lY,lW,lH: single; var W: TWatermark); var gWatermark: TWatermark; implementation procedure CreateTexture2D(Width, Height: integer; pData : bytep; var Texture: TGLuint); begin glDeleteTextures(1,@Texture); glGenTextures(1, @Texture); glBindTexture(GL_TEXTURE_2D, Texture); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA8, Width, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, PChar(pData)); end; procedure jpeg2bmp (s: string; var bmp: TBitmap); var jpg : TJpegImage; begin jpg := TJpegImage.Create; TRY jpg.LoadFromFile(s); bmp.Height := jpg.Height; bmp.Width := jpg.width; bmp.PixelFormat := pf24bit; bmp.Canvas.Draw(0,0, jpg); // convert JPEG to Bitmap FINALLY jpg.Free END; end; procedure png2bmp (s: string; var bmp: TBitmap); var {$IFDEF FPC} png : TPortableNetworkGraphic; {$ELSE} png: TPNGObject; {$ENDIF} begin {$IFDEF FPC} png := TPortableNetworkGraphic.Create; {$ELSE} png := TPNGObject.Create; {$ENDIF} TRY png.LoadFromFile(s); bmp.Height := png.Height; bmp.Width := png.width; bmp.PixelFormat := pf24bit; bmp.Canvas.Draw(0,0, png); // convert PNG to Bitmap FINALLY png.Free END; end; procedure LoadWatermark(var W: TWatermark); var bmp: TBitmap; clr: TColor; data: bytep; i,x,y: integer; begin if not fileexists(W.Filename) then begin W.filename := ''; exit; end; bmp := TBitmap.Create; if (UpCaseExt(W.Filename) = '.JPG') or (UpCaseExt(W.Filename) = '.JPEG') then jpeg2bmp (W.Filename,bmp) else if (UpCaseExt(W.Filename) = '.BMP') then bmp.LoadFromFile(W.Filename) else png2bmp (W.Filename,bmp); W.Filename := ''; getmem(data,bmp.Width*bmp.Height*4); i := 1; //FPC/Lazarus faster with update locking http://wiki.lazarus.freepascal.org/Fast_direct_pixel_access try {$IFDEF FPC} bmp.BeginUpdate(True); {$ENDIF} for y:= (bmp.Height-1) downto 0 do begin for x := (bmp.Width-1) downto 0 do begin clr := bmp.Canvas.Pixels[x,y];// := data^[i+2]+(data^[i+1] shl 8)+(data^[i] shl 16); data^[i] := clr and 255; data^[i+1] := (clr shr 8) and 255; data^[i+2] := (clr shr 16) and 255; data^[i+3] := 255; i := i + 4; end;//for X end; //for Y finally {$IFDEF FPC} bmp.EndUpdate(False); {$ENDIF} end; W.Ht := bmp.Height ; W.Wid := bmp.Width; bmp.free; CreateTexture2D(W.Wid,W.Ht, Data, W.Texture2D); freemem(data); end; procedure DrawWatermark ( lX,lY,lW,lH: single; var W: TWatermark); begin Enter2D; glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D,W.Texture2D); glBegin(GL_QUADS); glTexCoord2d (0,1); glVertex2f(lX+lW,lY+lH); glTexCoord2d (0, 0); glVertex2f(lX+lW,lY); glTexCoord2d ( 1, 0); glVertex2f(lX,lY); glTexCoord2d (1, 1); glVertex2f(lX,lY+lH); glend; glDisable(GL_TEXTURE_2D); end; initialization gWatermark.Ht := 0; gWatermark.Wid := 0; gWatermark.Texture2D := 0; end.
unit SrvrDM; interface { This DataModule is the COM object that the TRemoteServer component will connect to. Each remote connection gets a new DataModule that is used during that clients session. When using a TDatabase on a Remote Data Module, be sure to set it's HandleShared property to True. If you use a TSession then set it's AutoSessionName property to True. } uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComServ, ComObj, VCLCom, StdVcl, BdeProv, DataBkr, Serv_TLB, DBTables, Provider, Db, DBClient, BDE; type TProjectData = class(TDataModule, IProjectData) Project: TTable; Employee: TQuery; EmpProj: TQuery; ProjectProvider: TProvider; UpdateQuery: TQuery; Database: TDatabase; ProjectSource: TDataSource; procedure ProjectProviderBeforeUpdateRecord(Sender: TObject; SourceDS: TDataSet; DeltaDS: TClientDataSet; UpdateKind: TUpdateKind; var Applied: Boolean); protected { These methods are from the IProjectData interface. To add IProvider properties, use the "export" option on the local menu of dataset or provider components. To add other types of methods or properties use Edit | Add to Interface or the type library editor (View | Type Library). } function Get_ProjectProvider: IProvider; safecall; function Get_Employee: IProvider; safecall; end; var ProjectData: TProjectData; implementation {$R *.DFM} { These two functions publish the providers for this server. You can generate these by right clicking on the DataSet and choosing "Export from data module" } function TProjectData.Get_ProjectProvider: IProvider; begin Result := ProjectProvider.Provider; end; function TProjectData.Get_Employee: IProvider; begin Result := Employee.Provider; end; { This function implements cascaded deletes. Normally, you would do this in a trigger, but for the sake of this demo, it is done here. } procedure TProjectData.ProjectProviderBeforeUpdateRecord(Sender: TObject; SourceDS: TDataSet; DeltaDS: TClientDataSet; UpdateKind: TUpdateKind; var Applied: Boolean); const DeleteQuery = 'delete from EMPLOYEE_PROJECT where PROJ_ID = :ProjID'; begin if (UpdateKind = ukDelete) and (SourceDS = Project) then begin UpdateQuery.SQL.Text := DeleteQuery; UpdateQuery.Params[0].AsString := DeltaDS.FieldByName('PROJ_ID').AsString; UpdateQuery.ExecSQL; end; end; initialization TComponentFactory.Create(ComServer, TProjectData, Class_ProjectData, ciMultiInstance); end.
unit NtUtils.Processes.Memory; interface uses NtUtils.Exceptions, Ntapi.ntmmapi; // Allocate memory in a process function NtxAllocateMemoryProcess(hProcess: THandle; Size: NativeUInt; out Memory: TMemory; Protection: Cardinal = PAGE_READWRITE): TNtxStatus; // Free memory in a process function NtxFreeMemoryProcess(hProcess: THandle; Address: Pointer; Size: NativeUInt): TNtxStatus; // Change memory protection function NtxProtectMemoryProcess(hProcess: THandle; var Memory: TMemory; Protection: Cardinal; pOldProtected: PCardinal = nil): TNtxStatus; // Read memory function NtxReadMemoryProcess(hProcess: THandle; Address: Pointer; Buffer: Pointer; BufferSize: NativeUInt): TNtxStatus; // Write memory function NtxWriteMemoryProcess(hProcess: THandle; Address: Pointer; Buffer: Pointer; BufferSize: NativeUInt): TNtxStatus; // Flush instruction cache function NtxFlushInstructionCache(hProcess: THandle; Address: Pointer; Size: NativeUInt): TNtxStatus; // Lock memory pages in working set or physical memory function NtxLockVirtualMemory(hProcess: THandle; var Memory: TMemory; MapType: TMapLockType = MapProcess): TNtxStatus; // Unlock locked memory pages function NtxUnlockVirtualMemory(hProcess: THandle; var Memory: TMemory; MapType: TMapLockType = MapProcess): TNtxStatus; { -------------------------------- Extension -------------------------------- } // Allocate and write memory function NtxAllocWriteMemoryProcess(hProcess: THandle; Buffer: Pointer; BufferSize: NativeUInt; out Memory: TMemory): TNtxStatus; // Allocate and write executable memory function NtxAllocWriteExecMemoryProcess(hProcess: THandle; Buffer: Pointer; BufferSize: NativeUInt; out Memory: TMemory): TNtxStatus; { ----------------------------- Generic wrapper ----------------------------- } type NtxMemory = class // Query fixed-size information class function Query<T>(hProcess: THandle; Address: Pointer; InfoClass: TMemoryInformationClass; out Buffer: T): TNtxStatus; static; // Read a fixed-size structure class function Read<T>(hProcess: THandle; Address: Pointer; out Buffer: T): TNtxStatus; static; // Write a fixed-size structure class function Write<T>(hProcess: THandle; Address: Pointer; const Buffer: T): TNtxStatus; static; // Allocate and write a fixed-size structure class function AllocWrite<T>(hProcess: THandle; const Buffer: T; out Memory: TMemory): TNtxStatus; static; // Allocate and write executable memory a fixed-size structure class function AllocWriteExec<T>(hProcess: THandle; const Buffer: T; out Memory: TMemory): TNtxStatus; static; end; implementation uses Ntapi.ntpsapi, Ntapi.ntseapi; function NtxAllocateMemoryProcess(hProcess: THandle; Size: NativeUInt; out Memory: TMemory; Protection: Cardinal = PAGE_READWRITE): TNtxStatus; begin Memory.Address := nil; Memory.Size := Size; Result.Location := 'NtAllocateVirtualMemory'; Result.LastCall.Expects(PROCESS_VM_OPERATION, @ProcessAccessType); Result.Status := NtAllocateVirtualMemory(hProcess, Memory.Address, 0, Memory.Size, MEM_COMMIT, Protection); end; function NtxFreeMemoryProcess(hProcess: THandle; Address: Pointer; Size: NativeUInt): TNtxStatus; var Memory: TMemory; begin Memory.Address := Address; Memory.Size := Size; Result.Location := 'NtFreeVirtualMemory'; Result.LastCall.Expects(PROCESS_VM_OPERATION, @ProcessAccessType); Result.Status := NtFreeVirtualMemory(hProcess, Memory.Address, Memory.Size, MEM_RELEASE); end; function NtxProtectMemoryProcess(hProcess: THandle; var Memory: TMemory; Protection: Cardinal; pOldProtected: PCardinal = nil): TNtxStatus; var OldProtected: Cardinal; begin Result.Location := 'NtProtectVirtualMemory'; Result.LastCall.Expects(PROCESS_VM_OPERATION, @ProcessAccessType); Result.Status := NtProtectVirtualMemory(hProcess, Memory.Address, Memory.Size, Protection, OldProtected); if Result.IsSuccess and Assigned(pOldProtected) then pOldProtected^ := OldProtected; end; function NtxReadMemoryProcess(hProcess: THandle; Address: Pointer; Buffer: Pointer; BufferSize: NativeUInt): TNtxStatus; begin Result.Location := 'NtReadVirtualMemory'; Result.LastCall.Expects(PROCESS_VM_READ, @ProcessAccessType); Result.Status := NtReadVirtualMemory(hProcess, Address, Buffer, BufferSize, nil); end; function NtxWriteMemoryProcess(hProcess: THandle; Address: Pointer; Buffer: Pointer; BufferSize: NativeUInt): TNtxStatus; begin Result.Location := 'NtWriteVirtualMemory'; Result.LastCall.Expects(PROCESS_VM_WRITE, @ProcessAccessType); Result.Status := NtWriteVirtualMemory(hProcess, Address, Buffer, BufferSize, nil); end; function NtxFlushInstructionCache(hProcess: THandle; Address: Pointer; Size: NativeUInt): TNtxStatus; begin Result.Location := 'NtxFlushInstructionCacheProcess'; Result.LastCall.Expects(PROCESS_VM_WRITE, @ProcessAccessType); Result.Status := NtFlushInstructionCache(hProcess, Address, Size); end; function NtxLockVirtualMemory(hProcess: THandle; var Memory: TMemory; MapType: TMapLockType = MapProcess): TNtxStatus; begin Result.Location := 'NtLockVirtualMemory'; Result.LastCall.Expects(PROCESS_VM_OPERATION, @ProcessAccessType); if MapType = MapSystem then Result.LastCall.ExpectedPrivilege := SE_LOCK_MEMORY_PRIVILEGE; Result.Status := NtLockVirtualMemory(hProcess, Memory.Address, Memory.Size, MapType); end; function NtxUnlockVirtualMemory(hProcess: THandle; var Memory: TMemory; MapType: TMapLockType = MapProcess): TNtxStatus; begin Result.Location := 'NtUnlockVirtualMemory'; Result.LastCall.Expects(PROCESS_VM_OPERATION, @ProcessAccessType); if MapType = MapSystem then Result.LastCall.ExpectedPrivilege := SE_LOCK_MEMORY_PRIVILEGE; Result.Status := NtUnlockVirtualMemory(hProcess, Memory.Address, Memory.Size, MapType); end; { Extension } function NtxAllocWriteMemoryProcess(hProcess: THandle; Buffer: Pointer; BufferSize: NativeUInt; out Memory: TMemory): TNtxStatus; begin // Allocate writable memory Result := NtxAllocateMemoryProcess(hProcess, BufferSize, Memory); if Result.IsSuccess then begin // Write data Result := NtxWriteMemoryProcess(hProcess, Memory.Address, Buffer, BufferSize); // Undo allocation on failure if not Result.IsSuccess then NtxFreeMemoryProcess(hProcess, Memory.Address, Memory.Size); end; end; function NtxAllocWriteExecMemoryProcess(hProcess: THandle; Buffer: Pointer; BufferSize: NativeUInt; out Memory: TMemory): TNtxStatus; begin // Allocate and write RW memory Result := NtxAllocWriteMemoryProcess(hProcess, Buffer, BufferSize, Memory); if Result.IsSuccess then begin // Make it executable Result := NtxProtectMemoryProcess(hProcess, Memory, PAGE_EXECUTE_READ); // Always flush instruction cache when changing executable memory if Result.IsSuccess then Result := NtxFlushInstructionCache(hProcess, Memory.Address, Memory.Size); // Undo on failure if not Result.IsSuccess then NtxFreeMemoryProcess(hProcess, Memory.Address, Memory.Size); end; end; { NtxMemory } class function NtxMemory.Query<T>(hProcess: THandle; Address: Pointer; InfoClass: TMemoryInformationClass; out Buffer: T): TNtxStatus; begin Result.Location := 'NtQueryVirtualMemory'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TMemoryInformationClass); Result.LastCall.Expects(PROCESS_QUERY_INFORMATION, @ProcessAccessType); Result.Status := NtQueryVirtualMemory(hProcess, Address, InfoClass, @Buffer, SizeOf(Buffer), nil); end; class function NtxMemory.Read<T>(hProcess: THandle; Address: Pointer; out Buffer: T): TNtxStatus; begin Result := NtxReadMemoryProcess(hProcess, Address, @Buffer, SizeOf(Buffer)); end; class function NtxMemory.Write<T>(hProcess: THandle; Address: Pointer; const Buffer: T): TNtxStatus; begin Result := NtxWriteMemoryProcess(hProcess, Address, @Buffer, SizeOf(Buffer)); end; class function NtxMemory.AllocWrite<T>(hProcess: THandle; const Buffer: T; out Memory: TMemory): TNtxStatus; begin Result := NtxAllocWriteMemoryProcess(hProcess, @Buffer, SizeOf(Buffer), Memory); end; class function NtxMemory.AllocWriteExec<T>(hProcess: THandle; const Buffer: T; out Memory: TMemory): TNtxStatus; begin Result := NtxAllocWriteExecMemoryProcess(hProcess, @Buffer, SizeOf(Buffer), Memory); end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { Generic SQL Property Editor } { } { Copyright (c) 1999 Borland Software Corp. } { } {*******************************************************} unit SqlEdit; interface {$IFDEF MSWINDOWS} uses Windows, Messages, ActiveX, SysUtils, Forms, Classes, Controls, Graphics, StdCtrls, ExtCtrls; {$ENDIF} {$IFDEF LINUX} uses Libc, Messages, ActiveX, SysUtils, Forms, Classes, Controls, Graphics, StdCtrls, ExtCtrls; {$ENDIF} type TExecuteEvent = procedure of Object; TPopulateThread = class(TThread) private FExecuteEvent: TExecuteEvent; public constructor Create(ExecuteEvent: TExecuteEvent); procedure Execute; override; end; TGetTableNamesProc = procedure(List: TStrings; SystemTables: Boolean) of object; TGetFieldNamesProc = procedure(const TableName: string; List: TStrings) of Object; TRequiresQuoteCharProc = function(const Name: string): Boolean of Object; TSQLEditForm = class(TForm) OkButton: TButton; HelpButton: TButton; CancelButton: TButton; AddFieldButton: TButton; AddTableButton: TButton; SQLLabel: TLabel; FieldListLabel: TLabel; TableListLabel: TLabel; TopPanel: TPanel; ButtonPanel: TPanel; FieldsPanel: TPanel; MetaInfoPanel: TPanel; TableListPanel: TPanel; TableFieldsSplitter: TSplitter; MetaInfoSQLSplitter: TSplitter; SQLMemo: TMemo; Image1: TImage; TableList: TListBox; FieldList: TListBox; procedure FormShow(Sender: TObject); procedure HelpButtonClick(Sender: TObject); procedure TableFieldsSplitterCanResize(Sender: TObject; var NewSize: Integer; var Accept: Boolean); procedure MetaInfoSQLSplitterCanResize(Sender: TObject; var NewSize: Integer; var Accept: Boolean); procedure MetaInfoSQLSplitterMoved(Sender: TObject); procedure TableListClick(Sender: TObject); procedure AddTableButtonClick(Sender: TObject); procedure AddFieldButtonClick(Sender: TObject); procedure SQLMemoExit(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure SQLMemoEnter(Sender: TObject); private CharHeight: Integer; FQuoteChar: string; FPopulateThread: TPopulateThread; FStartTable: string; GetTableNames: TGetTableNamesProc; GetFieldNames: TGetFieldNamesProc; SQLCanvas: TControlCanvas; procedure InsertText(Text: string; AddComma: Boolean = True); procedure DrawCaretPosIndicator; procedure PopulateTableList; procedure PopulateFieldList; protected NameRequiresQuoteChar : TRequiresQuoteCharProc; property QuoteChar: string read FQuoteChar write FQuoteChar; property StartTable: string read FStartTable write FStartTable; end; function EditSQL(var SQL: string; AGetTableNames: TGetTableNamesProc; AGetFieldNames: TGetFieldNamesProc; AStartTblName : string = ''; AQuoteChar : string = ''; ANeedsQuoteCharFunc: TRequiresQuoteCharProc = nil ): Boolean; overload; function EditSQL(SQL: TStrings; AGetTableNames: TGetTableNamesProc; AGetFieldNames: TGetFieldNamesProc; AStartTblName : string = ''; AQuoteChar : string = ''; ANeedsQuoteCharFunc: TRequiresQuoteCharProc = nil ): Boolean; overload; function DefaultReqQuoteChar( Name: string): Boolean; implementation {$R *.DFM} const SSelect = 'select'; { Do not localize } SFrom = 'from'; { Do not localize } function EditSQL(var SQL: string; AGetTableNames: TGetTableNamesProc; AGetFieldNames: TGetFieldNamesProc; AStartTblName : string = ''; AQuoteChar : string = ''; ANeedsQuoteCharFunc: TRequiresQuoteCharProc = nil ): Boolean; overload; begin with TSQLEditForm.Create(nil) do try GetTableNames := AGetTableNames; GetFieldNames := AGetFieldNames; QuoteChar := AQuoteChar; StartTable := AStartTblName; NameRequiresQuoteChar := ANeedsQuoteCharFunc; SQLMemo.Lines.Text := SQL; Result := ShowModal = mrOK; if Result then SQL := SQLMemo.Lines.Text; finally Free; end; end; function EditSQL(SQL: TStrings; AGetTableNames: TGetTableNamesProc; AGetFieldNames: TGetFieldNamesProc; AStartTblName : string = ''; AQuoteChar : string = ''; ANeedsQuoteCharFunc: TRequiresQuoteCharProc = nil ): Boolean; overload; var SQLText: string; begin SQLText := SQL.Text; Result := EditSQL(SQLText, AGetTableNames, AGetFieldNames, AStartTblName, AQuoteChar, ANeedsQuoteCharFunc); if Result then SQL.Text := SQLText; end; procedure TSQLEditForm.FormShow(Sender: TObject); begin TableList.Sorted := True; HelpContext := 27271; //hcDADOSQLEdit SQLCanvas := TControlCanvas.Create; SQLCanvas.Control := SQLMemo; CharHeight := SQLCanvas.TextHeight('0'); PopulateTableList; // FPopulateThread := TPopulateThread.Create(PopulateTableList); end; procedure TSQLEditForm.FormDestroy(Sender: TObject); begin if Assigned(FPopulateThread) then begin FPopulateThread.Terminate; FPopulateThread.WaitFor; FPopulateThread.Free; end; SQLCanvas.Free; end; procedure TSQLEditForm.HelpButtonClick(Sender: TObject); begin Application.HelpContext(HelpContext); end; procedure TSQLEditForm.PopulateTableList; var I: integer; begin if @GetTableNames = nil then Exit; try Screen.Cursor := crHourGlass; GetTableNames(TableList.Items, False); Screen.Cursor := crDefault; if FStartTable <> '' then begin for I := 0 to TableList.Items.Count -1 do begin if AnsiCompareStr( FStartTable, TableList.Items[I] ) = 0 then begin TableList.ItemIndex := I; TableListClick(nil); break; end; end; end; if Assigned(FPopulateThread) then if FPopulateThread.Terminated then Exit; if (TableList.Items.Count > 0) and (TableList.ItemIndex = -1) then begin TableList.ItemIndex := 0; TableListClick(nil); end; except Screen.Cursor := crDefault; end; end; procedure TSQLEditForm.TableFieldsSplitterCanResize(Sender: TObject; var NewSize: Integer; var Accept: Boolean); begin Accept := (NewSize > 44) and (NewSize < (MetaInfoPanel.Height - 65)); end; procedure TSQLEditForm.MetaInfoSQLSplitterCanResize(Sender: TObject; var NewSize: Integer; var Accept: Boolean); begin Accept := (NewSize > 100) and (NewSize < (ClientWidth - 100)); end; procedure TSQLEditForm.MetaInfoSQLSplitterMoved(Sender: TObject); begin SQLLabel.Left := SQLMemo.Left; end; procedure TSQLEditForm.PopulateFieldList; begin if @GetFieldNames = nil then Exit; try GetFieldNames(TableList.Items[TableList.ItemIndex], FieldList.Items); FieldList.Items.Insert(0, '*'); except end; end; procedure TSQLEditForm.TableListClick(Sender: TObject); begin PopulateFieldList; end; procedure TSQLEditForm.InsertText(Text: string; AddComma: Boolean = True); var StartSave: Integer; S: string; begin S := SQLMemo.Text; StartSave := SQLMemo.SelStart; if (S <> '') and (StartSave > 0) and not (S[StartSave] in [' ','(']) and not (Text[1] = ' ') then begin if AddComma and (S[StartSave] <> ',') then Text := ', '+Text else Text := ' ' + Text; end; System.Insert(Text, S, StartSave+1); SQLMemo.Text := S; SQLMemo.SelStart := StartSave + Length(Text); SQLMemo.Update; DrawCaretPosIndicator; end; procedure TSQLEditForm.AddTableButtonClick(Sender: TObject); var TableName, SQLText: string; NeedsQuote, Blank: Boolean; begin if TableList.ItemIndex > -1 then begin SQLText := SQLMemo.Text; TableName := TableList.Items[TableList.ItemIndex]; if (QuoteChar <>'') and (QuoteChar <> ' ') then begin if Assigned(NameRequiresQuoteChar) then NeedsQuote := NameRequiresQuoteChar(TableName) else NeedsQuote := DefaultReqQuoteChar(TableName); if NeedsQuote then TableName := QuoteChar + TableName + QuoteChar; end; Blank := SQLText = ''; if Blank or (Copy(SQLText, 1, 6) = SSelect) then InsertText(Format(' %s %s', [SFrom, TableName]), False) else InsertText(TableName, False); if Blank then begin SQLMemo.SelStart := 0; SQLMemo.Update; InsertText(SSelect+' ', False); end; end; end; procedure TSQLEditForm.AddFieldButtonClick(Sender: TObject); var I: Integer; ColumnName: string; NeedsQuote: Boolean; begin if FieldList.ItemIndex > -1 then begin { Help the user and assume this is a select if starting with nothing } if SQLMemo.Text = '' then begin SQLMemo.Text := SSelect; SQLMemo.SelStart := Length(SQLMemo.Text); end; for I := 0 to FieldList.Items.Count - 1 do if FieldList.Selected[I] then begin ColumnName := FieldList.Items[I]; if (ColumnName <> '*') and (QuoteChar <> '') and (QuoteChar <> ' ') then begin if Assigned(NameRequiresQuoteChar) then NeedsQuote := NameRequiresQuoteChar(ColumnName) else NeedsQuote := DefaultReqQuoteChar(ColumnName); if NeedsQuote then ColumnName := QuoteChar + ColumnName + QuoteChar; end; InsertText(ColumnName, (SQLMemo.Text <> SSelect) and (ColumnName <> '*')); end; end; end; procedure TSQLEditForm.SQLMemoExit(Sender: TObject); begin DrawCaretPosIndicator; end; procedure TSQLEditForm.SQLMemoEnter(Sender: TObject); begin { Erase the CaretPos indicator } SQLMemo.Invalidate; end; procedure TSQLEditForm.DrawCaretPosIndicator; var XPos, YPos: Integer; begin with SQLMemo.CaretPos do begin YPos := (Y+1)*CharHeight; XPos := SQLCanvas.TextWidth(Copy(SQLMemo.Lines[Y], 1, X)) - 3 ; SQLCanvas.Draw(XPos ,YPos, Image1.Picture.Graphic); end; end; { TPopulateThread } constructor TPopulateThread.Create(ExecuteEvent: TExecuteEvent); begin FExecuteEvent := ExecuteEvent; inherited Create(False); end; procedure TPopulateThread.Execute; begin CoInitialize(nil); try FExecuteEvent; except end; CoUninitialize; end; function DefaultReqQuoteChar( Name: string): Boolean; var p: PChar; begin p := PChar(Name); Result := False; repeat if not (p^ in ['A'..'Z', '0'..'9', '_']) then begin Result := True; break; end; Inc(p) until p^ = #0; end; end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} {/* * (c) Copyright 1993, Silicon Graphics, Inc. * 1993-1995 Microsoft Corporation * ALL RIGHTS RESERVED */} unit frmMain; interface uses Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Controls, Dialogs, OpenGL; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private DC: HDC; hrc: HGLRC; procedure Init; procedure SetDCPixelFormat; protected procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; end; var frmGL: TfrmGL; implementation uses DGLUT; {$R *.DFM} {======================================================================= Инициализация} procedure TfrmGL.Init; const light_position : Array [0..3] of GLfloat = ( 1.0, 1.0, 1.0, 0.0 ); global_ambient : Array [0..3] of GLfloat = ( 0.75, 0.75, 0.75, 1.0 ); begin glLightfv(GL_LIGHT0, GL_POSITION, @light_position); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, @global_ambient); glFrontFace (GL_CW); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); end; {======================================================================= Рисование картинки} procedure TfrmGL.WMPaint(var Msg: TWMPaint); var ps : TPaintStruct; const low_ambient : Array [0..3] of GLfloat = ( 0.1, 0.1, 0.1, 1.0 ); more_ambient : Array [0..3] of GLfloat = ( 0.4, 0.4, 0.4, 1.0 ); most_ambient : Array [0..3] of GLfloat = ( 1.0, 1.0, 1.0, 1.0 ); begin BeginPaint(Handle, ps); glClear( GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT ); //* material has small ambient reflection */ glMaterialfv(GL_FRONT, GL_AMBIENT, @low_ambient); glMaterialf(GL_FRONT, GL_SHININESS, 40.0); glPushMatrix; glTranslatef (0.0, 2.0, 0.0); glutSolidTeapot(1.0); glPopMatrix; //* material has moderate ambient reflection */ glMaterialfv(GL_FRONT, GL_AMBIENT, @more_ambient); glPushMatrix; glTranslatef (0.0, 0.0, 0.0); glutSolidTeapot(1.0); glPopMatrix; //* material has large ambient reflection */ glMaterialfv(GL_FRONT, GL_AMBIENT, @most_ambient); glPushMatrix; glTranslatef (0.0, -2.0, 0.0); glutSolidTeapot(1.0); glPopMatrix; SwapBuffers(DC); EndPaint(Handle, ps); end; {======================================================================= Создание окна} procedure TfrmGL.FormCreate(Sender: TObject); begin DC := GetDC(Handle); SetDCPixelFormat; hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); Init; end; {======================================================================= Изменение размеров окна} procedure TfrmGL.FormResize(Sender: TObject); begin glViewport(0, 0, ClientWidth, ClientHeight ); glMatrixMode (GL_PROJECTION); glLoadIdentity; If ClientWidth <= ClientHeight then glOrtho (-4.0, 4.0, -4.0*ClientHeight/ClientWidth, 4.0*ClientHeight/ClientWidth, -10.0, 10.0) else glOrtho (-4.0*ClientWidth/ClientHeight, 4.0*ClientWidth/ClientHeight, -4.0, 4.0, -10.0, 10.0); glMatrixMode (GL_MODELVIEW); InvalidateRect(Handle, nil, False); end; {======================================================================= Конец работы программы} procedure TfrmGL.FormDestroy(Sender: TObject); begin wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC(Handle, DC); DeleteDC (DC); end; {======================================================================= Обработка нажатия клавиши} procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close; end; {======================================================================= Устанавливаем формат пикселей} procedure TfrmGL.SetDCPixelFormat; var nPixelFormat: Integer; pfd: TPixelFormatDescriptor; begin FillChar(pfd, SizeOf(pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat(DC, @pfd); SetPixelFormat(DC, nPixelFormat, @pfd); end; end.
{ License: modified LGPL with linking exception (like RTL, FCL and LCL) See the file COPYING.modifiedLGPL.txt, included in the Lazarus distribution, for details about the license. See also: https://wiki.lazarus.freepascal.org/FPC_modified_LGPL } unit mvExtraData; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics; type { TDrawingExtraData } TDrawingExtraData = class private FColor: TColor; FId: integer; procedure SetColor(AValue: TColor); public constructor Create(aId: integer); virtual; property Color: TColor read FColor write SetColor; property Id: integer read FId; end; TTrackExtraData = class(TDrawingExtraData) private FWidth: Double; procedure SetWidth(AValue: Double); public property Width: Double read FWidth write SetWidth; // Line width in mm end; implementation { TDrawingExtraData } constructor TDrawingExtraData.Create(aId: integer); begin FId := aId; FColor := clRed; end; procedure TDrawingExtraData.SetColor(AValue: TColor); begin if FColor = AValue then Exit; FColor := AValue; end; { TTrackExtraData } procedure TTrackExtraData.SetWidth(AValue: Double); begin if AValue = FWidth then Exit; FWidth := abs(AValue); end; end.
unit LittleTest12; { This unit compiles but is not semantically meaningfull it is test cases for the code formatting utility } interface function Foo(): String; implementation function Foo(): String; begin Result := 'Foo'; end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Data.DBXReaderTableStorage; interface uses Data.DBXCommon, Data.DBXCommonTable, Data.FMTBcd ; type TDBXReaderTableStorage = class(TDBXRowTable) private FLastNext: Boolean; FCommand: TDBXCommand; FReader: TDBXReader; FColumns: TDBXValueTypeArray; FNextCalled: Boolean; // function ToColumnType(DataType: Integer): Integer; public constructor Create(Command: TDBXCommand; Reader: TDBXReader); destructor Destroy; override; function GetOrdinal(const ColumnName: UnicodeString): Integer; override; function First: Boolean; override; function Next: Boolean; override; function InBounds: Boolean; override; procedure Close; override; protected function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override; function GetColumns: TDBXValueTypeArray; override; function GetStorage: TObject; override; function GetCommand: TObject; override; end; TBcdObject = class public constructor Create(Bcd: TBcd); private FBcd: TBcd; public property BcdValue: TBcd read FBcd; end; implementation uses Data.DBXPlatform, System.SysUtils, Data.DBXCommonResStrs ; constructor TDBXReaderTableStorage.Create(Command: TDBXCommand; Reader: TDBXReader); begin Inherited Create(nil, nil); FCommand := Command; FReader := Reader; end; destructor TDBXReaderTableStorage.Destroy; begin Close; FreeObjectArray(TDBXFreeArray(FColumns)); inherited Destroy; end; function TDBXReaderTableStorage.GetCommand: TObject; begin Result := FCommand; FCommand := nil; end; function TDBXReaderTableStorage.GetOrdinal( const ColumnName: UnicodeString): Integer; begin Result := FReader.GetOrdinal(ColumnName); end; function TDBXReaderTableStorage.First: Boolean; begin if FNextCalled then raise Exception.Create(SUnsupportedOperation); Result := True; end; function TDBXReaderTableStorage.Next: Boolean; begin FNextCalled := True; Result := FReader.Next; FLastNext := Result; end; function TDBXReaderTableStorage.InBounds: Boolean; begin if not FNextCalled then Next; Result := FLastNext; end; procedure TDBXReaderTableStorage.Close; begin FreeAndNil(FReader); FreeAndNil(FCommand); end; function TDBXReaderTableStorage.GetColumns: TDBXValueTypeArray; var Ordinal: Integer; ValueType: TDBXValueType; begin if FColumns = nil then begin SetLength(FColumns, FReader.ColumnCount); for Ordinal := Low(FColumns) to High(FColumns) do begin ValueType := FReader.ValueType[Ordinal]; FColumns[Ordinal] := TDBXValueType.Create; FColumns[Ordinal].Name := ValueType.Name; FColumns[Ordinal].DisplayName := ValueType.DisplayName; FColumns[Ordinal].DataType := ValueType.DataType; FColumns[Ordinal].SubType := ValueType.SubType; FColumns[Ordinal].Size := ValueType.Size; FColumns[Ordinal].Precision := ValueType.Precision; end; end; Result := FColumns; end; //function TDBXReaderTableStorage.ToColumnType(DataType: Integer): Integer; //begin // case DataType of // TDBXDataTypes.AnsiStringType, // TDBXDataTypes.WideStringType: // Result := TDBXColumnType.Varchar; // TDBXDataTypes.BooleanType: // Result := TDBXColumnType.Boolean; // TDBXDataTypes.Int16Type: // Result := TDBXColumnType.Short; // TDBXDataTypes.Int32Type: // Result := TDBXColumnType.Int; // TDBXDataTypes.Int64Type: // Result := TDBXColumnType.Long; // TDBXDataTypes.BcdType: // Result := TDBXColumnType.Decimal; // else // Result := TDBXColumnType.Notype; // end; //end; function TDBXReaderTableStorage.GetStorage: TObject; begin Result := FReader; end; function TDBXReaderTableStorage.GetWritableValue(const Ordinal: Integer): TDBXWritableValue; begin Result := TDBXWritableValue(FReader.Value[Ordinal]); end; constructor TBcdObject.Create(Bcd: TBcd); begin inherited Create; FBcd := Bcd; end; end.
unit uGMV_Monitor; interface uses Classes, XMLIntf, XMLDoc ; type TfReady = function: Boolean; stdcall; TfReset = function: Boolean; stdcall; TfgetBufferLength = function: integer; stdcall; TfgetStatus = function: PAnsiChar; stdcall; TResultRecord = record Value: string; UnitsName: string; UnitsValue: string; Method: string; Year: string; Month: string; Day: string; Hour: string; Minute: string; Second: string; end; TGMV_Monitor = class(TObject) private fVendor: string; fModel: string; fSerialNumber: string; fSoftwareVersion: string; fLibraryName: string; fMonitorLibrary: THandle; fReady: TfReady; fReset: TfReset; fgetBufferLength: TfgetBufferLength; fgetStatus: TfgetStatus; rrSystolic, rrDiastolic, rrPulse, rrTemp, rrOxygen: TResultRecord; function getBPString: string; function getPulseString: string; function getTempString: string; function getTempUnitString: string; function getSpO2String: string; function getXMLString: string; function getDescription: string; procedure setUpRR(var aRR: TResultRecord; aNode: IXMLNode); public Active: Boolean; constructor Create; destructor Destroy; override; procedure getData(aReset: Boolean = False); property Vendor: string read fVendor; property Model: string read fModel; property SerialNumber: string read fSerialNumber; property SoftwareVersion: string read fSoftwareVersion; property sBP: string read getBPString; property sPulse: string read getPulseString; property sTemp: string read getTempString; property sTempUnit: string read getTempUnitString; // ?? property sSpO2: string read getSpO2String; property XMLString: string read getXMLString; property LibraryName: string read fLibraryName; property Description: string read getDescription; procedure setVersionInfo; end; const sInvalidValue = 'Invalid Value'; tnVitals = 'Vitals'; tnVendor = 'Vendor'; tnModel = 'Model'; tnSerialNumber = 'Serial_Number'; tnResult = 'Result'; nnTemp = 'Body_temperature'; nnOxygen = 'Oxygen_saturation'; nnPulse = 'Pulse'; nnSBP = 'Systolic_blood_pressure'; nnDBP = 'Diastolic_blood_pressure'; nnValue = 'Value'; nnUnits = 'Units'; nnMethod = 'Method'; nnTimeStamp = 'Time_stamp'; anName = 'name'; anYear = 'year'; anMonth = 'month'; anDay = 'day'; anHour = 'hour'; anMinute = 'minute'; anSecond = 'second'; implementation uses Windows, Forms, SysUtils, uGMV_GlobalVars, uGMV_DLLCommon, uXML, Dialogs , {$WARN UNIT_PLATFORM OFF} FileCTRL {$WARN UNIT_PLATFORM ON} ; procedure ClearResultRecord(var aR: TResultRecord); begin with aR do begin Value := ''; UnitsName := ''; UnitsValue := ''; Method := ''; Year := ''; Month := ''; Day := ''; Hour := ''; Minute := ''; Second := ''; end; end; constructor TGMV_Monitor.Create; var sDir, sFN: string; i: Integer; FLB: TFileListBox; P: Pointer; DLLHandle: THandle; begin inherited Create; fVendor := 'Unknown'; fSoftwareVersion := 'Unknown'; fModel := 'Unknown'; Active := False; FLB := TFileListBox.Create(application); FLB.Parent := Application.MainForm; FLB.Visible := False; FLB.Mask := '*.dll'; sDir := ExtractFileDir(Application.ExeName) + '\' + GMV_PlugInDir; try if not SysUtils.DirectoryExists(sDir) then exit; FLB.ApplyFilePath(sDir); // Here is where the no parent issue fires DRP@5-28-2013 fMonitorLibrary := 0; for i := 0 to FLB.Items.Count - 1 do begin sFN := sDir + '\' + FLB.Items[i]; // FindModule(sFN, GMV_PlugInReset, DLLHandle, P); 2009-04-15 FindModule(sFN, GMV_PlugInReady, DLLHandle, P); // 2009-04-15 if Assigned(P) then begin fLibraryName := sFN; fMonitorLibrary := DLLHandle; // fReset := p; // commented out 2009-04-15 fReady := p; // if fReset then // commented out 2009-04015 if fReady then begin // FindModule(sFN, GMV_PlugInReady, DLLHandle, P); // fReady := p; FindModule(sFN,GMV_PlugInReset,DLLHandle,P); fReset := P; FindModule(sFN, GMV_PlugInReady, DLLHandle, P); fgetBufferLength := P; FindModule(sFN, GMV_PlugInGetStatus, DLLHandle, P); fgetStatus := P; // getData(true); // commented out 2009-04-15 setVersionInfo; // zzzzzzandria 2009-04-15 Active := True; break; end; FreeLibrary(DLLHandle); fMonitorLibrary := 0; end; end; except // Swallowing the exception tho I doubt it will work even with DLL libraries see line 163 DRP@5-28-2013 { on E:Exception do ShowMessage('uGMV_Monitor Error: ' + E.Message); } end; FLB.Free; end; destructor TGMV_Monitor.Destroy; begin if fMonitorLibrary <> 0 then try FreeLibrary(fMonitorLibrary); except end; inherited; end; function TGMV_Monitor.getBPString: string; begin Result := rrSystolic.Value + '/' + rrDiastolic.Value; if Result = '/' then Result := ''; end; function TGMV_Monitor.getPulseString: string; begin Result := rrPulse.Value; end; function TGMV_Monitor.getTempString: string; begin Result := rrTemp.Value; end; function TGMV_Monitor.getTempUnitString: string; begin Result := rrTemp.UnitsName; end; function TGMV_Monitor.getSpO2String: string; begin Result := rrOxygen.Value; end; function TGMV_Monitor.getXMLString: string; begin Result := ''; try // Ready always reaturns False if not Assigned(fReady) then Exit; if fReady then Result := string(AnsiString(fGetStatus)) else Result := ''; // if not Assigned(fReset) then Exit; // fReset; except end; end; procedure TGMV_Monitor.setUpRR(var aRR: TResultRecord; aNode: IXMLNode); begin ClearResultRecord(aRR); with aRR do begin try Value := aNode.ChildNodes[nnValue].Text; except on E: Exception do ShowMessage('Setup RR Value:' + #13#10 + E.Message); end; try UnitsName := aNode.ChildNodes[nnUnits].GetAttribute(anName); except on E: Exception do ShowMessage('Setup RR Units Name:' + #13#10 + E.Message); end; try UnitsValue := aNode.ChildNodes[nnUnits].Text; except on E: Exception do ShowMessage('Setup RR Units Value:' + #13#10 + E.Message); end; try Method := aNode.ChildNodes[nnMethod].Text; except on E: Exception do ShowMessage('Setup RR Method:' + #13#10 + E.Message); end; try Year := aNode.ChildNodes[nnTimeStamp].GetAttribute(anYear); except on E: Exception do ShowMessage('Setup RR Year:' + #13#10 + E.Message); end; try Month := aNode.ChildNodes[nnTimeStamp].GetAttribute(anMonth); except on E: Exception do ShowMessage('Setup RR Month :' + #13#10 + E.Message); end; try Day := aNode.ChildNodes[nnTimeStamp].GetAttribute(anDay); except on E: Exception do ShowMessage('Setup RR day:' + #13#10 + E.Message); end; try Hour := aNode.ChildNodes[nnTimeStamp].GetAttribute(anHour); except on E: Exception do ShowMessage('Setup RR Hour:' + #13#10 + E.Message); end; try Minute := aNode.ChildNodes[nnTimeStamp].GetAttribute(anMinute); except on E: Exception do ShowMessage('Setup RR Minute:' + #13#10 + E.Message); end; try Second := aNode.ChildNodes[nnTimeStamp].GetAttribute(anSecond); except on E: Exception do ShowMessage('Setup RR Second:' + #13#10 + E.Message); end; end; end; procedure TGMV_Monitor.setVersionInfo; var xDOC: IXMLDocument; xNode: IXMLNode; s: string; begin s := XMLString; xDOC := XMLDocument(s); xNode := xDoc.ChildNodes[tnVitals]; if Assigned(xNode) then begin fVendor := xNode.ChildNodes[tnVendor].Text; fModel := xNode.ChildNodes[tnModel].Text; fSerialNumber := xNode.ChildNodes[tnSerialNumber].Text; // fSoftwareVersion := xNode.ChildNodes[tnVendor]; end; end; procedure TGMV_Monitor.getData(aReset: Boolean = False); var xDOC: IXMLDocument; xxNode, xNode: IXMLNode; s, ss: string; i: Integer; begin s := XMLString; if s = '' then begin ClearResultRecord(rrSystolic); ClearResultRecord(rrDiastolic); ClearResultRecord(rrPulse); ClearResultRecord(rrTemp); ClearResultRecord(rrOxygen); Exit; end; xDOC := XMLDocument(s); xNode := xDoc.ChildNodes[tnVitals]; if Assigned(xNode) then begin if aReset then begin fVendor := xNode.ChildNodes[tnVendor].Text; fModel := xNode.ChildNodes[tnModel].Text; fSerialNumber := xNode.ChildNodes[tnSerialNumber].Text; // fSoftwareVersion := xNode.ChildNodes[tnVendor]; end; for i := 0 to xNode.ChildNodes.Count - 1 do begin xxNode := xNode.ChildNodes[i]; if xxNode.Nodename = tnResult then begin try ss := xxNode.GetAttribute(anName); if ss = nnPulse then setUpRR(rrPulse, xxNode); if ss = nnTemp then setUpRR(rrTemp, xxNode); if ss = nnOxygen then setUpRR(rrOxygen, xxNode); if ss = nnSBP then setUpRR(rrSystolic, xxNode); if ss = nnDBP then setUpRR(rrDiastolic, xxNode); except on E: Exception do ShowMessage('Get Data:' + #13#10 + E.Message); end; end; end; end; fReset; // reset is the part of the protocol end; function TGMV_Monitor.getDescription: string; begin Result := fVendor + ' ' + fModel + ' (SN: ' + fSerialNumber + ')' + #13 + '_____________________________' + #13 + #13 + 'Software: ' + fSoftwareVersion; end; end.
{**************************************************************************************************} { } { Project JEDI Code Library (JCL) } { } { The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); } { you may not use this file except in compliance with the License. You may obtain a copy of the } { License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF } { ANY KIND, either express or implied. See the License for the specific language governing rights } { and limitations under the License. } { } { The Original Code is JclFileUtils.pas. } { } { The Initial Developer of the Original Code is documented in the accompanying } { help file JCL.chm. Portions created by these individuals are Copyright (C) of these individuals. } { } {**************************************************************************************************} { } { This unit contains routines and classes for working with files, directories and path strings. } { Additionally it contains wrapper classes for file mapping objects and version resources. } { Generically speaking, everything that has to do with files and directories. Note that filesystem } { specific functionality has been extracted into external units, for example JclNTFS which } { contains NTFS specific utility routines, and that the JclShell unit contains some file related } { routines as well but they are specific to the Windows shell. } { } { Unit owner: Marcel van Brakel } { Last modified: March 25, 2002 } { } {**************************************************************************************************} unit JclFileUtils; {$I jcl.inc} {$WEAKPACKAGEUNIT ON} interface uses {$IFDEF MSWINDOWS} Windows, {$ENDIF MSWINDOWS} Classes, Graphics, SysUtils, JclBase, JclSysInfo; //-------------------------------------------------------------------------------------------------- // Path Manipulation // // Various support routines for working with path strings. For example, building a path from // elements or extracting the elements from a path, interpretation of paths and transformations of // paths. //-------------------------------------------------------------------------------------------------- const {$IFDEF LINUX} PathSeparator = '/'; {$ENDIF LINUX} {$IFDEF MSWINDOWS} DriveLetters = ['a'..'z', 'A'..'Z']; PathDevicePrefix = '\\.\'; PathSeparator = '\'; PathUncPrefix = '\\'; {$ENDIF MSWINDOWS} type TCompactPath = ({cpBegin, }cpCenter, cpEnd); function PathAddSeparator(const Path: string): string; function PathAddExtension(const Path, Extension: string): string; function PathAppend(const Path, Append: string): string; function PathBuildRoot(const Drive: Byte): string; function PathCanonicalize(const Path: string): string; function PathCommonPrefix(const Path1, Path2: string): Integer; function PathCompactPath(const DC: HDC; const Path: string; const Width: Integer; CmpFmt: TCompactPath): string; overload; function PathCompactPath(const Canvas: TCanvas; const Path: string; const Width: Integer; CmpFmt: TCompactPath): string; overload; procedure PathExtractElements(const Source: string; var Drive, Path, FileName, Ext: string); function PathExtractFileDirFixed(const S: AnsiString): AnsiString; function PathExtractFileNameNoExt(const Path: string): string; function PathExtractPathDepth(const Path: string; Depth: Integer): string; function PathGetDepth(const Path: string): Integer; function PathGetLongName(const Path: string): string; function PathGetLongName2(Path: string): string; function PathGetShortName(const Path: string): string; function PathIsAbsolute(const Path: string): Boolean; function PathIsChild(const Path, Base: AnsiString): Boolean; function PathIsDiskDevice(const Path: string): Boolean; function PathIsUNC(const Path: string): Boolean; function PathRemoveSeparator(const Path: string): string; function PathRemoveExtension(const Path: string): string; //-------------------------------------------------------------------------------------------------- // Files and Directories // // Routines for working with files and directories. Includes routines to extract various file // attributes or update them, volume locking and routines for creating temporary files. //-------------------------------------------------------------------------------------------------- type TDelTreeProgress = function (const FileName: string; Attr: DWORD): Boolean; TFileListOption = (flFullNames, flRecursive, flMaskedSubfolders); TFileListOptions = set of TFileListOption; function BuildFileList(const Path: string; const Attr: Integer; const List: TStrings): Boolean; function AdvBuildFileList(const Path: string; const Attr: Integer; const Files: TStrings; const Options: TFileListOptions = []; const SubfoldersMask: string = ''): Boolean; function CloseVolume(var Volume: THandle): Boolean; procedure CreateEmptyFile(const FileName: string); function DeleteDirectory(const DirectoryName: string; MoveToRecycleBin: Boolean): Boolean; function DelTree(const Path: string): Boolean; function DelTreeEx(const Path: string; AbortOnFailure: Boolean; Progress: TDelTreeProgress): Boolean; function DirectoryExists(const Name: string): Boolean; {$IFDEF MSWINDOWS} function DiskInDrive(Drive: Char): Boolean; {$ENDIF MSWINDOWS} function FileCreateTemp(var Prefix: string): THandle; function FileExists(const FileName: string): Boolean; function GetBackupFileName(const FileName: string): string; function FileGetDisplayName(const FileName: string): string; function FileGetSize(const FileName: string): Integer; function FileGetTempName(const Prefix: string): string; function FileGetTypeName(const FileName: string): string; function FindUnusedFileName(const FileName, FileExt, Suffix: AnsiString): AnsiString; function ForceDirectories(Name: string): Boolean; function GetDirectorySize(const Path: string): Int64; function GetDriveTypeStr(const Drive: Char): string; function GetFileAgeCoherence(const FileName: string): Boolean; procedure GetFileAttributeList(const Items: TStrings; const Attr: Integer); procedure GetFileAttributeListEx(const Items: TStrings; const Attr: Integer); function GetFileInformation(const FileName: string): TSearchRec; function GetFileLastWrite(const FileName: string): TFileTime; function GetFileLastAccess(const FileName: string): TFileTime; function GetFileCreation(const FileName: string): TFileTime; function GetModulePath(const Module: HMODULE): string; function GetSizeOfFile(const FileName: string): Int64; overload; function GetSizeOfFile(Handle: THandle): Int64; overload; function GetStandardFileInfo(const FileName: string): TWin32FileAttributeData; function IsDirectory(const FileName: string): Boolean; function LockVolume(const Volume: string; var Handle: THandle): Boolean; function OpenVolume(const Drive: Char): THandle; function SetDirLastWrite(const DirName: string; const DateTime: TDateTime): Boolean; function SetDirLastAccess(const DirName: string; const DateTime: TDateTime): Boolean; function SetDirCreation(const DirName: string; const DateTime: TDateTime): Boolean; function SetFileLastWrite(const FileName: string; const DateTime: TDateTime): Boolean; function SetFileLastAccess(const FileName: string; const DateTime: TDateTime): Boolean; function SetFileCreation(const FileName: string; const DateTime: TDateTime): Boolean; procedure ShredFile(const FileName: string; Times: Integer = 1); function UnlockVolume(var Handle: THandle): Boolean; function Win32DeleteFile(const FileName: string; MoveToRecycleBin: Boolean): Boolean; function Win32BackupFile(const FileName: string; Move: Boolean): Boolean; function Win32RestoreFile(const FileName: string): Boolean; //-------------------------------------------------------------------------------------------------- // TFileVersionInfo // // Class that enables reading the version information stored in a PE file. //-------------------------------------------------------------------------------------------------- type TFileFlag = (ffDebug, ffInfoInferred, ffPatched, ffPreRelease, ffPrivateBuild, ffSpecialBuild); TFileFlags = set of TFileFlag; PLangIdRec = ^TLangIdRec; TLangIdRec = packed record case Integer of 0: ( LangId: Word; CodePage: Word); 1: ( Pair: DWORD); end; EJclFileVersionInfoError = class (EJclError); TJclFileVersionInfo = class (TObject) private FBuffer: string; FFixedInfo: PVSFixedFileInfo; FFileFlags: TFileFlags; FItemList: TStrings; FItems: TStrings; FLanguages: array of TLangIdRec; FLanguageIndex: Integer; FTranslations: array of TLangIdRec; function GetFixedInfo: TVSFixedFileInfo; function GetLanguageCount: Integer; function GetLanguageIds(Index: Integer): string; function GetLanguageNames(Index: Integer): string; function GetLanguages(Index: Integer): TLangIdRec; function GetTranslationCount: Integer; function GetTranslations(Index: Integer): TLangIdRec; procedure SetLanguageIndex(const Value: Integer); protected procedure CreateItemsForLanguage; procedure CheckLanguageIndex(Value: Integer); procedure ExtractData; procedure ExtractFlags; function GetBinFileVersion: string; function GetBinProductVersion: string; function GetFileOS: DWORD; function GetFileSubType: DWORD; function GetFileType: DWORD; function GetVersionKeyValue(Index: Integer): string; public constructor Attach(VersionInfoData: Pointer; Size: Integer); constructor Create(const FileName: string); destructor Destroy; override; class function VersionLanguageId(const LangIdRec: TLangIdRec): string; class function VersionLanguageName(const LangId: Word): string; function TranslationMatchesLanguages(Exact: Boolean = True): Boolean; property BinFileVersion: string read GetBinFileVersion; property BinProductVersion: string read GetBinProductVersion; property Comments: string index 1 read GetVersionKeyValue; property CompanyName: string index 2 read GetVersionKeyValue; property FileDescription: string index 3 read GetVersionKeyValue; property FixedInfo: TVSFixedFileInfo read GetFixedInfo; property FileFlags: TFileFlags read FFileFlags; property FileOS: DWORD read GetFileOS; property FileSubType: DWORD read GetFileSubType; property FileType: DWORD read GetFileType; property FileVersion: string index 4 read GetVersionKeyValue; property Items: TStrings read FItems; property InternalName: string index 5 read GetVersionKeyValue; property LanguageCount: Integer read GetLanguageCount; property LanguageIds[Index: Integer]: string read GetLanguageIds; property LanguageIndex: Integer read FLanguageIndex write SetLanguageIndex; property Languages[Index: Integer]: TLangIdRec read GetLanguages; property LanguageNames[Index: Integer]: string read GetLanguageNames; property LegalCopyright: string index 6 read GetVersionKeyValue; property LegalTradeMarks: string index 7 read GetVersionKeyValue; property OriginalFilename: string index 8 read GetVersionKeyValue; property PrivateBuild: string index 12 read GetVersionKeyValue; property ProductName: string index 9 read GetVersionKeyValue; property ProductVersion: string index 10 read GetVersionKeyValue; property SpecialBuild: string index 11 read GetVersionKeyValue; property TranslationCount: Integer read GetTranslationCount; property Translations[Index: Integer]: TLangIdRec read GetTranslations; end; function OSIdentToString(const OSIdent: DWORD): string; function OSFileTypeToString(const OSFileType: DWORD; const OSFileSubType: DWORD = 0): string; function VersionResourceAvailable(const FileName: string): Boolean; function VersionFixedFileInfo(const FileName: string; var FixedInfo: TVSFixedFileInfo): Boolean; function FormatVersionString(const HiV, LoV: Word): string; overload; function FormatVersionString(const Major, Minor, Build, Revision: Word): string; overload; //-------------------------------------------------------------------------------------------------- // Streams // // TStream descendent classes for dealing with temporary files and for using file mapping objects. //-------------------------------------------------------------------------------------------------- { TTempFileStream } type TJclTempFileStream = class (THandleStream) private FFileName: string; public constructor Create(const Prefix: string); destructor Destroy; override; property FileName: string read FFileName; end; TJclCustomFileMapping = class; { TJclFileMappingView } TJclFileMappingView = class (TCustomMemoryStream) private FFileMapping: TJclCustomFileMapping; FOffsetHigh: Cardinal; FOffsetLow: Cardinal; function GetIndex: Integer; function GetOffset: Int64; public constructor Create(const FileMap: TJclCustomFileMapping; Access, Size: Cardinal; ViewOffset: Int64); constructor CreateAt(FileMap: TJclCustomFileMapping; Access, Size: Cardinal; ViewOffset: Int64; Address: Pointer); destructor Destroy; override; function Flush(const Count: Cardinal): Boolean; procedure LoadFromStream(const Stream: TStream); procedure LoadFromFile(const FileName: string); function Write(const Buffer; Count: Longint): Longint; override; property Index: Integer read GetIndex; property FileMapping: TJclCustomFileMapping read FFileMapping; property Offset: Int64 read GetOffset; end; { TJclCustomFileMapping } TJclFileMappingRoundOffset = (rvDown, rvUp); TJclCustomFileMapping = class (TObject) private FExisted: Boolean; FHandle: THandle; FName: string; FRoundViewOffset: TJclFileMappingRoundOffset; FViews: TList; function GetCount: Integer; function GetView(Index: Integer): TJclFileMappingView; protected procedure ClearViews; procedure InternalCreate(const FileHandle: THandle; const Name: string; const Protect: Cardinal; MaximumSize: Int64; const SecAttr: PSecurityAttributes); procedure InternalOpen(const Name: string; const InheritHandle: Boolean; const DesiredAccess: Cardinal); constructor Create; public constructor Open(const Name: string; const InheritHandle: Boolean; const DesiredAccess: Cardinal); destructor Destroy; override; function Add(const Access, Count: Cardinal; const Offset: Int64): Integer; function AddAt(const Access, Count: Cardinal; const Offset: Int64; const Address: Pointer): Integer; procedure Delete(const Index: Integer); function IndexOf(const View: TJclFileMappingView): Integer; property Count: Integer read GetCount; property Existed: Boolean read FExisted; property Handle: THandle read FHandle; property Name: string read FName; property RoundViewOffset: TJclFileMappingRoundOffset read FRoundViewOffset write FRoundViewOffset; property Views[index: Integer]: TJclFileMappingView read GetView; end; { TJclFileMapping } TJclFileMapping = class (TJclCustomFileMapping) private FFileHandle: THandle; public constructor Create(const FileName: string; FileMode: Cardinal; const Name: string; Protect: Cardinal; const MaximumSize: Int64; const SecAttr: PSecurityAttributes); overload; constructor Create(const FileHandle: THandle; const Name: string; Protect: Cardinal; const MaximumSize: Int64; const SecAttr: PSecurityAttributes); overload; destructor Destroy; override; property FileHandle: THandle read FFileHandle; end; { TJclSwapFileMapping } TJclSwapFileMapping = class (TJclCustomFileMapping) public constructor Create(const Name: string; Protect: Cardinal; const MaximumSize: Int64; const SecAttr: PSecurityAttributes); end; //-------------------------------------------------------------------------------------------------- // TJclFileMappingStream //-------------------------------------------------------------------------------------------------- TJclFileMappingStream = class (TCustomMemoryStream) private FFileHandle: THandle; FMapping: THandle; protected procedure Close; public constructor Create(const FileName: string; FileMode: Word = fmOpenRead or fmShareDenyWrite); destructor Destroy; override; function Write(const Buffer; Count: Longint): Longint; override; end; //-------------------------------------------------------------------------------------------------- // TJclMappedTextReader //-------------------------------------------------------------------------------------------------- TJclMappedTextReader = class (TPersistent) private FContent: PChar; FEnd: PChar; FFreeStream: Boolean; FLastLineNumber: Integer; FLastPosition: PChar; FLineCount: Integer; FMemoryStream: TCustomMemoryStream; FPosition: PChar; FSize: Integer; function GetAsString: string; function GetEof: Boolean; function GetChars(Index: Integer): Char; function GetLineCount: Integer; function GetLines(LineNumber: Integer): string; function GetPosition: Integer; function GetPositionFromLine(LineNumber: Integer): Integer; procedure SetPosition(const Value: Integer); protected procedure AssignTo(Dest: TPersistent); override; procedure Init; function PtrFromLine(LineNumber: Integer): PChar; function StringFromPosition(var StartPos: PChar): string; public constructor Create(MemoryStream: TCustomMemoryStream; FreeStream: Boolean = True); overload; constructor Create(const FileName: string); overload; destructor Destroy; override; procedure GoBegin; function Read: Char; function ReadLn: string; property AsString: string read GetAsString; property Chars[Index: Integer]: Char read GetChars; property Content: PChar read FContent; property Eof: Boolean read GetEof; property Lines[LineNumber: Integer]: string read GetLines; property LineCount: Integer read GetLineCount; property PositionFromLine[LineNumber: Integer]: Integer read GetPositionFromLine; property Position: Integer read GetPosition write SetPosition; property Size: Integer read FSize; end; //-------------------------------------------------------------------------------------------------- // TJclFileMaskComparator //-------------------------------------------------------------------------------------------------- // TODO UNTESTET/UNDOCUMENTED type TJclFileMaskComparator = class(TObject) private FFileMask: string; FExts: array of string; FNames: array of string; FWildChars: array of Byte; FSeparator: Char; procedure CreateMultiMasks; function GetCount: Integer; function GetExts(Index: Integer): string; function GetMasks(Index: Integer): string; function GetNames(Index: Integer): string; procedure SetFileMask(const Value: string); procedure SetSeparator(const Value: Char); public constructor Create; function Compare(const NameExt: string): Boolean; property Count: Integer read GetCount; property Exts[Index: Integer]: string read GetExts; property FileMask: string read FFileMask write SetFileMask; property Masks[Index: Integer]: string read GetMasks; property Names[Index: Integer]: string read GetNames; property Separator: Char read FSeparator write SetSeparator; end; //-------------------------------------------------------------------------------------------------- // Exceptions //-------------------------------------------------------------------------------------------------- EJclPathError = class (EJclError); EJclFileUtilsError = class (EJclError); EJclTempFileStreamError = class (EJclWin32Error); EJclFileMappingError = class (EJclWin32Error); EJclFileMappingViewError = class (EJclWin32Error); implementation uses {$IFDEF MSWINDOWS} ActiveX, ShellApi, ShlObj, {$ENDIF MSWINDOWS} JclDateTime, JclResources, JclSecurity, JclShell, JclStrings, JclSysUtils, JclWin32; { Some general notes: This unit redeclares some functions from FileCtrl.pas to avoid a dependeny on that unit in the JCL. The problem is that FileCtrl.pas uses some units (eg Forms.pas) which have ridiculous initialization requirements. They add 4KB (!) to the executable and roughly 1 second of startup. That initialization is only necessary for GUI applications and is unacceptable for high performance services or console apps. The routines which query files or directories for their attributes deliberately use FindFirst eventhough there may be easier ways to get at the required information. This is because FindFirst is about the only routine which doesn't cause the file's last modification/accessed time to be changed which is usually an undesired side-effect. } //================================================================================================== // TJclTempFileStream //================================================================================================== constructor TJclTempFileStream.Create(const Prefix: string); var FileHandle: THandle; begin FFileName := Prefix; FileHandle := FileCreateTemp(FFileName); if FileHandle = INVALID_HANDLE_VALUE then raise EJclTempFileStreamError.CreateResRec(@RsFileStreamCreate); inherited Create(FileHandle); end; //-------------------------------------------------------------------------------------------------- destructor TJclTempFileStream.Destroy; begin if THandle(Handle) <> INVALID_HANDLE_VALUE then CloseHandle(Handle); inherited Destroy; end; //================================================================================================== // TJclFileMappingView //================================================================================================== constructor TJclFileMappingView.Create(const FileMap: TJclCustomFileMapping; Access, Size: Cardinal; ViewOffset: Int64); var BaseAddress: Pointer; OffsetLow, OffsetHigh: Cardinal; begin inherited Create; if FileMap = nil then raise EJclFileMappingViewError.CreateResRec(@RsViewNeedsMapping); FFileMapping := FileMap; // Offset must be a multiple of system memory allocation granularity RoundToAllocGranularity64(ViewOffset, FFileMapping.RoundViewOffset = rvUp); I64ToCardinals(ViewOffset, OffsetLow, OffsetHigh); FOffsetHigh := OffsetHigh; FOffsetLow := OffsetLow; BaseAddress := MapViewOfFile(FFileMapping.Handle, Access, FOffsetHigh, FOffsetLow, Size); if BaseAddress = nil then raise EJclFileMappingViewError.CreateResRec(@RsCreateFileMappingView); // If we are mapping a file and size = 0 then MapViewOfFile has mapped the entire file. We must // figure out the size ourselves before we can call SetPointer. Since in case of failure to // retrieve the size we raise an exception, we also have to explicitly unmap the view which // otherwise would have been done by the destructor. if (Size = 0) and (FileMap is TJclFileMapping) then begin Size := GetFileSize(TJclFileMapping(FileMap).FFileHandle, nil); if Size = DWORD(-1) then begin UnMapViewOfFile(BaseAddress); raise EJclFileMappingViewError.CreateResRec(@RsFailedToObtainSize); end; end; SetPointer(BaseAddress, Size); FFileMapping.FViews.Add(Self); end; //-------------------------------------------------------------------------------------------------- constructor TJclFileMappingView.CreateAt(FileMap: TJclCustomFileMapping; Access, Size: Cardinal; ViewOffset: Int64; Address: Pointer); var BaseAddress: Pointer; OffsetLow, OffsetHigh: Cardinal; begin inherited Create; if FileMap = nil then raise EJclFileMappingViewError.CreateResRec(@RsViewNeedsMapping); FFileMapping := FileMap; // Offset must be a multiple of system memory allocation granularity RoundToAllocGranularity64(ViewOffset, FFileMapping.RoundViewOffset = rvUp); RoundToAllocGranularityPtr(Address, FFileMapping.RoundViewOffset = rvUp); I64ToCardinals(ViewOffset, OffsetLow, OffsetHigh); FOffsetHigh := OffsetHigh; FOffsetLow := OffsetLow; BaseAddress := MapViewOfFileEx(FFileMapping.Handle, Access, FOffsetHigh, FOffsetLow, Size, Address); if BaseAddress = nil then raise EJclFileMappingViewError.CreateResRec(@RsCreateFileMappingView); // If we are mapping a file and size = 0 then MapViewOfFile has mapped the entire file. We must // figure out the size ourselves before we can call SetPointer. Since in case of failure to // retrieve the size we raise an exception, we also have to explicitly unmap the view which // otherwise would have been done by the destructor. if (Size = 0) and (FileMap is TJclFileMapping) then begin Size := GetFileSize(TJclFileMapping(FileMap).FFileHandle, nil); if Size = DWORD(-1) then begin UnMapViewOfFile(BaseAddress); raise EJclFileMappingViewError.CreateResRec(@RsFailedToObtainSize); end; end; SetPointer(BaseAddress, Size); FFileMapping.FViews.Add(Self); end; //-------------------------------------------------------------------------------------------------- destructor TJclFileMappingView.Destroy; var IndexOfSelf: Integer; begin if Memory <> nil then begin UnMapViewOfFile(Memory); SetPointer(nil, 0); end; if FFileMapping <> nil then begin IndexOfSelf := FFileMapping.IndexOf(Self); if IndexOfSelf <> -1 then FFileMapping.FViews.Delete(IndexOfSelf); end; inherited Destroy; end; //-------------------------------------------------------------------------------------------------- function TJclFileMappingView.Flush(const Count: Cardinal): Boolean; begin Result := FlushViewOfFile(Memory, Count); end; //-------------------------------------------------------------------------------------------------- function TJclFileMappingView.GetIndex: Integer; begin Result := FFileMapping.IndexOf(Self); end; //-------------------------------------------------------------------------------------------------- function TJclFileMappingView.GetOffset: Int64; begin CardinalsToI64(Result, FOffsetLow, FOffsetHigh); end; //-------------------------------------------------------------------------------------------------- procedure TJclFileMappingView.LoadFromFile(const FileName: string); var Stream: TFileStream; begin Stream := TFileStream.Create(Filename, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream); finally FreeAndNil(Stream); end; end; //-------------------------------------------------------------------------------------------------- procedure TJclFileMappingView.LoadFromStream(const Stream: TStream); begin if Stream.Size > Size then raise EJclFileMappingViewError.CreateResRec(@RsLoadFromStreamSize); Stream.Position := 0; Stream.ReadBuffer(Memory^, Stream.Size); end; //-------------------------------------------------------------------------------------------------- function TJclFileMappingView.Write(const Buffer; Count: Integer): Longint; begin Result := 0; if (Size - Position) >= Count then begin System.Move(Buffer, Pointer(Longint(Memory) + Position)^, Count); Position := Position + Count; Result := Count; end; end; //================================================================================================== // TJclCustomFileMapping //================================================================================================== function TJclCustomFileMapping.Add(const Access, Count: Cardinal; const Offset: Int64): Integer; var View: TJclFileMappingView; begin // The view adds itself to the FViews list View := TJclFileMappingView.Create(Self, Access, Count, Offset); Result := View.Index; end; //-------------------------------------------------------------------------------------------------- function TJclCustomFileMapping.AddAt(const Access, Count: Cardinal; const Offset: Int64; const Address: Pointer): Integer; var View: TJclFileMappingView; begin // The view adds itself to the FViews list View := TJclFileMappingView.CreateAt(Self, Access, Count, Offset, Address); Result := View.Index; end; //-------------------------------------------------------------------------------------------------- procedure TJclCustomFileMapping.ClearViews; var I: Integer; begin // Note that the view destructor removes the view object from the FViews list so we must loop // downwards from count to 0 for I := FViews.Count - 1 downto 0 do TJclFileMappingView(FViews[I]).Free; end; //-------------------------------------------------------------------------------------------------- constructor TJclCustomFileMapping.Create; begin inherited Create; FViews := TList.Create; FRoundViewOffset := rvDown; end; //-------------------------------------------------------------------------------------------------- constructor TJclCustomFileMapping.Open(const Name: string; const InheritHandle: Boolean; const DesiredAccess: Cardinal); begin Create; InternalOpen(Name, InheritHandle, DesiredAccess); end; //-------------------------------------------------------------------------------------------------- procedure TJclCustomFileMapping.Delete(const Index: Integer); begin // Note that the view destructor removes itself from FViews TJclFileMappingView(FViews[Index]).Free; end; //-------------------------------------------------------------------------------------------------- destructor TJclCustomFileMapping.Destroy; begin ClearViews; if FHandle <> 0 then CloseHandle(FHandle); FreeAndNil(FViews); inherited Destroy; end; //-------------------------------------------------------------------------------------------------- function TJclCustomFileMapping.GetCount: Integer; begin Result := FViews.Count; end; //-------------------------------------------------------------------------------------------------- function TJclCustomFileMapping.GetView(Index: Integer): TJclFileMappingView; begin Result := TJclFileMappingView(FViews.Items[index]); end; //-------------------------------------------------------------------------------------------------- function TJclCustomFileMapping.IndexOf(const View: TJclFileMappingView): Integer; begin Result := FViews.IndexOf(View); end; //-------------------------------------------------------------------------------------------------- procedure TJclCustomFileMapping.InternalCreate(const FileHandle: THandle; const Name: string; const Protect: Cardinal; MaximumSize: Int64; const SecAttr: PSecurityAttributes); var MaximumSizeLow, MaximumSizeHigh: Cardinal; begin FName := Name; I64ToCardinals(MaximumSize, MaximumSizeLow, MaximumSizeHigh); FHandle := CreateFileMapping(FileHandle, SecAttr, Protect, MaximumSizeHigh, MaximumSizeLow, PChar(Name)); if FHandle = 0 then raise EJclFileMappingError.CreateResRec(@RsCreateFileMapping); FExisted := GetLastError = ERROR_ALREADY_EXISTS; end; //-------------------------------------------------------------------------------------------------- procedure TJclCustomFileMapping.InternalOpen(const Name: string; const InheritHandle: Boolean; const DesiredAccess: Cardinal); begin FExisted := True; FName := Name; FHandle := OpenFileMapping(DesiredAccess, InheritHandle, PChar(Name)); if FHandle = 0 then raise EJclFileMappingError.CreateResRec(@RsCreateFileMapping); end; //================================================================================================== // TJclFileMapping //================================================================================================== constructor TJclFileMapping.Create(const FileName: string; FileMode: Cardinal; const Name: string; Protect: Cardinal; const MaximumSize: Int64; const SecAttr: PSecurityAttributes); begin FFileHandle := INVALID_HANDLE_VALUE; inherited Create; FFileHandle := THandle(FileOpen(FileName, FileMode)); if FFileHandle = INVALID_HANDLE_VALUE then raise EJclFileMappingError.CreateResRec(@RsFileMappingOpenFile); InternalCreate(FFileHandle, Name, Protect, MaximumSize, SecAttr); end; //-------------------------------------------------------------------------------------------------- constructor TJclFileMapping.Create(const FileHandle: THandle; const Name: string; Protect: Cardinal; const MaximumSize: Int64; const SecAttr: PSecurityAttributes); begin FFileHandle := INVALID_HANDLE_VALUE; inherited Create; if FileHandle = INVALID_HANDLE_VALUE then raise EJclFileMappingError.CreateResRec(@RsFileMappingInvalidHandle); InternalCreate(FileHandle, Name, Protect, MaximumSize, SecAttr); // Duplicate the handle into FFileHandle as opposed to assigning it directly. This will cause // FFileHandle to retrieve a unique copy which is independent of FileHandle. This makes the // remainder of the class, especially the destructor, easier. The caller will have to close it's // own copy of the handle explicitly. DuplicateHandle(GetCurrentProcess, FileHandle, GetCurrentProcess, @FFileHandle, 0, False, DUPLICATE_SAME_ACCESS); end; //-------------------------------------------------------------------------------------------------- destructor TJclFileMapping.Destroy; begin if FFileHandle <> INVALID_HANDLE_VALUE then CloseHandle(FFileHandle); inherited Destroy; end; //================================================================================================== // TJclSwapFileMapping //================================================================================================== constructor TJclSwapFileMapping.Create(const Name: string; Protect: Cardinal; const MaximumSize: Int64; const SecAttr: PSecurityAttributes); begin inherited Create; InternalCreate(INVALID_HANDLE_VALUE, Name, Protect, MaximumSize, SecAttr); end; //================================================================================================== // TJclFileMappingStream //================================================================================================== procedure TJclFileMappingStream.Close; begin if Memory <> nil then begin UnMapViewOfFile(Memory); SetPointer(nil, 0); end; if FMapping <> 0 then begin CloseHandle(FMapping); FMapping := 0; end; if FFileHandle <> INVALID_HANDLE_VALUE then begin FileClose(FFileHandle); FFileHandle := INVALID_HANDLE_VALUE; end; end; //-------------------------------------------------------------------------------------------------- constructor TJclFileMappingStream.Create(const FileName: string; FileMode: Word); var Protect, Access, Size: DWORD; BaseAddress: Pointer; begin inherited Create; FFileHandle := THandle(FileOpen(FileName, FileMode)); if FFileHandle = INVALID_HANDLE_VALUE then RaiseLastOSError; if (FileMode and $0F) = fmOpenReadWrite then begin Protect := PAGE_WRITECOPY; Access := FILE_MAP_COPY; end else begin Protect := PAGE_READONLY; Access := FILE_MAP_READ; end; FMapping := CreateFileMapping(FFileHandle, nil, Protect, 0, 0, nil); if FMapping = 0 then begin Close; raise EJclFileMappingError.CreateResRec(@RsCreateFileMapping); end; BaseAddress := MapViewOfFile(FMapping, Access, 0, 0, 0); if BaseAddress = nil then begin Close; raise EJclFileMappingViewError.CreateResRec(@RsCreateFileMappingView); end; Size := GetFileSize(FFileHandle, nil); if Size = DWORD(-1) then begin UnMapViewOfFile(BaseAddress); Close; raise EJclFileMappingViewError.CreateResRec(@RsFailedToObtainSize); end; SetPointer(BaseAddress, Size); end; //-------------------------------------------------------------------------------------------------- destructor TJclFileMappingStream.Destroy; begin Close; inherited; end; //-------------------------------------------------------------------------------------------------- function TJclFileMappingStream.Write(const Buffer; Count: Integer): Longint; begin Result := 0; if (Size - Position) >= Count then begin System.Move(Buffer, Pointer(Longint(Memory) + Position)^, Count); Position := Position + Count; Result := Count; end; end; //================================================================================================== // TJclMappedTextReader //================================================================================================== procedure TJclMappedTextReader.AssignTo(Dest: TPersistent); begin if Dest is TStrings then begin GoBegin; while not Eof do TStrings(Dest).Add(ReadLn); end else inherited; end; //-------------------------------------------------------------------------------------------------- constructor TJclMappedTextReader.Create(MemoryStream: TCustomMemoryStream; FreeStream: Boolean); begin FMemoryStream := MemoryStream; FFreeStream := FreeStream; Init; end; //-------------------------------------------------------------------------------------------------- constructor TJclMappedTextReader.Create(const FileName: string); begin FMemoryStream := TJclFileMappingStream.Create(FileName); FFreeStream := True; Init; end; //-------------------------------------------------------------------------------------------------- destructor TJclMappedTextReader.Destroy; begin if FFreeStream then FMemoryStream.Free; inherited; end; //-------------------------------------------------------------------------------------------------- function TJclMappedTextReader.GetEof: Boolean; begin Result := FPosition >= FEnd; end; //-------------------------------------------------------------------------------------------------- function TJclMappedTextReader.GetAsString: string; begin SetString(Result, Content, Size); end; //-------------------------------------------------------------------------------------------------- function TJclMappedTextReader.GetChars(Index: Integer): Char; begin if (Index < 0) or (Index >= Size) then raise EJclError.CreateResRec(@RsFileIndexOutOfRange); Result := Char(PByte(FContent + Index)^); end; //-------------------------------------------------------------------------------------------------- function TJclMappedTextReader.GetLineCount: Integer; {var P: PChar; L: Integer; C: Cardinal; begin if FLineCount = -1 then begin P := FContent; L := 0; while P < FEnd do begin if P^ = AnsiLineFeed then Inc(L); Inc(P); end; Dec(P); if (P >= FContent) and (P^ <> AnsiLineFeed) then Inc(L); FLineCount := L; end; Result := FLineCount; end;} function CountLines(StartPtr: PChar; Len: Integer): Integer; assembler; asm PUSH EDI MOV EDI, EAX MOV ECX, EDX MOV EAX, AnsiLineFeed XOR EDX, EDX @@1: REPNZ SCASB INC EDX OR ECX, ECX JNZ @@1 MOV EAX, EDX POP EDI end; begin if FLineCount = -1 then FLineCount := CountLines(FContent, FSize); Result := FLineCount; end; //-------------------------------------------------------------------------------------------------- function TJclMappedTextReader.GetLines(LineNumber: Integer): string; var P: PChar; begin P := PtrFromLine(LineNumber); Result := StringFromPosition(P); end; //-------------------------------------------------------------------------------------------------- function TJclMappedTextReader.GetPosition: Integer; begin Result := FPosition - FContent; end; //-------------------------------------------------------------------------------------------------- procedure TJclMappedTextReader.GoBegin; begin Position := 0; end; //-------------------------------------------------------------------------------------------------- procedure TJclMappedTextReader.Init; begin FContent := FMemoryStream.Memory; FSize := FMemoryStream.Size; FEnd := FContent + FSize; FPosition := FContent; FLineCount := -1; FLastLineNumber := 0; FLastPosition := FContent; end; //-------------------------------------------------------------------------------------------------- function TJclMappedTextReader.GetPositionFromLine(LineNumber: Integer): Integer; var P: PChar; begin P := PtrFromLine(LineNumber); if P = nil then Result := -1 else Result := P - FContent; end; //-------------------------------------------------------------------------------------------------- function TJclMappedTextReader.PtrFromLine(LineNumber: Integer): PChar; var LineOffset: Integer; begin Result := nil; LineOffset := LineNumber - FLastLineNumber; if (FLineCount <> -1) and (LineNumber > 0) then begin if -LineOffset > LineNumber then begin FLastLineNumber := 0; FLastPosition := FContent; LineOffset := LineNumber; end else if LineOffset > FLineCount - LineNumber then begin FLastLineNumber := FLineCount; FLastPosition := FEnd; LineOffset := LineNumber - FLineCount; end; end; if LineNumber <= 0 then Result := FContent else if LineOffset = 0 then Result := FLastPosition else if LineOffset > 0 then begin Result := FLastPosition; while (Result < FEnd) and (LineOffset > 0) do begin if Result^ = AnsiLineFeed then Dec(LineOffset); Inc(Result); end; end else if LineOffset < 0 then begin Result := FLastPosition; while (Result >= FContent) and (LineOffset < 1) do begin if Result^ = AnsiLineFeed then Inc(LineOffset); Dec(Result); end; Inc(Result, 2); end; FLastLineNumber := LineNumber; FLastPosition := Result; end; //-------------------------------------------------------------------------------------------------- function TJclMappedTextReader.Read: Char; begin if FPosition >= FEnd then Result := #0 else begin Result := FPosition^; Inc(FPosition); end; end; //-------------------------------------------------------------------------------------------------- function TJclMappedTextReader.ReadLn: string; begin Result := StringFromPosition(FPosition); end; //-------------------------------------------------------------------------------------------------- procedure TJclMappedTextReader.SetPosition(const Value: Integer); begin FPosition := FContent + Value; end; //-------------------------------------------------------------------------------------------------- function TJclMappedTextReader.StringFromPosition(var StartPos: PChar): string; var P, StringEnd: PChar; begin if (StartPos = nil) or (StartPos >= FEnd) then Result := '' else begin P := StartPos; while (P < FEnd) and (P^ <> AnsiLineFeed) do Inc(P); if (P > FContent) and ((P - 1)^ = AnsiCarriageReturn) then StringEnd := P - 1 else StringEnd := P; SetString(Result, StartPos, StringEnd - StartPos); StartPos := P + 1; end; end; //================================================================================================== // Path manipulation //================================================================================================== function PathAddSeparator(const Path: string): string; begin Result := Path; if (Length(Path) = 0) or (AnsiLastChar(Path) <> PathSeparator) then Result := Path + PathSeparator; end; //-------------------------------------------------------------------------------------------------- function PathAddExtension(const Path, Extension: string): string; begin Result := Path; if (Path <> '') and (ExtractFileExt(Path) = '') and (Extension <> '') then begin // Note that if we get here Path is quarenteed not to end in a '.' otherwise ExtractFileExt // would have returned '.' therefore there's no need to check it explicitly in the code below if Extension[1] = '.' then Result := Result + Extension else Result := Result + '.' + Extension; end; end; //-------------------------------------------------------------------------------------------------- function PathAppend(const Path, Append: string): string; var PathLength: Integer; B1, B2: Boolean; begin if Append = '' then Result := Path else begin PathLength := Length(Path); if PathLength = 0 then Result := Append else begin // The following code may look a bit complex but al it does is add Append to Path ensuring // that there is one and only one path separator character between them B1 := Path[PathLength] = PathSeparator; B2 := Append[1] = PathSeparator; if B1 and B2 then Result := Copy(Path, 1, PathLength - 1) + Append else begin if not (B1 or B2) then Result := Path + PathSeparator + Append else Result := Path + Append; end; end; end; end; //-------------------------------------------------------------------------------------------------- function PathBuildRoot(const Drive: Byte): string; begin {$IFDEF LINUX} Result := PathSeparator; {$ENDIF LINUX} {$IFDEF MSWINDOWS} // Remember, Win32 only allows 'a' to 'z' as drive letters (mapped to 0..25) if Drive < 26 then Result := Char(Drive + 65) + ':\' else raise EJclPathError.CreateResRecFmt(@RsPathInvalidDrive, [IntToStr(Drive)]); {$ENDIF MSWINDOWS} end; //-------------------------------------------------------------------------------------------------- { todoc Canonicalizes a path. Meaning, it parses the specified path for the character sequences '.' and '..' where '.' means skip over the next path part and '..' means remove the previous path part. For example: c:\users\.\delphi\data => c:\users\delphi\data c:\users\..\delphi\data => c:\brakelm\delphi\data c:\users\.\delphi\.. => c:\users c:\users\.\..\data => c:\data Thus, the '.' and '..' sequences have similar meaning to their counterparts in the filesystem. Path: the path to canonicalize Result: the canonicalized path Author: Jeff Notes: This function does not behave exactly like the one from shlwapi.dll!! Especially 'c:\..' => 'c:' whereas shlwapi returns 'c:\' } function PathCanonicalize(const Path: string): string; var List: TStrings; I: Integer; begin List := TStringList.Create; try StrIToStrings(Path, '\', List, False); I := 0; while I < List.Count do begin if List[I] = '.' then List.Delete(I) else if (List[I] = '..') then begin List.Delete(I); Dec(I); if I > 0 then List.Delete(I); end else Inc(I); end; Result := StringsToStr(List, '\', False); finally List.Free; end; end; //-------------------------------------------------------------------------------------------------- function PathCommonPrefix(const Path1, Path2: string): Integer; var P1, P2: PChar; LastSeparator: Integer; begin Result := 0; if (Path1 <> '') and (Path2 <> '') then begin // Initialize P1 to the shortest of the two paths so that the actual comparison loop below can // use the terminating #0 of that string to terminate the loop. if Length(Path1) <= Length(Path2) then begin P1 := @Path1[1]; P2 := @Path2[1]; end else begin P1 := @Path2[1]; P2 := @Path1[1]; end; LastSeparator := 0; while (P1^ = P2^) and (P1^ <> #0) do begin Inc(Result); if P1^ in [PathSeparator, ':'] then LastSeparator := Result; Inc(P1); Inc(P2); end; if (LastSeparator < Result) and (P1^ <> #0) then Result := LastSeparator; end; end; //-------------------------------------------------------------------------------------------------- function PathCompactPath(const DC: HDC; const Path: string; const Width: Integer; CmpFmt: TCompactPath): string; const Compacts: array [TCompactPath] of Cardinal = (DT_PATH_ELLIPSIS, DT_END_ELLIPSIS); var TextRect: TRect; P: PChar; Fmt: Cardinal; begin Result := ''; if (DC <> 0) and (Path <> '') and (Width > 0) then begin { Here's a note from the Platform SDK to explain the + 5 in the call below: "If dwDTFormat includes DT_MODIFYSTRING, the function could add up to four additional characters to this string. The buffer containing the string should be large enough to accommodate these extra characters." } P := StrAlloc(Length(Path) + 5); try StrPCopy(P, Path); TextRect := Rect(0, 0, Width, 255); Fmt := DT_MODIFYSTRING + DT_CALCRECT + Compacts[CmpFmt]; if DrawTextEx(DC, P, -1, TextRect, Fmt, nil) <> 0 then Result := P; finally StrDispose(P); end; end; end; //-------------------------------------------------------------------------------------------------- function PathCompactPath(const Canvas: TCanvas; const Path: string; const Width: Integer; CmpFmt: TCompactPath): string; overload; begin Result := PathCompactPath(Canvas.Handle, Path, Width, CmpFmt); end; //-------------------------------------------------------------------------------------------------- procedure PathExtractElements(const Source: string; var Drive, Path, FileName, Ext: string); begin Drive := ExtractFileDrive(Source); Path := ExtractFilePath(Source); // Path includes drive so remove that if Drive <> '' then Delete(Path, 1, Length(Drive)); // add/remove separators Drive := PathAddSeparator(Drive); Path := PathRemoveSeparator(Path); if (Path <> '') and (Path[1] = PathSeparator) then Delete(Path, 1, 1); // and extract the remaining elements FileName := PathExtractFileNameNoExt(Source); Ext := ExtractFileExt(Source); end; //-------------------------------------------------------------------------------------------------- function PathExtractFileDirFixed(const S: AnsiString): AnsiString; begin Result := PathAddSeparator(ExtractFileDir(S)); end; //-------------------------------------------------------------------------------------------------- function PathExtractFileNameNoExt(const Path: string): string; begin Result := PathRemoveExtension(ExtractFileName(Path)); end; //-------------------------------------------------------------------------------------------------- { todoc Returns the first Depth path parts of the specified path exclusing drive. Example: PathExtractPathDepth('c:\users\brakelm\data', 2) => 'c:\users\brakelm' Path: the path to extract from Depth: the depth of the path to return (i.e. the number of directory parts). Author: Jeff } function PathExtractPathDepth(const Path: string; Depth: Integer): string; var List: TStrings; LocalPath: string; I: Integer; begin List := TStringList.Create; try if IsDirectory(Path) then LocalPath := Path else LocalPath := ExtractFilePath(Path); StrIToStrings(LocalPath, '\', List, True); I := Depth + 1; if PathIsUNC(LocalPath) then I := I + 2; while (I < List.Count) do List.Delete(I); Result := PathAddSeparator(StringsToStr(List, '\', True)); finally List.Free; end; end; //-------------------------------------------------------------------------------------------------- { todoc Returns the depth of a path. That is the number of subdirectories in the path. Path: the path for which to return the depth Result: depth of the path Author: Jeff Notes: maybe this function should first apply PathCanonicalize() ? } function PathGetDepth(const Path: string): Integer; var List: TStrings; LocalPath: string; I, Start: Integer; begin Result := 0; List := TStringList.Create; try if IsDirectory(Path) then LocalPath := Path else LocalPath := ExtractFilePath(Path); StrIToStrings(LocalPath, '\', List, False); if PathIsUNC(LocalPath) then Start := 1 else Start := 0; for I := Start to List.Count - 1 do begin if (Pos(':', List[I]) = 0) then Inc(Result); end; finally List.Free; end; end; //-------------------------------------------------------------------------------------------------- function PathGetLongName2(Path: string): string; var I : Integer; SearchHandle : THandle; FindData : TWin32FindData; IsBackSlash : Boolean; begin Path := ExpandFileName(Path); Result := ExtractFileDrive(Path); I := Length(Result); if Length(Path) <= I then Exit; // only drive if Path[I + 1] = '\' then begin Result := Result + '\'; Inc(I); end; Delete(Path, 1, I); repeat I := Pos('\', Path); IsBackSlash := I > 0; if Not IsBackSlash then I := Length(Path) + 1; SearchHandle := FindFirstFile(PChar(Result + Copy(Path, 1, I - 1)), FindData); if SearchHandle <> INVALID_HANDLE_VALUE then begin try Result := Result + FindData.cFileName; if IsBackSlash then Result := Result + '\'; finally Windows.FindClose(SearchHandle); end; end else begin Result := Result + Path; Break; end; Delete(Path, 1, I); until Length(Path) = 0; end; //-------------------------------------------------------------------------------------------------- function PathGetLongName(const Path: string): string; var PIDL: PItemIDList; Desktop: IShellFolder; AnsiName: AnsiString; WideName: array [0..MAX_PATH] of WideChar; Eaten, Attr: ULONG; // both unused but API requires them (incorrect translation) begin Result := Path; if Path <> '' then begin if Succeeded(SHGetDesktopFolder(Desktop)) then begin MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, PChar(Path), -1, WideName, MAX_PATH); if Succeeded(Desktop.ParseDisplayName(0, nil, WideName, Eaten, PIDL, Attr)) then try SetLength(AnsiName, MAX_PATH); if SHGetPathFromIDList(PIDL, PChar(AnsiName)) then Result := PChar(AnsiName); finally CoTaskMemFree(PIDL); end; end; end; end; //-------------------------------------------------------------------------------------------------- function PathGetShortName(const Path: string): string; var Required: Integer; begin Result := Path; Required := GetShortPathName(PChar(Path), nil, 0); if Required <> 0 then begin SetLength(Result, Required); Required := GetShortPathName(PChar(Path), PChar(Result), Required); if (Required <> 0) and (Required = Length(Result) - 1) then SetLength(Result, Required) else Result := Path; end; end; //-------------------------------------------------------------------------------------------------- function PathIsAbsolute(const Path: string): Boolean; {$IFDEF MSWINDOWS} var I: Integer; {$ENDIF MSWINDOWS} begin Result := False; if Path <> '' then begin {$IFDEF LINUX} Result := (Path[1] = PathSeparator); {$ENDIF LINUX} {$IFDEF MSWINDOWS} I := 0; if PathIsUnc(Path) then I := Length(PathUncPrefix) else if PathIsDiskDevice(Path) then I := Length(PathDevicePrefix); Result := (Length(Path) > I + 2) and (Path[I + 1] in DriveLetters) and (Path[I + 2] = ':') and (Path[I + 3] = PathSeparator); {$ENDIF MSWINDOWS} end; end; //-------------------------------------------------------------------------------------------------- function PathIsChild(const Path, Base: AnsiString): Boolean; var L: Integer; B, P: string; begin Result := False; B := PathRemoveSeparator(Base); P := PathRemoveSeparator(Path); // an empty path or one that's not longer than base cannot be a subdirectory L := Length(B); if (P = '') or (L >= Length(P)) then Exit; {$IFDEF MSWINDOWS} Result := AnsiSameText(StrLeft(P, L), B) and (P[L+1] = PathSeparator); {$ENDIF MSWINDOWS} {$IFDEF LINUX} Result := AnsiSameStr(StrLeft(P, L), B) and (P[L+1] = PathSeparator); {$ENDIF LINUX} end; //-------------------------------------------------------------------------------------------------- function PathIsDiskDevice(const Path: string): Boolean; begin {$IFDEF LINUX} NotImplemented('PathIsDiskDevice'); {$ENDIF LINUX} {$IFDEF MSWINDOWS} Result := Copy(Path, 1, Length(PathDevicePrefix)) = PathDevicePrefix; {$ENDIF MSWINDOWS} end; //-------------------------------------------------------------------------------------------------- function PathIsUNC(const Path: string): Boolean; {$IFDEF MSWINDOWS} const cUNCSuffix = '?\UNC'; var P: PChar; function AbsorbSeparator: Boolean; begin Result := (P <> nil) and (P^ = '\'); if Result then Inc(P); end; function AbsorbMachineName: Boolean; var NonDigitFound: Boolean; begin // a valid machine name is a string composed of the set [a-z, A-Z, 0-9, -, _] but it may not // consist entirely out of numbers Result := True; NonDigitFound := False; while (P <> nil) and (P^ <> #0) and (P^ <> '\') do begin if P^ in ['a'..'z', 'A'..'Z', '-', '_', '.'] then begin NonDigitFound := True; Inc(P); end else if P^ in ['0'..'9'] then Inc(P) else begin Result := False; Break; end; end; Result := Result and NonDigitFound; end; function AbsorbShareName: Boolean; const InvalidCharacters = ['<','>','?','/',',','*','+','=','[',']','|',':',';','"','''']; begin // a valid share name is a string composed of a set the set !InvalidCharacters note that a // leading '$' is valid (indicates a hidden share) Result := True; while (P <> nil) and (P^ <> #0) and (P^ <> '\') do begin if P^ in InvalidCharacters then begin Result := False; Break; end; Inc(P); end; end; begin Result := Copy(Path, 1, Length(PathUncPrefix)) = PathUncPrefix; if Result then begin if Copy(Path, 1, Length(PathUncPrefix + cUNCSuffix)) = PathUncPrefix + cUNCSuffix then P := @Path[Length(PathUncPrefix + cUNCSuffix)] else begin P := @Path[Length(PathUncPrefix)]; Result := AbsorbSeparator and AbsorbMachineName; end; Result := Result and AbsorbSeparator; if Result then begin Result := AbsorbShareName; // remaining, if anything, is path and or filename (optional) check those? end; end; end; {$ENDIF MSWINDOWS} {$IFDEF LINUX} begin Result := False; end; {$ENDIF LINUX} //-------------------------------------------------------------------------------------------------- function PathRemoveSeparator(const Path: string): string; var L: Integer; begin L := Length(Path); if (L <> 0) and (AnsiLastChar(Path) = PathSeparator) then Result := Copy(Path, 1, L - 1) else Result := Path; end; //-------------------------------------------------------------------------------------------------- function PathRemoveExtension(const Path: string): string; var I: Integer; begin I := LastDelimiter(':.' + PathSeparator, Path); if (I > 0) and (Path[I] = '.') then Result := Copy(Path, 1, I - 1) else Result := Path; end; //================================================================================================== // Files and Directories //================================================================================================== function BuildFileList(const Path: string; const Attr: Integer; const List: TStrings): Boolean; var SearchRec: TSearchRec; R: Integer; begin Assert(List <> nil); R := FindFirst(Path, Attr, SearchRec); Result := R = 0; try if Result then begin while R = 0 do begin if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then List.Add(SearchRec.Name); R := FindNext(SearchRec); end; Result := R = ERROR_NO_MORE_FILES; end; finally SysUtils.FindClose(SearchRec); end; end; //-------------------------------------------------------------------------------------------------- function CloseVolume(var Volume: THandle): Boolean; begin Result := False; if Volume <> INVALID_HANDLE_VALUE then begin Result := CloseHandle(Volume); if Result then Volume := INVALID_HANDLE_VALUE; end; end; //-------------------------------------------------------------------------------------------------- procedure CreateEmptyFile(const FileName: string); var Handle: THandle; begin Handle := CreateFile(PChar(FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, 0, 0); if Handle <> INVALID_HANDLE_VALUE then CloseHandle(Handle) else RaiseLastOSError; end; //-------------------------------------------------------------------------------------------------- // todoc author Jeff function DeleteDirectory(const DirectoryName: string; MoveToRecycleBin: Boolean): Boolean; begin if MoveToRecycleBin then Result := SHDeleteFolder(0, DirectoryName, [doSilent, doAllowUndo]) else Result := DelTree(DirectoryName); end; //-------------------------------------------------------------------------------------------------- function DelTree(const Path: string): Boolean; begin Result := DelTreeEx(Path, False, nil); end; //-------------------------------------------------------------------------------------------------- function DelTreeEx(const Path: string; AbortOnFailure: Boolean; Progress: TDelTreeProgress): Boolean; var Files: TStringList; LPath: string; // writable copy of Path FileName: string; I: Integer; PartialResult: Boolean; Attr: DWORD; begin Result := True; Files := TStringList.Create; try LPath := PathRemoveSeparator(Path); BuildFileList(LPath + '\*.*', faAnyFile, Files); for I := 0 to Files.Count - 1 do begin FileName := LPath + '\' + Files[I]; PartialResult := True; // If the current file is itself a directory then recursively delete it Attr := GetFileAttributes(PChar(FileName)); if (Attr <> DWORD(-1)) and ((Attr and FILE_ATTRIBUTE_DIRECTORY) <> 0) then PartialResult := DelTreeEx(FileName, AbortOnFailure, Progress) else begin if Assigned(Progress) then PartialResult := Progress(FileName, Attr); if PartialResult then begin // Set attributes to normal in case it's a readonly file PartialResult := SetFileAttributes(PChar(FileName), FILE_ATTRIBUTE_NORMAL); if PartialResult then PartialResult := DeleteFile(FileName); end; end; if not PartialResult then begin Result := False; if AbortOnFailure then Break; end; end; finally FreeAndNil(Files); end; if Result then begin // Finally remove the directory itself Result := SetFileAttributes(PChar(LPath), FILE_ATTRIBUTE_NORMAL); if Result then begin {$IOCHECKS OFF} RmDir(LPath); {$IFDEF IOCHECKS_ON} {$IOCHECKS ON} {$ENDIF IOCHECKS_ON} Result := IOResult = 0; end; end; end; //-------------------------------------------------------------------------------------------------- function DirectoryExists(const Name: string): Boolean; var R: DWORD; begin R := GetFileAttributes(PChar(Name)); Result := (R <> DWORD(-1)) and ((R and FILE_ATTRIBUTE_DIRECTORY) <> 0); end; //-------------------------------------------------------------------------------------------------- {$IFDEF MSWINDOWS} function DiskInDrive(Drive: Char): Boolean; var ErrorMode: Cardinal; begin Result := False; if Drive in ['a'..'z'] then Dec(Drive, $20); Assert(Drive in ['A'..'Z']); if Drive in ['A'..'Z'] then begin { try to access the drive, it doesn't really matter how we access the drive and as such calling DiskSize is more or less a random choice. The call to SetErrorMode supresses the system provided error dialog if there is no disk in the drive and causes the to DiskSize to fail. } ErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); try Result := DiskSize(Ord(Drive) - $40) <> -1; finally SetErrorMode(ErrorMode); end; end; end; {$ENDIF MSWINDOWS} //-------------------------------------------------------------------------------------------------- function FileCreateTemp(var Prefix: string): THandle; var TempName: string; begin Result := INVALID_HANDLE_VALUE; TempName := FileGetTempName(Prefix); if TempName <> '' then begin Result := CreateFile(PChar(TempName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_DELETE_ON_CLOSE, 0); // In certain situations it's possible that CreateFile fails yet the file is actually created, // therefore explicitly delete it upon failure. if Result = INVALID_HANDLE_VALUE then DeleteFile(TempName); Prefix := TempName; end; end; //-------------------------------------------------------------------------------------------------- function FileExists(const FileName: string): Boolean; begin // Attempt to access the file, doesn't matter how, using FileGetSize is as good as anything else. Result := FileGetSize(FileName) <> -1; end; //-------------------------------------------------------------------------------------------------- { todoc returns a filename that can be used for backup purposes. this is similar to how delphi uses backup's: it simply prepends a tilde (~) to the extension. filename: the filename for which to return a backup filename result: the filename used for backup purposes author: Jeff } function GetBackupFileName(const FileName: string): string; var NewExt: string; begin NewExt := ExtractFileExt(FileName); if Length(NewExt) > 0 then begin NewExt[1] := '~'; NewExt := '.' + NewExt end; Result := ChangeFileExt(FileName, NewExt); end; //-------------------------------------------------------------------------------------------------- function FileGetDisplayName(const FileName: string): string; var FileInfo: TSHFileInfo; begin FillChar(FileInfo, SizeOf(FileInfo), #0); if SHGetFileInfo(PChar(FileName), 0, FileInfo, SizeOf(FileInfo), SHGFI_DISPLAYNAME) <> 0 then Result := FileInfo.szDisplayName else Result := FileName; end; //-------------------------------------------------------------------------------------------------- function FileGetSize(const FileName: string): Integer; var SearchRec: TSearchRec; OldMode: Cardinal; begin Result := -1; OldMode := SetErrorMode(SEM_FAILCRITICALERRORS); try if FindFirst(FileName, faAnyFile, SearchRec) = 0 then begin Result := SearchRec.Size; SysUtils.FindClose(SearchRec); end; finally SetErrorMode(OldMode); end; end; //-------------------------------------------------------------------------------------------------- function FileGetTempName(const Prefix: string): string; var TempPath, TempFile: string; R: Cardinal; begin Result := ''; R := GetTempPath(0, nil); SetLength(TempPath, R); R := GetTempPath(R, PChar(TempPath)); if R <> 0 then begin SetLength(TempPath, StrLen(PChar(TempPath))); SetLength(TempFile, MAX_PATH); R := GetTempFileName(PChar(TempPath), PChar(Prefix), 0, PChar(TempFile)); if R <> 0 then begin SetLength(TempFile, StrLen(PChar(TempFile))); Result := TempFile; end; end; end; //-------------------------------------------------------------------------------------------------- function FileGetTypeName(const FileName: string): string; var FileInfo: TSHFileInfo; RetVal: DWORD; begin FillChar(FileInfo, SizeOf(FileInfo), #0); RetVal := SHGetFileInfo(PChar(FileNAme), 0, FileInfo, SizeOf(FileInfo), SHGFI_TYPENAME or SHGFI_USEFILEATTRIBUTES); if RetVal <> 0 then Result := FileInfo.szTypeName; if (RetVal = 0) or (Trim(Result) = '') then begin // Lookup failed so mimic explorer behaviour by returning "XYZ File" Result := ExtractFileExt(FileName); Delete(Result, 1, 1); Result := TrimLeft(UpperCase(Result) + RsDefaultFileTypeName); end; end; //-------------------------------------------------------------------------------------------------- function FindUnusedFileName(const FileName, FileExt, Suffix: AnsiString): AnsiString; var I: Integer; begin Result := FileName + '.' + FileExt; I := 0; while FileExists(Result) do begin Inc(I); Result := FileName + Suffix + IntToStr(I) + '.' + FileExt; end; end; //-------------------------------------------------------------------------------------------------- // This routine is copied from FileCtrl.pas to avoid dependency on that unit. // See the remark at the top of this section function ForceDirectories(Name: string): Boolean; begin Result := True; if Length(Name) = 0 then raise EJclFileUtilsError.CreateResRec(@RsCannotCreateDir); Name := PathRemoveSeparator(Name); if (Length(Name) < 3) or DirectoryExists(Name) or (ExtractFilePath(Name) = Name) then Exit; Result := ForceDirectories(ExtractFilePath(Name)) and CreateDir(Name); end; //-------------------------------------------------------------------------------------------------- function GetDirectorySize(const Path: string): Int64; function RecurseFolder(const Path: string): Int64; var F: TSearchRec; R: Integer; begin Result := 0; R := SysUtils.FindFirst(Path + '*.*', faAnyFile, F); if R = 0 then try while R = 0 do begin if (F.Name <> '.') and (F.Name <> '..') then begin if (F.Attr and faDirectory) = faDirectory then Inc(Result, RecurseFolder(Path + F.Name + '\')) else Result := Result + (F.FindData.nFileSizeHigh shl 32) + F.FindData.nFileSizeLow; end; R := SysUtils.FindNext(F); end; if R <> ERROR_NO_MORE_FILES then Abort; finally SysUtils.FindClose(F); end; end; begin if not DirectoryExists(PathRemoveSeparator(Path)) then Result := -1 else try Result := RecurseFolder(PathAddSeparator(Path)) except Result := -1; end; end; //-------------------------------------------------------------------------------------------------- function GetDriveTypeStr(const Drive: Char): string; var DriveType: Integer; DriveStr: string; begin if not (Drive in ['a'..'z', 'A'..'Z']) then raise EJclPathError.CreateResRecFmt(@RsPathInvalidDrive, [Drive]); DriveStr := Drive + ':\'; DriveType := GetDriveType(PChar(DriveStr)); case DriveType of DRIVE_REMOVABLE: Result := RsRemovableDrive; DRIVE_FIXED: Result := RsHardDisk; DRIVE_REMOTE: Result := RsRemoteDrive; DRIVE_CDROM: Result := RsCDRomDrive; DRIVE_RAMDISK: Result := RsRamDisk; else Result := RsUnknownDrive; end; end; //-------------------------------------------------------------------------------------------------- function GetFileAgeCoherence(const FileName: string): Boolean; var Handle: THandle; FindData: TWin32FindData; begin Result := False; Handle := FindFirstFile(PChar(FileName), FindData); if Handle <> INVALID_HANDLE_VALUE then begin Windows.FindClose(Handle); Result := CompareFileTime(FindData.ftCreationTime, FindData.ftLastWriteTime) <= 0; end; end; //-------------------------------------------------------------------------------------------------- procedure GetFileAttributeList(const Items: TStrings; const Attr: Integer); begin Assert(Items <> nil); if Attr and faDirectory = faDirectory then Items.Add(RsAttrDirectory); if Attr and faReadOnly = faReadOnly then Items.Add(RsAttrReadOnly); if Attr and faSysFile = faSysFile then Items.Add(RsAttrSystemFile); if Attr and faVolumeID = faVolumeID then Items.Add(RsAttrVolumeID); if Attr and faArchive = faArchive then Items.Add(RsAttrArchive); if Attr and faAnyFile = faAnyFile then Items.Add(RsAttrAnyFile); if Attr and faHidden = faHidden then Items.Add(RsAttrHidden); end; //-------------------------------------------------------------------------------------------------- procedure GetFileAttributeListEx(const Items: TStrings; const Attr: Integer); begin Assert(Items <> nil); if Attr and FILE_ATTRIBUTE_READONLY = FILE_ATTRIBUTE_READONLY then Items.Add(RsAttrReadOnly); if Attr and FILE_ATTRIBUTE_HIDDEN = FILE_ATTRIBUTE_HIDDEN then Items.Add(RsAttrHidden); if Attr and FILE_ATTRIBUTE_SYSTEM = FILE_ATTRIBUTE_SYSTEM then Items.Add(RsAttrSystemFile); if Attr and FILE_ATTRIBUTE_DIRECTORY = FILE_ATTRIBUTE_DIRECTORY then Items.Add(RsAttrDirectory); if Attr and FILE_ATTRIBUTE_ARCHIVE = FILE_ATTRIBUTE_ARCHIVE then Items.Add(RsAttrArchive); if Attr and FILE_ATTRIBUTE_NORMAL = FILE_ATTRIBUTE_NORMAL then Items.Add(RsAttrNormal); if Attr and FILE_ATTRIBUTE_TEMPORARY = FILE_ATTRIBUTE_TEMPORARY then Items.Add(RsAttrTemporary); if Attr and FILE_ATTRIBUTE_COMPRESSED = FILE_ATTRIBUTE_COMPRESSED then Items.Add(RsAttrCompressed); if Attr and FILE_ATTRIBUTE_OFFLINE = FILE_ATTRIBUTE_OFFLINE then Items.Add(RsAttrOffline); if Attr and FILE_ATTRIBUTE_ENCRYPTED = FILE_ATTRIBUTE_ENCRYPTED then Items.Add(RsAttrEncrypted); if Attr and FILE_ATTRIBUTE_REPARSE_POINT = FILE_ATTRIBUTE_REPARSE_POINT then Items.Add(RsAttrReparsePoint); if Attr and FILE_ATTRIBUTE_SPARSE_FILE = FILE_ATTRIBUTE_SPARSE_FILE then Items.Add(RsAttrSparseFile); end; //-------------------------------------------------------------------------------------------------- function GetFileInformation(const FileName: string): TSearchRec; begin if FindFirst(FileName, faAnyFile, Result) = 0 then SysUtils.FindClose(Result) else RaiseLastOSError; end; //-------------------------------------------------------------------------------------------------- function GetFileLastWrite(const FileName: string): TFileTime; begin Result := GetFileInformation(FileName).FindData.ftLastWriteTime; end; //-------------------------------------------------------------------------------------------------- function GetFileLastAccess(const FileName: string): TFileTime; begin Result := GetFileInformation(FileName).FindData.ftLastAccessTime; end; //-------------------------------------------------------------------------------------------------- function GetFileCreation(const FileName: string): TFileTime; begin Result := GetFileInformation(FileName).FindData.ftCreationTime; end; //-------------------------------------------------------------------------------------------------- function GetModulePath(const Module: HMODULE): string; var L: Integer; begin L := MAX_PATH + 1; SetLength(Result, L); L := Windows.GetModuleFileName(Module, Pointer(Result), L); SetLength(Result, L); end; //-------------------------------------------------------------------------------------------------- function GetSizeOfFile(const FileName: string): Int64; var Handle: THandle; FindData: TWin32FindData; begin Result := 0; Handle := FindFirstFile(PChar(FileName), FindData); if Handle <> INVALID_HANDLE_VALUE then begin Windows.FindClose(Handle); Result := (FindData.nFileSizeHigh shl 32) + FindData.nFileSizeLow; end else RaiseLastOSError; end; //-------------------------------------------------------------------------------------------------- function GetSizeOfFile(Handle: THandle): Int64; var Size: TULargeInteger; begin Size.LowPart := GetFileSize(Handle, @Size.HighPart); Result := Size.QuadPart; end; //-------------------------------------------------------------------------------------------------- function GetStandardFileInfo(const FileName: string): TWin32FileAttributeData; var Handle: THandle; FileInfo: TByHandleFileInformation; begin Assert(FileName <> ''); if IsWin95 or IsWin95OSR2 or IsWinNT3 then begin Handle := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0); if Handle <> INVALID_HANDLE_VALUE then try if not GetFileInformationByHandle(Handle, FileInfo) then raise EJclFileUtilsError.CreateResRecFmt(@RsFileUtilsAttrUnavailable, [FileName]); Result.dwFileAttributes := FileInfo.dwFileAttributes; Result.ftCreationTime := FileInfo.ftCreationTime; Result.ftLastAccessTime := FileInfo.ftLastAccessTime; Result.ftLastWriteTime := FileInfo.ftLastWriteTime; Result.nFileSizeHigh := FileInfo.nFileSizeHigh; Result.nFileSizeLow := FileInfo.nFileSizeLow; finally CloseHandle(Handle); end else raise EJclFileUtilsError.CreateResRecFmt(@RsFileUtilsAttrUnavailable, [FileName]); end else begin if not GetFileAttributesEx(PChar(FileName), GetFileExInfoStandard, @Result) then raise EJclFileUtilsError.CreateResRecFmt(@RsFileUtilsAttrUnavailable, [FileName]); end; end; //-------------------------------------------------------------------------------------------------- function IsDirectory(const FileName: string): Boolean; var R: DWORD; begin R := GetFileAttributes(PChar(FileName)); Result := (R <> DWORD(-1)) and ((R and FILE_ATTRIBUTE_DIRECTORY) <> 0); end; //-------------------------------------------------------------------------------------------------- function LockVolume(const Volume: string; var Handle: THandle): Boolean; var BytesReturned: DWORD; begin Result := False; Handle := CreateFile(PChar('\\.\' + Volume), GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, 0); if Handle <> INVALID_HANDLE_VALUE then begin Result := DeviceIoControl(Handle, FSCTL_LOCK_VOLUME, nil, 0, nil, 0, BytesReturned, nil); if not Result then begin CloseHandle(Handle); Handle := INVALID_HANDLE_VALUE; end; end; end; //-------------------------------------------------------------------------------------------------- function OpenVolume(const Drive: Char): THandle; var VolumeName: array [0..6] of Char; begin VolumeName := '\\.\A:'; VolumeName[4] := Drive; Result := CreateFile(VolumeName, GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0); end; //-------------------------------------------------------------------------------------------------- type // indicates the file time to set, used by SetFileTimesHelper and SetDirTimesHelper TFileTimes = (ftLastAccess, ftLastWrite, ftCreation); function SetFileTimesHelper(const FileName: string; const DateTime: TDateTime; Times: TFileTimes): Boolean; var Handle: THandle; FileTime: TFileTime; SystemTime: TSystemTime; begin Result := False; Handle := CreateFile(PChar(FileName), GENERIC_WRITE, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0); if Handle <> INVALID_HANDLE_VALUE then try //SysUtils.DateTimeToSystemTime(DateTimeToLocalDateTime(DateTime), SystemTime); SysUtils.DateTimeToSystemTime(DateTime, SystemTime); if Windows.SystemTimeToFileTime(SystemTime, FileTime) then begin case Times of ftLastAccess: Result := SetFileTime(Handle, nil, @FileTime, nil); ftLastWrite: Result := SetFileTime(Handle, nil, nil, @FileTime); ftCreation: Result := SetFileTime(Handle, @FileTime, nil, nil); end; end; finally CloseHandle(Handle); end; end; //-------------------------------------------------------------------------------------------------- function SetFileLastAccess(const FileName: string; const DateTime: TDateTime): Boolean; begin Result := SetFileTimesHelper(FileName, DateTime, ftLastAccess); end; //-------------------------------------------------------------------------------------------------- function SetFileLastWrite(const FileName: string; const DateTime: TDateTime): Boolean; begin Result := SetFileTimesHelper(FileName, DateTime, ftLastWrite); end; //-------------------------------------------------------------------------------------------------- function SetFileCreation(const FileName: string; const DateTime: TDateTime): Boolean; begin Result := SetFileTimesHelper(FileName, DateTime, ftCreation); end; //-------------------------------------------------------------------------------------------------- // utility function for SetDirTimesHelper function BackupPrivilegesEnabled: Boolean; begin Result := IsPrivilegeEnabled(SE_BACKUP_NAME) and IsPrivilegeEnabled(SE_RESTORE_NAME); end; //-------------------------------------------------------------------------------------------------- function SetDirTimesHelper(const DirName: string; const DateTime: TDateTime; Times: TFileTimes): Boolean; var Handle: THandle; FileTime: TFileTime; SystemTime: TSystemTime; begin Result := False; if IsDirectory(DirName) and BackupPrivilegesEnabled then begin Handle := CreateFile(PChar(DirName), GENERIC_WRITE, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0); if Handle <> INVALID_HANDLE_VALUE then try SysUtils.DateTimeToSystemTime(DateTime, SystemTime); Windows.SystemTimeToFileTime(SystemTime, FileTime); case Times of ftLastAccess: Result := SetFileTime(Handle, nil, @FileTime, nil); ftLastWrite: Result := SetFileTime(Handle, nil, nil, @FileTime); ftCreation: Result := SetFileTime(Handle, @FileTime, nil, nil); end; finally CloseHandle(Handle); end; end; end; //-------------------------------------------------------------------------------------------------- function SetDirLastWrite(const DirName: string; const DateTime: TDateTime): Boolean; begin Result := SetDirTimesHelper(DirName, DateTime, ftLastWrite); end; //-------------------------------------------------------------------------------------------------- function SetDirLastAccess(const DirName: string; const DateTime: TDateTime): Boolean; begin Result := SetDirTimesHelper(DirName, DateTime, ftLastAccess); end; //-------------------------------------------------------------------------------------------------- function SetDirCreation(const DirName: string; const DateTime: TDateTime): Boolean; begin Result := SetDirTimesHelper(DirName, DateTime, ftCreation); end; //-------------------------------------------------------------------------------------------------- procedure ShredFile(const FileName: string; Times: Integer); const BUFSIZE = 4096; ODD_FILL = $C1; EVEN_FILL = $3E; var Fs: TFileStream; Size: Integer; N: Integer; ContentPtr: Pointer; begin Size := FileGetSize(FileName); if Size > 0 then begin if Times < 0 then Times := 2 else Times := Times * 2; ContentPtr := nil; Fs := TFileStream.Create(FileName, fmOpenReadWrite); try GetMem(ContentPtr, BUFSIZE); while Times > 0 do begin if Times mod 2 = 0 then FillMemory(ContentPtr, BUFSIZE, EVEN_FILL) else FillMemory(ContentPtr, BUFSIZE, ODD_FILL); Fs.Seek(0, soFromBeginning); N := Size div BUFSIZE; while N > 0 do begin Fs.Write(ContentPtr^, BUFSIZE); Dec(N); end; N := Size mod BUFSIZE; if N > 0 then Fs.Write(ContentPtr^, N); FlushFileBuffers(Fs.Handle); Dec(Times); end; finally if ContentPtr <> nil then FreeMem(ContentPtr, Size); Fs.Free; DeleteFile(FileName); end; end else DeleteFile(FileName); end; //-------------------------------------------------------------------------------------------------- function UnlockVolume(var Handle: THandle): Boolean; var BytesReturned: DWORD; begin Result := False; if Handle <> INVALID_HANDLE_VALUE then begin Result := DeviceIoControl(Handle, FSCTL_UNLOCK_VOLUME, nil, 0, nil, 0, BytesReturned, nil); if Result then begin CloseHandle(Handle); Handle := INVALID_HANDLE_VALUE; end; end; end; //-------------------------------------------------------------------------------------------------- // todoc Author: Jeff function Win32DeleteFile(const FileName: string; MoveToRecycleBin: Boolean): Boolean; begin if MoveToRecycleBin then Result := SHDeleteFiles(0, FileName, [doSilent, doAllowUndo, doFilesOnly]) else Result := Windows.DeleteFile(PChar(FileName)); end; //-------------------------------------------------------------------------------------------------- // todoc Author: Jeff function Win32BackupFile(const FileName: string; Move: Boolean): Boolean; begin if Move then Result := MoveFile(PChar(FileName), PChar(GetBackupFileName(FileName))) else Result := CopyFile(PChar(FileName), PChar(GetBackupFileName(FileName)), False) end; //-------------------------------------------------------------------------------------------------- // todoc Author: Jeff function Win32RestoreFile(const FileName: string): Boolean; var TempFileName: string; begin Result := False; TempFileName := FileGetTempName(''); if MoveFile(PChar(GetBackupFileName(FileName)), PChar(TempFileName)) then if Win32BackupFile(FileName, False) then Result := MoveFile(PChar(TempFileName), PChar(FileName)); end; //================================================================================================== // File Version info routines //================================================================================================== const VerKeyNames: array [1..12] of string[17] = ('Comments', 'CompanyName', 'FileDescription', 'FileVersion', 'InternalName', 'LegalCopyright', 'LegalTradeMarks', 'OriginalFilename', 'ProductName', 'ProductVersion', 'SpecialBuild', 'PrivateBuild'); //-------------------------------------------------------------------------------------------------- function OSIdentToString(const OSIdent: DWORD): string; begin case OSIdent of VOS_UNKNOWN: Result := RsVosUnknown; VOS_DOS: Result := RsVosDos; VOS_OS216: Result := RsVosOS216; VOS_OS232: Result := RsVosOS232; VOS_NT: Result := RsVosNT; VOS__WINDOWS16: Result := RsVosWindows16; VOS__PM16: Result := RsVosPM16; VOS__PM32: Result := RsVosPM32; VOS__WINDOWS32: Result := RsVosWindows32; VOS_DOS_WINDOWS16: Result := RsVosDosWindows16; VOS_DOS_WINDOWS32: Result := RsVosDosWindows32; VOS_OS216_PM16: Result := RsVosOS216PM16; VOS_OS232_PM32: Result := RsVosOS232PM32; VOS_NT_WINDOWS32: Result := RsVosNTWindows32; else Result := RsVosUnknown; end; if Result <> RsVosUnknown then Result := RsVosDesignedFor + Result; end; //-------------------------------------------------------------------------------------------------- function OSFileTypeToString(const OSFileType: DWORD; const OSFileSubType: DWORD): string; begin case OSFileType of VFT_UNKNOWN: Result := RsVftUnknown; VFT_APP: Result := RsVftApp; VFT_DLL: Result := RsVftDll; VFT_DRV: begin case OSFileSubType of VFT2_DRV_PRINTER: Result := RsVft2DrvPRINTER; VFT2_DRV_KEYBOARD: Result := RsVft2DrvKEYBOARD; VFT2_DRV_LANGUAGE: Result := RsVft2DrvLANGUAGE; VFT2_DRV_DISPLAY: Result := RsVft2DrvDISPLAY; VFT2_DRV_MOUSE: Result := RsVft2DrvMOUSE; VFT2_DRV_NETWORK: Result := RsVft2DrvNETWORK; VFT2_DRV_SYSTEM: Result := RsVft2DrvSYSTEM; VFT2_DRV_INSTALLABLE: Result := RsVft2DrvINSTALLABLE; VFT2_DRV_SOUND: Result := RsVft2DrvSOUND; VFT2_DRV_COMM: Result := RsVft2DrvCOMM; else Result := ''; end; Result := Result + ' ' + RsVftDrv; end; VFT_FONT: begin case OSFileSubType of VFT2_FONT_RASTER: Result := RsVft2FontRASTER; VFT2_FONT_VECTOR: Result := RsVft2FontVECTOR; VFT2_FONT_TRUETYPE: Result := RsVft2FontTRUETYPE; else Result := ''; end; Result := Result + ' ' + RsVftFont; end; VFT_VXD: Result := RsVftVxd; VFT_STATIC_LIB: Result := RsVftStaticLib; else Result := ''; end; Result := TrimLeft(Result); end; //-------------------------------------------------------------------------------------------------- function VersionResourceAvailable(const FileName: string): Boolean; var Size: DWORD; Handle: THandle; Buffer: string; begin Result := False; Size := GetFileVersionInfoSize(PChar(FileName), Handle); if Size > 0 then begin SetLength(Buffer, Size); Result := GetFileVersionInfo(PChar(FileName), Handle, Size, PChar(Buffer)); end; end; //-------------------------------------------------------------------------------------------------- function VersionFixedFileInfo(const FileName: string; var FixedInfo: TVSFixedFileInfo): Boolean; var Size, FixInfoLen: DWORD; Handle: THandle; Buffer: string; FixInfoBuf: PVSFixedFileInfo; begin Result := False; Size := GetFileVersionInfoSize(PChar(FileName), Handle); if Size > 0 then begin SetLength(Buffer, Size); if GetFileVersionInfo(PChar(FileName), Handle, Size, Pointer(Buffer)) and VerQueryValue(Pointer(Buffer), '\', Pointer(FixInfoBuf), FixInfoLen) and (FixInfoLen = SizeOf(TVSFixedFileInfo)) then begin Result := True; FixedInfo := FixInfoBuf^; end; end; end; //-------------------------------------------------------------------------------------------------- function FormatVersionString(const HiV, LoV: Word): string; begin Result := Format('%u.%.2u', [HiV, LoV]); end; //-------------------------------------------------------------------------------------------------- function FormatVersionString(const Major, Minor, Build, Revision: Word): string; begin Result := Format('%u.%u.%u.%u', [Major, Minor, Build, Revision]); end; //================================================================================================== // TJclFileVersionInfo //================================================================================================== constructor TJclFileVersionInfo.Attach(VersionInfoData: Pointer; Size: Integer); begin SetString(FBuffer, PChar(VersionInfoData), Size); ExtractData; end; //-------------------------------------------------------------------------------------------------- procedure TJclFileVersionInfo.CheckLanguageIndex(Value: Integer); begin if (Value < 0) or (Value >= LanguageCount) then raise EJclFileVersionInfoError.CreateResRec(@RsFileUtilsLanguageIndex); end; //-------------------------------------------------------------------------------------------------- constructor TJclFileVersionInfo.Create(const FileName: string); var Handle: THandle; Size: DWORD; begin Size := GetFileVersionInfoSize(PChar(FileName), Handle); if Size = 0 then raise EJclFileVersionInfoError.CreateResRec(@RsFileUtilsNoVersionInfo); SetLength(FBuffer, Size); Win32Check(GetFileVersionInfo(PChar(FileName), Handle, Size, PChar(FBuffer))); ExtractData; end; //-------------------------------------------------------------------------------------------------- procedure TJclFileVersionInfo.CreateItemsForLanguage; var I: Integer; begin FItems.Clear; for I := 0 to FItemList.Count - 1 do if Integer(FItemList.Objects[I]) = FLanguageIndex then FItems.AddObject(FItemList[I], Pointer(FLanguages[FLanguageIndex].Pair)); end; //-------------------------------------------------------------------------------------------------- destructor TJclFileVersionInfo.Destroy; begin FreeAndNil(FItemList); FreeAndNil(FItems); inherited; end; //-------------------------------------------------------------------------------------------------- procedure TJclFileVersionInfo.ExtractData; var Data, EndOfData: PChar; Len, ValueLen, DataType: Word; HeaderSize: Integer; Key: string; Error, IsUnicode: Boolean; procedure Padding(var DataPtr: PChar); begin while DWORD(DataPtr) and 3 <> 0 do Inc(DataPtr); end; procedure GetHeader; var P: PChar; TempKey: PWideChar; begin P := Data; Len := PWord(P)^; if Len = 0 then begin Error := True; Exit; end; Inc(P, SizeOf(Word)); ValueLen := PWord(P)^; Inc(P, SizeOf(Word)); if IsUnicode then begin DataType := PWord(P)^; Inc(P, SizeOf(Word)); TempKey := PWideChar(P); Inc(P, (lstrlenW(TempKey) + 1) * SizeOf(WideChar)); // length + #0#0 Key := TempKey; end else begin DataType := 1; Key := PAnsiChar(P); Inc(P, lstrlenA(P) + 1); end; Padding(P); HeaderSize := P - Data; Data := P; end; procedure FixKeyValue; const HexNumberCPrefix = '0x'; var I: Integer; begin // GAPI32.DLL version 5.5.2803.1 contanins '04050x04E2' value repeat I := Pos(HexNumberCPrefix, Key); if I > 0 then Delete(Key, I, Length(HexNumberCPrefix)); until I = 0; I := 1; while I <= Length(Key) do if Key[I] in AnsiHexDigits then Inc(I) else Delete(Key, I, 1); end; procedure ProcessStringInfo(Size: Integer); var EndPtr, EndStringPtr: PChar; LangIndex: Integer; LangIdRec: TLangIdRec; Value: string; begin EndPtr := Data + Size; LangIndex := 0; while not Error and (Data < EndPtr) do begin GetHeader; // StringTable FixKeyValue; if (ValueLen <> 0) or (Length(Key) <> 8) then begin Error := True; Break; end; Padding(Data); LangIdRec.LangId := StrToIntDef('$' + Copy(Key, 1, 4), 0); LangIdRec.CodePage := StrToIntDef('$' + Copy(Key, 5, 4), 0); SetLength(FLanguages, LangIndex + 1); FLanguages[LangIndex] := LangIdRec; EndStringPtr := Data + Len - HeaderSize; while not Error and (Data < EndStringPtr) do begin GetHeader; // String case DataType of 0: if ValueLen in [1..4] then Value := Format('$%.*x', [ValueLen * 2, PInteger(Data)^]) else Value := ''; 1: if ValueLen = 0 then Value := '' else if IsUnicode then begin Value := WideCharLenToString(PWideChar(Data), ValueLen); StrResetLength(Value); end else Value := PAnsiChar(Data); else Error := True; Break; end; Inc(Data, Len - HeaderSize); Padding(Data); // String.Padding FItemList.AddObject(Format('%s=%s', [Key, Value]), Pointer(LangIndex)); end; Inc(LangIndex); end; end; procedure ProcessVarInfo(Size: Integer); var TranslationIndex: Integer; begin GetHeader; // Var if Key = 'Translation' then begin SetLength(FTranslations, ValueLen div SizeOf(TLangIdRec)); for TranslationIndex := 0 to Length(FTranslations) - 1 do begin FTranslations[TranslationIndex] := PLangIdRec(Data)^; Inc(Data, SizeOf(TLangIdRec)); end; end; end; begin FItemList := TStringList.Create; FItems := TStringList.Create; Data := Pointer(FBuffer); Assert(DWORD(Data) mod 4 = 0); IsUnicode := (PWord(Data + 4)^ in [0, 1]); Error := True; GetHeader; EndOfData := Data + Len - HeaderSize; if (Key = 'VS_VERSION_INFO') and (ValueLen = SizeOf(TVSFixedFileInfo)) then begin FFixedInfo := PVSFixedFileInfo(Data); Error := FFixedInfo.dwSignature <> $FEEF04BD; Inc(Data, ValueLen); // VS_FIXEDFILEINFO Padding(Data); // VS_VERSIONINFO.Padding2 while not Error and (Data < EndOfData) do begin GetHeader; Inc(Data, ValueLen); // some files (VREDIR.VXD 4.00.1111) has non zero value of ValueLen Dec(Len, HeaderSize + ValueLen); if Key = 'StringFileInfo' then ProcessStringInfo(Len) else if Key = 'VarFileInfo' then ProcessVarInfo(Len) else Break; end; ExtractFlags; CreateItemsForLanguage; end; if Error then raise EJclFileVersionInfoError.CreateResRec(@RsFileUtilsNoVersionInfo); end; //-------------------------------------------------------------------------------------------------- procedure TJclFileVersionInfo.ExtractFlags; var Masked: DWORD; begin FFileFlags := []; Masked := FFixedInfo^.dwFileFlags and FFixedInfo^.dwFileFlagsMask; if (Masked and VS_FF_DEBUG) <> 0 then Include(FFileFlags, ffDebug); if (Masked and VS_FF_INFOINFERRED) <> 0 then Include(FFileFlags, ffInfoInferred); if (Masked and VS_FF_PATCHED) <> 0 then Include(FFileFlags, ffPatched); if (Masked and VS_FF_PRERELEASE) <> 0 then Include(FFileFlags, ffPreRelease); if (Masked and VS_FF_PRIVATEBUILD) <> 0 then Include(FFileFlags, ffPrivateBuild); if (Masked and VS_FF_SPECIALBUILD) <> 0 then Include(FFileFlags, ffSpecialBuild); end; //-------------------------------------------------------------------------------------------------- function TJclFileVersionInfo.GetBinFileVersion: string; begin with FFixedInfo^ do Result := Format('%u.%u.%u.%u', [HiWord(dwFileVersionMS), LoWord(dwFileVersionMS), HiWord(dwFileVersionLS), LoWord(dwFileVersionLS)]); end; //-------------------------------------------------------------------------------------------------- function TJclFileVersionInfo.GetBinProductVersion: string; begin with FFixedInfo^ do Result := Format('%u.%u.%u.%u', [HiWord(dwProductVersionMS), LoWord(dwProductVersionMS), HiWord(dwProductVersionLS), LoWord(dwProductVersionLS)]); end; //-------------------------------------------------------------------------------------------------- function TJclFileVersionInfo.GetFileOS: DWORD; begin Result := FFixedInfo^.dwFileOS; end; //-------------------------------------------------------------------------------------------------- function TJclFileVersionInfo.GetFileSubType: DWORD; begin Result := FFixedInfo^.dwFileSubtype; end; //-------------------------------------------------------------------------------------------------- function TJclFileVersionInfo.GetFileType: DWORD; begin Result := FFixedInfo^.dwFileType; end; //-------------------------------------------------------------------------------------------------- function TJclFileVersionInfo.GetFixedInfo: TVSFixedFileInfo; begin Result := FFixedInfo^; end; //-------------------------------------------------------------------------------------------------- function TJclFileVersionInfo.GetLanguageCount: Integer; begin Result := Length(FLanguages); end; //-------------------------------------------------------------------------------------------------- function TJclFileVersionInfo.GetLanguageIds(Index: Integer): string; begin CheckLanguageIndex(Index); Result := VersionLanguageId(FLanguages[Index]); end; //-------------------------------------------------------------------------------------------------- function TJclFileVersionInfo.GetLanguages(Index: Integer): TLangIdRec; begin CheckLanguageIndex(Index); Result := FLanguages[Index]; end; //-------------------------------------------------------------------------------------------------- function TJclFileVersionInfo.GetLanguageNames(Index: Integer): string; begin CheckLanguageIndex(Index); Result := VersionLanguageName(FLanguages[Index].LangId); end; //-------------------------------------------------------------------------------------------------- function TJclFileVersionInfo.GetTranslationCount: Integer; begin Result := Length(FTranslations); end; //-------------------------------------------------------------------------------------------------- function TJclFileVersionInfo.GetTranslations(Index: Integer): TLangIdRec; begin Result := FTranslations[Index]; end; //-------------------------------------------------------------------------------------------------- function TJclFileVersionInfo.GetVersionKeyValue(Index: Integer): string; begin Result := FItems.Values[VerKeyNames[Index]]; end; //-------------------------------------------------------------------------------------------------- procedure TJclFileVersionInfo.SetLanguageIndex(const Value: Integer); begin CheckLanguageIndex(Value); if FLanguageIndex <> Value then begin FLanguageIndex := Value; CreateItemsForLanguage; end; end; //-------------------------------------------------------------------------------------------------- function TJclFileVersionInfo.TranslationMatchesLanguages(Exact: Boolean): Boolean; var TransIndex, LangIndex: Integer; TranslationPair: DWORD; begin Result := (LanguageCount = TranslationCount) or (not Exact and (TranslationCount > 0)); if Result then for TransIndex := 0 to TranslationCount - 1 do begin TranslationPair := FTranslations[TransIndex].Pair; LangIndex := LanguageCount - 1; while (LangIndex >= 0) and (TranslationPair <> FLanguages[LangIndex].Pair) do Dec(LangIndex); if LangIndex < 0 then begin Result := False; Break; end; end; end; //-------------------------------------------------------------------------------------------------- class function TJclFileVersionInfo.VersionLanguageId(const LangIdRec: TLangIdRec): string; begin with LangIdRec do Result := Format('%.4x%.4x', [LangId, CodePage]); end; //-------------------------------------------------------------------------------------------------- class function TJclFileVersionInfo.VersionLanguageName(const LangId: Word): string; var R: DWORD; begin SetLength(Result, MAX_PATH); R := VerLanguageName(LangId, PChar(Result), MAX_PATH); SetLength(Result, R); end; //================================================================================================== // TJclFileMaskComparator //================================================================================================== function TJclFileMaskComparator.Compare(const NameExt: string): Boolean; var I: Integer; NamePart, ExtPart: string; NameWild, ExtWild: Boolean; begin Result := False; I := StrLastPos('.', NameExt); if I = 0 then begin NamePart := NameExt; ExtPart := ''; end else begin NamePart := Copy(NameExt, 1, I - 1); ExtPart := Copy(NameExt, I + 1, Length(NameExt)); end; for I := 0 to Length(FNames) - 1 do begin NameWild := FWildChars[I] and 1 = 1; ExtWild := FWildChars[I] and 2 = 2; if ((not NameWild and StrSame(FNames[I], NamePart)) or (NameWild and (StrMatches(FNames[I], NamePart, 1)))) and ((not ExtWild and StrSame(FExts[I], ExtPart)) or (ExtWild and (StrMatches(FExts[I], ExtPart, 1)))) then begin Result := True; Break; end; end; end; //-------------------------------------------------------------------------------------------------- constructor TJclFileMaskComparator.Create; begin inherited; FSeparator := ';'; end; //-------------------------------------------------------------------------------------------------- procedure TJclFileMaskComparator.CreateMultiMasks; const WildChars = ['*', '?']; var List: TStrings; I, N: Integer; NS, ES: string; begin FExts := nil; FNames := nil; FWildChars := nil; List := TStringList.Create; try StrToStrings(FFileMask, FSeparator, List); SetLength(FExts, List.Count); SetLength(FNames, List.Count); SetLength(FWildChars, List.Count); for I := 0 to List.Count - 1 do begin N := StrLastPos('.', List[I]); if N = 0 then begin NS := List[I]; ES := ''; end else begin NS := Copy(List[I], 1, N - 1); ES := Copy(List[I], N + 1, 255); end; FNames[I] := NS; FExts[I] := ES; N := 0; if StrContainsChars(NS, WildChars, False) then N := N or 1; if StrContainsChars(ES, WildChars, False) then N := N or 2; FWildChars[I] := N; end; finally List.Free; end; end; //-------------------------------------------------------------------------------------------------- function TJclFileMaskComparator.GetCount: Integer; begin Result := Length(FWildChars); end; //-------------------------------------------------------------------------------------------------- function TJclFileMaskComparator.GetExts(Index: Integer): string; begin Result := FExts[Index]; end; //-------------------------------------------------------------------------------------------------- function TJclFileMaskComparator.GetMasks(Index: Integer): string; begin Result := FNames[Index] + '.' + FExts[Index]; end; //-------------------------------------------------------------------------------------------------- function TJclFileMaskComparator.GetNames(Index: Integer): string; begin Result := FNames[Index]; end; //-------------------------------------------------------------------------------------------------- procedure TJclFileMaskComparator.SetFileMask(const Value: string); begin FFileMask := Value; CreateMultiMasks; end; //-------------------------------------------------------------------------------------------------- procedure TJclFileMaskComparator.SetSeparator(const Value: Char); begin if FSeparator <> Value then begin FSeparator := Value; CreateMultiMasks; end; end; //-------------------------------------------------------------------------------------------------- function AdvBuildFileList(const Path: string; const Attr: Integer; const Files: TStrings; const Options: TFileListOptions; const SubfoldersMask: string): Boolean; var FileMask: string; RootDir: string; Folders: TStringList; CurrentItem: Integer; Counter: Integer; LocAttr: Integer; procedure BuildFolderList; var FindInfo: TSearchRec; Rslt: Integer; begin Counter := Folders.Count - 1; CurrentItem := 0; while CurrentItem <= Counter do begin // searching for subfolders Rslt := FindFirst(Folders[CurrentItem] + '*.*', faDirectory, FindInfo); try while Rslt = 0 do begin if (FindInfo.Name <> '.') and (FindInfo.Name <> '..') and (FindInfo.Attr and faDirectory = faDirectory) then Folders.Add(Folders[CurrentItem] + FindInfo.Name + PathSeparator); Rslt := FindNext(FindInfo); end; finally FindClose(FindInfo); end; Counter := Folders.Count - 1; Inc(CurrentItem); end; end; procedure FillFileList(CurrentCounter: Integer); var FindInfo: TSearchRec; Rslt: Integer; CurrentFolder: String; FileAttr: Integer; begin CurrentFolder := Folders[CurrentCounter]; Rslt := FindFirst(CurrentFolder + FileMask, LocAttr, FindInfo); try while Rslt = 0 do begin FileAttr := FindInfo.Attr and not FILE_ATTRIBUTE_NORMAL; // Include all normal files if (LocAttr and FileAttr) = FileAttr then if flFullNames in Options then Files.Add(CurrentFolder + FindInfo.Name) else Files.Add(FindInfo.Name); Rslt := FindNext(FindInfo); end; finally FindClose(FindInfo); end; end; begin Assert(Files <> nil); FileMask := ExtractFileName(Path); RootDir := ExtractFilePath(Path); Folders := TStringList.Create; try Folders.Add(RootDir); if Attr = faAnyFile then LocAttr := faReadOnly + faHidden + faSysFile + faArchive else LocAttr := Attr; // here's the recursive search for nested folders if flRecursive in Options then BuildFolderList; for Counter := 0 to Folders.Count - 1 do begin if (((flMaskedSubfolders in Options) and (StrMatches(SubfoldersMask, Folders[Counter], 1))) or (not (flMaskedSubfolders in Options))) then FillFileList(Counter); end; finally Folders.Free; end; Result := True; end; end.
{--------------------------------------- Small shell utility to convert any texts file into quoted pascal string variable which then can be included as part of Pascal program using directive $INCLUDE @author irfanbagus @link http://forum.lazarus.freepascal.org/index.php?topic=20706.0 ----------------------------------------} program txt2inc; {$mode objfpc}{$H+} uses classes, sysutils; var src, dst: TStringList; i: integer; begin if paramCount < 3 then begin writeLn(); writeLn(ExtractFileName(ParamStr(0))+' [source] [dest] [const name]'); exit; end; src:= TStringList.Create(); dst:= TStringList.Create(); try src.loadFromFile(paramStr(1)); dst.add(paramStr(3)+': string = '); for i:=0 to src.count-2 do begin dst.add(' ' + QuotedStr(src[i]) + ' + LineEnding + '); end; if (src.count > 0) then begin dst.add(' ' + QuotedStr(src[src.count-1]) + ';'); end; dst.saveToFile(paramStr(2)); finally src.free(); dst.free(); end; end.
{$MODE OBJFPC} program LongestIncreasingSubsequence; const InputFile = 'LIS.INP'; OutputFile = 'LIS.OUT'; max = Round(1E5); maxV = Round(1E9); var a, t: array[0..max + 1] of Integer; s: array[1..max + 2] of Integer; n, m: Integer; procedure Enter; var f: TextFile; i: Integer; begin AssignFile(f, InputFile); Reset(f); try ReadLn(f, n); for i := 1 to n do Read(f, a[i]); finally CloseFile(f); end; end; procedure Init; begin a[0] := -maxV - 1; a[n + 1] := maxV + 1; m := 1; s[1] := n + 1; end; function BinarySearch(v: Integer): Integer; var Low, Middle, High: Integer; begin Low := 2; High := m; while Low <= High do begin Middle := (Low + High) div 2; if a[s[Middle]] > v then Low := Middle + 1 else High := Middle - 1; end; Result := High; end; procedure Optimize; var i, lambda: Integer; begin for i := n downto 0 do begin lambda := BinarySearch(a[i]); t[i] := s[lambda]; if lambda + 1 > m then m := lambda + 1; s[lambda + 1] := i; end; end; procedure PrintResult; var f: TextFile; i: Integer; begin AssignFile(f, OutputFile); Rewrite(f); try WriteLn(f, m - 2); i := t[0]; while i <> n + 1 do begin Write(f, i, ' '); i := t[i]; end; finally CloseFile(f); end; end; begin Enter; Init; Optimize; PrintResult; end. 12 1 2 3 8 9 4 5 6 2 3 9 10
{ Copyright (C) Alexey Torgashin, uvviewsoft.com License: MPL 2.0 or LGPL } unit ATSynEdit_Cmp_CSS_Provider; {$mode objfpc}{$H+} interface uses SysUtils, Classes; type TATCssProvider = class abstract public procedure GetProps(L: TStringList); virtual; abstract; procedure GetValues(const AProp: string; L: TStringList); virtual; abstract; end; type { TATCssBasicProvider } TATCssBasicProvider = class(TATCssProvider) private ListProps: TStringList; ListColors: TStringList; public constructor Create(const AFilenameProps, AFilenameColors: string); destructor Destroy; override; procedure GetProps(L: TStringList); override; procedure GetValues(const AProp: string; L: TStringList); override; end; implementation uses ATStringProc, ATStringProc_Separator; { TATCssBasicProvider } constructor TATCssBasicProvider.Create(const AFilenameProps, AFilenameColors: string); var i: integer; begin ListProps:= TStringList.Create; ListColors:= TStringList.Create; if FileExists(AFilenameProps) then ListProps.LoadFromFile(AFilenameProps); if FileExists(AFilenameColors) then ListColors.LoadFromFile(AFilenameColors); for i:= ListProps.Count-1 downto 0 do if ListProps[i]='' then ListProps.Delete(i); for i:= ListColors.Count-1 downto 0 do if ListColors[i]='' then ListColors.Delete(i); end; destructor TATCssBasicProvider.Destroy; begin FreeAndNil(ListColors); FreeAndNil(ListProps); inherited Destroy; end; procedure TATCssBasicProvider.GetProps(L: TStringList); var S, SKey, SVal: string; begin L.Clear; for S in ListProps do begin SSplitByChar(S, '=', SKey, SVal); L.Add(SKey); end; end; procedure TATCssBasicProvider.GetValues(const AProp: string; L: TStringList); var S, SKey, SVal, SItem: string; Sep: TATStringSeparator; N: integer; begin L.Clear; //add values specific to AProp for S in ListProps do begin SSplitByChar(S, '=', SKey, SVal); if SameText(AProp, SKey) then begin Sep.Init(SVal, ','); while Sep.GetItemStr(SItem) do L.Add(SItem); Break; end; end; //auto add 'color' values N:= L.IndexOf('$c'); if N>=0 then begin L.Delete(N); L.AddStrings(ListColors); end else if SEndsWith(AProp, '-background') or SEndsWith(AProp, '-color') then L.AddStrings(ListColors); //add common values L.Add('inherit'); L.Add('initial'); L.Add('unset'); L.Add('var()'); end; end.
unit OS.ProcessOpener; interface uses SysUtils, Windows, Dialogs, OS.SecurityDescriptor; type TProcessBuffer = reference to procedure (const CurrentBuffer: String; var CurrentResult: AnsiString); TProcessOpener = class public function OpenProcWithProcessFunction(const Path, Command: String; const ProcessBufferFunction: TProcessBuffer): AnsiString; function OpenProcWithOutput(const Path, Command: String): AnsiString; class function Create: TProcessOpener; private ProcessBuffer: TProcessBuffer; function GetSecurityDescriptor: TSecurityAttributes; procedure CreatePipeWithHandles( var ReadHandle, WriteHandle: THandle); function ReadFromHandle(const ReadHandle: THandle): AnsiString; var SecurityDescriptorManipulator: TSecurityDescriptorManipulator; end; procedure DefaultProcessBuffer(const CurrentBuffer: String; var CurrentResult: AnsiString); var ProcessOpener: TProcessOpener; implementation function TProcessOpener.GetSecurityDescriptor: TSecurityAttributes; begin result.nLength := sizeof(result); result.lpSecurityDescriptor := SecurityDescriptorManipulator.GetSecurityDescriptor; result.bInheritHandle := true; end; class function TProcessOpener.Create: TProcessOpener; begin if ProcessOpener = nil then result := inherited Create as self else result := ProcessOpener; end; procedure TProcessOpener.CreatePipeWithHandles( var ReadHandle, WriteHandle: THandle); var SecurityAttributes: TSecurityAttributes; begin SecurityAttributes := GetSecurityDescriptor; if not CreatePipe(ReadHandle, WriteHandle, @SecurityAttributes, 0) then raise EOSError.Create('CreatePipe Error (' + UIntToStr(GetLastError) + ')'); end; function TProcessOpener.ReadFromHandle( const ReadHandle: THandle): AnsiString; var Buffer: array[0..512] of AnsiChar; BytesRead: DWORD; begin result := ''; while ReadFile(ReadHandle, Buffer, SizeOf(Buffer) - 1, BytesRead, nil) do begin Buffer[BytesRead] := #0; ProcessBuffer(String(Buffer), result); end; end; function TProcessOpener.OpenProcWithOutput(const Path, Command: String ): AnsiString; begin result := OpenProcWithProcessFunction(Path, Command, DefaultProcessBuffer); end; function TProcessOpener.OpenProcWithProcessFunction( const Path, Command: String; const ProcessBufferFunction: TProcessBuffer): AnsiString; const StartupSettingsTemplate: TStartupInfo = (cb: sizeof(STARTUPINFO); dwFlags: STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; wShowWindow: SW_HIDE); var StartupSettings: TStartupInfo; WriteHandle, ReadHandle: THandle; ProcessInformation: _PROCESS_INFORMATION; begin ProcessBuffer := ProcessBufferFunction; SecurityDescriptorManipulator := TSecurityDescriptorManipulator.Create; CreatePipeWithHandles(ReadHandle, WriteHandle); StartupSettings := StartupSettingsTemplate; StartupSettings.hStdOutput := WriteHandle; StartupSettings.hStdError := WriteHandle; if not CreateProcess(nil, PWideChar(WideString(Command)), nil, nil, True, 0, nil, PWideChar(WideString(Path)), StartupSettings, ProcessInformation) then raise EOSError.Create( 'CreateProcess Error(Command: ' + Command + ' Path: ' + Path + ' ErrorCode: ' + UIntToStr(GetLastError) + ')'); CloseHandle(WriteHandle); result := ReadFromHandle(ReadHandle); CloseHandle(ReadHandle); FreeAndNil(SecurityDescriptorManipulator); end; procedure DefaultProcessBuffer(const CurrentBuffer: String; var CurrentResult: AnsiString); begin CurrentResult := AnsiString(String(CurrentResult) + CurrentBuffer); end; initialization ProcessOpener := TProcessOpener.Create; finalization ProcessOpener.Free; end.
{ Mystix Copyright (C) 2005 Piotr Jura This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. You can contact with me by e-mail: pjura@o2.pl } unit uMRU; interface uses Classes, SysUtils, uMyIniFiles; type TMRUList = class private fMRUList: TStringList; fLimit: Integer; fMyIniFile: TMyIniFile; fIniSection: String; function GetItem(Index: Integer): String; procedure Read; procedure Write; function GetCount: Integer; public constructor Create(aMyIniFile: TMyIniFile; aLimit: Integer; aIniSection: String); destructor Destroy; override; procedure Add(Item: String); procedure Clear; property AllItems: TStringList read fMRUList; property Count: Integer read GetCount; property Items[Index: Integer]: String read GetItem; default; end; implementation { TMRUList } procedure TMRUList.Add(Item: String); begin if fMRUList.IndexOf(Item) <> -1 then fMRUList.Delete(fMRUList.IndexOf(Item)); fMRUList.Insert(0, Item); if fMRUList.Count > fLimit then fMRUList.Delete(fLimit); end; procedure TMRUList.Clear; begin fMRUList.Clear; end; constructor TMRUList.Create(aMyIniFile: TMyIniFile; aLimit: Integer; aIniSection: String); begin fMyIniFile := aMyIniFile; fLimit := aLimit; fIniSection := aIniSection; fMRUList := TStringList.Create; Read; end; destructor TMRUList.Destroy; begin Write; fMRUList.Free; inherited; end; function TMRUList.GetCount: Integer; begin Result := fMRUList.Count; end; function TMRUList.GetItem(Index: Integer): String; begin Result := fMRUList[Index]; end; procedure TMRUList.Read; var i: Integer; begin i := 1; while (fMyIniFile.ValueExists(fIniSection, 'MRUItem' + IntToStr(i))) and (i <= fLimit) do begin fMRUList.Add( fMyIniFile.ReadString(fIniSection, 'MRUItem' + IntToStr(i), '') ); Inc(i); end; end; procedure TMRUList.Write; var i: Integer; begin for i := 1 to fMRUList.Count do fMyIniFile.WriteString(fIniSection, 'MRUItem' + IntToStr(i), fMRUList[i - 1]); end; end.
unit DAOTest; interface uses TestClasses, Generics.Collections; type TDAOTest = class function GetList: TObjectList<TTest>; procedure Add(Title: string); procedure Delete(Index: Integer); procedure Edit(Index: Integer; Title: string); end; implementation uses JoanModule; { TDAOTest } procedure TDAOTest.Add(Title: string); begin Joan.JoanQuery.Close; Joan.JoanQuery.SQL.Text := 'INSERT INTO test (title) VALUES (:title)'; Joan.JoanQuery.ParamByName('title').AsString := Title; Joan.JoanQuery.ExecSQL; end; procedure TDAOTest.Delete(Index: Integer); begin Joan.JoanQuery.Close; Joan.JoanQuery.SQL.Text := 'DELETE FROM test WHERE Idx = :Idx'; Joan.JoanQuery.ParamByName('Idx').Asinteger := Index; Joan.JoanQuery.ExecSQL; end; procedure TDAOTest.Edit(Index: Integer; Title: string); begin Joan.JoanQuery.Close; Joan.JoanQuery.SQL.Text := 'UPDATE test SET Title = :Title WHERE Idx = :Idx'; Joan.JoanQuery.ParamByName('Idx').Asinteger := Index; Joan.JoanQuery.ParamByName('Title').AsString := Title; Joan.JoanQuery.ExecSQL; end; function TDAOTest.GetList: TObjectList<TTest>; var Test: TTest; begin Result := TObjectList<TTest>.Create; Joan.JoanQuery.Close; Joan.JoanQuery.SQL.Text := 'SELECT * FROM test'; Joan.JoanQuery.Open; Joan.JoanQuery.First; while not Joan.JoanQuery.Eof do begin Test := TTest.Create; Test.Idx := Joan.JoanQuery.FieldByName('idx').AsInteger; Test.Title := Joan.JoanQuery.FieldByName('title').AsString; // TObjectList<TTest> 여기에다가 값을 넣는다. Result.Add(Test); Joan.JoanQuery.Next; end; end; end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit DSAzDlgACL; interface uses Vcl.Buttons, System.Classes, Vcl.Controls, DSAzure, Vcl.ExtCtrls, Vcl.Forms, Vcl.Graphics, Vcl.Grids, Vcl.StdCtrls; type TAzACL = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; rgPublicDataAccess: TRadioGroup; sgId: TStringGrid; cbxRead: TCheckBox; cbxDelete: TCheckBox; cbxWrite: TCheckBox; cbxList: TCheckBox; gbxAccessPolicy: TGroupBox; lbeStart: TLabeledEdit; lbeExpiry: TLabeledEdit; gbxIdentifiers: TGroupBox; procedure sgIdSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: string); procedure sgIdSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure sgIdGetEditText(Sender: TObject; ACol, ARow: Integer; var Value: string); procedure FormCreate(Sender: TObject); procedure lbeStartChange(Sender: TObject); procedure lbeExpiryChange(Sender: TObject); procedure cbxReadClick(Sender: TObject); procedure cbxWriteClick(Sender: TObject); procedure cbxDeleteClick(Sender: TObject); procedure cbxListClick(Sender: TObject); procedure rgPublicDataAccessClick(Sender: TObject); private { Private declarations } FAPArray: TAccessPolicyArray; FIndex: Integer; FLastValidIdentifier: String; procedure MoveIndex(NewIndex: Integer); procedure SetPublicDataAccess(const Access: string); function GetPublicDataAccess: string; function GetAccessPolicy(idx: Integer): TAccessPolicy; function GetIdentifier(idx: Integer): string; function GetCount: Integer; procedure DeleteRow(ARow: Integer); function GetRawIdentifier(idx: Integer): string; public { Public declarations } procedure SetAccessPolicyLength(Size: Integer); procedure SetAccessPolicy(Index: Integer; const Id: string; AP: TAccessPolicy); procedure SetBaseline; procedure MoveToRow(ARow: Integer); property PublicDataAccess: string read GetPublicDataAccess write SetPublicDataAccess; property AccessPolicy[idx: Integer]: TAccessPolicy read GetAccessPolicy; property Identifier[idx: Integer]: string read GetIdentifier; property RawIdentifier[idx: Integer]: string read GetRawIdentifier; property Count: Integer read GetCount; end; implementation uses Data.DBXClientResStrs, Vcl.Dialogs, System.SysUtils, System.UITypes; {$R *.dfm} { TAzACL } procedure TAzACL.cbxDeleteClick(Sender: TObject); begin FAPArray[FIndex].PermDelete := cbxDelete.Checked; OKBtn.Enabled := true; end; procedure TAzACL.cbxListClick(Sender: TObject); begin FAPArray[FIndex].PermList := cbxList.Checked; OKBtn.Enabled := true; end; procedure TAzACL.cbxReadClick(Sender: TObject); begin FAPArray[FIndex].PermRead := cbxRead.Checked; OKBtn.Enabled := true; end; procedure TAzACL.cbxWriteClick(Sender: TObject); begin FAPArray[FIndex].PermWrite := cbxWrite.Checked; OKBtn.Enabled := true; end; procedure TAzACL.DeleteRow(ARow: Integer); begin if (ARow < (sgId.RowCount - 1)) and (sgId.Cells[0, ARow+1] <> EmptyStr) then begin while ARow < sgId.RowCount - 1 do begin sgId.Cells[0, ARow] := sgId.Cells[0, ARow + 1]; FAPArray[ARow] := FAPArray[ARow + 1]; Inc(ARow); end; sgId.Cells[0, ARow] := EmptyStr; end; end; procedure TAzACL.FormCreate(Sender: TObject); begin SetLength(FAPArray, sgId.RowCount); end; function TAzACL.GetAccessPolicy(idx: Integer): TAccessPolicy; begin Result := FAPArray[idx]; end; function TAzACL.GetCount: Integer; begin Result := Length(FAPArray); end; function TAzACL.GetIdentifier(idx: Integer): string; begin Result := TAzureService.Encode(sgId.Cells[0, idx]); end; function TAzACL.GetPublicDataAccess: string; begin case rgPublicDataAccess.ItemIndex of 0: Result := 'container'; 1: Result := 'blob'; else Result := ''; end; end; function TAzACL.GetRawIdentifier(idx: Integer): string; begin Result := sgId.Cells[0, idx]; end; procedure TAzACL.lbeExpiryChange(Sender: TObject); begin FAPArray[FIndex].Expiry := lbeExpiry.Text; OKBtn.Enabled := true; end; procedure TAzACL.lbeStartChange(Sender: TObject); begin FAPArray[FIndex].Start := lbeStart.Text; OKBtn.Enabled := true; end; procedure TAzACL.MoveIndex(NewIndex: Integer); begin FIndex := NewIndex; cbxRead.Checked := FAPArray[FIndex].PermRead; cbxWrite.Checked := FAPArray[FIndex].PermWrite; cbxDelete.Checked := FAPArray[FIndex].PermDelete; cbxList.Checked := FAPArray[FIndex].PermList; lbeStart.Text := FAPArray[FIndex].Start; lbeExpiry.Text := FAPArray[FIndex].Expiry; end; procedure TAzACL.MoveToRow(ARow: Integer); begin if sgId.Cells[0, ARow] = EmptyStr then begin gbxAccessPolicy.Caption := SNewPolicyCaption; FAPArray[ARow] := TAccessPolicy.Create; end else gbxAccessPolicy.Caption := sgId.Cells[0, ARow]; MoveIndex(ARow); end; procedure TAzACL.rgPublicDataAccessClick(Sender: TObject); begin OKBtn.Enabled := true; end; procedure TAzACL.SetAccessPolicy(Index: Integer; const Id: string; AP: TAccessPolicy); begin FAPArray[Index] := AP; sgId.Cells[0, Index] := TAzureService.Decode(Id); end; procedure TAzACL.SetAccessPolicyLength(Size: Integer); begin SetLength(FAPArray, Size); end; procedure TAzACL.SetBaseline; begin OKBtn.Enabled := false; end; procedure TAzACL.SetPublicDataAccess(const Access: string); begin if 'blob' = Access then rgPublicDataAccess.ItemIndex := 1 else if 'container' = Access then rgPublicDataAccess.ItemIndex := 0 else if EmptyStr = Access then rgPublicDataAccess.ItemIndex := 2 else rgPublicDataAccess.ItemIndex := -1 end; procedure TAzACL.sgIdGetEditText(Sender: TObject; ACol, ARow: Integer; var Value: string); begin MoveToRow(ARow); FLastValidIdentifier := Value; end; procedure TAzACL.sgIdSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if ARow > 0 then CanSelect := sgId.Cells[ACol, ARow-1] <> EmptyStr; if CanSelect then begin MoveToRow(ARow); FLastValidIdentifier := sgId.Cells[ACol, ARow]; end; end; procedure TAzACL.sgIdSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: string); begin if ARow = FIndex then begin if Value = EmptyStr then begin if MessageDlg(Format(SAreYouSurePolicy, [ARow+1]), mtWarning, [mbYes, mbNo], 0) = mrYes then begin DeleteRow(ARow); MoveToRow(ARow); end else sgId.Cells[ACol, ARow] := FLastValidIdentifier; end else FLastValidIdentifier := Value; gbxAccessPolicy.Caption := sgId.Cells[ACol, ARow]; OKBtn.Enabled := true; end; end; end.
unit u_ext_info; interface uses Windows, u_obimp_const; const //============================================ //dll exported functions names FUNC_NAME_EXTENSION_INFO = 'GetExtensionInfo_v2'; FUNC_NAME_CREATE_INSTANCE_PG = 'CreateExtenInstancePG_v2'; //============================================ //Available extension types: EXT_TYPE_TRANSPORT = $0001; EXT_TYPE_PLUGIN = $0002; EXT_TYPE_MAX = $0002; type //common extension information TExtensionInfo = record ExtType : Word; ExtUUID : array[0..15] of Byte; ExtName : WideString; //must not be empty ExtVer : WideString; ExtAuthor : WideString; ExtInfoURL : WideString; ExtParams : Pointer; //according ExtType ExtTimer : Boolean; //extensions wants to receive timer ticks for instances, every ~1000 msecs will be called TimerTick function end; pExtensionInfo = ^TExtensionInfo; /////////////////////////////////////////////////////////////////////////////// /// PLUGIN extension /////////////////////////////////////////////////////////////////////////////// //plugin extension parameters TExtParamsPG = record ListenTextMsgs: Boolean; end; pExtParamsPG = ^TExtParamsPG; TExtServerInfo = record VerMajor : Word; VerMinor : Word; VerRelease : Word; VerBuild : Word; PathUserDB : WideString; PathLogFiles : WideString; end; pExtServerInfo = ^TExtServerInfo; TExtPlugTextMsg = record AccSender : WideString; AccRcver : WideString; MsgType : DWord; MsgText : WideString; AckRequired : Boolean; //delivery report from receiver required MsgEncrypted : Boolean; //if message is encrypted then it will be base64 encoded, but anyway it can't be decryted SystemMsg : Boolean; //system message flag SystemMsgPos : Byte; //system message popup position (0 - default, 1 - screen center) MultipleMsg : Boolean; //multiple message flag RcverOffline : Boolean; //receiver is offline at message sending moment TranspOwnerAcc : WideString; //transport owner account name if message was send to transport TranspUUIDHex : WideString; //transport UUID in hex if message was send to transport end; pExtPlugTextMsg = ^TExtPlugTextMsg; //plugin extension interface IExtensionPG = interface procedure TimerTick; stdcall; procedure NotifyTextMsg(const ExtPlugTextMsg: TExtPlugTextMsg); stdcall; end; //plugin events interface IEventsPG = interface procedure GetServerInfo(var ServerInfo: TExtServerInfo); stdcall; end; implementation end.
{**********************************************} { TeeChart Office / TeeTree } { Inspector object. } { Copyright (c) 2001-2004 by David Berneda } {**********************************************} unit TeeInspector; {$I TeeDefs.inc} interface Uses {$IFNDEF LINUX} Windows, {$ENDIF} {$IFDEF D6} Types, {$ENDIF} {$IFDEF CLX} QGrids, QGraphics, QStdCtrls, QMenus, QForms, QControls, Qt, {$ELSE} Grids, Graphics, Controls, Forms, StdCtrls, Menus, {$ENDIF} {$IFDEF CLR} Variants, {$ENDIF} Classes, SysUtils, TeCanvas, TeeProcs; type TInspectorItemStyle=( iiBoolean, iiString, iiSelection, iiColor, iiPen, iiGradient, iiBrush, iiFont, iiImage, iiButton, iiInteger, iiDouble ); TInspectorItem=class; TGetItemProc=procedure(Const S:String; AObject:TObject=nil) of object; TGetInspectorItems=procedure(Sender:TInspectorItem; Proc:TGetItemProc) of object; TTeeInspector=class; TInspectorItem=class(TCollectionItem) private FCaption : String; FData : TObject; FEnabled : Boolean; FStyle : TInspectorItemStyle; FValue : Variant; FVisible : Boolean; IData : TObject; FOnChange : TNotifyEvent; FOnGetItems : TGetInspectorItems; Procedure Changed; Procedure RebuildInspector; procedure SetCaption(const Value: String); procedure SetVisible(const Value: Boolean); procedure SetValue(const Value: Variant); procedure SetData(const Value: TObject); protected Function StyleToInt:Integer; public Constructor Create(Collection:TCollection); override; Function Inspector:TTeeInspector; property Data:TObject read FData write SetData; published property Caption:String read FCaption write SetCaption; property Enabled:Boolean read FEnabled write FEnabled default True; property Style:TInspectorItemStyle read FStyle write FStyle default iiBoolean; property Value:Variant read FValue write SetValue; property Visible:Boolean read FVisible write SetVisible default True; property OnChange:TNotifyEvent read FOnChange write FOnChange; property OnGetItems:TGetInspectorItems read FOnGetItems write FOnGetItems; end; TInspectorItems=class(TOwnedCollection) private Function Get(Index:Integer):TInspectorItem; Procedure Put(Index:Integer; Const Value:TInspectorItem); protected procedure Update(Item: TCollectionItem); override; public Inspector : TTeeInspector; Function Add( AStyle:TInspectorItemStyle; Const ACaption:String; AData:TObject):TInspectorItem; overload; Function Add( AStyle:TInspectorItemStyle; Const ACaption:String; AData:TObject; const AOnChange:TNotifyEvent):TInspectorItem; overload; Function Add( AStyle:TInspectorItemStyle; Const ACaption:String; const AOnChange:TNotifyEvent):TInspectorItem; overload; Function Add( AStyle:TInspectorItemStyle; Const ACaption:String; InitialValue:Variant; const AOnChange:TNotifyEvent):TInspectorItem; overload; Function Add( AStyle:TInspectorItemStyle; Const ACaption:String; InitialValue:Variant):TInspectorItem; overload; Function Add( AStyle:TInspectorItemStyle; Const ACaption:String; InitialValue:Variant; AData:TObject; const AOnChange:TNotifyEvent):TInspectorItem; overload; property Item[Index:Integer]:TInspectorItem read Get write Put; default; end; TComboFlatGrid=class(TComboFlat) {$IFNDEF CLX} private {$IFNDEF CLR} procedure CMFocusChanged(var Message: TCMFocusChanged); message CM_FOCUSCHANGED; {$ENDIF} {$ELSE} protected function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override; {$ENDIF} end; TEditGrid=class(TEdit) {$IFNDEF CLX} private {$IFNDEF CLR} procedure CMFocusChanged(var Message: TCMFocusChanged); message CM_FOCUSCHANGED; {$ENDIF} {$ELSE} protected function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override; {$ENDIF} end; TInspectorHeader=class(TPersistent) private FFont : TFont; FVisible : Boolean; Procedure CanvasChanged(Sender:TObject); procedure SetFont(const Value: TFont); procedure SetVisible(const Value: Boolean); public Inspector : TTeeInspector; Constructor Create; Destructor Destroy; override; Procedure Update; published property Font:TFont read FFont write SetFont; property Visible:Boolean read FVisible write SetVisible default True; end; TTeeInspector=class(TStringGrid) private FHeader : TInspectorHeader; FItems : TInspectorItems; IComboGrid : TComboFlatGrid; IEditGrid : TEditGrid; procedure AddComboItem(Const S:String; AObject:TObject); procedure ComboChange(Sender: TObject); Procedure CreateCombo; Procedure CreateEdit; procedure EditChange(Sender: TObject); procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); Procedure HideCombos; procedure InternalSetHeader; Function MinRow:Integer; Procedure SetComboIndex; procedure SetHeader(Const Value:TInspectorHeader); Procedure SetItems(const Value:TInspectorItems); Function ValidRow(ARow:Integer):Boolean; protected procedure DrawCell(ACol, ARow: Integer; ARect: TRect; AState: TGridDrawState); override; Procedure DoPositionCombos(WhenVisible:Boolean); Function Item(ARow:Integer):TInspectorItem; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure Loaded; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure Rebuild; procedure Resize; override; function SelectCell(ACol, ARow: Integer): Boolean; override; {$IFDEF CLX} Procedure SetParent(const Value: TWidgetControl); override; {$ELSE} Procedure SetParent(AParent: TWinControl); override; {$ENDIF} procedure TopLeftChanged; override; public Constructor Create(AOwner:TComponent); override; Destructor Destroy; override; Procedure Clear; Procedure SetProperties(const AMenu:TPopupMenu); published property Items:TInspectorItems read FItems write SetItems; property Color default clBtnFace; property ColCount default 2; property DefaultColWidth default 82; property DefaultRowHeight default 19; property FixedCols default 0; property GridLineWidth default 0; property RowCount default 1; property Header:TInspectorHeader read FHeader write SetHeader; {$IFDEF CLX} property ScrollBars default ssAutoBoth; {$ENDIF} end; implementation Uses TeeConst, TeePenDlg, Math, TeeEdiGrad, TeeBrushDlg, TeeEdiFont; { TInspectorItems } procedure TInspectorItem.Changed; begin if Assigned(FOnChange) then FOnChange(Self); end; constructor TInspectorItem.Create(Collection: TCollection); begin inherited; FVisible:=True; FEnabled:=True; if csDesigning in Inspector.ComponentState then RebuildInspector; end; Procedure TInspectorItem.RebuildInspector; begin if not (csLoading in Inspector.ComponentState) then Inspector.Rebuild; end; Function TInspectorItem.Inspector:TTeeInspector; begin result:=TInspectorItems(Collection).Inspector; end; procedure TInspectorItem.SetCaption(const Value: String); begin if FCaption<>Value then begin FCaption:=Value; RebuildInspector; end; end; procedure TInspectorItem.SetData(const Value: TObject); begin if FData<>Value then begin FData:=Value; if Style=iiSelection then with Inspector do if Item(Row)=Self then begin SetComboIndex; with IComboGrid do if ItemIndex=-1 then Self.Value:='' else Self.Value:=IComboGrid.Items[IComboGrid.ItemIndex]; end; end; end; procedure TInspectorItem.SetValue(const Value: Variant); begin FValue:=Value; Inspector.Invalidate; end; procedure TInspectorItem.SetVisible(const Value: Boolean); begin if FVisible<>Value then begin FVisible:=Value; RebuildInspector; end; end; Function TInspectorItem.StyleToInt:Integer; begin case FStyle of iiButton : result:=0; iiBoolean : result:=1; iiPen : result:=3; iiGradient : result:=4; iiColor : result:=2; iiInteger, iiDouble, iiString : result:=10; iiSelection : result:=0; iiFont : result:=7; iiImage : result:=8; iiBrush : result:=9; else result:=-1; end; end; { TInspectorItems } Function TInspectorItems.Get(Index:Integer):TInspectorItem; begin result:=TInspectorItem(inherited Items[Index]); end; Procedure TInspectorItems.Put(Index:Integer; Const Value:TInspectorItem); begin inherited Items[Index]:=Value; end; Function TInspectorItems.Add( AStyle:TInspectorItemStyle; Const ACaption:String; AData:TObject):TInspectorItem; var c : TNotifyEvent; begin c:=nil; result:=Add(AStyle,ACaption,{$IFDEF CLR}varNull{$ELSE}vaNull{$ENDIF},AData,c); end; Function TInspectorItems.Add( AStyle:TInspectorItemStyle; Const ACaption:String; AData:TObject; const AOnChange:TNotifyEvent):TInspectorItem; begin result:=Add(AStyle,ACaption,{$IFDEF CLR}varNull{$ELSE}vaNull{$ENDIF},AData,AOnChange); end; Function TInspectorItems.Add( AStyle:TInspectorItemStyle; Const ACaption:String; const AOnChange:TNotifyEvent):TInspectorItem; begin result:=Add(AStyle,ACaption,{$IFDEF CLR}varNull{$ELSE}vaNull{$ENDIF},nil,AOnChange); end; Function TInspectorItems.Add( AStyle:TInspectorItemStyle; Const ACaption:String; InitialValue:Variant; const AOnChange:TNotifyEvent):TInspectorItem; begin result:=Add(AStyle,ACaption,InitialValue,nil,AOnChange); end; Function TInspectorItems.Add( AStyle:TInspectorItemStyle; Const ACaption:String; InitialValue:Variant):TInspectorItem; var c : TNotifyEvent; begin c:=nil; result:=Add(AStyle,ACaption,InitialValue,nil,c); end; Function TInspectorItems.Add(AStyle:TInspectorItemStyle; Const ACaption:String; InitialValue:Variant; AData:TObject; const AOnChange:TNotifyEvent):TInspectorItem; begin result:=TInspectorItem(inherited Add); with result do begin FStyle:=AStyle; FCaption:=ACaption; FValue:=InitialValue; FData:=AData; FOnChange:=AOnChange; end; with Inspector do begin RowCount:=RowCount+1; Cells[0,RowCount-1]:=ACaption; Objects[0,RowCount-1]:=result; end; end; procedure TInspectorItems.Update(Item: TCollectionItem); begin if not (csLoading in Inspector.ComponentState) then Inspector.Rebuild; end; { TTeeInspector } Constructor TTeeInspector.Create(AOwner:TComponent); begin inherited; FHeader:=TInspectorHeader.Create; FHeader.Inspector:=Self; FHeader.Font.Color:=clNavy; FItems:=TInspectorItems.Create(Self,TInspectorItem); FItems.Inspector:=Self; Color:=clBtnFace; ColCount:=2; DefaultColWidth:=82; DefaultRowHeight:=19; FixedCols:=0; RowCount:=1; GridLineWidth:=0; Options:=[goFixedVertLine, goVertLine, goHorzLine, goColSizing, goThumbTracking]; {$IFDEF CLX} ScrollBars:=ssAutoBoth; {$ENDIF} Header.Update; CreateCombo; CreateEdit; end; Destructor TTeeInspector.Destroy; begin FItems.Free; FHeader.Free; inherited; end; Procedure TTeeInspector.SetItems(const Value:TInspectorItems); begin FItems.Assign(Value); end; procedure TTeeInspector.SetHeader(Const Value:TInspectorHeader); begin FHeader.Assign(Value); end; Procedure TTeeInspector.InternalSetHeader; begin { set header cells text } if Header.Visible then begin Cells[0,0]:=TeeMsg_Property; Cells[1,0]:=TeeMsg_Value; end else Rows[0].Clear; end; Procedure TTeeInspector.CreateEdit; begin { create edit box } IEditGrid:=TEditGrid.Create(Self); with IEditGrid do begin Name:='IEditGrid'; Visible:=False; OnChange:=Self.EditChange; OnKeyDown:=Self.EditKeyDown; end; end; Procedure TTeeInspector.SetComboIndex; begin with IComboGrid do begin if Items.Count=0 then with Item(Row) do if Assigned(FOnGetItems) then FOnGetItems(Item(Row),AddComboItem); ItemIndex:=Items.IndexOfObject(Item(Row).Data); end; end; Procedure TTeeInspector.CreateCombo; begin { create combobox } IComboGrid:=TComboFlatGrid.Create(Self); with IComboGrid do begin Name:='IComboGrid'; Style:=csDropDownList; DropDownCount:=8; ItemHeight:=21; Visible:=False; OnChange:=Self.ComboChange; end; end; Procedure TTeeInspector.Resize; begin inherited; if ColCount>0 then {$IFDEF CLX} if (not Assigned(Owner)) or (not (csReading in Owner.ComponentState)) then {$ENDIF} ColWidths[1]:=ClientWidth-ColWidths[0]; { resize combobox width (if visible) } DoPositionCombos(True); if (Row=0) and (RowCount>MinRow) then MoveColRow(1,MinRow,True,True); end; {$IFDEF CLX} Procedure TTeeInspector.SetParent(const Value: TWinControl); {$ELSE} Procedure TTeeInspector.SetParent(AParent: TWinControl); {$ENDIF} begin inherited; if (not (csDestroying in ComponentState)) and (not (csDesigning in ComponentState)) then begin IComboGrid.Parent:=Parent; IEditGrid.Parent:=Parent; end; end; procedure TTeeInspector.EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of TeeKey_Escape: begin HideCombos; SetFocus; end; TeeKey_Up: begin HideCombos; SetFocus; if Row>=MinRow then Row:=Row-1; end; TeeKey_Down: begin HideCombos; SetFocus; if Row<RowCount then Row:=Row+1; end; end; end; Function TTeeInspector.Item(ARow:Integer):TInspectorItem; begin result:=TInspectorItem(Objects[0,ARow]); end; procedure TTeeInspector.EditChange(Sender: TObject); begin { the inspector edit box has changed } with Item(Row) do begin if Style=iiString then Value:=IEditGrid.Text else Value:=StrToIntDef(IEditGrid.Text,0); Changed; end; end; procedure TTeeInspector.ComboChange(Sender: TObject); var tmpItem : TMenuItem; begin { the inspector combobox has changed, select subitem } if IComboGrid.Tag {$IFDEF CLR}<>nil{$ELSE}<>0{$ENDIF} then begin tmpItem:=TMenuItem(IComboGrid.Tag).Items[IComboGrid.ItemIndex]; tmpItem.Checked:=True; if Assigned(tmpItem.OnClick) then tmpItem.OnClick(tmpItem); end else with Item(Row) do begin Value:=IComboGrid.Items[IComboGrid.ItemIndex]; Data:=IComboGrid.Items.Objects[IComboGrid.ItemIndex]; Changed; end; end; Procedure TTeeInspector.Clear; begin Items.Clear; end; // A Menu can be used to fill the Inspector. Procedure TTeeInspector.SetProperties(const AMenu:TPopupMenu); var t : Integer; tmpSt : String; tmp : Integer; tmp2 : Integer; tmpInspectorItem : TInspectorItem; begin { set properties at inspector, if any } HideCombos; Items.Clear; tmp:=0; if Assigned(AMenu) then with AMenu do begin { call OnPopup to prepare items } if Assigned(OnPopup) then OnPopup(AMenu); RowCount:=Items.Count; { fill properties... } for t:=0 to Items.Count-1 do begin if {$IFDEF D5}(not Items[t].IsLine){$ELSE}(Items[t].Caption<>'-'){$ENDIF} and (Items[t].Enabled) and (Items[t].HelpContext<>5) then { 5 means "dont put at inspector" } begin tmpSt:=StripHotkey(Items[t].Caption); { remove trailing ellipsi "..." } While tmpSt[Length(tmpSt)]='.' do Delete(tmpSt,Length(tmpSt),1); Inc(tmp); tmpInspectorItem:=TInspectorItem(Self.Items.Add); with tmpInspectorItem do begin Caption:=tmpSt; Data:=TObject(AMenu.Items[t].Tag); IData:=AMenu.Items[t]; if Items[t].Count>0 then Style:=iiSelection; end; if Header.Visible then tmp2:=tmp else tmp2:=tmp-1; Cells[0,tmp2]:=tmpSt; Objects[1,tmp2]:=tmpInspectorItem; end; end; end; if Header.Visible then RowCount:=tmp+1 else RowCount:=tmp; { enable / disable inspector } Enabled:=Assigned(AMenu); { resize grid column } ColWidths[1]:=ClientWidth-ColWidths[0]; end; const TeeInspectorButtonSize=16; procedure TTeeInspector.DrawCell(ACol, ARow: Integer; ARect: TRect; AState: TGridDrawState); Function BooleanCell(ARow:Integer):Boolean; var tmp : TObject; begin { returns True if the inspector cell (menu item) is True } result:=False; tmp:=Item(ARow).IData; if Assigned(tmp) then begin if tmp is TMenuItem then result:=(tmp as TMenuItem).Checked; end else result:=Item(ARow).Value; end; Function CellType(ARow:Integer):Integer; var tmp : TInspectorItem; begin { returns the type of the cell if it points to a menu item } result:=-1; tmp:=Item(ARow); if Assigned(tmp) then if Assigned(tmp.IData) then begin if tmp.IData is TMenuItem then result:=(tmp.IData as TMenuItem).HelpContext end else result:=tmp.StyleToInt; end; Procedure DrawEllipsis; begin { draw small "ellipsis" buttons } with Canvas do begin {$IFDEF CLX} Pen.Color:=clBlack; Pen.Style:=psSolid; DrawPoint(ARect.Left+4,ARect.Bottom-6); DrawPoint(ARect.Left+6,ARect.Bottom-6); DrawPoint(ARect.Left+8,ARect.Bottom-6); {$ELSE} Pen.Handle:=TeeCreatePenSmallDots(clBlack); MoveTo(ARect.Left+4,ARect.Bottom-6); LineTo(ARect.Left+10,ARect.Bottom-6); {$ENDIF} end; end; Function CurrentItem:TMenuItem; begin { returns the Menu Item associated to current grid cell } result:=TMenuItem(Item(ARow).IData); end; Function CurrentItemCount:Integer; var tmp : TMenuItem; begin tmp:=CurrentItem; if Assigned(tmp) then result:=tmp.Count else result:=0; end; Function RectangleItem:TRect; begin result:=TeeRect(ARect.Right+2,ARect.Top+2,ARect.Right+40,ARect.Bottom-2); end; Procedure DrawText(Const S:String; LeftPos:Integer=-1); begin if LeftPos=-1 then LeftPos:=ARect.Right+2; Canvas.TextOut(LeftPos,ARect.Top,S); end; var tmp : Integer; tmpSt : String; tmpMiddle : Integer; tmpCanvas : TTeeCanvas3D; tmpGrad : TCustomTeeGradient; tmpFont : TTeeFont; tmpImage : TPicture; tmpItem : TMenuItem; tmpPen : TChartPen; tmpColor : TColor; tmpData : TObject; {$IFDEF CLX} QC : QColorH; {$ENDIF} tmpBrush : TChartBrush; begin { draw checkboxes and buttons at Property Inspector } { draw thin dotted grid lines } with Canvas do begin {$IFDEF CLX} Start; {$ENDIF} if goHorzLine in Options then begin {$IFNDEF CLX} Pen.Handle:=TeeCreatePenSmallDots(clDkGray); {$ENDIF} MoveTo(ARect.Left,ARect.Bottom-1); LineTo(ARect.Right-1,ARect.Bottom-1); end; end; if (ARow=0) and Header.Visible then begin { draw top row text } with Canvas do begin tmpColor:=Font.Color; Font.Assign(Header.Font); if gdSelected in AState then Font.Color:=tmpColor; TextOut(ARect.Left+2,ARect.Top+{$IFDEF CLX}2{$ELSE}1{$ENDIF},Cells[ACol,0]); end; end else if (ACol=1) and ValidRow(ARow) then { draw value cells } with Canvas do begin { resize rectangle to button / checkbox size } Inc(ARect.Left,2); Inc(ARect.Top,2); Dec(ARect.Bottom,1); ARect.Right:=ARect.Left+TeeInspectorButtonSize; if CellType(ARow)=2 then { color property } begin tmpItem:=CurrentItem; if Assigned(tmpItem) {$IFDEF CLR}and Assigned(tmpItem.Tag){$ENDIF} then Brush.Color:={$IFDEF CLR}Integer{$ELSE}TColor{$ENDIF}(tmpItem.Tag) else Brush.Color:={$IFDEF CLR}Integer{$ELSE}TColor{$ENDIF}(Item(ARow).Value); FillRect(TeeRect(ARect.Left,ARect.Top,ARect.Right-1,ARect.Bottom-1)); tmpSt:=ColorToString(Brush.Color); if Copy(tmpSt,1,2)='cl' then begin Brush.Style:=bsClear; DrawText(Copy(tmpSt,3,255)); end; end else if CellType(ARow)=10 then // String DrawText(Item(ARow).Value,ARect.Left) else begin { draw button or check-box } if CellType(ARow)=1 then { boolean ? } begin if Item(ARow).Enabled then tmpColor:=Color else tmpColor:=clSilver; TeeDrawCheckBox(ARect.Left,ARect.Top,Canvas,BooleanCell(ARow),tmpColor); end else if (CellType(ARow)<>-1) and (CurrentItemCount=0) and (Item(ARow).Style<>iiSelection) and (Item(ARow).Style<>iiString) and (Item(ARow).Style<>iiInteger) and (Item(ARow).Style<>iiDouble) then begin { button } {$IFDEF CLX} Pen.Style:=psSolid; FillRect(ARect); {$ELSE} Dec(ARect.Bottom); Dec(ARect.Right,2); tmp:=DFCS_BUTTONPUSH or DFCS_FLAT; DrawFrameControl(Handle,ARect,DFC_BUTTON,tmp); {$ENDIF} end; tmpMiddle:=(ARect.Top+ARect.Bottom) div 2; case CellType(ARow) of 0: if (CurrentItemCount=0) and (Item(ARow).Style<>iiSelection) then DrawEllipsis { button } else begin { combobox (submenu items) } tmpSt:=''; if CurrentItem<>nil then begin for tmp:=0 to CurrentItem.Count-1 do begin tmpItem:=CurrentItem.Items[tmp]; if tmpItem.RadioItem and tmpItem.Checked then begin tmpSt:=StripHotKey(tmpItem.Caption); break; end; end; end else tmpSt:=Item(ARow).Value; if tmpSt<>'' then DrawText(tmpSt,ARect.Left); end; 1: { boolean } begin { draw Yes/No } if BooleanCell(ARow) then tmpSt:=TeeMsg_Yes else tmpSt:=TeeMsg_No; DrawText(StripHotKey(tmpSt)); end; 3: begin { pen } DrawEllipsis; tmpPen:=TChartPen(Item(ARow).Data); if Assigned(tmpPen) then begin TeeSetTeePen(Pen,tmpPen,tmpPen.Color,Handle); MoveTo(ARect.Right+tmpPen.Width+1,tmpMiddle); LineTo(ARect.Right+30,tmpMiddle); end; end; 4: begin { gradient } DrawEllipsis; tmpGrad:=TCustomTeeGradient(Item(ARow).Data); if Assigned(tmpGrad) then if tmpGrad.Visible then begin tmpCanvas:=TTeeCanvas3D.Create; try tmpCanvas.ReferenceCanvas:=Canvas; tmpGrad.Draw(tmpCanvas,RectangleItem); finally tmpCanvas.Free; {$IFDEF CLX} with Canvas.Brush do begin QC:=QColor(clBtnFace); try QBrush_setColor(Handle, QC); finally QColor_destroy(QC); end; end; {$ENDIF} end; end else DrawText(TeeMsg_None); end; 6: begin { integer } // IntToStr(CurrentItem.HelpContext) DrawText(Item(ARow).Value); end; 7: begin { font } DrawEllipsis; tmpFont:=TTeeFont(Item(ARow).Data); if Assigned(tmpFont) then with tmpFont do begin Font.Color:=Color; Font.Name:=Name; Font.Style:=Style; end; DrawText(Font.Name); end; 8: begin { image } DrawEllipsis; tmpImage:=TPicture(Item(ARow).Data); if Assigned(tmpImage) and Assigned(tmpImage.Graphic) then tmpSt:=TeeMsg_Image else tmpSt:=TeeMsg_None; DrawText(tmpSt); end; 9: begin { pattern brush } DrawEllipsis; tmpData:=Item(ARow).Data; if Assigned(tmpData) then begin tmpBrush:=TChartBrush(tmpData); if Assigned(tmpBrush.Image.Graphic) then Brush.Bitmap:=tmpBrush.Image.Bitmap else Brush.Assign(tmpBrush); end; {$IFNDEF CLX} if (CurrentItem<>nil) then SetBkColor(Handle,ColorToRGB(StrToInt(CurrentItem.Hint))); // 6.01 {$ENDIF} FillRect(RectangleItem); Brush.Style:=bsSolid; {$IFNDEF CLX} if (CurrentItem<>nil) then SetBkColor(Handle,ColorToRGB(Self.Color)); // 6.01 {$ENDIF} end; end; end; end else inherited; {$IFDEF CLX} Canvas.Stop; {$ENDIF} end; procedure TTeeInspector.AddComboItem(Const S:String; AObject:TObject); begin IComboGrid.Items.AddObject(S,AObject); end; Procedure TTeeInspector.HideCombos; begin { remove previous combobox, if any } if Assigned(IComboGrid) then IComboGrid.Hide; { remove previous edit box, if any } if Assigned(IEditGrid) then IEditGrid.Hide; end; // Reload grid cells with Visible Items procedure TTeeInspector.Rebuild; var t : Integer; tmp : Integer; begin tmp:=0; for t:=0 to Items.Count-1 do if Items[t].Visible then Inc(tmp); RowCount:=Math.Max(1,tmp); if Header.Visible then begin tmp:=1; if Items.Count>0 then RowCount:=RowCount+1; end else tmp:=0; for t:=0 to Items.Count-1 do if Items[t].Visible then begin Cells[0,tmp]:=Items[t].Caption; Objects[0,tmp]:=Items[t]; Inc(tmp); end; end; procedure TTeeInspector.Loaded; begin inherited; Rebuild; if RowCount>MinRow then MoveColRow(1,MinRow,True,True); end; Function TTeeInspector.MinRow:Integer; begin if Assigned(FHeader) and Header.Visible then result:=1 else result:=0; end; procedure TTeeInspector.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var tmp : TObject; tmpR : TRect; t : Integer; tmpItem : TInspectorItem; begin { execute the inspector property (menu item associated) } inherited; if (Col=1) and ValidRow(Row) then { clicked at column 1? } begin HideCombos; { calculate rectangle for button or checkbox } tmpR:=CellRect(Col,Row); { cell contains selection of items? } tmpItem:=Item(Row); if Assigned(tmpItem) then begin if (tmpItem.Style=iiString) or (tmpItem.Style=iiInteger) or (tmpItem.Style=iiDouble) then begin with IEditGrid do begin { set Edit box position and size } DoPositionCombos(False); Text:=Self.Item(Row).Value; Show; SetFocus; end; end else if tmpItem.Style=iiSelection then begin { create combobox } with IComboGrid do begin tmp:=tmpItem.IData; Tag:={$IFDEF CLR}Variant{$ELSE}Integer{$ENDIF}(tmp); { menu item } { set ComboBox position and size } DoPositionCombos(False); { fill combobox and select item } Items.Clear; if Assigned(tmp) and (tmp is TMenuItem) then begin with TMenuItem(tmp) do for t:=0 to Count-1 do if Items[t].RadioItem then begin IComboGrid.Items.Add(StripHotKey(Items[t].Caption)); if Items[t].Checked then ItemIndex:=t; end; end else begin with Self.Item(Row) do if Assigned(FOnGetItems) then begin FOnGetItems(tmpItem,AddComboItem); SetComboIndex; end else ItemIndex:=-1; end; Show; end; end; tmpR.Right:=tmpR.Left+TeeInspectorButtonSize; { clicked on rectangle? } if PointInRect(tmpR,X,Y) then begin if tmpItem.Enabled then begin Case tmpItem.Style of iiBoolean: begin if tmpItem.Value{$IFDEF CLR}=True{$ENDIF} then tmpItem.Value:=False else tmpItem.Value:=True; end; iiColor: tmpItem.Value:=EditColor(Self,{$IFDEF CLR}TColor{$ENDIF}(tmpItem.Value)); iiFont: if tmpItem.Data is TTeeFont then EditTeeFontEx(Self,TTeeFont(tmpItem.Data)) else EditTeeFont(Self,TTeeFont(tmpItem.Data)); iiPen: EditChartPen(Self,TChartPen(tmpItem.Data)); iiBrush: EditChartBrush(Self,TChartBrush(tmpItem.Data)); iiGradient: EditTeeGradient(Self,TCustomTeeGradient(tmpItem.Data)); end; { repaing grid cell } if tmpItem.StyleToInt=0 then InvalidateCell(Col,Row); tmpItem.Changed; if Assigned(tmpItem.IData) and (tmpItem.IData is TMenuItem) then TMenuItem(tmpItem.IData).Click; { repaint clicked grid cell } InvalidateCell(Col,Row); end; end; end; end; end; procedure TTeeInspector.KeyDown(var Key: Word; Shift: TShiftState); begin { emulate mouse clicking when pressing the SPACE key } if Key=TeeKey_Space then With CellRect(1,Row) do MouseDown(mbLeft,[],Left+4,Top+4) else inherited; end; Procedure TTeeInspector.DoPositionCombos(WhenVisible:Boolean); var R : TRect; begin { set inspector combobox position and size } R:=CellRect(Col,Row); if Assigned(IComboGrid) and ((not WhenVisible) or IComboGrid.Visible) then with IComboGrid do begin Left:=Self.Left+R.Left+1; Width:=R.Right-R.Left+1; Top:=Self.Top+R.Top-1; end; if Assigned(IEditGrid) and ((not WhenVisible) or IEditGrid.Visible) then with IEditGrid do begin Left:=Self.Left+R.Left+1; Width:=R.Right-R.Left+1; Height:=R.Bottom-R.Top+1; Top:=Self.Top+R.Top; end; end; procedure TTeeInspector.TopLeftChanged; begin { reposition the inspector ComboBox (if visible) when scrolling } DoPositionCombos(True); end; Function TTeeInspector.ValidRow(ARow:Integer):Boolean; begin if Assigned(FHeader) and Header.Visible then result:=ARow>0 else result:=Assigned(Items) and (Items.Count>0); end; Function TTeeInspector.SelectCell(ACol, ARow: Integer): Boolean; begin { Avoid selecting the first grid column (when clicking) } result:= (ACol>0) and ValidRow(ARow) and inherited SelectCell(ACol,ARow); end; procedure TTeeInspector.MouseMove(Shift: TShiftState; X, Y: Integer); var tmpR : TRect; tmp : TGridCoord; tmpCursor : TCursor; tmpItem : TInspectorItem; begin tmpCursor:=crDefault; tmp:=MouseCoord(x,y); { mouse to grid Row,Col } if (tmp.X=1) and ValidRow(tmp.Y) then { at column 1? } begin tmpItem:=Item(tmp.Y); if Assigned(tmpItem) and (tmpItem.Style<>iiSelection) then begin tmpR:=CellRect(tmp.X,tmp.Y); { Row,Col to screen pixel Rect } tmpR.Right:=tmpR.Left+TeeInspectorButtonSize; { clicked on rectangle? } if PointInRect(tmpR,X,Y) and tmpItem.Enabled then tmpCursor:=crHandPoint; end; end; Cursor:=tmpCursor; end; { TComboFlatGrid } {$IFNDEF CLX} {$IFNDEF CLR} procedure TComboFlatGrid.CMFocusChanged(var Message: TCMFocusChanged); begin if Visible then if GetFocus<>Handle then Hide; end; {$ENDIF} {$ELSE} function TComboFlatGrid.EventFilter(Sender: QObjectH; Event: QEventH): Boolean; begin Result := inherited EventFilter(Sender, Event); if QEvent_type(Event)=QEventType_FocusOut then if Visible then Hide; end; {$ENDIF} { TEditGrid } {$IFNDEF CLX} {$IFNDEF CLR} procedure TEditGrid.CMFocusChanged(var Message: TCMFocusChanged); begin if Visible then if GetFocus<>Handle then Hide; end; {$ENDIF} {$ELSE} function TEditGrid.EventFilter(Sender: QObjectH; Event: QEventH): Boolean; begin Result := inherited EventFilter(Sender, Event); if QEvent_type(Event)=QEventType_FocusOut then if Visible then Hide; end; {$ENDIF} { TInspectorHeader } constructor TInspectorHeader.Create; begin inherited; FFont:=TTeeFont.Create(CanvasChanged); FVisible:=True; end; procedure TInspectorHeader.SetFont(const Value: TFont); begin FFont.Assign(Value); end; Procedure TInspectorHeader.CanvasChanged(Sender:TObject); begin Inspector.Invalidate; end; procedure TInspectorHeader.SetVisible(const Value: Boolean); begin if FVisible<>Value then begin FVisible:=Value; Inspector.InternalSetHeader; Inspector.Rebuild; end; end; procedure TInspectorHeader.Update; begin Inspector.InternalSetHeader; CanvasChanged(nil); end; destructor TInspectorHeader.Destroy; begin FFont.Free; inherited; end; end.
{ Maze builder class of the Lazarus Mazes program. For more detais on the implementation, see wikipedia: http://en.wikipedia.org/wiki/Maze_generation_algorithm#Recursive_backtracker Copyright (C) 2012 G.A. Nijland (eny @ lazarus forum http://www.lazarus.freepascal.org/) This source 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 code 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. A copy of the GNU General Public License is available on the World Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit MazeBuilderDepthFirst; {$mode objfpc}{$H+} interface uses Maze, Classes, SysUtils; type { TMazeBuilderDepthFirst } TMazeBuilderDepthFirst = class private Queue: TFPList; procedure ProcessCell(pCell: TMazeCell); function ExtractFromQueue(const pIndex: integer): TMazeCell; public function BuildMaze(const pWidth, pHeight: integer; const pStartRow: integer = 0; const pStartCol: integer = 0): TMaze; end; implementation { TMazeBuilderDepthFirst } // Retrieve the requested element from the backtrack queue and delete it // from the queue so it doesn't get processed anymore. function TMazeBuilderDepthFirst.ExtractFromQueue(const pIndex: integer): TMazeCell; begin result := TMazeCell(Queue[pIndex]); Queue.Delete(pIndex); end; // Scant the given cell for all neighbours and generate a new path // for those neighbours in a random way. procedure TMazeBuilderDepthFirst.ProcessCell(pCell: TMazeCell); // Check if the cell is valid and available for the next step procedure CheckForAvailability(const pCell: TMazeCell); begin if assigned(pCell) then if pCell.Tag = 0 then Queue.Add(pCell) end; var EOQ : integer; // End Of Queue cell: TMazeCell; // Next cell to visit dir : TDirection; // Loop control var begin // Set the cell as visited pCell.Tag := 1; // Remember where we are in the queue EOQ := Queue.Count; // Find all neighbours that have not been visited yet for dir in TDirection do CheckForAvailability(pCell.Neighbour[dir]); // Process all neighbours that were found (and added to the queue) while Queue.Count <> EOQ do begin // If only 1 then use that one else select one randomly. if EOQ = Queue.Count-1 then Cell := ExtractFromQueue(Queue.Count-1) else Cell := ExtractFromQueue(EOQ + random(Queue.Count - EOQ)); // Determine the direction and enable that direction, but do check if // this cell has not been processed in the mean time via another route! if Cell.Tag = 0 then begin for dir in TDirection do if Cell.Neighbour[dir] = pCell then begin Cell.CanGo[dir] := true; break end; // Process neighbours of this one ProcessCell(Cell); end; end; end; function TMazeBuilderDepthFirst.BuildMaze(const pWidth, pHeight: integer; const pStartRow: integer; const pStartCol: integer): TMaze; begin // Init the queue that will hold cells for backtracking Queue := TFPList.Create; // Create a new maze object and populate it result := TMaze.Create(pWidth, pHeight); result.SetStartCell(pStartRow, pStartCol); ProcessCell(result.StartCell); // Clean up Queue.Free; end; end.
unit WGBase; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ExtCtrls; type rVec2 = record x, y: double; end; pVoxel = ^rVoxel; rVoxel = record Child: array [0..3] of pVoxel; end; tGrid = array of array of double; tVectorArray = array[0..7] of rVec2; { cVectorGrid } cVectorGrid = class private GridDim: longword; fGrid: array of rVec2; function GetVec(i, j: integer): rVec2; procedure SetVec(i, j: integer; AValue: rVec2); public seed: longword; //property Grid[i, j: integer]: rVec2 read GetVec write SetVec; Grid: array[-20..+20, -20..+20] of rVec2; procedure GenVectors; function GetIDP(v: rVec2; GridSize: double): double; end; { cWorld } cWorld = class Pos: rVec2; Grid: tGrid; VectorGrid: cVectorGrid; TerSeed: longword; RootVoxel: pVoxel; constructor Create(Sx, Sy, Seed: longword); destructor Destroy; procedure GetTerrain(p1,p2: rVec2; VoxLvl: word); procedure Draw(pb: tPaintBox); end; const MinVoxelDim = 1; var World: cWorld; implementation uses Dialogs, Noises, Util; function max(a,b:integer): integer; begin if a>=b then Result:= a else Result:= b; end; function srand(seed: longword): double; //inline; begin randseed:= seed; Result:= random; end; operator + (a,b: rVec2): rVec2; begin Result.x:= a.x + b.x; Result.y:= a.y + b.y; end; operator - (a,b: rVec2): rVec2; begin Result.x:= a.x - b.x; Result.y:= a.y - b.y; end; function Vec2(x, y: single): rVec2; inline; begin Result.x:= x; Result.y:= y; end; { cVectorGrid } function cVectorGrid.GetVec(i, j: integer): rVec2; begin if (abs(i) > GridDim) or (abs(j) > GridDim) then begin setlength(fGrid, sqr(max(i,j)*2 +1)); end; end; procedure cVectorGrid.SetVec(i, j: integer; AValue: rVec2); begin end; procedure cVectorGrid.GenVectors; var i, j: Integer; begin for i:= low(Grid) to high(Grid) do for j:= low(Grid) to high(Grid) do begin Grid[i, j].x:= random - 0.5; Grid[i, j].y:= random - 0.5; normalize(Grid[i, j]); end; end; function cVectorGrid.GetIDP(v: rVec2; GridSize: double): double; //interpolated dot prod var i, gx, gy, dx, dy: integer; l: rVec2; GridVectors: tVectorArray; p: array [0..3] of double; begin gx:= round(v.x / GridSize); if gx >= 0 then dx:= 1 else dx:= -1; gy:= round(v.y / GridSize); if gy >= 0 then dy:= 1 else dy:= -1; GridVectors[4]:= Vec2(gx, gy) - v; //wrong square GridVectors[5]:= Vec2(gx + GridSize*dx, gy) - v; GridVectors[6]:= Vec2(gx + GridSize*dx, gy + GridSize*dy) - v; GridVectors[7]:= Vec2(gx, gy + GridSize*dy) - v; GridVectors[0]:= Grid[gx,gy]; GridVectors[1]:= Grid[gx + dx,gy]; GridVectors[2]:= Grid[gx + dx, gy + dy]; GridVectors[3]:= Grid[gx,gy + dy]; for i:= 0 to 7 do begin //GridVectors[i]:= Vec2(gx, gy) - v; Normalize(GridVectors[i]); end; {for i:= 0 to 3 do begin GridVectors[i].x:= srand(arg + i) - 0.5; GridVectors[i].y:= srand(arg + 4 + i) - 0.5; Normalize(GridVectors[i]); end; } l.x:= abs(v.x - gx * GridSize); l.y:= abs(v.y - gy * GridSize); if l.x > 1 then showmessage('PIZDOS'); for i:= 0 to 3 do begin p[i]:= DotProd(GridVectors[i], GridVectors[i + 4]); if p[i] > 1 then p[i]:= 1; //showmessage('PIZDOS'); end; p[0]:= SmoothStep(p[0], p[1], l.x); if abs(p[0]) > 1 then{ p[i]:= 1; } //showmessage('PIZDOS1'); p[1]:= SmoothStep(p[2], p[3], l.x); if abs(p[1]) > 1 then{ p[i]:= 1; } //showmessage('PIZDOS2'); Result:= SmoothStep(p[0], p[1], l.y); if abs(Result) > 1 then{ p[i]:= 1; } //showmessage('PIZDOS3'); end; { cWorld } constructor cWorld.Create(Sx, Sy, Seed: longword); var i, j: integer; v: rVec2; begin TerSeed:= Seed; //randomize; VectorGrid.Free; VectorGrid:= cVectorGrid.Create; VectorGrid.seed:= Seed; setlength(Grid, Sx, Sy); VectorGrid.GenVectors; for i:= 0 to Sx - 1 do for j:= 0 to Sy - 1 do begin v.x:= i / Sx - 0.5; v.y:= j / Sy - 0.5; {if p1 > p2 then //do u even need this begin p1:= p1 + p2; p2:= p1 - p2; p1:= p1 - p2; end; } { if p3 > p4 then begin p3:= p3 + p4; p4:= p3 - p4; p3:= p3 - p4; end; } { p1:= smoothstep(p1, p2, (v.x - cx)/seed); p2:= smoothstep(p3, p4, (v.y - cy)/seed);} { p1:= 2*(v.x - cx)*(p2-p1)/sx; p2:= 2*(v.y - cy)*(p4-p3)/sy;} Grid[i, j]:= VectorGrid.GetIDP(v, 0.025); end; end; destructor cWorld.Destroy; begin VectorGrid.Destroy; end; procedure cWorld.GetTerrain(p1, p2: rVec2; VoxLvl: word); begin end; procedure cWorld.Draw(pb: tPaintBox); var i, j: integer; r: int64; begin with pb, pb.Canvas do begin for i:= 0 to ClientWidth - 1 do begin for j:= 0 to ClientHeight - 1 do try r:= trunc(Grid[i,j]) mod $7FFFFFF ; Pixels[i, j]:= r; except on e: exception do begin e.Free; end; end; end; end; end; end.
unit IWTemplateProcessorHTML; interface uses Classes, IWApplication, IWLayoutMgr; type TIWTemplateProcessorHTMLTagType = (ttIntraWeb, ttBorland); TIWUnknownTagEvent = procedure(const AName: string; var VValue: string) of object; TIWTemplateFiles = class(TPersistent) protected FDefault: string; FIE: string; FNetscape6: string; // procedure AssignTo(ADest: TPersistent); override; published //@@ Species the default template to use. If none is specified, the form's name + .html is used. //Must contain only a filename, and no path information. property Default: string read FDefault write FDefault; //@@ Species the template to use for Internet Explorer. If none is specified Default is used. //Must contain only a filename, and no path information. property IE: string read FIE write FIE; //@@ Species the template to use for Netscape 6. If none is specified Default is used. //Must contain only a filename, and no path information. property Netscape6: string read FNetscape6 write FNetscape6; end; //@@ TIWTemplateProcessorHTML is a template processor that processes HTML templates. More //information on usage of this component is available in the IntraWeb manual. TIWTemplateProcessorHTML = class(TIWLayoutMgr) protected FMasterFormTag: Boolean; FOnUnknownTag: TIWUnknownTagEvent; FTagType: TIWTemplateProcessorHTMLTagType; FTemplates: TIWTemplateFiles; // function DoUnknownTag(const AName: string): string; procedure SetTemplates(const AValue: TIWTemplateFiles); public //@@ Able returns true if Enabled and the template file exists function Able: Boolean; override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Loaded; override; procedure Process(AStream: TStream; AControls: TStringList); override; procedure ProcessStream(AStream: TStream; ATemplateStream: TStream; AControls: TStringList); function TemplatePathname: string; published //@@ If the control being placed in the template is an input control or a button it must be //embedded in a FORM tag otherwise browsers typically ignore the control. Such controls that //require this are the listboxes, comboboxes, memos, edit boxes and buttons. URLs and other //clickable controls do not require this. One master FORM tag can be used or many. IntraWeb //will parse the document and retrieve data from any and all FORM sections. // //By Default IntraWeb will wrap the template output with a master FORM tag. However there are //HTML tags which are not valid inside of FORM tags and this may limit the flexibility of //certain templates. Another option is to put a FORM tag around every individual control but //this can lead to unwanted white space. IntraWeb's templates are designed to be easy to use, //however it is also a goal that they are flexible. To meet both of these goals the MastFormTag //property exists. Setting it to False will cause IntraWeb not to render a master FORM tag. //In this case you will need to insert your own FORM tags in your template to contain all //input and button controls. // //The FORM tag does not need to be name or have an ACTION attribute and in fact should not have //an ACTION attribute. The FORM tag should be of the following form: // //<FORM onSubmit="return FormDefaultSubmit();"> //Put your HTML and input control(s) here //</FORM> // //Using this form will ensure that the output from your template will work properly with //IntraWeb. It may also add unnecessary whitespace, so be careful. // //Note: Internet Explorer will render FORM controls without a valid FORM tag, but Netscape 4 //will not. This is because to Internet Explorer "patches" bad HTML on the fly while Netscape 4 //typically rejects bad HTML. Even though Internet Explorer will render such controls outside of //a FORM tag, IntraWeb will not recognize the data from such controls. property MasterFormTag: Boolean read FMasterFormTag write FMasterFormTag; //@@ If TagType = ttBorland, Tags will be processed as <#TagName#> instead of {%TagName%}. //These tags are harder to use wtih WSYWIG HTML editors, but are compatible with WebBroker / //WebSnap type templates. property TagType: TIWTemplateProcessorHTMLTagType read FTagType write FTagType; //@@ Specifies the filename(s) to use as the template in the templates directory. If left blank //the processor will attempt to us a file of the same name as the form with an .html extension //if one exists. property Templates: TIWTemplateFiles read FTemplates write SetTemplates; //@@ OnUnknownTag is fired if while processing the template the processor finds a tag of the //form {%TagName%} for which it cannot find a matching component. This allows you to implement //your own custom handling of extra tags that IW does not recognize. property OnUnknownTag: TIWUnknownTagEvent read FOnUnknownTag write FOnUnknownTag; end; implementation uses CopyPrsr, IWControl, IWServerControllerBase, IWTypes, IWGlobal, IWForm, IWControlInterface, SysUtils, SWStrings, SWSystem, IWHTMLTag; { TIWTemplateProcessorHTML } function TIWTemplateProcessorHTML.Able: Boolean; begin Result := False; if Enabled then begin Result := FileExists(TemplatePathname); end; end; constructor TIWTemplateProcessorHTML.Create(AOwner: TComponent); begin inherited; FMasterFormTag := True; FTemplates := TIWTemplateFiles.Create; end; destructor TIWTemplateProcessorHTML.Destroy; begin FreeAndNil(FTemplates); inherited; end; function TIWTemplateProcessorHTML.DoUnknownTag(const AName: string): string; begin Result := ''; if Assigned(OnUnknownTag) then begin OnUnknownTag(AName, Result); end; end; procedure TIWTemplateProcessorHTML.Loaded; var s: string; begin inherited Loaded; if not (csDesigning in ComponentState) then begin if Length(Templates.Default) = 0 then begin s := Copy(Owner.ClassName, 2, MaxInt) + '.html'; if Assigned(GServerController) and FileExists(GServerController.TemplateDir + s) then begin FTemplates.Default := s; end; end; end; end; procedure TIWTemplateProcessorHTML.Process(AStream: TStream; AControls: TStringList); var LSrcStream: TFileStream; begin LSrcStream := TFileStream.Create(TemplatePathname, fmOpenRead + fmShareDenyWrite); try ProcessStream(AStream, LSrcStream, AControls); finally FreeAndNil(LSrcStream); end; end; procedure TIWTemplateProcessorHTML.ProcessStream(AStream, ATemplateStream: TStream; AControls: TStringList); var i: Integer; LControl: TIWControl; LHeaderHasBeenWritten: Boolean; LParser: TCopyParser; LStream: TIWStream; LTagName: string; LTagParams: string; LName: string; LTerminated: Boolean; LWebApp: TIWApplication; function ProcessTag(AParser: TCopyParser; AControls: TStringList; const AEndTagChar1: Char; const AEndTagChar2: Char): string; var LCtrlName: string; LIControl: IIWControl; begin Result := ''; with AParser do begin SkipToken(True); LCtrlName := TokenString; if Length(LCtrlName) > 0 then begin i := AControls.IndexOf(LCtrlName); if i > -1 then begin LControl := TIWControl(AControls.Objects[i]); LIControl := LControl; if Assigned(LControl.HTML) then begin LControl.HTML.AddStringParam('CLASS', LControl.RenderCSSClass); // relative positioning is not used from IW controls LControl.HTML.AddStringParam('STYLE', {'position:relative;' + }LControl.RenderStyle + LControl.HTML.Params.Values['STYLE']); LControl.HTML.AddStringParam('ID', LControl.HTMLName); Result := LControl.MakeHTMLTag(LControl.HTML); if not MasterFormTag then begin if LIControl.SupportsInput then begin with FormTag.Contents.AddTag('INPUT') do begin AddStringParam('TYPE', 'HIDDEN'); AddStringParam('NAME', LControl.HTMLName); AddStringParam('ID', LControl.HTMLName); end; end; end; end; end else begin Result := DoUnknownTag(LCtrlName); end; end; SkipToken(True); if TagType <> ttBorland then begin CheckToken(AEndTagChar1); SkipToken(True); end; CheckToken(AEndTagChar2); SkipToken(True); end; end; procedure SkipAndOutput(AParser: TCopyParser); begin with AParser do begin CopyTokenToOutput; SkipToken(True); end; end; procedure SkipOverNextHTMLTag(AParser: TCopyParser); begin with AParser do begin SkipToToken('<'); SkipToken(True); CheckToken('/'); SkipToToken('>'); SkipToken(True); end; end; procedure WriteHead; begin LHeaderHasBeenWritten := True; LStream.Write('<HEAD>' + EOL + HeadContent); WriteScriptSection(LStream); end; begin LStream := TIWStream(AStream); LParser := TCopyParser.Create(ATemplateStream, LStream); try LHeaderHasBeenWritten := false; LTerminated := false; if Assigned (GSetWebApplicationThreadVar) then begin LWebApp := GSetWebApplicationThreadVar(nil); GSetWebApplicationThreadVar(LWebApp); LTerminated := Assigned(LWebApp) and LWebApp.Terminated; end; if not LTerminated and not MasterFormTag then begin JavaScript := JavaScript + 'var SubmitClickConfirmOriginal = SubmitClickConfirm;' + EOL + 'SubmitClickConfirm = SubmitClickConfirm_Template;'; end; with LParser do begin while Token <> toEOF do begin case Token of '<': begin // SkipToken first in case of short circuit if (SkipToken(True) = '#') and (TagType = ttBorland) then begin LStream.Write(ProcessTag(LParser, AControls, '#', '>')); end else begin // <!DOCTYPE - etc. this is why TokenString + SkipTo LTagName := TokenString; // Must be separate from above, SkipToToken modfies result value of TokenString LTagName := LTagName + SkipToToken('>'); //SkipToken(True); Removed. Fixes CR bug. 26/04 // i := Pos(' ', LTagName); if i > 0 then begin LTagParams := Copy(LTagName, i + 1, MaxInt); SetLength(LTagName, i - 1); LTagParams := StringReplace(LTagParams, '../files/', URLBase + '/files/' , [rfReplaceAll, rfIgnoreCase]); end else begin LTagParams := ''; end; if AnsiSameText(LTagName, 'BODY') then begin while Length(LTagParams) > 0 do begin LName := Trim(Fetch(LTagParams, '"')); LName := UpperCase(Copy(LName, 1, Length(LName) - 1)); if LName <> '' then begin if AnsiSameText(LName, 'BGCOLOR') then begin if BodyTag.Params.Values['BGCOLOR'] = '' then begin BodyTag.AddStringParam('BGCOLOR', Fetch(LTagParams, '"')); end; end else begin if AnsiSameText(LName, 'OnLoad') then begin InitProc := InitProc + Fetch(LTagParams, '"') + ';'; end else begin if AnsiSameText(LName, 'OnBlur') then begin BodyTag.Params.Values[LName] := BodyTag.Params.Values[LName] + Fetch(LTagParams, '"') + ';'; end else begin BodyTag.Params.Values[LName] := Fetch(LTagParams, '"'); end; end; end; end; end; if not LHeaderHasBeenWritten then begin WriteHead; end; LStream.Write(BodyTag.RenderCloseTag(false){ + EOL + BodyContent.Render}); SkipToken(True); if MasterFormTag and not LTerminated then begin FormTag.AddStringParam('onSubmit', 'return FormDefaultSubmit();'); LStream.Write(FormTag.RenderCloseTag(false)); // SkipToken(True);// Added. Fixes CR bug. 26/04 {LStream.Write(FormContent); LStream.Write('</FORM>');} end; end else if AnsiSameText(LTagName, '/BODY') then begin {if MasterFormTag then begin // LStream.Write(FormTag.RenderCloseTag(false)); // SkipToken(True);// Added. Fixes CR bug. 26/04 // LStream.Write(FormContent); LStream.Write('</FORM>'); end;} if not LTerminated then begin if not MasterFormTag then begin FormTag.AddStringParam('onSubmit', 'return FormDefaultSubmit();'); LStream.Write(FormTag.RenderCloseTag(false)); // SkipToken(True);// Added. Fixes CR bug. 26/04 end; LStream.Write(FormContent); LStream.Write('</FORM>' + EOL); end; LStream.Write('</BODY>'); SkipToken(True); // Added. Fixes CR bug. 26/04 end else if AnsiSameText(LTagName, 'HEAD') then begin if not LHeaderHasBeenWritten then begin WriteHead; end; SkipToken(True); end else if AnsiSameText(LTagName, 'TITLE') then begin if Length(Title) > 0 then begin SkipOverNextHTMLTag(LParser); LStream.Write('<TITLE>' + Title + '</TITLE>' + EOL); end else begin LStream.Write('<TITLE>'); SkipToken(True); // Added. Fixes CR bug. 26/04 end; end else begin LStream.Write('<' + Trim(LTagName + ' ' + LTagParams) + '>'); SkipToken(True);// Added. Fixes CR bug. 26/04 end; end; end; '{': begin // SkipToken first in case of short circuit if (SkipToken(True) = '%') and (TagType = ttIntraWeb) then begin LStream.Write(ProcessTag(LParser, AControls, '%', '}')); end else begin LStream.Write('{'); SkipAndOutput(LParser); end; end else begin SkipAndOutput(LParser); end; end; end; end; finally FreeAndNil(LParser); end; end; procedure TIWTemplateProcessorHTML.SetTemplates(const AValue: TIWTemplateFiles); begin FTemplates.Assign(AValue); end; function TIWTemplateProcessorHTML.TemplatePathname: string; begin if (FBrowser = brNetscape6) and (Length(Templates.Netscape6) > 0) then begin Result := Templates.Netscape6; end else if (FBrowser = brIE) and (Length(Templates.IE) > 0) then begin Result := Templates.IE; end else if Length(Templates.Default) > 0 then begin Result := Templates.Default; end; Result := GServerController.TemplateDir + Result; end; { TIWTemplateFiles } procedure TIWTemplateFiles.AssignTo(ADest: TPersistent); begin if ADest is TIWTemplateFiles then begin with TIWTemplateFiles(ADest) do begin Default := Self.Default; IE := Self.IE; Netscape6 := Self.Netscape6; end; end else begin inherited; end; end; end.
unit ACBrEscPosChequeToshiba; interface uses Classes, ACBrPosPrinter, {$IFDEF MSWINDOWS} Dialogs, {$ENDIF} SysUtils; type TACBrEscPosChequeToshiba = class(TACBrEscPosChequeClass) private type TPrintStatus = (psChequePosicionado); TPrintStatusSets = set of TPrintStatus; function InternoChequeConcluido: boolean; procedure LigaEstacaoCheque; procedure DesligaEstacaoCheque; procedure EjetarDocumento; protected FXML: String; FVirarCheque: boolean; FUltimoStatus: TPrintStatusSets; function GetChequeProntoClass: boolean; override; function LerStatus: TPrintStatusSets; public constructor create(AOwner: TACBrPosPrinter); override; function PosPrinter: TACBrPosPrinter; Procedure ImprimeCheque(Banco: String; Valor: Double; Favorecido, Cidade: String; Data: TDateTime; Observacao: String = ''); override; Procedure CancelaImpressaoCheque; override; Function LerCMC7: AnsiString; override; end; implementation uses ACBrUtil, IniFiles, ACBrExtenso, DateUtils, ACBrConsts; var FPCheque: TACBrEscPosChequeToshiba; const TAMANHO_MAXIMO_LINHA_CHEQUE_FontB = 85; TAMANHO_MAXIMO_LINHA_CHEQUE_FontA = 68; type TStringHelperX = record helper for String function asInteger: integer; function Max(value: integer): integer; end; TPosicaoCheque = record case boolean of true: (ColValor: array [1 .. 2] of Ansichar; LinValor: array [1 .. 2] of Ansichar; ColExt1: array [1 .. 2] of Ansichar; LinExt1: array [1 .. 2] of Ansichar; ColExt2: array [1 .. 2] of Ansichar; LinExt2: array [1 .. 2] of Ansichar; ColFavor: array [1 .. 2] of Ansichar; LinFavor: array [1 .. 2] of Ansichar; ColCidade: array [1 .. 2] of Ansichar; LinCidade: array [1 .. 2] of Ansichar; ColDia: array [1 .. 2] of Ansichar; ColMes: array [1 .. 2] of Ansichar; ColAno: array [1 .. 2] of Ansichar; ColMsg: array [1 .. 2] of Ansichar; LinMsg: array [1 .. 2] of Ansichar); false: (texto: array [1 .. 50] of Ansichar); end; procedure TACBrEscPosChequeToshiba.ImprimeCheque(Banco: String; Valor: Double; Favorecido, Cidade: String; Data: TDateTime; Observacao: String); var pos: TPosicaoCheque; extenso: TACBrExtenso; sExtenso: string; sExtenso1: string; sExtenso2: string; FMatriz: Array [1 .. 14] of string; procedure CarregaPosicao; var x: integer; sPos: string; begin // inicializa a matriz do cheque; for x := Low(FMatriz) to High(FMatriz) do FMatriz[x] := PadLeft('', TAMANHO_MAXIMO_LINHA_CHEQUE_FontA, ' '); with TIniFile.create(ArquivoPosCheque) do try sPos := readString('FormatoCheque', Banco, ''); if sPos = '' then sPos := readString('FormatoCheque', '000', ''); finally free; end; if sPos = '' then begin sPos := '58,02,12,03,01,06,05,07,35,09,52,58,68,25,10'; end; WriteLog(ArqLog, 'Layout de cheque<' + Banco + '> "' + sPos + '" em: ' + ArquivoPosCheque); sPos := StringReplace(sPos, ',', '', [rfReplaceAll]); sPos := copy(sPos, 1, sizeof(pos.texto)); FillChar(pos, sizeof(pos), #0); for x := 1 to length(sPos) do if sPos[x] <> ';' then pos.texto[x] := Ansichar(sPos[x]); end; procedure FillMatriz(ALin: String; ACol: String; texto: string); var x, i, mx: integer; LLin,LCol:integer; begin if texto = '' then exit; LLin := strToIntDef(ALin,0); LCol := strToIntDef(ACol,0)-2; if LLin < 1 then LLin := 1; if LCol < 1 then LCol := 1; if (LCol+length(texto)) > TAMANHO_MAXIMO_LINHA_CHEQUE_FontA then LCol := TAMANHO_MAXIMO_LINHA_CHEQUE_FontA - length(texto); mx := LCol + length(texto); if mx > TAMANHO_MAXIMO_LINHA_CHEQUE_FontA then mx := TAMANHO_MAXIMO_LINHA_CHEQUE_FontA; i := 1; for x := LCol to mx do begin FMatriz[LLin][x] := texto[i]; inc(i); end; end; procedure quebraLinhaExtenso(s: string; ATamanhoExt1: integer); var rst: string; x: integer; mx: integer; begin mx := ATamanhoExt1; rst := copy(s, 1, mx); if (length(s) > mx) then begin for x := length(rst) downto 1 do begin if rst[x] = ' ' then begin rst := copy(s, 1, x - 1); break; end; end; end; sExtenso1 := rst; sExtenso2 := ''; if rst <> s then begin sExtenso2 := copy(s, length(sExtenso1) + 1); end; end; var cmd: string; procedure ImprimirCmd(var texto: AnsiString); begin FPosPrinter.ImprimirCmd(texto); end; var desligar: boolean; function mask(c: char): string; var i: integer; begin result := '1'; for i := 1 to 8 do result := result + PadRight(c, 9, c) + inttoStr(i); result := result + c + c + c + c; end; const fontB = ESC + '!' + #2; fontA = ESC + '!' + #0; var s: string; i: integer; begin CarregaPosicao; desligar := CheckAtivar; try //FPosPrinter.ImprimirCmd(FPosPrinterClass.cmd.Zera); LigaEstacaoCheque; try FPosPrinter.ImprimirCmd(ESC + '!' + #1); // monta o extenso extenso := TACBrExtenso.create(nil); try sExtenso := TiraAcentos(extenso.ValorToTexto(Valor)); finally extenso.free; end; quebraLinhaExtenso('###' + sExtenso + '###', TAMANHO_MAXIMO_LINHA_CHEQUE_FontA - StrToIntDef(pos.ColExt1, 10)); if Observacao <> '' then FillMatriz(pos.LinMsg, pos.ColMsg, Observacao); FillMatriz(pos.LinCidade, pos.ColCidade, Cidade); FillMatriz(pos.LinCidade, pos.ColDia, dayOf(Data).ToString); FillMatriz(pos.LinCidade, pos.ColMes, formatDateTime('mmmm', Data)); FillMatriz(pos.LinCidade, pos.ColAno, formatDateTime('YY', Data)); // manda favorecido FillMatriz((StrToInt(pos.LinFavor)).ToString, pos.ColFavor, Favorecido); FillMatriz((StrToInt(pos.LinExt2)).ToString, pos.ColExt2, sExtenso2); FillMatriz((StrToInt(pos.LinExt1)).ToString, pos.ColExt1, sExtenso1); // manda o valor s := FormatFloat('0.00', Valor); FillMatriz((StrToInt(pos.LinValor)).ToString, pos.ColValor, s); for i := high(FMatriz) downto low(FMatriz) do if trim(FMatriz[i]) = '' then FPosPrinter.ImprimirCmd(LF) else FPosPrinter.ImprimirCmd(FMatriz[i]); FPosPrinter.ImprimirCmd(FPosPrinterClass.cmd.FonteNormal); finally EjetarDocumento; end; finally CheckDesativar(not desligar); end; end; // *) procedure TACBrEscPosChequeToshiba.CancelaImpressaoCheque; var ret: AnsiString; begin inherited; DesligaEstacaoCheque; end; function TACBrEscPosChequeToshiba.InternoChequeConcluido: boolean; var ret: AnsiString; begin CheckAtivar; try result := false; LerStatus; result := not(psChequePosicionado in FUltimoStatus); finally CheckDesativar(); end; end; constructor TACBrEscPosChequeToshiba.create(AOwner: TACBrPosPrinter); begin inherited; FPCheque := self; // ArquivoPosCheque := ExtractFilePath(ParamStr(0)) + 'checkLayouts.xml'; // arquivo fornecido pela toshiba end; procedure TACBrEscPosChequeToshiba.DesligaEstacaoCheque; begin CheckAtivar; try // #define CMD_SET_PRINT_SATATION_CR "\x1B\x63\x30\x02" FPosPrinter.ImprimirCmd(#$1B + #$63 + #$30 + #$2); finally CheckDesativar(); end; end; procedure TACBrEscPosChequeToshiba.EjetarDocumento; begin LigaEstacaoCheque; try FPosPrinter.ImprimirCmd(ESC + #$69); finally DesligaEstacaoCheque; end; end; function TACBrEscPosChequeToshiba.GetChequeProntoClass: boolean; var ret: AnsiString; desligar: boolean; begin desligar := CheckAtivar; try result := false; LerStatus; if psChequePosicionado in FUltimoStatus then begin result := true; end; finally CheckDesativar(not desligar); end; end; function TACBrEscPosChequeToshiba.LerCMC7: AnsiString; var LRetorno: AnsiString; LSair: boolean; LTimeOut: TDateTime; LLenBytes: integer; LControlePorta: boolean; desligar: boolean; begin if not ChequePronto then exit; desligar := CheckAtivar; try LControlePorta := FPosPrinter.controlePorta; FPosPrinter.controlePorta := false; FPosPrinter.device.Limpar; // LigaEstacaoCheque; try FPosPrinter.ImprimirCmd(ESC + 'I'); // Read check paper LSair := false; LTimeOut := IncMilliSecond(now, 5000); LLenBytes := 0; LRetorno := ''; repeat if FPosPrinter.device.BytesParaLer > 0 then begin LRetorno := LRetorno + FPosPrinter.device.LeString(100); if length(LRetorno) <> LLenBytes then begin LTimeOut := IncMilliSecond(now, 5000); LLenBytes := length(LRetorno); end; end; if ((LLenBytes > 30) and (LRetorno[length(LRetorno)] in [#0, 'a'])) then break; if LTimeOut < now then LSair := true; until LSair; if (length(LRetorno) > 0) then begin result := StringReplace(copy(LRetorno, length(LRetorno) - 35, 36), ' ', '', [rfReplaceAll]); if FVirarCheque then // comentado para nao virar o cheque exit; FPosPrinter.ImprimirCmd(ESC + '5'); end; (* case 19: { unsigned int bytesWritten = 0; unsigned char cmdEjetarDocumento[2] = {0x1B, 0x69}; unsigned char cmdEstacaoCheque[4] = {0x1B, 0x63, 0x30, 0x08}; //SELECIONA ESTACAO ret = _Write(cmdEstacaoCheque, sizeof(cmdEstacaoCheque), &bytesWritten); //EJETAR DOCUMENTO ret = _Write(cmdEjetarDocumento, sizeof(cmdEjetarDocumento), &bytesWritten); if(ret == 0) { printf(">> Funcao Executada com Sucesso (%d) <<\n\n", ret); }else { printf(">> Erro na Execucao da Funcao (%d) <<\n\n", ret); } } break; *) EjetarDocumento; finally FPosPrinter.controlePorta := LControlePorta; end; finally CheckDesativar(not desligar); end; end; function TACBrEscPosChequeToshiba.LerStatus: TPrintStatusSets; var statusByte: array [1 .. 16] of byte; nBytes: integer; B: AnsiString; procedure convToBytes(dados: string; var bytes: array of byte); var i, n: integer; begin n := 0; for i := low(dados) to high(dados) do begin bytes[n] := ord(dados[i]); inc(n); end; end; begin CheckAtivar; try result := []; FillChar(statusByte, sizeof(statusByte), #0); B := FPosPrinter.TxRx(DLE + ENQ + '4', 2, 100); // na 1NR retorna 10, na 2NR retorna 16 ? if length(B) <> 2 then raise exception.create('Esperava 2 chrs'); nBytes := ((ord(B[1]) * 16) + ord(B[2]) - 2); B := FPosPrinter.device.LeString(100, nBytes); convToBytes(copy(B, 1, nBytes), statusByte); if not TestBit(statusByte[2], 1) then result := result + [psChequePosicionado]; FUltimoStatus := result; finally CheckDesativar(); end; end; procedure TACBrEscPosChequeToshiba.LigaEstacaoCheque; begin CheckAtivar; try FPosPrinter.ImprimirCmd(#$1B + #$63 + #$30 + #$8); // #define CMD_SET_PRINT_SATATION_DI_LANDSCAPE "\x1B\x63\x30\x08" // #define CMD_SET_PRINT_SATATION_DI_PORTRAIT "\x1B\x63\x30\x04" finally CheckDesativar(); end; end; function TACBrEscPosChequeToshiba.PosPrinter: TACBrPosPrinter; begin result := FPosPrinter; end; { TStringHelperX } function TStringHelperX.asInteger: integer; begin result := StrToIntDef(self, 0); end; function TStringHelperX.Max(value: integer): integer; begin result := asInteger; if result > value then result := value; end; end.
unit MapLegalAddressSelectDialogUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons; type TMapLegalAddressSelectDialog = class(TForm) OKButton: TBitBtn; CancelButton: TBitBtn; Label1: TLabel; LegalAddressEdit: TEdit; NumberGroupBox: TGroupBox; Label9: TLabel; Label10: TLabel; StartNumberEdit: TEdit; AllNumbersCheckBox: TCheckBox; ToEndOfNumbersCheckBox: TCheckBox; EndNumberEdit: TEdit; procedure AllNumbersCheckBoxClick(Sender: TObject); procedure ToEndOfNumbersCheckBoxClick(Sender: TObject); procedure OKButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } LegalAddress : String; LegalAddressNumberStart, LegalAddressNumberEnd : String; AllLegalAddressNumbers, ToEndOfLegalAddressNumbers : Boolean; end; var MapLegalAddressSelectDialog: TMapLegalAddressSelectDialog; implementation {$R *.DFM} uses WinUtils; {==========================================================} Procedure TMapLegalAddressSelectDialog.AllNumbersCheckBoxClick(Sender: TObject); begin If AllNumbersCheckBox.Checked then begin ToEndofNumbersCheckBox.Checked := False; ToEndofNumbersCheckBox.Enabled := False; StartNumberEdit.Text := ''; StartNumberEdit.Enabled := False; StartNumberEdit.Color := clBtnFace; EndNumberEdit.Text := ''; EndNumberEdit.Enabled := False; EndNumberEdit.Color := clBtnFace; end else EnableSelectionsInGroupBoxOrPanel(NumberGroupBox); end; {AllNumbersCheckBoxClick} {=============================================================} Procedure TMapLegalAddressSelectDialog.ToEndOfNumbersCheckBoxClick(Sender: TObject); begin If ToEndOfNumbersCheckBox.Checked then begin EndNumberEdit.Text := ''; EndNumberEdit.Enabled := False; EndNumberEdit.Color := clBtnFace; end else EnableSelectionsInGroupBoxOrPanel(NumberGroupBox); end; {ToEndOfNumbersCheckBoxClick} {=========================================================} Procedure TMapLegalAddressSelectDialog.OKButtonClick(Sender: TObject); var Continue : Boolean; begin Continue := True; If (Trim(LegalAddressEdit.Text) = '') then begin Continue := False; MessageDlg('Please enter a legal address street to search for.', mtError, [mbOK], 0); LegalAddressEdit.SetFocus; end; {If (Trim(LegalAddressEdit.Text) = '')} If Continue then begin If ((Trim(StartNumberEdit.Text) = '') and (Trim(EndNumberEdit.Text) = '') and (not ToEndOfNumbersCheckBox.Checked)) then AllNumbersCheckBox.Checked := True; AllLegalAddressNumbers := AllNumbersCheckBox.Checked; ToEndOfLegalAddressNumbers := ToEndOfNumbersCheckBox.Checked; LegalAddress := LegalAddressEdit.Text; If not AllLegalAddressNumbers then begin LegalAddressNumberStart := StartNumberEdit.Text; LegalAddressNumberEnd := EndNumberEdit.Text; end; {If not AllLegalAddressNumbers} ModalResult := mrOK; end; {If Continue} end; {OKButtonClick} end.
unit classesArbeitsmittel; interface uses System.SysUtils, System.StrUtils, Vcl.Dialogs, System.UITypes, classes, classesPersonen, classesTelefonie, 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, Vcl.StdCtrls, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Mask, Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids; type TArbeitsmittelHelper = class private SqlQuery: TFDQuery; public function gibArbeitsmittelKlassen(): TStringList; function gibArbeitsmittelTypen(): TStringList; constructor create(Connection: TFDConnection); end; TGegenstand = class private SqlQuery : TFDQuery; FId : integer; FBezeichnung: string; procedure IdErmitteln(); public property Id : integer read FId write FId; property Bezeichnung: string read FBezeichnung write FBezeichnung; function Loeschen(): boolean; const TABLE_NAME: string = ''; end; type THersteller = class(TGegenstand) private public constructor create(Bezeichnung: string; Connection: TFDConnection); constructor CreateFromId(Id: integer; Connection: TFDConnection); procedure Speichern(); procedure Aktualisieren(); const TABLE_NAME: string = 'Hersteller'; end; type TArbeitsmittelKlasse = class(TGegenstand) private procedure IdErmitteln(); public constructor create(Bezeichnung: string; Connection: TFDConnection); constructor CreateFromId(Id: integer; Connection: TFDConnection); function Speichern(): boolean; function Aktualisieren(): boolean; const TABLE_NAME: string = 'ArbeitsmittelKlasse'; end; type TArbeitsmittelTyp = class(THersteller) private FHersteller : THersteller; FArbeistmittelKlasse: TArbeitsmittelKlasse; FHatSim : boolean; procedure IdErmitteln(); public property Hersteller : THersteller read FHersteller write FHersteller; property ArbeitsmittelKlasse: TArbeitsmittelKlasse read FArbeistmittelKlasse write FArbeistmittelKlasse; property HatSim : boolean read FHatSim write FHatSim; constructor create(Bezeichnung: string; Hersteller: THersteller; klasse: TArbeitsmittelKlasse; HatSim: boolean; Connection: TFDConnection); constructor CreateFromId(Id: integer; Connection: TFDConnection); procedure Speichern(); procedure Aktualisieren(); const TABLE_NAME: string = 'ArbeitsmittelTyp'; end; type TArbeitsmittel = class(THersteller) private FArbeitsmittelTyp: TArbeitsmittelTyp; FImei : Variant; FSerienNummer : Variant; FSimKarte : TSimKarte; procedure setImei(Value: Variant); public property ArbeitsmittelTyp: TArbeitsmittelTyp read FArbeitsmittelTyp write FArbeitsmittelTyp; property Imei : Variant read FImei write setImei; property SerienNummer : Variant read FSerienNummer write FSerienNummer; property SimKarte : TSimKarte read FSimKarte write FSimKarte; constructor create(Bezeichnung: string; typ: TArbeitsmittelTyp; Imei, serienNr: Variant; Connection: TFDConnection; sim: TSimKarte = nil); constructor CreateFromId(Id: integer; Connection: TFDConnection); procedure Speichern(); procedure Aktualisieren(); const TABLE_NAME: string = 'Arbeitsmittel'; end; implementation { TGegenstand } procedure TGegenstand.IdErmitteln; begin with self.SqlQuery, SQL do begin Clear; Add('SELECT Id FROM ' + self.TABLE_NAME + ' ORDER BY Id DESC LIMIT 1'); end; self.SqlQuery.Open; if self.SqlQuery.RecordCount = 1 then self.Id := self.SqlQuery.FieldByName('Id').AsInteger; self.SqlQuery.Close end; function TGegenstand.Loeschen(): boolean; begin result := false; if self.Id <> 0 then begin with self.SqlQuery, SQL do begin Clear; Add('DELETE FROM ' + self.TABLE_NAME + ' WHERE Id = :id'); ParamByName('id').Value := self.Id; end; self.SqlQuery.ExecSQL; end; if self.SqlQuery.RowsAffected = 1 then result := true; end; { THersteller } procedure THersteller.Aktualisieren; begin if self.Id <> 0 then begin with self.SqlQuery, SQL do begin Clear; Add('UPDATE ' + self.TABLE_NAME); Add('SET Bezeichnung = :name'); Add('WHERE Id = :id'); ParamByName('name').Value := self.Bezeichnung; ParamByName('id').Value := self.Id; end; self.SqlQuery.ExecSQL; end; end; constructor THersteller.create(Bezeichnung: string; Connection: TFDConnection); begin self.Id := 0; self.Bezeichnung := Bezeichnung; self.SqlQuery := TFDQuery.create(nil); self.SqlQuery.Connection := Connection; end; constructor THersteller.CreateFromId(Id: integer; Connection: TFDConnection); begin self.SqlQuery := TFDQuery.create(nil); self.SqlQuery.Connection := Connection; with self.SqlQuery, SQL do begin Clear; Add('SELECT * FROM ' + self.TABLE_NAME + ' WHERE Id = :id'); ParamByName('id').Value := Id; Open; end; if self.SqlQuery.RecordCount = 1 then begin self.Id := self.SqlQuery.FieldByName('Id').AsInteger; self.Bezeichnung := self.SqlQuery.FieldByName('Bezeichnung').AsString; end; self.SqlQuery.Close; end; procedure THersteller.Speichern; begin if self.Id = 0 then begin with self.SqlQuery, SQL do begin Clear; Add('INSERT INTO ' + self.TABLE_NAME + ' (Bezeichnung)'); Add('VALUES (:name)'); ParamByName('name').Value := self.Bezeichnung; end; self.SqlQuery.ExecSQL; self.IdErmitteln; end; end; { TArbeitsmittelKlasse } function TArbeitsmittelKlasse.Aktualisieren(): boolean; begin result := false; if self.Id <> 0 then begin with self.SqlQuery, SQL do begin Clear; Add('UPDATE ' + self.TABLE_NAME); Add('SET Bezeichnung = :name'); Add('WHERE Id = :id'); ParamByName('name').Value := self.Bezeichnung; ParamByName('id').Value := self.Id; end; self.SqlQuery.ExecSQL; if self.SqlQuery.RowsAffected = 1 then result := true; end; end; constructor TArbeitsmittelKlasse.create(Bezeichnung: string; Connection: TFDConnection); begin self.Id := 0; self.Bezeichnung := Bezeichnung; self.SqlQuery := TFDQuery.create(nil); self.SqlQuery.Connection := Connection end; constructor TArbeitsmittelKlasse.CreateFromId(Id: integer; Connection: TFDConnection); begin self.SqlQuery := TFDQuery.create(nil); self.SqlQuery.Connection := Connection; with self.SqlQuery, SQL do begin Clear; Add('SELECT * FROM ' + self.TABLE_NAME + ' WHERE Id = :id'); ParamByName('id').Value := Id; end; self.SqlQuery.Open(); if self.SqlQuery.RecordCount = 1 then begin self.Id := self.SqlQuery.FieldByName('Id').AsInteger; self.Bezeichnung := self.SqlQuery.FieldByName('Bezeichnung').AsString; end; self.SqlQuery.Close; end; procedure TArbeitsmittelKlasse.IdErmitteln; begin with self.SqlQuery, SQL do begin Clear; Add('SELECT Id FROM ' + self.TABLE_NAME + ' ORDER BY Id DESC LIMIT 1'); end; self.SqlQuery.Open; if self.SqlQuery.RecordCount = 1 then self.Id := self.SqlQuery.FieldByName('Id').AsInteger; self.SqlQuery.Close end; function TArbeitsmittelKlasse.Speichern(): boolean; begin result := false; if self.Id = 0 then begin with self.SqlQuery, SQL do begin Clear; Add('INSERT INTO ' + self.TABLE_NAME + ' (Bezeichnung)'); Add('VALUES (:name)'); ParamByName('name').Value := self.Bezeichnung; end; self.SqlQuery.ExecSQL; if self.SqlQuery.RowsAffected = 1 then begin result := true; self.IdErmitteln; end else result := self.Aktualisieren; end end; { TArbeitsmittelTyp } procedure TArbeitsmittelTyp.Aktualisieren; begin if self.Id <> 0 then begin with self.SqlQuery, SQL do begin Clear; Add('UPDATE ' + self.TABLE_NAME); Add('SET Bezeichnung = :name,'); Add('Hersteller = :hersteller,'); Add('ArbeitsmittelKlasse = :klasse,'); Add('HatSim = :sim'); Add('WHERE Id = :id'); ParamByName('name').Value := self.Bezeichnung; ParamByName('hersteller').Value := self.Hersteller.Id; ParamByName('klasse').Value := self.ArbeitsmittelKlasse.Id; ParamByName('sim').Value := self.HatSim; ParamByName('id').Value := self.Id; end; self.SqlQuery.ExecSQL; end; end; constructor TArbeitsmittelTyp.create(Bezeichnung: string; Hersteller: THersteller; klasse: TArbeitsmittelKlasse; HatSim: boolean; Connection: TFDConnection); begin self.Id := 0; self.Bezeichnung := Bezeichnung; self.Hersteller := Hersteller; self.ArbeitsmittelKlasse := klasse; self.HatSim := HatSim; self.SqlQuery := TFDQuery.create(nil); self.SqlQuery.Connection := Connection; end; constructor TArbeitsmittelTyp.CreateFromId(Id: integer; Connection: TFDConnection); var Hersteller_Id: integer; Klassen_Id : integer; begin self.SqlQuery := TFDQuery.create(nil); self.SqlQuery.Connection := Connection; with self.SqlQuery, SQL do begin Clear; Add('SELECT * FROM ' + self.TABLE_NAME + ' WHERE Id = :id'); ParamByName('id').Value := Id; Open; end; if self.SqlQuery.RecordCount = 1 then begin Hersteller_Id := self.SqlQuery.FieldByName('Hersteller_Id').AsInteger; Klassen_Id := self.SqlQuery.FieldByName('ArbeitsmittelKlasse_Id').AsInteger; self.Id := self.SqlQuery.FieldByName('Id').AsInteger; self.Bezeichnung := self.SqlQuery.FieldByName('Bezeichnung').AsString; self.Hersteller := THersteller.CreateFromId(Hersteller_Id, Connection); self.ArbeitsmittelKlasse := TArbeitsmittelKlasse.CreateFromId(Klassen_Id, Connection); self.HatSim := self.SqlQuery.FieldByName('HatSim').AsBoolean; end; self.SqlQuery.Close; end; procedure TArbeitsmittelTyp.IdErmitteln; begin with self.SqlQuery, SQL do begin Clear; Add('SELECT Id FROM ' + self.TABLE_NAME + ' ORDER BY Id DESC LIMIT 1'); end; self.SqlQuery.Open; if self.SqlQuery.RecordCount = 1 then self.Id := self.SqlQuery.FieldByName('Id').AsInteger; self.SqlQuery.Close end; procedure TArbeitsmittelTyp.Speichern; begin if self.Id = 0 then begin with self.SqlQuery, SQL do begin Clear; Add('INSERT INTO ' + self.TABLE_NAME + ' (Bezeichnung, Hersteller_id, ArbeitsmittelKlasse_Id, HatSim)'); Add('VALUES(:name, :hersteller, :klasse, :sim)'); ParamByName('name').Value := self.Bezeichnung; ParamByName('hersteller').Value := self.Hersteller.Id; ParamByName('klasse').Value := self.ArbeitsmittelKlasse.Id; ParamByName('sim').Value := self.HatSim; end; self.SqlQuery.ExecSQL; self.IdErmitteln; end; end; { TArbeitsmittel } procedure TArbeitsmittel.Aktualisieren; begin if self.Id <> 0 then begin with self.SqlQuery, SQL do begin Clear; Add('UPDATE ' + self.TABLE_NAME); Add('SET Bezeichnung = :name,'); Add('ArbeitsmittelTyp_id = :typ,'); Add('IMEI = :imei,'); Add('Seriennummer = :serial,'); Add('Sim_Id = :sim'); Add('WHERE Id = :id'); ParamByName('name').Value := self.Bezeichnung; ParamByName('typ').Value := self.ArbeitsmittelTyp.Id; ParamByName('imei').Value := self.Imei; ParamByName('serial').Value := self.SerienNummer; if self.ArbeitsmittelTyp.HatSim then ParamByName('sim').Value := self.SimKarte.Id else ParamByName('sim').Clear; ParamByName('id').Value := self.Id; end; self.SqlQuery.ExecSQL; end; end; constructor TArbeitsmittel.create(Bezeichnung: string; typ: TArbeitsmittelTyp; Imei, serienNr: Variant; Connection: TFDConnection; sim: TSimKarte = nil); begin self.Id := 0; self.Bezeichnung := Bezeichnung; self.ArbeitsmittelTyp := typ; self.Imei := Imei; self.SerienNummer := serienNr; self.SimKarte := sim; self.SqlQuery := TFDQuery.create(nil); self.SqlQuery.Connection := Connection; end; constructor TArbeitsmittel.CreateFromId(Id: integer; Connection: TFDConnection); var Typen_Id: integer; Sim_Id : integer; begin self.SqlQuery := TFDQuery.create(nil); self.SqlQuery.Connection := Connection; with self.SqlQuery, SQL do begin Clear; Add('SELECT * FROM ' + self.TABLE_NAME + ' WHERE Id = :id'); ParamByName('id').Value := Id; end; self.SqlQuery.Open(); if self.SqlQuery.RecordCount = 1 then begin self.Id := self.SqlQuery.FieldByName('Id').AsInteger; self.Bezeichnung := self.SqlQuery.FieldByName('Bezeichnung').AsString; Typen_Id := self.SqlQuery.FieldByName('ArbeitsmittelTyp_Id').AsInteger; self.ArbeitsmittelTyp := TArbeitsmittelTyp.CreateFromId(Typen_Id, Connection); self.Imei := self.SqlQuery.FieldByName('IMEI').AsVariant; self.SerienNummer := self.SqlQuery.FieldByName('Seriennummer').AsVariant; if self.ArbeitsmittelTyp.HatSim then begin Sim_Id := self.SqlQuery.FieldByName('Sim_Id').AsVariant; self.SimKarte := TSimKarte.CreateFromId(Sim_Id, Connection); end; end; self.SqlQuery.Close; end; procedure TArbeitsmittel.setImei(Value: Variant); var imeiAsInt: integer; begin if Length(Value) = 15 then if tryStrToInt(Value, imeiAsInt) then self.FImei := Value else MessageDlg('Die IMEI darf nur Zahlen enthalten!', mtError, [mbOk], 0) else MessageDlg('Die IMEI muss 15 Zeichen lang sein!', mtError, [mbOk], 0); end; procedure TArbeitsmittel.Speichern; begin if self.Id = 0 then begin with self.SqlQuery, SQL do begin Clear; Add('INSERT INTO ' + self.TABLE_NAME + ' (Bezeichnung, ArbeitsmittelTyp_Id, IMEI, Seriennummer, Sim_Id)'); Add('VALUES (:name, :typ, :imei, :serial, :sim)'); ParamByName('name').Value := self.Bezeichnung; ParamByName('typ').Value := self.ArbeitsmittelTyp.Id; ParamByName('imei').Value := self.Imei; ParamByName('serial').Value := self.SerienNummer; if self.ArbeitsmittelTyp.HatSim then ParamByName('sim').Value := self.SimKarte.Id else ParamByName('sim').Clear; end; self.SqlQuery.ExecSQL; self.IdErmitteln; end; end; { TArbeitsmittelHelper } constructor TArbeitsmittelHelper.create(Connection: TFDConnection); begin self.SqlQuery := TFDQuery.create(nil); self.SqlQuery.Connection := Connection; end; function TArbeitsmittelHelper.gibArbeitsmittelKlassen: TStringList; var KlassenListe: TStringList; I : integer; begin KlassenListe := TStringList.create; with self.SqlQuery, SQL do begin Clear; Add('SELECT Bezeichnung FROM ArbeitsmittelKlasse') end; self.SqlQuery.Open(); while not self.SqlQuery.Eof do begin KlassenListe.Add(self.SqlQuery.FieldByName('Bezeichnung').AsString); self.SqlQuery.Next; end; result := KlassenListe; end; function TArbeitsmittelHelper.gibArbeitsmittelTypen: TStringList; var TypenListe: TStringList; I : integer; begin TypenListe := TStringList.create; with self.SqlQuery, SQL do begin Clear; Add('SELECT Bezeichnung FROM ArbeitsmittelTyp') end; self.SqlQuery.Open(); while not self.SqlQuery.Eof do begin TypenListe.Add(self.SqlQuery.FieldByName('Bezeichnung').AsString); self.SqlQuery.Next; end; result := TypenListe; end; end.
unit U_Tableaux; interface uses U_Element, SysUtils; const VALMAX = 100; type TABLEAU = array of ELEMENT; // retourne un tableau comprenant des valeurs entre 1 et VALMAX function tableauAleatoire (taille : CARDINAL) : TABLEAU; // retourne un tableau comprenant des valeurs entre 1 et taille tel que t[i] = i function tableauCroissant (taille : CARDINAL) : TABLEAU; // fait une copie de t function copieTableau (t : TABLEAU) : TABLEAU; // affiche le tableau procedure afficheTableau (const t : TABLEAU); implementation function tableauCroissant (taille : CARDINAL) : TABLEAU; var t : TABLEAU; i : CARDINAL; begin setlength(t,taille); for i := low(t) to high(t) do begin t[i] := i; end {for}; tableauCroissant := t; end {tableauCroissant}; function tableauAleatoire (taille : CARDINAL) : TABLEAU; var t : TABLEAU; i : CARDINAL; begin setlength(t,taille); for i := low(t) to high(t) do begin t[i] := elementAleatoire(VALMAX); end {for}; tableauAleatoire := t; end {tableauAleatoire}; function copieTableau (t : TABLEAU) : TABLEAU; var tt : TABLEAU; i : CARDINAL; begin setlength(tt,length(t)); for i := low(t) to high(t) do tt[i] := t[i]; copieTableau := tt; end {copieTableau}; procedure afficheTableau (const t : TABLEAU); var i : CARDINAL; begin write('['); for i := low(t) to high(t) do begin write(t[i]); if i < high(t) then write(','); end {for}; write(']'); end {afficheTableau}; initialization // a commenter pour obtenir toujous les memes tableaux avec des // execution successives randomize; end {U_Tableaux}.
unit pdv_confirma_qtde_peso; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, cxControls, cxContainer, cxEdit, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinFoggy, dxSkinGlassOceans, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven, dxSkinSharp, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinsDefaultPainters, dxSkinValentine, dxSkinXmas2008Blue, cxTextEdit, cxCurrencyEdit, cxLabel, StdCtrls, cxButtons; type TfrmConfirmaQtdePeso = class(TForm) panBotoes: TPanel; btnConfirmar: TcxButton; btnCancelar: TcxButton; panFechamento: TPanel; lblQtde: TcxLabel; edtQuantidade: TcxCurrencyEdit; lblValor: TcxLabel; edtValor: TcxCurrencyEdit; procedure btnCancelarClick(Sender: TObject); procedure btnConfirmarClick(Sender: TObject); procedure edtQuantidadeKeyPress(Sender: TObject; var Key: Char); private { Private declarations } FQtde: Double; protected { Protected declarations } public property Qtde: Double read FQtde; { Public declarations } end; var frmConfirmaQtdePeso: TfrmConfirmaQtdePeso; function ConfirmaQtdePeso(flValorUnit: Double; boBalanca: Boolean = False) : Double; implementation uses lib_db, lib_mensagem, main_base, lib_vmsis; {$R *.dfm} function ConfirmaQtdePeso(flValorUnit: Double; boBalanca: Boolean = False): Double; var Acesso_Perifericos: TAcesso_Perifericos; Begin Result := 0.0; frmConfirmaQtdePeso := TfrmConfirmaQtdePeso.Create(Application); Acesso_Perifericos := TAcesso_Perifericos.Create; try frmConfirmaQtdePeso.edtQuantidade.Enabled := not boBalanca; if flValorUnit > 0.0 then frmConfirmaQtdePeso.edtValor.Text := formatfloat('###,###,##0.00', flValorUnit) else frmConfirmaQtdePeso.edtValor.Text := '0,00'; if boBalanca then frmConfirmaQtdePeso.edtQuantidade.Text := formatfloat('###,###,##0.000', Acesso_Perifericos.LeBalanca) else frmConfirmaQtdePeso.edtQuantidade.Text := formatfloat('###,###,##0.000', 0.0); if StrToFloat(frmConfirmaQtdePeso.edtQuantidade.Text) < 0.001 then frmConfirmaQtdePeso.edtQuantidade.Enabled := True; frmConfirmaQtdePeso.ShowModal; Result := frmConfirmaQtdePeso.Qtde; finally FreeAndNil(Acesso_Perifericos); FreeAndNil(frmConfirmaQtdePeso); end; end; procedure TfrmConfirmaQtdePeso.btnCancelarClick(Sender: TObject); begin FQtde := 0.0; Close; end; procedure TfrmConfirmaQtdePeso.btnConfirmarClick(Sender: TObject); begin if (edtQuantidade.Text = '') then begin Aviso(INFORMAR_QTDE); edtQuantidade.SetFocus; end else begin FQtde := StrToFloat(edtQuantidade.Text); Close; end; end; procedure TfrmConfirmaQtdePeso.edtQuantidadeKeyPress(Sender: TObject; var Key: Char); begin if (key in [#13]) then begin if (edtQuantidade.Text = '') then begin Aviso(INFORMAR_QTDE); edtQuantidade.SetFocus; end else btnConfirmarClick(btnConfirmar); end; end; end.
unit Main; interface procedure Execute(); implementation uses Windows, Messages, SysUtils, Variants, Classes, IniFiles, eStrings, eCmdLine, eFiles, eBackupSystemHelpers, DateUtils; procedure DeleteOldHistoryFiles(const iDestinationFolder,iName:string); var lSearch2:TSearchRec; lOk:dword; lHistoryFolder: string; begin lHistoryFolder := MakePath(iDestinationFolder)+'__History\'+iName; ForceDirectories(lHistoryFolder); lOk := FindFirst(MakePath(iDestinationFolder)+iName+' - *.*',faAnyFile,lSearch2); try while lOk = 0 do begin if (lSearch2.Attr and faDirectory) = 0 then begin writeln('Moving old "'+lSearch2.Name+'" to History.'); DeleteFile(pChar(MakePath(iDestinationFolder)+lSearch2.Name)); end; lOk := FindNext(lSearch2); end; finally FindClose(lSearch2); end; end; procedure MoveOldFilesToHistory(const iDestinationFolder,iName:string); var lSearch2:TSearchRec; lOk:dword; lHistoryFolder: string; begin lHistoryFolder := MakePath(iDestinationFolder)+'__History\'+iName; ForceDirectories(lHistoryFolder); lOk := FindFirst(MakePath(iDestinationFolder)+iName+' - *.*',faAnyFile,lSearch2); try while lOk = 0 do begin if (lSearch2.Attr and faDirectory) = 0 then begin writeln('Moving old "'+lSearch2.Name+'" to History.'); MoveFile(pChar(MakePath(iDestinationFolder)+lSearch2.Name), pChar(MakePath(lHistoryFolder)+lSearch2.Name)); end; lOk := FindNext(lSearch2); end; finally FindClose(lSearch2); end; end; function ArchiveFolderIfChanged(const iSourceFolder, iName:string; var ioLastArchiveDate:TDateTime; const iDestinationFolder, iWinZipPath:string; iParams:string; iSourceIsParentFolder:boolean=true; iNoHistory:boolean=false):boolean; var lDate: TDatetime; lFolder, lDestinationFile, lTempDestinationFile, lSourcePattern, lZipCommand:string; begin //lDestinationFile := MakePath(lDestinationFolder)+lSearch.Name; if iSourceIsParentFolder then lFolder := MakePath(MakePath(iSourceFolder)+iName) else lFolder := MakePath(iSourceFolder); lDate := GetFolderDate(ExcludeTrailingBackslash(lFolder)); if ioLastArchiveDate = lDate then begin writeln(iName+' - archived '+DateTimeToStr(ioLastArchiveDate)+', no change since. skipping.'); result := false; end else begin writeln(iName+' - archived '+DateTimeToStr(ioLastArchiveDate)+', changed '+DateTimeToStr(lDate)); lDestinationFile := MakePath(iDestinationFolder)+iName+' - changed '+FormatDateTime('yyyymmdd-hhnnss',lDate)+' - created '+FormatDateTime('yyyymmdd-hhnnss',Now)+'.zip'; lTempDestinationFile := MakePath(iDestinationFolder)+'__temp_'+iName+' - changed '+FormatDateTime('yyyymmdd-hhnnss',lDate)+' - created '+FormatDateTime('yyyymmdd-hhnnss',Now)+'.zip'; lSourcePattern := MakePath(lFolder)+'*.*'; { zip to temp file } //ChDir(ExtractFilePath(lSourcePattern)); Replace(iParams,'%BASE%',ExtractFilePath(lSourcePattern)); writeln('Zipping up "'+lSourcePattern+'" to "'+lTempDestinationFile+'".'); lZipCommand := '-r -o -p -whs -ybc '+iParams+' "'+lTempDestinationFile+'" "'+lSourcePattern+'"'; writeln(' '+lZipCommand); ExecuteAndWait(iWinzipPath,lZipCommand); if iNoHistory then begin DeleteOldHistoryFiles(iDestinationFolder,iName); end else begin { move old files to History folder } MoveOldFilesToHistory(iDestinationFolder,iName); end; { rename temp file to proper name } MoveFile(pChar(lTempDestinationFile),pChar(lDestinationFile)); ioLastArchiveDate := lDate; result := true; end; end; procedure Process; var i: Integer; lSourceFolder: string; lSearch:TSearchRec; lOk:dword; lDestinationFolder: string; lDateStr: string; lArciveDate: TDatetime; SourcePath: string; lDestinationFile,lTempDestinationFile: string; Command: string; fCfgFile:string; fFolders:TStringList; lWinzipPath, lWinZipParams:string; fDestination:string; lNoHistory: boolean; begin fFolders := TStringList.Create(); if ParamCount > 0 then fCfgFile := ParamStr(1) else fCfgFile := ChangeFileExt(GetModuleName,'.cfg'); writeln('Reading config file '+fCfgFile); if FileExists(fCfgFile) then begin with TMemIniFile.Create(fCfgFile) do try fDestination := ReadString('General','Destination',ExtractFilePath(GetModuleName)); lWinzipPath := ReadString('General','wzzip','c:\Program Files\WinZip\wzzip.exe'); //for i := 0 to fFolders.Count-1 do begin //writeln('Folder '+fFolders.Names[i]); //end; { for } { Process Folders that have subfolders, in "Folders" section } ReadSectionValues('Folders',fFolders); for i := 0 to fFolders.Count-1 do try lSourceFolder := fFolders.Values[fFolders.Names[i]]; lDestinationFolder := MakePath(fDestination)+fFolders.Names[i]; ForceDirectories(lDestinationFolder); writeln('Folder '+fFolders.Names[i]+' '+lSourceFolder); lOk := FindFirst(MakePath(lSourceFolder)+'*.*',faDirectory,lSearch); try while lOk = 0 do begin if (lSearch.Name <> '.') and (lSearch.Name <> '..') and ((lSearch.Attr and faDirectory) = faDirectory)then begin //Writeln(' Subfolder '+lSearch.Name); lDateStr := ReadString('ArchiveDates for '+fFolders.Names[i],lSearch.Name,''); lArciveDate := StrToDateTimeDef(lDateSTr,0); lWinZipParams := ReadString('ZipParams',fFolders.Names[i],'')+' '+ReadString('ZipParams','*',''); lNoHistory := ReadString('NoHistory',fFolders.Names[i],'false') = 'true'; if ArchiveFolderIfChanged(lSourceFolder, lSearch.Name, lArciveDate, lDestinationFolder, lWinZipPath, lWinzipParams, true, lNoHistory) then begin WriteString('ArchiveDates for '+fFolders.Names[i],lSearch.Name,DateTimeToStr(lArciveDate)); UpdateFile(); end; end; lOk := FindNext(lSearch); end; { while } finally FindClose(lSearch); end; except on E:Exception do begin Writeln(E.Classname+': '+E.Message); //ToDo: log message end; end; { Process Folders that don't have individual subfolders, in "SimpleFolders" section } ReadSectionValues('SimpleFolders',fFolders); for i := 0 to fFolders.Count-1 do try lSourceFolder := ExcludeTrailingBackslash(fFolders.Values[fFolders.Names[i]]); lDestinationFolder := MakePath(fDestination);//+fFolders.Names[i]; ForceDirectories(lDestinationFolder); lDateStr := ReadString('ArchiveDates SimpleFolders',fFolders.Names[i],''); lArciveDate := StrToDateTimeDef(lDateSTr,0); lWinZipParams := ReadString('ZipParams',fFolders.Names[i],''); if ArchiveFolderIfChanged(lSourceFolder, fFolders.Names[i], lArciveDate, lDestinationFolder, lWinZipPath, lWinZipParams, false) then begin WriteString('ArchiveDates SimpleFolders',fFolders.Names[i],DateTimeToStr(lArciveDate)); UpdateFile(); end; except on E:Exception do begin Writeln(E.Classname+': '+E.Message); //ToDo: log message end; end; finally Free(); end; { with } end; end; procedure Execute; begin Writeln('elitedevelopments StuffZipper 0.3'); Writeln; try Process(); except on E:Exception do Writeln(E.Classname+': '+E.Message); end; Writeln('Done.'); if SwitchExists('wait') then begin Writeln('Press Enter.'); Readln; end; Writeln; end; end.
{------------------------------------------------------------------------------ // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2009 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com // EasyComponents是HhfComponents的升级版本,当前主版本号为2.0 // +2011-04-10 12:53:43 TEasyCustomMoneyEdit 通过下拉按钮组输入金额信息 ------------------------------------------------------------------------------} unit untEasyMoneyEdit; //控件在Delphi7下或更高版本下 {$IFDEF VER150} {$ELSE} {$DEFINE DELPHI9_LVL} {$ENDIF} {$IFDEF UNICODE} {$DEFINE DELPHI9_LVL DELPHI_UNICODE} {$ENDIF} interface uses Windows, Messages, StdCtrls, Classes, Graphics, Controls, SysUtils, Forms, Math, ComObj, untEasyAbout, untEasyCustomDropDownEdit, CheckLst, untEasyMenus, Buttons; type TEasyCustomMoneyEdit = class; {TEasyMoneyTextTabForm} TEasyMoneyTextTabForm = class(TForm) private FButtonWidth : integer; FButtonHeight: integer; FButtonColor : TColor; procedure CMWantSpecialKey(var Msg: TCMWantSpecialKey); message CM_WANTSPECIALKEY; procedure WMClose(var Msg:TMessage); message WM_CLOSE; protected procedure Paint; override; public constructor Create(aOwner:TComponent); override; destructor Destroy; override; published property ButtonWidth:integer read FButtonWidth write FButtonWidth; property ButtonHeight:integer read FButtonHeight write FButtonHeight; property ButtonColor:TColor read FButtonColor write FButtonColor; end; { TEasyCalculatorButton } TEasyCalculatorButton = class(TSpeedButton) protected procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; end; { TEasyCalculatorLook } TEasyCalculatorLook = class(TPersistent) private FButtonBkg: TBitmap; FButtonWidth: integer; FButtonHeight: integer; FButtonColor: TColor; FColor: TColor; FFont: TFont; FFlat: boolean; procedure SetFont(const Value: TFont); procedure SetButtonBkg(const Value: TBitmap); public constructor Create; destructor Destroy; override; procedure Assign(Source: TPersistent); override; published property ButtonWidth:integer read FButtonWidth write FButtonWidth; property ButtonHeight:integer read FButtonHeight write FButtonHeight; property ButtonColor:TColor read FButtonColor write FButtonColor; property Color:TColor read FColor write FColor; property Flat:boolean read FFlat write FFlat; property Font:TFont read FFont write SetFont; property ButtonBkg:TBitmap read FButtonBkg write SetButtonBkg; end; { TEasyCustomMoneyEdit } TEasyCustomMoneyEdit = class(TEasyCustomDropDownEdit) private FEditorEnabled: Boolean; FOnClickBtn : TNotifyEvent; FCalcForm : TEasyMoneyTextTabForm; FCalcClosed : Boolean; FCloseClick : Boolean; FDecim : Integer; sp : array[0..22] of TEasyCalculatorButton; newval : boolean; prevval : extended; prevop : integer; FCalculatorLook: TEasyCalculatorLook; procedure BtnClick(Sender: TObject); virtual; procedure FormDeactivate(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); //按钮事件 procedure NumButtonClick(Sender: TObject); //运算函数 procedure docalc; procedure doplus; procedure domin; procedure domul; procedure dodiv; procedure doeq; procedure doperc; // procedure BuildCalculator(AForm:TForm); function GetValue: extended; procedure SetValue(const Value: extended); procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure CMEnter(var Message: TCMGotFocus); message CM_ENTER; procedure CMExit(var Message: TCMExit); message CM_EXIT; procedure WMPaste(var Message: TWMPaste); message WM_PASTE; procedure WMCut(var Message: TWMCut); message WM_CUT; procedure WMKeyDown(var Msg:TWMKeydown); message WM_KEYDOWN; procedure SetCalculatorLook(const Value: TEasyCalculatorLook); procedure SetEditorEnabled(const Value: Boolean); protected procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; procedure DestroyWnd; override; function GetParentForm(Control: TControl): TCustomForm; virtual; procedure KeyPress(var key:char); override; procedure CalcChange; virtual; procedure SetTextDirect(s:string); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; //显示隐藏 procedure ShowCalculator; procedure HideCalculator; property Text; property Value:extended read GetValue write SetValue; property About; property EnterTAB; property BorderColor; property FocusColor; property TextRightAlign; property EditLabel; property LabelPosition; property LabelSpacing; property AutoFocus; property AppereanceStyle; property Button; property Flat; property Anchors; property Constraints; property DragKind; property AutoSelect; property AutoSize; property CalculatorLook:TEasyCalculatorLook read FCalculatorLook write SetCalculatorLook; property Color; property DragCursor; property DragMode; property EditorEnabled: Boolean read FEditorEnabled write SetEditorEnabled default True; property Enabled; property Font; property MaxLength; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Visible; property Height; property Width; property OnChange; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; property OnEndDock; property OnStartDock; property OnClickBtn: TNotifyEvent read FOnClickBtn write FOnClickBtn; end; { TEasyMoneyEdit } TEasyMoneyEdit = class(TEasyCustomMoneyEdit) published property Text; property Value; property About; property EnterTAB; property BorderColor; property FocusColor; property TextRightAlign; property EditLabel; property LabelPosition; property LabelSpacing; property AutoFocus; property AppereanceStyle; property Button; property Flat; property Anchors; property Constraints; property DragKind; property AutoSelect; property AutoSize; property CalculatorLook; property Color; property DragCursor; property DragMode; property EditorEnabled; property Enabled; property Font; property MaxLength; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Visible; property Height; property Width; property OnChange; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; property OnEndDock; property OnStartDock; property OnClickBtn; end; implementation function StripThousandSep(s:string):string; begin while (Pos(ThousandSeparator,s)>0) do Delete(s,Pos(ThousandSeparator,s),1); Result := s; end; { TEasyMoneyTextTabForm } procedure TEasyMoneyTextTabForm.CMWantSpecialKey( var Msg: TCMWantSpecialKey); begin inherited; if msg.CharCode in [vk_up,vk_down,vk_left,vk_right,vk_tab] then msg.result:=1; end; constructor TEasyMoneyTextTabForm.Create(aOwner: TComponent); begin inherited; // end; destructor TEasyMoneyTextTabForm.Destroy; begin // inherited; end; procedure TEasyMoneyTextTabForm.Paint; var i,j: integer; r : trect; oldColor:TColor; begin inherited; with canvas do begin pen.color:=clBlack; r := GetClientRect; Rectangle(r.left,r.top,r.right,r.bottom); oldColor := Canvas.Brush.Color; Canvas.Brush.Color := ButtonColor; Canvas.Pen.Color := ButtonColor; for i := 1 to 6 do for j := 1 to 4 do begin if (i=5) and (j<2) then Continue; if i=6 then Continue; Rectangle(2+(2+FButtonWidth)*(i-1),2+(2+FButtonHeight)*(j-1), (2+FButtonWidth)*(i),(2+FButtonHeight)*(j)); end; Canvas.brush.color:=oldColor; end; end; procedure TEasyMoneyTextTabForm.WMClose(var Msg: TMessage); begin inherited; self.Free; end; { TEasyCalculatorButton } procedure TEasyCalculatorButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; Repaint; end; procedure TEasyCalculatorButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; Repaint; end; procedure TEasyCalculatorButton.Paint; var hasGlyph: boolean; r: TRect; s:string; begin hasGlyph := false; if Assigned(Glyph) then hasGlyph := not Glyph.Empty; if not Flat or not hasGlyph then inherited else begin s := Trim(Caption); if FState = bsDown then Canvas.Draw(1,1,Glyph) else Canvas.Draw(0,0,Glyph); r := ClientRect; Canvas.Brush.Style := bsClear; if FState = bsDown then OffsetRect(r,1,1); Canvas.Font.Assign(self.Font); DrawText(Canvas.Handle, Pchar(s),length(s),r,DT_SINGLELINE or DT_CENTER or DT_VCENTER); end; end; { TEasyCustomMoneyEdit } procedure TEasyCustomMoneyEdit.BtnClick(Sender: TObject); begin if not FCloseClick then ShowCalculator; FCloseClick := False; if Assigned(FOnClickBtn) then FOnClickBtn(Sender); end; procedure TEasyCustomMoneyEdit.BuildCalculator(AForm: TForm); var i, n : integer; FButtonWidth : integer; FButtonHeight: integer; begin FButtonWidth := FCalculatorLook.ButtonWidth; FButtonHeight := FCalculatorLook.ButtonHeight; n:=5; AForm.Width:=4+n*(FButtonWidth+2); AForm.Height:=4+4*(FButtonHeight+2); for i:=0 to 18 do begin sp[i] := TEasyCalculatorButton.Create(AForm); sp[i].Font.Assign(FCalculatorLook.Font); if not FCalculatorLook.ButtonBkg.Empty then begin sp[i].Glyph:=FCalculatorLook.ButtonBkg; sp[i].Spacing:=-(FCalculatorLook.ButtonBkg.Width shr 1)-(FCalculatorLook.Font.Size shr 1); sp[i].Margin:=0; sp[i].Flat := (FCalculatorLook.Flat) or not FCalculatorLook.ButtonBkg.Empty;; end; case i of 0,1,4,7:sp[i].left:=2; 2,5,8,14:sp[i].left:=2+(FButtonWidth+2); 3,6,9,15:sp[i].left:=2+2*(FButtonWidth+2); 10,11,12,13:sp[i].left:=2+3*(FButtonWidth+2); 16,17,18:sp[i].left:=2+4*(FButtonWidth+2); end; case i of 7,8,9,10:sp[i].top:=2; 4,5,6,11,18:sp[i].top:=2+(FButtonHeight+2); 1,2,3,12,16:sp[i].top:=2+2*(FButtonHeight+2); 0,13,14,15,17:sp[i].top:=2+3*(FButtonHeight+2); end; sp[i].width:=FButtonWidth; sp[i].height:=FButtonHeight; sp[i].tag:=i; sp[i].flat:= (FCalculatorLook.Flat) or not FCalculatorLook.ButtonBkg.Empty; case i of 0..9:sp[i].caption:=inttostr(i)+' '; 10:sp[i].caption:='+ '; 11:sp[i].caption:='- '; 12:sp[i].caption:='* '; 13:sp[i].caption:='/ '; 14:sp[i].caption:='+/- '; 15:sp[i].caption:='. '; 16:sp[i].caption:='C '; 17:sp[i].caption:='= '; 18:sp[i].caption:='% '; end; sp[i].OnClick := NumButtonClick; sp[i].Parent:=AForm; sp[i].Visible:=true; end; end; procedure TEasyCustomMoneyEdit.CalcChange; begin // end; procedure TEasyCustomMoneyEdit.CMEnter(var Message: TCMGotFocus); begin if AutoSelect and not (csLButtonDown in ControlState) then SelectAll; inherited; end; procedure TEasyCustomMoneyEdit.CMExit(var Message: TCMExit); begin inherited; // end; constructor TEasyCustomMoneyEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); OnButtonClick := BtnClick; FDecim := 0; Text := '0'; ControlStyle := ControlStyle - [csSetCaption]; FEditorEnabled := True; FCalcClosed := True; Enabled := True; FCalculatorLook := TEasyCalculatorLook.Create; // IndentR := 19; // IndentL := 0; // EditType := etFloat; end; procedure TEasyCustomMoneyEdit.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.Style := Params.Style or ES_MULTILINE; end; procedure TEasyCustomMoneyEdit.CreateWnd; begin inherited; // end; destructor TEasyCustomMoneyEdit.Destroy; begin FCalculatorLook.Free; inherited; end; procedure TEasyCustomMoneyEdit.DestroyWnd; begin inherited; // end; procedure TEasyCustomMoneyEdit.docalc; var e: extended; begin if Text = '' then Text := '0'; e := strtofloat(StripThousandSep(Text)); try case prevop of 0:prevval := prevval + e; 1:prevval := prevval * e; 2:prevval := prevval - e; 3:if (e<>0) then prevval:=prevval/e else prevval:=0; else prevval:=strtofloat(StripThousandSep(Text)); end; except prevval:=0; end; Text:=format('%g',[prevval]); // FloatValue := prevval; newval := true; end; procedure TEasyCustomMoneyEdit.dodiv; begin docalc; prevop:=3; end; procedure TEasyCustomMoneyEdit.doeq; begin DoCalc; if Text = '' then Text := '0'; prevval := strtofloat(StripThousandSep(Text)); prevop := -1; end; procedure TEasyCustomMoneyEdit.domin; begin docalc; prevop:=2; end; procedure TEasyCustomMoneyEdit.domul; begin docalc; prevop:=1; end; procedure TEasyCustomMoneyEdit.doperc; var e:extended; begin if Text='' then Text:='0'; e:=strtofloat(StripThousandSep(Text)); e:=prevval*e/100; Text:=format('%g',[e]); end; procedure TEasyCustomMoneyEdit.doplus; begin docalc; prevop := 0; end; procedure TEasyCustomMoneyEdit.FormDeactivate(Sender: TObject); var pt:tpoint; r:trect; begin {check cursor here...} getcursorpos(pt); pt:=screentoclient(pt); r:=clientrect; r.left:=r.right-16; FCloseClick:=ptinrect(r,pt); postmessage((Sender as TForm).Handle,WM_CLOSE,0,0); end; procedure TEasyCustomMoneyEdit.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var s:string; begin if key in [vk_F4, vk_tab] then Postmessage((Sender as TForm).Handle,WM_CLOSE,0,0); if (key = vk_back) then begin s := Text; Delete(s,Length(Text),1); if s = '' then s := '0'; Text := s; end; end; procedure TEasyCustomMoneyEdit.FormKeyPress(Sender: TObject; var Key: Char); begin CalcChange; if Key = DecimalSeparator then if (pos(DecimalSeparator,Text)=0) then Text:=Text+DecimalSeparator; {$IFNDEF DELPHI_UNICODE} if (key in ['0'..'9']) then {$ENDIF} {$IFDEF DELPHI_UNICODE} if character.IsNumber(key) then {$ENDIF} begin if (MaxLength > 0) and (Length(Text) = MaxLength) then Exit; end; case key of '0'..'9': if (Text = '0') or (newval) then begin SetTextDirect(key); newval := false; end else SetTextDirect(Text + key); 'c','C': begin Text := '0'; prevval := 0; newval := true; prevop := -1; end; '+':doplus; '/':dodiv; '-':domin; '*':domul; '=':doeq; '%':doperc; #13: begin doeq; postmessage((Sender as TForm).Handle,WM_CLOSE,0,0); end; #27: postmessage((Sender as TForm).Handle,WM_CLOSE,0,0); end; end; function TEasyCustomMoneyEdit.GetParentForm( Control: TControl): TCustomForm; begin Result := nil; if Assigned(Control) then if Control is TCustomForm then begin Result := Control as TCustomForm; Exit; end else begin if Assigned(Control.Parent) then Result := GetParentForm(Control.Parent); end; end; function TEasyCustomMoneyEdit.GetValue: extended; begin if Text = '' then Text := '0'; try Result := StrToFloat(StripThousandSep(Text)); except Result := 0; end; end; procedure TEasyCustomMoneyEdit.HideCalculator; begin FCalcForm.Free; FCalcform := nil; end; procedure TEasyCustomMoneyEdit.KeyPress(var key: char); begin if FCalcClosed or (Assigned(FCalcForm) and (FCalcForm.Visible = false)) then case key of 'c','C':begin Text:='0'; newval:=true; prevop:=-1; end; '+':doplus; '/':dodiv; '-':domin; '*':domul; '=',#13:doeq; '%':doperc; end; {$IFNDEF DELPHI_UNICODE} if not (Key in ['0'..'9',DecimalSeparator,#8,'-']) then key := #0; {$ENDIF} {$IFDEF DELPHI_UNICODE} if not (character.IsNumber(Key) or (Key = DecimalSeparator) or (Key = #8) or (Key = '-')) then key := #0; {$ENDIF} {$IFNDEF DELPHI_UNICODE} if ((Text='0') or (newval)) and (key in ['0'..'9']) then {$ENDIF} {$IFDEF DELPHI_UNICODE} if ((Text='0') or (newval)) and (character.IsNumber(key)) then {$ENDIF} begin Text := Key; Key := #0; SelStart := 1 + Length(''); SelLength := 0; Newval := False; Exit; end; if (Length(Text) = 1) and (Key = #8) then begin Text := '0'; Key := #0; SelStart := 1 + Length(''); SelLength := 0; Exit; end; if (Key = ThousandSeparator) then begin Key := #0; end; if (Key = DecimalSeparator) and (Pos(Key,Text)>0) then begin Key := #0; end; inherited; end; procedure TEasyCustomMoneyEdit.NumButtonClick(Sender: TObject); var s:string; e,n:extended; f: double; begin CalcChange; if ((Sender as TEasyCalculatorButton).Tag in [10..14,16,17,18,19..22]) then FDecim := 0; if (Integer((Sender as TEasyCalculatorButton).Tag) in [0..9,14,15]) then begin if (MaxLength > 0) and (Length(Text) = MaxLength) then Exit; end; if ((Sender as TEasyCalculatorButton).Tag < 10) then begin f := StrToFloatDef(Text, 0.0); if ((StrToFloatDef(Text, 0.0) = 0.0 ) and (FDecim = 0)) or (newval) then begin Text := IntToStr((sender as TEasyCalculatorButton).Tag); newval := false; end else begin if FDecim > 0 then begin f := f + (Sender as TEasyCalculatorButton).Tag / FDecim; FDecim := FDecim * 10; end else f := f * 10 + (Sender as TEasyCalculatorButton).Tag; Text := Format('%g', [f]); end; end else begin case ((sender as TEasyCalculatorButton).tag) of 10:begin doplus; prevop:=0; end; 11:begin domin; prevop:=2; end; 12:begin domul; prevop:=1; end; 13:begin dodiv; prevop:=3; end; 14:if pos('-',Text)=0 then Text:='-'+Text else begin s := Text; delete(s,1,1); Text := s; end; 15:begin if pos(DecimalSeparator,Text) = 0 then begin Text := Text + DecimalSeparator; end; FDecim := 10; if newval then Text := '0'; newval := false; end; 16:begin Text := '0'; prevval := 0; prevop := -1; end; 17:doeq; 18:begin doperc; end; 19..22:begin if Text='' then Text:='0'; e:=strtofloat(StripThousandSep(Text)); n:=e; if (e<>n) then Text:=Format('%g',[e]); end; end; end; Modified := True; end; procedure TEasyCustomMoneyEdit.SetCalculatorLook( const Value: TEasyCalculatorLook); begin FCalculatorLook.Assign(Value); end; procedure TEasyCustomMoneyEdit.SetEditorEnabled(const Value: Boolean); begin FEditorEnabled := Value; ReadOnly:=not fEditorEnabled; end; procedure TEasyCustomMoneyEdit.SetTextDirect(s: string); begin inherited Text := s; end; procedure TEasyCustomMoneyEdit.SetValue(const Value: extended); begin Text := Format('%g',[value]); end; procedure TEasyCustomMoneyEdit.ShowCalculator; var P: TPoint; fDropDirection:boolean; {$IFDEF DELPHI9_LVL} w, h : integer; {$ENDIF} begin FCalcClosed := False; FDecim := 0; newval := true; P := Point(0, 0); P := Self.ClientToScreen(P); FCalcForm := TEasyMoneyTextTabForm.CreateNew(self, 0); FCalcForm.BorderStyle:=bsNone; FCalcForm.Visible := False; FCalcForm.ButtonWidth := FCalculatorLook.ButtonWidth; FCalcForm.ButtonHeight := FCalculatorLook.ButtonHeight; if not FCalculatorLook.ButtonBkg.Empty then FCalcForm.ButtonColor := FCalculatorLook.Color else FCalcForm.ButtonColor := FCalculatorLook.ButtonColor; FCalcForm.FormStyle := fsStayOnTop; FCalcForm.Color := FCalculatorLook.Color; FCalcForm.OnDeactivate := FormDeactivate; FCalcForm.OnKeypress := FormKeyPress; FCalcForm.OnKeyDown := FormKeyDown; P := Point(0, 0); P := ClientToScreen(P); FCalcForm.Left:=P.x; BuildCalculator(FCalcForm); FDropDirection := false; if P.y + FCalcForm.Height >= GetSystemMetrics(SM_CYSCREEN) then fDropDirection := True; if P.y - FCalcForm.Height <= 0 then fDropDirection := False; if (FDropDirection=false) then FCalcForm.Top:=P.y + self.Height else FCalcForm.Top:=P.y - FCalcForm.Height; {$IFNDEF DELPHI9_LVL} FCalcForm.Show; {$ENDIF} {$IFDEF DELPHI9_LVL} w := FCalcForm.Width; h := FCalcForm.Height; FCalcForm.Width := 0; FCalcForm.height := 0; FCalcForm.Show; FCalcForm.Left:=P.x; FDropDirection:=false; if P.y + FCalcForm.Height >= GetSystemMetrics(SM_CYSCREEN) then fDropDirection := True; if P.y - FCalcForm.Height <= 0 then fDropDirection := False; if (FDropDirection=false) then FCalcForm.Top:=P.y + self.Height else FCalcForm.Top:=P.y - FCalcForm.Height; FCalcForm.width := w; FCalcForm.Height := h; {$ENDIF} end; procedure TEasyCustomMoneyEdit.WMCut(var Message: TWMCut); begin if FEditorEnabled then inherited; end; procedure TEasyCustomMoneyEdit.WMKeyDown(var Msg: TWMKeydown); begin inherited; if (msg.CharCode=vk_F4) then begin ShowCalculator; end; if (msg.CharCode = vk_delete) then if Text = '' then Text := '0'; end; procedure TEasyCustomMoneyEdit.WMPaste(var Message: TWMPaste); begin if FEditorEnabled then inherited; end; procedure TEasyCustomMoneyEdit.WMSize(var Message: TWMSize); begin // end; { TEasyCalculatorLook } procedure TEasyCalculatorLook.Assign(Source: TPersistent); begin if Source is TEasyCalculatorLook then begin ButtonBkg.Assign(TEasyCalculatorLook(Source).ButtonBkg); ButtonWidth := TEasyCalculatorLook(Source).ButtonWidth; ButtonHeight := TEasyCalculatorLook(Source).ButtonHeight; ButtonColor := TEasyCalculatorLook(Source).ButtonColor; Color := TEasyCalculatorLook(Source).Color; Font.Assign(TEasyCalculatorLook(Source).Font); Flat := TEasyCalculatorLook(Source).Flat; end; end; constructor TEasyCalculatorLook.Create; begin inherited; FFont := TFont.Create; FButtonWidth := 24; FButtonHeight := 24; FButtonColor := clSilver; FColor := clWhite; FbuttonBkg := TBitmap.Create; end; destructor TEasyCalculatorLook.Destroy; begin FFont.Free; FbuttonBkg.Free; inherited; end; procedure TEasyCalculatorLook.SetButtonBkg(const Value: TBitmap); begin FButtonBkg.Assign(Value); end; procedure TEasyCalculatorLook.SetFont(const Value: TFont); begin FFont.Assign(Value); end; end.
unit Ex10Unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, MTUtils, ComCtrls, ExtCtrls, StrUtils; const UM_PROGRESS_CHANGE = WM_USER + 2; type TProgressData = class public CurrValue: Integer; CalcResult: Int64; ThreadStateInfo: string; constructor Create(ACurrValue: Integer; ACalcResult: Int64; AThreadStateInfo: string); end; TMyThread = class(TThread) private FFormHandle: THandle; FMaxValue: Integer; public EndWork: Boolean; procedure Execute; override; constructor Create(AMaxValue: Integer; AFormHandle: THandle); end; TForm1 = class(TForm) btnRunInParallelThread: TButton; ProgressBar1: TProgressBar; Label1: TLabel; labResult: TLabel; edMaxValue: TEdit; Label2: TLabel; labThreadStateInfo: TLabel; Label3: TLabel; labPostMsgProcessCount: TLabel; Label4: TLabel; labPostMsgCount: TLabel; Timer1: TTimer; Label5: TLabel; labEndWork: TLabel; procedure btnRunInParallelThreadClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { Private declarations } FMyThread: TMyThread; FPostMsgProcessCount: Integer; procedure UMProgressChange(var Msg: TMessage); message UM_PROGRESS_CHANGE; public { Public declarations } end; var Form1: TForm1; PostMessageCount: Integer; implementation {$R *.dfm} procedure TForm1.btnRunInParallelThreadClick(Sender: TObject); var MaxValue: Integer; begin // Уничтожаем запущенный поток if Assigned(FMyThread) then FreeAndNil(FMyThread); MaxValue := StrToInt(edMaxValue.Text); ProgressBar1.Max := MaxValue; ProgressBar1.Position := 0; FPostMsgProcessCount := 0; PostMessageCount := 0; labResult.Caption := '0'; labThreadStateInfo.Caption := 'Start'; // Создаём и запускаем новый поток FMyThread := TMyThread.Create(MaxValue, Handle); end; procedure TForm1.FormDestroy(Sender: TObject); begin FMyThread.Free; end; procedure TForm1.Timer1Timer(Sender: TObject); begin labPostMsgProcessCount.Caption := IntToStr(FPostMsgProcessCount); labPostMsgCount.Caption := IntToStr(PostMessageCount); if Assigned(FMyThread) then labEndWork.Caption := IfThen(FMyThread.EndWork, 'ДА', 'НЕТ'); end; procedure TForm1.UMProgressChange(var Msg: TMessage); var ProgressData: TProgressData; begin ProgressData := TProgressData(Msg.WParam); ProgressBar1.Position := ProgressData.CurrValue; labResult.Caption := IntToStr(ProgressData.CalcResult); labThreadStateInfo.Caption := ProgressData.ThreadStateInfo; Inc(FPostMsgProcessCount); // Здесь необходимо уничтожить объект TProgressData: ProgressData.Free; end; { TMyThread } constructor TMyThread.Create(AMaxValue: Integer; AFormHandle: THandle); begin inherited Create(False); FMaxValue := AMaxValue; FFormHandle := AFormHandle; end; procedure TMyThread.Execute; var CurrVal: Integer; CalcResult: Int64; ThreadStateInfo: string; ProgressData: TProgressData; begin CurrVal := 0; CalcResult := 0; // Выполняем некоторые вычисления while CurrVal < FMaxValue do begin if Terminated then Break; Inc(CurrVal); CalcResult := CalcResult + CurrVal; ThreadStateInfo := Format('Progress: %f%%', [CurrVal / FMaxValue * 100]); // Обновление прогресса выполняется только 1 раз из 10000 if CurrVal mod 10000 = 0 then begin // Создаём объект ProgressData непосредственно перед PostMessage ProgressData := TProgressData.Create(CurrVal, CalcResult, ThreadStateInfo); PostMessage(FFormHandle, UM_PROGRESS_CHANGE, WPARAM(ProgressData), 0); Inc(PostMessageCount); end; end; // Обновляем прогресс в конце вычислений ProgressData := TProgressData.Create(CurrVal, CalcResult, ThreadStateInfo); PostMessage(FFormHandle, UM_PROGRESS_CHANGE, WPARAM(ProgressData), 0); Inc(PostMessageCount); // Этот флаг необходим, чтобы главный поток мог убедиться, что // доп. поток отработал корректно до последнего EndWork := True; end; { TProgressData } constructor TProgressData.Create(ACurrValue: Integer; ACalcResult: Int64; AThreadStateInfo: string); begin CurrValue := ACurrValue; CalcResult := ACalcResult; ThreadStateInfo := AThreadStateInfo; end; end.
{*******************************************************} { } { Delphi LiveBindings Framework } { } { Copyright(c) 2012-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit Data.Bind.Controls; interface uses System.Classes, Data.Bind.Components, System.SysUtils; type TNavigateButton = (nbFirst, nbPrior, nbNext, nbLast, nbInsert, nbDelete, nbEdit, nbPost, nbCancel, nbRefresh, nbApplyUpdates, nbCancelUpdates); TNavigateButtons = set of TNavigateButton; TBindNavigatorController = class(TComponent) private (*[weak]*) FDataSource: TBaseBindScopeComponent; FScopeNavigator: IScopeNavigator; FScopeNavigatorUpdates: IScopeNavigatorUpdates; FScopeState: IScopeState; FScopeEditor: IScopeEditor; FOnDataChanged: TNotifyEvent; FOnEditingChanged: TNotifyEvent; FOnActiveChanged: TNotifyEvent; function GetActive: Boolean; function GetBOF: Boolean; function GetEOF: Boolean; function GetSelected: Boolean; function GetEditing: Boolean; procedure SetDataSource(const Value: TBaseBindScopeComponent); function GetCanModify: Boolean; function GetCanInsert: Boolean; function GetCanDelete: Boolean; function GetCanRefresh: Boolean; procedure DoOnEditingChanged(Sender: TObject); procedure DoOnDataChanged(Sender: TObject); procedure DoOnDataScrolled(Sender: TObject; Distance: Integer); procedure DoOnActiveChanged(Sender: TObject); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AComponent: TComponent); override; destructor Destroy; override; procedure EnableButtons(AButtons: TNavigateButtons; ADataSourceEnabled: Boolean; ASetEnabled: TProc<TNavigateButton, Boolean>); procedure DisableButtons(ASetEnabled: TProc<TNavigateButton, Boolean>); procedure ExecuteButton(AButton: TNavigateButton; AConfirmDelete: TFunc<Boolean>); procedure Next; procedure Prior; procedure First; procedure Last; procedure Insert; procedure Delete; procedure Cancel; procedure Post; procedure Refresh; procedure Edit; procedure ApplyUpdates; procedure CancelUpdates; function CanApplyUpdates: Boolean; function CanCancelUpdates: Boolean; property Active: Boolean read GetActive; property Editing: Boolean read GetEditing; property Eof: Boolean read GetEOF; {Upper case EOF conflicts with C++} property BOF: Boolean read GetBOF; property Selected: Boolean read GetSelected; property DataSource: TBaseBindScopeComponent read FDataSource write SetDataSource; property CanModify: Boolean read GetCanModify; property CanInsert: Boolean read GetCanInsert; property CanDelete: Boolean read GetCanDelete; property CanRefresh: Boolean read GetCanRefresh; property OnEditingChanged: TNotifyEvent read FOnEditingChanged write FOnEditingChanged; property OnDataChanged: TNotifyEvent read FOnDataChanged write FOnDataChanged; property OnActiveChanged: TNotifyEvent read FOnActiveChanged write FOnActiveChanged; end; const NavigatorScrollButtons = [nbFirst, nbPrior, nbNext, nbLast]; NavigatorEditButtons = [nbInsert, nbDelete, nbEdit, nbPost, nbCancel, nbRefresh, nbApplyUpdates, nbCancelUpdates]; NavigatorButtons = [nbFirst, nbPrior, nbNext, nbLast, nbInsert, nbDelete, nbEdit, nbPost, nbCancel, nbRefresh, nbApplyUpdates, nbCancelUpdates]; NavigatorDefaultButtons = [nbFirst, nbPrior, nbNext, nbLast, nbInsert, nbDelete, nbEdit, nbPost, nbCancel, nbRefresh]; implementation { TBindNavigatorController } procedure TBindNavigatorController.ApplyUpdates; begin if FScopeNavigatorUpdates <> nil then FScopeNavigatorUpdates.ApplyUpdates; end; function TBindNavigatorController.CanApplyUpdates: Boolean; begin Result := (FScopeNavigatorUpdates <> nil) and FScopeNavigatorUpdates.CanApplyUpdates; end; function TBindNavigatorController.CanCancelUpdates: Boolean; begin Result := (FScopeNavigatorUpdates <> nil) and FScopeNavigatorUpdates.CanCancelUpdates; end; procedure TBindNavigatorController.Cancel; begin if Assigned(FScopeEditor) then FScopeEditor.Cancel end; procedure TBindNavigatorController.CancelUpdates; begin if FScopeNavigatorUpdates <> nil then FScopeNavigatorUpdates.CancelUpdates; end; constructor TBindNavigatorController.Create(AComponent: TComponent); begin inherited Create(AComponent); end; procedure TBindNavigatorController.Delete; begin if Assigned(FScopeEditor) then FScopeEditor.Delete end; destructor TBindNavigatorController.Destroy; begin SetDataSource(nil); // Clear notifications inherited; end; procedure TBindNavigatorController.DisableButtons( ASetEnabled: TProc<TNavigateButton, Boolean>); var I: TNavigateButton; begin for I := Low(TNavigateButton) to High(TNavigateButton) do ASetEnabled(I, False); end; type TState = (stUnknown, stEnable, stDisable); procedure TBindNavigatorController.EnableButtons(AButtons: TNavigateButtons; ADataSourceEnabled: Boolean; ASetEnabled: TProc<TNavigateButton, Boolean>); var FUpState: TState; FFirstState: TState; FLastState: TState; FDnState: TState; FCanModifyState: TState; FCanRefreshState: TState; FStateSelected: TState; function Selected: Boolean; begin if FStateSelected = stUnknown then if Self.Active and Self.Selected then FStateSelected := stEnable else FStateSelected := stDisable; Result := FStateSelected = stEnable; end; function CanModify: Boolean; begin if FCanModifyState = stUnknown then if ADataSourceEnabled and Self.CanModify then FCanModifyState := stEnable else FCanModifyState := stDisable; Result := FCanModifyState = stEnable; end; function CanRefresh: Boolean; begin if FCanRefreshState = stUnknown then if ADataSourceEnabled and Self.CanRefresh then FCanRefreshState := stEnable else FCanRefreshState := stDisable; Result := FCanRefreshState = stEnable; end; function UpEnable: Boolean; begin if FUpState = stUnknown then if ADataSourceEnabled and Selected and not Self.BOF then FUpState := stEnable else FUpState := stDisable; Result := FUpState = stEnable; end; function DnEnable: Boolean; begin if FDnState = stUnknown then if ADataSourceEnabled and Selected and not Self.EOF then FDnState := stEnable else FDnState := stDisable; Result := FDnState = stEnable; end; function LastEnable: Boolean; begin if FLastState = stUnknown then if ADataSourceEnabled and (Selected and not Self.EOF) or ((not Selected) and not (BOF and EOF)) then FLastState := stEnable else FLastState := stDisable; Result := FLastState = stEnable; end; function FirstEnable: Boolean; begin if FFirstState = stUnknown then if ADataSourceEnabled and (Selected and not Self.BOF) or ((not Selected) and not (BOF and EOF)) then FFirstState := stEnable else FFirstState := stDisable; Result := FFirstState = stEnable; end; var LButton: TNavigateButton; begin FUpState := stUnknown; FDnState := stUnknown; FFirstState := stUnknown; FLastState := stUnknown; FCanModifyState := stUnknown; FCanRefreshState := stUnknown; FStateSelected := stUnknown; for LButton in AButtons do begin case LButton of nbFirst: ASetEnabled(nbFirst, FirstEnable); nbPrior: ASetEnabled(nbPrior, UpEnable); nbNext: ASetEnabled(nbNext, DnEnable); nbLast: ASetEnabled(nbLast, LastEnable); nbInsert: ASetEnabled(nbInsert, CanModify and Self.CanInsert); nbDelete: ASetEnabled(nbDelete, Selected and CanModify and Self.CanDelete); nbEdit: ASetEnabled(nbEdit, CanModify and not Self.Editing); nbPost: ASetEnabled(nbPost, CanModify and Self.Editing); nbCancel: ASetEnabled(nbCancel, CanModify and Self.Editing); nbRefresh: ASetEnabled(nbRefresh, CanRefresh); nbApplyUpdates: ASetEnabled(nbApplyUpdates, CanModify and Self.CanApplyUpdates); nbCancelUpdates: ASetEnabled(nbCancelUpdates, CanModify and Self.CanCancelUpdates); else Assert(False); end end; end; procedure TBindNavigatorController.ExecuteButton(AButton: TNavigateButton; AConfirmDelete: TFunc<Boolean>); begin case AButton of nbPrior: Self.Prior; nbNext: Self.Next; nbFirst: Self.First; nbLast: Self.Last; nbInsert: Self.Insert; nbEdit: Self.Edit; nbCancel: Self.Cancel; nbPost: Self.Post; nbRefresh: Self.Refresh; nbDelete: if (not Assigned(AConfirmDelete)) or AConfirmDelete() then Self.Delete; nbApplyUpdates: Self.ApplyUpdates; nbCancelUpdates: Self.CancelUpdates; else Assert(False); end; end; procedure TBindNavigatorController.DoOnActiveChanged(Sender: TObject); begin if Assigned(FOnActiveChanged) then FOnActiveChanged(Sender); end; procedure TBindNavigatorController.DoOnDataChanged(Sender: TObject); begin if Assigned(FOnDataChanged) then FOnDataChanged(Sender); end; procedure TBindNavigatorController.DoOnDataScrolled(Sender: TObject; Distance: Integer); begin if Assigned(FOnDataChanged) then FOnDataChanged(Sender); end; procedure TBindNavigatorController.DoOnEditingChanged(Sender: TObject); begin if Assigned(FOnEditingChanged) then FOnEditingChanged(Sender); end; procedure TBindNavigatorController.Edit; begin if Assigned(FScopeEditor) then FScopeEditor.Edit end; procedure TBindNavigatorController.First; begin if Assigned(FScopeNavigator) then FScopeNavigator.First end; function TBindNavigatorController.GetActive: Boolean; begin if Assigned(FScopeState) then Result := FScopeState.Active else Result := False; end; function TBindNavigatorController.GetBOF: Boolean; begin if Assigned(FScopeNavigator) then Result := FScopeNavigator.BOF else Result := True; end; function TBindNavigatorController.GetCanModify: Boolean; begin if Assigned(FScopeState) then Result := FScopeState.CanModify else Result := False; end; function TBindNavigatorController.GetCanInsert: Boolean; begin if Assigned(FScopeState) then Result := FScopeState.CanInsert else Result := False; end; function TBindNavigatorController.GetCanDelete: Boolean; begin if Assigned(FScopeState) then Result := FScopeState.CanDelete else Result := False; end; function TBindNavigatorController.GetCanRefresh: Boolean; begin if Assigned(FScopeState) then Result := FScopeState.CanRefresh else Result := False; end; function TBindNavigatorController.GetEditing: Boolean; begin if Assigned(FScopeState) then Result := FScopeState.Editing else Result := False; end; function TBindNavigatorController.GetEOF: Boolean; begin if Assigned(FScopeNavigator) then Result := FScopeNavigator.EOF else Result := True; end; function TBindNavigatorController.GetSelected: Boolean; begin if Assigned(FScopeNavigator) then Result := FScopeNavigator.Selected else Result := True; end; procedure TBindNavigatorController.Insert; begin if Assigned(FScopeEditor) then FScopeEditor.Insert end; procedure TBindNavigatorController.Last; begin if Assigned(FScopeNavigator) then FScopeNavigator.Last; end; procedure TBindNavigatorController.Next; begin if Assigned(FScopeNavigator) then FScopeNavigator.Next; end; procedure TBindNavigatorController.Post; begin if Assigned(FScopeEditor) then FScopeEditor.Post end; procedure TBindNavigatorController.Prior; begin if Assigned(FScopeNavigator) then FScopeNavigator.Prior; end; procedure TBindNavigatorController.Refresh; begin if Assigned(FScopeEditor) then FScopeEditor.Refresh; end; procedure TBindNavigatorController.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = TOperation.opRemove then begin if AComponent = FDataSource then DataSource := nil; end; end; procedure TBindNavigatorController.SetDataSource(const Value: TBaseBindScopeComponent); begin if FDataSource <> nil then begin FScopeNavigator := nil; if FScopeState <> nil then begin FScopeState.RemoveActiveChanged(DoOnActiveChanged); FScopeState.RemoveDataSetChanged(DoOnDataChanged); FScopeState.RemoveDataSetScrolled(DoOnDataScrolled); FScopeState.RemoveEditingChanged(DoOnEditingChanged); end; FScopeState := nil; FScopeEditor := nil; FScopeNavigatorUpdates := nil; FDataSource.RemoveFreeNotification(Self); end; FDataSource := Value; if FDataSource <> nil then begin FDataSource.FreeNotification(Self); Supports(FDataSource, IScopeNavigator, FScopeNavigator); Supports(FDataSource, IScopeNavigatorUpdates, FScopeNavigatorUpdates); Supports(FDataSource, IScopeState, FScopeState); Supports(FDataSource, IScopeEditor, FScopeEditor); if Assigned(FScopeState) then begin FScopeState.AddActiveChanged(DoOnActiveChanged); FScopeState.AddDataSetChanged(DoOnDataChanged); FScopeState.AddDataSetScrolled(DoOnDataScrolled); FScopeState.AddEditingChanged(DoOnEditingChanged); end; end; end; end.
unit Getter.TrimBasics.Factory; interface uses SysUtils, Getter.TrimBasics, Getter.TrimBasics.FAT, Getter.TrimBasics.NTFS; type TMetaTrimBasicsGetter = class of TTrimBasicsGetter; TTrimBasicsGetterFactory = class public function GetSuitableTrimBasicsGetter(const FileToGetAccess: String): TTrimBasicsGetter; class function Create: TTrimBasicsGetterFactory; private function TryAndGetRightGetter: TTrimBasicsGetter; function TestGetterCompatibility(TTrimBasicsGetterToTry: TMetaTrimBasicsGetter; LastResult: TTrimBasicsGetter): TTrimBasicsGetter; var FFileToGetAccess: String; end; var TrimBasicsGetterFactory: TTrimBasicsGetterFactory; implementation class function TTrimBasicsGetterFactory.Create: TTrimBasicsGetterFactory; begin if TrimBasicsGetterFactory = nil then result := inherited Create as self else result := TrimBasicsGetterFactory; end; function TTrimBasicsGetterFactory.GetSuitableTrimBasicsGetter( const FileToGetAccess: String): TTrimBasicsGetter; begin FFileToGetAccess := FileToGetAccess; result := TryAndGetRightGetter; if result = nil then raise EArgumentNilException.Create('Argument Nil: ' + 'TrimBasicsGetter is not set'); end; function TTrimBasicsGetterFactory.TryAndGetRightGetter: TTrimBasicsGetter; begin result := nil; result := TestGetterCompatibility(TFATTrimBasicsGetter, result); result := TestGetterCompatibility(TNTFSTrimBasicsGetter, result); end; function TTrimBasicsGetterFactory.TestGetterCompatibility( TTrimBasicsGetterToTry: TMetaTrimBasicsGetter; LastResult: TTrimBasicsGetter): TTrimBasicsGetter; begin if LastResult <> nil then exit(LastResult); result := TTrimBasicsGetterToTry.Create(FFileToGetAccess); if not result.IsPartitionMyResponsibility then FreeAndNil(result); end; initialization TrimBasicsGetterFactory := TTrimBasicsGetterFactory.Create; finalization TrimBasicsGetterFactory.Free; end.
unit u_J16LevelWithFilterImp; interface uses Classes, SysUtils, StrUtils, u_ExamineImp, u_J08TaskIntf, u_J08Task, u_J16CommonDef; type TLevelWithFilterMeasure = Class(TCustomExamineItem, IStatText2XLS) Private FOption: TLevelWithFilterOption; Procedure InternalCheck(const Value: Boolean; const ExceptionInfo: String); Private FLevelDataFileList: TStringList; procedure CallBack_TextFileFound(const FileName: string; const Info: TSearchRec; var Abort: Boolean); Protected //inteface IStatText2XLS Procedure DoStatText2XLS; Protected Procedure Init; Override; Procedure DoProcess; Override; Public End; implementation uses u_GPIB_DEV2, u_J16Receiver, u_ExamineGlobal, u_J08WeakGlobal, PlumUtils, u_J16Utils, u_CommonDef, CnCommon, XLSReadWriteII5, XLSSheetData5, Xc12Utils5; const CONST_TXT_EXTFILENAME: Array[dmmAmpli..dmmDirect] of String = ('.放大.txt', '.直通.txt'); { TLevelWithFilterMeasure } procedure TLevelWithFilterMeasure.CallBack_TextFileFound( const FileName: string; const Info: TSearchRec; var Abort: Boolean); begin self.FLevelDataFileList.Add(FileName); Log(FileName); end; procedure TLevelWithFilterMeasure.DoProcess; {------------------------------------------------------------------------------ 共分10个段,每段三个测试频点,最后一个段为FM段,根据界面选项进行放大或直通模式下进行测试 ----------------------------------------------------------------------------} const CONST_SG_LEVEL: Array[0..1] of Integer = (-60, -40); CONST_BAND_FREQS: Array[0..9] of Array[0..2] of Integer = ( (0500, 1000, 1490), (1500, 1800, 2180), (2200, 2600, 3100), (3200, 3800, 4600), (4700, 5500, 6700), (6800, 8300, 9700), (9800, 11500, 14100), (14200, 16600, 20600), (20700, 25000, 30000), (88000, 98000, 108000) ); // CONST_MODULS_FREQS: Array[0..1] of Integer = (15000, 90000); // CONST_TEST_LEVELS: Array[0..21] of Integer = (0, -10, -20, -30, -40, -50, -60, // -70, -80, -90, -100, -100, -90, -80, -70, -60, -50, -40, -30, -20, -10, 0); var InsLost: Double; CurrStep, TotalStep: Integer; var SG: ISignalGenerator; Radio: IJ08Receiver; Calibrator: ISlopeCalibrate; bid, pid, sid: integer; var ManualMode: TJ08_DevManualMode; LevelsMeasured: Array[0..9] of Array[0..2] of Double; Procedure SaveLevelsMeasured2TextFile; var iBand, iFreq : integer; TextFileName: String; StrList: TStringList; TextDir: STring; begin TextDir:= TextDir_NoFilter(); if Not DirectoryExists(TextDir) then begin ForceDirectories(TextDir); end; TextFileName:= TextDir + ProductSN + CONST_TXT_EXTFILENAME[ManualMode]; StrList:= TStringList.Create; try for iBand := 0 to Length(LevelsMeasured) - 1 do for iFreq := 0 to Length(LevelsMeasured[iBand]) - 1 do begin //FM不进行首尾0dBm激励的测试 StrList.Add(IntToStr(Trunc(LevelsMeasured[iBand, iFreq]))); end; StrList.SaveToFile(TextFileName); finally StrList.Free; end; Log('记录数据文件: ' + TextFileName); end; var iBand, iFreq: Integer; Modulate: TJ08_ModuType; FreqKHz: Integer; DummyHInt: STring; begin Log('------有滤波器电平读数测试(自动切换)------------'); Randomize(); self.FUI.SyncUI(@Self.FOption); CurrStep:= 0; TotalStep:= 31; InsLost:= FUI.ExamineItem.InlineInsertLost; Radio:= TJ16Receiver.Create; Calibrator:= Radio as ISlopeCalibrate; ManualMode:= dmmAmpli; if FOption.ManualMode = 1 then ManualMode:= dmmDirect; Log('----------'+CONST_STR_DEVMANUALMODE[ManualMode] + '模式 ' +InttoStr(CONST_SG_LEVEL[FOption.ManualMode])+ 'dBm -------------'); try {$IFNDEF Debug_Emu} SG:= TMG36XX.Create; With SG do begin pid:= 3; Iden:= 'SG'; LoadInstrumentParam(bid, pid, sid); Connnect(bid, pid, sid); end; if not Radio.ReceiverTrunedOn then Radio.OpenReceiver; Calibrator.SetCoeffValid( True ); WaitMS(100); Calibrator.LevelDataFormat( 1 ); WaitMS(100); InternalCheck(Radio.SetHiGain(damManual, ManualMode), '设置' + CONST_STR_DEVMANUALMODE[ManualMode] + '模式失败'); WaitMS(100); {$ENDIF} Log('打开接收机,上报校准后数据'); for iBand:= 0 to Length(CONST_BAND_FREQS) - 1 do begin Log('第'+ IntToStr(iBand + 1) +'段'); for iFreq := 0 to Length(CONST_BAND_FREQS[iBand]) - 1 do begin FreqKHz:= CONST_BAND_FREQS[iBand, iFreq]; if iBand <= Length(CONST_BAND_FREQS) - 2 then begin Modulate:= mtAM; end else begin Modulate:= mtFM; end; {$IFNDEF Debug_Emu} SG.SetFreqency(FreqKHz / 1000); SG.SetLevelDbm(CONST_SG_LEVEL[FOption.ManualMode] + InsLost); SG.SetOnOff(True); {$ENDIF} WaitMS(200); {$IFNDEF Debug_Emu} InternalCheck(Radio.SetFrequency(Modulate, FreqKHz * 1000), '设置频率失败'); {$ENDIF} WaitMS(self.FOption.StableDelay); {$IFDEF DEBUG_emu} if Modulate = mtAM then begin if ManualMode = dmmAmpli then LevelsMeasured[iBand, iFreq]:= -550 + Random(10) - 5 else LevelsMeasured[iBand, iFreq]:= -350 + Random(10) - 5; end else begin LevelsMeasured[iBand, iFreq]:= -5500 + Random(500) - 250 end; {$ELSE} InternalCheck(Radio.ReadLevel(LevelsMeasured[iBand, iFreq], Modulate), '读取电平值失败'); // InternalCheck(Radio.ReadLevel(LevelsMeasured[iBand, iFreq], Modulate, DummyHint), '读取电平值失败'); {$ENDIF} Log(Format(' %6.0f @%.3f MHz', [LevelsMeasured[iBand, iFreq], FreqKHz / 1000])); // if k = 0 then // begin // CoeffSrc[i, j].AX:= CONST_LEVELS_PER_MODE[j, k]; // CoeffSrc[i, j].AY:= SampledLevels[i, j, k]; // end // else // begin // CoeffSrc[i, j].BX:= CONST_LEVELS_PER_MODE[j, k]; // CoeffSrc[i, j].BY:= SampledLevels[i, j, k]; // end; Inc(CurrStep); FUI.set_Percent((CurrStep / TotalStep) * 100); CheckWishStop(); end; end; // save to text file SaveLevelsMeasured2TextFile(); Inc(CurrStep); FUI.set_Percent((CurrStep / TotalStep) * 100); //curr step count value should be 13 CheckWishStop(); Log('完成'); finally Set_Status(esComplete); end; end; procedure TLevelWithFilterMeasure.DoStatText2XLS; var Level: Array[0..29] of Integer; LevelStrs: TStringList; Procedure ReadLevelValue(FileName: String); var Ptr: PInteger; i: Integer; begin Ptr:= @Level[0]; LevelStrs.LoadFromFile(FileName); if LevelStrs.Count <> 30 then Raise Exception.Create('数据记录的行数不正确'); for i := 0 to LevelStrs.Count - 1 do begin Ptr^:= StrToInt(LevelStrs[i]); Inc(Ptr); end; end; var i, iline: Integer; iCol: Integer; iRow: Integer; SN: String; StatXLSFileName: String; ASheet: TXLSWorksheet; rs: TResourceStream; wb: TXLSReadWriteII5; RangeExp: String; // CellType: TXLSCellType; var iMode: TJ08_DevManualMode; begin Log('统计文本被调用'); FLevelDataFileList:= TStringList.Create; LevelStrs:= TStringList.Create; try for iMode := dmmAmpli to dmmDirect do begin FLevelDataFileList.Clear(); CnCommon.FindFile(TextDir_NoFilter(), '*' + CONST_TXT_EXTFILENAME[iMode], CallBack_TextFileFound); FLevelDataFileList.Sort(); //每个文件共44个数 Log('共找到' + IntToStr(FLevelDataFileList.Count) + '个文件'); //把文件中的数据填充到EXCEL中, 从B49开始(B47是标题), 从B94开始((B92是标题)) if FLevelDataFileList.Count > 0 then begin wb:= TXLSReadWriteII5.Create(Nil); try StatXLSFileName:= TextDir_NoFilter() + '\数据统计.xlsx'; if FileExists(StatXLSFileName) then begin wb.LoadFromFile(StatXLSFilename); end else begin rs:= TResourceStream.Create(HInstance, 'StatTemplate', 'MYFILE'); try wb.LoadFromStream(rs); finally rs.Free; end; end; ASheet:= wb.Sheets[0]; iCol:= 1; for i := 0 to FLevelDataFileList.Count - 1 do begin ReadLevelValue(FLevelDataFileList[i]); SN:= ExtractFileName(FLevelDataFileList[i]); SetLength(SN, Length(SN) - Length(ExtractFileExt(SN))); SetLength(SN, Length(SN) - Length(ExtractFileExt(SN))); if iMode = dmmAmpli then iRow:= 46 else iRow:= 91; ASheet.ClearCell(iCol, iRow); ASheet.AsString[iCol, iRow]:= SN; Inc(iRow); for iLine := 0 to Length(Level) - 1 do begin if (iLine > 0) and (iLine Mod 3 = 0) then begin RangeExp:= Format('%s:%s', [ ColRowToRefStr(iCol, iRow + iLine - 2), ColRowToRefStr(iCol, iRow + iLine) ]); ASheet.AsFormula[iCol, iRow + iLine + 1]:= Format('Max(%s) - Min(%s)', [RangeExp, RangeExp]); // CellType:= ASheet.CellType[iCol, iRow + iLine + 1]; // Log(PChar(IntToStr(Integer(CellType)))); // ASheet.ClearCell(iCol, iRow + iLine + 1); // CellType:= ASheet.CellType[iCol, iRow + iLine + 1]; // Log(PChar(IntToStr(Integer(CellType)))); Inc(iRow); end; ASheet.ClearCell(iCol, iRow + iLine + 1); ASheet.AsInteger[iCol, iRow + iLine + 1]:= Level[iLine]; end; if (iLine > 0) and (iLine Mod 3 = 0) then begin RangeExp:= Format('%s:%s', [ ColRowToRefStr(iCol, iRow + iLine - 2), ColRowToRefStr(iCol, iRow + iLine) ]); ASheet.AsFormula[iCol, iRow + iLine + 1]:= Format('Max(%s) - Min(%s)', [RangeExp, RangeExp]); end; Inc(iCol); end; //填写公式, 每行的最小最大和差值 //COL: 1~iCol if iMode = dmmAmpli then iRow:= 46 //SN else iRow:= 91;//SN ASheet.AsString[iCol + 0, iRow]:= '最小值'; ASheet.AsString[iCol + 1, iRow]:= '最大值'; ASheet.AsString[iCol + 2, iRow]:= '差值'; for i := 1 to 40 do begin RangeExp:= Format('%s:%s', [ ColRowToRefStr(1, iRow + 1 + i), ColRowToRefStr(iCol - 1, iRow + 1 + i) ]); ASheet.AsFormula[iCol + 0, iRow + 1 + i]:= Format('Min(%s)', [RangeExp]); ASheet.AsFormula[iCol + 1, iRow + 1 + i]:= Format('Max(%s)', [RangeExp]); ASheet.AsFormula[iCol + 2, iRow + 1 + i]:= Format('Max(%s)-Min(%s)', [RangeExp, RangeExp]); end; wb.SaveToFile(StatXLSFileName); Log('统计完成'); finally wb.Free; end; end; end; finally LevelStrs.Free; FLevelDataFileList.Free; end; end; procedure TLevelWithFilterMeasure.Init; begin inherited; //FExamineCaption:= '电平测试'#$D#$A'(无滤波器)'; FExamineCaption:= '有滤波器电平'; // FExamineCaption:= '一本振'; // ExtractFileFromRes('LIB_INOUT32', 'inpout32.dll'); // ExtractFileFromRes('LIB_ELEXS', 'ELEXS.dll'); // ExtractFileFromRes('EXE_LO1', '一本振.exe'); end; procedure TLevelWithFilterMeasure.InternalCheck(const Value: Boolean; const ExceptionInfo: String); begin if Not Value then Raise Exception.Create(ExceptionInfo); end; end.
unit uPrincipal; { função CopyFile está presente na unit Windows que, portanto, precisa ser importada na cláusula uses da unit em que desejamos utilizar essa função. Function CopyFile(lpExistingFileName:PWideChar; lpNewFileName: PWideChar; bFailIfExists: LongBool): LongBool; ONDE: 1.lpExistingFileName: Caminho do arquivo a ser copiado; 2.lpNewFileName: Caminho do novo arquivo de destino; 3.bFailIfExists: Parâmetro do tipo boolean que define se o processo de cópia deve ser interrompido e uma falha apresentada caso o arquivo de destino já exista (valor True). Caso seja passado o valor False, o arquivo de destino será sobrescrito, caso exista. assim se passamos o último argumento como True, indicando que o processo deve falhar caso o arquivo de destino já exista. } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var pathOrigem, pathDestino: string; begin pathOrigem:= ExtractFileDir(GetCurrentDir)+'\10. CopyFile\pasta_origem\teste.txt'; //Pega o caminho do exe + caminho da pasta origem. pathDestino:= ExtractFileDir(GetCurrentDir)+'\10. CopyFile\pasta_destino\teste.txt';; //Pega o caminho do exe + caminho da pasta destino. if CopyFile(pchar(pathOrigem),pchar(pathDestino), true) then //Atenção: a função tem q converter string com o pchar(). ShowMessage('Arquivo copiado com sucesso') else ShowMessage('#Atenção# - Problema ao copiar o arquivo.'); end; procedure TForm1.Button2Click(Sender: TObject); var pathOrigem, pathDestino: string; begin pathOrigem:= ExtractFileDir(GetCurrentDir)+'\10. CopyFile\pasta_origem\teste.txt'; //Pega o caminho do exe + caminho da pasta origem. pathDestino:= ExtractFileDir(GetCurrentDir)+'\10. CopyFile\pasta_destino\teste.txt';; //Pega o caminho do exe + caminho da pasta destino. if FileExists(pathOrigem) then begin if not FileExists(pathdestino) then begin if CopyFile(pchar(pathOrigem),pchar(pathDestino),true) then begin ShowMessage('Arquivo de destino copiado com sucesso.') end; end else begin if MessageDlg('Foi encontrado um arquivo com o mesmo nome, deseja substituir o arquivo?',mtConfirmation,[mbYes,mbNo],0) = mrYes then begin if CopyFile(pchar(pathOrigem),pchar(pathDestino),false) then begin ShowMessage('Arquivo substituido com sucesso.'); end else begin ShowMessage('Copia não realizada!'); end; end; end; end; end; end.
unit LLVM.Imports.ExecutionEngine; interface //based on ExecutionEngine.h uses LLVM.Imports, LLVM.Imports.Types, LLVM.Imports.Target, LLVM.Imports.TargetMachine; procedure LLVMLinkInMCJIT; cdecl; external CLLVMLibrary; procedure LLVMLinkInInterpreter; cdecl; external CLLVMLibrary; type TLLVMGenericValueRef = type TLLVMRef; PLLVMGenericValueRef = ^TLLVMGenericValueRef; TLLVMExecutionEngineRef = type TLLVMRef; TLLVMMCJITMemoryManagerRef = type TLLVMRef; TLLVMMCJITCompilerOptions = packed record OptLevel: Cardinal; CodeModel: TLLVMCodeModel; NoFramePointerElim: TLLVMBool; EnableFastISel: TLLVMBool; MCJMM: TLLVMMCJITMemoryManagerRef; end; function LLVMCreateGenericValueOfInt(Ty: TLLVMTypeRef; N: UInt64; IsSigned: TLLVMBool): TLLVMGenericValueRef; cdecl; external CLLVMLibrary; function LLVMCreateGenericValueOfPointer(P: Pointer): TLLVMGenericValueRef; cdecl; external CLLVMLibrary; function LLVMCreateGenericValueOfFloat(Ty: TLLVMTypeRef; N: Double): TLLVMGenericValueRef; cdecl; external CLLVMLibrary; function LLVMGenericValueIntWidth(GenValRef: TLLVMGenericValueRef): Cardinal; cdecl; external CLLVMLibrary; function LLVMGenericValueToInt(GenVal: TLLVMGenericValueRef; IsSigned: TLLVMBool): UInt64; cdecl; external CLLVMLibrary; function LLVMGenericValueToPointer(GenVal: TLLVMGenericValueRef): Pointer; cdecl; external CLLVMLibrary; function LLVMGenericValueToFloat(TyRef: TLLVMTypeRef; GenVal: TLLVMGenericValueRef): Double; cdecl; external CLLVMLibrary; procedure LLVMDisposeGenericValue(GenVal: TLLVMGenericValueRef); cdecl; external CLLVMLibrary; function LLVMCreateExecutionEngineForModule(out OutEE: TLLVMExecutionEngineRef; M: TLLVMModuleRef; out OutError: TLLVMChar): TLLVMBool; cdecl; external CLLVMLibrary; function LLVMCreateInterpreterForModule(out OutInterp: TLLVMExecutionEngineRef; M: TLLVMModuleRef; out OutError: TLLVMChar): TLLVMBool; cdecl; external CLLVMLibrary; function LLVMCreateJITCompilerForModule(out OutJIT: TLLVMExecutionEngineRef; M: TLLVMModuleRef; OptLevel: Cardinal; out OutError: TLLVMChar): TLLVMBool; cdecl; external CLLVMLibrary; procedure LLVMInitializeMCJITCompilerOptions(var Options: TLLVMMCJITCompilerOptions; SizeOfOptions: TLLVMSizeT = SizeOf(TLLVMMCJITCompilerOptions)); cdecl; external CLLVMLibrary; function LLVMCreateMCJITCompilerForModule(out OutJIT: TLLVMExecutionEngineRef; M: TLLVMModuleRef; var Options: TLLVMMCJITCompilerOptions; SizeOfOptions: TLLVMSizeT; out OutError: TLLVMChar): TLLVMBool; cdecl; external CLLVMLibrary; procedure LLVMDisposeExecutionEngine(EE: TLLVMExecutionEngineRef); cdecl; external CLLVMLibrary; procedure LLVMRunStaticConstructors(EE: TLLVMExecutionEngineRef); cdecl; external CLLVMLibrary; procedure LLVMRunStaticDestructors(EE: TLLVMExecutionEngineRef); cdecl; external CLLVMLibrary; function LLVMRunFunctionAsMain(EE: TLLVMExecutionEngineRef; F: TLLVMValueRef; ArgC: Cardinal; ArgV: Pointer; EnvP: Pointer): Integer; cdecl; external CLLVMLibrary; function LLVMRunFunction(EE: TLLVMExecutionEngineRef; F: TLLVMValueRef; NumArgs: Cardinal; Args: PLLVMGenericValueRef): TLLVMGenericValueRef; cdecl; external CLLVMLibrary; procedure LLVMFreeMachineCodeForFunction(EE: TLLVMExecutionEngineRef; F: TLLVMValueRef); cdecl; external CLLVMLibrary; procedure LLVMAddModule(EE: TLLVMExecutionEngineRef; M: TLLVMModuleRef); cdecl; external CLLVMLibrary; function LLVMRemoveModule(EE: TLLVMExecutionEngineRef; M: TLLVMModuleRef; out OutMod: TLLVMModuleRef; out OutError: TLLVMChar): TLLVMBool; cdecl; external CLLVMLibrary; function LLVMFindFunction(EE: TLLVMExecutionEngineRef; const Name: PLLVMChar; out OutFn: TLLVMValueRef): TLLVMBool; cdecl; external CLLVMLibrary; function LLVMRecompileAndRelinkFunction(EE: TLLVMExecutionEngineRef; Fn: TLLVMValueRef): Pointer; cdecl; external CLLVMLibrary; function LLVMGetExecutionEngineTargetData(EE: TLLVMExecutionEngineRef): TLLVMTargetDataRef; cdecl; external CLLVMLibrary; function LLVMGetExecutionEngineTargetMachine(EE: TLLVMExecutionEngineRef): TLLVMTargetMachineRef; cdecl; external CLLVMLibrary; procedure LLVMAddGlobalMapping(EE: TLLVMExecutionEngineRef; Global: TLLVMValueRef; Addr: Pointer); cdecl; external CLLVMLibrary; function LLVMGetPointerToGlobal(EE: TLLVMExecutionEngineRef; Global: TLLVMValueRef): Pointer; cdecl; external CLLVMLibrary; function LLVMGetGlobalValueAddress(EE: TLLVMExecutionEngineRef; const Name: PLLVMChar): UInt64; cdecl; external CLLVMLibrary; function LLVMGetFunctionAddress(EE: TLLVMExecutionEngineRef; const Name: PLLVMChar): UInt64; cdecl; external CLLVMLibrary; type TLLVMMemoryManagerAllocateCodeSectionCallback = function(Opaque: Pointer; Size: NativeUInt; Alignment: Cardinal; SectionID: Cardinal; const SectionName: PLLVMChar): Pointer; cdecl; TLLVMMemoryManagerAllocateDataSectionCallback = function(Opaque: Pointer; SIze: NativeUInt; Alignment: Cardinal; SectionID: Cardinal; const SectionName: PLLVMChar; IsReadOnly: TLLVMBool): Pointer; cdecl; TLLVMMemoryManagerFinalizeMemoryCallback = function(Opaque: Pointer; out ErrMsg: PLLVMChar): TLLVMBool; cdecl; TLLVMMemoryManagerDestroyCallback = procedure(Opaque: Pointer); cdecl; {** * Create a simple custom MCJIT memory manager. This memory manager can * intercept allocations in a module-oblivious way. This will return NULL * if any of the passed functions are NULL. * * @param Opaque An opaque client object to pass back to the callbacks. * @param AllocateCodeSection Allocate a block of memory for executable code. * @param AllocateDataSection Allocate a block of memory for data. * @param FinalizeMemory Set page permissions and flush cache. Return 0 on * success, 1 on error. *} function LLVMCreateSimpleMCJITMemoryManager( Opaque: Pointer; AllocateCodeSection: TLLVMMemoryManagerAllocateCodeSectionCallback; AllocateDataSection: TLLVMMemoryManagerAllocateDataSectionCallback; FinalizeMemory: TLLVMMemoryManagerFinalizeMemoryCallback; Destroy: TLLVMMemoryManagerDestroyCallback): TLLVMMCJITMemoryManagerRef; cdecl; external CLLVMLibrary; procedure LLVMDisposeMCJITMemoryManager(MM: TLLVMMCJITMemoryManagerRef); cdecl; external CLLVMLibrary; (*===-- JIT Event Listener functions -------------------------------------===*) function LLVMCreateGDBRegistrationListener: TLLVMJITEventListenerRef; cdecl; external CLLVMLibrary; function LLVMCreateIntelJITEventListener: TLLVMJITEventListenerRef; cdecl; external CLLVMLibrary; function LLVMCreateOProfileJITEventListener: TLLVMJITEventListenerRef; cdecl; external CLLVMLibrary; function LLVMCreatePerfJITEventListener: TLLVMJITEventListenerRef; cdecl; external CLLVMLibrary; implementation end.
unit main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, XPMan, filedrag, ComCtrls, Menus, PSVClass, ToolWin, ImgList, BrowseForFolderU; var psvFile : TPSVFile; initialSaveDir : string; type TForm1 = class(TForm) XPManifest1: TXPManifest; FileDrag1: TFileDrag; ListView1: TListView; MainMenu1: TMainMenu; File1: TMenuItem; OpenPSVfile1: TMenuItem; Extractfile1: TMenuItem; ExtractAllFiles1: TMenuItem; N1: TMenuItem; Exit1: TMenuItem; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; StatusBar1: TStatusBar; ToolBar1: TToolBar; btnLoadFile: TToolButton; btnSaveFile: TToolButton; btnExtractAll: TToolButton; ImageList1: TImageList; PopupMenu1: TPopupMenu; ExtractFile2: TMenuItem; ExtractAll1: TMenuItem; Help1: TMenuItem; About1: TMenuItem; ToolButton4: TToolButton; btnSavePS1: TToolButton; ExtractPS1Save1: TMenuItem; ExtractPS1Save2: TMenuItem; SaveDialog2: TSaveDialog; Options1: TMenuItem; procedure FileDrag1Drop(Sender: TObject); procedure Exit1Click(Sender: TObject); procedure OpenPSVfile1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Extractfile1Click(Sender: TObject); procedure ExtractFile; procedure ExtractAll; procedure ExtractAllFiles1Click(Sender: TObject); procedure btnExtractAllClick(Sender: TObject); procedure btnLoadFileClick(Sender: TObject); procedure btnSaveFileClick(Sender: TObject); procedure loadFile; procedure ExtractFile2Click(Sender: TObject); procedure ExtractAll1Click(Sender: TObject); procedure PopupMenu1Popup(Sender: TObject); Procedure ClearDisplay; procedure FormShow(Sender: TObject); procedure showAbout; procedure About1Click(Sender: TObject); procedure ExtractPS1; procedure ExtractPS1Save2Click(Sender: TObject); procedure btnSavePS1Click(Sender: TObject); procedure ExtractPS1Save1Click(Sender: TObject); procedure Options1Click(Sender: TObject); procedure showoptions; procedure SaveDialog2TypeChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses PSVFormat, about, options; {$R *.dfm} procedure TForm1.About1Click(Sender: TObject); begin showAbout; end; procedure TForm1.ClearDisplay; begin ListView1.Clear; end; procedure TForm1.Exit1Click(Sender: TObject); begin Close; end; procedure TForm1.ExtractAll; var location : string; begin if ListView1.Items.Count > 0 then begin location := ''; location := BrowseforFolder('Choose location to save to..', initialSaveDir, True); if location <> '' then begin if PSVFile.extractAllFiles(location) then begin statusbar1.SimpleText := 'Extraction complete'; end else begin statusbar1.SimpleText := 'Extraction cancelled'; end; end else begin statusbar1.SimpleText := 'Extraction cancelled'; end; end else begin statusbar1.SimpleText := 'Nothing to Extract!'; end; end; procedure TForm1.ExtractAll1Click(Sender: TObject); begin ExtractAll; end; procedure TForm1.ExtractAllFiles1Click(Sender: TObject); begin ExtractAll; end; procedure TForm1.ExtractFile; var anItem : TlistItem; begin if ListView1.SelCount > 0 then begin anItem := listView1.Selected; saveDialog1.FileName := PSVFile.CleanFileName(anItem.Caption); if saveDialog1.Execute then begin if PSVFile.extractAFile(anItem.Index, saveDialog1.FileName) then begin StatusBar1.SimpleText := 'File saved'; end else begin StatusBar1.SimpleText := 'Extraction aborted'; end; end; end else begin StatusBar1.SimpleText := 'No file selected to extract'; end; end; procedure TForm1.Extractfile1Click(Sender: TObject); Begin ExtractFile; end; procedure TForm1.ExtractFile2Click(Sender: TObject); begin ExtractFile; end; procedure TForm1.ExtractPS1; begin saveDialog2.FileName := '*.mcs'; saveDialog2.DefaultExt := 'mcs'; saveDialog2.FilterIndex := 1; if SaveDialog2.Execute then begin if PSVFile.extractPS1Save(saveDialog2.FileName) then begin StatusBar1.SimpleText := 'File saved'; end else begin StatusBar1.SimpleText := 'Extraction aborted'; end; end; end; procedure TForm1.ExtractPS1Save1Click(Sender: TObject); begin ExtractPS1 end; procedure TForm1.ExtractPS1Save2Click(Sender: TObject); begin ExtractPS1 end; procedure TForm1.FileDrag1Drop(Sender: TObject); begin clearDisplay; if not PSVFile.loadFile(FileDrag1.Files.Strings[0]) then begin showmessage('Error loading file'); StatusBar1.SimpleText := 'Error loading file!'; PSVFile.Clear; end else begin StatusBar1.SimpleText := ExtractFileName(FileDrag1.Files.Strings[0]) + ' Loaded'; end; end; procedure TForm1.FormCreate(Sender: TObject); begin PSVFile := TPSVFile.Create; UseLatestCommonDialogs := True; ReportMemoryLeaksOnShutdown := DebugHook <> 0; end; procedure TForm1.FormDestroy(Sender: TObject); begin PSVFile.Destroy; end; procedure TForm1.FormShow(Sender: TObject); begin if paramcount > 0 then begin if ExtractFileExt(lowercase(paramstr(1))) = '.psv' then begin if not PSVFile.loadFile(paramstr(1)) then begin showmessage('Error loading file'); StatusBar1.SimpleText := 'Error loading file!'; PSVFile.Clear; end else begin StatusBar1.SimpleText := ExtractFileName(paramstr(1)) + ' Loaded'; end; end else begin StatusBar1.SimpleText := 'File not loaded!'; end; end; end; procedure TForm1.loadFile; begin if OpenDialog1.Execute then begin clearDisplay; if not PSVFile.loadFile(openDialog1.FileName) then begin showmessage('Error loading file'); StatusBar1.SimpleText := 'Error loading file!'; PSVFile.Clear; end else begin StatusBar1.SimpleText := ExtractFileName(openDialog1.FileName) + ' Loaded'; end; end else begin StatusBar1.SimpleText := 'Load cancelled'; end; end; procedure TForm1.OpenPSVfile1Click(Sender: TObject); begin LoadFile; end; procedure TForm1.Options1Click(Sender: TObject); begin showOptions; end; procedure TForm1.PopupMenu1Popup(Sender: TObject); begin //No items! if ListView1.Items.Count > 0 then begin popupMenu1.Items[0].Enabled := True; popupMenu1.Items[1].Enabled := True; end else begin popupMenu1.Items[0].Enabled := False; popupMenu1.Items[1].Enabled := False; end; //No item selected if ListView1.SelCount > 0 then begin popupMenu1.Items[0].Enabled := True; end else begin popupMenu1.Items[0].Enabled := False; end; end; procedure TForm1.SaveDialog2TypeChange(Sender: TObject); begin if SaveDialog2.FilterIndex = 1 then begin SaveDialog2.DefaultExt := 'mcs'; end; if SaveDialog2.FilterIndex = 2 then begin SaveDialog2.DefaultExt := ''; end; end; procedure TForm1.showAbout; begin AboutBox.ShowModal; end; procedure TForm1.showoptions; var optionMenu : TOptionsForm; begin optionMenu := TOptionsForm.Create(Form1); optionMenu.ShowModal; optionMenu.Free; end; procedure TForm1.btnLoadFileClick(Sender: TObject); begin LoadFile; end; procedure TForm1.btnSaveFileClick(Sender: TObject); begin ExtractFile; end; procedure TForm1.btnSavePS1Click(Sender: TObject); begin ExtractPS1 end; procedure TForm1.btnExtractAllClick(Sender: TObject); begin ExtractAll; end; end.
unit Unit3; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Memo, ClientModuleUnit1, FMX.Controls.Presentation, DBXJSON, System.JSON, Datasnap.DSCommon, FMX.ScrollBox, FMX.Edit, AndroidApi.JNI.Media, System.IOUtils, FMX.TabControl; type TMyCallback = class(TDBXCallback) public function Execute(const Arg: TJSONValue): TJSONValue; override; end; TForm3 = class(TForm) DSClientCallbackChannelManager1: TDSClientCallbackChannelManager; MemoLog: TMemo; ButtonBroadcast: TButton; EditMsg: TEdit; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ButtonBroadcastClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormSaveState(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { Private declarations } FMyCallbackName:string; procedure QueueLogMsg(const s:string); procedure Beep(); public { Public declarations } procedure LogMsg(const s:string); end; var Form3: TForm3; ToneGenerator: JToneGenerator; implementation uses DSProxy; // for “TDSTunnelSession” //uses DSProxy; // <- for “TDSAdminClient” {$R *.fmx} {$R *.LgXhdpiPh.fmx ANDROID} {$R *.Windows.fmx MSWINDOWS} procedure TForm3.Button1Click(Sender: TObject); begin ClientModule1.ServerMethods1Client.LogString('button 1'); end; procedure TForm3.Button2Click(Sender: TObject); begin ClientModule1.ServerMethods1Client.LogString('button 2'); end; procedure TForm3.ButtonBroadcastClick(Sender: TObject); var AClient: TDSAdminClient; begin AClient := TDSAdminClient.Create(ClientModule1.SQLConnection1.DBXConnection); try AClient.BroadcastToChannel( DSClientCallbackChannelManager1.ChannelName, TJSONString.Create(EditMsg.Text) ); finally AClient.Free; end; end; procedure TForm3.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; {$IFDEF ANDROID} if assigned(ToneGenerator) then ToneGenerator.release; {$ENDIF} end; procedure TForm3.FormCreate(Sender: TObject); var R: TBinaryReader; begin DSClientCallbackChannelManager1.ManagerId := TDSSessionHelper.GenerateSessionId; FMyCallbackName := TDSSessionHelper.GenerateSessionId; DSClientCallbackChannelManager1.RegisterCallback( FMyCallbackName, TMyCallback.Create ); SaveState.StoragePath := TPath.GetHomePath; if SaveState.Stream.Size > 0 then begin // Recover previously typed text in Edit1 control. R := TBinaryReader.Create(SaveState.Stream); try EditMsg.Text := R.ReadString; finally R.Free; end; end; end; procedure TForm3.FormSaveState(Sender: TObject); var W: TBinaryWriter; begin SaveState.Stream.Clear; // Current state is only saved when something was edited. // If nothing has changed, the state will be removed this way. if EditMsg.Text.Length > 0 then begin // Save typed text in Edit1 control. W := TBinaryWriter.Create(SaveState.Stream); try W.Write(EditMsg.Text); finally W.Free; end; end; end; procedure TForm3.FormShow(Sender: TObject); begin inherited; {$IFDEF ANDROID} ToneGenerator:=nil; {$ENDIF} //TabControl1.TabIndex:=0; //timer1.Enabled:=true; end; { TMyCallback } function TMyCallback.Execute(const Arg: TJSONValue): TJSONValue; begin Form3.QueueLogMsg(Arg.ToString); Form3.beep(); Result := TJSONTrue.Create; end; procedure TForm3.QueueLogMsg(const s: string); begin TThread.Queue(nil, procedure begin Form3.LogMsg(s) end ); end; procedure TForm3.Timer1Timer(Sender: TObject); begin //TabControl1.TabIndex:=1; //Timer1.Enabled:=false; EditMsg.Text:='TEST'; Form3.ButtonBroadcastClick(Form3); end; procedure TForm3.LogMsg(const s: string); begin MemoLog.Lines.Add(DateTimeToStr(Now) + ': ' + s); end; procedure TForm3.beep; var Volume: Integer; StreamType: Integer; ToneType: Integer; begin {$IFDEF ANDROID} if not assigned(ToneGenerator) then begin Volume:= TJToneGenerator.JavaClass.MAX_VOLUME; // çàäàåì ãðîìêîñòü StreamType:= TJAudioManager.JavaClass.STREAM_NOTIFICATION; ToneType:= TJToneGenerator.JavaClass.TONE_CDMA_ABBR_ALERT; // òèï çâóêà ToneGenerator:= TJToneGenerator.JavaClass.init(StreamType, Volume); end; ToneGenerator.startTone(ToneType,500); {$ENDIF} end; end.
unit Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.PG, FireDAC.Phys.PGDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.Stan.StorageJSON, Redis.Commons, Redis.Client, Redis.NetLib.INDY, Redis.Values ; type TForm1 = class(TForm) Panel1: TPanel; Panel2: TPanel; Button1: TButton; Button2: TButton; Panel3: TPanel; DBGrid1: TDBGrid; FDConnection1: TFDConnection; FDQueryListarVenda: TFDQuery; DataSource1: TDataSource; Label1: TLabel; Label2: TLabel; Panel4: TPanel; Panel5: TPanel; FDQueryNovaVenda: TFDQuery; Button3: TButton; CheckBox1: TCheckBox; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } FRedis: IRedisClient; FCodigoVendedor: Integer; FChaveCache: string; procedure ListarVendas(const UsarCache: Boolean); procedure ExecutarVenda; procedure LimparCache; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin Self.ListarVendas(Self.CheckBox1.Checked); end; procedure TForm1.Button2Click(Sender: TObject); begin Self.ExecutarVenda; end; procedure TForm1.Button3Click(Sender: TObject); begin Self.LimparCache(); end; procedure TForm1.ExecutarVenda; { Ao fazer uma venda os dados são registrados no banco de dados e por isso o cache deve ser limpo para evitar inconsistências } var sCodigoProduto: string; begin InputQuery('Nova venda', 'Código do Produto:', sCodigoProduto); Self.FDQueryNovaVenda.ParamByName('vendedor').Value := Self.FCodigoVendedor; Self.FDQueryNovaVenda.ParamByName('produto').Value := StrToInt(sCodigoProduto); Self.FDQueryNovaVenda.ExecSQL; Self.LimparCache; end; procedure TForm1.FormCreate(Sender: TObject); begin Self.FDConnection1.Open; Self.FRedis := TRedisClient.Create('localhost', 6379); Self.FRedis.Connect; Self.FCodigoVendedor := 1; Self.FChaveCache := Format('CACHE:MOBILEDAYS:2020:VENDAS:%d', [Self.FCodigoVendedor]); end; procedure TForm1.LimparCache; begin Self.FRedis.DEL(Self.FChaveCache); end; procedure TForm1.ListarVendas(const UsarCache: Boolean); { Aqui exemplificamos um fluxo de cacheamento. Obviamente que este código estaria no servidor RESTful eventualmente desenvolvido em DataSnap. Codificamos aqui para efeitos didáticos. } const SETE_DIAS = 60 * 60 * 24 * 7; var cInicio: Cardinal; sOrigem: string; oDados: TRedisString; oStream: TStringStream; begin cInicio := GetTickCount; oStream := TStringStream.Create; Self.FDQueryListarVenda.Close; try if UsarCache then oDados := Self.FRedis.GET(Self.FChaveCache); if oDados.HasValue then begin sOrigem := 'REDIS'; oStream.WriteString(oDados); oStream.Seek(0, 0); Self.FDQueryListarVenda.LoadFromStream(oStream, sfJSON); Self.FRedis.EXPIRE(Self.FChaveCache, SETE_DIAS); end else begin sOrigem := 'SGBD'; Self.FDQueryListarVenda.Open; if UsarCache then begin Self.FDQueryListarVenda.SaveToStream(oStream, sfJSON); oStream.Seek(0, 0); Self.FRedis.&SET(Self.FChaveCache, oStream.DataString, SETE_DIAS); end; end; finally Self.Panel5.Caption := Format('%s: %g segundos', [sOrigem, (GetTickCount - cInicio) / 1000]); oStream.Free; end; end; end.
(* PrimeVectorClass: MM, 2020-06-05 *) (* ------ *) (* Simple Class to store Prime Vectors in an IntArray *) (* ========================================================================= *) UNIT PrimeVectorClass; INTERFACE USES VectorClass; TYPE PrimeVector = ^PrimeVectorObj; PrimeVectorObj = OBJECT(VectorObj) PUBLIC CONSTRUCTOR Init; DESTRUCTOR Done; VIRTUAL; PROCEDURE Add(value: INTEGER); VIRTUAL; PROCEDURE InsertElementAt(pos, value: INTEGER); VIRTUAL; END; (* PrimeVectorObj *) IMPLEMENTATION FUNCTION IsPrime(value: INTEGER): BOOLEAN; VAR i, count, check: INTEGER; BEGIN (* IsPrime *) count := 0; FOR i := 2 TO value - 1 DO BEGIN IF (value MOD i = 0) THEN Inc(count); END; (* FOR *) IsPrime := count = 0; END; (* IsPrime *) CONSTRUCTOR PrimeVectorObj.Init; BEGIN (* PrimeVectorObj.Init *) INHERITED Init; END; (* PrimeVectorObj.Init *) DESTRUCTOR PrimeVectorObj.Done; BEGIN (* PrimeVectorObj.Done *) INHERITED Done; END; (* PrimeVectorObj.Done *) PROCEDURE PrimeVectorObj.Add(value: INTEGER); BEGIN (* PrimeVectorObj.Add *) IF (IsPrime(value)) THEN INHERITED Add(value) ELSE WriteLn('"', value, '" is not a Prime Number, cannot be added.'); END; (* PrimeVectorObj.Add *) PROCEDURE PrimeVectorObj.InsertElementAt(pos, value: INTEGER); BEGIN (* PrimeVectorObj.InsertElementAt *) IF (IsPrime(value)) THEN INHERITED InsertElementAt(pos, value) ELSE WriteLn('"', value, '" is not a Prime Number, cannot be added.'); END; (* PrimeVectorObj.InsertElementAt *) END. (* PrimeVectorObj *)
program vectorordenado; const dimF = 8; {Dimensión física del vector} type vector = array [1..dimF] of integer; dim = 0..dimF; {----------------------------------------------------------------------------- CARGARVECTORORDENADO - Carga ordenadamente nros aleatorios entre 0 y 100 en el vector hasta que llegue el nro 99 o hasta que se complete el vector} Procedure cargarVectorOrdenado ( var vec: vector; var dimL: dim); var d, pos, j: integer; begin Randomize; { Inicializa la secuencia de random a partir de una semilla} dimL := 0; d:= random(100); while (d <> 99) and ( dimL < dimF ) do begin pos:= 1; while (pos <= dimL) and (vec[pos]< d) do pos:= pos + 1; for j:= dimL downto pos do vec[j+1]:= vec[j] ; vec[pos]:= d; dimL := dimL + 1; d:= random(100) end; end; {----------------------------------------------------------------------------- IMPRIMIRVECTOR - Imprime todos los nros del vector } Procedure imprimirVector ( var vec: vector; var dimL: dim ); var i: dim; begin for i:= 1 to dimL do write ('-----'); writeln; write (' '); for i:= 1 to dimL do begin if(vec[i] < 9)then write ('0'); write(vec[i], ' | '); end; writeln; for i:= 1 to dimL do write ('-----'); writeln; writeln; End; procedure Buscar (num: integer; dimL,inf,sup: dim; v:vector; var exito: boolean); var mitad:dim; begin if (dimL=0) then exito:=false else begin if (v[dimL]=num) then exito:=true else begin mitad:=(inf+sup)div 2; if (dimL<>mitad) then if (v[mitad]<num) then Buscar(num,mitad,mitad,sup,v,exito) else Buscar(num,mitad,inf,mitad,v,exito) else exito:=false end; end; end; {PROGRAMA PRINCIPAL} var v: vector; dimL : dim; num: integer; exito:boolean; begin cargarVectorOrdenado(v,dimL); writeln('Nros almacenados: '); imprimirVector(v, dimL); read(num); Buscar(num,dimL,1,dimL,v,exito); write(exito); readln(num); end.
unit JACell; {$mode objfpc}{$H+} {$i JA.inc} interface uses JATypes, JAList, JASpatial; type PJACell = ^TJACell; TJACellLeaf = record Cell : PJACell; GridPosition : TVec2SInt16; Neighbours : PJACell; {} end; PJACellLeaf = ^TJACellLeaf; TJACell = record Split : boolean; Depth : SInt16; BoundsRect : TJRectSInt32; BoundsRadius : Float32; Cells : PJACell; {child cells} Leaf : PJACellLeaf; {assigned if leaf cell} Nodes : PJAList; {nodes inside this cell} NodesCount : UInt16; PathCost : Float32; PathBlock : boolean; Data : pointer; end; function JACellCreate() : PJACell; function JACellDestroy(ACell : PJACell) : boolean; function JACellSplit(ACell : PJACell; AMinimumSize : Float32 =1.0) : SInt32; {recursively split down to a minimum size} //procedure Split(AMinimumSize : JFloat32=1.0); virtual; abstract; //procedure Combine; virtual; abstract;{collect all child entites then remove child nodes} //function HitTest(APosition : TVec3):boolean; {test if vertex inside Node} //function GetLeaf(APosition : TVec3):TJSpatialNode; virtual; function JACellNodePush(ACell : PJACell; ANode : PJASpatial) : PJACell; {returns absolute leaf cell for the pushed node} function JACellNodeExtract(ACell : PJACell; ANode : PJASpatial) : PJASpatial; {returns extracted node or nil on no extraction} function JACellNodePick(ACell : PJACell; APosition : TVec2; ARadius : Float32) : PJASpatial; {returns result node or nil if no match} implementation function JACellCreate : PJACell; begin Result := JAMemGet(SizeOf(TJACell)); end; function JACellDestroy(ACell : PJACell) : boolean; begin JAMemFree(ACell,SizeOf(TJACell)); end; function JACellSplit(ACell : PJACell; AMinimumSize : Float32) : SInt32; var I : SInt32; BoundingBoxes : array of TJBBox; begin //ExtractAABBCorners(AABB,AABBCorners); {if any accuracy issues creep in, -0.1 from box width} { if (FNodeBoundingBox.Max.X-FNodeBoundingBox.Min.X) > AMinimumSize then {split} begin SetLength(BoundingBoxes, FNodeCount); with FNodeBoundingBox do begin BoundingBoxes[0].Min.X := Min.X; BoundingBoxes[0].Max.X := (Max.X-Min.X)*0.5+Min.X; BoundingBoxes[0].Min.Z := Min.Z; BoundingBoxes[0].Max.Z := (Max.Z-Min.Z)*0.5+Min.Z; BoundingBoxes[1].Min.X := (Max.X-Min.X)*0.5+Min.X; BoundingBoxes[1].Max.X := Max.X; BoundingBoxes[1].Min.Z := Min.Z; BoundingBoxes[1].Max.Z := (Max.Z-Min.Z)*0.5+Min.Z; BoundingBoxes[2].Min.X := Min.X; BoundingBoxes[2].Max.X := (Max.X-Min.X)*0.5+Min.X; BoundingBoxes[2].Min.Z := (Max.Z-Min.Z)*0.5+Min.Z; BoundingBoxes[2].Max.Z := Max.Z; BoundingBoxes[3].Min.X := (Max.X-Min.X)*0.5+Min.X; BoundingBoxes[3].Max.X := Max.X; BoundingBoxes[3].Min.Z := (Max.Z-Min.Z)*0.5+Min.Z; BoundingBoxes[3].Max.Z := Max.Z; BoundingBoxes[0].Min.Y := Min.Y; BoundingBoxes[1].Min.Y := Min.Y; BoundingBoxes[2].Min.Y := Min.Y; BoundingBoxes[3].Min.Y := Min.Y; BoundingBoxes[0].Max.Y := Max.Y; BoundingBoxes[1].Max.Y := Max.Y; BoundingBoxes[2].Max.Y := Max.Y; BoundingBoxes[3].Max.Y := Max.Y; end; for I := 0 to 3 do begin FNodes[I] := TJSpatialNodeQuad.Create(BoundingBoxes[I], Self, FNodeDepth+1); FNodes[I].Split(AMinimumSize); end; FNodeSplit := true; end; } end; function JACellNodePush(ACell : PJACell; ANode : PJASpatial) : PJACell; begin end; function JACellNodeExtract(ACell : PJACell; ANode : PJASpatial) : PJASpatial; begin end; function JACellNodePick(ACell : PJACell; APosition : TVec2; ARadius : Float32) : PJASpatial; begin end; end.
unit Exceptions; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Diagnostics, System.Threading; type TfExceptions = class(TForm) Memo1: TMemo; Button1: TButton; Memo2: TMemo; Label2: TLabel; Button2: TButton; Memo3: TMemo; Label1: TLabel; Label3: TLabel; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button2Click(Sender: TObject); private FPath: string; function LoadNumbers(AIgnore: Integer): Boolean; procedure WriteMemoException(E: Exception); public end; var fExceptions: TfExceptions; implementation {$R *.dfm} procedure TfExceptions.Button1Click(Sender: TObject); var LStopWatch: TStopWatch; begin try Memo1.Lines.Clear; Memo2.Lines.Clear; try LStopWatch := TStopWatch.StartNew; LoadNumbers(1); finally LStopWatch.Stop; Label1.Caption := 'Tempo de processamento: ' + IntToStr(LStopWatch.ElapsedMilliseconds) + ' ms'; end; except on E: Exception do begin WriteMemoException(E); raise; end; end; end; procedure TfExceptions.Button2Click(Sender: TObject); var i: Integer; LStopWatch: TStopWatch; begin Memo1.Lines.Clear; Memo2.Lines.Clear; LStopWatch := TStopWatch.StartNew; for i := 0 to 7 do LoadNumbers(i); LStopWatch.Stop; Label1.Caption := 'Tempo de processamento: ' + IntToStr(LStopWatch.ElapsedMilliseconds) + ' ms'; end; procedure TfExceptions.FormCreate(Sender: TObject); begin FPath := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'text.txt'; end; function TfExceptions.LoadNumbers(AIgnore: Integer): Boolean; var st: TStringList; s: String; begin st := TStringList.Create; st.LoadFromFile(FPath); try s := st.Text; Memo2.Lines.Add(StringReplace(s, IntToStr(AIgnore), '', [rfReplaceAll])); except on E: Exception do begin WriteMemoException(E); Memo1.Lines.Add(Format('Erro ao tentar retirar número %d', [AIgnore])); end; end; FreeAndNil(st); Result := True; end; procedure TfExceptions.WriteMemoException(E: Exception); begin Memo1.Lines.Add('Classe Exception: ' + E.ClassName); Memo1.Lines.Add('Erro: ' + E.Message); end; end.
{Twofish 'Monte Carlo Tests', we 06.2006} program T_MCTFUL; {$i STD.INC} {$ifdef APPCONS} {$apptype console} {$endif} {$ifndef FPC} {$N+} {$endif} uses {$ifdef WINCRT} wincrt, {$endif} tf_base, tf_cbc, tf_ecb, BTypes, mem_util; var logfile: text; const IMAX = 399; JMAX = 9999; {---------------------------------------------------------------------------} procedure output({$ifdef CONST} const {$endif} s: str255); {-writeln to logfile} begin writeln(logfile,s); end; {---------------------------------------------------------------------------} function i2s(L: longint): str255; var s: string[20]; begin str(L,s); i2s := s; end; {---------------------------------------------------------------------------} procedure ECBEncr; {-Reproduce ecb_e_m.txt} procedure TestBits(kbits: word); {-generate part for keysize kbits} var i,j,Err: Integer; PT, CT: TTFBlock; Key: array[0..31] of byte; ctx: TTFContext; begin write(kbits, ' bits '); output('=========='); output(''); output('KEYSIZE='+i2s(kbits)); output(''); fillchar(Key, sizeof(Key), 0); fillchar(PT, sizeof(PT), 0); CT := PT; for i:=0 to IMAX do begin if i and 7 = 0 then write('.'); Err := TF_ECB_Init(Key, kbits, ctx); if Err<>0 then begin writeln('TF_ECB_Init error: ',Err); halt; end; output('I='+i2s(I)); output('KEY='+HexStr(@Key, kbits div 8)); output('PT='+HexStr(@CT,16)); for j:=0 to JMAX do begin PT := CT; Err := TF_ECB_Encrypt(@CT, @CT, 16, ctx); if Err<>0 then begin writeln('TF_ECB_Encrypt error: ', Err); halt; end; end; output('CT='+HexStr(@CT,16)); output(''); case kbits of 128: for j:=0 to 15 do Key[j] := Key[j] xor CT[j]; 192: begin for j:=0 to 7 do Key[j] := Key[j] xor PT[8+j]; for j:=0 to 15 do Key[j+8] := Key[j+8] xor CT[j]; end; 256: begin for j:=0 to 15 do Key[j] := Key[j] xor PT[j]; for j:=0 to 15 do Key[j+16] := Key[j+16] xor CT[j]; end; end; end; writeln; end; begin assign(logfile, 'ecb_e_m.log'); rewrite(logfile); writeln('ecb_e_m.log'); output(''); output('========================='); output(''); output('FILENAME: "ecb_e_m.txt"'); output(''); output('Electronic Codebook (ECB) Mode - ENCRYPTION'); output('Monte Carlo Test'); output(''); output('Algorithm Name: TWOFISH'); output('Principal Submitter: Bruce Schneier, Counterpane Systems'); output(''); TestBits(128); TestBits(192); TestBits(256); output('=========='); output(''); close(logfile); end; {---------------------------------------------------------------------------} procedure ECBDecr; {-Reproduce ecb_d_m.txt} procedure TestBits(kbits: word); {-generate part for keysize kbits} var i,j,Err: Integer; PT, CT: TTFBlock; Key: array[0..31] of byte; ctx: TTFContext; begin write(kbits, ' bits '); output('=========='); output(''); output('KEYSIZE='+i2s(kbits)); output(''); fillchar(Key, sizeof(Key), 0); fillchar(PT, sizeof(PT), 0); CT := PT; for i:=0 to IMAX do begin if i and 7 = 0 then write('.'); Err := TF_ECB_Init(Key, kbits, ctx); if Err<>0 then begin writeln('TF_ECB_Init error: ', Err); halt; end; output('I='+i2s(I)); output('KEY='+HexStr(@Key, kbits div 8)); output('CT='+HexStr(@CT,16)); for j:=0 to JMAX do begin PT := CT; Err := TF_ECB_Decrypt(@CT, @CT, 16, ctx); if Err<>0 then begin writeln('TF_ECB_Decrypt error: ', Err); halt; end; end; output('PT='+HexStr(@CT,16)); output(''); case kbits of 128: for j:=0 to 15 do Key[j] := Key[j] xor CT[j]; 192: begin for j:=0 to 7 do Key[j] := Key[j] xor PT[8+j]; for j:=0 to 15 do Key[j+8] := Key[j+8] xor CT[j]; end; 256: begin for j:=0 to 15 do Key[j] := Key[j] xor PT[j]; for j:=0 to 15 do Key[j+16] := Key[j+16] xor CT[j]; end; end; end; writeln; end; begin assign(logfile, 'ecb_d_m.log'); rewrite(logfile); writeln('ecb_d_m.log'); output(''); output('========================='); output(''); output('FILENAME: "ecb_d_m.txt"'); output(''); output('Electronic Codebook (ECB) Mode - DECRYPTION'); output('Monte Carlo Test'); output(''); output('Algorithm Name: TWOFISH'); output('Principal Submitter: Bruce Schneier, Counterpane Systems'); output(''); TestBits(128); TestBits(192); TestBits(256); output('=========='); output(''); close(logfile); end; {---------------------------------------------------------------------------} procedure CBCEncr; {-Reproduce cbc_e_m.txt} procedure TestBits(kbits: word); {-generate part for keysize kbits} var i,j,Err: Integer; IV, PT, CT: TTFBlock; Key: array[0..31] of byte; ctx: TTFContext; begin write(kbits, ' bits '); output('=========='); output(''); output('KEYSIZE='+i2s(kbits)); output(''); fillchar(Key, sizeof(Key), 0); fillchar(PT, sizeof(PT), 0); fillchar(IV, sizeof(IV), 0); CT := PT; for i:=0 to IMAX do begin if i and 7 = 0 then write('.'); Err := TF_CBC_Init(Key, kbits, IV, ctx); if Err<>0 then begin writeln('TF_CBC_Init error: ', Err); halt; end; output('I='+i2s(I)); output('KEY='+HexStr(@Key, kbits div 8)); output('IV='+HexStr(@IV,16)); output('PT='+HexStr(@PT,16)); for j:=0 to JMAX do begin CT := PT; PT := ctx.IV; Err := TF_CBC_Encrypt(@CT, @CT, 16, ctx); if Err<>0 then begin writeln('TF_CBC_Encrypt error: ', Err); halt; end; end; IV := CT; output('CT='+HexStr(@CT,16)); output(''); case kbits of 128: for j:=0 to 15 do Key[j] := Key[j] xor CT[j]; 192: begin for j:=0 to 7 do Key[j] := Key[j] xor PT[8+j]; for j:=0 to 15 do Key[j+8] := Key[j+8] xor CT[j]; end; 256: begin for j:=0 to 15 do Key[j] := Key[j] xor PT[j]; for j:=0 to 15 do Key[j+16] := Key[j+16] xor CT[j]; end; end; end; writeln; end; begin assign(logfile, 'cbc_e_m.log'); rewrite(logfile); writeln('cbc_e_m.log'); output(''); output('========================='); output(''); output('FILENAME: "cbc_e_m.txt"'); output(''); output('Cipher Block Chaining (CBC) Mode - ENCRYPTION'); output('Monte Carlo Test'); output(''); output('Algorithm Name: TWOFISH'); output('Principal Submitter: Bruce Schneier, Counterpane Systems'); output(''); TestBits(128); TestBits(192); TestBits(256); output('=========='); output(''); close(logfile); end; {---------------------------------------------------------------------------} procedure CBCDecr; {-Reproduce cbc_d_m.txt} procedure TestBits(kbits: word); {-generate part for keysize kbits} var i,j,Err: Integer; IV, PT, CT: TTFBlock; Key: array[0..31] of byte; ctx: TTFContext; begin write(kbits, ' bits '); output('=========='); output(''); output('KEYSIZE='+i2s(kbits)); output(''); fillchar(Key, sizeof(Key), 0); fillchar(PT, sizeof(PT), 0); fillchar(IV, sizeof(IV), 0); for i:=0 to IMAX do begin if i and 7 = 0 then write('.'); CT := PT; Err := TF_CBC_Init(Key, kbits, IV, ctx); if Err<>0 then begin writeln('TF_CBC_Init error: ', Err); halt; end; output('I='+i2s(I)); output('KEY='+HexStr(@Key, kbits div 8)); output('IV='+HexStr(@IV,16)); output('CT='+HexStr(@CT,16)); PT := CT; for j:=0 to JMAX do begin CT := PT; Err := TF_CBC_Decrypt(@PT, @PT, 16, ctx); if Err<>0 then begin writeln('TF_CBC_Decrypt error: ', Err); halt; end; end; IV := ctx.IV; output('PT='+HexStr(@PT,16)); output(''); case kbits of 128: for j:=0 to 15 do Key[j] := Key[j] xor PT[j]; 192: begin for j:=0 to 7 do Key[j] := Key[j] xor CT[8+j]; for j:=0 to 15 do Key[j+8] := Key[j+8] xor PT[j]; end; 256: begin for j:=0 to 15 do Key[j] := Key[j] xor CT[j]; for j:=0 to 15 do Key[j+16] := Key[j+16] xor PT[j]; end; end; end; writeln; end; begin assign(logfile, 'cbc_d_m.log'); rewrite(logfile); writeln('cbc_d_m.log'); output(''); output('========================='); output(''); output('FILENAME: "cbc_d_m.txt"'); output(''); output('Cipher Block Chaining (CBC) Mode - DECRYPTION'); output('Monte Carlo Test'); output(''); output('Algorithm Name: TWOFISH'); output('Principal Submitter: Bruce Schneier, Counterpane Systems'); output(''); TestBits(128); TestBits(192); TestBits(256); output('=========='); output(''); close(logfile); end; begin writeln('T_MCTFUL - Twofish Full Monte Carlo Tests to *.LOG (c) 2006-2008 W.Ehrhardt'); HexUpper := true; ECBEncr; ECBDecr; CBCEncr; CBCDecr; end.
(* StringSet: MM, 2020-05-30 *) (* ------ *) (* A simple class for StringSet Operations *) (* ========================================================================= *) UNIT StringSetUnit; INTERFACE TYPE StringArray = ARRAY [0..0] OF STRING; StringSet = ^StringSetObj; StringSetObj = OBJECT PUBLIC CONSTRUCTOR Init(size: INTEGER); DESTRUCTOR Done; VIRTUAL; FUNCTION IsFull: BOOLEAN; FUNCTION Empty: BOOLEAN; FUNCTION Cardinality: INTEGER; FUNCTION Contains(x: STRING): BOOLEAN; PROCEDURE Add(x: STRING); PROCEDURE Remove(x: STRING); PROCEDURE Print; PROCEDURE Test; FUNCTION GetDataAt(x: INTEGER): STRING; PRIVATE elements: ^StringArray; size: INTEGER; n: INTEGER; END; (* StringSetObj *) FUNCTION Union(s1, s2: StringSet): StringSet; FUNCTION Intersect(s1, s2: StringSet): StringSet; FUNCTION Difference(s1, s2: StringSet): StringSet; IMPLEMENTATION CONSTRUCTOR StringSetObj.Init(size: INTEGER); BEGIN SELF.n := 0; SELF.size := size; GetMem(SELF.elements, size * SizeOf(STRING)); END; (* StringSetObj.Init *) DESTRUCTOR StringSetObj.Done; BEGIN FreeMem(SELF.elements, SELF.size * SizeOf(STRING)); END; (* StringSetObj.Done *) FUNCTION StringSetObj.IsFull: BOOLEAN; BEGIN (* StringSetObj.IsFull *) IsFull := n >= size; END; (* StringSetObj.IsFull *) FUNCTION StringSetObj.Empty: BOOLEAN; BEGIN (* StringSetObj.Empty *) Empty := n = 0; END; (* StringSetObj.Empty *) FUNCTION StringSetObj.Cardinality: INTEGER; BEGIN (* StringSetObj.Cardinality *) Cardinality := n; END; (* StringSetObj.Cardinality *) FUNCTION StringSetObj.Contains(x: STRING): BOOLEAN; VAR i: INTEGER; BEGIN (* StringSetObj.Contains *) i := 0; WHILE ((i < n) AND ({$R-}elements^[i]{$R+} <> x)) DO BEGIN Inc(i); END; (* WHILE *) Contains := i <> n; END; (* StringSetObj.Contains *) PROCEDURE StringSetObj.Add(x: STRING); BEGIN (* StringSetObj.Add *) IF (IsFull) THEN BEGIN WriteLn('Error: Set is full, program will be halted.'); HALT; END ELSE BEGIN IF (NOT Contains(x)) THEN BEGIN {$R-}elements^[n]{$R+} := x; Inc(n); END; (* IF *) END; (* IF *) END; (* StringSetObj.Add *) PROCEDURE StringSetObj.Remove(x: STRING); VAR i: INTEGER; found: BOOLEAN; BEGIN (* StringSetObj.Remove *) IF (Empty) THEN BEGIN WriteLn('Set is already empty, programm will be halted.'); HALT; END ELSE IF (NOT Contains(x)) THEN BEGIN WriteLn('Info: Cannot remove "', x, '", element not in Set.'); END ELSE BEGIN found := FALSE; FOR i := 0 TO n DO BEGIN IF (found) THEN BEGIN {$R-}elements^[i] := elements^[i+1];{$R+} END ELSE BEGIN IF ({$R-}elements^[i] = x) THEN BEGIN found := TRUE; elements^[i] := elements^[i+1]; Dec(n); END; (* IF *) END; (* IF *) END; (* FOR *) END; (* IF *) END; (* StringSetObj.Remove *) PROCEDURE StringSetObj.Test; BEGIN (* StringSetObj.Test *) WriteLn('n: ', n); WriteLn('Size: ', size); SELF.Print; END; (* StringSetObj.Test *) PROCEDURE StringSetObj.Print; VAR i: INTEGER; BEGIN (* StringSetObj.Print *) FOR i := 0 TO n - 1 DO BEGIN WriteLn({$R-}elements^[i]{$R+}); END; (* FOR *) END; (* StringSetObj.Print *) FUNCTION StringSetObj.GetDataAt(x: INTEGER): STRING; BEGIN (* StringSetObj.GetData *) IF (x <= n) THEN GetDataAt := {$R-}elements^[x]{$R+} ELSE BEGIN WriteLn('Invalid position [', x, '] in Set (size: ',n,'), program will be halted.'); HALT; END; (* IF *) END; (* StringSetObj.GetData *) FUNCTION Union(s1, s2: StringSet): StringSet; VAR target: StringSet; data: STRING; i: INTEGER; BEGIN (* Union *) New(target, Init(s1^.Cardinality + s2^.Cardinality)); FOR i := 0 TO s1^.Cardinality - 1 DO BEGIN data := s1^.GetDataAt(i); target^.Add(data); END; (* FOR *) FOR i := 0 TO s2^.Cardinality - 1 DO BEGIN data := s2^.GetDataAt(i); target^.Add(data); END; (* FOR *) Union := target; END; (* Union *) FUNCTION Intersect(s1, s2: StringSet): StringSet; VAR target: StringSet; data: STRING; i: INTEGER; BEGIN (* Intersect *) New(target, Init(s1^.Cardinality)); FOR i := 0 TO s1^.Cardinality - 1 DO BEGIN data := s1^.GetDataAt(i); target^.Add(data); END; (* FOR *) FOR i := target^.Cardinality - 1 DOWNTO 0 DO BEGIN data := target^.GetDataAt(i); IF (NOT s2^.Contains(data)) THEN target^.Remove(data); END; (* FOR *) Intersect := target; END; (* Intersect *) FUNCTION Difference(s1, s2: StringSet): StringSet; VAR target, temp: StringSet; data: STRING; i: INTEGER; BEGIN (* Difference *) target := Union(s1, s2); temp := Intersect(s1, s2); FOR i := target^.Cardinality - 1 DOWNTO 0 DO BEGIN data := target^.GetDataAt(i); IF (temp^.Contains(data)) THEN target^.Remove(data); END; (* FOR *) Dispose(temp, Done); Difference := target; END; (* Difference *) END. (* StringSetUnit *)
unit UHTTPGetThread; //Download by http://www.codefans.net interface uses classes, SysUtils, wininet, windows; type TOnProgressEvent = procedure(TotalSize, Readed: Integer) of object; THTTPGetThread = class(TThread) private FTAcceptTypes: string; //接收文件类型 *.* FTAgent: string; //浏览器名 Nokia6610/1.0 (5.52) Profile/MIDP-1.0 Configuration/CLDC-1.02 FTURL: string; // url FTFileName: string; //文件名 FTStringResult: AnsiString; FTUserName: string; //用户名 FTPassword: string; //密码 FTPostQuery: string; //方法名,post或者get FTReferer: string; FTBinaryData: Boolean; FTUseCache: Boolean; //是否从缓存读数据 FTMimeType: string; //Mime类型 FTResult: Boolean; FTFileSize: Integer; FTToFile: Boolean; //是否文件 BytesToRead, BytesReaded: LongWord; FTProgress: TOnProgressEvent; procedure ParseURL(URL: string; var HostName, FileName: string; var portNO: integer); //取得url的主机名和文件名 procedure UpdateProgress; procedure setResult(FResult: boolean); function getResult(): boolean; protected procedure Execute; override; public function getFileName(): string; function getToFile(): boolean; function getFileSize(): integer; function getStringResult(): AnsiString; constructor Create(aAcceptTypes, aMimeType, aAgent, aURL, aFileName, aUserName, aPassword, aPostQuery, aReferer: string; aBinaryData, aUseCache: Boolean; aProgress: TOnProgressEvent; aToFile: Boolean); published property BResult: boolean read getResult write setResult; end; implementation { THTTPGetThread } constructor THTTPGetThread.Create(aAcceptTypes, aMimeType, aAgent, aURL, aFileName, aUserName, aPassword, aPostQuery, aReferer: string; aBinaryData, aUseCache: Boolean; aProgress: TOnProgressEvent; aToFile: Boolean); begin FreeOnTerminate := True; inherited Create(True); FTAcceptTypes := aAcceptTypes; FTAgent := aAgent; FTURL := aURL; FTFileName := aFileName; FTUserName := aUserName; FTPassword := aPassword; //FTPostQuery := aPostQuery; FTPostQuery := StringReplace(aPostQuery, #13#10, '', [rfReplaceAll]); FTStringResult := ''; FTReferer := aReferer; FTProgress := aProgress; FTBinaryData := aBinaryData; FTUseCache := aUseCache; FTMimeType := aMimeType; FTResult := false; FTToFile := aToFile; FTFileSize := 0; Resume; end; procedure THTTPGetThread.Execute; var hSession: hInternet; //回话句柄 hConnect: hInternet; //连接句柄 hRequest: hInternet; //请求句柄 Host_Name: string; //主机名 File_Name: string; //文件名 port_no: integer; RequestMethod: PChar; InternetFlag: longWord; AcceptType: PAnsiChar; dwBufLen, dwIndex: longword; Buf: Pointer; //缓冲区 f: file; Data: array[0..$400] of Char; TempStr: AnsiString; mime_Head: string; procedure CloseHandles; begin InternetCloseHandle(hRequest); InternetCloseHandle(hConnect); InternetCloseHandle(hSession); end; begin inherited; buf := nil; try try ParseURL(FTURL, Host_Name, File_Name, port_no); if Terminated then begin FTResult := False; Exit; end; //建立会话 hSession := InternetOpen(pchar(FTAgent), //lpszCallerName指定正在使用网络函数的应用程序 INTERNET_OPEN_TYPE_PRECONFIG, //参数dwAccessType指定访问类型 nil, //服务器名(lpszProxyName)。 accesstype为GATEWAY_PROXY_INTERNET_ACCESS和CERN_PROXY_ACCESS时 nil, //NProxyPort参数用在CERN_PROXY_INTERNET_ACCESS中用来指定使用的端口数。使用INTERNET_INVALID_PORT_NUMBER相当于提供却省的端口数。 0); //设置额外的选择。你可以使用INTERNET_FLAG_ASYNC标志去指示使用返回句句柄的将来的Internet函数将为回调函数发送状态信息,使用InternetSetStatusCallback进行此项设置 //建立连接 hConnect := InternetConnect(hSession, //会话句柄 PChar(Host_Name), //指向包含Internet服务器的主机名称(如http://www.mit.edu)或IP地址(如202.102.13.141)的字符串 port_no, //INTERNET_DEFAULT_HTTP_PORT, //是将要连结到的TCP/IP的端口号 PChar(FTUserName), //用户名 PChar(FTPassword), //密码 INTERNET_SERVICE_HTTP, //协议 0, // 可选标记,设置为INTERNET_FLAG_SECURE,表示使用SSL/PCT协议完成事务 0); //应用程序定义的值,用来为返回的句柄标识应用程序设备场境 if FTPostQuery = '' then RequestMethod := 'GET' else RequestMethod := 'POST'; if FTUseCache then InternetFlag := 0 else InternetFlag := INTERNET_FLAG_RELOAD; AcceptType := PAnsiChar('Accept: ' + FTAcceptTypes); //建立一个http请求句柄 hRequest := HttpOpenRequest(hConnect, //InternetConnect返回的HTTP会话句柄 RequestMethod, //指向在申请中使用的"动词"的字符串,如果设置为NULL,则使用"GET" PChar(File_Name), //指向包含动词的目标对象名称的字符串,通常是文件名称、可执行模块或搜索说明符 'HTTP/1.0', //指向包含HTTP版本的字符串,如果为NULL,则默认为"HTTP/1.0"; PChar(FTReferer), //指向包含文档地址(URL)的字符串,申请的URL必须是从该文档获取的 @AcceptType, //指向客户接收的内容的类型 InternetFlag, 0); mime_Head := 'Content-Type: ' + FTMimeType; if FTPostQuery = '' then FTResult := HttpSendRequest(hRequest, nil, 0, nil, 0) else //发送一个指定请求到httpserver FTResult := HttpSendRequest(hRequest, pchar(mime_Head), //mime 头 length(mime_Head), //头长度 PChar(FTPostQuery), //附加数据缓冲区,可为空 strlen(PChar(FTPostQuery))); //附加数据缓冲区长度 if Terminated then begin //CloseHandles; FTResult := False; Exit; end; dwIndex := 0; dwBufLen := 1024; GetMem(Buf, dwBufLen); //接收header信息和一个http请求 FTResult := HttpQueryInfo(hRequest, HTTP_QUERY_CONTENT_LENGTH, Buf, //指向一个接收请求信息的缓冲区的指针 dwBufLen, //HttpQueryInfo内容的大小 dwIndex); //读取的字节数 if Terminated then begin FTResult := False; Exit; end; if FTResult or not FTBinaryData then begin //如果请求 if FTResult then FTFileSize := StrToInt(string(StrPas(PAnsiChar(Buf)))); BytesReaded := 0; if FTToFile then begin AssignFile(f, FTFileName); Rewrite(f, 1); end else FTStringResult := ''; while True do begin if Terminated then begin FTResult := False; Exit; end; if not InternetReadFile(hRequest, @Data, //数据内容 SizeOf(Data), //大小 BytesToRead) //读取的字节数 then Break else if BytesToRead = 0 then Break else begin if FTToFile then BlockWrite(f, Data, BytesToRead) //将读出的数据写入文件 else begin TempStr := Data; SetLength(TempStr, BytesToRead); FTStringResult := FTStringResult + TempStr; end; inc(BytesReaded, BytesToRead); if Assigned(FTProgress) then //执行回调函数 Synchronize(UpdateProgress); end; end; if FTToFile then FTResult := FTFileSize = Integer(BytesReaded) else begin // SetLength(FTStringResult, BytesReaded); FTResult := BytesReaded <> 0; end; end; except end; finally if FTToFile then CloseFile(f); if assigned(Buf) then FreeMem(Buf); CloseHandles; end; end; function THTTPGetThread.getFileName: string; begin result := FTFileName; end; function THTTPGetThread.getFileSize: integer; begin result := FTFileSize; end; function THTTPGetThread.getResult: boolean; begin result := FTResult; end; function THTTPGetThread.getStringResult: AnsiString; begin result := FTStringResult; end; function THTTPGetThread.getToFile: boolean; begin result := FTToFile; end; procedure THTTPGetThread.ParseURL(URL: string; var HostName, FileName: string; var portNO: integer); var i: Integer; begin if Pos('http://', LowerCase(URL)) <> 0 then Delete(URL, 1, 7); i := Pos('/', URL); HostName := Copy(URL, 1, i); FileName := Copy(URL, i, Length(URL) - i + 1); i := pos(':', hostName); if i <> 0 then begin portNO := strtoint(copy(hostName, i + 1, length(hostName) - i - 1)); hostName := copy(hostName, 1, i - 1); end else portNO := 80; if (Length(HostName) > 0) and (HostName[Length(HostName)] = '/') then SetLength(HostName, Length(HostName) - 1); end; procedure THTTPGetThread.setResult(FResult: boolean); begin FTResult := FResult; end; procedure THTTPGetThread.UpdateProgress; begin FTProgress(FTFileSize, BytesReaded); end; end.
{ test ranges representation and I/O } program ranges; type R1 = 'a' .. 'z'; // subset of chars R2 = 1 .. 10; // int8 R3 = 100 .. 200; // uint8 R4 = 0 .. 300; // int16 R5 = 0 .. 65535; // uint16 R6 = -16384 .. 65536; // int32 var v1, t1 : R1; v2, t2 : R2; v3, t3 : R3; v4, t4 : R4; v5, t5 : R5; v6, t6 : R6; tmp : text; begin v1 := 'x'; v2 := 1; v3 := 200; v4 := 123; v5 := 32768; v6 := -1; writeln('initial : ', v1, ' ', v2, ' ', v3, ' ', v4, ' ', v5, ' ', v6); writeln('write part 1 ...'); rewrite(tmp); writeln(tmp, v1, ' ', v2, ' ', v3); writeln('read part 1 ...'); reset(tmp); readln(tmp, t1, t2, t3); writeln('write part 2 ...'); rewrite(tmp); writeln(tmp, v4, ' ', v5, ' ', v6); writeln('read part 2 ...'); reset(tmp); readln(tmp, t4, t5, t6); writeln('final : ', t1, ' ', t2, ' ', t3, ' ', t4, ' ', t5, ' ', t6); end.
unit adot.Arithmetic; interface { Implementation of IArithmetic for all basic types in Delphi: class function TArithmeticUtils<T>.DefaultArithmetic: IArithmetic<T>; - Used by TBox<T> to make possible arithmetic operations without type conversion. - Can be used for calculations on generic types, for example Avg/Sum etc implemented in TList<T> } uses adot.Types, {$If Defined(MSWindows)} System.AnsiStrings, System.WideStrings, {$EndIf} System.SysUtils, System.Character; type TArithmeticUtils<T> = class private class var FArithmetic: IArithmetic<T>; type { Platform-dependent integer types } TArithmeticNativeInt = class(TCustomArithmetic<NativeInt>) protected class var FOrdinal: TArithmeticNativeInt; public class function Ordinal: TArithmeticNativeInt; function Add(Left: NativeInt; Right: NativeInt): NativeInt; override; function Subtract(Left: NativeInt; Right: NativeInt): NativeInt; override; function Multiply(Left: NativeInt; Right: NativeInt): NativeInt; override; function Divide(Left: NativeInt; Right: NativeInt): NativeInt; override; function Negative(Value: NativeInt): NativeInt; override; end; TArithmeticNativeUInt = class(TCustomArithmetic<NativeUInt>) protected class var FOrdinal: TArithmeticNativeUInt; public class function Ordinal: TArithmeticNativeUInt; function Add(Left: NativeUInt; Right: NativeUInt): NativeUInt; override; function Subtract(Left: NativeUInt; Right: NativeUInt): NativeUInt; override; function Multiply(Left: NativeUInt; Right: NativeUInt): NativeUInt; override; function Divide(Left: NativeUInt; Right: NativeUInt): NativeUInt; override; function Negative(Value: NativeUInt): NativeUInt; override; end; { 32-bit platforms and 64-bit Windows platforms 64-bit iOS platforms } TArithmeticLongInt = class(TCustomArithmetic<LongInt>) protected class var FOrdinal: TArithmeticLongInt; public class function Ordinal: TArithmeticLongInt; function Add(Left: LongInt; Right: LongInt): LongInt; override; function Subtract(Left: LongInt; Right: LongInt): LongInt; override; function Multiply(Left: LongInt; Right: LongInt): LongInt; override; function Divide(Left: LongInt; Right: LongInt): LongInt; override; function Negative(Value: LongInt): LongInt; override; end; { 32-bit platforms and 64-bit Windows platforms 64-bit iOS platforms } TArithmeticLongWord = class(TCustomArithmetic<LongWord>) protected class var FOrdinal: TArithmeticLongWord; public class function Ordinal: TArithmeticLongWord; function Add(Left: LongWord; Right: LongWord): LongWord; override; function Subtract(Left: LongWord; Right: LongWord): LongWord; override; function Multiply(Left: LongWord; Right: LongWord): LongWord; override; function Divide(Left: LongWord; Right: LongWord): LongWord; override; function Negative(Value: LongWord): LongWord; override; end; { Platform-independent integer types } TArithmeticShortInt = class(TCustomArithmetic<ShortInt>) protected class var FOrdinal: TArithmeticShortInt; public class function Ordinal: TArithmeticShortInt; function Add(Left: ShortInt; Right: ShortInt): ShortInt; override; function Subtract(Left: ShortInt; Right: ShortInt): ShortInt; override; function Multiply(Left: ShortInt; Right: ShortInt): ShortInt; override; function Divide(Left: ShortInt; Right: ShortInt): ShortInt; override; function Negative(Value: ShortInt): ShortInt; override; end; TArithmeticSmallInt = class(TCustomArithmetic<SmallInt>) protected class var FOrdinal: TArithmeticSmallInt; public class function Ordinal: TArithmeticSmallInt; function Add(Left: SmallInt; Right: SmallInt): SmallInt; override; function Subtract(Left: SmallInt; Right: SmallInt): SmallInt; override; function Multiply(Left: SmallInt; Right: SmallInt): SmallInt; override; function Divide(Left: SmallInt; Right: SmallInt): SmallInt; override; function Negative(Value: SmallInt): SmallInt; override; end; TArithmeticFixedInt = class(TCustomArithmetic<FixedInt>) protected class var FOrdinal: TArithmeticFixedInt; public class function Ordinal: TArithmeticFixedInt; function Add(Left: FixedInt; Right: FixedInt): FixedInt; override; function Subtract(Left: FixedInt; Right: FixedInt): FixedInt; override; function Multiply(Left: FixedInt; Right: FixedInt): FixedInt; override; function Divide(Left: FixedInt; Right: FixedInt): FixedInt; override; function Negative(Value: FixedInt): FixedInt; override; end; TArithmeticInteger = class(TArithmeticFixedInt); TArithmeticInt64 = class(TCustomArithmetic<Int64>) protected class var FOrdinal: TArithmeticInt64; public class function Ordinal: TArithmeticInt64; function Add(Left: Int64; Right: Int64): Int64; override; function Subtract(Left: Int64; Right: Int64): Int64; override; function Multiply(Left: Int64; Right: Int64): Int64; override; function Divide(Left: Int64; Right: Int64): Int64; override; function Negative(Value: Int64): Int64; override; end; TArithmeticByte = class(TCustomArithmetic<Byte>) protected class var FOrdinal: TArithmeticByte; public class function Ordinal: TArithmeticByte; function Add(Left: Byte; Right: Byte): Byte; override; function Subtract(Left: Byte; Right: Byte): Byte; override; function Multiply(Left: Byte; Right: Byte): Byte; override; function Divide(Left: Byte; Right: Byte): Byte; override; function Negative(Value: Byte): Byte; override; end; TArithmeticWord = class(TCustomArithmetic<Word>) protected class var FOrdinal: TArithmeticWord; public class function Ordinal: TArithmeticWord; function Add(Left: Word; Right: Word): Word; override; function Subtract(Left: Word; Right: Word): Word; override; function Multiply(Left: Word; Right: Word): Word; override; function Divide(Left: Word; Right: Word): Word; override; function Negative(Value: Word): Word; override; end; TArithmeticFixedUInt = class(TCustomArithmetic<FixedUInt>) protected class var FOrdinal: TArithmeticFixedUInt; public class function Ordinal: TArithmeticFixedUInt; function Add(Left: FixedUInt; Right: FixedUInt): FixedUInt; override; function Subtract(Left: FixedUInt; Right: FixedUInt): FixedUInt; override; function Multiply(Left: FixedUInt; Right: FixedUInt): FixedUInt; override; function Divide(Left: FixedUInt; Right: FixedUInt): FixedUInt; override; function Negative(Value: FixedUInt): FixedUInt; override; end; TArithmeticCardinal = class(TArithmeticFixedUInt); TArithmeticUInt64 = class(TCustomArithmetic<UInt64>) protected class var FOrdinal: TArithmeticUInt64; public class function Ordinal: TArithmeticUInt64; function Add(Left: UInt64; Right: UInt64): UInt64; override; function Subtract(Left: UInt64; Right: UInt64): UInt64; override; function Multiply(Left: UInt64; Right: UInt64): UInt64; override; function Divide(Left: UInt64; Right: UInt64): UInt64; override; function Negative(Value: UInt64): UInt64; override; end; { Real types } TArithmeticSingle = class(TCustomArithmetic<Single>) protected class var FOrdinal: TArithmeticSingle; public class function Ordinal: TArithmeticSingle; function Add(Left: Single; Right: Single): Single; override; function Subtract(Left: Single; Right: Single): Single; override; function Multiply(Left: Single; Right: Single): Single; override; function Divide(Left: Single; Right: Single): Single; override; function Negative(Value: Single): Single; override; end; TArithmeticDouble = class(TCustomArithmetic<double>) protected class var FOrdinal: TArithmeticDouble; public class function Ordinal: TArithmeticDouble; function Add(Left: double; Right: double): double; override; function Subtract(Left: double; Right: double): double; override; function Multiply(Left: double; Right: double): double; override; function Divide(Left: double; Right: double): double; override; function Negative(Value: double): double; override; end; TArithmeticReal = class(TCustomArithmetic<Real>) protected class var FOrdinal: TArithmeticReal; public class function Ordinal: TArithmeticReal; function Add(Left: Real; Right: Real): Real; override; function Subtract(Left: Real; Right: Real): Real; override; function Multiply(Left: Real; Right: Real): Real; override; function Divide(Left: Real; Right: Real): Real; override; function Negative(Value: Real): Real; override; end; TArithmeticExtended = class(TCustomArithmetic<Extended>) protected class var FOrdinal: TArithmeticExtended; public class function Ordinal: TArithmeticExtended; function Add(Left: Extended; Right: Extended): Extended; override; function Subtract(Left: Extended; Right: Extended): Extended; override; function Multiply(Left: Extended; Right: Extended): Extended; override; function Divide(Left: Extended; Right: Extended): Extended; override; function Negative(Value: Extended): Extended; override; end; TArithmeticComp = class(TCustomArithmetic<Comp>) protected class var FOrdinal: TArithmeticComp; public class function Ordinal: TArithmeticComp; function Add(Left: Comp; Right: Comp): Comp; override; function Subtract(Left: Comp; Right: Comp): Comp; override; function Multiply(Left: Comp; Right: Comp): Comp; override; function Divide(Left: Comp; Right: Comp): Comp; override; function Negative(Value: Comp): Comp; override; end; TArithmeticCurrency = class(TCustomArithmetic<Currency>) protected class var FOrdinal: TArithmeticCurrency; public class function Ordinal: TArithmeticCurrency; function Add(Left: Currency; Right: Currency): Currency; override; function Subtract(Left: Currency; Right: Currency): Currency; override; function Multiply(Left: Currency; Right: Currency): Currency; override; function Divide(Left: Currency; Right: Currency): Currency; override; function Negative(Value: Currency): Currency; override; end; { string types } {$If Defined(MSWindows)} TArithmeticAnsiString = class(TCustomArithmetic<AnsiString>) protected class var FOrdinal: TArithmeticAnsiString; public class function Ordinal: TArithmeticAnsiString; function Add(Left: AnsiString; Right: AnsiString): AnsiString; override; function Subtract(Left: AnsiString; Right: AnsiString): AnsiString; override; function Multiply(Left: AnsiString; Right: AnsiString): AnsiString; override; function Divide(Left: AnsiString; Right: AnsiString): AnsiString; override; function Negative(Value: AnsiString): AnsiString; override; end; {$EndIf} TArithmeticString = class(TCustomArithmetic<String>) protected class var FOrdinal: TArithmeticString; public class function Ordinal: TArithmeticString; function Add(Left: String; Right: String): String; override; function Subtract(Left: String; Right: String): String; override; function Multiply(Left: String; Right: String): String; override; function Divide(Left: String; Right: String): String; override; function Negative(Value: String): String; override; end; {$IF defined(MSWINDOWS)} TArithmeticWideString = class(TCustomArithmetic<WideString>) protected class var FOrdinal: TArithmeticWideString; public class function Ordinal: TArithmeticWideString; function Add(Left: WideString; Right: WideString): WideString; override; function Subtract(Left: WideString; Right: WideString): WideString; override; function Multiply(Left: WideString; Right: WideString): WideString; override; function Divide(Left: WideString; Right: WideString): WideString; override; function Negative(Value: WideString): WideString; override; end; {$ENDIF} public class function DefaultArithmetic: IArithmetic<T>; static; end; implementation { TArithmeticUtils<T> } class function TArithmeticUtils<T>.DefaultArithmetic: IArithmetic<T>; begin if FArithmetic = nil then begin { Platform-dependent integer types } if TypeInfo(T) = TypeInfo(NativeInt) then FArithmetic := IArithmetic<T>( IArithmetic<NativeInt> (TArithmeticNativeInt.Ordinal) ) else if TypeInfo(T) = TypeInfo(NativeUInt) then FArithmetic := IArithmetic<T>( IArithmetic<NativeUInt>(TArithmeticNativeUInt.Ordinal) ) else if TypeInfo(T) = TypeInfo(LongInt) then FArithmetic := IArithmetic<T>( IArithmetic<LongInt> (TArithmeticLongInt.Ordinal) ) else if TypeInfo(T) = TypeInfo(LongWord) then FArithmetic := IArithmetic<T>( IArithmetic<LongWord> (TArithmeticLongWord.Ordinal) ) else { Platform-independent integer types } if TypeInfo(T) = TypeInfo(ShortInt) then FArithmetic := IArithmetic<T>( IArithmetic<ShortInt> (TArithmeticShortInt.Ordinal) ) else if TypeInfo(T) = TypeInfo(SmallInt) then FArithmetic := IArithmetic<T>( IArithmetic<SmallInt> (TArithmeticSmallInt.Ordinal) ) else if TypeInfo(T) = TypeInfo(FixedInt) then FArithmetic := IArithmetic<T>( IArithmetic<FixedInt> (TArithmeticFixedInt.Ordinal) ) else if TypeInfo(T) = TypeInfo(integer) then FArithmetic := IArithmetic<T>( IArithmetic<integer> (TArithmeticInteger.Ordinal) ) else if TypeInfo(T) = TypeInfo(Int64) then FArithmetic := IArithmetic<T>( IArithmetic<Int64> (TArithmeticInt64.Ordinal) ) else if TypeInfo(T) = TypeInfo(Byte) then FArithmetic := IArithmetic<T>( IArithmetic<Byte> (TArithmeticByte.Ordinal) ) else if TypeInfo(T) = TypeInfo(Word) then FArithmetic := IArithmetic<T>( IArithmetic<Word> (TArithmeticWord.Ordinal) ) else if TypeInfo(T) = TypeInfo(FixedUInt) then FArithmetic := IArithmetic<T>( IArithmetic<FixedUInt> (TArithmeticFixedUInt.Ordinal) ) else if TypeInfo(T) = TypeInfo(Cardinal) then FArithmetic := IArithmetic<T>( IArithmetic<Cardinal> (TArithmeticCardinal.Ordinal) ) else if TypeInfo(T) = TypeInfo(UInt64) then FArithmetic := IArithmetic<T>( IArithmetic<UInt64> (TArithmeticUInt64.Ordinal) ) else { Real types } if TypeInfo(T) = TypeInfo(Single) then FArithmetic := IArithmetic<T>( IArithmetic<Single> (TArithmeticSingle.Ordinal) ) else if TypeInfo(T) = TypeInfo(Double) then FArithmetic := IArithmetic<T>( IArithmetic<Double> (TArithmeticDouble.Ordinal) ) else if TypeInfo(T) = TypeInfo(Real) then FArithmetic := IArithmetic<T>( IArithmetic<Real> (TArithmeticReal.Ordinal) ) else if TypeInfo(T) = TypeInfo(Extended) then FArithmetic := IArithmetic<T>( IArithmetic<Extended> (TArithmeticExtended.Ordinal) ) else if TypeInfo(T) = TypeInfo(Comp) then FArithmetic := IArithmetic<T>( IArithmetic<Comp> (TArithmeticComp.Ordinal) ) else if TypeInfo(T) = TypeInfo(Currency) then FArithmetic := IArithmetic<T>( IArithmetic<Currency> (TArithmeticCurrency.Ordinal) ) else { String types } {$IFDEF MSWINDOWS} if TypeInfo(T) = TypeInfo(AnsiString) then FArithmetic := IArithmetic<T>( IArithmetic<AnsiString>(TArithmeticAnsiString.Ordinal) ) else {$ENDIF} if TypeInfo(T) = TypeInfo(String) then FArithmetic := IArithmetic<T>( IArithmetic<String> (TArithmeticString.Ordinal) ) else {$IFDEF MSWINDOWS} if TypeInfo(T) = TypeInfo(WideString) then FArithmetic := IArithmetic<T>( IArithmetic<WideString>(TArithmeticWideString.Ordinal) ) else {$ENDIF} { unsupported type} raise Exception.Create('not implemented'); end; Result := FArithmetic; end; { TArithmeticUtils<T>.TArithmeticNativeInt } class function TArithmeticUtils<T>.TArithmeticNativeInt.Ordinal: TArithmeticNativeInt; begin if FOrdinal = nil then FOrdinal := TArithmeticNativeInt.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticNativeInt.Add(Left, Right: NativeInt): NativeInt; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticNativeInt.Divide(Left, Right: NativeInt): NativeInt; begin Result := Left div Right; end; function TArithmeticUtils<T>.TArithmeticNativeInt.Multiply(Left, Right: NativeInt): NativeInt; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticNativeInt.Negative(Value: NativeInt): NativeInt; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticNativeInt.Subtract(Left, Right: NativeInt): NativeInt; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticNativeUInt } class function TArithmeticUtils<T>.TArithmeticNativeUInt.Ordinal: TArithmeticNativeUInt; begin if FOrdinal = nil then FOrdinal := TArithmeticNativeUInt.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticNativeUInt.Add(Left, Right: NativeUInt): NativeUInt; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticNativeUInt.Divide(Left, Right: NativeUInt): NativeUInt; begin Result := Left div Right; end; function TArithmeticUtils<T>.TArithmeticNativeUInt.Multiply(Left, Right: NativeUInt): NativeUInt; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticNativeUInt.Negative(Value: NativeUInt): NativeUInt; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticNativeUInt.Subtract(Left, Right: NativeUInt): NativeUInt; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticLongInt } class function TArithmeticUtils<T>.TArithmeticLongInt.Ordinal: TArithmeticLongInt; begin if FOrdinal = nil then FOrdinal := TArithmeticLongInt.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticLongInt.Add(Left, Right: LongInt): LongInt; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticLongInt.Divide(Left, Right: LongInt): LongInt; begin Result := Left div Right; end; function TArithmeticUtils<T>.TArithmeticLongInt.Multiply(Left, Right: LongInt): LongInt; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticLongInt.Negative(Value: LongInt): LongInt; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticLongInt.Subtract(Left, Right: LongInt): LongInt; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticLongWord } class function TArithmeticUtils<T>.TArithmeticLongWord.Ordinal: TArithmeticLongWord; begin if FOrdinal = nil then FOrdinal := TArithmeticLongWord.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticLongWord.Add(Left, Right: LongWord): LongWord; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticLongWord.Divide(Left, Right: LongWord): LongWord; begin Result := Left div Right; end; function TArithmeticUtils<T>.TArithmeticLongWord.Multiply(Left, Right: LongWord): LongWord; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticLongWord.Negative(Value: LongWord): LongWord; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticLongWord.Subtract(Left, Right: LongWord): LongWord; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticShortInt } class function TArithmeticUtils<T>.TArithmeticShortInt.Ordinal: TArithmeticShortInt; begin if FOrdinal = nil then FOrdinal := TArithmeticShortInt.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticShortInt.Add(Left, Right: ShortInt): ShortInt; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticShortInt.Divide(Left, Right: ShortInt): ShortInt; begin Result := Left div Right; end; function TArithmeticUtils<T>.TArithmeticShortInt.Multiply(Left, Right: ShortInt): ShortInt; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticShortInt.Negative(Value: ShortInt): ShortInt; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticShortInt.Subtract(Left, Right: ShortInt): ShortInt; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticSmallInt } class function TArithmeticUtils<T>.TArithmeticSmallInt.Ordinal: TArithmeticSmallInt; begin if FOrdinal = nil then FOrdinal := TArithmeticSmallInt.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticSmallInt.Add(Left, Right: SmallInt): SmallInt; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticSmallInt.Divide(Left, Right: SmallInt): SmallInt; begin Result := Left div Right; end; function TArithmeticUtils<T>.TArithmeticSmallInt.Multiply(Left, Right: SmallInt): SmallInt; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticSmallInt.Negative(Value: SmallInt): SmallInt; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticSmallInt.Subtract(Left, Right: SmallInt): SmallInt; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticFixedInt } class function TArithmeticUtils<T>.TArithmeticFixedInt.Ordinal: TArithmeticFixedInt; begin if FOrdinal = nil then FOrdinal := TArithmeticFixedInt.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticFixedInt.Add(Left, Right: FixedInt): FixedInt; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticFixedInt.Divide(Left, Right: FixedInt): FixedInt; begin Result := Left div Right; end; function TArithmeticUtils<T>.TArithmeticFixedInt.Multiply(Left, Right: FixedInt): FixedInt; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticFixedInt.Negative(Value: FixedInt): FixedInt; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticFixedInt.Subtract(Left, Right: FixedInt): FixedInt; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticInt64 } class function TArithmeticUtils<T>.TArithmeticInt64.Ordinal: TArithmeticInt64; begin if FOrdinal = nil then FOrdinal := TArithmeticInt64.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticInt64.Add(Left, Right: Int64): Int64; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticInt64.Divide(Left, Right: Int64): Int64; begin Result := Left div Right; end; function TArithmeticUtils<T>.TArithmeticInt64.Multiply(Left, Right: Int64): Int64; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticInt64.Negative(Value: Int64): Int64; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticInt64.Subtract(Left, Right: Int64): Int64; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticByte } class function TArithmeticUtils<T>.TArithmeticByte.Ordinal: TArithmeticByte; begin if FOrdinal = nil then FOrdinal := TArithmeticByte.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticByte.Add(Left, Right: Byte): Byte; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticByte.Divide(Left, Right: Byte): Byte; begin Result := Left div Right; end; function TArithmeticUtils<T>.TArithmeticByte.Multiply(Left, Right: Byte): Byte; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticByte.Negative(Value: Byte): Byte; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticByte.Subtract(Left, Right: Byte): Byte; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticWord } class function TArithmeticUtils<T>.TArithmeticWord.Ordinal: TArithmeticWord; begin if FOrdinal = nil then FOrdinal := TArithmeticWord.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticWord.Add(Left, Right: Word): Word; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticWord.Divide(Left, Right: Word): Word; begin Result := Left div Right; end; function TArithmeticUtils<T>.TArithmeticWord.Multiply(Left, Right: Word): Word; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticWord.Negative(Value: Word): Word; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticWord.Subtract(Left, Right: Word): Word; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticFixedUInt } class function TArithmeticUtils<T>.TArithmeticFixedUInt.Ordinal: TArithmeticFixedUInt; begin if FOrdinal = nil then FOrdinal := TArithmeticFixedUInt.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticFixedUInt.Add(Left, Right: FixedUInt): FixedUInt; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticFixedUInt.Divide(Left, Right: FixedUInt): FixedUInt; begin Result := Left div Right; end; function TArithmeticUtils<T>.TArithmeticFixedUInt.Multiply(Left, Right: FixedUInt): FixedUInt; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticFixedUInt.Negative(Value: FixedUInt): FixedUInt; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticFixedUInt.Subtract(Left, Right: FixedUInt): FixedUInt; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticUInt64 } class function TArithmeticUtils<T>.TArithmeticUInt64.Ordinal: TArithmeticUInt64; begin if FOrdinal = nil then FOrdinal := TArithmeticUInt64.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticUInt64.Add(Left, Right: UInt64): UInt64; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticUInt64.Divide(Left, Right: UInt64): UInt64; begin Result := Left div Right; end; function TArithmeticUtils<T>.TArithmeticUInt64.Multiply(Left, Right: UInt64): UInt64; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticUInt64.Negative(Value: UInt64): UInt64; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticUInt64.Subtract(Left, Right: UInt64): UInt64; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticSingle } class function TArithmeticUtils<T>.TArithmeticSingle.Ordinal: TArithmeticSingle; begin if FOrdinal = nil then FOrdinal := TArithmeticSingle.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticSingle.Add(Left, Right: Single): Single; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticSingle.Divide(Left, Right: Single): Single; begin Result := Left / Right; end; function TArithmeticUtils<T>.TArithmeticSingle.Multiply(Left, Right: Single): Single; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticSingle.Negative(Value: Single): Single; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticSingle.Subtract(Left, Right: Single): Single; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticDouble } class function TArithmeticUtils<T>.TArithmeticDouble.Ordinal: TArithmeticDouble; begin if FOrdinal = nil then FOrdinal := TArithmeticDouble.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticDouble.Add(Left, Right: double): double; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticDouble.Divide(Left, Right: double): double; begin Result := Left / Right; end; function TArithmeticUtils<T>.TArithmeticDouble.Multiply(Left, Right: double): double; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticDouble.Negative(Value: double): double; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticDouble.Subtract(Left, Right: double): double; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticReal } class function TArithmeticUtils<T>.TArithmeticReal.Ordinal: TArithmeticReal; begin if FOrdinal = nil then FOrdinal := TArithmeticReal.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticReal.Add(Left, Right: Real): Real; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticReal.Divide(Left, Right: Real): Real; begin Result := Left / Right; end; function TArithmeticUtils<T>.TArithmeticReal.Multiply(Left, Right: Real): Real; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticReal.Negative(Value: Real): Real; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticReal.Subtract(Left, Right: Real): Real; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticExtended } class function TArithmeticUtils<T>.TArithmeticExtended.Ordinal: TArithmeticExtended; begin if FOrdinal = nil then FOrdinal := TArithmeticExtended.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticExtended.Add(Left, Right: Extended): Extended; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticExtended.Divide(Left, Right: Extended): Extended; begin Result := Left / Right; end; function TArithmeticUtils<T>.TArithmeticExtended.Multiply(Left, Right: Extended): Extended; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticExtended.Negative(Value: Extended): Extended; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticExtended.Subtract(Left, Right: Extended): Extended; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticComp } class function TArithmeticUtils<T>.TArithmeticComp.Ordinal: TArithmeticComp; begin if FOrdinal = nil then FOrdinal := TArithmeticComp.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticComp.Add(Left, Right: Comp): Comp; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticComp.Divide(Left, Right: Comp): Comp; begin Result := Left / Right; end; function TArithmeticUtils<T>.TArithmeticComp.Multiply(Left, Right: Comp): Comp; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticComp.Negative(Value: Comp): Comp; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticComp.Subtract(Left, Right: Comp): Comp; begin Result := Left - Right; end; { TArithmeticUtils<T>.TArithmeticCurrency } class function TArithmeticUtils<T>.TArithmeticCurrency.Ordinal: TArithmeticCurrency; begin if FOrdinal = nil then FOrdinal := TArithmeticCurrency.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticCurrency.Add(Left, Right: Currency): Currency; begin Result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticCurrency.Divide(Left, Right: Currency): Currency; begin Result := Left / Right; end; function TArithmeticUtils<T>.TArithmeticCurrency.Multiply(Left, Right: Currency): Currency; begin Result := Left * Right; end; function TArithmeticUtils<T>.TArithmeticCurrency.Negative(Value: Currency): Currency; begin Result := -Value; end; function TArithmeticUtils<T>.TArithmeticCurrency.Subtract(Left, Right: Currency): Currency; begin Result := Left - Right; end; {$IFDEF MSWINDOWS} { TArithmeticUtils<T>.TArithmeticAnsiString } class function TArithmeticUtils<T>.TArithmeticAnsiString.Ordinal: TArithmeticAnsiString; begin if FOrdinal = nil then FOrdinal := TArithmeticAnsiString.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticAnsiString.Add(Left, Right: AnsiString): AnsiString; begin result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticAnsiString.Subtract(Left, Right: AnsiString): AnsiString; begin result := Left; if AnsiEndsText(Right, Left) then SetLength(Result, Length(Result)-Length(Right)); end; function TArithmeticUtils<T>.TArithmeticAnsiString.Negative(Value: AnsiString): AnsiString; var I: Integer; L,U: AnsiString; begin L := AnsiUpperCase(Value); U := AnsiLowerCase(Value); result := Value; for I := Low(Result) to High(Result) do if Result[I] = L[I] then Result[I] := U[I] else Result[I] := L[I]; end; function TArithmeticUtils<T>.TArithmeticAnsiString.Multiply(Left, Right: AnsiString): AnsiString; begin raise Exception.Create('Bad operation'); end; function TArithmeticUtils<T>.TArithmeticAnsiString.Divide(Left, Right: AnsiString): AnsiString; begin raise Exception.Create('Bad operation'); end; {$EndIf} { TArithmeticUtils<T>.TArithmeticString } class function TArithmeticUtils<T>.TArithmeticString.Ordinal: TArithmeticString; begin if FOrdinal = nil then FOrdinal := TArithmeticString.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticString.Add(Left, Right: String): String; begin result := Left + Right; end; function TArithmeticUtils<T>.TArithmeticString.Subtract(Left, Right: String): String; begin result := Left; if result.EndsWith(Right, True) then SetLength(Result, Length(Result)-Length(Right)); end; function TArithmeticUtils<T>.TArithmeticString.Negative(Value: String): String; var I: Integer; begin result := Value; for I := Low(Result) to High(Result) do if Result[I].IsUpper then Result[I] := Result[I].ToLower else Result[I] := Result[I].ToUpper; end; function TArithmeticUtils<T>.TArithmeticString.Multiply(Left, Right: String): String; begin raise Exception.Create('Bad operation'); end; function TArithmeticUtils<T>.TArithmeticString.Divide(Left, Right: String): String; begin raise Exception.Create('Bad operation'); end; { TArithmeticUtils<T>.TArithmeticWideString } {$IF defined(MSWINDOWS)} class function TArithmeticUtils<T>.TArithmeticWideString.Ordinal: TArithmeticWideString; begin if FOrdinal = nil then FOrdinal := TArithmeticWideString.Create; Result := FOrdinal; end; function TArithmeticUtils<T>.TArithmeticWideString.Add(Left, Right: WideString): WideString; begin result := TArithmeticString.Ordinal.Add(Left, Right); end; function TArithmeticUtils<T>.TArithmeticWideString.Subtract(Left, Right: WideString): WideString; begin result := TArithmeticString.Ordinal.Subtract(Left, Right); end; function TArithmeticUtils<T>.TArithmeticWideString.Negative(Value: WideString): WideString; begin result := TArithmeticString.Ordinal.Negative(Value); end; function TArithmeticUtils<T>.TArithmeticWideString.Multiply(Left, Right: WideString): WideString; begin result := TArithmeticString.Ordinal.Multiply(Left, Right); end; function TArithmeticUtils<T>.TArithmeticWideString.Divide(Left, Right: WideString): WideString; begin result := TArithmeticString.Ordinal.Divide(Left, Right); end; {$ENDIF} end.
unit uCefScriptClickElement; interface uses // // uCefScriptBase, uCefScriptNavBase, uCefWebAction; type TScriptClickElement = class(TCefScriptNavBase) private FSpeed: Integer; FTag: string; FId: string; FName: string; FClass: string; FAttrName: string; FValueRegExpr: string; protected function DoNavEvent(const AWebAction: TCefWebAction): Boolean; override; public constructor Create(const ASpeed: Integer; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr: string; const ASetAsNav: Boolean; const AParent: TCefScriptBase); overload; constructor Create(const ASpeed: Integer; const AId: string; const ASetAsNav: Boolean; const AParent: TCefScriptBase); overload; constructor Create(const AId: string; const ASetAsNav: Boolean; const AParent: TCefScriptBase); overload; class function GetName: string; override; end; implementation uses // uCefUIFunc, uCefUtilConst; { TScriptClickElement } constructor TScriptClickElement.Create(const ASpeed: Integer; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr: string; const ASetAsNav: Boolean; const AParent: TCefScriptBase); begin inherited Create(ASetAsNav, AParent); FSpeed := ASpeed; FTag := ATag; FId := AId; FName := AName; FClass := AClass; FAttrName := AAttrName; FValueRegExpr := AAttrValueRegExpr; // if FSpeed = 0 then FSpeed := SPEED_DEF end; constructor TScriptClickElement.Create(const ASpeed: Integer; const AId: string; const ASetAsNav: Boolean; const AParent: TCefScriptBase); begin Create(ASpeed, '', AId, '', '', '', '', ASetAsNav, AParent) end; constructor TScriptClickElement.Create(const AId: string; const ASetAsNav: Boolean; const AParent: TCefScriptBase); begin Create(AParent.Controller.Speed, AId, ASetAsNav, AParent) end; function TScriptClickElement.DoNavEvent(const AWebAction: TCefWebAction): Boolean; var bol: Boolean; begin bol := CefUIScrollToElement(Chromium.Browser, FAbortEvent, FSpeed, FTag, FId, FName, FClass, FAttrName, FValueRegExpr); if not bol then begin FailMsg2('fail scroll to element'); Exit(False); end; bol := CefUIMouseMoveToElement(Chromium.Browser, FAbortEvent, FController.Cursor, FSpeed, FTag, FId, FName, FClass, FAttrName, FValueRegExpr); if not bol then begin FailMsg2('fail mouse move to element'); Exit(False); end; CefUIMouseClick(Self);// Chromium.Browser, FController.Cursor); Exit(True); end; class function TScriptClickElement.GetName: string; begin Result := 'click'; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 2010-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Vcl.Samples.Calendar; interface uses System.Classes, Vcl.Controls, Winapi.Messages, Winapi.Windows, Vcl.Forms, Vcl.Graphics, Vcl.StdCtrls, Vcl.Grids, System.SysUtils; type TDayOfWeek = 0..6; TCalendar = class(TCustomGrid) private FDate: TDateTime; FMonthOffset: Integer; FOnChange: TNotifyEvent; FReadOnly: Boolean; FStartOfWeek: TDayOfWeek; FUpdating: Boolean; FUseCurrentDate: Boolean; function GetCellText(ACol, ARow: Integer): string; function GetDateElement(Index: Integer): Integer; procedure SetCalendarDate(Value: TDateTime); procedure SetDateElement(Index: Integer; Value: Integer); procedure SetStartOfWeek(Value: TDayOfWeek); procedure SetUseCurrentDate(Value: Boolean); function StoreCalendarDate: Boolean; protected procedure Change; dynamic; procedure ChangeMonth(Delta: Integer); procedure ChangeScale(M, D: Integer); override; procedure Click; override; function DaysPerMonth(AYear, AMonth: Integer): Integer; virtual; function DaysThisMonth: Integer; virtual; procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override; function IsLeapYear(AYear: Integer): Boolean; virtual; function SelectCell(ACol, ARow: Longint): Boolean; override; procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure RecalcColumns(AHeight, AWidth: Integer); public constructor Create(AOwner: TComponent); override; property CalendarDate: TDateTime read FDate write SetCalendarDate stored StoreCalendarDate; property CellText[ACol, ARow: Integer]: string read GetCellText; procedure NextMonth; procedure NextYear; procedure PrevMonth; procedure PrevYear; procedure UpdateCalendar; virtual; published property Align; property Anchors; property BorderStyle; property Color; property Constraints; property Ctl3D; property Day: Integer index 3 read GetDateElement write SetDateElement stored False; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property GridLineWidth; property Month: Integer index 2 read GetDateElement write SetDateElement stored False; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly: Boolean read FReadOnly write FReadOnly default False; property ShowHint; property StartOfWeek: TDayOfWeek read FStartOfWeek write SetStartOfWeek; property TabOrder; property TabStop; property UseCurrentDate: Boolean read FUseCurrentDate write SetUseCurrentDate default True; property Visible; property StyleElements; property Year: Integer index 1 read GetDateElement write SetDateElement stored False; property OnClick; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnStartDock; property OnStartDrag; end; implementation constructor TCalendar.Create(AOwner: TComponent); begin inherited Create(AOwner); { defaults } FUseCurrentDate := True; FixedCols := 0; FixedRows := 1; ColCount := 7; RowCount := 7; ScrollBars := ssNone; Options := Options - [goRangeSelect] + [goDrawFocusSelected]; FDate := Date; UpdateCalendar; end; procedure TCalendar.Change; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TCalendar.Click; var TheCellText: string; begin inherited Click; TheCellText := CellText[Col, Row]; if TheCellText <> '' then Day := StrToInt(TheCellText); end; function TCalendar.IsLeapYear(AYear: Integer): Boolean; begin Result := (AYear mod 4 = 0) and ((AYear mod 100 <> 0) or (AYear mod 400 = 0)); end; function TCalendar.DaysPerMonth(AYear, AMonth: Integer): Integer; const DaysInMonth: array[1..12] of Integer = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); begin Result := DaysInMonth[AMonth]; if (AMonth = 2) and IsLeapYear(AYear) then Inc(Result); { leap-year Feb is special } end; function TCalendar.DaysThisMonth: Integer; begin Result := DaysPerMonth(Year, Month); end; procedure TCalendar.DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); var TheText: string; begin TheText := CellText[ACol, ARow]; with ARect, Canvas do TextRect(ARect, Left + (Right - Left - TextWidth(TheText)) div 2, Top + (Bottom - Top - TextHeight(TheText)) div 2, TheText); end; function TCalendar.GetCellText(ACol, ARow: Integer): string; var DayNum: Integer; begin if ARow = 0 then { day names at tops of columns } Result := FormatSettings.ShortDayNames[(StartOfWeek + ACol) mod 7 + 1] else begin DayNum := FMonthOffset + ACol + (ARow - 1) * 7; if (DayNum < 1) or (DayNum > DaysThisMonth) then Result := '' else Result := IntToStr(DayNum); end; end; function TCalendar.SelectCell(ACol, ARow: Longint): Boolean; begin if ((not FUpdating) and FReadOnly) or (CellText[ACol, ARow] = '') then Result := False else Result := inherited SelectCell(ACol, ARow); end; procedure TCalendar.SetCalendarDate(Value: TDateTime); begin FDate := Value; UpdateCalendar; Change; end; function TCalendar.StoreCalendarDate: Boolean; begin Result := not FUseCurrentDate; end; function TCalendar.GetDateElement(Index: Integer): Integer; var AYear, AMonth, ADay: Word; begin DecodeDate(FDate, AYear, AMonth, ADay); case Index of 1: Result := AYear; 2: Result := AMonth; 3: Result := ADay; else Result := -1; end; end; procedure TCalendar.SetDateElement(Index: Integer; Value: Integer); var AYear, AMonth, ADay: Word; begin if Value > 0 then begin DecodeDate(FDate, AYear, AMonth, ADay); case Index of 1: if AYear <> Value then AYear := Value else Exit; 2: if (Value <= 12) and (Value <> AMonth) then AMonth := Value else Exit; 3: if (Value <= DaysThisMonth) and (Value <> ADay) then ADay := Value else Exit; else Exit; end; FDate := EncodeDate(AYear, AMonth, ADay); FUseCurrentDate := False; UpdateCalendar; Change; end; end; procedure TCalendar.SetStartOfWeek(Value: TDayOfWeek); begin if Value <> FStartOfWeek then begin FStartOfWeek := Value; UpdateCalendar; end; end; procedure TCalendar.SetUseCurrentDate(Value: Boolean); begin if Value <> FUseCurrentDate then begin FUseCurrentDate := Value; if Value then begin FDate := Date; { use the current date, then } UpdateCalendar; end; end; end; { Given a value of 1 or -1, moves to Next or Prev month accordingly } procedure TCalendar.ChangeMonth(Delta: Integer); var AYear, AMonth, ADay: Word; NewDate: TDateTime; CurDay: Integer; begin DecodeDate(FDate, AYear, AMonth, ADay); CurDay := ADay; if Delta > 0 then ADay := DaysPerMonth(AYear, AMonth) else ADay := 1; NewDate := EncodeDate(AYear, AMonth, ADay); NewDate := NewDate + Delta; DecodeDate(NewDate, AYear, AMonth, ADay); if DaysPerMonth(AYear, AMonth) > CurDay then ADay := CurDay else ADay := DaysPerMonth(AYear, AMonth); CalendarDate := EncodeDate(AYear, AMonth, ADay); end; procedure TCalendar.ChangeScale(M, D: Integer); begin inherited ChangeScale(M, D); RecalcColumns(Height, Width); end; procedure TCalendar.PrevMonth; begin ChangeMonth(-1); end; procedure TCalendar.NextMonth; begin ChangeMonth(1); end; procedure TCalendar.NextYear; begin if IsLeapYear(Year) and (Month = 2) and (Day = 29) then Day := 28; Year := Year + 1; end; procedure TCalendar.PrevYear; begin if IsLeapYear(Year) and (Month = 2) and (Day = 29) then Day := 28; Year := Year - 1; end; procedure TCalendar.UpdateCalendar; var AYear, AMonth, ADay: Word; FirstDate: TDateTime; begin FUpdating := True; try DecodeDate(FDate, AYear, AMonth, ADay); FirstDate := EncodeDate(AYear, AMonth, 1); FMonthOffset := 2 - ((DayOfWeek(FirstDate) - StartOfWeek + 7) mod 7); { day of week for 1st of month } if FMonthOffset = 2 then FMonthOffset := -5; MoveColRow((ADay - FMonthOffset) mod 7, (ADay - FMonthOffset) div 7 + 1, False, False); Invalidate; finally FUpdating := False; end; end; procedure TCalendar.WMSize(var Message: TWMSize); begin RecalcColumns(Message.Height, Message.Width); end; procedure TCalendar.RecalcColumns(AHeight, AWidth: Integer); var GridLines: Integer; begin GridLines := 6 * GridLineWidth; DefaultColWidth := (AWidth - GridLines) div 7; DefaultRowHeight := (AHeight - GridLines) div 7; end; end.
{ ********************************************************************** } { } { Delphi Open-Tools API } { } { Copyright (C) 2000, 2001 Borland Software Corporation } { } { ********************************************************************** } unit DesignMenus; interface uses Types, Classes; type IMenuItem = interface; IMenuItems = interface ['{C9CC6C38-C96A-4514-8D6F-1D121727BFAF}'] // protected function GetItem(Index: Integer): IMenuItem; // public function SameAs(const AItem: IUnknown): Boolean; function Find(const ACaption: WideString): IMenuItem; function FindByName(const AName: string): IMenuItem; function Count: Integer; property Items[Index: Integer]: IMenuItem read GetItem; procedure Clear; function AddItem(const ACaption: WideString; AShortCut: TShortCut; AChecked, AEnabled: Boolean; AOnClick: TNotifyEvent = nil; hCtx: THelpContext = 0; const AName: string = ''): IMenuItem; overload; function AddItem(AAction: TBasicAction; const AName: string = ''): IMenuItem; overload; function InsertItem(const ACaption: WideString; AShortCut: TShortCut; AChecked, AEnabled: Boolean; AOnClick: TNotifyEvent = nil; hCtx: THelpContext = 0; const AName: string = ''): IMenuItem; overload; function InsertItem(Index: Integer; const ACaption: WideString; AShortCut: TShortCut; AChecked, AEnabled: Boolean; AOnClick: TNotifyEvent = nil; hCtx: THelpContext = 0; const AName: string = ''): IMenuItem; overload; function InsertItem(AAction: TBasicAction; const AName: string = ''): IMenuItem; overload; function InsertItem(Index: Integer; AAction: TBasicAction; const AName: string = ''): IMenuItem; overload; function AddLine(const AName: string = ''): IMenuItem; function InsertLine(const AName: string = ''): IMenuItem; overload; function InsertLine(Index: Integer; const AName: string = ''): IMenuItem; overload; end; IMenu = interface ['{0993FAE4-17E2-4EB7-81DF-26634D7F9E16}'] function Items: IMenuItems; end; IMainMenu = interface(IMenu) ['{5D137DC1-73F4-48CB-8351-E14A369AE924}'] end; IPopupMenu = interface(IMenu) ['{E2E9ED8C-4D54-482B-AC62-23F1CEBFE414}'] procedure Popup(X, Y: Integer); function PopupComponent: TComponent; end; IMenuItem = interface(IMenuItems) ['{DAF029E1-9592-4B07-A450-A10056A2B9B5}'] // protected function GetCaption: WideString; procedure SetCaption(const ACaption: WideString); function GetChecked: Boolean; procedure SetChecked(AChecked: Boolean); function GetEnabled: Boolean; procedure SetEnabled(AEnabled: Boolean); function GetGroupIndex: Byte; procedure SetGroupIndex(AGroupIndex: Byte); function GetHelpContext: THelpContext; procedure SetHelpContext(AHelpContext: THelpContext); function GetHint: string; procedure SetHint(const AHint: string); function GetRadioItem: Boolean; procedure SetRadioItem(ARadioItem: Boolean); function GetShortCut: TShortCut; procedure SetShortCut(AShortCut: TShortCut); function GetTag: LongInt; procedure SetTag(AValue: LongInt); function GetVisible: Boolean; procedure SetVisible(AVisible: Boolean); // public function Name: TComponentName; function MenuIndex: Integer; function Parent: IMenuItem; function HasParent: Boolean; function IsLine: Boolean; property Caption: WideString read GetCaption write SetCaption; property Checked: Boolean read GetChecked write SetChecked; property Enabled: Boolean read GetEnabled write SetEnabled; property GroupIndex: Byte read GetGroupIndex write SetGroupIndex; property HelpContext: THelpContext read GetHelpContext write SetHelpContext; property Hint: string read GetHint write SetHint; property RadioItem: Boolean read GetRadioItem write SetRadioItem; property ShortCut: TShortCut read GetShortCut write SetShortCut; property Tag: LongInt read GetTag write SetTag; property Visible: Boolean read GetVisible write SetVisible; end; type TLocalMenuType = (lmBase, lmModule, lmSelection, lmComponent); TLocalMenuTypes = set of TLocalMenuType; const CNoLocalMenus = []; CAllLocalMenus = [Low(TLocalMenuType)..High(TLocalMenuType)]; CLocalMenusIf: array [Boolean] of TLocalMenuTypes = (CNoLocalMenus, CAllLocalMenus); type IDesignLocalMenu = interface ['{70ED1A8D-6275-4BC8-813C-F6D9066FD6BB}'] function BuildLocalMenu(Allow: TLocalMenuTypes = CAllLocalMenus): IPopupMenu; procedure InvokeLocalMenu(X, Y: Integer); end; implementation end.
{*********************************************} { TeeChart Delphi Component Library } { Cross-Hair demo } { Copyright (c) 1995-2001 by David Berneda } { All rights reserved } {*********************************************} unit ucrossh; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Teengine, Series, ExtCtrls, Chart, Buttons, TeeProcs; type TCrossHairForm = class(TForm) Chart1: TChart; LineSeries1: TLineSeries; Panel1: TPanel; Label1: TLabel; BitBtn1: TBitBtn; Label2: TLabel; CheckBox1: TCheckBox; BitBtn2: TBitBtn; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure Chart1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure LineSeries1AfterDrawValues(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure BitBtn2Click(Sender: TObject); private { Private declarations } public { Public declarations } OldX,OldY:Longint; CrossHairColor:TColor; CrossHairStyle:TPenStyle; end; implementation {$R *.dfm} Uses udemutil; procedure TCrossHairForm.FormCreate(Sender: TObject); begin LineSeries1.FillSampleValues(30); { <-- some random values } OldX:=-1; { initialize variables } CrossHairColor:=clYellow; CrossHairStyle:=psSolid; end; procedure TCrossHairForm.Chart1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); { This procedure draws the crosshair lines } Procedure DrawCross(AX,AY:Integer); begin With Chart1,Canvas do begin Pen.Color:=CrossHairColor; Pen.Style:=CrossHairStyle; Pen.Mode:=pmXor; Pen.Width:=1; MoveTo(ax,ChartRect.Top-Height3D); LineTo(ax,ChartRect.Bottom-Height3D); MoveTo(ChartRect.Left+Width3D,ay); LineTo(ChartRect.Right+Width3D,ay); end; end; Var tmpX,tmpY:Double; begin if (OldX<>-1) then begin DrawCross(OldX,OldY); { draw old crosshair } OldX:=-1; end; { check if mouse is inside Chart rectangle } if PtInRect( Chart1.ChartRect, Point(X-Chart1.Width3D,Y+Chart1.Height3D) ) then begin DrawCross(x,y); { draw crosshair at current position } { store old position } OldX:=x; OldY:=y; { set label text } With LineSeries1 do begin GetCursorValues(tmpX,tmpY); { <-- get values under mouse cursor } Label1.Caption:=GetVertAxis.LabelValue(tmpY)+ ' '+ GetHorizAxis.LabelValue(tmpX); end; end; end; procedure TCrossHairForm.LineSeries1AfterDrawValues(Sender: TObject); begin OldX:=-1; { Reset old mouse position } end; procedure TCrossHairForm.CheckBox1Click(Sender: TObject); begin if CheckBox1.Checked then Chart1.Cursor:=crCross else Chart1.Cursor:=crDefault; Chart1.OriginalCursor:=Chart1.Cursor; end; procedure TCrossHairForm.BitBtn2Click(Sender: TObject); begin CrossHairColor:=EditColor(Self,CrossHairColor); end; end.
unit uUsersOfTravelProgress; interface uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, Soap.encddecd, System.IOUtils, FMX.Dialogs, FMX.Forms, Classes, SysUtils, System.UITypes, System.Variants, FMX.Graphics, Data.DB, Data.DbxSqlite, Data.SqlExpr; type TUsersOfTravelProgress = class(TCollectionItem) public IdUsersOfTravelProgress: string; IdUser: string; ActionId: string; EventId: string; State: string; end; TUsersOfTravelProgressList = class(TCollection) public procedure AddProgressRecord(IdUsersOfTravelProgress, ActionId, EventId, State, IdUser: string); function ConnectToDb: TSQLConnection; procedure LoadUsersOfTravelProgress; procedure SaveUsersOfTravelProgress; function CheckEvent(EventId: string): boolean; function SelectByUserIdCount(UserId: string): integer; procedure SaveInDB(Item: TUsersOfTravelProgress); function SelectByUserId(UserId: string): string; end; implementation { TUsersOfTravelProgressList } procedure TUsersOfTravelProgressList.AddProgressRecord(IdUsersOfTravelProgress, ActionId, EventId, State, IdUser: string); var Item: TUsersOfTravelProgress; begin Item := TUsersOfTravelProgress(self.Add); Item.IdUsersOfTravelProgress := IdUsersOfTravelProgress; Item.ActionId := ActionId; Item.EventId := EventId; Item.State := State; Item.IdUser := IdUser; end; function TUsersOfTravelProgressList.CheckEvent(EventId: string): boolean; var connect: TSQLConnection; query: TSQLQuery; begin connect := ConnectToDb; query := TSQLQuery.Create(nil); try query.SQLConnection := connect; query.SQL.Text := 'select Login from UsersOfTravelProgress where EventId = "' + EventId + '"'; query.Open; if query.Eof then begin result := false; connect.Close; end else begin result := true; connect.Close; end; finally freeandnil(query); end; freeandnil(connect); end; function TUsersOfTravelProgressList.ConnectToDb: TSQLConnection; var ASQLConnection: TSQLConnection; Path: string; begin ASQLConnection := TSQLConnection.Create(nil); ASQLConnection.ConnectionName := 'SQLITECONNECTION'; ASQLConnection.DriverName := 'Sqlite'; ASQLConnection.LoginPrompt := false; ASQLConnection.Params.Values['Host'] := 'localhost'; ASQLConnection.Params.Values['FailIfMissing'] := 'False'; ASQLConnection.Params.Values['ColumnMetaDataSupported'] := 'False'; Createdir(IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) + IncludeTrailingPathDelimiter('ExampleDb')); Path := IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) + IncludeTrailingPathDelimiter('ExampleDb') + 'ExampleDb.db'; ASQLConnection.Params.Values['Database'] := Path; ASQLConnection.Execute('CREATE TABLE if not exists UsersOfTravelProgress(' + 'IdUsersOfTravelProgess TEXT,' + 'ActionId TEXT,' + 'EventId TEXT,' + 'State TEXT,' + 'IdUser TEXT' + ');', nil); ASQLConnection.Open; result := ASQLConnection; end; procedure TUsersOfTravelProgressList.LoadUsersOfTravelProgress; var ASQLConnection: TSQLConnection; RS: TDataset; Item: TUsersOfTravelProgress; begin ASQLConnection := ConnectToDb; try ASQLConnection.Execute ('select IdUsersOfTravelProgess,ActionId,EventId,State from UsersOfTravelProgress', nil, RS); while not RS.Eof do begin Item := TUsersOfTravelProgress(self.Add); Item.IdUsersOfTravelProgress := RS.FieldByName('IdUsersOfTravelProgess').Value; Item.ActionId := RS.FieldByName('ActionId').Value; Item.EventId := RS.FieldByName('EventId').Value; Item.State := RS.FieldByName('State').Value; RS.Next; end; finally freeandnil(ASQLConnection); end; end; procedure TUsersOfTravelProgressList.SaveInDB(Item: TUsersOfTravelProgress); var query: String; querity: TSQLQuery; connect: TSQLConnection; Guid: TGUID; begin connect := ConnectToDb; querity := TSQLQuery.Create(nil); try querity.SQLConnection := connect; CreateGUID(Guid); query := 'INSERT INTO UsersOfTravelProgress (IdUsersOfTravelProgess,ActionId,EventId,State,IdUser) VALUES (:IdUsersOfTravelProgess,:ActionId,:EventId,:State,:IdUser)'; querity.Params.CreateParam(TFieldType.ftString, 'IdUsersOfTravelProgess', ptInput); querity.Params.ParamByName('IdUsersOfTravelProgess').AsString := GUIDToString(Guid); querity.Params.CreateParam(TFieldType.ftString, 'ActionId', ptInput); querity.Params.ParamByName('ActionId').AsString := Item.ActionId; querity.Params.CreateParam(TFieldType.ftString, 'EventId', ptInput); querity.Params.ParamByName('EventId').AsString := Item.EventId; querity.Params.CreateParam(TFieldType.ftString, 'State', ptInput); querity.Params.ParamByName('State').AsString := Item.State; querity.Params.CreateParam(TFieldType.ftString, 'IdUser', ptInput); querity.Params.ParamByName('IdUser').AsString := Item.IdUser; querity.SQL.Text := query; querity.ExecSQL(); finally freeandnil(querity); end; freeandnil(connect); end; procedure TUsersOfTravelProgressList.SaveUsersOfTravelProgress; var i: integer; DB: TSQLConnection; Params: TParams; query: string; begin query := 'INSERT INTO UsersOfTravelProgress (IdUsersOfTravelProgess,ActionId,EventId,State,IdUser) VALUES (:IdUsersOfTravelProgess,:ActionId,:EventId,:State,:IdUser)'; DB := ConnectToDb; try for i := 0 to self.Count - 1 do begin Params := TParams.Create; Params.CreateParam(TFieldType.ftString, 'IdUsersOfTravelProgess', ptInput); Params.ParamByName('IdUsersOfTravelProgess').AsString := TUsersOfTravelProgress(self.Items[i]).IdUsersOfTravelProgress; Params.CreateParam(TFieldType.ftString, 'ActionId', ptInput); Params.ParamByName('ActionId').AsString := TUsersOfTravelProgress(self.Items[i]).ActionId; Params.CreateParam(TFieldType.ftString, 'EventId', ptInput); Params.ParamByName('EventId').AsString := TUsersOfTravelProgress(self.Items[i]).EventId; Params.CreateParam(TFieldType.ftString, 'State', ptInput); Params.ParamByName('State').AsString := TUsersOfTravelProgress(self.Items[i]).State; Params.CreateParam(TFieldType.ftString, 'IdUser', ptInput); Params.ParamByName('IdUser').AsString := TUsersOfTravelProgress(self.Items[i]).IdUser; DB.Execute(query, Params); freeandnil(Params); end; finally freeandnil(DB); end; end; function TUsersOfTravelProgressList.SelectByUserId(UserId: string): string; var ASQLConnection: TSQLConnection; RS: TDataset; begin ASQLConnection := ConnectToDb; try ASQLConnection.Execute ('select ActionId from UsersOfTravelProgress WHERE IdUser = "' + UserId + '"', nil, RS); while not RS.Eof do begin result := RS.FieldByName('ActionId').Value; RS.Next; end; finally freeandnil(ASQLConnection); end; freeandnil(RS); end; function TUsersOfTravelProgressList.SelectByUserIdCount(UserId: string) : integer; var ASQLConnection: TSQLConnection; RS: TDataset; i: integer; begin i := 0; ASQLConnection := ConnectToDb; try ASQLConnection.Execute ('select State from UsersOfTravelProgress WHERE IdUser = "' + UserId + '"', nil, RS); while not RS.Eof do begin RS.Next; inc(i); end; finally freeandnil(ASQLConnection); end; result := i; freeandnil(RS); end; end.
unit ADAPT.UnitTests.Generics.Comparers; interface {$I ADAPT.inc} uses {$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES} System.Classes, System.SysUtils, {$ELSE} Classes, SysUtils, {$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES} DUnitX.TestFramework; type [TestFixture] TAdaptUnitTestGenericsComparer = class(TObject) public [Test] [TestCase('A = A', 'A,A,True')] [TestCase('A <> B', 'A,B,False')] [TestCase('B <> A', 'B,A,False')] procedure AEqualToB(const AValueA, AValueB: String; const AExpectedResult: Boolean); [Test] [TestCase('A > A', 'A,A,False')] [TestCase('A > B', 'A,B,False')] [TestCase('B > A', 'B,A,True')] procedure AGreaterThanB(const AValueA, AValueB: String; const AExpectedResult: Boolean); [Test] [TestCase('A >= A', 'A,A,True')] [TestCase('A >= B', 'A,B,False')] [TestCase('B >= A', 'B,A,True')] procedure AGreaterThanOrEqualToB(const AValueA, AValueB: String; const AExpectedResult: Boolean); [Test] [TestCase('A < A', 'A,A,False')] [TestCase('A < B', 'A,B,True')] [TestCase('B < A', 'B,A,False')] procedure ALessThanB(const AValueA, AValueB: String; const AExpectedResult: Boolean); [Test] [TestCase('A <= A', 'A,A,True')] [TestCase('A <= B', 'A,B,True')] [TestCase('B <= A', 'B,A,False')] procedure ALessThanOrEqualToB(const AValueA, AValueB: String; const AExpectedResult: Boolean); end; implementation uses ADAPT.Comparers; { TAdaptUnitTestGenericsComparer } procedure TAdaptUnitTestGenericsComparer.AEqualToB(const AValueA, AValueB: String; const AExpectedResult: Boolean); begin if AExpectedResult then Assert.IsTrue(ADStringComparer.AEqualToB(AValueA, AValueB), Format('ValueA is "%s", ValueB is "%s"... these SHOULD evaluate as Matching, but do not!', [AValueA, AValueB])) else Assert.IsFalse(ADStringComparer.AEqualToB(AValueA, AValueB), Format('ValueA is "%s", ValueB is "%s"... these SHOULD evaluate as NOT Matching, but evaluate as Matching!', [AValueA, AValueB])) end; procedure TAdaptUnitTestGenericsComparer.AGreaterThanB(const AValueA, AValueB: String; const AExpectedResult: Boolean); begin if AExpectedResult then Assert.IsTrue(ADStringComparer.AGreaterThanB(AValueA, AValueB), Format('ValueA is "%s", ValueB is "%s"... ValueA SHOULD be GREATER THAN ValueB, but is not!', [AValueA, AValueB])) else Assert.IsFalse(ADStringComparer.AGreaterThanB(AValueA, AValueB), Format('ValueA is "%s", ValueB is "%s"... ValueB SHOULD be GREATER THAN ValueA, but is not!', [AValueA, AValueB])) end; procedure TAdaptUnitTestGenericsComparer.AGreaterThanOrEqualToB(const AValueA, AValueB: String; const AExpectedResult: Boolean); begin if AExpectedResult then Assert.IsTrue(ADStringComparer.AGreaterThanOrEqualToB(AValueA, AValueB), Format('ValueA is "%s", ValueB is "%s"... ValueA SHOULD be GREATER THAN OR EQUAL TO ValueB, but is not!', [AValueA, AValueB])) else Assert.IsFalse(ADStringComparer.AGreaterThanOrEqualToB(AValueA, AValueB), Format('ValueA is "%s", ValueB is "%s"... ValueA should NOT be GREATER THAN OR EQUAL TO ValueB, but is not!', [AValueA, AValueB])) end; procedure TAdaptUnitTestGenericsComparer.ALessThanB(const AValueA, AValueB: String; const AExpectedResult: Boolean); begin if AExpectedResult then Assert.IsTrue(ADStringComparer.ALessThanB(AValueA, AValueB), Format('ValueA is "%s", ValueB is "%s"... ValueA SHOULD be LESS THAN ValueB, but is not!', [AValueA, AValueB])) else Assert.IsFalse(ADStringComparer.ALessThanB(AValueA, AValueB), Format('ValueA is "%s", ValueB is "%s"... ValueB SHOULD be LESS THAN ValueA, but is not!', [AValueA, AValueB])) end; procedure TAdaptUnitTestGenericsComparer.ALessThanOrEqualToB(const AValueA, AValueB: String; const AExpectedResult: Boolean); begin if AExpectedResult then Assert.IsTrue(ADStringComparer.ALessThanOrEqualToB(AValueA, AValueB), Format('ValueA is "%s", ValueB is "%s"... ValueA SHOULD be LESS THAN OR EQUAL TO ValueB, but is not!', [AValueA, AValueB])) else Assert.IsFalse(ADStringComparer.ALessThanOrEqualToB(AValueA, AValueB), Format('ValueA is "%s", ValueB is "%s"... ValueA should NOT be LESS THAN OR EQUAL TO ValueB, but is not!', [AValueA, AValueB])) end; initialization TDUnitX.RegisterTestFixture(TAdaptUnitTestGenericsComparer); end.
///////////////////////////////////////////////////////// // // // FlexGraphics library // // Copyright (c) 2002-2009, FlexGraphics software. // // // // FlexGraphics library file formats support // // Metafiles (wmf/emf) files // // // ///////////////////////////////////////////////////////// unit FormatMetaFile; {$I FlexDefs.inc} interface uses Windows, Types, UITypes, Classes, Graphics, FlexBase, FlexFileFormats; resourcestring sWmfFileDescription = 'Windows Metafiles'; sEmfFileDescription = 'Windows Enhanced Metafiles'; type TDoublePoint = record X, Y: double; end; TFlexMetafileFormat = class(TFlexFileFormat) protected // Internal fields FMetafile: TMetafile; FFlexPanel: TFlexPanel; FCanvas: TCanvas; FXForm: TXForm; FWExt: TDoublePoint; FWOrg: TDoublePoint; FVExt: TDoublePoint; FVOrg: TDoublePoint; procedure RegisterSupportedExtensions; override; procedure MetaToFlex(var Points; PointCount: integer); procedure ConvertEmr(DC: HDC; var lpEmr: TEMR); public procedure ImportFromStream(AStream: TStream; AFlexPanel: TFlexPanel; const Extension: TFlexFileExtension; const AFileName: string); override; procedure ExportToStream(AStream: TStream; AFlexPanel: TFlexPanel; const Extension: TFlexFileExtension; const AFileName: string); override; end; implementation uses SysUtils, Math, FlexUtils, FlexControls, FlexPath, FlexProps; function EnumEMFCallback( DC: HDC; // handle to device context var lpHTable: THandleTable; // pointer to metafile handle table var lpEMR: TEMR; // pointer to metafile record nObj: integer; // count of objects lpClientData: integer // pointer to optional data ): integer; far; stdcall; begin if not PlayEnhMetafileRecord(DC, lpHTable, PEnhMetaRecord(@lpEMR)^, nObj) then Result := 0 else begin Result := 1; TFlexMetafileFormat(lpClientData).ConvertEmr(DC, lpEmr); end; end; // Transformation to map recording device's device coordinate space // to destination device's logical coordinate space function GetPlayTransformation(hEmf: HENHMETAFILE; const rcPic: TRect; var xformPlay: TXForm): boolean; var Header: TEnhMetaHeader; sx0, sy0, sx1, sy1: double; rx, ry: double; begin Result := False; if GetEnhMetaFileHeader(hEmf, sizeof(Header), @Header) <= 0 then Exit; try // frame rectangle size in 0.01 mm -> 1 mm -> percentage -> device pixels with Header do begin sx0 := rclFrame.left / 100.0 / szlMillimeters.cx * szlDevice.cx; sy0 := rclFrame.top / 100.0 / szlMillimeters.cy * szlDevice.cy; sx1 := rclFrame.right / 100.0 / szlMillimeters.cx * szlDevice.cx; sy1 := rclFrame.bottom / 100.0 / szlMillimeters.cy * szlDevice.cy; end; // source to destination ratio with rcPic do begin rx := (right - left) / (sx1 - sx0); ry := (bottom - top) / (sy1 - sy0); end; with xformPlay do begin // x' = x * eM11 + y * eM21 + eDx // y' = x * eM12 + y * eM22 + eDy eM11 := rx; eM21 := 0; eDx := (-sx0*rx + rcPic.left); eM12 := 0; eM22 := ry; eDy := (-sy0*ry + rcPic.top); end; Result := True; except // Skip exceptions end; end; procedure PointsToAngles(const R: TRect; const ptStart, ptEnd: TPoint; var angStart, angEnd: double); var HR, WR: double; Coeff: double; function CalcAngle(X, Y: double): double; begin Y := Y * Coeff; if X = 0 then begin if Y > 0 then Result := 90 else Result := 270; end else begin Result := 180.0 * ArcTan2(Y, X) / pi; if Result < 0 then Result := 360.0 + Result; end; end; begin WR := (R.Right - R.Left) / 2; HR := (R.Bottom - R.Top) / 2; if HR = 0 then Coeff := 0 else Coeff := WR / HR; angStart := CalcAngle(ptStart.X - R.Left - WR, HR - (ptStart.Y - R.Top)); angEnd := CalcAngle(ptEnd.X - R.Left - WR, HR - (ptEnd.Y - R.Top)); end; // TFlexMetafileFormat //////////////////////////////////////////////////////// procedure TFlexMetafileFormat.RegisterSupportedExtensions; begin RegisterExtension('wmf', sWmfFileDescription, [skImport, skExport]); RegisterExtension('emf', sEmfFileDescription, [skImport, skExport]); end; procedure TFlexMetafileFormat.ImportFromStream(AStream: TStream; AFlexPanel: TFlexPanel; const Extension: TFlexFileExtension; const AFileName: string); var Bmp: TBitmap; R: TRect; begin FMetafile := Nil; Bmp := TBitmap.Create; try FMetafile := TMetafile.Create; FMetafile.LoadFromStream(AStream); FCanvas := Bmp.Canvas; FFlexPanel := AFlexPanel; FVOrg.X := 0; FVOrg.Y := 0; FVExt.X := 1; FVExt.Y := 1; FWOrg.X := 0; FWOrg.Y := 0; FWExt.X := 1; FWExt.Y := 1; R := Rect(0, 0, FMetafile.Width, FMetafile.Height); Bmp.Width := R.Right; Bmp.Height := R.Bottom; FFlexPanel.DocWidth := R.Right * PixelScaleFactor; FFlexPanel.DocHeight := R.Bottom * PixelScaleFactor; GetPlayTransformation(FMetafile.Handle, R, FXForm); // Enumerate EnumEnhMetafile(FCanvas.Handle, FMetafile.Handle, @EnumEMFCallback, Self, R); finally FCanvas := Nil; FMetafile.Free; FMetafile := Nil; FFlexPanel := Nil; Bmp.Free; end; end; procedure TFlexMetafileFormat.ExportToStream(AStream: TStream; AFlexPanel: TFlexPanel; const Extension: TFlexFileExtension; const AFileName: string); begin FMetafile := TMetafile.Create; try FFlexPanel := AFlexPanel; FMetafile.Width := ScaleValue(FFlexPanel.DocWidth, 100); FMetafile.Height := ScaleValue(FFlexPanel.DocHeight, 100); // Paint to metafile canvas FCanvas := TMetafileCanvas.Create(FMetafile, 0); try with FFlexPanel do PaintTo(FCanvas, Rect(0, 0, ScaleValue(DocWidth, 100), ScaleValue(DocHeight, 100)), Point(0, 0), 100, ActiveScheme, False, False, False, True, True); finally FCanvas.Free; FCanvas := Nil; end; FMetafile.Enhanced := CompareText(Extension.Extension, 'wmf') <> 0; FMetafile.SaveToStream(AStream); finally FFlexPanel := Nil; FMetafile.Free; FMetafile := Nil; end; end; procedure TFlexMetafileFormat.MetaToFlex(var Points; PointCount: integer); var i: integer; px, py: double; pt: PPoint; begin pt := @Points; for i:=0 to PointCount-1 do begin px := (pt.x - FWOrg.X) * FVExt.X / FWExt.X + FVOrg.X; py := (pt.y - FWOrg.Y) * FVExt.Y / FWExt.Y + FVOrg.Y; pt.X := Round( (px * FXForm.eM11 + px * FXForm.eM12 + FXForm.eDx) * PixelScaleFactor); pt.Y := Round( (py * FXForm.eM21 + py * FXForm.eM22 + FXForm.eDy) * PixelScaleFactor); inc(pt); end; end; procedure TFlexMetafileFormat.ConvertEmr(DC: HDC; var lpEmr: TEMR); type TSetupProp = (spPen, spBrush, spFont); TSetupProps = set of TSetupProp; var i, j: integer; Control: TFlexControl; Curve: TFlexCurve; Text: TFlexText; TextMetric: TTextMetric; TextStr: string; Points: TPointArray; PointTypes: TPointTypeArray; PolyPointCount: array of Dword; IsSolid: boolean; pt: TPoint; R: TRect; Bmp: TBitmap; AngStart, AngEnd: double; function Scale(const Value: integer; NoPixelScaleFactor: boolean = False): integer; begin if NoPixelScaleFactor then Result := Round(Value * FVExt.X / FWExt.Y * FXForm.eM11) else Result := Round(Value * FVExt.X / FWExt.Y * FXForm.eM11 * PixelScaleFactor); end; procedure SetupProps(Control: TFlexControl; Props: TSetupProps); var PenProp: TPenProp; BrushProp: TBrushProp; FontProp: TFontProp; LogObj: array of byte; begin if spPen in Props then begin PenProp := TPenProp(Control.Props['Pen']); if Assigned(PenProp) and (TObject(PenProp) is TPenProp) then begin SetLength(LogObj, SizeOf(TLogPen)); GetObject(GetCurrentObject(DC, OBJ_PEN), Length(LogObj), @LogObj[0]); with PenProp, PLogPen(@LogObj[0])^ do begin Style := TPenStyle(lopnStyle); Width := Scale(lopnWidth.X); if Width = 0 then Width := 1; Color := lopnColor; end; end; end; if spBrush in Props then begin BrushProp := TBrushProp(Control.Props['Brush']); if Assigned(BrushProp) and (TObject(BrushProp) is TBrushProp) then begin SetLength(LogObj, SizeOf(TLogBrush)); GetObject(GetCurrentObject(DC, OBJ_BRUSH), Length(LogObj), @LogObj[0]); with BrushProp, PLogBrush(@LogObj[0])^ do begin Color := lbColor; case lbStyle of BS_SOLID: Style := bsSolid; BS_HATCHED: case lbHatch of HS_BDIAGONAL : Style := bsBDiagonal; HS_CROSS : Style := bsCross; HS_DIAGCROSS : Style := bsDiagCross; HS_FDIAGONAL : Style := bsFDiagonal; HS_HORIZONTAL : Style := bsHorizontal; HS_VERTICAL : Style := bsVertical; end; BS_DIBPATTERN, BS_DIBPATTERN8X8, BS_DIBPATTERNPT: begin Bmp := TBitmap.Create; try with PBitmapInfo(lbHatch)^.bmiHeader do begin Bmp.Width := biWidth; Bmp.Height := biHeight; end; StretchDIBits(Bmp.Canvas.Handle, 0, 0, Bmp.Width, Bmp.Height, 0, 0, Bmp.Width, Bmp.Height, PChar(lbHatch) + PBitmapInfo(lbHatch).bmiHeader.biSize, PBitmapInfo(lbHatch)^, lbColor and $FFFF, SRCCOPY); Bitmap := Bmp; Method := bmBitmap; finally Bmp.Free; end; end; else Style := bsClear; end; end; end; end; if spFont in Props then begin FontProp := TFontProp(Control.Props['Font']); if Assigned(FontProp) and (TObject(FontProp) is TFontProp) then begin SetLength(LogObj, SizeOf(TLogFont)); GetObject(GetCurrentObject(DC, OBJ_FONT), Length(LogObj), @LogObj[0]); with PLogFont(@LogObj[0])^ do begin lfHeight := Scale(lfHeight, True); end; FontProp.Handle := CreateFontIndirect(PLogFont(@LogObj[0])^); FontProp.Color := GetTextColor(DC); end; end; end; procedure AssignSmallPoints(SrcPoints: PSmallPoint; PointCount: integer); var i: integer; begin SetLength(Points, PointCount); for i:=0 to PointCount-1 do begin Points[i].X := SrcPoints.x; Points[i].Y := SrcPoints.y; inc(SrcPoints); end; end; procedure AssignPoints(SrcPoints: PPoint; PointCount: integer); var i: integer; begin SetLength(Points, PointCount); for i:=0 to PointCount-1 do begin Points[i].X := SrcPoints.x; Points[i].Y := SrcPoints.y; inc(SrcPoints); end; end; function PictureFromEMR(Emr: Pointer; offBmiSrc, cbBmiSrc, offBitsSrc, cbBitsSrc: integer): TFlexControl; var BitmapInfo: PBitmapInfo; Bits: Pointer; Bmp: TBitmap; begin if cbBitsSrc = 0 then begin Result := TFlexBox.Create(FFlexPanel, FFlexPanel.ActiveScheme, FFlexPanel.ActiveLayer); SetupProps(Result, [spBrush]); TFlexBox(Result).PenProp.Style := psClear; Exit; end; BitmapInfo := PBitmapInfo(PChar(Emr) + offBmiSrc); Bits := PChar(Emr) + offBitsSrc; Bmp := TBitmap.Create; try Bmp.Width := BitmapInfo.bmiHeader.biWidth; Bmp.Height := Abs(BitmapInfo.bmiHeader.biHeight); StretchDIBits(Bmp.Canvas.Handle, 0, 0, Bmp.Width, Bmp.Height, 0, 0, Bmp.Width, Bmp.Height, Bits, BitmapInfo^, DIB_RGB_COLORS, SRCCOPY); Result := TFlexPicture.Create(FFlexPanel, FFlexPanel.ActiveScheme, FFlexPanel.ActiveLayer); with TFlexPicture(Result) do begin PictureProp.Graphic := Bmp; AutoSizeProp.Value := True; AutoSizeProp.Value := False; end; finally Bmp.Free; end; end; begin case lpEMR.iType of EMR_SETVIEWPORTEXTEX: with PEMRSetViewPortExtEx(@lpEMR).szlExtent do begin FVExt.X := cx; FVExt.Y := cy; end; EMR_SETVIEWPORTORGEX: with PEMRSetViewPortOrgEx(@lpEMR).ptlOrigin do begin FVOrg.X := X; FVOrg.Y := Y; end; EMR_SETWINDOWEXTEX: with PEMRSetViewPortExtEx(@lpEMR).szlExtent do begin FWExt.X := cx; FWExt.Y := cy; end; EMR_SETWINDOWORGEX: with PEMRSetViewPortOrgEx(@lpEMR).ptlOrigin do begin FWOrg.X := X; FWOrg.Y := Y; end; EMR_RECTANGLE, EMR_ROUNDRECT: begin if lpEMR.iType = EMR_RECTANGLE then begin R := PEmrRectangle(@lpEMR).rclBox; j := 0; end else begin R := PEmrRoundRect(@lpEMR).rclBox; j := Scale(PEmrRoundRect(@lpEMR).szlCorner.cx); end; MetaToFlex(R, 2); Control := TFlexBox.Create(FFlexPanel, FFlexPanel.ActiveScheme, FFlexPanel.ActiveLayer); Control.DocRect := R; TFlexBox(Control).RoundnessProp.Value := j; SetupProps(Control, [spPen, spBrush]); end; EMR_ARC, EMR_ELLIPSE: begin Control := TFlexEllipse.Create(FFlexPanel, FFlexPanel.ActiveScheme, FFlexPanel.ActiveLayer); if lpEMR.iType = EMR_ARC then R := PEmrArc(@lpEMR).rclBox else R := PEmrEllipse(@lpEMR).rclBox; MetaToFlex(R, 2); Control.DocRect := R; if lpEMR.iType = EMR_ARC then begin with PEmrArc(@lpEMR)^ do PointsToAngles(rclBox, ptlStart, ptlEnd, AngStart, AngEnd); TFlexEllipse(Control).BeginAngleProp.Value := Round(AngStart * PixelScaleFactor); TFlexEllipse(Control).EndAngleProp.Value := Round(AngEnd * PixelScaleFactor); end; SetupProps(Control, [spPen, spBrush]); end; EMR_EXTTEXTOUTW: begin with PEMRExtTextOut(@lpEMR)^ do begin TextStr := WideCharLenToString( PWideChar(PChar(@lpEMR) + emrtext.offString), emrtext.nChars); pt := emrtext.ptlReference; MetaToFlex(pt, 1); end; Text := TFlexText.Create(FFlexPanel, FFlexPanel.ActiveScheme, FFlexPanel.ActiveLayer); Text.Left := pt.X; Text.Top := pt.Y; Text.TextProp.Text := TextStr; SetupProps(Text, [spFont]); Text.AutoSizeProp.Value := true; j := GetTextAlign(DC); case j and (TA_LEFT or TA_RIGHT or TA_CENTER) of TA_CENTER : Text.Left := Text.Left - Text.Width div 2; TA_RIGHT : Text.Left := Text.Left - Text.Width; end; case j and (TA_TOP or TA_BOTTOM or TA_BASELINE) of TA_BASELINE: begin GetTextMetrics(DC, TextMetric); Text.Top := Text.Top - Scale(TextMetric.tmAscent); end; TA_BOTTOM: Text.Top := Text.Top - Text.Height; end; end; EMR_POLYLINE, EMR_POLYLINE16, EMR_POLYGON, EMR_POLYGON16: begin if (lpEMR.iType = EMR_POLYLINE16) or (lpEMR.iType = EMR_POLYGON16) then begin with PEMRPolyline16(@lpEmr)^ do AssignSmallPoints(@apts, cpts); end else with PEMRPolyline(@lpEmr)^ do AssignPoints(@aptl, cptl); Curve := TFlexCurve.Create(FFlexPanel, FFlexPanel.ActiveScheme, FFlexPanel.ActiveLayer); MetaToFlex(Points[0], Length(Points)); Curve.SetPoints(Points); if (lpEMR.iType = EMR_POLYGON16) or (lpEMR.iType = EMR_POLYGON) then begin Curve.IsSolidProp.Value := true; SetupProps(Curve, [spPen, spBrush]); end else SetupProps(Curve, [spPen]); end; EMR_POLYPOLYGON16, EMR_POLYPOLYGON, EMR_POLYPOLYLINE16, EMR_POLYPOLYLINE: begin if (lpEMR.iType = EMR_POLYPOLYLINE16) or (lpEMR.iType = EMR_POLYPOLYGON16) then with PEMRPolyPolyline16(@lpEmr)^ do begin SetLength(PolyPointCount, nPolys); for i:=0 to Length(PolyPointCount)-1 do PolyPointCount[i] := aPolyCounts[i]; AssignSmallPoints(@aPolyCounts[nPolys], cpts); end else with PEMRPolyPolyline(@lpEmr)^ do begin SetLength(PolyPointCount, nPolys); for i:=0 to Length(PolyPointCount)-1 do PolyPointCount[i] := aPolyCounts[i]; AssignPoints(@aPolyCounts[nPolys], cptl); end; IsSolid := (lpEMR.iType = EMR_POLYPOLYGON16) or (lpEMR.iType = EMR_POLYPOLYGON); SetLength(PointTypes, Length(Points)); for i:=0 to Length(PointTypes)-1 do PointTypes[i] := ptNode; j := 0; for i:=0 to Length(PolyPointCount)-1 do begin inc(j, PolyPointCount[i]); if IsSolid then PointTypes[j-1] := ptEndNodeClose else PointTypes[j-1] := ptEndNode; end; Curve := TFlexCurve.Create(FFlexPanel, FFlexPanel.ActiveScheme, FFlexPanel.ActiveLayer); MetaToFlex(Points[0], Length(Points)); Curve.SetPointsEx(Points, PointTypes); if IsSolid then SetupProps(Curve, [spPen, spBrush]) else SetupProps(Curve, [spPen]); end; EMR_STRETCHDIBITS: begin with PEmrStretchDIBits(@lpEMR)^ do begin Control := PictureFromEMR(@lpEmr, offBmiSrc, cbBmiSrc, offBitsSrc, cbBitsSrc); R := Rect(xDest, yDest, xDest + cxDest, yDest + cyDest); MetaToFlex(R, 2); Control.DocRect := R; end; end; EMR_BITBLT: begin with PEmrBitBlt(@lpEMR)^ do begin Control := PictureFromEMR(@lpEmr, offBmiSrc, cbBmiSrc, offBitsSrc, cbBitsSrc); R := Rect(xDest, yDest, xDest + cxDest, yDest + cyDest); MetaToFlex(R, 2); Control.DocRect := R; end; end; EMR_STRETCHBLT: begin with PEmrStretchBlt(@lpEMR)^ do begin Control := PictureFromEMR(@lpEmr, offBmiSrc, cbBmiSrc, offBitsSrc, cbBitsSrc); R := Rect(xDest, yDest, xDest + cxDest, yDest + cyDest); MetaToFlex(R, 2); Control.DocRect := R; end; end; EMR_MASKBLT: begin with PEmrMaskBlt(@lpEMR)^ do begin Control := PictureFromEMR(@lpEmr, offBmiSrc, cbBmiSrc, offBitsSrc, cbBitsSrc); R := Rect(xDest, yDest, xDest + cxDest, yDest + cyDest); MetaToFlex(R, 2); Control.DocRect := R; if Control is TFlexPicture then TFlexPicture(Control).PictureProp.Masked := True; end; end; end; end; initialization RegisteredFlexFileFormats.RegisterFormat(TFlexMetafileFormat); end.
unit Unit_Test_Variable_Stream; interface { Test a variable stream of Strings. Do the test using in-memory streams, and file streams. } uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VariableStream, Vcl.StdCtrls, System.IOUtils; type TTestForm = class(TForm) Memo1: TMemo; Button1: TButton; Memo2: TMemo; ListBox1: TListBox; Button2: TButton; ListBox2: TListBox; ListBox3: TListBox; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } procedure AddItems(const AStream:TStringsStream; const AItems:TStrings); procedure Test(const AStream:TStringsStream); public { Public declarations } end; var TestForm: TTestForm; implementation {$R *.dfm} const Max_Examples=5; Examples:Array[0..Max_Examples-1] of String=('Hello','This is quite a long text','12 34 56','','A'); Num_Samples=100000; function RandomString:String; begin result:=Examples[Random(Max_Examples)]; end; procedure TTestForm.AddItems(const AStream:TStringsStream; const AItems:TStrings); var t : Integer; begin AItems.BeginUpdate; try AItems.Clear; for t:=0 to AStream.Count-1 do AItems.Add(AStream[t]); finally AItems.EndUpdate; end; end; procedure TTestForm.Test(const AStream:TStringsStream); var t : Integer; begin // Clear AStream.Clear; // Add many strings for t:=0 to Num_Samples-1 do AStream.Append(RandomString); // Show Count Memo2.Clear; Memo2.Lines.Add('Count: '+AStream.Count.ToString); // Show Items AddItems(AStream,ListBox1.Items); // Delete one item AStream.Delete(0); // Show Items AddItems(AStream,ListBox2.Items); // Modify one item AStream[3]:='New Text !'; // Show Items AddItems(AStream,ListBox3.Items); // Remove empty unused space AStream.Trim; end; procedure TTestForm.Button1Click(Sender: TObject); var Data : TStringsStream; begin Data:=TStringsStream.Create(TMemoryStream); try Test(Data); finally Data.Free; end; end; const TestIndex='test.index'; procedure TTestForm.Button2Click(Sender: TObject); var Data : TStringsStream; begin Data:=TStringsStream.Create(TFileStream.Create(TestIndex,fmCreate), TFileStream.Create('test.data',fmCreate)); try Test(Data); finally Data.Free; end; end; procedure TTestForm.FormCreate(Sender: TObject); var Data : TStringsStream; begin Memo2.Clear; if TFile.Exists(TestIndex) then begin Data:=TStringsStream.Create(TFileStream.Create('test.index',fmOpenRead), TFileStream.Create('test.data',fmOpenRead)); try AddItems(Data,ListBox1.Items); finally Data.Free; end; end; end; end.
unit iWVInterface; { ================================================================================ * * Application: TDrugs Patch OR*3*377 and WV*1*24 * Developer: doma.user@domain.ext * Site: Salt Lake City ISC * * Description: Main interface unit for other applications to use. * * Notes: * ================================================================================ } interface uses System.Classes; type TWVAbleToConceive = (atcUnknown, atcYes, atcNo); TWVLactationStatus = (lsUnknown, lsYes, lsNo); TWVPregnancyStatus = (psUnknown, psYes, psNo, psUnsure); IWVController = interface; IWVPatient = interface; IWVWebSite = interface; IWVController = interface(IInterface) ['{46CCE409-CE72-4157-8876-BF169BEE315F}'] function getWebSite(aIndex: integer): IWVWebSite; function getWebSiteCount: integer; function getWebSiteListName: string; function EditPregLacData(aDFN: string): boolean; function SavePregnancyAndLactationData(aList: TStrings): boolean; function MarkAsEnteredInError(aItemID: string): boolean; function InitController(aForceInit: boolean = False): boolean; function IsValidWVPatient(aDFN: string): boolean; function GetRecordIDType(aRecordID: string; var aType: string): boolean; function GetLastError: string; function GetWebSiteURL(aWebSiteName: string): string; function OpenExternalWebsite(aWebSite: IWVWebSite): boolean; property WebSite[aIndex: integer]: IWVWebSite read getWebSite; property WebSiteCount: integer read getWebSiteCount; property WebSiteListName: string read getWebSiteListName; end; IWVPatient = interface(IInterface) ['{B99012A3-5DE8-4AEF-9D78-E15C11BF8017}'] function getDFN: string; procedure setDFN(const aValue: string); property DFN: string read getDFN write setDFN; end; IWVWebSite = interface(IInterface) ['{FB801C45-686F-4994-9326-10A32E84CC45}'] function GetName: string; function GetURL: string; property Name: string read GetName; property URL: string read GetURL; end; const WV_ABLE_TO_CONCEIVE: array [TWVAbleToConceive] of string = ('Unknown', 'Yes', 'No'); WV_LACTATION_STATUS: array [TWVLactationStatus] of string = ('Unknown', 'Yes', 'No'); WV_PREGNANCY_STATUS: array [TWVPregnancyStatus] of string = ('Unknown', 'Yes', 'No', 'Unsure'); function WomensHealth: IWVController; implementation uses oWVController; var fWVController: IWVController; function WomensHealth: IWVController; begin fWVController.QueryInterface(IWVController, Result); end; initialization TWVController.Create.GetInterface(IWVController, fWVController); end.
unit UsuarioDataUn; interface uses SysUtils, Classes, FMTBcd, Provider, osSQLDataSetProvider, DB, SqlExpr, osCustomDataSetProvider, osUtils, osSQLDataSet; type TUsuarioData = class(TDataModule) MasterDataSet: TosSQLDataset; MasterProvider: TosSQLDataSetProvider; MasterDataSource: TDataSource; GrupoDataSet: TosSQLDataset; GrupoProvider: TosSQLDataSetProvider; MasterDataSetIDUSUARIO: TIntegerField; MasterDataSetNOME: TStringField; MasterDataSetIDCARGO: TIntegerField; MasterDataSetAPELIDO: TStringField; MasterDataSetSENHA: TStringField; MasterDataSetSTATUS: TStringField; GrupoUsuarioDataSet: TosSQLDataset; GrupoUsuarioDataSetIDGRUPOUSUARIO: TIntegerField; GrupoUsuarioDataSetIDGRUPO: TIntegerField; GrupoUsuarioDataSetIDUSUARIO: TIntegerField; private public procedure Validate(PDataSet: TDataSet); end; var UsuarioData: TUsuarioData; implementation uses osErrorHandler, SQLMainData; {$R *.dfm} procedure TUsuarioData.Validate(PDataSet: TDataSet); begin with PDataSet, HError do begin Clear; WarningEmpty(FieldByName('IdCargo')); CheckEmpty(FieldByName('Apelido')); CheckEmpty(FieldByName('Nome')); WarningEmpty(FieldByName('Senha')); Check; end; end; initialization OSRegisterClass(TUsuarioData); end.
unit adot.Collections.Trees; interface { TTreeArrayClass<T> } uses adot.Types, adot.Collections.Types, adot.Collections.Vectors, System.Generics.Collections, System.Generics.Defaults; type { Simple class to build/keep tree as array of nodes with FirstChild/NextSibling properties. The tree is kept as array of nodes and thus there is no Delete/Remove functionality. The only way to delete a node (with subnodes) is call Rollback. As soon as Node is commited (Append + Commit or Add) the only way to delete it is Clear for whole tree. } TTreeArrayClass<T> = class public type TNode = record Data: T; FirstChild: integer; NextSibling: integer; end; PNode = ^TNode; { Enumerates all nodes (by index) } TEnumerator = record private Nodes: TVector<TNode>; Index: integer; function GetCurrent: integer; public procedure Init(const ANodes: TVector<TNode>); function MoveNext: Boolean; property Current: integer read GetCurrent; end; { Same as TEnumerator but returns value instead of index } TValuesEnumerator = record private Enum: TEnumerator; function GetCurrent: T; public procedure Init(const ANodes: TVector<TNode>); function MoveNext: Boolean; property Current: T read GetCurrent; end; { Enumerates all nodes (by index) starting from specified one } TSubtreeEnumerator = record private Nodes: TVector<TNode>; Stack: TVector<integer>; CurrentNode: integer; public procedure Init(const ANodes: TVector<TNode>; ARoot: integer); function MoveNext: Boolean; property Current: integer read CurrentNode; end; { Enumerates all values } TValuesCollection = record Nodes: TVector<TNode>; procedure Init(const ANodes: TVector<TNode>); function GetEnumerator: TValuesEnumerator; end; { Enumerable subtree starting from specified node } TSubtreeCollection = record Nodes: TVector<TNode>; Root: integer; procedure Init(const ANodes: TVector<TNode>; ARoot: integer); function GetEnumerator: TSubtreeEnumerator; end; var Nodes: TVector<TNode>; { Tree of the nodes stored as array. It is recommended to create single root node. } Stack: TVector<integer>; { Stack for tracking of CurParent } CurParent: integer; { Current destination (parent node) for Append/Add. } private function GetEmpty: boolean; function GetCount: integer; function GetValue(n: integer): T; procedure SetValue(n: integer; const Value: T); function GetTotalSizeBytes: int64; function GetSubtreeCollection(StaringNode: integer): TSubtreeCollection; function GetValuesCollection: TValuesCollection; public { Empty Nodes and other structures. } procedure Clear; { Sequentional adding. Append/Commit(or Rollback) must be balanced. Example: Tree.Append('root item'); Tree.Add('child 1'); Tree.Append('child 2'); Tree.Add('child 2.1'); Tree.Add('child 2.2'); Tree.Add('child 2.3'); Tree.Commit; Tree.Add('child 3'); Tree.Commit; No need to keep/handle pointers to nodes, no need to navigate directly parent/child node etc. } { add new node (as child to CurParent) and make it CurParent } function Append(const Value: T): integer; overload; function Append: integer; overload; { Add = Append + Commit (add single child without own sibling/child nodes) } function Add(const Value: T): integer; overload; function Add: integer; overload; { all subchilds are added, assign parent node as CurParent } function Commit: integer; overload; function Commit(ReverseOrderOfChildNodes: Boolean): integer; overload; { remove CurParent with all childs and assign parent node as CurParent } function Rollback: integer; { Random add functions. Example: Tree.Clear; I := Tree.AddChild('root item', -1); J := Tree.AddChild('child 1', I); J := Tree.AddSibling('child 2', J); K := Tree.AddChild('child 2.1', J); K := Tree.AddSibling('child 2.2', K); K := Tree.AddSibling('child 2.3', K); J := Tree.AddSibling('child 3', J); } { Add child node (AParent=-1 for root node). Only one root node is allowed. } function AddChild(const Value: T; AParent: integer): integer; { Add sibling node. APrevSibling must be provided. } function AddSibling(const Value: T; APrevSibling: integer): integer; { Example: for I in Tree do (*...*) ; } { Enumerator of all nodes (top-down,left-right). } function GetEnumerator: TEnumerator; function ToArray: TArray<T>; property Empty: boolean read GetEmpty; property Count: integer read GetCount; property Values[n: integer]: T read GetValue write SetValue; default; property TotalSizeBytes: int64 read GetTotalSizeBytes; { Enumerator of all nodes from subtree (top-down,left-right). } property Subtree[StaringNode: integer]: TSubtreeCollection read GetSubtreeCollection; property ValuesCollection: TValuesCollection read GetValuesCollection; end; implementation uses adot.Tools; { TTreeArrayClass<T>.TEnumerator } procedure TTreeArrayClass<T>.TEnumerator.Init(const ANodes: TVector<TNode>); begin Self := Default(TEnumerator); Nodes := ANodes; Index := 0; end; function TTreeArrayClass<T>.TEnumerator.GetCurrent: integer; begin result := Index-1; end; function TTreeArrayClass<T>.TEnumerator.MoveNext: Boolean; begin result := Index < Nodes.Count; if result then inc(Index); end; { TTreeArrayClass<T> } function TTreeArrayClass<T>.GetCount: integer; begin result := Nodes.Count; end; function TTreeArrayClass<T>.GetEmpty: boolean; begin result := Nodes.Empty; end; function TTreeArrayClass<T>.GetEnumerator: TEnumerator; begin result.Init(Nodes); end; function TTreeArrayClass<T>.GetSubtreeCollection(StaringNode: integer): TSubtreeCollection; begin result.Init(Nodes, StaringNode); end; function TTreeArrayClass<T>.GetTotalSizeBytes: int64; begin result := Nodes.TotalSizeBytes + Stack.TotalSizeBytes + SizeOf(CurParent); end; function TTreeArrayClass<T>.GetValue(n: integer): T; begin result := Nodes.Items[n].Data; end; procedure TTreeArrayClass<T>.SetValue(n: integer; const Value: T); begin Nodes.Items[n].Data := Value; end; function TTreeArrayClass<T>.ToArray: TArray<T>; var I: Integer; begin setLength(result, Nodes.Count); for I := 0 to Nodes.Count-1 do result[I] := Nodes.Items[I].Data; end; function TTreeArrayClass<T>.GetValuesCollection: TValuesCollection; begin result.Init(Nodes); end; procedure TTreeArrayClass<T>.Clear; begin Nodes.Clear; Stack.Clear; CurParent := -1; end; function TTreeArrayClass<T>.Append(const Value: T): integer; var Node: PNode; begin Result := Nodes.Add; Node := @Nodes.Items[result]; Node.Data := Value; Node.FirstChild := -1; if CurParent < 0 then if Nodes.Count > 1 then begin Nodes.DeleteLast; raise EForbiddenOperation.Create('Only one root node is allowed'); end else Node.NextSibling := -1 else with Nodes.Items[CurParent] do begin Node.NextSibling := FirstChild; FirstChild := result; end; Stack.Add(result); { to be able rollback, we save Nodes.Count + CurParent } Stack.Add(CurParent); CurParent := result; end; function TTreeArrayClass<T>.Append: integer; begin result := Append(Default(T)); end; function TTreeArrayClass<T>.Add(const Value: T): integer; var Node: PNode; begin { We can use pair Append+Commit here, but we can make it more efficient if we avoid manipulations with Stack/CurParent. } // result := Append(Value); // Commit; Result := Nodes.Add; Node := @Nodes.Items[result]; Node.Data := Value; Node.FirstChild := -1; if CurParent < 0 then if Nodes.Count > 1 then begin Nodes.DeleteLast; raise EForbiddenOperation.Create('Only one root node is allowed'); end else Node.NextSibling := -1 else with Nodes.Items[CurParent] do begin Node.NextSibling := FirstChild; FirstChild := result; end; end; function TTreeArrayClass<T>.Add: integer; begin result := Add(Default(T)); end; function TTreeArrayClass<T>.Commit(ReverseOrderOfChildNodes: Boolean): integer; var FirstChild, C,I,J: Integer; begin C := CurParent; CurParent := Stack.ExtractLast; { stored CurParrent } Result := Stack.ExtractLast; { stored Count (used by rollback) = index of item to be commited } { we added items in reverse order, we restore normal order here } if ReverseOrderOfChildNodes then Exit; { if there is no child nodes, we can exit } FirstChild := Nodes.Items[C].FirstChild; if FirstChild < 0 then Exit; { if there is one only child node, we can exit } I := Nodes.Items[FirstChild].NextSibling; if I < 0 then Exit; { We just taken NextSibling from FirstChild and will insert all childs before that node. It means FirstChild became last node in new chain and we should assign NextSibling = -1. } Nodes.Items[FirstChild].NextSibling := -1; repeat J := Nodes.Items[I].NextSibling; Nodes.Items[I].NextSibling := FirstChild; FirstChild := I; I := J; until I < 0; Nodes.Items[C].FirstChild := FirstChild; end; function TTreeArrayClass<T>.Commit: integer; begin Result := Commit(False); end; function TTreeArrayClass<T>.Rollback: integer; begin CurParent := Stack.ExtractLast; { Append method always adds item as first child to its parent. It means we don't need to scan chain to remove the node currectly. } if CurParent >= 0 then with Nodes.Items[CurParent] do FirstChild := Nodes.Items[FirstChild].NextSibling; { now we can delete the node with all subnodes } Result := Stack.ExtractLast; Nodes.Count := Result; end; function TTreeArrayClass<T>.AddChild(const Value: T; AParent: integer): integer; var Node: PNode; begin Result := Nodes.Add; Node := @Nodes.Items[result]; Node.Data := Value; Node.FirstChild := -1; if AParent=-1 then Node.NextSibling := -1 else with Nodes.Items[AParent] do begin Node.NextSibling := FirstChild; FirstChild := Result; end; end; function TTreeArrayClass<T>.AddSibling(const Value: T; APrevSibling: integer): integer; var Node: PNode; begin Assert(APrevSibling >= 0); Result := Nodes.Add; Nodes.Items[APrevSibling].NextSibling := Result; Node := @Nodes.Items[result]; Node.Data := Value; Node.FirstChild := -1; Node.NextSibling := -1; end; { TTreeArrayClass<T>.TSubtreeEnumerator } procedure TTreeArrayClass<T>.TSubtreeEnumerator.Init(const ANodes: TVector<TNode>; ARoot: integer); begin Self := Default(TSubtreeEnumerator); Nodes := ANodes; Stack.Clear; Stack.Add(ARoot); CurrentNode := -1; end; function TTreeArrayClass<T>.TSubtreeEnumerator.MoveNext: Boolean; var I,J: integer; begin Result := not Stack.Empty; if not Result then Exit; CurrentNode := Stack.ExtractLast; J := Stack.Count; I := Nodes[CurrentNode].FirstChild; while I >= 0 do begin Stack.Add(I); I := Nodes[I].NextSibling; end; TArrayUtils.Inverse<integer>(Stack.Items, J, Stack.Count-J); end; { TTreeArrayClass<T>.TSubtreeCollection } procedure TTreeArrayClass<T>.TSubtreeCollection.Init(const ANodes: TVector<TNode>; ARoot: integer); begin Self := Default(TSubtreeCollection); Nodes := ANodes; Root := ARoot; end; function TTreeArrayClass<T>.TSubtreeCollection.GetEnumerator: TSubtreeEnumerator; begin result.Init(Nodes, Root); end; { TTreeArrayClass<T>.TValuesEnumerator } procedure TTreeArrayClass<T>.TValuesEnumerator.Init(const ANodes: TVector<TNode>); begin Self := Default(TValuesEnumerator); Enum.Init(ANodes); end; function TTreeArrayClass<T>.TValuesEnumerator.GetCurrent: T; begin result := Enum.Nodes.Items[Enum.Current].Data; end; function TTreeArrayClass<T>.TValuesEnumerator.MoveNext: Boolean; begin result := Enum.MoveNext; end; { TTreeArrayClass<T>.TValuesCollection } procedure TTreeArrayClass<T>.TValuesCollection.Init(const ANodes: TVector<TNode>); begin Self := Default(TValuesCollection); Nodes := ANodes; end; function TTreeArrayClass<T>.TValuesCollection.GetEnumerator: TValuesEnumerator; begin result.Init(Nodes); end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} {$HPPEMIT '#pragma link "Data.DbxFirebird"'} {Do not Localize} unit Data.DbxFirebird; interface uses Data.DBXDynalink, Data.DBXDynalinkNative, Data.DBXCommon, Data.DbxFirebirdReadOnlyMetaData, Data.DbxFirebirdMetaData; type TDBXFirebirdProperties = class(TDBXProperties) strict private const StrServerCharSet = 'ServerCharSet'; function GetDatabase: string; function GetPassword: string; function GetUserName: string; function GetServerCharSet: string; procedure SetServerCharSet(const Value: string); procedure SetDatabase(const Value: string); procedure SetPassword(const Value: string); procedure SetUserName(const Value: string); public constructor Create(DBXContext: TDBXContext); override; published property Database: string read GetDatabase write SetDatabase; property UserName: string read GetUserName write SetUserName; property Password: string read GetPassword write SetPassword; property ServerCharSet: string read GetServerCharSet write SetServerCharSet; end; TDBXFirebirdDriver = class(TDBXDynalinkDriverNative) public constructor Create(DBXDriverDef: TDBXDriverDef); override; end; implementation uses Data.DBXPlatform, System.SysUtils; const sDriverName = 'Firebird'; { TDBXFirebirdDriver } constructor TDBXFirebirdDriver.Create(DBXDriverDef: TDBXDriverDef); var Props: TDBXFirebirdProperties; I, Index: Integer; begin Props := TDBXFirebirdProperties.Create(DBXDriverDef.FDBXContext); if DBXDriverDef.FDriverProperties <> nil then begin for I := 0 to DBXDriverDef.FDriverProperties.Count - 1 do begin Index := Props.Properties.IndexOfName(DBXDriverDef.FDriverProperties.Properties.Names[I]); if Index > -1 then Props.Properties.Strings[Index] := DBXDriverDef.FDriverProperties.Properties.Strings[I]; end; Props.AddUniqueProperties(DBXDriverDef.FDriverProperties.Properties); DBXDriverDef.FDriverProperties.AddUniqueProperties(Props.Properties); end; inherited Create(DBXDriverDef, TDBXDynalinkDriverLoader, Props); rpr; end; { TDBXFirebirdProperties } constructor TDBXFirebirdProperties.Create(DBXContext: TDBXContext); begin inherited Create(DBXContext); Values[TDBXPropertyNames.DriverUnit] := 'Data.DBXFirebird'; Values[TDBXPropertyNames.DriverPackageLoader] := 'TDBXDynalinkDriverLoader,DBXFirebirdDriver160.bpl'; Values[TDBXPropertyNames.DriverAssemblyLoader] := 'Borland.Data.TDBXDynalinkDriverLoader,Borland.Data.DbxCommonDriver,Version=16.0.0.0,Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken; Values[TDBXPropertyNames.MetaDataPackageLoader] := 'TDBXFirebirdMetaDataCommandFactory,DbxFirebirdDriver160.bpl'; Values[TDBXPropertyNames.MetaDataAssemblyLoader] := 'Borland.Data.TDBXFirebirdMetaDataCommandFactory,Borland.Data.DbxFirebirdDriver,Version=16.0.0.0,Culture=neutral,PublicKeyToken=' + TDBXPlatform.GetPublicKeyToken; Values[TDBXPropertyNames.GetDriverFunc] := 'getSQLDriverINTERBASE'; Values[TDBXPropertyNames.LibraryName] := 'dbxfb.dll'; Values[TDBXPropertyNames.LibraryNameOsx] := 'libsqlfb.dylib'; Values[TDBXPropertyNames.VendorLib] := 'fbclient.dll'; Values[TDBXPropertyNames.VendorLibWin64] := 'fbclient.dll'; Values[TDBXPropertyNames.VendorLibOsx] := '/Library/Frameworks/Firebird.framework/Firebird'; Values[TDBXPropertyNames.Database] := 'database.fdb'; Values[TDBXPropertyNames.UserName] := 'sysdba'; Values[TDBXPropertyNames.Password] := 'masterkey'; Values[TDBXPropertyNames.Role] := 'RoleName'; Values[TDBXPropertyNames.MaxBlobSize] := '-1'; Values[TDBXPropertyNames.ErrorResourceFile] := ''; Values[TDBXDynalinkPropertyNames.LocaleCode] := '0000'; Values[TDBXPropertyNames.IsolationLevel] := 'ReadCommitted'; Values['ServerCharSet'] := ''; Values['SQLDialect'] := '3'; Values['CommitRetain'] := 'False'; Values['WaitOnLocks'] := 'True'; Values['TrimChar'] := 'False'; end; function TDBXFirebirdProperties.GetDatabase: string; begin Result := Values[TDBXPropertyNames.Database]; end; function TDBXFirebirdProperties.GetPassword: string; begin Result := Values[TDBXPropertyNames.Password]; end; function TDBXFirebirdProperties.GetServerCharSet: string; begin Result := Values[StrServerCharSet]; end; function TDBXFirebirdProperties.GetUserName: string; begin Result := Values[TDBXPropertyNames.UserName]; end; procedure TDBXFirebirdProperties.SetDatabase(const Value: string); begin Values[TDBXPropertyNames.Database] := Value; end; procedure TDBXFirebirdProperties.SetPassword(const Value: string); begin Values[TDBXPropertyNames.Password] := Value; end; procedure TDBXFirebirdProperties.SetServerCharSet(const Value: string); begin Values[StrServerCharSet] := Value; end; procedure TDBXFirebirdProperties.SetUserName(const Value: string); begin Values[TDBXPropertyNames.UserName] := Value; end; initialization TDBXDriverRegistry.RegisterDriverClass(sDriverName, TDBXFirebirdDriver); end.
unit BrickCamp.service; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.SvcMgr, Spring.Container, Spring.Logging, BrickCamp.TService; type TsrvBrickCamp = class(TService) procedure ServiceExecute(Sender: TService); private FService: TCbdService; public function GetServiceController: TServiceController; override; procedure Initialize; end; var srvBrickCamp: TsrvBrickCamp; implementation uses BrickCamp.services; {$R *.DFM} procedure ServiceController(CtrlCode: DWord); stdcall; begin srvBrickCamp.Controller(CtrlCode); end; function TsrvBrickCamp.GetServiceController: TServiceController; begin Result := ServiceController; end; procedure TsrvBrickCamp.Initialize; begin try FService := TCbdService.Create; FService.Run; except on E: exception do begin CbLog.Error(E.Message); raise; end; end; end; procedure TsrvBrickCamp.ServiceExecute(Sender: TService); begin Initialize; end; end.
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // unit RN_PerfTimer; interface uses Windows; function getPerfTime(): Int64; function getPerfDeltaTimeUsec(const start, &end: Int64): Integer; implementation function getPerfTime(): Int64; var count: Int64; begin QueryPerformanceCounter(count); Result := count; end; function getPerfDeltaTimeUsec(const start, &end: Int64): Integer; var freq, elapsed: Int64; begin freq := 0; if (freq = 0) then QueryPerformanceFrequency(freq); elapsed := &end - start; Result := Trunc(elapsed * 1000000 / freq); end; end.
unit GeneralFunctions; //Minor modifications: // Added DetectCPUType from original MainUnit in FastCodeBenchmarkTool091 // Added GetCPUFrequence from original MainUnit in FastCodeBenchmarkTool091 {$mode delphi} interface uses Windows, SysUtils, Classes; type TVersion = record Major: integer; Minor: integer; Release: integer; Build: integer; end; PVS_FIXEDFILEINFO = ^VS_FIXEDFILEINFO; TCPUIDResult = packed record EAX: Cardinal; EBX: Cardinal; ECX: Cardinal; EDX: Cardinal; end; TCPUFeatures = class(TPersistent) private FSEP: Boolean; FMTRR: Boolean; FMSR: Boolean; FPSE: Boolean; FTSC: Boolean; FMCE: Boolean; FMMX: Boolean; FPAT: Boolean; FPAE: Boolean; FXSR: Boolean; FVME: Boolean; FPGE: Boolean; FCMOV: Boolean; FFPU: Boolean; FCX8: Boolean; FSIMD: Boolean; FMCA: Boolean; FAPIC: Boolean; FDE: Boolean; FPSE36: Boolean; FSERIAL: Boolean; F3DNOW: Boolean; FEX3DNOW: Boolean; FEXMMX: Boolean; published property _3DNOW: Boolean read F3DNOW write F3DNOW stored False; property EX_3DNOW: Boolean read FEX3DNOW write FEX3DNOW stored False; property EX_MMX: Boolean read FEXMMX write FEXMMX stored False; property SIMD: Boolean read FSIMD write FSIMD stored False; property SERIAL: Boolean read FSERIAL write FSERIAL stored False; property XSR: Boolean read FXSR write FXSR stored False; property MMX: Boolean read FMMX write FMMX stored False; property PSE36: Boolean read FPSE36 write FPSE36 stored False; property PAT: Boolean read FPAT write FPAT stored False; property CMOV: Boolean read FCMOV write FCMOV stored False; property MCA: Boolean read FMCA write FMCA stored False; property PGE: Boolean read FPGE write FPGE stored False; property MTRR: Boolean read FMTRR write FMTRR stored False; property SEP: Boolean read FSEP write FSEP stored False; property APIC: Boolean read FAPIC write FAPIC stored False; property CX8: Boolean read FCX8 write FCX8 stored False; property MCE: Boolean read FMCE write FMCE stored False; property PAE: Boolean read FPAE write FPAE stored False; property MSR: Boolean read FMSR write FMSR stored False; property TSC: Boolean read FTSC write FTSC stored False; property PSE: Boolean read FPSE write FPSE stored False; property DE: Boolean read FDE write FDE stored False; property VME: Boolean read FVME write FVME stored False; property FPU: Boolean read FFPU write FFPU stored False; end; TCPUID = array[1..4] of Longint; TVendor = array [0..11] of char; function GetCPUID : TCPUID; assembler; register; function IsCPUID_Available : Boolean; register; function GetCPUVendor : TVendor; assembler; register; function GetCPUFeaturesInfo(FeatureSetIndex : Integer) : Boolean; function ExecuteCPUID : TCPUIDResult; assembler; function GetFormattedVersion: string; function GetModuleVersionDFL(ModuleFileName: string; var Ver: TVersion; Product: Boolean = False): string; function DetectCPUType(Family, Model: Integer): String; function GetCPUFrequencyMHz : Cardinal; implementation //uses MainUnit; resourcestring TEXT_NO_VERSIONINFO = 'No version info'; var CPUID_Level : DWORD; CPUID : TCPUIDResult; const ID_BIT = $200000; CPUID_CPUFEATURESET : DWORD = $1; CPUID_CPUSIGNATUREEX: DWORD = $80000001; SFS_FPU = 0; SFS_VME = 1; SFS_DE = 2; SFS_PSE = 3; SFS_TSC = 4; SFS_MSR = 5; SFS_PAE = 6; SFS_MCE = 7; SFS_CX8 = 8; SFS_APIC = 9; SFS_SEP = 11; SFS_MTRR = 12; SFS_PGE = 13; SFS_MCA = 14; SFS_CMOV = 15; SFS_PAT = 16; SFS_PSE36 = 17; SFS_SERIAL = 18; SFS_MMX = 23; SFS_XSR = 24; SFS_SIMD = 25; EFS_EXMMXA = 22; { AMD Specific } EFS_EXMMXC = 24; { Cyrix Specific } EFS_3DNOW = 31; EFS_EX3DNOW = 30; function GetCPUID : TCPUID; assembler; register; asm push ebx {Save affected register} push edi mov edi,eax {@Resukt} mov eax,1 dw $a20f {CPUID Command} stosd {CPUID[1]} mov eax,ebx stosd {CPUID[2]} mov eax,ecx stosd {CPUID[3]} mov eax,edx stosd {CPUID[4]} pop edi {Restore registers} pop ebx end; function IsCPUID_Available : Boolean; register; asm pushfd {direct access to flags no possible, only via stack} pop eax {flags to EAX} mov edx,eax {save current flags} xor eax,id_bit {not ID bit} push eax {onto stack} popfd {from stack to flags, with not ID bit} pushfd {back to stack} pop eax {get back to EAX} xor eax,edx {check if ID bit affected} jz @exit {no, CPUID not availavle} mov al,True {Result=True} @exit: end; function GetCPUVendor : TVendor; assembler; register; asm push ebx {Save affected register} push edi mov edi,eax {@Result (TVendor)} mov eax,0 dw $a20f {CPUID Command} mov eax,ebx xchg ebx,ecx {save ECX result} mov ecx,4 @1: stosb shr eax,8 loop @1 mov eax,edx mov ecx,4 @2: stosb shr eax,8 loop @2 mov eax,ebx mov ecx,4 @3: stosb shr eax,8 loop @3 pop edi {Restore registers} pop ebx end; function GetCPUFeaturesInfo(FeatureSetIndex : Integer) : Boolean; begin if (FeatureSetIndex >= 0) and (FeatureSetIndex <21) then begin CPUID_Level := CPUID_CPUFEATURESET; CPUID := ExecuteCPUID; end; if (FeatureSetIndex >= 21) and (FeatureSetIndex <= 23) then begin CPUID_Level := CPUID_CPUSIGNATUREEX; CPUID := ExecuteCPUID; end; case FeatureSetIndex of 0 : Result := ((CPUID.EDX and (1 shl SFS_SIMD)) <> 0); // SIMD 1 : Result := ((CPUID.EDX and (1 shl SFS_XSR)) <> 0); // XSR 2 : Result := ((CPUID.EDX and (1 shl SFS_MMX)) <> 0); // MMX 3 : Result := ((CPUID.EDX and (1 shl SFS_SERIAL)) <> 0); // SERIAL 4 : Result := ((CPUID.EDX and (1 shl SFS_PSE36)) <> 0); // PSE36 5 : Result := ((CPUID.EDX and (1 shl SFS_PAT)) <> 0); // PAT 6 : Result := ((CPUID.EDX and (1 shl SFS_CMOV)) <> 0); // CMOV 7 : Result := ((CPUID.EDX and (1 shl SFS_MCA)) <> 0); // MCA 8 : Result := ((CPUID.EDX and (1 shl SFS_PGE)) <> 0); // PGE 9 : Result := ((CPUID.EDX and (1 shl SFS_MTRR)) <> 0); // MTRR 10 : Result := ((CPUID.EDX and (1 shl SFS_SEP)) <> 0); // SEP 11 : Result := ((CPUID.EDX and (1 shl SFS_APIC)) <> 0); // APIC 12 : Result := ((CPUID.EDX and (1 shl SFS_CX8)) <> 0); // CX8 13 : Result := ((CPUID.EDX and (1 shl SFS_MCE)) <> 0); // MCE 14 : Result := ((CPUID.EDX and (1 shl SFS_PAE)) <> 0); // PAE 15 : Result := ((CPUID.EDX and (1 shl SFS_MSR)) <> 0); // MSR 16 : Result := ((CPUID.EDX and (1 shl SFS_TSC)) <> 0); // TSC 17 : Result := ((CPUID.EDX and (1 shl SFS_PSE)) <> 0); // PSE 18 : Result := ((CPUID.EDX and (1 shl SFS_DE)) <> 0); // DE 19 : Result := ((CPUID.EDX and (1 shl SFS_VME)) <> 0);// VME 20 : Result := ((CPUID.EDX and (1 shl SFS_FPU)) <> 0); // FPU 21 : Result := ((CPUID.EDX and (1 shl EFS_EXMMXA)) <> 0) or ((CPUID.EDX and (1 shl EFS_EXMMXC)) <> 0); // EX_MMX 22 : Result := ((CPUID.EDX and (1 shl EFS_EX3DNOW)) <> 0); // EX_3DNOW 23 : Result := ((CPUID.EDX and (1 shl EFS_3DNOW)) <> 0); // _3DNOW else begin Result := False; // MessageBox(MainForm.Handle,'Index out of bounds',nil,MB_OK) end; end; end; function ExecuteCPUID : TCPUIDResult; assembler; asm push ebx push edi mov edi, eax mov eax, CPUID_LEVEL dw $A20F stosd mov eax, ebx stosd mov eax, ecx stosd mov eax, edx stosd pop edi pop ebx end; function GetFormattedVersion: string; var ver: TVersion; begin GetModuleVersionDFL(GetModuleName(HInstance), ver); Result := Format('%d.%d.%d', [ver.Major, ver.Minor, ver.Release]) end; function GetModuleVersionDFL(ModuleFileName: string; var Ver: TVersion; Product: Boolean = False): string; var VersionBufferLength: Integer; PVersionBuffer : Pointer; Dummy : Dword; PFixedFileInfo : PVS_FIXEDFILEINFO; ModuleVersionLength: Dword; VerW1, VerW2 : DWord; begin Ver.Major := 0; Ver.Minor := 0; Ver.Release := 0; Ver.Build := 0; VersionBufferLength:= GetFileVersionInfoSize(PChar(ModuleFileName),Dummy); PVersionBuffer:= AllocMem(VersionBufferLength); if (PVersionBuffer <> nil) then begin if (GetFileVersionInfo(PChar(ModuleFileName), VersionBufferLength,VersionBufferLength, PVersionBuffer)) then begin if (VerQueryValue(PVersionBuffer, '\', Pointer(PFixedFileInfo),ModuleVersionLength)) then begin if Product then begin VerW1 := PFixedFileInfo^.dwProductVersionMS; VerW2 := PFixedFileInfo^.dwProductVersionLS; end else begin VerW1 := PFixedFileInfo^.dwFileVersionMS; VerW2 := PFixedFileInfo^.dwFileVersionLS; end; Ver.Major := ((VerW1) and $FFFF0000) shr 16; Ver.Minor := ((VerW1) and $0000FFFF); Ver.Release := ((VerW2) and $FFFF0000) shr 16; Ver.Build := ((VerW2) and $0000FFFF); Result := Format('%d.%d.%d.%d', [Ver.Major, Ver.Minor, Ver.Release,Ver.Build]); end; end else begin Result:= TEXT_NO_VERSIONINFO; end; FreeMem(PVersionBuffer); end else begin Result:= TEXT_NO_VERSIONINFO; end; end; function DetectCPUType(Family, Model: Integer): String; var P2Array : array[0..5] of Integer; // Family : 6 P3Array : array[0..5] of Integer; // Family : 6 P4Array : array[0..5] of Integer; // Family : 15 XPArray : array[0..5] of Integer; // Family : 6 PrescottArray : array[0..5] of Integer; // Family : 15 OpteronArray : array[0..5] of Integer; // Family : 15 PentiumMArray : array[0..5] of Integer; // Family : 6 AthlonArray : array[0..5] of Integer; // Family : 6 Athlon64Array : array[0..5] of Integer; // Family : 15 CPUDetected : Boolean; I : Integer; Vendor: String; begin P2Array[0] := 5; //0101 P3Array[0] := 7; // 0111 P3Array[1] := 8; // 1000 P3Array[2] := 10; // 1010 P3Array[3] := 11; // 1011 P4Array[0] := 0; // 0000 P4Array[1] := 1; // 0001 P4Array[2] := 2; // 0010 XPArray[0] := 6; // 0110 XPArray[1] := 8; // 1000 XPArray[2] := 10; // 1010 PrescottArray[0] := 3; // 0011 OpteronArray[0] := 5; // 0101 AthlonArray[0] := 4; // 0100 Athlon64Array[0] := 4; // 0100 CPUDetected := False; Vendor := GetCPUVendor; begin if Vendor = 'GenuineIntel' then begin // Intel processors detection if Family = 6 then begin for I := 0 to 5 do begin if Model = P3Array[I] then begin Result := 'Pentium 3'; Exit; end; end; end; if Family = 6 then begin for I := 0 to 5 do begin if Model = P2Array[I] then begin Result := 'Pentium 2'; Exit; end; end; end; if Family = 6 then begin for I := 0 to 5 do begin if Model = PentiumMArray[I] then begin Result := 'Pentium M'; Exit; end; end; end; if Family = 15 then begin for I := 0 to 5 do begin if Model = P4Array[I] then begin Result := 'P4 Northwood'; Exit; end; end; end; if Family = 15 then begin for I := 0 to 5 do begin if Model = PrescottArray[I] then begin Result := 'P4 Prescott'; Exit; end; end; end; end; if Vendor = 'AuthenticAMD' then begin // AMD processor detection if Family = 6 then begin for I := 0 to 5 do begin if Model = XPArray[I] then begin Result := 'Athlon XP'; Exit; end; end; end; if Family = 6 then begin for I := 0 to 5 do begin if Model = AthlonArray[I] then begin Result := 'Athlon'; Exit; end; end; end; if Family = 15 then begin for I := 0 to 5 do begin if Model = Athlon64Array[I] then begin Result := 'Athlon 64'; Exit; end; end; end; if Family = 15 then begin for I := 0 to 5 do begin if Model = OpteronArray[I] then begin Result := 'Opteron'; Exit; end; end; end; end; end; if CPUDetected = False then begin Result := 'Not detected'; Exit; end; end; function GetCPUFrequencyMHz : Cardinal; function RDTSC : Int64; asm rdtsc end; var RDTSCCountStart, RDTSCCountEnd, RDTSCTicks, lpFrequency, lpPerformanceCount, StartCount, EndCount, NoOfTicks : Int64; I1, I2 : Cardinal; J : Int64; Succes : Boolean; RunTimeSec : Double; const NOOFRUNS : Cardinal = 1000; begin Succes := QueryPerformanceFrequency(lpFrequency); if not Succes then raise Exception.Create('QueryPerformanceFrequency failed'); Succes := QueryPerformanceCounter(lpPerformanceCount); if Succes then StartCount := lpPerformanceCount else raise Exception.Create('QueryPerformanceCounter failed'); RDTSCCountStart := RDTSC; //Do something for a while J := 0; for I1 := 0 to NOOFRUNS do begin for I2 := 0 to NOOFRUNS do begin J := J + 1; end; end; RDTSCCountEnd := RDTSC; Succes := QueryPerformanceCounter(lpPerformanceCount); if Succes then EndCount := lpPerformanceCount else raise Exception.Create('QueryPerformanceCounter failed'); NoOfTicks := EndCount - StartCount; if NoOfTicks < 0 then raise Exception.Create('Performance counter wrapped around'); RunTimeSec := NoOfTicks / lpFrequency; RDTSCTicks := RDTSCCountEnd - RDTSCCountStart; if RDTSCTicks < 0 then raise Exception.Create('Time stamp counter counter wrapped around'); Result := Round(RDTSCTicks / RunTimeSec / 1000000); end; end.
{****************************************************************} {* *} {* Unit Name: TeeFunnel *} {* Purpose : The Funnel or Pipeline Series *} {* Author : Marjan Slatinek, marjan@steema.com *} {* History : v1.0 (Requires TeeChart v5 or later) *} {* : v1.5 (Ported to 7.0 and .NET by David Berneda) *} {* *} {****************************************************************} unit TeeFunnel; {$I TeeDefs.inc} interface Uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} {$IFDEF CLX} QGraphics, Types, {$ELSE} Graphics, {$ENDIF} Classes, SysUtils, TeEngine, Chart, TeCanvas; type TFunnelSeries = class(TChartSeries) private FAboveColor : TColor; FAutoUpdate : Boolean; FBelowColor : TColor; FDifferenceLimit: Double; FLinesPen : TChartPen; FOpportunityValues: TChartValueList; FQuotesSorted : Boolean; FWithinColor : TColor; { internal } IPolyPoints : Array of TPoint; ISorted : Boolean; IMin : Double; IMax : Double; ISlope : Double; IDiff : Double; BoundingPoints: Array[0..3] of TPoint; function DefineFunnelRegion(ValueIndex: Integer): TColor; function GetQuoteValues: TChartValueList; virtual; procedure SetAboveColor(const Value: TColor); procedure SetAutoUpdate(const Value: boolean); procedure SetBelowColor(const Value: TColor); procedure SetDifferenceLimit(const Value: double); procedure SetLinesPen(const Value: TChartPen); procedure SetOpportunityValues(const Value: TChartValueList); procedure SetQuotesSorted(const Value: boolean); procedure SetQuoteValues(const Value: TChartValueList); virtual; procedure SetWithinColor(const Value: TColor); protected procedure AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False);override; procedure DoBeforeDrawChart; override; procedure DrawAllValues; override; Procedure DrawMark( ValueIndex:Integer; Const St:String; APosition:TSeriesMarkPosition); override; procedure DrawValue(ValueIndex: Integer);override; class Function GetEditorClass:String; override; procedure GetMarkText(Sender: TChartSeries; ValueIndex: Integer; var MarkText: String); public Constructor Create(AOwner: TComponent); override; Destructor Destroy; override; function AddSegment(Const AQuote, AOpportunity: Double; Const ALabel: String; AColor: TColor): Integer; function Clicked(X,Y:Integer):Integer; override; Function CountLegendItems:Integer; override; Function LegendItemColor(LegendIndex:Integer):TColor; override; Function LegendString( LegendIndex:Integer; LegendTextStyle:TLegendTextStyle ):String; override; Function MaxXValue:Double; override; Function MinXValue:Double; override; Function MinYValue:Double; override; procedure Recalc; published property Brush; property Pen; property AboveColor: TColor read FAboveColor write SetAboveColor default clGreen; property AutoUpdate: boolean read FAutoUpdate write SetAutoUpdate default true; property BelowColor : TColor read FBelowColor write SetBelowColor default clRed; property DifferenceLimit : double read FDifferenceLimit write SetDifferenceLimit; property LinesPen:TChartPen read FLinesPen write SetLinesPen; property OpportunityValues: TChartValueList read FOpportunityValues write SetOpportunityValues; property QuotesSorted : boolean read FQuotesSorted write SetQuotesSorted default false; property QuoteValues: TChartValueList read GetQuoteValues write SetQuoteValues; property WithinColor : TColor read FWithinColor write SetWithinColor default clYellow; end; implementation {$IFDEF CLR} {$R 'TFunnelSeries.bmp'} {$ELSE} {$R TeeFunne.res} {$ENDIF} Uses {$IFDEF D6} {$IFNDEF CLX} Types, {$ENDIF} {$ENDIF} TeeProcs, TeeProCo, TeeConst; { TFunnelSeries } Constructor TFunnelSeries.Create(AOwner: TComponent); begin inherited; FOpportunityValues := TChartValueList.Create(Self,TeeMsg_OpportunityValues); Self.XValues.Name := ''; Self.XValues.Order := loNone; PercentFormat:=TeeMsg_FunnelPercent; FOpportunityValues.Order := loNone; Self.QuoteValues.Order := loDescending; Self.YValues.Name := TeeMsg_QuoteValues; FAutoUpdate := true; FQuotesSorted := false; ISorted := false; FDifferenceLimit := 30.0; FAboveColor := clGreen; FWithinColor := clYellow; FBelowColor := clRed; OnGetMarkText := GetMarkText; FLinesPen:=CreateChartPen; IUseSeriesColor:=False; end; Destructor TFunnelSeries.Destroy; begin FLinesPen.Free; IPolyPoints:=nil; inherited; end; function TFunnelSeries.AddSegment(const AQuote, AOpportunity: Double; const ALabel: String; AColor: TColor): Integer; begin FOpportunityValues.TempValue := AOpportunity; Result := Add(AQuote,ALabel,AColor); if Not FQuotesSorted then begin YValues.Sort; XVAlues.FillSequence; ISorted := true; end; end; function TFunnelSeries.GetQuoteValues: TChartValueList; begin Result := MandatoryValueList; end; procedure TFunnelSeries.Recalc; begin if not ISorted then begin QuoteValues.Sort; XValues.FillSequence; ISorted := true; end; if Count>0 then begin IMax := QuoteValues.First; IMin := QuoteValues.Last; ISlope := 0.5*(IMax-IMin) / Count; end; end; procedure TFunnelSeries.SetAutoUpdate(const Value: boolean); begin FAutoUpdate := Value; if FAutoUpdate then Recalc; end; procedure TFunnelSeries.SetQuoteValues(const Value: TChartValueList); begin SetYValues(Value); { overrides the default YValues } end; procedure TFunnelSeries.SetQuotesSorted(const Value: boolean); begin FQuotesSorted := Value; ISorted := FQuotesSorted; end; procedure TFunnelSeries.SetOpportunityValues(const Value: TChartValueList); begin SetChartValueList(FOpportunityValues,Value); { standard method } end; procedure TFunnelSeries.DrawValue(ValueIndex: Integer); begin With ParentChart.Canvas do begin AssignBrush(Self.Brush,DefineFunnelRegion(ValueIndex)); if ParentChart.View3D then PolygonWithZ(IPolyPoints,StartZ) else Polygon(IPolyPoints); end end; procedure TFunnelSeries.DrawAllValues; procedure DrawVertLine(ValueIndex: Integer); var tmpX : Integer; begin tmpX:=CalcXPosValue(ValueIndex + 0.5); With ParentChart.Canvas do if ParentChart.View3D then VertLine3D(tmpX,CalcYPosValue(IMax - ISlope*(ValueIndex+1)), CalcYPosValue(ISlope*(ValueIndex+1)),StartZ) else DoVertLine(tmpX,CalcYPosValue(IMax - ISlope*(ValueIndex+1)), CalcYPosValue(ISlope*(ValueIndex+1))); end; var t : Integer; begin inherited; With ParentChart.Canvas do begin AssignVisiblePen(Self.Pen); Brush.Style := bsClear; BoundingPoints[0] := TeePoint(CalcXPosValue(-0.5),CalcYPosValue(IMax)); BoundingPoints[1] := TeePoint(CalcXPosValue(Count-0.5), CalcYPosValue((IMax+IMin)*0.5)); BoundingPoints[2] := TeePoint(BoundingPoints[1].x, CalcYPosValue((IMax-IMin)*0.5)); BoundingPoints[3] := TeePoint(BoundingPoints[0].x, CalcYPosValue(0.0)); if ParentChart.View3D then PolygonWithZ(BoundingPoints,StartZ) else Polygon(BoundingPoints); if Self.LinesPen.Visible then begin AssignVisiblePen(Self.LinesPen); for t:=FirstValueIndex to LastValueIndex-1 do DrawVertLine(t); end; end; end; function TFunnelSeries.MinYValue: Double; begin Result := 0; end; function TFunnelSeries.MaxXValue: Double; begin Result := Count -0.5; end; function TFunnelSeries.MinXValue: Double; begin Result := -0.5; end; procedure TFunnelSeries.SetDifferenceLimit(const Value: double); begin if FDifferenceLimit<>Value then begin FDifferenceLimit := Value; if FAutoUpdate then Recalc; Repaint; end; end; procedure TFunnelSeries.SetAboveColor(const Value: TColor); begin SetColorProperty(FAboveColor,Value); end; procedure TFunnelSeries.SetBelowColor(const Value: TColor); begin SetColorProperty(FBelowColor,Value); end; procedure TFunnelSeries.SetWithinColor(const Value: TColor); begin SetColorProperty(FWithinColor,Value); end; procedure TFunnelSeries.GetMarkText(Sender: TChartSeries; ValueIndex: Integer; var MarkText: String); begin MarkText := FormatFloat(PercentFormat, 100*FOpportunityValues.Value[ValueIndex]/QuoteValues.Value[ValueIndex]); end; procedure TFunnelSeries.DrawMark(ValueIndex: Integer; const St: String; APosition: TSeriesMarkPosition); begin APosition.LeftTop := TeePoint(CalcXPosValue(ValueIndex)-APosition.Width div 2, CalcYPosValue(IMax*0.5)-APosition.Height div 2); inherited; end; function TFunnelSeries.DefineFunnelRegion(ValueIndex: Integer): TColor; var tmpX, tmpY : Integer; begin { Calculate multiplying factor } if QuoteValues.Value[ValueIndex]=0 then IDiff:=0 else IDiff := FOpportunityValues.Value[ValueIndex]/QuoteValues.Value[ValueIndex]; { calculate bouding rectangle } BoundingPoints[0] := TeePoint(CalcXPosValue(ValueIndex-0.5),CalcYPosValue(IMax - ISlope*ValueIndex)); BoundingPoints[1] := TeePoint(CalcXPosValue(ValueIndex+0.5),CalcYPosValue(IMax - ISlope*(ValueIndex+1))); BoundingPoints[2] := TeePoint(BoundingPoints[1].x,CalcYPosValue(ISlope*(ValueIndex+1))); BoundingPoints[3] := TeePoint(BoundingPoints[0].x,CalcYPosValue(ISlope*ValueIndex)); tmpY := CalcYPosValue((IMax - 2*ISlope*ValueIndex)*IDiff+ISlope*ValueIndex); { Actual value, expressed in axis scale } if tmpY <= BoundingPoints[0].Y then { IDiff >= 1 } begin SetLength(IPolyPoints,4); IPolyPoints[0] := BoundingPoints[0]; IPolyPoints[1] := BoundingPoints[1]; IPolyPoints[2] := BoundingPoints[2]; IPolyPoints[3] := BoundingPoints[3]; end else if (tmpY > BoundingPoints[0].Y) and (tmpY <= BoundingPoints[1].Y) then begin SetLength(IPolyPoints,5); IPolyPoints[0] := TeePoint(BoundingPoints[0].x,tmpY); tmpX := CalcXPosValue((IMax - 2*ISlope*ValueIndex)*(1-IDiff)/ISlope + ValueIndex - 0.5); IPolyPoints[1] := TeePoint(tmpX,tmpY); IPolyPoints[2] := BoundingPoints[1]; IPolyPoints[3] := BoundingPoints[2]; IPolyPoints[4] := BoundingPoints[3]; end else if tmpY > BoundingPoints[2].y then begin SetLength(IPolyPoints,3); IPolyPoints[0] := TeePoint(BoundingPoints[0].x,tmpY); tmpX := CalcXPosValue((IMax - 2*ISlope*ValueIndex)*IDiff /ISlope + ValueIndex-0.5); IPolyPoints[1] := TeePoint(tmpX,tmpY); IPolyPoints[2] := BoundingPoints[3]; end else begin SetLength(IPolyPoints,4); IPolyPoints[0] := TeePoint(BoundingPoints[0].x, tmpY); IPolyPoints[1] := TeePoint(BoundingPoints[1].x, tmpY); IPolyPoints[2] := BoundingPoints[2]; IPolyPoints[3] := BoundingPoints[3]; end; if IDiff >= 1 then Result := FAboveColor else if (1-IDiff)*100 > FDifferenceLimit then Result := FBelowColor else Result := FWithinColor; end; function TFunnelSeries.Clicked(X, Y: Integer): Integer; var t : Integer; begin Result := inherited Clicked(X,Y); if (result=-1) and (FirstValueIndex>-1) and (LastValueIndex>-1) then for t := FirstValueIndex to LastValueIndex do begin DefineFunnelRegion(t); if PointInPolygon(TeePoint(X,Y),IPolyPoints) then begin Result := t; break; end end; end; procedure TFunnelSeries.AddSampleValues(NumValues: Integer; OnlyMandatory:Boolean=False); var t: Integer; begin for t := 0 to NumValues - 1 do AddSegment(2.3*NumValues*(t+1),(2.3-RandomValue(2))*NumValues*(t+2), TeeMsg_FunnelSegment+TeeStr(t+1),clTeeColor); Recalc; end; procedure TFunnelSeries.DoBeforeDrawChart; begin inherited; if Visible and Assigned(GetVertAxis) then GetVertAxis.Visible:=False; end; function TFunnelSeries.CountLegendItems: Integer; begin result:=3; end; function TFunnelSeries.LegendItemColor(LegendIndex: Integer): TColor; begin Case LegendIndex of 0: result:=AboveColor; 1: result:=WithinColor; else result:=BelowColor; end; end; function TFunnelSeries.LegendString(LegendIndex: Integer; LegendTextStyle: TLegendTextStyle): String; begin Case LegendIndex of 0: result:=TeeMsg_FunnelExceed; 1: result:=FormatFloat(PercentFormat,DifferenceLimit)+ TeeMsg_FunnelWithin; else result:=FormatFloat(PercentFormat,DifferenceLimit)+ TeeMsg_FunnelBelow; end; end; class function TFunnelSeries.GetEditorClass: String; begin result:='TFunnelSeriesEditor'; end; procedure TFunnelSeries.SetLinesPen(const Value: TChartPen); begin FLinesPen.Assign(Value); end; initialization RegisterTeeSeries(TFunnelSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_FunnelSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryStats,1); finalization UnRegisterTeeSeries([TFunnelSeries]); end.
unit SIP_Call; interface uses SIP_Script, Classes, SIP_App ,SIP_Action, SIP_RingList, SysUtils, SyncObjs, SIP_Env, pjsua, DTMF, Log4D, SIP_Event; type TStatusKind=(skBusy,skBusyRoute,skNoAnswer,skNoDTMF,skNotFound,skError,skSuccess,skFailDTMF,skFailAnnounce); TDTMFState=(dNone,dNotDetected,dDetectedDigit,dDetectedAll,dNotExpected,dHangedup,dRetry); TSIPCall=class(TThread) private CurrentScript:TSIPScript; CurrentAction:Integer; CurrentMessage:String; CurrentMessageName:String; CurrentStartID:Integer; ReceiveCnt,SendCnt:Integer; ConversationLock:TEvent; Stop:Boolean; CurrentAddress:TSIPAddress; EnvLock:TCriticalSection; QueueID:Cardinal; DTMFFail:Boolean; DTMF_Decoder:TDTMF; DTMFDetectStr:String; CurrentEnv:ISIPEnv; CurrentEvent:TSIPEvent; Stack:TStringList; FHangupTimeOut:Int64; FIsHangupTimeOut:Boolean; FHangup:Boolean; procedure DoAction(Action: TSIPAction); procedure Ring(Action: TSIPAction); procedure SMS(Action: TSIPAction); procedure Mail(Action: TSIPAction); procedure Delay(Milliseconds:Cardinal); procedure Play(FileName:String;Last:Boolean;Action: TSIPAction); procedure DTMF; procedure Jump(ScriptID:Integer); procedure Call(ScriptID:Integer); procedure Hangup; procedure AddToSIPThread; procedure NextAction; procedure LastAction; procedure Status(const S:String);inline; procedure StatusAddress(const S:String);inline; procedure NextScript; procedure AddReport(Info:String); procedure EventReport(Info:String); procedure AddSamples(Buffer: pointer; Size: Integer); function StatusKind(Status: Integer): TStatusKind; procedure RingTimeout; protected FID:Integer; FSIPApp:TSIPApp; FReport:String; FLastScript:Integer; FLastScriptDescription:String; FLastPhone:String; FLastPlayAction:TSIPAction; FDTMFWaitCount,FDTMFFrameCount:Integer; ExpectedDigits,DetectedDigits:String; DTMFState:TDTMFState; FChannelLog:TLogLogger; FAccount:Integer; procedure Execute;override; public Phone:String; PhoneKind:String; CallID:Integer; DTMF_Port:pjmedia_port; procedure InitDTMF; constructor Create(App:TSIPApp;ID:Integer); destructor Destroy;override; procedure Signal; procedure SignalFailure; procedure StartSIP; procedure Retry(Status:Integer;Description:String=''); function DTMFFrame:boolean; procedure DTMFDetect; procedure DTMFTimeout; procedure LogError(S:String;const Err: Exception = nil); procedure LogInfo(S:String); procedure LogDebug(S:String); procedure StopEvent(EventID:Integer); procedure StopCurrent; procedure Received(Buffer:Pointer;Size:Integer); procedure Sent(Buffer:Pointer;Size:Integer); property InHangup:boolean read FHangup write FHangup; property ChannelIndex:Integer read FID; end; const DefRetry=0; const DefDelay=15; type EventArray=array of Integer; var SIPBUSY,SIPBUSYROUTE,SIPNOANSWER,SIPNOTFOUND:EventArray; procedure InitArray(S:String;out A:EventArray); implementation uses SIP_Thread,Logger,dm_Alarm, Windows, SIP_Sound, StrUtils, SIP_Monitor,SIP_QueueManager; procedure InitArray(S:String;out A:EventArray); var L:TStrings; I: Integer; begin L:=TStringList.Create; try L.CommaText:=S; SetLength(A,L.Count); for I := 0 to L.Count - 1 do A[I]:=StrToIntDef(L[I],0); finally L.Free; end; end; function InArray(E:Integer;A:EventArray):Boolean; var I: Integer; begin Result:=False; for I := 0 to Length(A)-1 do if A[I]=E then begin Result:=True; Break; end; end; { TSIPCall } procedure TSIPCall.AddToSIPThread; begin ConversationLock.ResetEvent; dmAlarm.SIPThread.AddCall(Self); while True do case ConversationLock.WaitFor(1000) of wrSignaled: begin FHangupTimeOut:=0; FIsHangupTimeOut:=False; Break; end; wrAbandoned: begin LogError(Format('Conversation event abandoned CallID: %d, Phone: %s',[CallID,Phone])); Terminate; Break; end; wrTimeout: begin if Terminated then Break; if (FHangupTimeOut>0) and (GetTick64>FHangupTimeOut) then begin FHangupTimeOut:=0; FIsHangupTimeOut:=True; dmAlarm.SIPThread.AddCall(Self); end else if InHangup then dmAlarm.SIPThread.AddCall(Self); end; wrError: begin LogError(Format('Conversation event error: %d, CallID: %d, Phone: %s',[ConversationLock.LastError,CallID,Phone])); Terminate; Break; end; end; end; procedure TSIPCall.Call; begin if CurrentScript<>nil then Stack.AddObject(IntToStr(CurrentScript.ScriptID),TObject(CurrentAction)); AddReport('Извикване на сценарий '+IntToStr(ScriptID)); Jump(ScriptID); end; function get_frame(port: ppjmedia_port;frame:ppjmedia_frame):integer;cdecl; begin Result:=0; end; function put_frame(port: ppjmedia_port;frame:ppjmedia_frame):integer;cdecl; var O:TObject; begin Result:=0; if frame.frame_type<>1 then Exit; O:=TObject(port.port_data_p); if O is TSIPCall then TSIPCall(O).AddSamples(frame.buffer,frame.size); end; function on_destroy(port: ppjmedia_port):integer;cdecl; begin Result:=0; end; procedure TSIPCall.AddSamples(Buffer: pointer; Size: Integer); var I:Integer; C:Char; ID:Integer; Port:Integer; begin ID:=CallID; if (ID>=0) and DTMFFrame then begin Exit; end; Size:=Size div 2; // Size is in bytes for I := 0 to Size - 1 do begin C:=DTMF_Decoder.AddSample(PSmallIntArray(Buffer)[I]); if C<>#0 then begin DetectedDigits:=RightStr(DetectedDigits+C,15); DTMFState:=dDetectedDigit; if (RightStr(DetectedDigits,Length(ExpectedDigits))=ExpectedDigits) then begin Port:=pjsua_call_get_conf_port(ID); if Port>0 then TSIPThread.CheckStatus(pjsua_conf_disconnect(Port,DTMF_Port.port_data_l),'pjsua_conf_disconnect'); LogInfo(Format('[%10.10d] Successfully detected DTMF digits: %s',[ID,ExpectedDigits])); DTMFDetect; Signal; end else LogInfo(Format('[%10.10d] Last 15 detected DTMF digits: %s',[ID,DetectedDigits])); end; end; end; const PCM='pcm'; constructor TSIPCall.Create; begin FID:=ID; AddLoggers(ChangeFileExt(ParamStr(0),'Channel.ini'),FID); FChannelLog:=DefaultHierarchy.GetLogger('Channel'+IntToStr(FID)); FChannelLog.Info('#####################################################'); FChannelLog.Info('Starting channel '+IntToStr(FID)); FSIPApp:=App; DTMF_Port.port_data_l:=-1; ConversationLock:=TEvent.Create; Stop:=False; InHangup:=False; EnvLock:=TCriticalSection.Create; Stack:=TStringList.Create; FreeOnTerminate:=False; inherited Create(False); CallID:=-1; DTMFState:=dNone; Status('инициализиран'); DTMFDetectStr:='dtmfdetect('+IntToStr(ID)+')'; DTMF_Decoder:=TDTMF.Create(SIP_CLOCK_RATE); DTMF_Port.info.name.s:=@DTMFDetectStr[1]; DTMF_Port.info.name.sz:=Length(DTMFDetectStr); DTMF_Port.info.signature:='dtmf'; DTMF_Port.info.mediatype:=1; DTMF_Port.info.has_info:=1; DTMF_Port.info.need_info:=0; DTMF_Port.info.payload_type:=255; DTMF_Port.info.encoding_name.s:=@PCM[1]; DTMF_Port.info.encoding_name.sz:=Length(PCM); DTMF_Port.info.clock_rate:=SIP_CLOCK_RATE; DTMF_Port.info.channel_count:=1; DTMF_Port.info.bits_per_sample:=16; DTMF_Port.info.samples_per_frame:=SIP_DTMF_FRAME; DTMF_Port.info.bytes_per_frame:=DTMF_Port.info.samples_per_frame*2; DTMF_Port.port_data_p:=self; DTMF_Port.get_frame:=get_frame; DTMF_Port.put_frame:=put_frame; DTMF_Port.on_destroy:=on_destroy; end; procedure TSIPCall.Delay; begin if Milliseconds>0 then Sleep(Milliseconds); end; destructor TSIPCall.Destroy; begin Status('унищожен'); DTMF_Port.port_data_p:=nil; if DTMF_Port.port_data_l>=0 then TSIPThread.CheckStatus(pjmedia_port_destroy(@DTMF_Port),'pjmedia_port_destroy'); // TSIPThread.CheckStatus(pjsua_conf_remove_port(DTMF_Port.port_data_l),'pjsua_conf_remove_port'); FreeAndNil(Stack); FreeAndNil(ConversationLock); FreeAndNil(DTMF_Decoder); FChannelLog.Info('Stopping channel '+IntToStr(FID)); FChannelLog.Info('#####################################################'); inherited; FreeAndNil(EnvLock); end; procedure TSIPCall.DoAction(Action:TSIPAction); begin if Stop then begin Hangup; LastAction; Exit; end; if (Action=nil) or (InHangup) then begin Hangup; Exit; end; Status(Action.Action); //Log.Debug(Action.Action); case Action.OpCode of OP_RING:Ring(Action); OP_DELAY: Delay(StrToIntDef(Action.Operand[1],0)); OP_PLAY: Play(Action.Operand[1],Action=FLastPlayAction,Action); OP_DTMF: DTMF; OP_JUMP: Jump(StrToIntDef(Action.Operand[1],0)); OP_CALL: Call(StrToIntDef(Action.Operand[1],0)); OP_HANGUP: Hangup; OP_SMS: SMS(Action); OP_Mail: Mail(Action); end; if not (Action.OpCode in [OP_CALL,OP_JUMP,OP_RING,OP_Play,OP_HANGUP,OP_DTMF]) then NextAction; end; procedure TSIPCall.DTMF; begin if CallID<0 then NextAction else AddToSIPThread; end; procedure TSIPCall.DTMFDetect; begin FHangupTimeOut:=0; FIsHangupTimeOut:=False; DTMFState:=dDetectedAll; AddReport('DTMF успешно разпознаване'); end; function TSIPCall.DTMFFrame:boolean; begin Inc(FDTMFFrameCount); Result:= FDTMFFrameCount>FDTMFWaitCount ; end; procedure TSIPCall.DTMFTimeout; var Port:Integer; begin FIsHangupTimeOut:=False; FHangupTimeOut:=0; if (CallID>=0) and (DTMF_Port.port_data_l>=0) then begin Port:=pjsua_call_get_conf_port(CallID); if Port>0 then TSIPThread.CheckStatus(pjsua_conf_disconnect(Port,DTMF_Port.port_data_l),'pjsua_conf_disconnect'); end; LogInfo(Format('[%10.10d] DTMF timeout',[CallID])); AddReport('Таймаут при изчакване на DTMF'); if DTMFFail then SignalFailure else Signal; end; procedure TSIPCall.RingTimeout; begin FIsHangupTimeOut:=False; FHangupTimeOut:=0; LogInfo(Format('[%10.10d] Ring timeout',[CallID])); AddReport('Таймаут при позвъняване'); TSIPThread.Hangup(Self); end; procedure TSIPCall.EventReport(Info: String); begin if CurrentEvent<>nil then CurrentEvent.AddReport(FormatDateTime('yyyy-mm-dd hh:nn:ss ',Now)+Info+#13#10,''); end; procedure TSIPCall.Execute; begin try while not Terminated do begin if ((CurrentScript=nil) and (CallID<0)) or ((CurrentScript<>nil) and (CurrentScript.Count<=0)) then NextScript else if (CurrentScript=nil) then DoAction(nil) else if CurrentAction<CurrentScript.Count then DoAction(CurrentScript.Action[CurrentAction]) end; Status('Затворен'); except on E:Exception do begin LogError(E.Message,E); Status(E.Message); StatusAddress(E.Message); end; end; end; procedure TSIPCall.Hangup; begin if CallID<0 then begin if (dtmfState<>dRetry) and (CurrentMessage<>'') and (CurrentAddress<>nil) and (CurrentAddress.RingSequence<>'') then begin if CurrentAddress.RingSequence[1]='s' then begin Delete(CurrentAddress.RingSequence,1,1); Status('Генериране на SMS за '+CurrentAddress.MobilePhone); StatusAddress('генериране на SMS'); AddReport('Генериране на SMS за '+CurrentAddress.MobilePhone); FSIPApp.SMSQueue.Add(CurrentMessageName,CurrentAddress.MobilePhone,CurrentMessage,CurrentAddress,QueueID); end else if CurrentAddress.RingSequence[1]='m' then begin Delete(CurrentAddress.RingSequence,1,1); Status('Генериране на EMail за '+CurrentAddress.EMail); StatusAddress('генериране на EMail'); AddReport('Генериране на EMail за '+CurrentAddress.EMail); FSIPApp.MailQueue.Add(CurrentMessageName,CurrentAddress.EMail,CurrentMessage,CurrentEnv.SIPSettings.Values['SMTPSubject'],CurrentAddress,QueueID); end; end; NextAction; end else AddToSIPThread; end; procedure TSIPCall.InitDTMF; begin if (CurrentScript<>nil) and CurrentScript.IsDTMF then DTMFState:=dNotDetected else DTMFState:=dHangedup; end; procedure TSIPCall.Jump(ScriptID: Integer); begin if ScriptID<=0 then CurrentScript:=nil else begin CurrentScript:=CurrentEnv.SIPLibrary.Script[ScriptID]; if (CurrentScript<>nil) and (CurrentScript.Count>0) then begin Status('Изпълнение на '+CurrentScript.Description); FLastScript:=ScriptID; FLastScriptDescription:=CurrentScript.Description; AddReport('Канал '+IntToStr(FID)+' - изпълнение на сценарий '+CurrentScript.Description); end else CurrentScript:=nil; end; CurrentAction:=0; end; procedure TSIPCall.LastAction; begin CurrentAction:=0; CurrentScript:=nil; end; procedure TSIPCall.LogDebug(S: String); begin S:=Format('{%2.2d} %s',[FID,S]); if Log<>nil then Log.Debug(S); FChannelLog.Debug(S); end; procedure TSIPCall.LogError(S: String;const Err: Exception); begin S:=Format('{%2.2d} %s',[FID,S]); if Log<>nil then Log.Error(S,Err); FChannelLog.Error(S,Err); end; procedure TSIPCall.LogInfo(S: String); begin S:=Format('{%2.2d} %s',[FID,S]); if Log<>nil then Log.Info(S); FChannelLog.Info(S); end; procedure TSIPCall.Mail(Action: TSIPAction); var Announcement:TSIPAnnouncement; EMail:String; begin Announcement:=CurrentEnv.SIPSound.Buffer[StrToIntDef(Action.Operand[1],0)]; if (Announcement.Text<>'') and (CurrentAddress<>nil) and (CurrentAddress.TryCount=1) then begin EMail:=''; if SameText(Action.Operand[2],'group') then EMail:=CurrentAddress.EMail else if SameText(Action.Operand[2],'person') then begin EMail:=CurrentEnv.SIPMail.Values[Action.Operand[3]]; end; if EMail<>'' then begin Status('Генериране на EMail('+Announcement.Name+') за '+EMail); StatusAddress('генериране на EMail'); AddReport('Генериране на EMail('+Announcement.Name+') за '+EMail); FSIPApp.MailQueue.Add(Announcement.Name,EMail,Announcement.Text,CurrentEnv.SIPSettings.Values['SMTPSubject'],CurrentAddress,QueueID); end; end; end; procedure TSIPCall.NextAction; begin CurrentAction:=CurrentAction+1; if (CurrentScript<>nil) and (CurrentAction>=CurrentScript.Count) then begin if Stack.Count>0 then begin if FLastScript>0 then AddReport('Край на изпълнение на сценарий '+FLastScriptDescription); CurrentScript:=CurrentEnv.SIPLibrary.Script[StrToIntDef(Stack[Stack.Count-1],0)]; if CurrentScript<>nil then begin FLastScript:=CurrentScript.ScriptID; FLastScriptDescription:=CurrentScript.Description; end else begin FLastScript:=0; FLastScriptDescription:=''; end; CurrentAction:=Integer(Stack.Objects[Stack.Count-1]); Stack.Delete(Stack.Count-1); NextAction; end else begin CurrentAction:=0; CurrentScript:=nil end; end; end; procedure TSIPCall.NextScript; var ScriptID:Integer; Event:TSIPEvent; StartID:Integer; MinDelay,MaxDelay:Integer; begin Status(''); if FLastScript>0 then begin AddReport('Край на изпълнение на сценарий '+FLastScriptDescription+#13#10); FLastScript:=0; FLastScriptDescription:=''; if not (DTMFState in [dRetry,dNotExpected,dDetectedAll]) and (CurrentAddress<>nil) then FSIPApp.SIPQueueManager.Fail(CurrentAddress,QueueID,pkSIP); end; if (CurrentEvent<>nil) and (FReport<>'') then CurrentEvent.AddReport(FReport,''); CurrentEnv:=nil; FReport:=''; EnvLock.Enter; try Stop:=False; InHangup:=False; CurrentEvent:=nil; CurrentStartID:=0; finally EnvLock.Leave; end; FSIPApp.SIPQueueManager.Next(ScriptID,CurrentAddress,QueueID,CurrentEnv,Event,StartID); if CurrentEnv<>nil then begin MinDelay:=StrToIntDef(CurrentEnv.SIPSettings.Values['ScriptMinDelay'],0); MaxDelay:=StrToIntDef(CurrentEnv.SIPSettings.Values['ScriptMaxDelay'],0); if (MinDelay>=0) then begin if MinDelay>10000 then MinDelay:=10000; if MaxDelay>10000 then MaxDelay:=10000; if MaxDelay<MinDelay then MaxDelay:=MinDelay; Sleep(MinDelay+Random(MaxDelay-MinDelay+1)); end; end; EnvLock.Enter; try CurrentEvent:=Event; CurrentStartID:=StartID; finally EnvLock.Leave; end; if ScriptID<0 then Terminate else begin Jump(ScriptID); if CurrentAddress<>nil then begin AddReport(Format('Опит: %d, обект: %s',[CurrentAddress.TryCount,CurrentAddress.ObjectName])); //if CurrentScript<>nil then // CurrentAddress.Data:=CurrentScript.Description end; DTMFState:=dNone; if CurrentScript<>nil then FLastPlayAction:=CurrentScript.LastPlayAction else FLastPlayAction:=nil end; end; procedure TSIPCall.Play; var Announcement:TSIPAnnouncement; begin if CallID<0 then begin Announcement:=CurrentEnv.SIPSound.Buffer[StrToIntDef(Action.Operand[1],0)]; if (Announcement<>nil) and (Announcement.Text<>'') then begin CurrentMessage:=CurrentMessage+' '+Announcement.Text; CurrentMessageName:=CurrentMessageName+' '+Announcement.Name; end; NextAction; end else begin try AddToSIPThread; finally if (CallID>=0) and Last and (DTMFState=dHangedup) then DTMFState:=dNotExpected end; end; end; procedure TSIPCall.AddReport(Info: String); begin if CurrentAddress<>nil then CurrentAddress.AddReport(StringOfChar(' ',Stack.Count*2)+Info) else begin if FReport<>'' then FReport:=FReport+#13#10; FReport:=FReport+FormatDateTime('yyyy-mm-dd hh:nn:ss ',Now)+StringOfChar(' ',Stack.Count*2)+Info; end; end; function TSIPCall.StatusKind(Status:Integer):TStatusKind; begin case dtmfstate of dDetectedAll,dNotExpected: Result:=skSuccess; dDetectedDigit: Result:= skFailDTMF; dHangedup : Result:= skFailAnnounce; dNotDetected: Result:=skNoDTMF; else if InArray(Status,SIPBUSY) then Result:=skBusy else if InArray(Status,SIPBUSYROUTE) then Result:=skBusyRoute else if InArray(Status,SIPNOANSWER) then Result:=skNoAnswer else if InArray(Status,SIPNOTFOUND) then Result:=skNotFound else Result:=skError; end; end; procedure TSIPCall.StopCurrent; begin EnvLock.Enter; try Stop:=True; dmAlarm.SIPThread.AddCall(Self); finally EnvLock.Leave; end; end; procedure TSIPCall.StopEvent(EventID: Integer); begin EnvLock.Enter; try if (CurrentStartID=EventID) then Stop:=True; dmAlarm.SIPThread.AddCall(Self); finally EnvLock.Leave; end; end; procedure TSIPCall.Received(Buffer: Pointer; Size: Integer); var Old:Integer; begin Old:=ReceiveCnt div 10000; ReceiveCnt:=ReceiveCnt+Size; if Old<>(ReceiveCnt div 10000) then LogDebug('Bytes received: '+IntToStr(ReceiveCnt)); end; procedure TSIPCall.Sent(Buffer: Pointer; Size: Integer); var Old:Integer; begin Old:=SendCnt div 10000; SendCnt:=SendCnt+Size; if Old<>(SendCnt div 10000) then LogDebug('Bytes sent: '+IntToStr(SendCnt)); end; procedure TSIPCall.Retry; var RetrySequence:Boolean; I:Integer; SK:TStatusKind; begin if (QueueID>0) and (CurrentAddress<>nil) then begin RetrySequence:=False; SK:=StatusKind(Status); case SK of skBusy:begin CurrentAddress.Status:='заето'; if Description<>'' then CurrentAddress.Status:=CurrentAddress.Status+' ('+Description+')'; AddReport(CurrentAddress.Status); if CurrentAddress.RetryBusy>0 then begin DTMFState:=dRetry; CurrentAddress.RetryBusy:=CurrentAddress.RetryBusy-1; FSIPApp.SIPQueueManager.Retry(CurrentAddress,CurrentAddress.DelayBusy,QueueID); end else RetrySequence:=True; end; skBusyRoute:begin CurrentAddress.Status:='претоварване'; if Description<>'' then CurrentAddress.Status:=CurrentAddress.Status+' ('+Description+')'; AddReport(CurrentAddress.Status); if CurrentAddress.RetryBusyRoute>0 then begin DTMFState:=dRetry; CurrentAddress.RetryBusyRoute:=CurrentAddress.RetryBusyRoute-1; FSIPApp.SIPQueueManager.Retry(CurrentAddress,CurrentAddress.DelayBusyRoute,QueueID); end else RetrySequence:=True; end; skNoAnswer: begin CurrentAddress.Status:='неотговорил'; if Description<>'' then CurrentAddress.Status:=CurrentAddress.Status+' ('+Description+')'; AddReport(CurrentAddress.Status); RetrySequence:=True; end; skNoDTMF:begin CurrentAddress.Status:='липсва DTMF'; if Description<>'' then CurrentAddress.Status:=CurrentAddress.Status+' ('+Description+')'; AddReport(CurrentAddress.Status); RetrySequence:=True; end; skNotFound: begin CurrentAddress.Status:='грешен номер'; if Description<>'' then CurrentAddress.Status:=CurrentAddress.Status+' ('+Description+')'; AddReport(CurrentAddress.Status); for I := Length(CurrentAddress.RingSequence) downto 2 do if CurrentAddress.RingSequence[I]=CurrentAddress.RingSequence[1] then Delete(CurrentAddress.RingSequence,I,1); RetrySequence:=True; end; skSuccess: begin CurrentAddress.Status:=CurrentAddress.Method; if Description<>'' then CurrentAddress.Status:=CurrentAddress.Status+' ('+Description+')'; AddReport('Успешно оповестяване, метод '+CurrentAddress.Status); EventReport('Успешно оповестяване на '+CurrentAddress.ObjectName+ ' по '+CurrentAddress.Status+ '(опит '+IntToStR(CurrentAddress.TryCount)+ ') по сценарий '+FLastScriptDescription); FSIPApp.SIPQueueManager.Succeed(CurrentAddress,QueueID,pkSIP); //CurrentAddress:=nil; end; skFailDTMF: begin CurrentAddress.Status:='грешен DTMF'; if Description<>'' then CurrentAddress.Status:=CurrentAddress.Status+' ('+Description+')'; AddReport(CurrentAddress.Status); if CurrentAddress.RetryFailDTMF>0 then begin DTMFState:=dRetry; CurrentAddress.RetryFailDTMF:=CurrentAddress.RetryFailDTMF-1; FSIPApp.SIPQueueManager.Retry(CurrentAddress,CurrentAddress.DelayFailDTMF,QueueID); end else RetrySequence:=True; end; skFailAnnounce: begin CurrentAddress.Status:='прекъснал'; if Description<>'' then CurrentAddress.Status:=CurrentAddress.Status+' ('+Description+')'; AddReport(CurrentAddress.Status); if CurrentAddress.RetryFailDTMF>0 then begin DTMFState:=dRetry; CurrentAddress.RetryFailDTMF:=CurrentAddress.RetryFailDTMF-1; FSIPApp.SIPQueueManager.Retry(CurrentAddress,CurrentAddress.DelayFailDTMF,QueueID); end else RetrySequence:=True; end else begin CurrentAddress.Status:='грешка SIP '+IntToStr(Status); if Description<>'' then CurrentAddress.Status:=CurrentAddress.Status+' ('+Description+')'; AddReport(CurrentAddress.Status); RetrySequence:=True; end; end; if RetrySequence then begin Delete(CurrentAddress.RingSequence,1,1); if CurrentAddress.RingSequence<>'' then begin DTMFState:=dRetry; FSIPApp.SIPQueueManager.Retry(CurrentAddress,1,QueueID); end else begin AddReport('Неуспешно оповестяване'); EventReport('Неуспешно оповестяване на '+CurrentAddress.ObjectName+ ' по сценарий '+FLastScriptDescription); FSIPApp.SIPQueueManager.Fail(CurrentAddress,QueueID,pkSIP); end; end; end; end; procedure TSIPCall.Ring; var APhone,APhoneKind:String; begin CurrentMessage:=''; CurrentMessageName:=''; APhone:=''; APhoneKind:='тел. номер'; if SameText(Action.Operand[1],'group') then begin if (CurrentAddress.TryCount=1) then begin CurrentAddress.RingSequence:=Action.operand[3]; if CurrentAddress.RingSequence='' then CurrentAddress.RingSequence:='1'; CurrentAddress.RetryBusy:=StrToIntDef(Action.operand[4],DefRetry); CurrentAddress.DelayBusy:=StrToIntDef(Action.operand[5],DefDelay); CurrentAddress.RetryBusyRoute:=StrToIntDef(Action.operand[6],DefRetry); CurrentAddress.DelayBusyRoute:=StrToIntDef(Action.operand[7],DefDelay); CurrentAddress.RetryFailDTMF:=StrToIntDef(Action.operand[8],DefRetry); CurrentAddress.DelayFailDTMF:=StrToIntDef(Action.operand[9],DefDelay); end; APhoneKind:=CurrentAddress.Method; if CurrentAddress.RingSequence<>'' then case CurrentAddress.RingSequence[1] of '1':begin APhone:=CurrentAddress.Phone; end; '2':begin APhone:=CurrentAddress.HomePhone; end; '3':begin APhone:=CurrentAddress.MobilePhone; end; 's':begin NextAction; Exit; end; 'm':begin NextAction; Exit; end; end; end else if SameText(Action.Operand[1],'person') then begin APhone:=CurrentEnv.SIPAddress.Values[Action.Operand[2]]; end; if APhone='' then begin if CurrentAddress.Status='' then CurrentAddress.Status:='липсва '+APhoneKind; AddReport(CurrentAddress.Status); Retry(404,CurrentAddress.Status); LastAction; Exit; end; Phone:='sip:'+APhone; PhoneKind:=APhoneKind; if Pos('@',Phone)<=0 then Phone:=Phone+'@'+CurrentEnv.SIPSettings.Values['SIPHost']; AddToSIPThread; end; procedure TSIPCall.SMS; var Announcement:TSIPAnnouncement; APhone:String; begin Announcement:=CurrentEnv.SIPSound.Buffer[StrToIntDef(Action.Operand[1],0)]; if (Announcement.Text<>'') and (CurrentAddress<>nil) and (CurrentAddress.TryCount=1) then begin APhone:=''; if SameText(Action.Operand[2],'group') then APhone:=CurrentAddress.MobilePhone else if SameText(Action.Operand[2],'person') then begin Aphone:=CurrentEnv.SIPMobile.Values[Action.Operand[3]]; end; if APhone<>'' then begin Status('Генериране на SMS('+Announcement.Name+') за '+APhone); StatusAddress('генериране на SMS'); AddReport('Генериране на SMS('+Announcement.Name+') за '+APhone); FSIPApp.SMSQueue.Add(Announcement.Name,APhone,Announcement.Text,CurrentAddress,QueueID); end; end; end; procedure TSIPCall.Signal; begin NextAction; ConversationLock.SetEvent; end; procedure TSIPCall.SignalFailure; begin LastAction; ConversationLock.SetEvent; end; procedure TSIPCall.StartSIP; var A:TSIPAction; Announcement:TSIPAnnouncement; begin if ConversationLock.WaitFor(0)=wrSignaled then Exit; try if Stop then begin LastAction; if CallID>=0 then dmAlarm.SIPThread.Hangup(Self) else ConversationLock.SetEvent; end; if (CurrentScript=nil) and (CallID>=0) then begin AddReport('Прекъсване на връзката с '+FLastPhone); dmAlarm.SIPThread.Hangup(Self); end; if InHangup then begin AddReport(FLastPhone+' прекъсна връзката'); dmAlarm.SIPThread.Hangup(Self); end; if (CurrentScript<>nil) and (CurrentAction>=0) and (CurrentAction<CurrentScript.Count) then begin A:=CurrentScript.Action[CurrentAction]; if A<>nil then case A.OpCode of OP_RING: begin if FIsHangupTimeOut then begin RingTimeOut; end else if CallID>=0 then begin CurrentAction:=Currentaction-1; Status('прекъсване на връзката с '+FLastPhone); StatusAddress('прекъсване на връзката'); AddReport('Прекъсване на връзката с '+FLastPhone); dmAlarm.SIPThread.Hangup(Self); end else begin FLastPhone:=Phone; Status('позвъняване на '+Phone); StatusAddress('позвъняване на '+PhoneKind); AddReport('Позвъняване на '+PhoneKind+' '+Phone); FHangupTimeOut:=GetTick64+StrToIntDef(CurrentEnv.SIPSettings.Values['RingTimeOut'],60)*1000; dmAlarm.SIPThread.MakeCall(Self); end; end; OP_PLAY: begin Status('предаване на съобщение '+A.Operand[1]+' на '+Phone); StatusAddress('предаване на съобщение'); AddReport('Предаване на съобщение '+A.Operand[1]+' на '+Phone); Announcement:=CurrentEnv.SIPSound.Buffer[StrToIntDef(A.Operand[1],0)]; dmAlarm.SIPThread.PlaySound(Self,Announcement) end; OP_HANGUP: begin Status('прекъсване на връзката с '+FLastPhone); StatusAddress('прекъсване на връзката'); AddReport('Прекъсване на връзката с '+FLastPhone); dmAlarm.SIPThread.Hangup(Self); end; OP_DTMF: if FIsHangupTimeOut then begin DTMFTimeOut; end else begin FDTMFFrameCount:=0; DTMFFail:=StrToIntDef(A.Operand[2],0)<>0; FDTMFWaitCount:=StrToIntDef(A.Operand[1],0)*SIP_DTMF_RATE; Status('изчакване на DTMF от '+Phone); StatusAddress('изчакване на DTMF'); AddReport('Изчакване на DTMF от '+Phone); ExpectedDigits:=CurrentAddress.DTMF+'#'; DetectedDigits:=''; FHangupTimeOut:=GetTick64+StrToIntDef(A.Operand[1],0)*1000; dmAlarm.SIPThread.WaitDTMF(Self); end; end; end; except on E:Exception do begin LastAction; ConversationLock.SetEvent; end; end; end; procedure TSIPCall.Status(const S: String); begin if (CurrentScript<>nil) and (CurrentScript.Count>0) and (CurrentEvent<>nil) then begin if FSIPApp.SIPStatus<>nil then FSIPApp.SIPStatus.Status(FID,CurrentEvent.Name,CurrentScript.Description,IntToStr(CurrentAction+1),S); end else begin if FSIPApp.SIPStatus<>nil then FSIPApp.SIPStatus.Status(FID,'','','',S); end; end; procedure TSIPCall.StatusAddress(const S: String); begin if CurrentAddress<>nil then CurrentAddress.Status:=S; end; end.
unit bolt_impl; {$mode delphi} // for now interface uses bolt; // Options represents the options that can be set when opening a database. type TOptions = record // Timeout is the amount of time to wait to obtain a file lock. // When set to zero it will wait indefinitely. This option is only // available on Darwin and Linux. Timeout: cardinal; // Sets the DB.NoGrowSync flag before memory mapping the file. NoGrowSync: boolean; // Do not sync freelist to disk. This improves the database write performance // under normal operation, but requires a full database re-sync during recovery. NoFreelistSync: boolean; // Open database in read-only mode. Uses flock(..., LOCK_SH |LOCK_NB) to // grab a shared lock (UNIX). ReadOnly: boolean; // Sets the DB.MmapFlags flag before memory mapping the file. MmapFlags: integer; // InitialMmapSize is the initial mmap size of the database // in bytes. Read transactions won't block write transaction // if the InitialMmapSize is large enough to hold database mmap // size. (See DB.Begin for more information) // // If <=0, the initial map size is 0. // If initialMmapSize is smaller than the previous database size, // it takes no effect. InitialMmapSize: SizeUint; // PageSize overrides the default OS page size. PageSize: SizeUint; // NoSync sets the initial value of DB.NoSync. Normally this can just be // set directly on the DB itself when returned from Open(), but this option // is useful in APIs which expose Options but not the underlying DB. NoSync: boolean; end; POptions = ^TOptions; function OpenBoltDatabase(const name: string; opts: POptions = nil): bolt.IDB; implementation uses pl, hash, monotime, sysutils, crc64; const Version = 2; // Represents a marker value to indicate that a file is a Bolt DB. Magic = $ED0CDAED; const maxMapSize = int64($FFFFFFFFFFFF); // 256TB // maxAllocSize is the size used when creating array pointers. maxAllocSize = $7FFFFFFF; procedure Error(const msg: string); begin raise Exception.Create(msg); end; const DefaultMaxBatchSize = 1000; DefaultMaxBatchDelay = 10; DefaultAllocSize = 16 * 1024 * 1024; var DefaultOptions: TOptions; // all zeros type TTx = class; TDB = class; TBucket = class; txid = uint64; pgid = uint64; inode = record flags : cardinal; pgid : pgid; key : array of byte; value : array of byte; end; pinode = ^inode; node = class public bucket : TBucket; isLeaf : boolean; unbalanced : boolean; spilled : boolean; key : pbyte; pgid : pgid; parent : node; children : array of node; inodes : array of pinode; end; page = record id : pgid; flags : word; count : word; overflow : cardinal; ptr : PtrUint; end; Ppage = ^page; branchPageElement = record pos : cardinal; ksize : cardinal; pgid : pgid; end; PbranchPageElement = ^branchPageElement; TBranchPageElementArray = array [0..0] of branchPageElement; PBranchPageElementArray = ^TBranchPageElementArray; leafPageElement = record flags : cardinal; pos : cardinal; ksize : cardinal; vsize : cardinal; end; PleafPageElement = ^leafPageElement; bucket = record root : pgid; // page id of the bucket's root-level page sequence : uint64; // monotonically incrementing, used by NextSequence() end; meta = record magic : cardinal; version : cardinal; pageSize : cardinal; flags : cardinal; root : bucket; freelist : pgid; pgid : pgid; txid : txid; checksum : uint64; end; Pmeta = ^meta; TtxPending = class public ids : array of pgid; alloctx : array of txid; // txids allocating the ids lastReleaseBegin : txid; // beginning txid of last matching releaseRange end; TFreelist = class private ids : array of pgid; // all free and available free page ids. allocs : TQQHash; // mapping of txid that allocated a pgid. pending : TQHash; // mapping of soon-to-be free page ids by tx. cache : TQHashSet; // fast lookup of all free and pending page ids. public constructor Create; destructor Destroy; override; end; // Bucket represents a collection of key/value pairs inside the database. TBucket = class(TInterfacedObject, bolt.IBucket) public // bucket part root : pgid; sequence : uint64; // Bucket part tx : TTx; // the associated transaction buckets : TSHash; // subbucket cache page : Ppage; // inline page reference rootNode : node; // materialized node for the root page. nodes : TQHash; // node cache // Sets the threshold for filling nodes when they split. By default, // the bucket will fill to 50% but it can be useful to increase this // amount if you know that your write workloads are mostly append-only. // // This is non-persisted across transactions so it must be set in every Tx. FillPercent : double; protected procedure Dereference; public // interface implementation function Bucket(const name: string): IBucket; // get existing or create new if tx is rw function Cursor: ICursor; // return cursor for enumerating keys with values. subbuckets are omitted function BucketsCursor: ICursor; // return cursor for enumerating names of subbuckets. regular keys are omitted function Put(const kv: TKV; overwrite: boolean): boolean; function Get(const key: TDbValue; out value: TDbValue): boolean; end; TCommitHandler = procedure; TTx = class(TInterfacedObject, ITX) private fWritable : boolean; managed : boolean; fDb : TDB; meta : Pmeta; root : TBucket; pages : TQPtrHash; //map[pgid]*page stats : TtxStats; commitHandlers : array of TCommitHandler; public WriteFlag : integer; public // interface methods function DB: IDB; function DbSize: SizeUint; function ID: txid; function Writable: boolean; function Bucket(const name: string; createIfNotExists: boolean): IBucket; procedure DeleteBucket(const name: string); function Cursor: ICursor; // return cursor for enumerating names of DB root buckets procedure Commit; procedure Done; // rollback if tx is active end; TDB = class(TInterfacedObject, IDB) private fPath: string; fOpened: boolean; fFd: integer; fWritable: boolean; fNoSync: boolean; fNoGrowSync: boolean; fMmapFlags: integer; fNoFreelistSync: boolean; fMaxBatchSize: SizeUint; fMaxBatchDelay: integer; fAllocSize: SizeUint; fPageSize: SizeUint; fMmapLock: TRtlCriticalSection; fRwTx: TTx; procedure InitDbFile; function AdjustMmapSize(size: int64): int64; public constructor Create(const aFileName: string; opt: POptions); destructor Destroy; override; public // interface methods procedure Close; function Writable: boolean; function BeginTx(readOnly: boolean): ITx; procedure Sync; end; TCursor = class(TInterfacedObject, bolt.ICursor) public function First(out kv: TKV): boolean; function Last(out kv: TKV): boolean; function Next(out kv: TKV): boolean; function Prev(out kv: TKV): boolean; function Seek(const key: TDbValue; out kv: TKV): boolean; // key can be partial procedure Delete; function Bucket: IBucket; end; const pageHeaderSize = sizeof(page) - sizeof(PtrUint); const minKeysPerPage = 2; const branchPageElementSize = sizeof(branchPageElement); const leafPageElementSize = sizeof(leafPageElement); const branchPageFlag = $01; leafPageFlag = $02; metaPageFlag = $04; freelistPageFlag = $10; const bucketLeafFlag = $01; const // MaxKeySize is the maximum length of a key, in bytes. MaxKeySize = 32768; // MaxValueSize is the maximum length of a value, in bytes. MaxValueSize = (1 shl 31) - 2; const bucketHeaderSize = sizeof(bucket); const minFillPercent = 0.1; maxFillPercent = 1.0; // DefaultFillPercent is the percentage that split pages are filled. // This value can be changed by setting Bucket.FillPercent. const DefaultFillPercent = 0.5; function page_type(d: Ppage): string; begin if (d^.flags and branchPageFlag) <> 0 then result := 'branch' else if (d^.flags and leafPageFlag) <> 0 then result := 'leaf' else if (d^.flags and metaPageFlag) <> 0 then result := 'meta' else if (d^.flags and freelistPageFlag) <> 0 then result := 'freelist' else result := Format('unknown<%02x>', [d^.flags]) end; { TFreelist } constructor TFreelist.Create; begin allocs := TQQHash.Create; pending := TQHash.Create(false); cache := TQHashSet.Create; end; destructor TFreelist.Destroy; begin allocs.Free; pending.Free; cache.Free; inherited Destroy; end; { TTx } function TTx.Bucket(const name: string; createIfNotExists: boolean): IBucket; begin end; procedure TTx.Commit; begin end; function TTx.Cursor: ICursor; begin end; function TTx.DB: IDB; begin end; function TTx.DbSize: SizeUint; begin end; procedure TTx.DeleteBucket(const name: string); begin end; procedure TTx.Done; begin end; function TTx.ID: txid; begin end; function TTx.Writable: boolean; begin end; { TDB } function TDB.BeginTx(readOnly: boolean): ITx; begin end; procedure TDB.Close; begin if not fOpened then exit; if fFd <> THandle(-1) then begin FileClose(fFd); fFd := THandle(-1); end; fOpened := false; end; procedure TDB.Sync; begin end; function TDB.Writable: boolean; begin result := fWritable; end; function meta_checksum(m: Pmeta): uint64; begin result := uint64(UpdateCRC64(m^, sizeof(meta) - sizeof(uint64), -1)); end; function meta_valid(m: Pmeta): boolean; begin result := meta_checksum(m) = m^.checksum; end; procedure TDB.InitDbFile; var buf: array of byte; i: integer; p: Ppage; m: Pmeta; begin SetLength(buf, fPageSize * 4); // Create two meta pages on a buffer. for i := 0 to 1 do begin p := Ppage(@buf[fPageSize * i]); p^.id := pgid(i); p^.flags := metaPageFlag; // Initialize the meta page. m := Pmeta(@p^.ptr); m^.magic := magic; m^.version := version; m^.pageSize := uint32(fPageSize); m^.freelist := 2; m^.root.root := 3; m^.pgid := 4; m^.txid := txid(i); m^.checksum := meta_checksum(m); end; // Write an empty freelist at page 3. p := Ppage(@buf[fPageSize * 2]); p^.id := pgid(2); p^.flags := freelistPageFlag; p^.count := 0; // Write an empty leaf page at page 4. p := Ppage(@buf[fPageSize * 3]); p^.id := pgid(3); p^.flags := leafPageFlag; p^.count := 0; FileSeek(fFd, 0, fsFromBeginning); FileWrite(fFd, buf[0], fPageSize * 4); FileFlush(fFd); end; function TDB.AdjustMmapSize(size: int64): int64; var i: cardinal; remainder: int64; begin // Double the size from 32KB until 1GB. for i := 15 to 30 do begin if size <= (1 shl i) then begin result := 1 shl i; exit; end; end; // Verify the requested size is not above the maximum allowed. if size > maxMapSize then Error('mmap too large'); // If larger than 1GB then grow by 1GB at a time. remainder := size mod int64(maxMmapStep); if remainder > 0 then inc(size, int64(maxMmapStep) - remainder); // Ensure that the mmap size is a multiple of the page size. // This should always be true since we're incrementing in MBs. pageSize := int64(db.pageSize) if (size mod fPageSize) <> 0 then size := ((size div int64(fPageSize)) + 1) * int64(fPageSize); // If we've exceeded the max size then only grow up to the max size. if size > maxMapSize then size := maxMapSize; result := size; end; procedure TDB.Mmap(minsz: int64); var fsz: int64; size: int64; begin EnterCriticalSection(fMmapLock); try fsz := FileSeek(fFd, int64(0), fsFromEnd); if fsz < 0 then Error('can not get file size'); if fsz < (fPageSize * 4) then Error('file size is too small'); if fsz < minsz then fsz := minsz; size := AdjustMmapSize(fsz); if fRwTx <> nil then fRwTx.root.dereference(); {$ifdef windows} {$else} {$endif} finally LeaveCriticalsection(fMmapLock); end; end; constructor TDB.Create(const aFileName: string; opt: POptions); var mode: integer; firstPage: array [0..4095] of byte; meta: Pmeta; begin InitializeCriticalSection(fMmapLock); fPath := aFileName; fOpened := true; if opt = nil then opt := @DefaultOptions; fNoSync := opt^.NoSync; fNoGrowSync := opt^.NoGrowSync; fMmapFlags := opt^.MmapFlags; fNoFreelistSync := opt^.NoFreelistSync; // Set default values for later DB operations. fMaxBatchSize := DefaultMaxBatchSize; fMaxBatchDelay := DefaultMaxBatchDelay; fAllocSize := DefaultAllocSize; if opt^.ReadOnly then mode := fmOpenRead or fmShareExclusive else begin fWritable := true; if not FileExists(aFileName) then FileClose(FileCreate(aFileName)); mode := fmOpenReadWrite; end; // Open data file and separate sync handler for metadata writes. fPath := aFileName; fFd := FileOpen(aFileName, mode or fmShareExclusive); if fFd = THandle(-1) then Error('can not open db file'); fPageSize := opt^.PageSize; if fPageSize = 0 then fPageSize := 4096; if FileSeek(fFd, int64(0), fsFromEnd) = 0 then InitDbFile else begin FileSeek(fFd, 0, fsFromBeginning); if (FileRead(fFd, firstPage[0], 4096) <> 4096) or not meta_valid(Pmeta(@firstPage[0]))) then Error('db file is corrupted'); end; (* // Initialize page pool. db.pagePool = sync.Pool{ New: func() interface{} { return make([]byte, db.pageSize) }, } *) (* // Memory map the data file. if err := db.mmap(options.InitialMmapSize); err != nil { _ = db.close() return nil, err } if db.readOnly { return db, nil } *) db.loadFreelist() // Flush freelist when transitioning from no sync to sync so // NoFreelistSync unaware boltdb can open the db later. if !db.NoFreelistSync && !db.hasSyncedFreelist() { tx, err := db.Begin(true) if tx != nil { err = tx.Commit() } if err != nil { _ = db.close() return nil, err } } // Mark the database as opened and return. return db, nil } end; destructor TDB.Destroy; begin if fOpened then Close; DeleteCriticalSection(fMmapLock); inherited Destroy; end; { TCursor } function TCursor.Bucket: IBucket; begin end; procedure TCursor.Delete; begin end; function TCursor.First(out kv: TKV): boolean; begin end; function TCursor.Last(out kv: TKV): boolean; begin end; function TCursor.Next(out kv: TKV): boolean; begin end; function TCursor.Prev(out kv: TKV): boolean; begin end; function TCursor.Seek(const key: TDbValue; out kv: TKV): boolean; begin end; { TBucket } function TBucket.Bucket(const name: string): IBucket; begin end; function TBucket.BucketsCursor: ICursor; begin end; function TBucket.Cursor: ICursor; begin end; function TBucket.Get(const key: TDbValue; out value: TDbValue): boolean; begin end; function TBucket.Put(const kv: TKV; overwrite: boolean): boolean; begin end; function OpenBoltDatabase(const name: string; opts: POptions): bolt.IDB; begin result := TDB.Create(name, options); end; end.
{$R-} {$Q-} unit ncEncCrypt2; // To disable as much of RTTI as possible (Delphi 2009/2010), // Note: There is a bug if $RTTI is used before the "unit <unitname>;" section of a unit, hence the position {$IF CompilerVersion >= 21.0} {$WEAKLINKRTTI ON} {$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])} {$ENDIF} interface uses Classes, Sysutils; { ****************************************************************************** } { A few predefined types to help out } type Pbyte = ^byte; Pword = ^word; Pdword = ^dword; Pint64 = ^int64; dword = longword; Pwordarray = ^Twordarray; Twordarray = array [0 .. 19383] of word; Pdwordarray = ^Tdwordarray; Tdwordarray = array [0 .. 8191] of dword; { ****************************************************************************** } { The base class from which all hash algorithms are to be derived } type EncEnc_hash = class(Exception); TncEnc_hash = class(TComponent)protected fInitialized: boolean; { Whether or not the algorithm has been initialized } public property Initialized: boolean read fInitialized; { Get the algorithm id } class function GetAlgorithm: string; virtual; abstract; { Get the algorithm name } class function GetHashSize: integer; virtual; abstract; { Get the size of the digest produced - in bits } class function SelfTest: boolean; virtual; abstract; function SelfTestProp: boolean; { Tests the implementation with several test vectors } procedure Init; virtual; abstract; { Initialize the hash algorithm } procedure Final(var Digest); virtual; abstract; { Create the final digest and clear the stored information. The size of the Digest var must be at least equal to the hash size } procedure Burn; virtual; abstract; { Clear any stored information with out creating the final digest } procedure Update(const Buffer; Size: longword); virtual; abstract; { Update the hash buffer with Size bytes of data from Buffer } procedure UpdateStream(Stream: TStream; Size: longword); { Update the hash buffer with Size bytes of data from the stream } procedure UpdateStr(const Str: string); { Update the hash buffer with the string } destructor Destroy; override; published property Algorithm: string read GetAlgorithm; property HashSize: integer read GetHashSize; end; TncEnc_hashclass = class of TncEnc_hash; { ****************************************************************************** } { The base class from which all encryption components will be derived. } { Stream ciphers will be derived directly from this class where as } { Block ciphers will have a further foundation class TncEnc_blockcipher. } type EncEnc_cipher = class(Exception); TncEnc_cipher = class(TComponent)protected fInitialized: boolean; // Whether or not the key setup has been done yet public property Initialized: boolean read fInitialized; { Get the algorithm id } class function GetAlgorithm: string; virtual; abstract; { Get the algorithm name } class function GetMaxKeySize: integer; virtual; abstract; function GetMaxKeySizeProp: integer; { Get the maximum key size (in bits) } class function SelfTest: boolean; virtual; abstract; function SelfTestProp: boolean; { Tests the implementation with several test vectors } procedure Init(const Key; Size: longword; InitVector: pointer); virtual; { Do key setup based on the data in Key, size is in bits } procedure InitStr(const Key: string; HashType: TncEnc_hashclass); { Do key setup based on a hash of the key string } procedure Burn; virtual; { Clear all stored key information } procedure Reset; virtual; abstract; { Reset any stored chaining information } procedure Encrypt(const Indata; var Outdata; Size: longword); virtual; abstract; { Encrypt size bytes of data and place in Outdata } procedure Decrypt(const Indata; var Outdata; Size: longword); virtual; abstract; { Decrypt size bytes of data and place in Outdata } function EncryptStream(InStream, OutStream: TStream; Size: longword): longword; { Encrypt size bytes of data from InStream and place in OutStream } function DecryptStream(InStream, OutStream: TStream; Size: longword): longword; { Decrypt size bytes of data from InStream and place in OutStream } constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Algorithm: string read GetAlgorithm; property MaxKeySize: integer read GetMaxKeySize; end; TncEnc_cipherclass = class of TncEnc_cipher; { ****************************************************************************** } { The base class from which all block ciphers are to be derived, this } { extra class takes care of the different block encryption modes. } type TncEnc_ciphermode = (cmCBC, cmCFB8bit, cmCFBblock, cmOFB, cmCTR); // cmCFB8bit is equal to ncEnccrypt v1.xx's CFB mode EncEnc_blockcipher = class(EncEnc_cipher); TncEnc_blockcipher = class(TncEnc_cipher)protected fCipherMode: TncEnc_ciphermode; { The cipher mode the encrypt method uses } procedure InitKey(const Key; Size: longword); virtual; abstract; public class function GetBlockSize: integer; virtual; abstract; function GetBlockSizeProp: integer; { Get the block size of the cipher (in bits) } procedure SetIV(const Value); virtual; abstract; { Sets the IV to Value and performs a reset } procedure GetIV(var Value); virtual; abstract; { Returns the current chaining information, not the actual IV } procedure Encrypt(const Indata; var Outdata; Size: longword); override; { Encrypt size bytes of data and place in Outdata using CipherMode } procedure Decrypt(const Indata; var Outdata; Size: longword); override; { Decrypt size bytes of data and place in Outdata using CipherMode } procedure EncryptECB(const Indata; var Outdata); virtual; abstract; { Encrypt a block of data using the ECB method of encryption } procedure DecryptECB(const Indata; var Outdata); virtual; abstract; { Decrypt a block of data using the ECB method of decryption } procedure EncryptCBC(const Indata; var Outdata; Size: longword); virtual; abstract; { Encrypt size bytes of data using the CBC method of encryption } procedure DecryptCBC(const Indata; var Outdata; Size: longword); virtual; abstract; { Decrypt size bytes of data using the CBC method of decryption } procedure EncryptCFB8bit(const Indata; var Outdata; Size: longword); virtual; abstract; { Encrypt size bytes of data using the CFB (8 bit) method of encryption } procedure DecryptCFB8bit(const Indata; var Outdata; Size: longword); virtual; abstract; { Decrypt size bytes of data using the CFB (8 bit) method of decryption } procedure EncryptCFBblock(const Indata; var Outdata; Size: longword); virtual; abstract; { Encrypt size bytes of data using the CFB (block) method of encryption } procedure DecryptCFBblock(const Indata; var Outdata; Size: longword); virtual; abstract; { Decrypt size bytes of data using the CFB (block) method of decryption } procedure EncryptOFB(const Indata; var Outdata; Size: longword); virtual; abstract; { Encrypt size bytes of data using the OFB method of encryption } procedure DecryptOFB(const Indata; var Outdata; Size: longword); virtual; abstract; { Decrypt size bytes of data using the OFB method of decryption } procedure EncryptCTR(const Indata; var Outdata; Size: longword); virtual; abstract; { Encrypt size bytes of data using the CTR method of encryption } procedure DecryptCTR(const Indata; var Outdata; Size: longword); virtual; abstract; { Decrypt size bytes of data using the CTR method of decryption } constructor Create(AOwner: TComponent); override; published property BlockSize: integer read GetBlockSizeProp; property CipherMode: TncEnc_ciphermode read fCipherMode write fCipherMode default cmCBC; end; TncEnc_blockcipherclass = class of TncEnc_blockcipher; { ****************************************************************************** } { Helper functions } procedure XorBlock(var InData1, InData2; Size: longword); implementation uses ncEncryption; { ** TncEnc_hash ***************************************************************** } procedure TncEnc_hash.UpdateStream(Stream: TStream; Size: longword); var Buffer: array [0 .. 8191] of byte; i, read: integer; begin for i := 1 to (Size div Sizeof(Buffer)) do begin read := Stream.Read(Buffer, Sizeof(Buffer)); Update(Buffer, read); end; if (Size mod Sizeof(Buffer)) <> 0 then begin read := Stream.Read(Buffer, Size mod Sizeof(Buffer)); Update(Buffer, read); end; end; procedure TncEnc_hash.UpdateStr(const Str: string); var Bytes: TBytes; begin Bytes := BytesOf(Str); Update(Bytes[0], Length(Bytes)); end; destructor TncEnc_hash.Destroy; begin if fInitialized then Burn; inherited Destroy; end; { ** TncEnc_cipher *************************************************************** } procedure TncEnc_cipher.Init(const Key; Size: longword; InitVector: pointer); begin if fInitialized then Burn; if (Size <= 0) or ((Size and 3) <> 0) or (Size > longword(GetMaxKeySize)) then raise EncEnc_cipher.Create('Invalid key size') else fInitialized := true; end; procedure TncEnc_cipher.InitStr(const Key: string; HashType: TncEnc_hashclass); var Hash: TncEnc_hash; Digest: pointer; begin if fInitialized then Burn; try GetMem(Digest, HashType.GetHashSize div 8); Hash := HashType.Create(Self); Hash.Init; Hash.UpdateStr(Key); Hash.Final(Digest^); Hash.Free; if MaxKeySize < HashType.GetHashSize then Init(Digest^, MaxKeySize, nil) else Init(Digest^, HashType.GetHashSize, nil); FillChar(Digest^, HashType.GetHashSize div 8, $FF); FreeMem(Digest); except raise EncEnc_cipher.Create('Unable to allocate sufficient memory for hash digest'); end; end; procedure TncEnc_cipher.Burn; begin fInitialized := false; end; function TncEnc_cipher.EncryptStream(InStream, OutStream: TStream; Size: longword): longword; var Buffer: array [0 .. 8191] of byte; i, Read: longword; begin Result := 0; for i := 1 to (Size div Sizeof(Buffer)) do begin Read := InStream.Read(Buffer, Sizeof(Buffer)); Inc(Result, Read); Encrypt(Buffer, Buffer, Read); OutStream.Write(Buffer, Read); end; if (Size mod Sizeof(Buffer)) <> 0 then begin Read := InStream.Read(Buffer, Size mod Sizeof(Buffer)); Inc(Result, Read); Encrypt(Buffer, Buffer, Read); OutStream.Write(Buffer, Read); end; end; function TncEnc_cipher.DecryptStream(InStream, OutStream: TStream; Size: longword): longword; var Buffer: array [0 .. 8191] of byte; i, Read: longword; begin Result := 0; for i := 1 to (Size div Sizeof(Buffer)) do begin Read := InStream.Read(Buffer, Sizeof(Buffer)); Inc(Result, Read); Decrypt(Buffer, Buffer, Read); OutStream.Write(Buffer, Read); end; if (Size mod Sizeof(Buffer)) <> 0 then begin Read := InStream.Read(Buffer, Size mod Sizeof(Buffer)); Inc(Result, Read); Decrypt(Buffer, Buffer, Read); OutStream.Write(Buffer, Read); end; end; constructor TncEnc_cipher.Create(AOwner: TComponent); begin inherited Create(AOwner); Burn; end; destructor TncEnc_cipher.Destroy; begin if fInitialized then Burn; inherited Destroy; end; { ** TncEnc_blockcipher ********************************************************** } procedure TncEnc_blockcipher.Encrypt(const Indata; var Outdata; Size: longword); begin case fCipherMode of cmCBC: EncryptCBC(Indata, Outdata, Size); cmCFB8bit: EncryptCFB8bit(Indata, Outdata, Size); cmCFBblock: EncryptCFBblock(Indata, Outdata, Size); cmOFB: EncryptOFB(Indata, Outdata, Size); cmCTR: EncryptCTR(Indata, Outdata, Size); end; end; procedure TncEnc_blockcipher.Decrypt(const Indata; var Outdata; Size: longword); begin case fCipherMode of cmCBC: DecryptCBC(Indata, Outdata, Size); cmCFB8bit: DecryptCFB8bit(Indata, Outdata, Size); cmCFBblock: DecryptCFBblock(Indata, Outdata, Size); cmOFB: DecryptOFB(Indata, Outdata, Size); cmCTR: DecryptCTR(Indata, Outdata, Size); end; end; constructor TncEnc_blockcipher.Create(AOwner: TComponent); begin inherited Create(AOwner); fCipherMode := cmCBC; end; { ** Helpher functions ********************************************************* } procedure XorBlock(var InData1, InData2; Size: longword); var i: longword; begin for i := 1 to Size do Pbyte(longword(@InData1) + i - 1)^ := Pbyte(longword(@InData1) + i - 1)^ xor Pbyte(longword(@InData2) + i - 1)^; end; function TncEnc_hash.SelfTestProp: boolean; begin Result := SelfTest; end; function TncEnc_cipher.GetMaxKeySizeProp: integer; begin Result := GetMaxKeySize; end; function TncEnc_cipher.SelfTestProp: boolean; begin Result := SelfTest; end; function TncEnc_blockcipher.GetBlockSizeProp: integer; begin Result := GetBlockSize; end; end.
{*******************************************************} { } { Delphi VCL Extensions (RX) } { } { Added by Polaris Software } {*******************************************************} unit rrxcombo; { RX RXColorCombo support constants } { Reserved diapasone from MaxExtStrID - 500 to MaxExtStrID - 545 } interface const { The minimal VCL's used string ID is 61440. The custom IDs must be less that above. } MaxExtStrID = 61300; { RxCombos } const SColorBlack = MaxExtStrID - 500; SColorMaroon = MaxExtStrID - 501; SColorGreen = MaxExtStrID - 502; SColorOlive = MaxExtStrID - 503; SColorNavy = MaxExtStrID - 504; SColorPurple = MaxExtStrID - 505; SColorTeal = MaxExtStrID - 506; SColorGray = MaxExtStrID - 507; SColorSilver = MaxExtStrID - 508; SColorRed = MaxExtStrID - 509; SColorLime = MaxExtStrID - 510; SColorYellow = MaxExtStrID - 511; SColorBlue = MaxExtStrID - 512; SColorFuchsia = MaxExtStrID - 513; SColorAqua = MaxExtStrID - 514; SColorWhite = MaxExtStrID - 515; SColorScrollBar = MaxExtStrID - 516; SColorBackground = MaxExtStrID - 517; SColorActiveCaption = MaxExtStrID - 518; SColorInactiveCaption = MaxExtStrID - 519; SColorMenu = MaxExtStrID - 520; SColorWindow = MaxExtStrID - 521; SColorWindowFrame = MaxExtStrID - 522; SColorMenuText = MaxExtStrID - 523; SColorWindowText = MaxExtStrID - 524; SColorCaptionText = MaxExtStrID - 525; SColorActiveBorder = MaxExtStrID - 526; SColorInactiveBorder = MaxExtStrID - 527; SColorAppWorkSpace = MaxExtStrID - 528; SColorHighlight = MaxExtStrID - 529; SColorHighlightText = MaxExtStrID - 530; SColorBtnFace = MaxExtStrID - 531; SColorBtnShadow = MaxExtStrID - 532; SColorGrayText = MaxExtStrID - 533; SColorBtnText = MaxExtStrID - 534; SColorInactiveCaptionText = MaxExtStrID - 535; SColorBtnHighlight = MaxExtStrID - 536; SColor3DDkShadow = MaxExtStrID - 537; SColor3DLight = MaxExtStrID - 538; SColorInfoText = MaxExtStrID - 539; SColorInfoBk = MaxExtStrID - 540; SColorCream = MaxExtStrID - 541; SColorMoneyGreen = MaxExtStrID - 542; SColorSkyBlue = MaxExtStrID - 543; SColorNone = MaxExtStrID - 544; SColorDefault = MaxExtStrID - 545; SColorCustom = MaxExtStrID - 546; implementation end.
unit EarthType; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, Buttons, DB, OleCtrls, ExtCtrls, Mask, rxToolEdit, rxCurrEdit; type TEarthTypeForm = class(TForm) lbl_qiymc: TLabel; btn_ok: TBitBtn; btn_cancel: TBitBtn; Gbox: TGroupBox; sgEarthType: TStringGrid; gbox2: TGroupBox; lblD_t_no: TLabel; lblD_t_name: TLabel; Label1: TLabel; Label2: TLabel; edtEa_name: TEdit; edtAge: TEdit; edtEa_no: TCurrencyEdit; edtEa_name_en: TEdit; btn_add: TBitBtn; btn_delete: TBitBtn; btn_edit: TBitBtn; procedure sgEarthTypeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure btn_cancelClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btn_deleteClick(Sender: TObject); procedure btn_addClick(Sender: TObject); procedure btn_editClick(Sender: TObject); procedure btn_okClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure edtEa_noKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } procedure button_status(int_status:integer;bHaveRecord:boolean); procedure Get_oneRecord(aEarthNo: String); function Delete_oneRecord(strSQL:string):boolean; function Update_oneRecord(strSQL:string):boolean; function Insert_oneRecord(strSQL:string):boolean; function GetInsertSQL:string; function GetUpdateSQL:string; function GetDeleteSQL:string; function Check_Data:boolean; function isExistedRecord(aEarthNo:string):boolean; public { Public declarations } end; type TEarthRecord=Record ea_no:String; ea_name:string; ea_name_en:string; age:string; end; var EarthTypeForm: TEarthTypeForm; m_iGridSelectedRow: integer; m_DataSetState: TDataSetState; m_EarthRecord: TEarthRecord; implementation uses MainDM, public_unit; {$R *.dfm} procedure TEarthTypeForm.button_status(int_status: integer; bHaveRecord: boolean); begin case int_status of 1: //浏览状态 begin btn_edit.Enabled :=bHaveRecord; btn_delete.Enabled :=bHaveRecord; btn_edit.Caption :='修改'; btn_ok.Enabled :=false; btn_add.Enabled :=true; Enable_Components(self,false); m_DataSetState := dsBrowse; end; 2: //修改状态 begin btn_edit.Enabled :=true; btn_edit.Caption :='放弃'; btn_ok.Enabled :=true; btn_add.Enabled :=false; btn_delete.Enabled :=false; Enable_Components(self,true); m_DataSetState := dsEdit; end; 3: //增加状态 begin btn_edit.Enabled :=true; btn_edit.Caption :='放弃'; btn_ok.Enabled :=true; btn_add.Enabled :=false; btn_delete.Enabled :=false; Enable_Components(self,true); m_DataSetState := dsInsert; end; end; end; function TEarthTypeForm.Check_Data: boolean; begin if trim(edtEa_no.Text) = '' then begin messagebox(self.Handle,'请输入土类代码!','数据校对',mb_ok); edtEa_no.SetFocus; result := false; exit; end; if trim(edtEa_name.Text) = '' then begin messagebox(self.Handle,'请输入土类名称!','数据校对',mb_ok); edtEa_name.SetFocus; result := false; exit; end; result := true; end; function TEarthTypeForm.Delete_oneRecord(strSQL: string): boolean; begin with MainDataModule.qryEarthType do begin close; sql.Clear; sql.Add(strSQL); try try ExecSQL; MessageBox(self.Handle,'删除成功!','删除数据',MB_OK+MB_ICONINFORMATION); result := true; except MessageBox(self.Handle,'数据库错误,不能删除所选数据。','数据库错误',MB_OK+MB_ICONERROR); result := false; end; finally close; end; end; end; procedure TEarthTypeForm.Get_oneRecord(aEarthNo: String); begin if aEarthNo='' then exit; with MainDataModule.qryEarthType do begin close; sql.Clear; sql.Add('SELECT ea_no,ea_name,ea_name_en,age FROM earthtype '); sql.Add(' WHERE ea_no=' + ''''+aEarthNo+''''); open; while not Eof do begin edtEa_no.Text := FieldByName('ea_no').AsString; edtEa_name.Text := FieldByName('ea_name').AsString; edtEa_name_en.Text := FieldByName('ea_name_en').AsString; edtAge.Text := FieldByName('age').AsString; m_EarthRecord.age := edtAge.Text; m_EarthRecord.ea_no := edtEa_no.Text; m_EarthRecord.ea_name := edtEa_name.Text ; m_EarthRecord.ea_name_en := edtEa_name_en.Text; next; end; close; end; end; function TEarthTypeForm.GetDeleteSQL: string; begin result :='DELETE FROM earthtype WHERE ea_no='+ ''''+edtEa_no.Text+''''; end; function TEarthTypeForm.GetInsertSQL: string; begin if trim(edtAge.Text)='' then result := 'INSERT INTO earthtype (ea_no,ea_name,ea_name_en) VALUES(' +''''+trim(edtEa_no.Text)+''''+',' +''''+trim(edtEa_name.Text)+''''+',' +''''+trim(edtEa_name_en.Text)+''')' else result := 'INSERT INTO earthtype (ea_no,ea_name,ea_name_en,age) VALUES(' +''''+trim(edtEa_no.Text)+''''+',' +''''+trim(edtEa_name.Text)+''''+',' +''''+trim(edtEa_name_en.Text)+''''+',' +''''+trim(edtAge.Text)+''')'; end; function TEarthTypeForm.GetUpdateSQL: string; var strSQLWhere,strSQLSet:string; begin strSQLWhere:=' WHERE ea_no='+''''+sgEarthType.Cells[1,sgEarthType.Row]+''''; strSQLSet:='UPDATE earthtype SET '; strSQLSet := strSQLSet + 'ea_no' +'='+''''+trim(edtEa_no.Text)+''''+','; strSQLSet := strSQLSet + 'ea_name' +'='+''''+trim(edtEa_name.Text)+''''+','; strSQLSet := strSQLSet + 'ea_name_en' +'='+''''+trim(edtEa_name_en.Text)+''''+','; strSQLSet := strSQLSet + 'age' +'='+''''+trim(edtAge.Text)+''''; result := strSQLSet + strSQLWhere; end; function TEarthTypeForm.Insert_oneRecord(strSQL: string): boolean; begin with MainDataModule.qryEarthType do begin close; sql.Clear; sql.Add(strSQL); try try ExecSQL; MessageBox(self.Handle,'增加数据成功!','增加数据',MB_OK+MB_ICONINFORMATION); result := true; except MessageBox(self.Handle,'数据库错误,增加数据失败。','数据库错误',MB_OK+MB_ICONERROR); result:= false; end; finally close; end; end; end; function TEarthTypeForm.isExistedRecord(aEarthNo: string): boolean; begin with MainDataModule.qryEarthType do begin close; sql.Clear; sql.Add('SELECT ea_no FROM earthtype '); sql.Add(' WHERE ea_no=' + ''''+aEarthNo+'''' ); try try Open; if eof then result:=false else begin result:=true; messagebox(self.Handle,'此类别代码已经存在,请输入新的类别代码!','数据校对',mb_ok); edtEa_no.SetFocus; end; except result:=false; end; finally close; end; end; end; function TEarthTypeForm.Update_oneRecord(strSQL: string): boolean; begin with MainDataModule.qryEarthType do begin close; sql.Clear; sql.Add(strSQL); try try ExecSQL; MessageBox(self.Handle,'更新数据成功!','更新数据',MB_OK+MB_ICONINFORMATION); result := true; except MessageBox(self.Handle,'数据库错误,更新数据失败。','数据库错误',MB_OK+MB_ICONERROR); result:= false; end; finally close; end; end; end; procedure TEarthTypeForm.sgEarthTypeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if sgEarthType.Tag =1 then exit; if (ARow <>0) and (ARow<>m_iGridSelectedRow) then if sgEarthType.Cells[1,ARow]<>'' then begin Get_oneRecord(sgEarthType.Cells[1,ARow]); if sgEarthType.Cells[1,ARow]='' then Button_status(1,false) else Button_status(1,true); end else begin clear_data(self); end; m_iGridSelectedRow:=ARow; end; procedure TEarthTypeForm.btn_cancelClick(Sender: TObject); begin self.Close; end; procedure TEarthTypeForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TEarthTypeForm.btn_deleteClick(Sender: TObject); var strSQL: string; begin if MessageBox(self.Handle, '您确定要删除吗?','警告', MB_YESNO+MB_ICONQUESTION)=IDNO then exit; if edtEa_no.Text <> '' then begin strSQL := self.GetDeleteSQL; if Delete_oneRecord(strSQL) then begin Clear_Data(self); DeleteStringGridRow(sgEarthType,sgEarthType.Row); self.Get_oneRecord(sgEarthType.Cells[1,sgEarthType.Row]); if sgEarthType.Cells[1,sgEarthType.row]='' then button_status(1,false) else button_status(1,true); end; end; end; procedure TEarthTypeForm.btn_addClick(Sender: TObject); begin Clear_Data(self); m_EarthRecord.age := ''; m_EarthRecord.ea_no := ''; Button_status(3,true); edtEa_no.SetFocus; edtEa_no.ReadOnly := false; end; procedure TEarthTypeForm.btn_editClick(Sender: TObject); begin if btn_edit.Caption ='修改' then begin Button_status(2,true); end else begin clear_data(self); Button_status(1,true); self.Get_oneRecord(sgEarthType.Cells[1,sgEarthType.Row]); end; end; procedure TEarthTypeForm.btn_okClick(Sender: TObject); var strSQL: string; begin if not Check_Data then exit; if m_DataSetState = dsInsert then begin if isExistedRecord(trim(edtEa_no.Text)) then exit; strSQL := self.GetInsertSQL; if Insert_oneRecord(strSQL) then begin if (sgEarthType.RowCount =2) and (sgEarthType.Cells[1,1] ='') then else sgEarthType.RowCount := sgEarthType.RowCount+1; m_iGridSelectedRow:= sgEarthType.RowCount-1; sgEarthType.Cells[1,sgEarthType.RowCount-1] := trim(edtEa_no.Text); sgEarthType.Cells[2,sgEarthType.RowCount-1] := trim(edtEa_name.Text); sgEarthType.Row := sgEarthType.RowCount-1; Button_status(1,true); btn_add.SetFocus; edtEa_no.ReadOnly := true; end; end else if m_DataSetState = dsEdit then begin if sgEarthType.Cells[1,sgEarthType.Row]<>trim(edtEa_no.Text) then if isExistedRecord(trim(edtEa_no.Text)) then exit; strSQL := self.GetUpdateSQL; if self.Update_oneRecord(strSQL) then begin sgEarthType.Cells[1,sgEarthType.Row] := edtEa_no.Text ; sgEarthType.Cells[2,sgEarthType.Row] := edtEa_name.Text ; Button_status(1,true); btn_add.SetFocus; end; end; end; procedure TEarthTypeForm.FormCreate(Sender: TObject); var i: integer; begin self.Left := trunc((screen.Width -self.Width)/2); self.Top := trunc((Screen.Height - self.Height)/2); sgEarthType.RowHeights[0] := 16; sgEarthType.Cells[1,0] := '土类代码'; sgEarthType.Cells[2,0] := '土类名称'; sgEarthType.ColWidths[0]:=10; sgEarthType.ColWidths[1]:=125; sgEarthType.ColWidths[2]:=125; m_iGridSelectedRow:= -1; Clear_Data(self); with MainDataModule.qryEarthType do begin close; sql.Clear; sql.Add('SELECT ea_no,ea_name,age FROM earthtype'); open; i:=0; sgEarthType.Tag :=1; while not Eof do begin i:=i+1; sgEarthType.RowCount := i +1; sgEarthType.Cells[1,i] := FieldByName('ea_no').AsString; sgEarthType.Cells[2,i] := FieldByName('ea_name').AsString; Next ; end; close; sgEarthType.Tag :=0; end; if i>0 then begin sgEarthType.Row :=1; m_iGridSelectedRow :=1; Get_oneRecord(sgEarthType.Cells[1,sgEarthType.Row]); button_status(1,true); end else button_status(1,false); end; procedure TEarthTypeForm.edtEa_noKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin change_focus(key,self); end; end.
unit Bitmaps; interface uses Windows, Messages; type Color = byte; PAColor = ^AColor; PColor = ^Color; AColor = array [0 .. MaxInt div sizeof(Color)-1] of Color; Bitmap = record H : HWND; DC : HDC; sizeX, sizeY, stride : integer; Pixels : PAColor; end; procedure CreateBitmap (var B: Bitmap; sizeX, sizeY: integer); procedure DestroyBitmap (var B: Bitmap); function NearestColor(r,g,b: integer): Color; procedure SetFogTable (fogr, fogg, fogb : integer); var ColorTable : array [0..255] of TRGBQuad; FogTable : array [0..319,0..255] of Color; implementation uses Memory; procedure SetFogTable (fogr, fogg, fogb : integer); var i,j,f,r,g,b: integer; begin for i := 0 to 319 do begin // уровень тумана if i<64 then f := i*4 else f := 256; f := (f*(256*2-f)) div (1*256); for j := 0 to 255 do begin // цвет r := (ColorTable[j].rgbRed * f + fogr * (256-f)) div 256; g := (ColorTable[j].rgbGreen * f + fogg * (256-f)) div 256; b := (ColorTable[j].rgbBlue * f + fogb * (256-f)) div 256; FogTable[i,j] := NearestColor(r,g,b); end; end; end; function IndexToRGB (i: integer): TRGBQuad; const MainColors : array [0..15] of TRGBQuad = ( (rgbBlue: 0; rgbGreen: 255; rgbRed: 255), (rgbBlue: 64; rgbGreen: 255; rgbRed: 192), (rgbBlue: 128; rgbGreen: 255; rgbRed: 128), (rgbBlue: 192; rgbGreen: 255; rgbRed: 64), (rgbBlue: 255; rgbGreen: 255; rgbRed: 0), (rgbBlue: 0; rgbGreen: 128; rgbRed: 255), (rgbBlue: 128; rgbGreen: 192; rgbRed: 255), (rgbBlue: 255; rgbGreen: 255; rgbRed: 255), (rgbBlue: 255; rgbGreen: 192; rgbRed: 128), (rgbBlue: 255; rgbGreen: 128; rgbRed: 0), (rgbBlue: 0; rgbGreen: 0; rgbRed: 255), (rgbBlue: 128; rgbGreen: 64; rgbRed: 255), (rgbBlue: 255; rgbGreen: 128; rgbRed: 255), (rgbBlue: 255; rgbGreen: 64; rgbRed: 128), (rgbBlue: 255; rgbGreen: 0; rgbRed: 0), (rgbBlue: 0; rgbGreen: 0; rgbRed: 0)); var l,c : integer; //cr,cg,cb : integer; begin if i=0 then Result := MainColors[15] else begin l := (i-1) div 15+1; // 1..17 c := (i-1) mod 15; result.rgbBlue := (MainColors[c].rgbBlue *1+0) div 1 * l div 17; result.rgbGreen := (MainColors[c].rgbGreen*1+0) div 1 * l div 17; result.rgbRed := (MainColors[c].rgbRed *1+0) div 1 * l div 17; end; Result.rgbReserved := 0; { cr := i and 7; cg := (i shr 3) and 3; cb := i shr 5; result.rgbRed := cr*36; result.rgbGreen := (cr+cb)*14+cg*14; result.rgbBlue := cb*36; result.rgbReserved := 0; } end; procedure CreateBitmap (var B: Bitmap; sizeX, sizeY: integer); var BI : ^TBitmapInfo; MS : MemoryState; ScreenDC: HDC; i : integer; begin SaveState(MS); BI := Alloc(sizeof(TBitmapInfo) + 255*sizeof(tagRGBQuad)); FillChar(BI^, SizeOf(BI^), 0); B.sizeX := sizeX; B.sizeY := sizeY; B.stride := (sizeX+3) and not 3; with BI.bmiHeader do begin biSize := SizeOf(BI.bmiHeader); biWidth := sizeX; biHeight := sizeY; biPlanes := 1; biBitCount := sizeof(Color)*8; end; {$IFOPT R+} {$DEFINE OLD_R} {$R-} {$ENDIF} for i := 0 to 255 do begin BI.bmiColors[i] := ColorTable[i]; BI.bmiColors[i].rgbGreen := (BI.bmiColors[i].rgbRed + BI.bmiColors[i].rgbBlue + BI.bmiColors[i].rgbGreen) div 3; end; {$IFDEF OLD_R} {$R+} {$UNDEF OLD_R} {$ENDIF} ScreenDC := GetDC(0); with B do begin DC := CreateCompatibleDC(ScreenDC); H := CreateDIBSection(DC, BI^, DIB_RGB_COLORS, pointer(Pixels), 0, 0); SelectObject(DC, H); ReleaseDC(0, ScreenDC); end; RestoreState(MS); end; procedure DestroyBitmap (var B: Bitmap); begin with B do if H <> 0 then begin SelectObject(DC, 0); DeleteDC(DC); DeleteObject(H); H := 0; end; end; function NearestColor(r,g,b: integer): Color; var i : integer; dst,adst : integer; begin dst := 1024; Result := 0; for i := 0 to 255 do begin adst := abs(r-ColorTable[i].rgbRed) + abs(g-ColorTable[i].rgbGreen) + abs(b-ColorTable[i].rgbBlue); if adst<dst then begin Result := i; dst := adst; end; end; //Result := r or g shl 8 or b shl 16; end; var i: integer; initialization for i := 0 to 255 do ColorTable[i] := IndexToRGB(i); end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Web.HTTPDMethods; // Define methods for accessing apache server. // These methods can be use for different versions of Apache 2.0. interface uses System.SysUtils; type // Pointer to pool PHTTPDPool = type Pointer; // Pointer to request PHTTPDRequest = type Pointer; // Pointer to server record PHTTPDServer_rec = type Pointer; THTTPDMethods = class public type THandlerProc = function(const p: PHTTPDRequest): Integer; cdecl; TInitiationProc = Procedure(const p: PHTTPDPool; const s: PHTTPDServer_rec); cdecl; TTerminationFunc = function(const p: Pointer): Integer; cdecl; public // Consts class function get_AP_OK: Integer; class function get_AP_DONE: Integer; class function get_AP_DECLINED: Integer; class function get_APR_HOOK_REALLY_FIRST: Integer; // May pass to hook_handler class function get_APR_HOOK_FIRST: Integer; class function get_APR_HOOK_MIDDLE: Integer; class function get_APR_HOOK_LAST: Integer; class function get_APR_HOOK_REALLY_LAST: Integer; // Utils class procedure hook_handler(const AHandler: THandlerProc; const APre: PPChar; const ASucc: PPChar; AOrder: Integer); class procedure hook_child_init(const AInitiation: TInitiationProc; const APre: PPChar; const ASucc: PPChar; AOrder: Integer); class procedure pool_cleanup_register(const p: PHTTPDPool; const data: Pointer; APlainTermination: TTerminationFunc; AChildTermination: TTerminationFunc); class function server_root_relative(const ARequestRec: PHTTPDRequest; const AURI: UTF8String): UTF8String; // Read request class function get_handler(const ARequestRec: PHTTPDRequest): UTF8String; class function get_method(const ARequestRec: PHTTPDRequest): UTF8String; class function get_ContentType(const ARequestRec: PHTTPDRequest): UTF8String; class function get_protocol(const ARequestRec: PHTTPDRequest): UTF8String; class function get_unparsed_uri(const ARequestRec: PHTTPDRequest): UTF8String; class function get_args(const ARequestRec: PHTTPDRequest): UTF8String; class function get_path_info(const ARequestRec: PHTTPDRequest): UTF8String; class function get_filename(const ARequestRec: PHTTPDRequest): UTF8String; class function get_headers_in_Accept(const ARequestRec: PHTTPDRequest): UTF8String; class function get_headers_in_From(const ARequestRec: PHTTPDRequest): UTF8String; class function get_hostname(const ARequestRec: PHTTPDRequest): UTF8String; class function get_headers_in_Referer(const ARequestRec: PHTTPDRequest): UTF8String; class function get_headers_in_UserAgent(const ARequestRec: PHTTPDRequest): UTF8String; class function get_content_encoding(const ARequestRec: PHTTPDRequest): UTF8String; class function get_headers_in_ContentType(const ARequestRec: PHTTPDRequest): UTF8String; class function get_headers_in_ContentLength(const ARequestRec: PHTTPDRequest): UTF8String; class function get_headers_in_Title(const ARequestRec: PHTTPDRequest): UTF8String; class function get_ServerPort(const ARequestRec: PHTTPDRequest): UTF8String; class function get_Content(const ARequestRec: PHTTPDRequest): TBytes; class function get_client_block(const ARequestRec: PHTTPDRequest; Buffer: PByte; Count: Integer): Integer; class function get_Field(const ARequestRec: PHTTPDRequest; const AName: UTF8String): UTF8String; class function get_connection_ClientIP(const ARequestRec: PHTTPDRequest): UTF8String; class function get_connection_RemoteHost(const ARequestRec: PHTTPDRequest): UTF8String; class function get_headers_in_Connection(const ARequestRec: PHTTPDRequest): UTF8String; class function get_headers_in_Cookie(const ARequestRec: PHTTPDRequest): UTF8String; /// <summary> Returns the header Authorization value </summary> class function get_headers_in_Authorization(const ARequestRec: PHTTPDRequest): UTF8String; // write request response class procedure set_status(const ARequestRec: PHTTPDRequest; ACode: Integer); class procedure add_headers_out(const ARequestRec: PHTTPDRequest; const Key, Value: UTF8String); class procedure set_headers_out(const ARequestRec: PHTTPDRequest; const Key, Value: UTF8String); class procedure set_headers_out_ContentType(const ARequestRec: PHTTPDRequest; const AType: UTF8String); class procedure set_headers_out_ContentEncoding(const ARequestRec: PHTTPDRequest; const AValue: UTF8String); class procedure set_ContentType(const ARequestRec: PHTTPDRequest; const AValue: UTF8String); class procedure set_headers_out_ContentLength(const ARequestRec: PHTTPDRequest; AValue: Integer); class procedure set_location(const ARequestRec: PHTTPDRequest; const AValue: UTF8String); // redirect class function write_buffer(const ARequestRec: PHTTPDRequest; var Buffer; Count: Integer): Integer; class function write_string(const ARequestRec: PHTTPDRequest; const AValue: UTF8String): Integer; end; EHTTPMethodsError = class(Exception); THTTPDInit = class public type TRegisterHooksProc = procedure(const p: PHTTPDPool); TModuleData = pbyte; private class var FRegisterHooksProc: TRegisterHooksProc; class var FModuleData: TModuleData; class var FHandlerName: UTF8String; class var FModuleName: UTF8String; class var FRegisterCustomHooksProc: TRegisterHooksProc; class function GetModuleName: PUTF8Char; static; // Defaults to the DLL/SO's name public class procedure InitModule(const ARegisterHooksProc: TRegisterHooksProc; const AModuleData: TModuleData; const AHandlerName: UTF8String); class property RegisterHooksProc: TRegisterHooksProc read FRegisterHooksProc; class property RegisterCustomHooksProc: TRegisterHooksProc read FRegisterCustomHooksProc write FRegisterCustomHooksProc; class property ModuleData: TModuleData read FModuleData; class property HandlerName: UTF8String read FHandlerName; class property ModuleName: PUTF8Char read GetModuleName; end; implementation uses {$IFDEF MSWINDOWS} Winapi.Windows, {$ENDIF} Web.HTTPDImpl, Web.ApacheConst, System.Math; procedure CheckRegister; inline; begin if GHTTPDImpl = nil then raise EHTTPMethodsError.CreateRes(@sHTTPDImplNotRegistered); end; { TRequestRecReader } class function THTTPDMethods.get_args( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_args(ARequestRec); end; class function THTTPDMethods.get_connection_ClientIP( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_connection_ClientIP(ARequestRec); end; class function THTTPDMethods.get_connection_RemoteHost( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_connection_RemoteHost(ARequestRec); end; class function THTTPDMethods.get_Content( const ARequestRec: PHTTPDRequest): TBytes; begin CheckRegister; Result := GHTTPDImpl.get_Content(ARequestRec); end; class function THTTPDMethods.get_client_block(const ARequestRec: PHTTPDRequest; Buffer: PByte; Count: Integer): Integer; begin CheckRegister; Result := GHTTPDImpl.get_client_block(ARequestRec, Buffer, Count); end; class function THTTPDMethods.get_ContentType( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_ContentType(ARequestRec); end; class function THTTPDMethods.get_content_encoding( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_content_encoding(ARequestRec); end; class function THTTPDMethods.get_Field(const ARequestRec: PHTTPDRequest; const AName: UTF8String): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_headers_in_Field(ARequestRec, AName); end; class function THTTPDMethods.get_filename( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_filename(ARequestRec); end; class function THTTPDMethods.get_handler( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_handler(ARequestRec); end; class function THTTPDMethods.get_headers_in_Accept( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_headers_in_Accept(ARequestRec); end; class function THTTPDMethods.get_headers_in_Cookie( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_headers_in_Cookie(ARequestRec); end; class function THTTPDMethods.get_headers_in_Authorization( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_headers_in_Authorization(ARequestRec); end; class function THTTPDMethods.get_headers_in_Connection( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_headers_in_Connection(ARequestRec); end; class function THTTPDMethods.get_headers_in_ContentLength( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_headers_in_ContentLength(ARequestRec); end; class function THTTPDMethods.get_headers_in_ContentType( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_headers_in_ContentType(ARequestRec); end; class function THTTPDMethods.get_headers_in_From( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_headers_in_From(ARequestRec); end; class function THTTPDMethods.get_headers_in_Referer( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_headers_in_Referer(ARequestRec); end; class function THTTPDMethods.get_headers_in_Title( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_headers_in_Title(ARequestRec); end; class function THTTPDMethods.get_headers_in_UserAgent( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_headers_in_UserAgent(ARequestRec); end; class function THTTPDMethods.get_hostname( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_hostname(ARequestRec); end; class function THTTPDMethods.get_method( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_method(ARequestRec); end; class function THTTPDMethods.get_path_info( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_path_info(ARequestRec); end; class function THTTPDMethods.get_protocol( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_protocol(ARequestRec); end; class function THTTPDMethods.get_ServerPort( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_ServerPort(ARequestRec); end; class function THTTPDMethods.get_unparsed_uri( const ARequestRec: PHTTPDRequest): UTF8String; begin CheckRegister; Result := GHTTPDImpl.get_unparsed_uri(ARequestRec); end; class procedure THTTPDMethods.hook_handler(const AHandler: THandlerProc; const APre, ASucc: PPChar; AOrder: Integer); begin CheckRegister; GHTTPDImpl.hook_handler(AHandler, APre, ASucc, AOrder); end; class procedure THTTPDMethods.pool_cleanup_register(const p: PHTTPDPool; const data: Pointer; APlainTermination, AChildTermination: TTerminationFunc); begin CheckRegister; GHTTPDImpl.pool_cleanup_register(p, data, APlainTermination, AChildTermination); end; class procedure THTTPDMethods.hook_child_init(const AInitiation: TInitiationProc; const APre, ASucc: PPChar; AOrder: Integer); begin CheckRegister; GHTTPDImpl.hook_child_init(AInitiation, APre, ASucc, AOrder); end; class function THTTPDMethods.server_root_relative( const ARequestRec: PHTTPDRequest; const AURI: UTF8String): UTF8String; begin CheckRegister; Result := GHTTPDImpl.server_root_relative(ARequestRec, AURI); end; class procedure THTTPDMethods.set_ContentType( const ARequestRec: PHTTPDRequest; const AValue: UTF8String); begin CheckRegister; GHTTPDImpl.set_ContentType(ARequestRec, AValue); end; class procedure THTTPDMethods.add_headers_out(const ARequestRec: PHTTPDRequest; const Key, Value: UTF8String); begin CheckRegister; GHTTPDImpl.add_headers_out(ARequestRec, Key, Value); end; class procedure THTTPDMethods.set_headers_out( const ARequestRec: PHTTPDRequest; const Key, Value: UTF8String); begin CheckRegister; GHTTPDImpl.set_headers_out(ARequestRec, Key, Value); end; class procedure THTTPDMethods.set_headers_out_ContentEncoding( const ARequestRec: PHTTPDRequest; const AValue: UTF8String); begin CheckRegister; GHTTPDImpl.set_headers_out_ContentEncoding(ARequestRec, AValue); end; class procedure THTTPDMethods.set_headers_out_ContentLength( const ARequestRec: PHTTPDRequest; AValue: Integer); begin CheckRegister; GHTTPDImpl.set_headers_out_ContentLength(ARequestRec, AValue); end; class procedure THTTPDMethods.set_headers_out_ContentType( const ARequestRec: PHTTPDRequest; const AType: UTF8String); begin CheckRegister; GHTTPDImpl.set_headers_out_ContentType(ARequestRec, AType); end; class procedure THTTPDMethods.set_location(const ARequestRec: PHTTPDRequest; const AValue: UTF8String); begin CheckRegister; GHTTPDImpl.set_headers_out_location(ARequestRec, AValue); end; class procedure THTTPDMethods.set_status(const ARequestRec: PHTTPDRequest; ACode: Integer); begin CheckRegister; GHTTPDImpl.set_status(ARequestRec, ACode); end; class function THTTPDMethods.write_buffer(const ARequestRec: PHTTPDRequest; var Buffer; Count: Integer): Integer; begin CheckRegister; Result := GHTTPDImpl.write_buffer(ARequestRec, Buffer, Count); end; class function THTTPDMethods.write_string(const ARequestRec: PHTTPDRequest; const AValue: UTF8String): Integer; begin CheckRegister; Result := GHTTPDImpl.write_string(ARequestRec, AValue); end; class function THTTPDMethods.get_APR_HOOK_FIRST: Integer; begin CheckRegister; Result := GHTTPDImpl.get_APR_HOOK_FIRST; end; class function THTTPDMethods.get_APR_HOOK_LAST: Integer; begin CheckRegister; Result := GHTTPDImpl.get_APR_HOOK_LAST; end; class function THTTPDMethods.get_APR_HOOK_MIDDLE: Integer; begin CheckRegister; Result := GHTTPDImpl.get_APR_HOOK_MIDDLE; end; class function THTTPDMethods.get_APR_HOOK_REALLY_FIRST: Integer; begin CheckRegister; Result := GHTTPDImpl.get_APR_HOOK_REALLY_FIRST; end; class function THTTPDMethods.get_APR_HOOK_REALLY_LAST: Integer; begin CheckRegister; Result := GHTTPDImpl.get_APR_HOOK_REALLY_LAST; end; class function THTTPDMethods.get_AP_DECLINED: Integer; begin CheckRegister; Result := GHTTPDImpl.get_AP_DECLINED; end; class function THTTPDMethods.get_AP_DONE: Integer; begin CheckRegister; Result := GHTTPDImpl.get_AP_DONE; end; class function THTTPDMethods.get_AP_OK: Integer; begin CheckRegister; Result := GHTTPDImpl.get_AP_OK; end; { HTTPDInit } class function THTTPDInit.GetModuleName: PUTF8Char; begin Result := PUTF8Char(FModuleName); end; class procedure THTTPDInit.InitModule(const ARegisterHooksProc: TRegisterHooksProc; const AModuleData: TModuleData; const AHandlerName: UTF8String); var LModuleName: string; LHandlerName: UTF8String; begin Assert(Assigned(ARegisterHooksProc)); Assert(AModuleData <> nil); CheckRegister; // Set global variables // Extract module name SetLength(LModuleName, MAX_PATH+1); SetLength(LModuleName, GetModuleFileName(HInstance, PChar(LModuleName), Length(LModuleName))); LModuleName := ExtractFileName(string(LModuleName)); if AHandlerName <> '' then LHandlerName := AHandlerName else begin // If no handler name provided, generate one from dll name LHandlerName := UTF8String(Lowercase(ChangeFileExt(LModuleName, '-handler'))); {do not localize} end; FModuleName := UTF8String(LowerCase(LModuleName)); FHandlerName := LHandlerName; FModuleData := AModuleData; FRegisterHooksProc := ARegisterHooksProc; // Initialize module data GHTTPDImpl.InitModule; end; end.
unit SimpleScriptObj; interface uses Classes, Sample_TLB, SiteComp, HTTPProd, WebAuto; type TSimpleScriptObject = class(TComponent, IGetScriptObject, IWebVariableName) private FSampleValue: string; protected { IWebVariableName } function GetVariableName: string; { IGetScriptObject } function GetScriptObject: IDispatch; published property SampleValue: string read FSampleValue write FSampleValue; end; TSimpleScriptObjectWrapper = class(TScriptObject, ISimpleScriptObjectWrapper) private FSimpleScriptObject: TSimpleScriptObject; protected { ISimpleScriptObjectWrapper } function Get_SampleValue: WideString; safecall; public constructor Create(ASimpleScriptObject: TSimpleScriptObject); end; var SampleComServer: TAbstractScriptComServerObject; implementation uses ActiveX, SysUtils; type TSampleComServer = class(TAbstractScriptComServerObject) protected function ImplGetTypeLib: ITypeLib; override; end; function TSampleComServer.ImplGetTypeLib: ITypeLib; begin if LoadRegTypeLib(LIBID_Sample, 1, 0, 0, Result) <> S_OK then Result := nil; end; { TSimpleScriptObjectWrapper } constructor TSimpleScriptObjectWrapper.Create(ASimpleScriptObject: TSimpleScriptObject); begin inherited Create; FSimpleScriptObject := ASimpleScriptObject; end; function TSimpleScriptObjectWrapper.Get_SampleValue: WideString; begin Result := FSimpleScriptObject.SampleValue; end; { TSimpleScriptObject } function TSimpleScriptObject.GetScriptObject: IDispatch; begin Result := TSimpleScriptObjectWrapper.Create(Self); end; function TSimpleScriptObject.GetVariableName: string; begin Result := Self.Name; end; initialization SampleComServer := TSampleComServer.Create; SampleComServer.RegisterScriptClass(TSimpleScriptObjectWrapper, Class_SimpleScriptObjectWrapper); finalization FreeAndNil(SampleComServer); end.
unit uSalePromotionEditor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, Buttons,uConst,uTC,ADODB,uDBuitls; type TEditor=(TESaleAdd,TESaleModify); TfrmEditor = class(TForm) lblStart: TLabel; dtpStart: TDateTimePicker; lblEnd: TLabel; dtpEnd: TDateTimePicker; lblPromotionType: TLabel; cbbPromotionType: TComboBox; lblPromotion: TLabel; edtDiscountPrice: TEdit; lblUnit: TLabel; lblSetDiscount: TLabel; edtDiscount: TEdit; pnlTop: TPanel; pnlButtom: TPanel; btnOK: TButton; btnCancel: TButton; lbl1: TLabel; edtPtype: TEdit; lbl2: TLabel; edtBtype: TEdit; btnPtype: TSpeedButton; btnBtype: TSpeedButton; lblOrgPriceValue: TLabel; lblOrgPrice: TLabel; procedure cbbPromotionTypeChange(Sender: TObject); procedure edtDiscountChange(Sender: TObject); procedure edtDiscountPriceKeyPress(Sender: TObject; var Key: Char); procedure btnPtypeClick(Sender: TObject); procedure btnBtypeClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure edtPtypeKeyPress(Sender: TObject; var Key: Char); procedure edtPtypeExit(Sender: TObject); procedure edtBtypeExit(Sender: TObject); procedure edtBtypeKeyPress(Sender: TObject; var Key: Char); procedure FormCreate(Sender: TObject); procedure edtPtypeDblClick(Sender: TObject); procedure edtBtypeDblClick(Sender: TObject); private { Private declarations } ResultPtypeRecord:TResultRecord; ResultBtypeRecord:TResultRecord; ASql : String; procedure IniView; function CheckValid:Boolean; function GetOrgprice(ptypeid,btypeid:String):double; procedure SetOrgPrice; procedure ClearTC; procedure UpdateStandard(const ptypeid:String;Sale:Boolean); public { Public declarations } EditMode:TEditor; Spentity:TSalePromotion; end; var frmEditor: TfrmEditor; implementation {$R *.dfm} procedure TfrmEditor.cbbPromotionTypeChange(Sender: TObject); begin edtDiscount.Visible:=(cbbPromotionType.ItemIndex =1); edtDiscountPrice.Enabled :=(cbbPromotionType.ItemIndex =0); edtDiscountPrice.Text := ''; lblSetDiscount.Visible := edtDiscount.Visible; end; procedure TfrmEditor.edtDiscountChange(Sender: TObject); var orgPrice:double; disCount:double; begin orgPrice:= 0; disCount := strtofloatdef(Trim(edtDiscount.Text),0.0); edtDiscountPrice.Text := floatToStr(orgPrice * disCount); end; procedure TfrmEditor.edtDiscountPriceKeyPress(Sender: TObject; var Key: Char); begin if not (key in ['0'..'9','.',#8]) then key:=#0; if (key='.') and (Pos('.',edtDiscountPrice.Text)>0) then key:=#0; end; procedure TfrmEditor.IniView; begin if EditMode = TESaleAdd then begin edtPtype.Text :=''; edtBtype.Text :=''; dtpStart.DateTime := Now; dtpEnd.DateTime := Now; edtDiscountPrice.Text :=''; edtDiscount.Text :=''; lblSetDiscount.Visible := False; edtDiscount.Visible := False; lblOrgPriceValue.Caption := '0'; end else begin edtPtype.Text := Spentity.PFullName ; edtBtype.Text := Spentity.BFullName ; dtpStart.DateTime := Spentity.StartDate; dtpEnd.DateTime := Spentity.EndDate; edtDiscountPrice.Text := floatTostr(Spentity.DiscountPrice);//-0.001); edtDiscount.Text :=''; lblOrgPriceValue.Caption := floatTostr(Spentity.PPrice); lblSetDiscount.Visible := False; edtDiscount.Visible := False; btnPtype.Enabled := False; edtPtype.Enabled := False; end; end; procedure TfrmEditor.btnPtypeClick(Sender: TObject); begin frmTC := TfrmTC.Create(Self); frmTC.Basictype := btPtype; frmTC.SearchStr := Trim(edtPtype.Text); if frmTC.ShowModal=mrOK then begin Self.ResultPtypeRecord := frmTC.ResultRecord; edtPtype.Text := Self.ResultPtypeRecord.fullname; end; frmTC.Free; SetOrgPrice; end; procedure TfrmEditor.btnBtypeClick(Sender: TObject); begin frmTC := TfrmTC.Create(Self); frmTC.Basictype := btBtype; frmTC.SearchStr := Trim(edtBtype.Text); if frmTC.ShowModal=mrOK then begin Self.ResultBtypeRecord := frmTC.ResultRecord; edtBtype.Text := Self.ResultBtypeRecord.fullname; end; frmTC.Free; SetOrgPrice; end; procedure TfrmEditor.btnCancelClick(Sender: TObject); begin Self.Close; Self.ModalResult := mrOk; end; procedure TfrmEditor.btnOKClick(Sender: TObject); var tempDataset,existsDataset,dataset:TADODATASet; atempSql:string; temSpentity:TSalePromotion ; price:Double; tempptypeid,tempbtypeid,tempspid:string; procedure AddSPtoDB(SpEntity:TSalePromotion); begin if (not SpEntity.IStoAllBtype) or (SpEntity.Btypeid=ALLBTYPEID) then begin //更改商品全名 // if Pos('【促】',SpEntity.PFullName)=0 then // begin // ASql:='update ptype set FullName=''【促】'+SpEntity.PFullName+''' where typeid='''+SpEntity.PTypeid+''''; // DbHelper.Execute(ASql,dataset); // end // else // begin // SpEntity.PFullName := Copy(SpEntity.PFullName,POS('】',SpEntity.PFullName)+2,Length(SpEntity.PFullName)); // end; end; UpdateStandard(SpEntity.PTypeid,True); if SpEntity.Btypeid<>'00000' then begin //修改跟踪价格 ASql := 'if not Exists(select * from price where ptypeid='''+SpEntity.PTypeid+''' and btypeid='''+SpEntity.Btypeid+''')' + ' begin insert into price(ptypeid,btypeid,costprice,saleprice,discount,remarked) values('''+SpEntity.PTypeid+''','''+SpEntity.Btypeid+''',0,'+floattostr(SpEntity.DiscountPrice)+',1.0,0) end'+ ' else begin update price set saleprice='+floattostr(SpEntity.DiscountPrice)+' where ptypeid='''+SpEntity.PTypeid+''' and btypeid='''+SpEntity.Btypeid+''' end'; DbHelper.Execute(ASql,dataset); end; //插入记录 ASql:= ' insert into SalesPromotion(PTypeId,BTypeId,OrgPrice,usercode,OrgFullName,BFullName,starttime,endtime,DiscountPrice,Invalid,ISToAllBtype,Visible) ' + 'values('''+SpEntity.PTypeid+''','''+SpEntity.Btypeid+''','+floattostr(SpEntity.PPrice) +',''' + SpEntity.PuserCode+''','''+SpEntity.PFullName+''','''+ SpEntity.BFullName +''','''+ datetostr(SpEntity.StartDate)+''','''+ datetostr(SpEntity.EndDate)+''','+ floattostr(SpEntity.DiscountPrice) +','+booltostr(SpEntity.Invalid)+','+booltostr(SpEntity.IStoAllBtype)+','+booltostr(SpEntity.Visible)+')'; DbHelper.Execute(ASql,dataset); end; procedure update(ASpEntity:TSalePromotion); begin //修改SalesPromotion信息 ASql := 'update SalesPromotion set starttime='''+DateToStr(ASpEntity.StartDate)+''',endtime='''+DateToStr(ASpEntity.EndDate)+ ''',DiscountPrice='+floatTostr(ASpEntity.DiscountPrice)+',IsToAllBtype='+booltostr(ASpEntity.IStoAllBtype)+ ',Visible='+booltostr(ASpEntity.Visible)+',BFullName='''+ ASpEntity.BFullName +''',BTypeId='''+ASpEntity.Btypeid+''',OrgPrice='+ floatTostr(ASpEntity.PPrice)+ ' where spid='''+ASpEntity.SpId+''''; dataset:=nil; DBHelper.Execute(ASql,dataset); //price价格的saleprice设置有触发器 ASql := 'update SalesPromotion set Invalid=1 where spid='''+ASpEntity.SpId+''''; dataset:=nil; DBHelper.Execute(ASql,dataset); ASQl := 'update price set saleprice='+floattostr(ASpEntity.DiscountPrice)+' where ptypeid='''+ASpEntity.PTypeid+''' and btypeid='''+ASpEntity.Btypeid+''''; DBHelper.Execute(ASql,dataset); dataset:=nil; ASql := 'update SalesPromotion set Invalid=0 where spid='''+ASpEntity.SpId+''''; DBHelper.Execute(ASql,dataset); end; procedure GetSPFromUI(var ASpentity:TSalePromotion); begin if ASpentity=nil then ASpentity:=TSalePromotion.Create; ASpentity.SpId:=''; ASpentity.PuserCode := Self.ResultPtypeRecord.usercode; ASpentity.PFullName := Self.ResultPtypeRecord.fullname; ASpentity.PTypeid := Self.ResultPtypeRecord.typeid; ASpentity.BFullName := Self.ResultBtypeRecord.fullname; ASpentity.Btypeid := Self.ResultBtypeRecord.typeid; ASpentity.PPrice := Strtofloatdef(Self.lblOrgPriceValue.caption,0); ASpentity.DiscountPrice := Strtofloatdef(Trim(edtDiscountPrice.Text),0);//+0.001; ASpentity.IStoAllBtype := ASpentity.Btypeid =ALLBTYPEID; ASpentity.Visible := not ASpentity.IStoAllBtype; ASpentity.StartDate := dtpStart.Date; ASpentity.EndDate := dtpEnd.Date; end; procedure GetModifySPFromUI(var ModifySpentity:TSalePromotion); begin ModifySpentity:=TSalePromotion.Create; if Self.ResultBtypeRecord.typeid<>'' then begin ModifySpentity.BFullName := Self.ResultBtypeRecord.fullname; ModifySpentity.Btypeid := Self.ResultBtypeRecord.typeid; end else begin ModifySpentity.BFullName := Spentity.BFullName; ModifySpentity.Btypeid := Spentity.Btypeid; end; ModifySpentity.PPrice := Strtofloatdef(Self.lblOrgPriceValue.caption,0); ModifySpentity.DiscountPrice := Strtofloatdef(Trim(edtDiscountPrice.Text),0);//+0.001; ModifySpentity.IStoAllBtype := ModifySpentity.Btypeid =ALLBTYPEID; ModifySpentity.Invalid := True; ModifySpentity.Visible := not ModifySpentity.IStoAllBtype; ModifySpentity.StartDate := dtpStart.Date; ModifySpentity.EndDate := dtpEnd.Date; end; procedure copySP(ModifySpentity:TSalePromotion); begin Spentity.PPrice := ModifySpentity.PPrice; Spentity.DiscountPrice := ModifySpentity.DiscountPrice; Spentity.BFullName := ModifySpentity.BFullName; Spentity.Btypeid := ModifySpentity.Btypeid; Spentity.IStoAllBtype := ModifySpentity.IStoAllBtype; Spentity.StartDate := ModifySpentity.StartDate; Spentity.EndDate := ModifySpentity.EndDate end; procedure loopInsertAllBtype; begin atempSql := 'select * from btype where sonnum=0 and typeid<>''00000'''; tempDataset := TADODATASet.Create(nil); DBHelper.Execute(atempSql,tempDataset); with tempDataset do begin if not IsEmpty then begin First; while not eof do begin Spentity.BFullName := FieldValues['FullName']; Spentity.Btypeid := FieldValues['typeid']; Spentity.Visible := False; AddSPtoDB(Spentity); next; end; end; end; tempDataset.Free; end; begin dataset := nil; if not CheckValid then Exit; if EditMode = TESaleAdd then begin try GetSPFromUI(Self.Spentity); if Spentity.IStoAllBtype then begin //插入一条 ‘全名’ Spentity.Visible := True; AddSPtoDB(Spentity); loopInsertAllBtype; end else begin existsDataset:=TADODataSet.Create(nil); ASql := 'select * from SalesPromotion where ptypeid='''+SpEntity.PTypeid+''' and btypeid='''+SpEntity.Btypeid+''' and invalid=0' ; DbHelper.Execute(ASql,existsDataset); if existsDataset.Recordset.RecordCount>0 then begin if Application.MessageBox('该商品已进行促销,是否继续','提示',MB_YESNO)=idno then begin existsDataset.Free; Exit; end; end; existsDataset.Free; AddSPtoDB(Spentity); end; Self.Spentity.Free; Self.Spentity:=nil; except Application.MessageBox('信息添加异常!','提示'); ClearTC; edtPtype.Text:=''; edtBtype.Text:=''; Exit; end; Application.MessageBox('信息添加成功!','提示'); end else begin try GetModifySPFromUI(temSpentity); if Spentity.IStoAllBtype then begin if temSpentity.IStoAllBtype then begin copySP(temSpentity); Spentity.Visible := True; update(Spentity); Asql := 'Select * from salespromotion where invalid=0 and ptypeid='''+Spentity.PTypeid+''' and spid<>'+Spentity.SpId; tempDataset:= TADODataSet.Create(nil); DBHelper.Execute(ASql,tempDataset); with tempDataset do begin if not IsEmpty then begin First; while not eof do begin temSpentity.BFullName := FieldValues['BFullName']; temSpentity.Btypeid := FieldValues['btypeid']; temSpentity.SpId:= FieldValues['spid']; temSpentity.PuserCode := FieldValues['usercode']; temSpentity.PFullName := FieldValues['OrgFullName']; temSpentity.PTypeid := FieldValues['ptypeid']; temSpentity.Visible := False; update(temSpentity); next; end; end; end; dataset.Free; end else begin Asql := 'Select * from salespromotion where invalid=0 and ptypeid='''+Spentity.PTypeid+''' and spid<>'+Spentity.SpId; dataset:= TADODataSet.Create(nil); DBHelper.Execute(ASql,dataset); with dataset do begin if not IsEmpty then begin First; while not eof do begin price:=strtofloatdef(FieldValues['OrgPrice'],0); tempptypeid := FieldValues['ptypeid']; tempbtypeid := FieldValues['btypeid']; tempspid:= FieldValues['spid']; ASql := 'delete Salespromotion where spid='''+tempspid+''''; DBHelper.Execute(ASql,tempDataset); ASql := 'update price set saleprice='+floatToStr(price)+' where ptypeid='''+tempptypeid+''' and btypeid='''+tempbtypeid+''''; DBHelper.Execute(ASql,tempDataset); UpdateStandard(tempptypeid,False); next; end; end; end; dataset.Free; copySP(temSpentity); Spentity.Visible := True; update(Spentity); end; end else begin if temSpentity.IStoAllBtype then begin copySP(temSpentity); update(Spentity); loopInsertAllBtype; end else begin copySP(temSpentity); update(Spentity); end; end; except Application.MessageBox('信息修改异常!','提示'); Exit; end; Application.MessageBox('信息修改成功!','提示'); Self.ModalResult := mrOk; end; end; function TfrmEditor.CheckValid: Boolean; var currentDate:TDate; startDate:TDate; endDate:TDate; begin if EditMode = TESaleAdd then begin if Self.ResultPtypeRecord.typeid ='' then begin Application.MessageBox('未选择商品!','提示'); Result:=False; Exit; end; if Self.ResultBtypeRecord.typeid ='' then begin Application.MessageBox('未选择客户!','提示'); Result:=False; Exit; end; end else begin if (Self.Spentity.PTypeid='') and (Self.ResultPtypeRecord.typeid ='') then begin Application.MessageBox('未选择商品!','提示'); Result:=False; Exit; end; if (Self.Spentity.BTypeid='') and (Self.ResultBtypeRecord.typeid ='') then begin Application.MessageBox('未选择客户!','提示'); Result:=False; Exit; end; end; currentDate:=Now; startDate := dtpStart.Date; endDate := dtpEnd.Date; if startDate>endDate then begin Application.MessageBox('促销开始日期不能大于结束日期,请重新设置!','提示'); dtpStart.SetFocus; Result:=False; Exit; end; if currentDate>endDate then begin Application.MessageBox('促销结束日期已经小于当前日期,设置无效,请重新设置!','提示'); dtpEnd.SetFocus; Result:=False; Exit; end; if currentDate>endDate then begin Application.MessageBox('促销结束日期已经大于当前日期,设置无效,请重新设置!','提示'); dtpEnd.SetFocus; Result:=False; Exit; end; if Trim(edtDiscountPrice.Text)='' then begin Application.MessageBox('请设置促销价!','提示'); edtDiscountPrice.SetFocus; Result:=False; Exit; end; if (Pos('.',edtDiscountPrice.Text)>0) and (Length(edtDiscountPrice.Text)-Pos('.',edtDiscountPrice.Text)>2) then begin Application.MessageBox('促销价只能保留两位小数!','提示'); edtDiscountPrice.SetFocus; Result:=False; Exit; end; Result:=True; end; procedure TfrmEditor.FormShow(Sender: TObject); begin IniView; end; function TfrmEditor.GetOrgprice(ptypeid, btypeid: String): double; var saleprice:String; dataset:TADODataset; begin if (ptypeid='') or (btypeid='') then begin Result := 0; Exit; end; ASql := 'select saleprice from price where ptypeid='''+ptypeid+'''' +' and btypeid='''+btypeid+'''' ; dataset:=TADODataset.Create(nil); DBHelper.Execute(ASQl,dataset); if not dataset.IsEmpty then begin dataset.First; saleprice := dataset.FieldValues['saleprice']; end; dataset.Free; Result:=strtofloatDef(saleprice,0.0); end; procedure TfrmEditor.SetOrgPrice; begin if EditMode = TESaleAdd then begin lblOrgPriceValue.Caption := floatToStr(GetOrgprice(Self.ResultPtypeRecord.typeid,Self.ResultBtypeRecord.typeid)); end else begin if (Self.ResultBtypeRecord.typeid<>'') then lblOrgPriceValue.Caption := floatToStr(GetOrgprice(Self.Spentity.PTypeid,Self.ResultBtypeRecord.typeid)) else lblOrgPriceValue.Caption := floatToStr(GetOrgprice(Self.Spentity.PTypeid,Self.Spentity.Btypeid)); end; end; procedure TfrmEditor.edtPtypeKeyPress(Sender: TObject; var Key: Char); var UserInput:string; tempDataset:TADODataSet; begin if Key=#13 then begin UserInput:=Trim(edtPtype.Text); if UserInput='' then btnPtype.Click; ASql :='select * from ptype where fullname like ''%'+UserInput+'%'' or usercode like ''%'+UserInput+'%'' or Namepy like ''%'+UserInput+'%'''; try tempDataset := TADODataSet.Create(nil); DBhelper.Execute(ASql,tempDataset); if tempDataset.Recordset.RecordCount = 1 then begin with tempDataset do begin if not IsEmpty then begin First; ResultPtypeRecord.fullname := FieldValues['FullName']; ResultPtypeRecord.typeid := FieldValues['typeid']; ResultPtypeRecord.usercode := FieldValues['usercode']; edtPtype.Text := Self.ResultPtypeRecord.fullname; end; end; end else btnPtype.Click; finally tempDataset.Free; end; end; end; procedure TfrmEditor.edtPtypeExit(Sender: TObject); begin if ResultPtypeRecord.typeid='' then edtPtype.Text :=''; if edtPtype.Text<> ResultPtypeRecord.fullname then begin ResultPtypeRecord.typeid:=''; ResultPtypeRecord.usercode :=''; ResultPtypeRecord.fullname:=''; edtPtype.Text :=''; end; end; procedure TfrmEditor.edtBtypeExit(Sender: TObject); begin if ResultBtypeRecord.typeid='' then edtBtype.Text :=''; if edtbtype.Text<> ResultbtypeRecord.fullname then begin ResultbtypeRecord.typeid:=''; ResultbtypeRecord.usercode :=''; ResultbtypeRecord.fullname:=''; edtBtype.Text :=''; end; end; procedure TfrmEditor.edtBtypeKeyPress(Sender: TObject; var Key: Char); var UserInput:string; tempDataset:TADODataSet; begin if Key=#13 then begin UserInput:=Trim(edtBtype.Text); if UserInput='' then btnbtype.Click; ASql :='select * from Btype where fullname like ''%'+UserInput+'%'' or usercode like ''%'+UserInput+'%'' or Namepy like ''%'+UserInput+'%'''; try tempDataset := TADODataSet.Create(nil); DBhelper.Execute(ASql,tempDataset); if tempDataset.Recordset.RecordCount = 1 then begin with tempDataset do begin if not IsEmpty then begin First; ResultBtypeRecord.fullname := FieldValues['FullName']; ResultBtypeRecord.typeid := FieldValues['typeid']; ResultBtypeRecord.usercode := FieldValues['usercode']; edtBtype.Text := Self.ResultBtypeRecord.fullname; end; end; end else btnbtype.Click; finally tempDataset.Free; end; end; end; procedure TfrmEditor.ClearTC; begin ResultPtypeRecord.typeid:=''; ResultPtypeRecord.usercode:=''; ResultPtypeRecord.fullname:=''; ResultBtypeRecord.typeid:=''; ResultBtypeRecord.fullname:=''; ResultBtypeRecord.usercode:=''; end; procedure TfrmEditor.FormCreate(Sender: TObject); begin ClearTC; end; procedure TfrmEditor.edtPtypeDblClick(Sender: TObject); begin btnptype.Click; end; procedure TfrmEditor.edtBtypeDblClick(Sender: TObject); begin btnBtype.Click; end; procedure TfrmEditor.UpdateStandard(const ptypeid: String; Sale: Boolean); var tempSql,OrgStandard:String; temp:TADODataSet; begin tempSql := 'select standard from ptype where typeid='''+ptypeid+''''; temp:=TADODataSet.Create(nil); DBhelper.Execute(tempSql,temp); with temp do begin if not IsEmpty then begin First; while not eof do begin OrgStandard := FieldValues['Standard']; next; end; end; end; temp.Free; temp := nil; if Sale then begin if Pos('【促】',OrgStandard)>0 then Exit else begin OrgStandard:='【促】'+OrgStandard; tempSql := 'update ptype set Standard='''+OrgStandard+''' where typeid='''+ptypeid+''''; DBhelper.Execute(tempSql,temp); end; end else begin if Pos('【促】',OrgStandard)>0 then begin OrgStandard:= Copy(OrgStandard,7,Length(OrgStandard)-6); tempSql := 'update ptype set Standard='''+OrgStandard+''' where typeid='''+ptypeid+''''; DBhelper.Execute(tempSql,temp); end; end; end; end.
{ Copyright (C) Alexey Torgashin, uvviewsoft.com License: MPL 2.0 or LGPL } unit ATSynEdit_Cmp_RenderHTML; {$mode objfpc}{$H+} interface uses Graphics; procedure CanvasTextOutHTML(C: TCanvas; X, Y: integer; const Text: string); function CanvasTextWidthHTML(C: TCanvas; const Text: string): integer; implementation uses SysUtils, StrUtils, gstack; type TMyColorStack = specialize TStack<TColor>; //realloc dyn-array by Delta elements at once const CapacityDelta = 40; type TCharAtr = record AtrChar: Widechar; AtrBold, AtrItalic, AtrUnder, AtrStrike: boolean; AtrColor: TColor; end; TCharAtrArray = array of TCharAtr; function AtrToFontStyles(const Atr: TCharAtr): TFontStyles; begin Result:= []; if Atr.AtrBold then Include(Result, fsBold); if Atr.AtrItalic then Include(Result, fsItalic); if Atr.AtrUnder then Include(Result, fsUnderline); if Atr.AtrStrike then Include(Result, fsStrikeOut); end; function AtrToFontColor(const Atr: TCharAtr; DefColor: TColor): TColor; begin Result:= Atr.AtrColor; if Result=clNone then Result:= DefColor; end; function AtrSameStyles(const A1, A2: TCharAtr): boolean; begin Result:= (A1.AtrBold=A2.AtrBold) and (A1.AtrItalic=A2.AtrItalic) and (A1.AtrUnder=A2.AtrUnder) and (A1.AtrStrike=A2.AtrStrike) and (A1.AtrColor=A2.AtrColor); end; function HexCodeToInt(N: integer): integer; begin case N of ord('0')..ord('9'): Result:= N-Ord('0'); ord('a')..ord('f'): Result:= N-Ord('a')+10; ord('A')..ord('F'): Result:= N-Ord('A')+10; else Result:= 0; end; end; function _IsHexDigitCode(N: integer): boolean; begin case N of Ord('0')..Ord('9'), Ord('a')..Ord('f'), Ord('A')..Ord('F'): Result:= true; else Result:= false; end; end; function HtmlTokenToColor(const S: UnicodeString): TColor; var NLen, i: integer; N1, N2, N3: integer; begin Result:= clNone; NLen:= Length(S); for i:= 1 to NLen do if not _IsHexDigitCode(Ord(S[i])) then exit; case NLen of 6, 8: begin N1:= HexCodeToInt(ord(S[1]))*16 + HexCodeToInt(ord(S[2])); N2:= HexCodeToInt(ord(S[3]))*16 + HexCodeToInt(ord(S[4])); N3:= HexCodeToInt(ord(S[5]))*16 + HexCodeToInt(ord(S[6])); Result:= RGBToColor(N1, N2, N3); end; 3, 4: begin N1:= HexCodeToInt(ord(S[1]))*17; N2:= HexCodeToInt(ord(S[2]))*17; N3:= HexCodeToInt(ord(S[3]))*17; Result:= RGBToColor(N1, N2, N3); end; end; end; function _Unicode_StartsStr(const Sub, S: UnicodeString): boolean; begin Result:= (Length(S)>=Length(Sub)) and (Copy(S, 1, Length(Sub))=Sub); end; function _Unicode_EndsStr(const Sub, S: UnicodeString): boolean; begin Result:= (Length(S)>=Length(Sub)) and (Copy(S, Length(S)-Length(Sub)+1, Length(Sub))=Sub); end; procedure CalcAtrArray(const Text: string; out Atr: TCharAtrArray; out AtrLen: integer); var ColorStack: TMyColorStack; SWide, STag: UnicodeString; NLen: integer; bBold, bItalic, bUnder, bStrike, bTagClosing, bTagKnown: boolean; NColor: TColor; i, j, NCharPos: integer; begin AtrLen:= 0; Atr:= nil; if Text='' then exit; ColorStack:= nil; SWide:= UTF8Decode(Text); SetLength(Atr, CapacityDelta); bBold:= false; bItalic:= false; bUnder:= false; bStrike:= false; bTagClosing:= false; NColor:= clNone; NLen:= Length(SWide); i:= 0; repeat Inc(i); if i>NLen then Break; //tag is found if SWide[i]='<' then begin bTagKnown:= false; bTagClosing:= false; STag:= ''; j:= i+1; while (j<=NLen) and (SWide[j]<>'>') do Inc(j); if j<=NLen then begin bTagClosing:= SWide[i+1]='/'; if bTagClosing then STag:= Copy(SWide, i+2, j-i-2) else STag:= Copy(SWide, i+1, j-i-1); end; if not bTagClosing and _Unicode_StartsStr('font color="#', STag) and _Unicode_EndsStr('"', STag) then begin bTagKnown:= true; NCharPos:= Pos('#', STag); STag:= Copy(STag, NCharPos+1, Length(STag)-NCharPos-1); if not Assigned(ColorStack) then ColorStack:= TMyColorStack.Create; ColorStack.Push(NColor); NColor:= HtmlTokenToColor(STag); end else if bTagClosing and (STag='font') then begin bTagKnown:= true; if Assigned(ColorStack) and not ColorStack.IsEmpty() then begin NColor:= ColorStack.Top; ColorStack.Pop; end else NColor:= clNone; end else case STag of 'b': begin bTagKnown:= true; bBold:= not bTagClosing; end; 'i': begin bTagKnown:= true; bItalic:= not bTagClosing; end; 'u': begin bTagKnown:= true; bUnder:= not bTagClosing; end; 's': begin bTagKnown:= true; bStrike:= not bTagClosing; end; end; if bTagKnown then begin i:= j; Continue; end; end; //text out of tags if AtrLen>=Length(Atr) then SetLength(Atr, Length(Atr)+CapacityDelta); Inc(AtrLen); with Atr[AtrLen-1] do begin AtrChar:= SWide[i]; AtrBold:= bBold; AtrItalic:= bItalic; AtrUnder:= bUnder; AtrStrike:= bStrike; AtrColor:= NColor; end; until false; if Assigned(ColorStack) then FreeAndNil(ColorStack); end; procedure CanvasProcessHTML(C: TCanvas; X, Y: integer; const Text: string; DoTextOut: boolean; out TextWidth: integer); var AtrLen: integer; Atr: TCharAtrArray; SFragment: UnicodeString; SFragmentA: string; NDefColor: TColor; ch: Widechar; NWidth, i: integer; begin TextWidth:= 0; CalcAtrArray(Text, Atr, AtrLen); if AtrLen=0 then exit; SFragment:= ''; C.Brush.Style:= bsClear; //fix overlapping of fragments NDefColor:= C.Font.Color; for i:= 0 to AtrLen-1 do begin ch:= Atr[i].AtrChar; if (i=0) or AtrSameStyles(Atr[i], Atr[i-1]) then SFragment+= ch else begin C.Font.Style:= AtrToFontStyles(Atr[i-1]); C.Font.Color:= AtrToFontColor(Atr[i-1], NDefColor); SFragmentA:= UTF8Encode(SFragment); if DoTextOut then C.TextOut(X, Y, SFragmentA); NWidth:= C.TextWidth(SFragmentA); Inc(X, NWidth); Inc(TextWidth, NWidth); SFragment:= ch; end; end; if SFragment<>'' then begin C.Font.Style:= AtrToFontStyles(Atr[AtrLen-1]); C.Font.Color:= AtrToFontColor(Atr[AtrLen-1], NDefColor); SFragmentA:= UTF8Encode(SFragment); if DoTextOut then C.TextOut(X, Y, SFragmentA); NWidth:= C.TextWidth(SFragmentA); Inc(X, NWidth); Inc(TextWidth, NWidth); end; C.Font.Style:= []; C.Font.Color:= NDefColor; end; procedure CanvasTextOutHTML(C: TCanvas; X, Y: integer; const Text: string); var NWidth: integer; begin CanvasProcessHTML(C, X, Y, Text, true, NWidth); end; function CanvasTextWidthHTML(C: TCanvas; const Text: string): integer; begin CanvasProcessHTML(C, 0, 0, Text, false, Result); end; end.
program triangle2; uses crt; { //BUT : Fait un triangle2 //ENTREE : La taille du triangle2 //SORTIE : Un triangle de la taille désirée VAR taille, i, j : ENTIER DEBUT ECRIRE 'Entrez la taille du triangle' LIRE taille //Récupération de la taille du triangle POUR i DE 1 A taille FAIRE //Boucle pour ecrire les ligne (diminue la longeur de la ligne à chaque itération) POUR j de 1 A (taille - i + 1) FAIRE //Bouble qui écrite le contenu de la ligne (diminue la longeur de la ligne à chaque itération) ECRIRE(i-1) //Le chiffre écrit est i - 1 pour commencer à 0 au lieu de 1 FINPOUR FINPOUR FIN } {CONST taille = 10;} VAR taille, i, j : INTEGER; BEGIN clrscr; writeln('Entrez la taille du triangle'); readln(taille); FOR i := 1 TO taille DO BEGIN FOR j := 1 TO (taille -i + 1) DO BEGIN write(i-1); END; writeln(); END; readln(); END.
///////////////////////////////////////////////////////// // // // FlexGraphics library // // Copyright (c) 2002-2009, FlexGraphics software. // // // // Path procedures and functions // // // ///////////////////////////////////////////////////////// unit FlexPath; {$I FlexDefs.inc} interface uses Windows, Classes, FlexUtils; type TPointType = ( ptNode, ptEndNode, ptEndNodeClose, ptControl ); TPointArray = packed array of TPoint; TPointTypeArray = packed array of TPointType; TSelectedArray = packed array of boolean; TRectArray = packed array of TRect; TPathEditFunc = ( pfOffset, {pfDelete, }pfJoin, pfBreak, pfClose, pfToLine, pfToCurve ); TPathEditFuncs = set of TPathEditFunc; PPathEditParams = ^TPathEditParams; TPathEditParams = record {$IFNDEF FG_C10} case TPathEditFunc of pfOffset: ( {$ENDIF} Offset: TPoint; MoveControls: boolean; {$IFNDEF FG_C10} ); {$ENDIF} end; PNearestPoint = ^TNearestPoint; TNearestPoint = record Point: TPoint; Index0: integer; Index1: integer; MinIndex: integer; MinSqrDist: single; CurvePos: single; IsNewMin: boolean; end; PPathFigureInfo = ^TPathFigureInfo; TPathFigureInfo = record FirstNode: integer; LastNode: integer; LastPoint: integer; IsClosed: boolean; IsCurve: boolean; end; TPathFigureInfos = array of TPathFigureInfo; PPathInfo = ^TPathInfo; TPathInfo = record PointCount: integer; IsCurve: boolean; Figures: TPathFigureInfos; end; TRerouteMode = ( rmAlways, rmAsNeeded, rmNever ); PRerouteParams = ^TRerouteParams; TRerouteParams = record RangeA: TRect; RangeB: TRect; Mode: TRerouteMode; Ortogonal: boolean; LinkMinGap: integer; SelfLink: boolean; LinkPointA: TPoint; LinkPointB: TPoint; end; function CalcPath(const Points: TPointArray; const Types: TPointTypeArray; var Range: TRect; Info: PPathInfo = Nil): boolean; function CreatePath(DC: HDC; const Points: TPointArray; const Types: TPointTypeArray; UseClosed, UseNotClosed: boolean; var Complete: boolean; OriginalBezier: boolean = false; Info: PPathInfo = Nil): boolean; function PointOnLine(const p, p0, p1: TPoint; StrokeWidth: integer; ScanLinePoints: TList = Nil; Nearest: PNearestPoint = Nil): boolean; function PointOnPath(const Points: TPointArray; const Types: TPointTypeArray; const Point: TPoint; Stroked, Filled: boolean; StrokeWidth: integer = 0; Nearest: PNearestPoint = Nil; Info: PPathInfo = Nil; LengthPos: PSingle = Nil): boolean; function FlattenPath(var Points: TPointArray; var Types: TPointTypeArray; Curvature: single; Info: PPathInfo = Nil): boolean; function ConnectorReroute(var Points: TPointArray; var PointTypes: TPointTypeArray; const Params: TRerouteParams): boolean; function PathLength(const Points: TPointArray; const Types: TPointTypeArray; Info: PPathInfo = Nil): single; function PathLengthPos(const Points: TPointArray; const Types: TPointTypeArray; PathPos: single; Nearest: PNearestPoint; Info: PPathInfo = Nil): boolean; function FindNearestPathSegment(const Points: TPointArray; const Types: TPointTypeArray; const Point: TPoint; var FirstIndex, NextIndex: integer; Nearest: PNearestPoint = Nil; Info: PPathInfo = Nil; ForInsert: boolean = true): boolean; function InsertPathPoint(var Points: TPointArray; var Types: TPointTypeArray; FirstIndex, NextIndex: integer; const Point: TPoint; StickThreshold: integer = 0; Info: PPathInfo = Nil): integer; function InsertNearestPoint(var Points: TPointArray; var Types: TPointTypeArray; const Point: TPoint; StickThreshold: integer = 0; Info: PPathInfo = Nil): integer; function GetEditPathCaps(const Points: TPointArray; const Types: TPointTypeArray; const Selected: TSelectedArray): TPathEditFuncs; function EditPath(var Points: TPointArray; var Types: TPointTypeArray; const Selected: TSelectedArray; Func: TPathEditFunc; Params: PPathEditParams = Nil): boolean; overload; function EditPath(var Points: TPointArray; var Types: TPointTypeArray; const Indexes: array of integer; Func: TPathEditFunc; Params: PPathEditParams = Nil): boolean; overload; procedure GetPathInfo(const Points: TPointArray; const Types: TPointTypeArray; var Info: TPathInfo); function GetFigureIndex(const Info: TPathInfo; PointIndex: integer): integer; function ChangePathCount(var Points: TPointArray; var Types: TPointTypeArray; Index, Delta: integer): boolean; implementation type TPathFunc = ( pfFlatten, pfOnLine, pfRange, pfPaint, pfLength ); TListPoint = packed record Point: TPoint; PointType: TPointType; end; PListPoints = ^TListPoints; TListPoints = array[0..(MaxInt div SizeOf(TListPoint))-1] of TListPoint; TPointList = class Data: PListPoints; Count: integer; Capacity: integer; Delta: integer; constructor Create(ACapacity: integer = 32); destructor Destroy; override; procedure Grow; procedure Clear; end; PBezierParams = ^TBezierParams; TBezierParams = record case Boolean {OriginalBezier} of False: ( x0, y0: single; x1, y1: single; x2, y2: single; x3, y3: single; p0pos, p3pos: single; ); True: ( OrigPoints: array[0..3] of TPoint; ); end; PPathParams = ^TPathParams; TPathParams = record UseClosed: boolean; UseNotClosed: boolean; Complete: boolean; OriginalBezier: boolean; IsFigureClosed: boolean; p0, p1: TPoint; // points of the current line segment Curvature: single; // [0.0 .. 1.0] Info: PPathInfo; FigureCount: integer; // Total processed figures in ProcessPath case Func: TPathFunc of pfFlatten: ( PointList: TPointList ); pfOnLine: ( CheckPoint: TPoint; StrokeWidth: integer; ScanLine: TList; Nearest: PNearestPoint; IsOnLine: boolean; CurLength: single; LengthPos: PSingle; ); pfLength: ( PathLength: single; PathPos: single; LengthNearest: PNearestPoint ); pfRange: ( Range: PRect ); pfPaint: ( PaintDC: HDC ); end; // TPointList ///////////////////////////////////////////////////////////////// constructor TPointList.Create(ACapacity: integer); begin Capacity := ACapacity; Delta := ACapacity; if Capacity > 0 then GetMem(Data, Capacity * SizeOf(TListPoint)); end; destructor TPointList.Destroy; begin Clear; end; procedure TPointList.Clear; begin FreeMem(Data); Data := Nil; Capacity := 0; end; procedure TPointList.Grow; begin inc(Capacity, Delta); ReallocMem(Data, Capacity*SizeOf(TListPoint)); inc(Delta, Delta); end; // Bezier curve and path routines ///////////////////////////////////////////// function PointOnLine(const p, p0, p1: TPoint; StrokeWidth: integer; ScanLinePoints: TList = Nil; Nearest: PNearestPoint = Nil): boolean; var SqrDist, SqrLength, SqrDist0, SqrDist1, Coeff: single; px, py, p0x, p0y, p1x, p1y: single; R: TRect; InRange: boolean; Index: integer; begin Result := StrokeWidth > 0; if Result then begin // Calculate normalized rect [p0, p1] inflated on StrokeWidth if p0.x < p1.x then begin R.Left := p0.x - StrokeWidth; R.Right := p1.x + StrokeWidth end else begin R.Right := p0.x + StrokeWidth; R.Left := p1.x - StrokeWidth end; if p0.y < p1.y then begin R.Top := p0.y - StrokeWidth; R.Bottom := p1.y + StrokeWidth end else begin R.Bottom := p0.y + StrokeWidth; R.Top := p1.y - StrokeWidth end; // Check that p in R Result := (p.x >= R.Left) and (p.x <= R.Right) and (p.y >= R.Top) and (p.y <= R.Bottom); end; if Result or Assigned(Nearest) then begin // Convert to float values and calculate length px := p.x; py := p.y; p0x := p0.x; p0y := p0.y; p1x := p1.x; p1y := p1.y; SqrLength := (p0x - p1x)*(p0x - p1x) + (p0y - p1y)*(p0y - p1y); SqrDist0 := (p0x - px)*(p0x - px) + (p0y - py)*(p0y - py); SqrDist1 := (p1x - px)*(p1x - px) + (p1y - py)*(p1y - py); // Check point-on-line if SqrLength < 1 then begin // Lenght too small SqrDist := SqrDist0; // There must be SqrDist0 = SqrDist1 Result := Result and (Abs(p.x - p0.x) <= StrokeWidth) and (Abs(p.y - p0.y) <= StrokeWidth); end else begin // Check distance Coeff := SqrLength - SqrDist0 - SqrDist1; SqrDist := Abs(4*SqrDist0*SqrDist1 - Coeff * Coeff) / (4*SqrLength); Result := Result and (SqrDist <= StrokeWidth*StrokeWidth); end; if Assigned(Nearest) then begin Nearest.IsNewMin := false; Index := Nearest.Index0; if (Nearest.MinIndex < 0) or (Nearest.MinSqrDist > SqrDist) then begin // Calculate nearest point if SqrLength = 0 then Coeff := 0 else Coeff := (SqrDist0 - SqrDist1 + SqrLength) / (2*SqrLength); R.Left := p0.x + Round((p1.x - p0.x) * Coeff); R.Top := p0.y + Round((p1.y - p0.y) * Coeff); if p0.x < p1.x then InRange := (R.Left >= p0.x) and (R.Left <= p1.x) else InRange := (R.Left >= p1.x) and (R.Left <= p0.x); if p0.y < p1.y then InRange := InRange and (R.Top >= p0.y) and (R.Top <= p1.y) else InRange := InRange and (R.Top >= p1.y) and (R.Top <= p0.y); if not InRange then begin if SqrDist0 < SqrDist1 then begin SqrDist := SqrDist0; R.Left := p0.x; R.Top := p0.y end else begin SqrDist := SqrDist1; R.Left := p1.x; R.Top := p1.y; Index := Nearest.Index1; end; InRange := (Nearest.MinIndex < 0) or (Nearest.MinSqrDist > SqrDist); end; if InRange then begin Nearest.Point.x := R.Left; Nearest.Point.y := R.Top; Nearest.MinIndex := Index; Nearest.MinSqrDist := SqrDist; Nearest.IsNewMin := true; end; end; end; end; if Assigned(ScanLinePoints) then begin if p1.y < p0.y then InRange := (p.y >= p1.y) and (p.y < p0.y) else InRange := (p.y >= p0.y) and (p.y < p1.y); if InRange then // Add point(s) to ScanList if p0.y = p1.y then begin // Add edge points ScanLinePoints.Insert( ListScanLess(pointer(p0.x), ScanLinePoints.List, ScanLinePoints.Count), pointer(p0.x) ); ScanLinePoints.Insert( ListScanLess(pointer(p1.x), ScanLinePoints.List, ScanLinePoints.Count), pointer(p1.x) ); end else begin // Add intersection point R.Left := p0.x + integer(int64(p1.x - p0.x)*(p.y - p0.y) div (p1.y - p0.y)); ScanLinePoints.Insert( ListScanLess(pointer(R.Left), ScanLinePoints.List, ScanLinePoints.Count), pointer(R.Left) ); end; end; end; procedure ProcessSegment(var Path: TPathParams; Bezier: PBezierParams); var TempBezier: packed record xm, ym: single; case byte of 1: ( A, B, C, AB: single; CheckAB1, CheckAB2: single ); 2: ( Next: TBezierParams ); 3: ( px, py: single; Length, NewLength: single; Coeff: single; ); end; TempList: TList; begin if Assigned(Bezier) then with TempBezier, Bezier^ do if Path.OriginalBezier and (Path.Func = pfPaint) then begin // Draw original bezier curve (GDI) PolyBezierTo(Path.PaintDC, OrigPoints[1], 3); Path.p1 := OrigPoints[3]; Path.p0 := OrigPoints[3]; exit; end else begin // Draw recoursive bezier curve A := y3 - y0; B := x0 - x3; C := A*x0 + B*y0; // Ax + By - C = 0 is line (x0,y0) - (x3,y3) AB := A*A + B*B; CheckAB1 := (A*x1 + B*y1 - C) * Path.Curvature; CheckAB2 := (A*x2 + B*y2 - C) * Path.Curvature; // Check subdivide if (CheckAB1*CheckAB1 >= AB) or (CheckAB2*CheckAB2 >= AB) then begin xm := (x0 + 3*x1 + 3*x2 + x3) * 0.125; ym := (y0 + 3*y1 + 3*y2 + y3) * 0.125; // Check small length if (xm <> x0) or (ym <> y0) then begin // Subdivide Next.x0 := x0; Next.y0 := y0; Next.x1 := (x0 + x1) * 0.5; Next.y1 := (y0 + y1) * 0.5; Next.x2 := (x0 + 2*x1 + x2) * 0.25; Next.y2 := (y0 + 2*y1 + y2) * 0.25; Next.x3 := xm; Next.y3 := ym; if Path.Func = pfOnLine then begin Next.p0pos := p0pos; Next.p3pos := p0pos + (p3pos - p0pos) * 0.5; end; ProcessSegment(Path, @Next); Next.x0 := xm; Next.y0 := ym; Next.x1 := (x1 + 2*x2 + x3) * 0.25; Next.y1 := (y1 + 2*y2 + y3) * 0.25; Next.x2 := (x2 + x3) * 0.5; Next.y2 := (y2 + y3) * 0.5; Next.x3 := x3; Next.y3 := y3; if Path.Func = pfOnLine then begin Next.p0pos := Next.p3pos; Next.p3pos := p3pos; end; ProcessSegment(Path, @Next); exit; end; end; // distance from (x1,y1) to the line is less than 1 // distance from (x2,y2) to the line is less than 1 Path.p1.x := Round(x3); Path.p1.y := Round(y3); end; with Path do begin case Func of pfFlatten: with PointList do begin if Count = Capacity then Grow; Data[Count].Point := p1; Data[Count].PointType := ptNode; inc(Count); end; pfOnLine: if not IsOnLine or Assigned(Nearest) then begin if IsFigureClosed then TempList := ScanLine else TempList := Nil; IsOnLine := PointOnLine(CheckPoint, p0, p1, StrokeWidth, TempList, Nearest) or IsOnLine; if Assigned(LengthPos) then with TempBezier do begin px := p0.x - p1.x; py := p0.y - p1.y; if p0.x = p1.x then Length := abs(py) else if p0.y = p1.y then Length := abs(px) else Length := sqrt(px*px + py*py); NewLength := CurLength + Length; end; if Assigned(Nearest) and Nearest.IsNewMin then with Nearest^ do if Assigned(Bezier) then begin // Correct index if Bezier.p3pos < 1 then MinIndex := Index0; // Calc bezier curve position (t) if p1.x <> p0.x then CurvePos := Bezier.p0pos + (Bezier.p3pos - Bezier.p0pos) * ( (Point.x - p0.x) / (p1.x - p0.x) ) else CurvePos := Bezier.p0pos; if Assigned(LengthPos) then LengthPos^ := CurLength + TempBezier.Length * CurvePos; end else if Assigned(LengthPos) then begin if p1.x <> p0.x then LengthPos^ := CurLength + TempBezier.Length * (Point.x - p0.x) / (p1.x - p0.x) else if p1.y <> p0.y then LengthPos^ := CurLength + TempBezier.Length * (Point.y - p0.y) / (p1.y - p0.y) else LengthPos^ := CurLength; end; if Assigned(LengthPos) then CurLength := TempBezier.NewLength; end; pfLength: with TempBezier do begin // Increase Nearest.CurvePos (total path length) to current segment length px := p0.x - p1.x; py := p0.y - p1.y; if p0.x = p1.x then Length := abs(py) else if p0.y = p1.y then Length := abs(px) else Length := sqrt(px*px + py*py); NewLength := PathLength + Length; // Check length stop if Assigned(LengthNearest) and (LengthNearest.MinIndex < 0) and (PathPos >= 0) and (PathPos <= NewLength) and (Length > 0) then with LengthNearest^ do begin // Calc point on segment Coeff := (PathPos - PathLength) / Length; Point.X := p0.x - Round(px * Coeff); Point.Y := p0.y - Round(py * Coeff); if (PathPos = NewLength) or (Assigned(Bezier) and (Bezier.p3pos = 1)) then begin MinIndex := Index1; CurvePos := 0; end else begin MinIndex := Index0; if Assigned(Bezier) then begin // Calc bezier curve position (t) if p1.x <> p0.x then CurvePos := Bezier.p0pos + (Bezier.p3pos - Bezier.p0pos) * ( (Point.x - p0.x) / (p1.x - p0.x) ) else CurvePos := Bezier.p0pos; end else CurvePos := Coeff; end; end else PathLength := NewLength; end; pfRange: with Range^ do begin if Left > p1.x then Left := p1.x else if Right < p1.x then Right := p1.x; if Top > p1.y then Top := p1.y else if Bottom < p1.y then Bottom := p1.y; end; pfPaint: LineTo(PaintDC, p1.x, p1.y); end; p0 := p1; end; end; function ProcessPath(const Points: TPointArray; const Types: TPointTypeArray; var Params: TPathParams): boolean; var FigIndex, FigEndIndex, Index, Count: integer; Bezier: TBezierParams; UseBezier: PBezierParams; InternalInfo: boolean; PathNearest: PNearestPoint; begin Result := true; Params.FigureCount := 0; Count := Length(Points); if Count <> Length(Types) then begin Result := false; exit; end; if (Count = 0) or (not Params.UseClosed and not Params.UseNotClosed) then // Empty path - do nothing exit; InternalInfo := not Assigned(Params.Info); with Params do try if InternalInfo then begin New(Info); GetPathInfo(Points, Types, Info^); end; if (Count <> Info.PointCount) then begin Result := false; exit; end; case Func of pfOnLine: PathNearest := Params.Nearest; pfLength: PathNearest := Params.LengthNearest; else PathNearest := Nil; end; // Process all figures for FigIndex:=0 to Length(Info.Figures)-1 do with Info.Figures[FigIndex] do begin if (IsClosed and not UseClosed) or (not IsClosed and not UseNotClosed) then begin // Skip figure Complete := false; continue; end; p0 := Points[FirstNode]; // BEGIN FIGURE inc(Params.FigureCount); case Func of pfFlatten: with PointList do begin if Count = Capacity then Grow; Data[Count].Point := p0; Data[Count].PointType := ptNode; inc(Count); end; pfRange: with Range^ do begin if Left > p0.x then Left := p0.x else if Right < p0.x then Right := p0.x; if Top > p0.y then Top := p0.y else if Bottom < p0.y then Bottom := p0.y; end; pfPaint: MoveToEx(PaintDC, p0.x, p0.y, Nil); end; IsFigureClosed := IsClosed; // PROCESS FIGURE POINTS Index := FirstNode; if IsClosed then FigEndIndex := LastNode else FigEndIndex := LastNode-1; while Index <= FigEndIndex do begin if Types[Index] = ptControl then begin // error Result := false; break; end; if Assigned(PathNearest) then PathNearest.Index0 := Index; if (Index < Count-2) and (Types[Index+1] = ptControl) then begin // Bezier curve segment UseBezier := @Bezier; with Bezier do if Params.OriginalBezier then begin OrigPoints[0] := Points[Index+0]; OrigPoints[1] := Points[Index+1]; OrigPoints[2] := Points[Index+2]; if Types[Index] = ptEndNodeClose then OrigPoints[3] := Points[FirstNode] else OrigPoints[3] := Points[Index+3]; end else begin // Init bezier parameters (convert to float values) p0pos := 0; p3pos := 1; x0 := Points[Index+0].x; y0 := Points[Index+0].y; x1 := Points[Index+1].x; y1 := Points[Index+1].y; x2 := Points[Index+2].x; y2 := Points[Index+2].y; if Types[Index] = ptEndNodeClose then begin // Closed curve - use first point of the figure x3 := Points[FirstNode].x; y3 := Points[FirstNode].y; if Assigned(PathNearest) then PathNearest.Index1 := FirstNode; end else begin // Use next node as end point of the bezier curve x3 := Points[Index+3].x; y3 := Points[Index+3].y; if Assigned(PathNearest) then PathNearest.Index1 := Index+3; end; end; inc(Index, 3); end else begin // Line segment UseBezier := Nil; if Types[Index] = ptEndNodeClose then begin p1 := Points[FirstNode]; if Assigned(PathNearest) then PathNearest.Index1 := FirstNode; end else begin p1 := Points[Index+1]; if Assigned(PathNearest) then PathNearest.Index1 := Index+1; end; inc(Index); end; // Process path segment ProcessSegment(Params, UseBezier); case Func of pfOnLine: if IsOnLine and not Assigned(Nearest) then break; pfLength: if Assigned(PathNearest) and (PathNearest.MinIndex >= 0) then break; end; end; // Check error if not Result then break; // END FIGURE case Func of pfFlatten: with PointList do if IsClosed then begin dec(Count); Data[Count-1].PointType := ptEndNodeClose end else Data[Count-1].PointType := ptEndNode; pfOnLine: if IsOnLine and not Assigned(Nearest) then break; pfLength: if Assigned(PathNearest) and (PathNearest.MinIndex >= 0) then break; pfPaint: if IsClosed then CloseFigure(PaintDC); end; end; finally if InternalInfo and Assigned(Info) then begin Dispose(Info); Info := Nil; end; end; end; // Interface routines ///////////////////////////////////////////////////////// function CalcPath(const Points: TPointArray; const Types: TPointTypeArray; var Range: TRect; Info: PPathInfo = Nil): boolean; var Path: TPathParams; begin if Length(Points) = 0 then begin SetRectEmpty(Range); Result := false; end else begin with Range do begin Left := Points[0].x; Top := Points[0].y; Right := Points[0].x; Bottom := Points[0].y; end; Path.UseClosed := true; Path.UseNotClosed := true; Path.OriginalBezier := false; Path.Curvature := 1; Path.Info := Info; Path.Func := pfRange; Path.Range := @Range; Result := ProcessPath(Points, Types, Path); end; end; function CreatePath(DC: HDC; const Points: TPointArray; const Types: TPointTypeArray; UseClosed, UseNotClosed: boolean; var Complete: boolean; OriginalBezier: boolean = false; Info: PPathInfo = Nil): boolean; var Path: TPathParams; begin Path.UseClosed := UseClosed; Path.UseNotClosed := UseNotClosed; Path.OriginalBezier := OriginalBezier; Path.Curvature := 1; Path.Info := Info; Path.Func := pfPaint; Path.PaintDC := DC; Result := BeginPath(DC); Result := Result and ProcessPath(Points, Types, Path); Result := Result and (Path.FigureCount > 0); if Result then EndPath(DC) else AbortPath(DC); Complete := Result and Path.Complete; end; function PointOnPath(const Points: TPointArray; const Types: TPointTypeArray; const Point: TPoint; Stroked, Filled: boolean; StrokeWidth: integer = 0; Nearest: PNearestPoint = Nil; Info: PPathInfo = Nil; LengthPos: PSingle = Nil): boolean; var ScanList: TList; Index: integer; Path: TPathParams; begin ScanList := Nil; try if Assigned(Nearest) then begin FillChar(Nearest^, SizeOf(Nearest^), 0); Nearest.MinIndex := -1; end; if Assigned(LengthPos) then LengthPos^ := 0.0; if Filled then begin ScanList := TList.Create; ScanList.Capacity := 64; end; if not Stroked then StrokeWidth := 0; Path.UseClosed := Stroked or Filled; Path.UseNotClosed := Stroked; Path.OriginalBezier := false; Path.Curvature := 1.0; Path.Info := Info; Path.Func := pfOnLine; Path.CheckPoint := Point; Path.StrokeWidth := StrokeWidth; Path.IsOnLine := false; Path.ScanLine := ScanList; Path.Nearest := Nearest; Path.CurLength := 0.0; Path.LengthPos := LengthPos; if ProcessPath(Points, Types, Path) then begin Result := Path.IsOnLine; if not Result and Filled then begin // Check ScanList Index := ListScanLess(pointer(Point.x), ScanList.List, ScanList.Count); Result := (Index < ScanList.Count) and ((Index and 1 <> 0) or (integer(ScanList[Index]) = Point.x)); end; end else Result := false; finally ScanList.Free; end; end; function PathLength(const Points: TPointArray; const Types: TPointTypeArray; Info: PPathInfo = Nil): single; var Path: TPathParams; begin Path.UseClosed := true; Path.UseNotClosed := true; Path.OriginalBezier := false; Path.Curvature := 1; Path.Info := Info; Path.Func := pfLength; Path.LengthNearest := Nil; Path.PathLength := 0; Path.PathPos := -1.0; if ProcessPath(Points, Types, Path) then Result := Path.PathLength else Result := -1.0; end; function PathLengthPos(const Points: TPointArray; const Types: TPointTypeArray; PathPos: single; Nearest: PNearestPoint; Info: PPathInfo = Nil): boolean; var Path: TPathParams; begin if Assigned(Nearest) then begin FillChar(Nearest^, SizeOf(Nearest^), 0); Nearest.MinIndex := -1; end; Path.UseClosed := true; Path.UseNotClosed := true; Path.OriginalBezier := false; Path.Curvature := 1; Path.Info := Info; Path.Func := pfLength; Path.LengthNearest := Nearest; Path.PathLength := 0; Path.PathPos := PathPos; Result := ProcessPath(Points, Types, Path); end; function FlattenPath(var Points: TPointArray; var Types: TPointTypeArray; Curvature: single; Info: PPathInfo = Nil): boolean; var Path: TPathParams; PointList: TPointList; i: integer; begin PointList := Nil; try Path.UseClosed := true; Path.UseNotClosed := true; Path.OriginalBezier := false; Path.Curvature := Curvature; Path.Info := Info; Path.Func := pfFlatten; PointList := TPointList.Create; Path.PointList := PointList; Result := ProcessPath(Points, Types, Path); if Result then begin SetLength(Points, PointList.Count); SetLength(Types, PointList.Count); for i:=0 to PointList.Count-1 do begin Points[i] := PointList.Data[i].Point; Types[i] := PointList.Data[i].PointType; end; end; finally PointList.Free; end; end; function InsertPathPoint(var Points: TPointArray; var Types: TPointTypeArray; FirstIndex, NextIndex: integer; const Point: TPoint; StickThreshold: integer = 0; Info: PPathInfo = Nil): integer; var Count: integer; InternalInfo: boolean; IsOutOfFigure, IsLastFirst, IsSegmentCurve: boolean; FigIndex, Index: integer; Path: TPathParams; Bezier: TBezierParams; Nearest: TNearestPoint; Ofs, Delta: TPoint; Coeff: single; function CalcBezier(a, b, c, t: single): single; var mt: single; begin mt := 1 - t; Result := mt*mt*a + 2*t*mt*b + t*t*c; end; begin Result := -1; Count := Length(Points); // Check indexes values if (Count <> Length(Types)) or (FirstIndex = NextIndex) or (FirstIndex < 0) or (FirstIndex > Count-1) or (NextIndex < -1) or (NextIndex > Count) then exit; // Check points types if (Types[FirstIndex] = ptControl) or ( (NextIndex >= 0) and (NextIndex < Count) and (Types[NextIndex] = ptControl) ) then exit; InternalInfo := not Assigned(Info); try // Check path info if InternalInfo then begin New(Info); GetPathInfo(Points, Types, Info^); end; if Info.PointCount <> Count then exit; // Find figure FigIndex := GetFigureIndex(Info^, FirstIndex); if FigIndex < 0 then exit; // Validate indexes with Info.Figures[FigIndex] do begin IsOutOfFigure := (NextIndex < FirstNode) or (NextIndex > LastNode); IsLastFirst := (NextIndex = FirstNode) and (FirstIndex = LastNode); if IsOutOfFigure then begin // NextIndex is out of figure if IsClosed or ((FirstIndex <> FirstNode) and (NextIndex < FirstNode)) or ((FirstIndex <> LastNode) and (NextIndex > LastNode)) then exit; end else begin if IsLastFirst and not IsClosed then exit; // Check index order if (NextIndex < FirstIndex) <> IsLastFirst then begin // Exchange indexes Index := FirstIndex; FirstIndex := NextIndex; NextIndex := Index; // Redefine IsLastFirst IsLastFirst := (NextIndex = FirstNode) and (FirstIndex = LastNode); end; end; // Define curve flag IsSegmentCurve := (FirstIndex < LastPoint) and (Types[FirstIndex+1] = ptControl); // Check index distance if not IsLastFirst and (Abs(NextIndex-FirstIndex) > 1) then if ((FirstIndex = FirstNode) and IsOutOfFigure) or not IsSegmentCurve or (NextIndex <> FirstIndex+3) then exit; // Calculate index to insert if IsOutOfFigure then begin if NextIndex < FirstIndex then Index := FirstIndex else Index := NextIndex; end else if IsLastFirst then Index := LastPoint+1 else Index := NextIndex; end; FillChar(Nearest, SizeOf(Nearest), 0); Nearest.MinIndex := -1; if IsSegmentCurve then begin // Insert bezier curve node FillChar(Path, SizeOf(Path), 0); Path.Curvature := 1; Path.Func := pfOnLine; Path.CheckPoint := Point; Path.StrokeWidth := 0; Path.IsOnLine := false; Path.ScanLine := Nil; Path.Nearest := @Nearest; with Bezier do begin x0 := Points[FirstIndex+0].x; y0 := Points[FirstIndex+0].y; x1 := Points[FirstIndex+1].x; y1 := Points[FirstIndex+1].y; x2 := Points[FirstIndex+2].x; y2 := Points[FirstIndex+2].y; x3 := Points[NextIndex].x; y3 := Points[NextIndex].y; p0pos := 0; p3pos := 1; end; Path.p0 := Points[FirstIndex+0]; ProcessSegment(Path, @Bezier); ChangePathCount(Points, Types, Index, 3); if Index < FirstIndex then inc(FirstIndex, 3); with Bezier do begin if Nearest.MinSqrDist <= StickThreshold*StickThreshold then begin Points[Index] := Nearest.Point; Ofs.x := 0; Ofs.y := 0; end else begin Points[Index] := Point; Ofs.x := Point.x - Nearest.Point.x; Ofs.y := Point.y - Nearest.Point.y; end; // Control points of FirstIndex { Points[FirstIndex+1].x := Round( (1-Nearest.CurvePos) * x0 + Nearest.CurvePos * x1 ); Points[FirstIndex+1].y := Round( (1-Nearest.CurvePos) * y0 + Nearest.CurvePos * y1 ); Points[FirstIndex+2].x := Round( CalcBezier(x0, x1, x2, Nearest.CurvePos) ) + Ofs.x; Points[FirstIndex+2].y := Round( CalcBezier(y0, y1, y2, Nearest.CurvePos) ) + Ofs.y; // Control points of inserted point Points[Index+1].x := Round( CalcBezier(x1, x2, x3, Nearest.CurvePos) ) + Ofs.x; Points[Index+1].y := Round( CalcBezier(y1, y2, y3, Nearest.CurvePos) ) + Ofs.y; Points[Index+2].x := Round( (1-Nearest.CurvePos) * x2 + Nearest.CurvePos * x3 ); Points[Index+2].y := Round( (1-Nearest.CurvePos) * y2 + Nearest.CurvePos * y3 ); } // Recalc Points[Index+2] := Points[FirstIndex+2]; if (Nearest.CurvePos = 0) or (Nearest.CurvePos = 1) then Coeff := 0 {must be infinity} else Coeff := 1 / (3 * (1 - Nearest.CurvePos) * Nearest.CurvePos); Delta.x := Round(Ofs.x * Coeff); Delta.y := Round(Ofs.y * Coeff); if (Delta.x <> 0) or (Delta.y <> 0) then begin // Change control points inc(Points[FirstIndex+1].x, Delta.x); inc(Points[FirstIndex+1].y, Delta.y); inc(Points[Index+2].x, Delta.x); inc(Points[Index+2].y, Delta.y); // Change bezier params x1 := Points[FirstIndex+1].x; y1 := Points[FirstIndex+1].y; x2 := Points[Index+2].x; y2 := Points[Index+2].y; end; // Calc new position of existing control points Points[FirstIndex+1].x := Round( (1-Nearest.CurvePos) * x0 + Nearest.CurvePos * x1 ); Points[FirstIndex+1].y := Round( (1-Nearest.CurvePos) * y0 + Nearest.CurvePos * y1 ); Points[Index+2].x := Round( (1-Nearest.CurvePos) * x2 + Nearest.CurvePos * x3 ); Points[Index+2].y := Round( (1-Nearest.CurvePos) * y2 + Nearest.CurvePos * y3 ); // Calc control points for inserted node Points[FirstIndex+2].x := Round(CalcBezier(x0, x1, x2, Nearest.CurvePos)); Points[FirstIndex+2].y := Round(CalcBezier(y0, y1, y2, Nearest.CurvePos)); Points[Index+1].x := Round(CalcBezier(x1, x2, x3, Nearest.CurvePos)); Points[Index+1].y := Round(CalcBezier(y1, y2, y3, Nearest.CurvePos)); // Set types of inserted control points Types[Index+1] := ptControl; Types[Index+2] := ptControl; end; end else begin // Insert line node if not IsOutOfFigure then PointOnLine(Point, Points[FirstIndex], Points[NextIndex], 0, Nil, @Nearest); ChangePathCount(Points, Types, Index, 1); if not IsOutOfFigure and (Nearest.MinSqrDist <= StickThreshold*PixelScaleFactor) then Points[Index] := Nearest.Point else Points[Index] := Point; if Index < FirstIndex then inc(FirstIndex); end; // Set type of inserted node if IsOutOfFigure and (Index > FirstIndex) then begin Types[FirstIndex] := ptNode; Types[Index] := ptEndNode; end else if IsLastFirst then begin Types[FirstIndex] := ptNode; Types[Index] := ptEndNodeClose; end else Types[Index] := ptNode; Result := Index; finally if InternalInfo and Assigned(Info) then Dispose(Info); end; end; function FindNearestPathSegment(const Points: TPointArray; const Types: TPointTypeArray; const Point: TPoint; var FirstIndex, NextIndex: integer; Nearest: PNearestPoint = Nil; Info: PPathInfo = Nil; ForInsert: boolean = true): boolean; var MemNearest: TNearestPoint; FigIndex: integer; InternalInfo: boolean; begin Result := false; InternalInfo := not Assigned(Info); try // Check nearest if not Assigned(Nearest) then Nearest := @MemNearest; // Check path info if InternalInfo then begin New(Info); GetPathInfo(Points, Types, Info^); end; // Find nearest point FillChar(Nearest^, SizeOf(Nearest^), 0); Nearest.MinIndex := -1; PointOnPath(Points, Types, Point, True, False, 0, Nearest, Info); if Nearest.MinIndex < 0 then exit; // Find figure FigIndex := GetFigureIndex(Info^, Nearest.MinIndex); if FigIndex < 0 then exit; // Define closest path segment with Info.Figures[FigIndex] do begin FirstIndex := Nearest.MinIndex; NextIndex := -1; if IsClosed then begin // Figure is closed if FirstIndex = LastNode then NextIndex := FirstNode else if Types[FirstIndex+1] = ptControl then NextIndex := FirstIndex+3 else NextIndex := FirstIndex+1; end else begin // Figure is non-closed if FirstIndex = LastNode then begin if FirstIndex < LastPoint then NextIndex := FirstIndex+3 else NextIndex := FirstIndex+1; end else if (FirstIndex = FirstNode) and (Nearest.Point.x = Points[FirstNode].x) and (Nearest.Point.y = Points[FirstNode].y) then NextIndex := FirstIndex-1 else if Types[FirstIndex+1] = ptControl then NextIndex := FirstIndex+3 else NextIndex := FirstIndex+1; end; Result := ForInsert or ((NextIndex >= FirstNode) and (NextIndex <= LastNode)); end; finally if InternalInfo and Assigned(Info) then Dispose(Info); end; end; function InsertNearestPoint(var Points: TPointArray; var Types: TPointTypeArray; const Point: TPoint; StickThreshold: integer = 0; Info: PPathInfo = Nil): integer; var FirstIndex, NextIndex: integer; InternalInfo: boolean; begin Result := -1; InternalInfo := not Assigned(Info); try // Check path info if InternalInfo then begin New(Info); GetPathInfo(Points, Types, Info^); end; // Find path segment if not FindNearestPathSegment(Points, Types, Point, FirstIndex, NextIndex, Nil, Info) then exit; // Insert new point Result := InsertPathPoint(Points, Types, FirstIndex, NextIndex, Point, StickThreshold, Info); finally if InternalInfo and Assigned(Info) then Dispose(Info); end; end; function GetEditPathCaps(const Points: TPointArray; const Types: TPointTypeArray; const Selected: TSelectedArray): TPathEditFuncs; var i, Count, SelCount: integer; First, Second: record IsFirst: boolean; PointType: TPointType; Figure: integer; end; Figures: integer; IsPrevEnd: boolean; begin Result := []; Count := Length(Selected); if (Count <> Length(Points)) or (Count <> Length(Types)) then exit; SelCount := 0; Figures := 0; IsPrevEnd := true; for i:=0 to Count-1 do begin if Selected[i] then begin // Check selected point inc(SelCount); if Types[i] = ptControl then begin Result := [pfOffset]; exit; end; case SelCount of 1: with First do begin IsFirst := IsPrevEnd; PointType := Types[i]; Figure := Figures; end; 2: with Second do begin IsFirst := IsPrevEnd; PointType := Types[i]; Figure := Figures; end; end; if (i < Length(Points)-1) and (Types[i+1] = ptControl) then Include(Result, pfToLine) else Include(Result, pfToCurve); if Types[i] = ptNode then Include(Result, pfBreak); end; // Check end of figure in path case Types[i] of ptNode: IsPrevEnd := false; ptEndNode, ptEndNodeClose: begin IsPrevEnd := true; inc(Figures); end; end; end; // Define pfJoin and pfClose capabilities if (SelCount = 2) and ( (First.IsFirst and (Second.PointType = ptEndNode)) or ((First.PointType = ptEndNode) or Second.IsFirst) ) then begin Include(Result, pfJoin); Include(Result, pfClose); end; if SelCount > 0 then begin Include(Result, pfOffset); //Include(Result, pfDelete); end; end; function EditPath(var Points: TPointArray; var Types: TPointTypeArray; const Selected: TSelectedArray; Func: TPathEditFunc; Params: PPathEditParams = Nil): boolean; type TFigure = record FirstNode: integer; EndNode: integer; LastPoint: integer; end; var Index, BreakIndex, NodeIndex, LastIndex, FirstIndex: integer; First, Second: TFigure; Temp: array of byte; Count, DeltaCount, MoveCount, Size: integer; Error, SameFigure, NeedMove: boolean; p0, p1, CtrlPointA, CtrlPointB: TPoint; function CalcFigure(Index: integer; var Figure: TFigure): boolean; begin with Figure do begin if Types[Index] = ptEndNode then begin // It is last point in figure. Find first point EndNode := Index; FirstNode := Index; repeat dec(Index); if Index < 0 then break; if Types[Index] = ptNode then FirstNode := Index; until Types[Index] in [ptEndNode, ptEndNodeClose]; Result := true; end else begin // It is first point in figure. Find last point FirstNode := Index; EndNode := Index; repeat inc(EndNode); until (EndNode = Count) or (Types[EndNode] in [ptEndNode, ptEndNodeClose]); Result := EndNode < Count; // check error in point types end; if not Result then exit; LastPoint := EndNode +1; while (LastPoint < Count) and (Types[LastPoint] = ptControl) do inc(LastPoint); dec(LastPoint); end; end; procedure ReverseFigureDirection(var Figure: TFigure); var i: integer; TempPoint: TPoint; TempType: TPointType; Count: integer; begin with Figure do begin Count := LastPoint - FirstNode +1; if Count <= 1 then exit; for i:=0 to (Count div 2)-1 do begin TempPoint := Points[FirstNode+i]; Points[FirstNode+i] := Points[LastPoint-i]; Points[LastPoint-i] := TempPoint; TempType := Types[FirstNode+i]; Types[FirstNode+i] := Types[LastPoint-i]; Types[LastPoint-i] := TempType; end; Types[EndNode] := Types[FirstNode]; Types[FirstNode] := ptNode; Result := true; // Points changed end; end; procedure ChangeCount(Index, Delta: integer); begin if Delta > 0 then begin SetLength(Points, Count + Delta); SetLength(Types, Count + Delta); end else dec(Index, Delta); Move(Points[Index], Points[Index+Delta], (Count - Index) * SizeOf(Points[0])); Move(Types[Index], Types[Index+Delta], (Count - Index) * SizeOf(Types[0])); if Delta < 0 then begin SetLength(Points, Count + Delta); SetLength(Types, Count + Delta); end; inc(Count, Delta); Result := true; // Points changed end; begin Temp := Nil; Result := Func in GetEditPathCaps(Points, Types, Selected); if not Result then exit; Result := false; Count := Length(Selected); if (Count <> Length(Points)) or (Count <> Length(Types)) then exit; case Func of pfOffset: if Assigned(Params) then with Params^ do if not Params.MoveControls then begin for Index:=0 to Count-1 do if Selected[Index] then begin inc(Points[Index].x, Offset.x); inc(Points[Index].y, Offset.y); Result := true; // Points changed end; end else begin BreakIndex := 0; FirstIndex := -1; NodeIndex := -1; for Index:=0 to Count-1 do begin if Index = BreakIndex then FirstIndex := Index; if Types[Index] <> ptControl then begin NodeIndex := Index; if Types[Index] in [ptEndNode, ptEndNodeClose] then if (Index < Count-1) and (Types[Index+1] = ptControl) then BreakIndex := Index + 3 else BreakIndex := Index + 1; end; NeedMove := Selected[Index]; if not NeedMove and (Index > NodeIndex) then // Check control point if Index - NodeIndex = 1 then begin // First control point - NodeIndex is owner NeedMove := Selected[NodeIndex]; end else begin // Second control point - owner is next (or first in figure) node if Types[NodeIndex] = ptEndNodeClose then // Last node and closed figure - check first node NeedMove := Selected[FirstIndex] else if Types[NodeIndex] <> ptEndNode then // Check next node in figure NeedMove := Selected[NodeIndex+3]; end; if NeedMove then begin inc(Points[Index].x, Offset.x); inc(Points[Index].y, Offset.y); Result := true; // Points changed end; end; end; { pfDelete: begin DeltaCount := 0; Index := 0; BreakIndex := 0; FirstIndex := -1; NodeIndex := -1; while Index < Count do begin if Index = BreakIndex then FirstIndex := Index; if Types[Index] <> ptControl then begin NodeIndex := Index; if Types[Index] in [ptEndNode, ptEndNodeClose] then if (Index < Count-1) and (Types[Index+1] = ptControl) then BreakIndex := Index + 3 else BreakIndex := Index + 1; if Selected[Index+DeltaCount] then begin end end else // Skip control points inc(Index); end; end; } pfJoin, pfClose: begin FirstIndex := -1; LastIndex := -1; SameFigure := true; for Index := 0 to Count-1 do begin if Selected[Index] then if FirstIndex < 0 then FirstIndex := Index else if LastIndex < 0 then begin LastIndex := Index; break; end; if (FirstIndex >= 0) and (Types[Index] in [ptEndNode, ptEndNodeClose]) then SameFigure := false; end; if (FirstIndex < 0) or (LastIndex < 0) then exit; // can't complete if SameFigure then begin case Func of pfJoin: // Join edge points of the figure if Types[LastIndex] = ptEndNode then begin // Find previous node Index := LastIndex -1; while (Index >= FirstIndex) and (Types[Index] = ptControl) do dec(Index); if Index < FirstIndex then exit; // error // Close figure and delete last point (join to first) Types[Index] := ptEndNodeClose; // Calculate middle point with Points[FirstIndex] do begin p0.x := x + abs(x - Points[LastIndex].x) div 2; p0.y := y + abs(y - Points[LastIndex].y) div 2; end; Points[FirstIndex] := p0; ChangeCount(LastIndex, -1); end; pfClose: // Close figure if Types[LastIndex] = ptEndNode then begin Types[LastIndex] := ptEndNodeClose; Result := true; // Points changed end; end; exit; end; // Define first and end nodes of selected figures if not CalcFigure(FirstIndex, First) then exit; if not CalcFigure(LastIndex, Second) then exit; // Calculate point count between first and second figures MoveCount := Second.FirstNode - First.LastPoint -1; if MoveCount > 0 then begin // Move Second figure after First figure DeltaCount := Second.LastPoint - Second.FirstNode +1; // Move points Size := DeltaCount * SizeOf(Points[0]); SetLength(Temp, Size); Move(Points[Second.FirstNode], Temp[0], Size); Move(Points[First.LastPoint+1], Points[First.LastPoint+1 +DeltaCount], MoveCount * SizeOf(Points[0])); Move(Temp[0], Points[First.LastPoint+1], Size); // Move types Size := DeltaCount * SizeOf(Types[0]); if Size > Length(Temp) then SetLength(Temp, Size); Move(Types[Second.FirstNode], Temp[0], Size); Move(Types[First.LastPoint+1], Types[First.LastPoint+1 +DeltaCount], MoveCount * SizeOf(Types[0])); Move(Temp[0], Types[First.LastPoint+1], Size); with Second do begin dec(FirstNode, MoveCount); dec(EndNode, MoveCount); dec(LastPoint, MoveCount); dec(LastIndex, MoveCount); end; Result := true; // Points changed end; // Check direction of First and Second figures if FirstIndex <> First.EndNode then ReverseFigureDirection(First); if LastIndex <> Second.FirstNode then ReverseFigureDirection(Second); // Complete function case Func of pfJoin: begin // Calculate middle point with Points[First.EndNode] do begin p0.x := x + abs(x - Points[Second.FirstNode].x) div 2; p0.y := y + abs(y - Points[Second.FirstNode].y) div 2; end; // Delete First.EndNode point if (First.EndNode < Count-1) and (Types[First.EndNode+1] = ptControl) then ChangeCount(First.EndNode, -3) else ChangeCount(First.EndNode, -1); // Set calculated middle point as result of join Points[First.EndNode] := p0; end; pfClose: // Replace ptEndNode type to ptNode (link figures) begin Types[First.EndNode] := ptNode; Result := true; // Points changed end; end; end; pfBreak: begin Index := 0; DeltaCount := 0; FirstIndex := 0; while Index < Count do begin BreakIndex := -1; // Define last point in figure LastIndex := FirstIndex; while (LastIndex < Count) and not (Types[LastIndex] in [ptEndNode, ptEndNodeClose]) do inc(LastIndex); if LastIndex = Count then break; // error in point types Index := FirstIndex; while Index <= LastIndex do begin if Selected[Index+DeltaCount] then if Types[Index] <> ptControl then begin // Break selected point ChangeCount(Index, 1); Types[Index] := ptEndNode; inc(LastIndex); inc(Index); dec(DeltaCount); BreakIndex := Index; end; inc(Index); end; // Check figure breaking if (BreakIndex >= 0) and (Types[LastIndex] = ptEndNodeClose) then begin Types[LastIndex] := ptNode; // Define last point of the figure if (LastIndex < Count-1) and (Types[LastIndex+1] = ptControl) then inc(LastIndex, 2); // Move points after last breaked before first point of the figure MoveCount := LastIndex - BreakIndex +1; // Move points Size := MoveCount * SizeOf(Points[0]); SetLength(Temp, Size); Move(Points[BreakIndex], Temp[0], Size); Move(Points[FirstIndex], Points[FirstIndex+MoveCount], (BreakIndex - FirstIndex) * SizeOf(Points[0])); Move(Temp[0], Points[FirstIndex], Size); // Move types Size := MoveCount * SizeOf(Types[0]); if Size > Length(Temp) then SetLength(Temp, Size); Move(Types[BreakIndex], Temp[0], Size); Move(Types[FirstIndex], Types[FirstIndex+MoveCount], (BreakIndex - FirstIndex) * SizeOf(Types[0])); Move(Temp[0], Types[FirstIndex], Size); end; FirstIndex := Index; end; end; pfToCurve: begin Index := 0; DeltaCount := 0; FirstIndex := 0; while Index < Count do begin // Define last point in figure LastIndex := FirstIndex; while (LastIndex < Count) and not (Types[LastIndex] in [ptEndNode, ptEndNodeClose]) do inc(LastIndex); if LastIndex = Count then break; // error in point types Index := FirstIndex; while Index <= LastIndex do begin if Selected[Index+DeltaCount] and ((Index >= Count-1) or (Types[Index+1] <> ptControl)) then begin // Define line points Error := false; p0 := Points[Index]; if Types[Index] = ptEndNodeClose then p1 := Points[FirstIndex] else if Index < LastIndex then p1 := Points[Index+1] else // Can't convert point Error := true; if not Error then begin // Calculate control points CtrlPointA.x := p0.x + (p1.x - p0.x) div 3; CtrlPointA.y := p0.y + (p1.y - p0.y) div 3; CtrlPointB.x := p1.x - (p1.x - p0.x) div 3; CtrlPointB.y := p1.y - (p1.y - p0.y) div 3; // Convert to curve point ChangeCount(Index+1, 2); Points[Index+1] := CtrlPointA; Types[Index+1] := ptControl; Points[Index+2] := CtrlPointB; Types[Index+2] := ptControl; inc(Index, 2); inc(LastIndex, 2); dec(DeltaCount, 2); end; end; inc(Index); end; FirstIndex := Index; end; end; pfToLine: begin Index := 0; DeltaCount := 0; while Index < Count do begin if Selected[Index+DeltaCount] and (Index < Count-1) and (Types[Index+1] = ptControl) then begin // Convert curve point to line point ChangeCount(Index+1, -2); inc(DeltaCount, 2); end; inc(Index); end; end; end; end; function EditPath(var Points: TPointArray; var Types: TPointTypeArray; const Indexes: array of integer; Func: TPathEditFunc; Params: PPathEditParams = Nil): boolean; overload; var Selected: TSelectedArray; i: integer; begin SetLength(Selected, Length(Points)); for i:=0 to Length(Selected)-1 do Selected[i] := false; for i:=0 to Length(Indexes)-1 do if Indexes[i] < Length(Selected) then Selected[Indexes[i]] := true; Result := EditPath(Points, Types, Selected, Func, Params); end; function ConnectorReroute(var Points: TPointArray; var PointTypes: TPointTypeArray; const Params: TRerouteParams): boolean; type TSide = ( sdNorth, sdEast, sdSouth, sdWest ); TSides = set of TSide; var Count: integer; RangeGapA, RangeGapB: TRect; RangeGapExist: boolean; procedure SetCount(ACount: integer); var i: integer; begin SetLength(Points, ACount); SetLength(PointTypes, ACount); for i:=0 to ACount-2 do PointTypes[i] := ptNode; PointTypes[ACount-1] := ptEndNode; Count := ACount; end; function CalcSides(const LinkPoint: TPoint; const Range: TRect): TSides; var OutsideX, OutsideY: boolean; Side: TSide; Dist: array[TSide] of integer; MinDist: integer; begin Result := []; with LinkPoint, Range do begin // Check link point outside OutsideX := (x < Left) or (x > Right); OutsideY := (y < Top) or (y > Bottom); if OutsideX or OutsideY then begin // LinkPoint outside Range if OutsideX then if x < Left then Include(Result, sdWest) // Outside left else Include(Result, sdEast); // Outside right if OutsideY then if y < Top then Include(Result, sdNorth) // Outside top else Include(Result, sdSouth); // Outside bottom end else begin // LinkPoint inside Range // Calc distances to edges Dist[sdNorth] := y - Top; Dist[sdEast] := Right - x; Dist[sdSouth] := Bottom - y; Dist[sdWest] := x - Left; // Find min distance MinDist := 0; for Side:=Low(Side) to High(Side) do if Side=Low(Side) then MinDist := Dist[Side] else if Dist[Side] < MinDist then MinDist := Dist[Side]; // Define active sides for Side:=Low(Side) to High(Side) do if Dist[Side] = MinDist then Include(Result, Side); end; end; end; function TryLinkOrtogonal(PtCount: integer; SideA, SideB: TSide): boolean; var Codirectional: boolean; IsHorizA, IsHorizB: boolean; Temp: TPoint; TempR: TRect; Exist: boolean; Size1, Size2{, Max1, Max2}: integer; FlagA, FlagB: boolean; function PointsOnGapInRange: boolean; var Temp: TRect; begin Result := true; // Test LinkA distribution Temp.TopLeft := Params.LinkPointA; Temp.BottomRight := Params.LinkPointA; inc(Temp.Right); inc(Temp.Bottom); case SideA of sdNorth : Temp.Top := RangeGapA.Top; sdEast : Temp.Right := RangeGapA.Right; sdSouth : Temp.Bottom := RangeGapA.Bottom; sdWest : Temp.Left := RangeGapA.Left; end; // Test temp intersects with RangeGapB if IntersectRect(Temp, Temp, RangeGapB) then exit; // Test LinkB distribution Temp.TopLeft := Params.LinkPointB; Temp.BottomRight := Params.LinkPointB; inc(Temp.Right); inc(Temp.Bottom); case SideB of sdNorth : Temp.Top := RangeGapB.Top; sdEast : Temp.Right := RangeGapB.Right; sdSouth : Temp.Bottom := RangeGapB.Bottom; sdWest : Temp.Left := RangeGapB.Left; end; // Test temp intersects with RangeGapA if IntersectRect(Temp, Temp, RangeGapA) then exit; Result := false; end; begin Result := false; // Define side type (horizontal or vertical) IsHorizA := SideA in [sdEast, sdWest]; IsHorizB := SideB in [sdEast, sdWest]; // Define codirectional sides (both horizontal or both vertical) Codirectional := (IsHorizA and IsHorizB) or (not IsHorizA and not IsHorizB); // Test incompatible imtermediate point count if ((PtCount = 1) or (PtCount = 3)) = Codirectional then exit; with Params do case PtCount of 0: begin // Straight line (no intermediate points) // Check link points lie on horiz or vert line if IsHorizA then begin if LinkPointA.y <> LinkPointB.y then exit; end else if LinkPointA.x <> LinkPointB.x then exit; // Check distribution if SideA = SideB then exit; if IsHorizA then begin // Test horizontal distribution if (SideA = sdEast) = (LinkPointA.x > LinkPointB.x) then exit; end else // Test vertical distribution if (SideA = sdNorth) = (LinkPointA.y < LinkPointB.y) then exit; // All conditions completed. Create link SetCount(2); end; 1: begin // Corner link (one intermediate point) // Check distribution if IsHorizA then begin // Test horizontal distribution case SideA of sdEast: if RangeGapA.Right > LinkPointB.x then exit; sdWest: if RangeGapA.Left < LinkPointB.x then exit; end; case SideB of sdNorth: if LinkPointA.y > RangeGapB.Top then exit; sdSouth: if LinkPointA.y < RangeGapB.Bottom then exit; end; end else begin // Test vertical distribution case SideA of sdNorth: if RangeGapA.Top < LinkPointB.y then exit; sdSouth: if RangeGapA.Bottom > LinkPointB.y then exit; end; case SideB of sdEast: if LinkPointA.x < RangeGapB.Right then exit; sdWest: if LinkPointA.x > RangeGapB.Left then exit; end; end; // All conditions completed. Create link SetCount(3); if IsHorizA then begin Points[1].x := LinkPointB.x; Points[1].y := LinkPointA.y; end else begin Points[1].x := LinkPointA.x; Points[1].y := LinkPointB.y; end; end; 2: begin // Step link (two intermediate points) // Check distribution if IsHorizA then begin // Test horizontal distribution if SideA <> SideB then begin // Check horizontal gap case SideA of sdEast: begin if RangeGapA.Right > RangeGapB.Left then exit; Temp.x := (RangeGapA.Right + RangeGapB.Left) div 2; end; sdWest: begin if RangeGapA.Left < RangeGapB.Right then exit; Temp.x := (RangeGapB.Right + RangeGapA.Left) div 2; end; end; end else begin // Check y position if SideA = sdEast then begin // Check LinkA if (LinkPointA.x < RangeGapB.Right) and (LinkPointA.y > RangeGapB.Top) and (LinkPointA.y < RangeGapB.Bottom) then exit; // Check LinkB if (LinkPointB.x < RangeGapA.Right) and (LinkPointB.y > RangeGapA.Top) and (LinkPointB.y < RangeGapA.Bottom) then exit; end else begin // Check LinkA if (LinkPointA.x > RangeGapB.Left) and (LinkPointA.y > RangeGapB.Top) and (LinkPointA.y < RangeGapB.Bottom) then exit; // Check LinkB if (LinkPointB.x > RangeGapA.Left) and (LinkPointB.y > RangeGapA.Top) and (LinkPointB.y < RangeGapA.Bottom) then exit; end; // Calc edge if SideA = sdEast then begin if RangeGapA.Right > RangeGapB.Right then Temp.x := RangeGapA.Right else Temp.x := RangeGapB.Right; end else if RangeGapA.Left < RangeGapB.Left then Temp.x := RangeGapA.Left else Temp.x := RangeGapB.Left; end; // All OK. Create link SetCount(4); Points[1].x := Temp.x; Points[1].y := LinkPointA.y; Points[2].x := Temp.x; Points[2].y := LinkPointB.y; end else begin // Test vertical distribution if SideA <> SideB then begin // Check vertical gap case SideA of sdNorth: begin if RangeGapA.Top < RangeGapB.Bottom then exit; Temp.y := (RangeGapA.Top + RangeGapB.Bottom) div 2; end; sdSouth: begin if RangeGapA.Bottom > RangeGapB.Top then exit; Temp.y := (RangeGapA.Bottom + RangeGapB.Top) div 2; end; end; end else begin // Check x position if SideA = sdNorth then begin // Check LinkA if (LinkPointA.y > RangeGapB.Top) and (LinkPointA.x > RangeGapB.Left) and (LinkPointA.x < RangeGapB.Right) then exit; // Check LinkB if (LinkPointB.y > RangeGapA.Top) and (LinkPointB.x > RangeGapA.Left) and (LinkPointB.x < RangeGapA.Right) then exit; end else begin // Check LinkA if (LinkPointA.y < RangeGapB.Bottom) and (LinkPointA.x > RangeGapB.Left) and (LinkPointA.x < RangeGapB.Right) then exit; // Check LinkB if (LinkPointB.y < RangeGapA.Bottom) and (LinkPointB.x > RangeGapA.Left) and (LinkPointB.x < RangeGapA.Right) then exit; end; // Calc edge if SideA = sdNorth then begin if RangeGapA.Top < RangeGapB.Top then Temp.y := RangeGapA.Top else Temp.y := RangeGapB.Top; end else if RangeGapA.Bottom > RangeGapB.Bottom then Temp.y := RangeGapA.Bottom else Temp.y := RangeGapB.Bottom; end; // All OK. Create link SetCount(4); Points[1].x := LinkPointA.x; Points[1].y := Temp.y; Points[2].x := LinkPointB.x; Points[2].y := Temp.y; end; end; 3: begin // Zigzag link (three intermediate points) // Check distribution if PointsOnGapInRange then exit; // Linking possible SetCount(5); if IsHorizA then begin // LinkA is West or East and LinkB is North or South Points[1].y := LinkPointA.y; // Test center (horizontal gap) if SideA = sdEast then begin Exist := RangeGapB.Left >= RangeGapA.Right; Temp.x := (RangeGapB.Left + RangeGapA.Right) div 2; end else begin Exist := RangeGapB.Right <= RangeGapA.Left; Temp.x := (RangeGapB.Right + RangeGapA.Left) div 2; end; if Exist then begin // Exist horizontal gap. Use it. Points[1].x := Temp.x; Points[2].x := Temp.x; if SideB = sdNorth then Points[2].y := RangeGapB.Top else Points[2].y := RangeGapB.Bottom; Points[3].x := LinkPointB.x; Points[3].y := Points[2].y; end else begin // Find vertical gap if SideB = sdNorth then begin // Check up gap Exist := RangeGapA.Bottom <= RangeGapB.Top; Temp.y := (RangeGapA.Bottom + RangeGapB.Top) div 2; end else begin // Check down gap Exist := RangeGapA.Top >= RangeGapB.Bottom; Temp.y := (RangeGapA.Top + RangeGapB.Bottom) div 2; end; if Exist then begin // Exist vertical gap. Use it. if SideA = sdEast then Points[1].x := RangeGapA.Right else Points[1].x := RangeGapA.Left; Points[2].x := Points[1].x; Points[2].y := Temp.y; Points[3].x := LinkPointB.x; Points[3].y := Temp.y; end else begin // No gaps. Make path around if SideA = sdEast then begin if RangeGapA.Right > RangeGapB.Right then Points[1].x := RangeGapA.Right else Points[1].x := RangeGapB.Right; end else if RangeGapA.Left < RangeGapB.Left then Points[1].x := RangeGapA.Left else Points[1].x := RangeGapB.Left; Points[2].x := Points[1].x; if SideB = sdNorth then begin if RangeGapA.Top < RangeGapB.Top then Points[2].y := RangeGapA.Top else Points[2].y := RangeGapB.Top; end else if RangeGapA.Bottom > RangeGapB.Bottom then Points[2].y := RangeGapA.Bottom else Points[2].y := RangeGapB.Bottom; Points[3].x := LinkPointB.x; Points[3].y := Points[2].y; end; end; end else begin // LinkA is North or South and LinkB is West or East Points[1].x := LinkPointA.x; // Test center (vertical gap) if SideA = sdNorth then begin Exist := RangeGapB.Bottom <= RangeGapA.Top; Temp.y := (RangeGapB.Bottom + RangeGapA.Top) div 2; end else begin Exist := RangeGapB.Top >= RangeGapA.Bottom; Temp.y := (RangeGapB.Top + RangeGapA.Bottom) div 2; end; if Exist then begin // Exist vertical gap. Use it. Points[1].y := Temp.y; Points[2].y := Temp.y; if SideB = sdEast then Points[2].x := RangeGapB.Right else Points[2].x := RangeGapB.Left; Points[3].x := Points[2].x; Points[3].y := LinkPointB.y; end else begin // Find horizontal gap if SideB = sdEast then begin // Check left gap Exist := RangeGapA.Left >= RangeGapB.Right; Temp.x := (RangeGapA.Left + RangeGapB.Right) div 2; end else begin // Check right gap Exist := RangeGapA.Right <= RangeGapB.Left; Temp.x := (RangeGapA.Right + RangeGapB.Left) div 2; end; if Exist then begin // Exist horizontal gap. Use it. if SideA = sdNorth then Points[1].y := RangeGapA.Top else Points[1].y := RangeGapA.Bottom; Points[2].x := Temp.x; Points[2].y := Points[1].y; Points[3].x := Temp.x; Points[3].y := LinkPointB.y; end else begin // No gaps. Make path around if SideA = sdNorth then begin if RangeGapA.Top < RangeGapB.Top then Points[1].y := RangeGapA.Top else Points[1].y := RangeGapB.Top; end else if RangeGapA.Bottom > RangeGapB.Bottom then Points[1].y := RangeGapA.Bottom else Points[1].y := RangeGapB.Bottom; Points[2].y := Points[1].y; if SideB = sdEast then begin if RangeGapA.Right > RangeGapB.Right then Points[2].x := RangeGapA.Right else Points[2].x := RangeGapB.Right; end else if RangeGapA.Left < RangeGapB.Left then Points[2].x := RangeGapA.Left else Points[2].x := RangeGapB.Left; Points[3].x := Points[2].x; Points[3].y := LinkPointB.y; end; end; end; end; 4: begin // Zigzag link (four intermediate points) // Check distribution if PointsOnGapInRange then exit; // Linking possible SetCount(6); if IsHorizA then begin // LinkA and LinkB is West or East Points[1].y := LinkPointA.y; // Calc vertical direction (Temp.y) // Test sides if SideA = SideB then begin // Unidirectional // Calc horizontal gap center if RangeGapA.Left >= RangeGapB.Right then Temp.x := (RangeGapA.Left + RangeGapB.Right) div 2 // left gap else Temp.x := (RangeGapA.Right + RangeGapB.Left) div 2; // right gap if ((SideA = sdEast) and (RangeGapA.Right < RangeGapB.Left)) or ((SideA = sdWest) and (RangeGapA.Left > RangeGapB.Right)) then begin // Step near LinkA // Calc vertical position by LinkB Size1 := Abs(LinkPointA.y - RangeGapB.Top) + Abs(LinkPointB.y - RangeGapB.Top); Size2 := Abs(LinkPointA.y - RangeGapB.Bottom) + Abs(LinkPointB.y - RangeGapB.Bottom); if Size1 < Size2 then Temp.y := RangeGapB.Top else Temp.y := RangeGapB.Bottom; // Build path Points[1].x := Temp.x; Points[2].x := Temp.x; Points[2].y := Temp.y; if SideA = sdEast then Points[3].x := RangeGapB.Right else Points[3].x := RangeGapB.Left; Points[3].y := Temp.y; Points[4].x := Points[3].x; Points[4].y := LinkPointB.y; end else begin // Step near LinkB // Calc vertical position by LinkA Size1 := Abs(LinkPointA.y - RangeGapA.Top) + Abs(LinkPointB.y - RangeGapA.Top); Size2 := Abs(LinkPointA.y - RangeGapA.Bottom) + Abs(LinkPointB.y - RangeGapA.Bottom); if Size1 < Size2 then Temp.y := RangeGapA.Top else Temp.y := RangeGapA.Bottom; if SideA = sdEast then Points[1].x := RangeGapA.Right else Points[1].x := RangeGapA.Left; Points[2].x := Points[1].x; Points[2].y := Temp.y; Points[3].x := Temp.x; Points[3].y := Temp.y; Points[4].x := Temp.x; Points[4].y := LinkPointB.y; end; end else begin // Contradirectional FlagA := true; FlagB := true; // Test vertical gap if RangeGapA.Top >= RangeGapB.Bottom then Temp.y := (RangeGapA.Top + RangeGapB.Bottom) div 2 else if RangeGapA.Bottom <= RangeGapB.Top then Temp.y := (RangeGapA.Bottom + RangeGapB.Top) div 2 else begin // No gaps. Make path around UnionRect(TempR, RangeGapA, RangeGapB); // Test links on TempR if SideA = sdEast then FlagA := TempR.Right - LinkPointA.x = LinkMinGap else FlagA := LinkPointA.x - TempR.Left = LinkMinGap; if SideB = sdEast then FlagB := TempR.Right - LinkPointB.x = LinkMinGap else FlagB := LinkPointB.x - TempR.Left = LinkMinGap; if FlagA and FlagB then begin // Make path around // Calc vertical pos (Temp.y) Size1 := Abs(LinkPointA.y - TempR.Top) + Abs(LinkPointB.y - TempR.Top); Size2 := Abs(LinkPointA.y - TempR.Bottom) + Abs(LinkPointB.y - TempR.Bottom); if Size1 < Size2 then Temp.y := TempR.Top else Temp.y := TempR.Bottom; end else begin // Calc points for long line from LinkPointA if SideA = sdEast then Points[1].x := TempR.Right else Points[1].x := TempR.Left; Points[2].x := Points[1].x; if LinkPointB.y < LinkPointA.y then Points[2].y := TempR.Top else Points[2].y := TempR.Bottom; Points[3].y := Points[2].y; if SideB = sdEast then Points[3].x := RangeGapB.Right else Points[3].x := RangeGapB.Left; Points[4].x := Points[3].x; Points[4].y := LinkPointB.y; // Calc distance Size1 := Abs(LinkPointA.x - Points[1].x) + Abs(Points[2].y - Points[1].y) + Abs(Points[3].x - Points[2].x) + Abs(Points[4].y - Points[3].y); // Calc points for long line from LinkPointA if SideA = sdEast then Points[1].x := RangeGapA.Right else Points[1].x := RangeGapA.Left; Points[2].x := Points[1].x; if LinkPointA.y < LinkPointB.y then Points[2].y := TempR.Top else Points[2].y := TempR.Bottom; Points[3].y := Points[2].y; if SideA = sdEast then Points[3].x := TempR.Left else Points[3].x := TempR.Right; Points[4].x := Points[3].x; Points[4].y := LinkPointB.y; // Calc distance Size2 := Abs(Points[2].y - Points[1].y) + Abs(Points[3].x - Points[2].x) + Abs(Points[4].y - Points[3].y) + Abs(LinkPointB.x - Points[4].x); if Size1 < Size2 then begin // Reconstruct link connection for long line from LinkPointA if SideA = sdEast then Points[1].x := TempR.Right else Points[1].x := TempR.Left; Points[2].x := Points[1].x; if LinkPointB.y < LinkPointA.y then Points[2].y := TempR.Top else Points[2].y := TempR.Bottom; Points[3].y := Points[2].y; if SideB = sdEast then Points[3].x := RangeGapB.Right else Points[3].x := RangeGapB.Left; Points[4].x := Points[3].x; Points[4].y := LinkPointB.y; end; end; end; // Build path if FlagA and FlagB then begin if SideA = sdEast then Points[1].x := RangeGapA.Right else Points[1].x := RangeGapA.Left; Points[2].x := Points[1].x; Points[2].y := Temp.y; if SideB = sdEast then Points[3].x := RangeGapB.Right else Points[3].x := RangeGapB.Left; Points[3].y := Temp.y; Points[4].x := Points[3].x; Points[4].y := LinkPointB.y; end; end; end else begin // LinkA and LinkB is North or South Points[1].x := LinkPointA.x; // Calc horizontal direction (Temp.x) // Test sides if SideA = SideB then begin // Unidirectional // Calc vertical gap center if RangeGapA.Top >= RangeGapB.Bottom then Temp.y := (RangeGapA.Top + RangeGapB.Bottom) div 2 // top gap else Temp.y := (RangeGapA.Bottom + RangeGapB.Top) div 2; // bottom gap if ((SideA = sdNorth) and (RangeGapA.Top > RangeGapB.Bottom)) or ((SideA = sdSouth) and (RangeGapA.Bottom < RangeGapB.Top)) then begin // Step near LinkA // Calc horizontal position by LinkB Size1 := Abs(LinkPointA.x - RangeGapB.Left) + Abs(LinkPointB.x - RangeGapB.Left); Size2 := Abs(LinkPointA.x - RangeGapB.Right) + Abs(LinkPointB.x - RangeGapB.Right); if Size1 < Size2 then Temp.x := RangeGapB.Left else Temp.x := RangeGapB.Right; // Build path Points[1].y := Temp.y; Points[2].y := Temp.y; Points[2].x := Temp.x; if SideA = sdNorth then Points[3].y := RangeGapB.Top else Points[3].y := RangeGapB.Bottom; Points[3].x := Temp.x; Points[4].y := Points[3].y; Points[4].x := LinkPointB.x; end else begin // Step near LinkB // Calc vertical position by LinkA Size1 := Abs(LinkPointA.x - RangeGapA.Left) + Abs(LinkPointB.x - RangeGapA.Left); Size2 := Abs(LinkPointA.x - RangeGapA.Right) + Abs(LinkPointB.x - RangeGapA.Right); if Size1 < Size2 then Temp.x := RangeGapA.Left else Temp.x := RangeGapA.Right; // Build path if SideA = sdNorth then Points[1].y := RangeGapA.Top else Points[1].y := RangeGapA.Bottom; Points[2].y := Points[1].y; Points[2].x := Temp.x; Points[3].y := Temp.y; Points[3].x := Temp.x; Points[4].y := Temp.y; Points[4].x := LinkPointB.x; end; end else begin // Contradirectional FlagA := true; FlagB := true; // Test horizontal gap if RangeGapA.Left >= RangeGapB.Right then Temp.x := (RangeGapA.Left + RangeGapB.Right) div 2 else if RangeGapA.Right <= RangeGapB.Left then Temp.x := (RangeGapA.Right + RangeGapB.Left) div 2 else begin // No gaps. Make path around UnionRect(TempR, RangeGapA, RangeGapB); // Test links on TempR if SideA = sdNorth then FlagA := LinkPointA.y - TempR.Top = LinkMinGap else FlagA := TempR.Bottom - LinkPointA.y = LinkMinGap; if SideB = sdNorth then FlagB := LinkPointB.y - TempR.Top = LinkMinGap else FlagB := TempR.Bottom - LinkPointB.y = LinkMinGap; if FlagA and FlagB then begin // Make path around // Calc horizontal pos (Temp.x) Size1 := Abs(LinkPointA.x - TempR.Left) + Abs(LinkPointB.x - TempR.Left); Size2 := Abs(LinkPointA.x - TempR.Right) + Abs(LinkPointB.x - TempR.Right); if Size1 < Size2 then Temp.x := TempR.Left else Temp.x := TempR.Right; end else begin // Calc points for long line from LinkPointA if SideA = sdNorth then Points[1].y := TempR.Top else Points[1].y := TempR.Bottom; Points[2].y := Points[1].y; if LinkPointB.x < LinkPointA.x then Points[2].x := TempR.Left else Points[2].x := TempR.Right; Points[3].x := Points[2].x; if SideB = sdNorth then Points[3].y := RangeGapB.Top else Points[3].y := RangeGapB.Bottom; Points[4].y := Points[3].y; Points[4].x := LinkPointB.x; // Calc distance Size1 := Abs(LinkPointA.y - Points[1].y) + Abs(Points[2].x - Points[1].x) + Abs(Points[3].y - Points[2].y) + Abs(Points[4].x - Points[3].x); // Calc points for long line from LinkPointA if SideA = sdNorth then Points[1].y := RangeGapA.Top else Points[1].y := RangeGapA.Bottom; Points[2].y := Points[1].y; if LinkPointA.x < LinkPointB.x then Points[2].x := TempR.Left else Points[2].x := TempR.Right; Points[3].x := Points[2].x; if SideB = sdNorth then Points[3].y := TempR.Top else Points[3].y := TempR.Bottom; Points[4].y := Points[3].y; Points[4].x := LinkPointB.x; // Calc distance Size2 := Abs(Points[2].x - Points[1].x) + Abs(Points[3].y - Points[2].y) + Abs(Points[4].x - Points[3].x) + Abs(LinkPointB.y - Points[4].y); if Size1 < Size2 then begin // Reconstruct link connection for long line from LinkPointA if SideA = sdNorth then Points[1].y := TempR.Top else Points[1].y := TempR.Bottom; Points[2].y := Points[1].y; if LinkPointB.x < LinkPointA.x then Points[2].x := TempR.Left else Points[2].x := TempR.Right; Points[3].x := Points[2].x; if SideB = sdNorth then Points[3].y := RangeGapB.Top else Points[3].y := RangeGapB.Bottom; Points[4].y := Points[3].y; Points[4].x := LinkPointB.x; end; end; end; // Build path if FlagA and FlagB then begin if SideA = sdNorth then Points[1].y := RangeGapA.Top else Points[1].y := RangeGapA.Bottom; Points[2].y := Points[1].y; Points[2].x := Temp.x; if SideB = sdNorth then Points[3].y := RangeGapB.Top else Points[3].y := RangeGapB.Bottom; Points[3].x := Temp.x; Points[4].y := Points[3].y; Points[4].x := LinkPointB.x; end; end; end; end; end; Points[0] := Params.LinkPointA; Points[Count-1] := Params.LinkPointB; Result := true; end; function TrySelfLinkOrtogonal(PtCount: integer; SideA, SideB: TSide): boolean; var Codirectional: boolean; IsHorizA, IsHorizB: boolean; Dest1, Dest2: integer; Temp: TPoint; begin Result := false; // Define side type (horizontal or vertical) IsHorizA := SideA in [sdEast, sdWest]; IsHorizB := SideB in [sdEast, sdWest]; // Define codirectional sides (both horizontal or both vertical) Codirectional := (IsHorizA and IsHorizB) or (not IsHorizA and not IsHorizB); with Params do begin if Codirectional then begin // Check point count if PtCount <> 4 then exit; // Linking possible SetCount(6); if IsHorizA then begin // SideA is sdEast or sdWest Dest1 := (LinkPointA.y - RangeGapA.Top) + (LinkPointB.y - RangeGapA.Top); Dest2 := (RangeGapA.Bottom - LinkPointA.y) + (RangeGapA.Bottom - LinkPointB.y); if Dest1 < Dest2 then Temp.y := RangeGapA.Top else Temp.y := RangeGapA.Bottom; if SideA = sdEast then Points[1].x := RangeGapA.Right else Points[1].x := RangeGapA.Left; Points[1].y := LinkPointA.y; Points[2].x := Points[1].x; Points[2].y := Temp.y; if SideB = sdEast then Points[3].x := RangeGapA.Right else Points[3].x := RangeGapA.Left; Points[3].y := Temp.y; Points[4].x := Points[3].x; Points[4].y := LinkPointB.y; end else begin // SideA is sdNorth or sdSouth Dest1 := (LinkPointA.x - RangeGapA.Left) + (LinkPointB.x - RangeGapA.Left); Dest2 := (RangeGapA.Right - LinkPointA.x) + (RangeGapA.Right - LinkPointB.x); if Dest1 < Dest2 then Temp.x := RangeGapA.Left else Temp.x := RangeGapA.Right; Points[1].x := LinkPointA.x; if SideA = sdNorth then Points[1].y := RangeGapA.Top else Points[1].y := RangeGapA.Bottom; Points[2].x := Temp.x; Points[2].y := Points[1].y; Points[3].x := Temp.x; if SideB = sdNorth then Points[3].y := RangeGapA.Top else Points[3].y := RangeGapA.Bottom; Points[4].x := LinkPointB.x; Points[4].y := Points[3].y; end; end else begin // Check point count if PtCount <> 3 then exit; // Linking possible SetCount(5); if IsHorizA then begin // SideA is sdEast or sdWest if SideA = sdEast then Points[1].x := RangeGapA.Right else Points[1].x := RangeGapA.Left; Points[1].y := LinkPointA.y; Points[2].x := Points[1].x; if SideB = sdNorth then Points[2].y := RangeGapA.Top else Points[2].y := RangeGapA.Bottom; Points[3].x := LinkPointB.x; Points[3].y := Points[2].y; end else begin // SideA is sdNorth or sdSouth Points[1].x := LinkPointA.x; if SideA = sdNorth then Points[1].y := RangeGapA.Top else Points[1].y := RangeGapA.Bottom; if SideB = sdEast then Points[2].x := RangeGapA.Right else Points[2].x := RangeGapA.Left; Points[2].y := Points[1].y; Points[3].x := Points[2].x; Points[3].y := LinkPointB.y; end; end; Points[0] := LinkPointA; Points[Count-1] := LinkPointB; end; Result := true; end; function LinkAnyCase(SideA, SideB: TSide): boolean; var Codirectional: boolean; IsHorizA, IsHorizB: boolean; Straight: boolean; Dist: integer; begin // Define side type (horizontal or vertical) IsHorizA := SideA in [sdEast, sdWest]; IsHorizB := SideB in [sdEast, sdWest]; // Define codirectional sides (both horizontal or both vertical) Codirectional := (IsHorizA and IsHorizB) or (not IsHorizA and not IsHorizB); with Params do begin if Codirectional then begin // 0 or 2 intermediate points if IsHorizA then Straight := LinkPointA.y = LinkPointB.y else Straight := LinkPointA.x = LinkPointB.x; if Straight then // 0 intermediate points - straight line SetCount(2) else begin // 2 intermediate points - zigzig SetCount(4); if IsHorizA then begin Dist := (LinkPointA.x + LinkPointB.x) div 2; Points[1].x := Dist; Points[1].y := LinkPointA.y; Points[2].x := Dist; Points[2].y := LinkPointB.y; end else begin Dist := (LinkPointA.y + LinkPointB.y) div 2; Points[1].x := LinkPointA.x; Points[1].y := Dist; Points[2].x := LinkPointB.x; Points[2].y := Dist; end; end; end else begin // 1 intermediate point SetCount(3); if IsHorizA then begin Points[1].x := LinkPointB.x; Points[1].y := LinkPointA.y; end else begin Points[1].x := LinkPointA.x; Points[1].y := LinkPointB.y; end; end; Points[0] := LinkPointA; Points[Count-1] := LinkPointB; end; Result := true; end; procedure CalcRangeGaps; begin if RangeGapExist then exit; with Params do if SelfLink then begin // Include in RangeGapA LinkPoints coors and inflate by LinkMinGap RangeGapA := RangeA; if LinkPointA.x < RangeGapA.Left then RangeGapA.Left := LinkPointA.x else if LinkPointA.x > RangeGapA.Right then RangeGapA.Right := LinkPointA.x; if LinkPointA.y < RangeGapA.Top then RangeGapA.Top := LinkPointA.y else if LinkPointA.y > RangeGapA.Bottom then RangeGapA.Bottom := LinkPointA.y; if LinkPointB.x < RangeGapA.Left then RangeGapA.Left := LinkPointB.x else if LinkPointB.x > RangeGapA.Right then RangeGapA.Right := LinkPointB.x; if LinkPointB.y < RangeGapA.Top then RangeGapA.Top := LinkPointB.y else if LinkPointB.y > RangeGapA.Bottom then RangeGapA.Bottom := LinkPointB.y; InflateRect(RangeGapA, LinkMinGap, LinkMinGap); // Set RangeGapB equal to RangeGapA RangeGapB := RangeGapA; end else begin // Calc ranges with min gap RangeGapA := RangeA; if LinkPointA.x < RangeGapA.Left then RangeGapA.Left := LinkPointA.x else if LinkPointA.x > RangeGapA.Right then RangeGapA.Right := LinkPointA.x; if LinkPointA.y < RangeGapA.Top then RangeGapA.Top := LinkPointA.y else if LinkPointA.y > RangeGapA.Bottom then RangeGapA.Bottom := LinkPointA.y; InflateRect(RangeGapA, LinkMinGap, LinkMinGap); RangeGapB := RangeB; if LinkPointB.x < RangeGapB.Left then RangeGapB.Left := LinkPointB.x else if LinkPointB.x > RangeGapB.Right then RangeGapB.Right := LinkPointB.x; if LinkPointB.y < RangeGapB.Top then RangeGapB.Top := LinkPointB.y else if LinkPointB.y > RangeGapB.Bottom then RangeGapB.Bottom := LinkPointB.y; InflateRect(RangeGapB, LinkMinGap, LinkMinGap); end; RangeGapExist := true; end; function IsLineIntersectRect(const PointA, PointB: TPoint; const R: TRect): boolean; var CodeA, CodeB: cardinal; begin CodeA := byte(PointA.y <= R.Top) shl 3 or byte(PointA.y >= R.Bottom) shl 2 or byte(PointA.x >= R.Right) shl 1 or byte(PointA.x <= R.Left); CodeB := byte(PointB.y <= R.Top) shl 3 or byte(PointB.y >= R.Bottom) shl 2 or byte(PointB.x >= R.Right) shl 1 or byte(PointB.x <= R.Left); Result := CodeA and CodeB = 0; end; var i: integer; Method: integer; SidesA, SidesB: TSides; SideA, SideB: TSide; NeedFull: boolean; IsHoriz: boolean; begin Result := false; // Test counts Count := Length(Points); if Count <> Length(PointTypes) then exit; // Test point types (support line's only and only not closed and with one figure) for i:=0 to Count-2 do if PointTypes[i] <> ptNode then exit; if (Count > 0) and (PointTypes[Count-1] <> ptEndNode) then exit; with Params do begin if Mode = rmAsNeeded then begin // Test count for full reroute NeedFull := false; if Count < 2 then NeedFull := true else // Test ortogonal for full reroute if Ortogonal then // Check all ortogonal segments for i:=0 to Count-2 do if (Points[i].x <> Points[i+1].x) and (Points[i].y <> Points[i+1].y) then begin // Slant line NeedFull := true; break; end; end else NeedFull := Mode = rmAlways; RangeGapExist := false; repeat // Reroute if NeedFull then begin if Ortogonal then begin CalcRangeGaps; // Calc active sides SidesA := CalcSides(LinkPointA, RangeGapA); SidesB := CalcSides(LinkPointB, RangeGapB); // Check error if (SidesA = []) or (SidesB = []) then exit; // Find link method (count of intermediate points) for Method:=0 to 4 do begin for SideA:=Low(SideA) to High(SideA) do begin if not (SideA in SidesA) then continue; for SideB:=Low(SideB) to High(SideB) do begin if not (SideB in SidesB) then continue; if SelfLink then Result := TrySelfLinkOrtogonal(Method, SideA, SideB) else Result := TryLinkOrtogonal(Method, SideA, SideB); if Result then exit; end; end; end; { // Method not found - link straight line SetCount(2); Points[0] := LinkPointA; Points[Count-1] := LinkPointB; } // Method not found - link with minimal points for SideA:=Low(SideA) to High(SideA) do begin if not (SideA in SidesA) then continue; for SideB:=Low(SideB) to High(SideB) do begin if not (SideB in SidesB) then continue; if LinkAnyCase(SideA, SideB) then break; end; end; end else begin // Move end points to link points {if Count < 2 then }SetCount(2); Points[0] := LinkPointA; Points[Count-1] := LinkPointB; end; break; // connector rerouted end else begin // Don't rerout if Ortogonal then begin // Check count and LinkPoints position if (Count >= 2) and ( (LinkPointA.x <> Points[0].x) or (LinkPointA.y <> Points[0].y) or (LinkPointB.x <> Points[Count-1].x) or (LinkPointB.y <> Points[Count-1].y)) then begin if Count = 2 then begin // Can't save ortogonal. Just move first and end points to link points Points[0] := LinkPointA; Points[1] := LinkPointB; end else begin // Move first point to LinkPointA // IsHoriz := Points[0].y = Points[1].y; i := 1; IsHoriz := true; repeat if (Points[i-1].x <> Points[i].x) or (Points[i-1].y <> Points[i].y) then begin // Define segment position IsHoriz := Points[i-1].y = Points[i].y; if i and 1 = 0 then IsHoriz := not IsHoriz; break; end; inc(i); until i = Length(Points); Points[0] := LinkPointA; if IsHoriz then Points[1].y := LinkPointA.y else Points[1].x := LinkPointA.x; // Move last point to LinkPointA // IsHoriz := Points[Count-1].y = Points[Count-2].y; i := Length(Points)-1; IsHoriz := true; repeat if (Points[i-1].x <> Points[i].x) or (Points[i-1].y <> Points[i].y) then begin // Define segment position IsHoriz := Points[i-1].y = Points[i].y; if i and 1 <> (Length(Points)-1) and 1 then IsHoriz := not IsHoriz; break; end; dec(i); until i = 0; Points[Count-1] := LinkPointB; if IsHoriz then Points[Count-2].y := LinkPointB.y else Points[Count-2].x := LinkPointB.x; end; end else begin // Just move first and end points to link points Points[0] := LinkPointA; Points[Count-1] := LinkPointB; end; end else begin // Non ortogonal link without reroute Points[0] := LinkPointA; Points[Count-1] := LinkPointB; end; if Mode = rmAsNeeded then begin // Check overlaping (connector with connected objects) CalcRangeGaps; for i:=0 to Count-2 do begin // Test segment for intersection with object ranges if i > 0 then NeedFull := IsLineIntersectRect(Points[i], Points[i+1], RangeGapA) else NeedFull := IsLineIntersectRect(Points[i], Points[i+1], RangeA); if NeedFull then break; if i < Count-2 then NeedFull := IsLineIntersectRect(Points[i], Points[i+1], RangeGapB) else NeedFull := IsLineIntersectRect(Points[i], Points[i+1], RangeB); if NeedFull then break; end; end; end; // Repeat if NeedFull changed to true until not NeedFull; end; Result := true; end; procedure GetPathInfo(const Points: TPointArray; const Types: TPointTypeArray; var Info: TPathInfo); var i, Count, LastCount: integer; FigIndex, FigCount: integer; FirstNodeIndex: integer; begin Info.IsCurve := false; Count := Length(Points); if (Count = 0) or (Count <> Length(Types)) then begin Info.Figures := Nil; exit; end; FigCount := Length(Info.Figures); FigIndex := -1; FirstNodeIndex := 0; with Info do begin PointCount := Count; for i:=0 to Count-1 do begin if i = FirstNodeIndex then begin // Start of figure inc(FigIndex); if FigIndex >= FigCount then begin FigCount := FigIndex+1; SetLength(Figures, FigCount); end; with Figures[FigIndex] do begin FirstNode := FirstNodeIndex; LastNode := -1; LastPoint := -1; IsClosed := false; IsCurve := false; end; end; case Types[i] of ptControl: // Curve point in figure Figures[FigIndex].IsCurve := true; ptEndNode, ptEndNodeClose: with Figures[FigIndex] do begin // End of figure LastNode := i; IsClosed := Types[i] = ptEndNodeClose; if (i < Count-2) and (Types[i+1] = ptControl) then begin LastCount := 3; IsCurve := true; end else LastCount := 1; FirstNodeIndex := i + LastCount; LastPoint := i + LastCount-1; Info.IsCurve := Info.IsCurve or IsCurve; end; end; end; end; if FigIndex < FigCount-1 then SetLength(Info.Figures, FigIndex+1); end; function GetFigureIndex(const Info: TPathInfo; PointIndex: integer): integer; var i: integer; begin Result := -1; for i:=0 to Length(Info.Figures)-1 do with Info.Figures[i] do if (PointIndex >= FirstNode) and (PointIndex <= LastPoint) then begin Result := i; break; end; end; function ChangePathCount(var Points: TPointArray; var Types: TPointTypeArray; Index, Delta: integer): boolean; var Count: integer; begin Count := Length(Points); Result := (Count = Length(Types)) and (Index >= 0) and (Index <= Count); if not Result then exit; if Delta > 0 then begin SetLength(Points, Count + Delta); SetLength(Types, Count + Delta); end else dec(Index, Delta); Move(Points[Index], Points[Index+Delta], (Count - Index) * SizeOf(Points[0])); Move(Types[Index], Types[Index+Delta], (Count - Index) * SizeOf(Types[0])); if Delta < 0 then begin SetLength(Points, Count + Delta); SetLength(Types, Count + Delta); end; end; end.
unit MainPageMod; interface uses Windows, Messages, SysUtils, Classes, HTTPApp, WebModu, HTTPProd, ReqMulti, WebSess, WebDisp, WebAdapt, WebComp, WebUsers; type TMainPageModule = class(TWebAppPageModule) PageProducer: TPageProducer; WebAppComponents: TWebAppComponents; ApplicationAdapter: TApplicationAdapter; EndUserSessionAdapter: TEndUserSessionAdapter; PageDispatcher: TPageDispatcher; AdapterDispatcher: TAdapterDispatcher; SessionsService: TSessionsService; PersistWebUserList: TWebUserList; RightsAdapter: TAdapter; Rights: TAdapterField; procedure WebAppPageModuleCreate(Sender: TObject); procedure WebAppPageModuleActivate(Sender: TObject); procedure WebAppPageModuleDeactivate(Sender: TObject); procedure RightsGetValue(Sender: TObject; var Value: Variant); private function GetUsersFileName: string; procedure LoadUserList; public procedure SaveUserList; function GetCurrentUserName: string; end; function MainPageModule: TMainPageModule; const cMainPageModTitle = 'MainPageModule'; resourcestring rNotLoggedIn = 'You are not currently logged in. Please log back in.'; implementation {$R *.dfm} {*.html} uses WebReq, WebCntxt, WebFact, Variants, SiteComp; var Lock: TMultiReadExclusiveWriteSynchronizer; resourcestring rHomePageTitle = 'Home Page'; rHomePageDescription = 'Welcome to this application'; function MainPageModule: TMainPageModule; begin Result := TMainPageModule(WebContext.FindModuleClass(TMainPageModule)); end; function TMainPageModule.GetUsersFileName: string; begin Result := ExtractFilePath(GetModuleName(HInstance)) + 'users.binary'; end; procedure TMainPageModule.SaveUserList; begin Lock.BeginWrite; try PersistWebUserList.SaveToFile(GetUsersFileName) finally Lock.EndWrite; end; end; procedure TMainPageModule.WebAppPageModuleCreate(Sender: TObject); begin // Up the emax connections (concurrent web modules) if WebRequestHandler <> nil then WebRequestHandler.MaxConnections := 100; end; procedure TMainPageModule.WebAppPageModuleActivate(Sender: TObject); begin // Because multiple instances of a WebPageModule are possible, // I have to reload the PersistWebUserList in case another web module // changed it. A speed imporovement would be to check to see // if the timestamp of the 'users.binary' file has changed, and only // reload it then. LoadUserList; end; procedure TMainPageModule.LoadUserList; begin // load up previous sessions and user information Lock.BeginRead; try try if FileExists(GetUsersFileName) then PersistWebUserList.LoadFromFile(GetUsersFileName) except end; finally Lock.EndRead; end; end; procedure TMainPageModule.WebAppPageModuleDeactivate(Sender: TObject); begin SaveUserList; end; function TMainPageModule.GetCurrentUserName: string; var WebUserItem: TWebUserItem; begin Result := ''; with MainPageModule do begin if not VarIsEmpty(EndUserSessionAdapter.UserID) then begin WebUserItem := PersistWebUserList.UserItems.FindUserID(EndUserSessionAdapter.UserId); if WebUserItem <> nil then Result := WebUserItem.UserName; end; end; end; procedure TMainPageModule.RightsGetValue(Sender: TObject; var Value: Variant); var WebUserItem: TWebUserItem; begin Value := ''; if not VarIsEmpty(EndUserSessionAdapter.UserID) then begin WebUserItem := PersistWebUserList.UserItems.FindUserID(EndUserSessionAdapter.UserId); if WebUserItem <> nil then Value := WebUserItem.AccessRights; end; end; initialization if WebRequestHandler <> nil then WebRequestHandler.AddWebModuleFactory( TWebAppPageModuleFactory.Create(TMainPageModule, TWebPageInfo.Create([wpPublished {, wpLoginRequired}], '.html', cMainPageModTitle, rHomePageTitle, rHomePageDescription), caCache)); Lock := TMultiReadExclusiveWriteSynchronizer.Create; finalization Lock.Free; end.
unit UtNau; interface uses UtVaixell, Uterror, Vcl.Dialogs, System.SysUtils, System.Classes; const NUM_VAIXELLS = 50; type Tnau = class private v_vaixells: array [0..NUM_VAIXELLS -1] of TVaixell; function primera_pos_lliure:integer; procedure vaixell_averiat(id:integer); procedure vaixell_arreglat(id:integer); public err:Terror; onEspatllat:procedure (id:integer) of object; onArreglat:procedure (id:integer) of object; onMeteo: procedure (pos:integer; temps:char) of object; onEnfonsat: procedure (pos:integer) of object; constructor crear_nau; destructor destruir_nau; function destruir_vaixells (i:integer):boolean; function crear_vaixell(codi,naviera,port:string;capacitat:integer):integer; function consultar_capacitat(vaixell:integer):integer; function consultar_desgast(vaixell:integer):extended; function consultar_codi(vaixell:integer):string; function buscarCodiRepetit(codi:string):boolean; function consultar_carrega(vaixell:integer):integer; function destruir_vaixell(vaixell:integer):boolean; function navegar_vaixell(vaixell:integer):boolean; function carregar_vaixell(vaixell:integer;quantitat:integer):boolean; function Posar_Manteniment(vaixell:integer):boolean; function Fi_manteniment(vaixell:integer):boolean; function descarregar_vaixell(vaixell:integer):boolean; function atracar_vaixell(vaixell:integer):boolean; function consultar_naviera(vaixell:integer):string; function consultar_port(vaixell:integer):string; function consultar_estat(vaixell:integer):integer; procedure buscar_naviera(naviera: string; llistat:TStrings); procedure canviar_temps (id:integer; estat: char); end; implementation { Tnau } function Tnau.atracar_vaixell(vaixell: integer): boolean; var res:boolean; begin res := false; if self.v_vaixells[vaixell] <> nil then begin if self.v_vaixells[vaixell].consultar_estat = 2 then begin self.v_vaixells[vaixell].atracar; res := true; end else begin err.codierror := -111; end; end else begin err.codierror := -103; end; result := res; end; function Tnau.buscarCodiRepetit(codi: string): boolean; var i:integer; res:boolean; begin i := 0; res := false; while ((i < NUM_VAIXELLS) and (res = false))do begin if self.v_vaixells[i] <> nil then begin if self.v_vaixells[i].consultar_codi = codi then begin res := true; end; end; i := i + 1; end; result := res; end; procedure Tnau.buscar_naviera(naviera: string; llistat:TStrings); var i:integer; estat:string; begin for i := 0 to NUM_VAIXELLS do begin if self.v_vaixells[i]<>nil then begin if self.v_vaixells[i].consultar_naviera=naviera then begin if v_vaixells[i].consultar_estat=2 then begin estat:='MAR'; end else begin if v_vaixells[i].consultar_estat=4 then begin estat:='En Manteniment'; end else begin estat:='NO esta en manteniment'; end; end; llistat.Add(v_vaixells[i].consultar_codi+'|Capacitat: '+inttostr(v_vaixells[i].consultar_capacitat)+'|Port Actual: '+v_vaixells[i].consultar_port_actual+ '|'+estat+'|Carrega: '+inttostr(v_vaixells[i].consultar_carregat)+'|Desgast: '+floattostr(v_vaixells[i].consultar_desgast)); end; end; end; end; procedure Tnau.canviar_temps(id:integer; estat: char); begin if (self.v_vaixells[id].consultar_estat = 2) OR (self.v_vaixells[id].consultar_estat = 3) then begin if estat=chr(221) then begin self.v_vaixells[id].incrementar_desgast(2); end; if estat=chr(218) then begin self.v_vaixells[id].incrementar_desgast(1); end; self.onMeteo(id, estat); end; if self.v_vaixells[id].consultar_desgast>100 then begin self.v_vaixells[id].canviar_estat(1); onEnfonsat(id); self.destruir_vaixells(id); end; end; function Tnau.carregar_vaixell(vaixell: integer;quantitat:integer): boolean; var res : boolean; begin res := false; if self.v_vaixells[vaixell] <> nil then begin if self.v_vaixells[vaixell].consultar_estat = 1 then begin if self.v_vaixells[vaixell].carregar(quantitat) then begin res := true; end else begin //error en utvaixell self.err.codierror := self.v_vaixells[vaixell].err.codierror; end; end else begin self.err.codierror := -105; end; end else begin //vaixell = nil self.err.codierror := -103; end; result := res; end; function Tnau.consultar_capacitat(vaixell: integer): integer; var res:integer; begin res := self.v_vaixells[vaixell].consultar_capacitat; result := res; end; function Tnau.consultar_carrega(vaixell:integer): integer; begin result := self.v_vaixells[vaixell].consultar_carregat; end; function Tnau.consultar_codi(vaixell: integer): string; begin result := self.v_vaixells[vaixell].consultar_codi; end; function Tnau.consultar_desgast(vaixell: integer): extended; begin result := self.v_vaixells[vaixell].consultar_desgast; end; function Tnau.consultar_estat(vaixell: integer): integer; begin result := self.v_vaixells[vaixell].consultar_estat; end; function Tnau.consultar_naviera(vaixell: integer): string; begin result := self.v_vaixells[vaixell].consultar_naviera; end; function Tnau.consultar_port(vaixell: integer): string; begin result := self.v_vaixells[vaixell].consultar_port_actual; end; constructor Tnau.crear_nau; var i:integer; begin for I := 0 to NUM_VAIXELLS - 1 do begin self.v_vaixells[i] := nil; //self.v_vaixells[i].onMeteo:=self.canviar_temps; end; self.err := Terror.Create; end; function Tnau.crear_vaixell(codi, naviera, port: string; capacitat: integer): integer; var pos:integer; begin pos := self.primera_pos_lliure; if pos >= 0 then begin if buscarCodiRepetit(codi) = false then begin self.v_vaixells[pos] := TVaixell.crear(pos,codi,naviera,port,capacitat); self.v_vaixells[pos].onEspatllat := self.vaixell_averiat; self.v_vaixells[pos].onArreglat := self.vaixell_arreglat; self.v_vaixells[pos].onMeteo:=self.canviar_temps; end else begin err.codierror := -102; pos := -1; end; end else begin self.err.codierror := -101; end; result := pos; end; function Tnau.descarregar_vaixell(vaixell: integer): boolean; var res:boolean; begin res := false; if self.v_vaixells[vaixell] <> nil then begin if self.v_vaixells[vaixell].consultar_estat = 1 then begin if self.v_vaixells[vaixell].consultar_carregat >= self.v_vaixells[vaixell].consultar_capacitat * 0.9 then begin self.v_vaixells[vaixell].descarregar; res := true; end else begin err.codierror := -109; end; end else begin err.codierror := -108; end; end else begin err.codierror := -103; end; result := res; end; destructor Tnau.destruir_nau; var i:integer; begin for i := 0 to NUM_VAIXELLS -1 do begin self.destruir_vaixells(i); end; self.err.Destroy; end; function Tnau.destruir_vaixell(vaixell: integer): boolean; var res:boolean; begin res:=true; if self.v_vaixells[vaixell] <> nil then begin if self.v_vaixells[vaixell].consultar_estat = 4 then begin self.v_vaixells[vaixell].Destroy; self.v_vaixells[vaixell] := nil; end else begin err.codierror := -104; res := false; end; end else begin // vaixell escollit nil err.codierror := -103; res := false; end; result := res; end; function Tnau.destruir_vaixells(i: integer): boolean; var res:boolean; begin res:= TRUE; if self.v_vaixells[i] <> nil then begin self.v_vaixells[i].destruir; self.v_vaixells[i] := nil; end else begin res:=FALSE; self.err.codiError := -103; end; result := res; end; function Tnau.Fi_manteniment(vaixell: integer): boolean; var res:boolean; begin res := false; if self.v_vaixells[vaixell] <> nil then begin if self.v_vaixells[vaixell].consultar_estat = 4 then begin self.v_vaixells[vaixell].treure_manteniment; res := true; end else begin //vaixell no esta a port self.err.codierror := -107; end; end else begin err.codierror := -103; end; result := res; end; function Tnau.navegar_vaixell(vaixell: integer): boolean; var res:boolean; begin if self.v_vaixells[vaixell] <> nil then begin res := self.v_vaixells[vaixell].navegar; self.err.codierror := self.v_vaixells[vaixell].err.codierror; end else begin self.err.codierror := -103; res := false; end; result := res; end; function Tnau.Posar_Manteniment(vaixell: integer): boolean; var res:boolean; desgast:integer; begin res := false; if self.v_vaixells[vaixell] <> nil then begin if self.v_vaixells[vaixell].consultar_estat = 1 then begin if self.v_vaixells[vaixell].consultar_carregat < self.v_vaixells[vaixell].consultar_capacitat * 0.9 then begin self.v_vaixells[vaixell].posar_manteniment; res := true; end else begin self.err.codierror := -110; end; end else begin //vaixell no esta a port self.err.codierror := -106; end; end else begin err.codierror := -103; end; result := res ; end; function Tnau.primera_pos_lliure: integer; var i:integer; begin i:=0; while ((self.v_vaixells[i] <> nil) and (i < NUM_VAIXELLS)) do begin i := i + 1; end; if i = NUM_VAIXELLS then begin i := -1; end; result := i; end; procedure Tnau.vaixell_arreglat(id: integer); begin self.onArreglat(id); end; procedure Tnau.vaixell_averiat(id: integer); begin self.onEspatllat(id); end; end.
unit fOrdersTS; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, fAutoSz, StdCtrls, ORCtrls, ORFn, ExtCtrls, rOrders, ORDtTm, mEvntDelay,uConst, VA508AccessibilityManager, ORNet, Vcl.ComCtrls, Vcl.OleCtrls, SHDocVw, rCore, ShellApi; type TfrmOrdersTS = class(TfrmAutoSz) pnlMiddle: TPanel; pnlTop: TPanel; lblPtInfo: TVA508StaticText; grpChoice: TGroupBox; radDelayed: TRadioButton; pnldif: TPanel; Image1: TImage; cmdOK: TButton; cmdCancel: TButton; pnlBottom: TPanel; fraEvntDelayList: TfraEvntDelayList; radReleaseNow: TRadioButton; memHelp: TRichEdit; btnHelp: TButton; procedure cmdOKClick(Sender: TObject); procedure cmdCancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure radDelayedClick(Sender: TObject); procedure radReleaseNowClick(Sender: TObject); procedure fraEvntDelayListcboEvntListChange(Sender: TObject); procedure UMStillDelay(var message: TMessage); message UM_STILLDELAY; procedure fraEvntDelayListmlstEventsDblClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure fraEvntDelayListmlstEventsChange(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormResize(Sender: TObject); procedure btnHelpClick(Sender: TObject); private OKPressed: Boolean; FResult : Boolean; helpString: string; FImmediatelyRelease: boolean; FCurrSpecialty: string; F1stClick: Boolean; end; function ShowDelayedEventsTreatingSepecialty(const ARadCaption: string; var AnEvent: TOrderDelayEvent; var ADlgLst: TStringlist; var ReleaseNow: boolean; AnLimitEvent: Char = #0): Boolean; var frmOrdersTS: TfrmOrdersTS; implementation uses ucore,fOrders, rMisc; {$R *.DFM} const TX_TRANSFER1= 'You selected the Transfer delayed event'; TX_TRANSFER = 'The release of orders entered ' + 'will be delayed until the patient is transferred to the ' + 'following specialty.'; TX_ADMIT1 = 'You selected the Admit delayed event'; TX_ADMIT = 'The release of orders entered ' + 'will be delayed until the patient is admitted to the ' + 'following specialty.'; TX_XISTEVT1 = 'Delayed orders already exist for event Delayed '; TX_XISTEVT2 = #13 + 'Do you want to view those orders?'; TX_MCHEVT1 = ' is already assigned to '; TX_MCHEVT2 = #13 + 'Do you still want to write delayed orders?'; function ShowDelayedEventsTreatingSepecialty(const ARadCaption: string; var AnEvent: TOrderDelayEvent; var ADlgLst: TStringlist; var ReleaseNow: boolean; AnLimitEvent: Char = #0): Boolean; var EvtInfo,speCap: string; begin frmOrdersTS := TfrmOrdersTS.Create(Application); frmOrdersTS.FCurrSpecialty := Piece(GetCurrentSpec(Patient.DFN),'^',1); frmOrdersTS.fraEvntDelayList.UserDefaultEvent := StrToIntDef(GetDefaultEvt(IntToStr(User.DUZ)),0); SetFormPosition(frmOrdersTS); //frmOrdersTs.fraEvntDelayList.Top := frmOrdersTS.Height - Result := frmOrdersTS.FResult; if Length(ARadCapTion)>0 then frmOrdersTS.radDelayed.Caption := ARadCaption; try ResizeFormToFont(TForm(frmOrdersTS)); if Length(frmOrdersTS.FCurrSpecialty)>0 then SpeCap := #13 + 'The current treating specialty is ' + frmOrdersTS.FCurrSpecialty else SpeCap := #13 + 'No treating specialty is available.'; if Patient.Inpatient then frmOrdersTS.lblPtInfo.Caption := Patient.Name + ' is currently admitted to ' + Encounter.LocationName + SpeCap else begin if (EnCounter.Location > 0) then frmOrdersTS.lblPtInfo.Caption := Patient.Name + ' is currently on ' + Encounter.LocationName + SpeCap else frmOrdersTS.lblPtInfo.Caption := Patient.Name + ' currently is an outpatient.' + SpeCap; end; if not CharInSet(AnLimitEvent, ['A','D','T','M','O']) then AnLimitEvent := #0; frmOrdersTs.fraEvntDelayList.EvntLimit := AnLimitEvent; if AnEvent.EventIFN > 0 then begin frmOrdersTS.fraEvntDelayList.DefaultEvent := AnEvent.EventIFN; frmOrdersTS.radDelayed.Checked := True; end else begin frmOrdersTS.radReleaseNow.Enabled := True; frmOrdersTS.radReleaseNow.Checked := False; frmOrdersTS.radDelayed.Checked := False; end; frmOrdersTS.radDelayed.Checked := True; frmOrdersTS.ShowModal; if frmOrdersTS.FImmediatelyRelease then begin AnEvent.EventIFN := 0; AnEvent.EventName := ''; AnEvent.Specialty := 0; AnEvent.Effective := 0; ReleaseNow := frmOrdersTS.FImmediatelyRelease; Result := frmOrdersTS.FResult; end; if (frmOrdersTS.OKPressed) and (frmOrdersTS.radDelayed.Checked) then begin EvtInfo := frmOrdersTS.fraEvntDelayList.mlstEvents.Items[frmOrdersTS.fraEvntDelayList.mlstEvents.ItemIndex]; AnEvent.EventType := CharAt(Piece(EvtInfo,'^',3),1); AnEvent.EventIFN := StrToInt64Def(Piece(EvtInfo,'^',1),0); AnEvent.TheParent := TParentEvent.Create; if StrToInt64Def(Piece(EvtInfo,'^',13),0) > 0 then begin AnEvent.TheParent.Assign(Piece(EvtInfo,'^',13)); if AnEvent.EventType = #0 then AnEvent.EventType := AnEvent.TheParent.ParentType; end; AnEvent.EventName := frmOrdersTS.fraEvntDelayList.mlstEvents.DisplayText[frmOrdersTS.fraEvntDelayList.mlstEvents.ItemIndex]; AnEvent.Specialty := 0; if frmOrdersTS.fraEvntDelayList.orDateBox.Visible then AnEvent.Effective := frmOrdersTS.fraEvntDelayList.orDateBox.FMDateTime else AnEvent.Effective := 0; ADlgLst.Clear; if StrToIntDef(AnEvent.TheParent.ParentDlg,0)>0 then ADlgLst.Add(AnEvent.TheParent.ParentDlg) else if Length(Piece(EvtInfo,'^',5))>0 then ADlgLst.Add(Piece(EvtInfo,'^',5)); if Length(Piece(EvtInfo,'^',6))>0 then ADlgLst.Add(Piece(EvtInfo,'^',6)+ '^SET'); Result := frmOrdersTS.FResult; end; finally frmOrdersTS.Release; frmOrdersTS.FImmediatelyRelease := False; frmOrdersTS.FCurrSpecialty := ''; frmOrdersTS.fraEvntDelayList.ResetProperty; end; end; procedure TfrmOrdersTS.FormCreate(Sender: TObject); var msgData: TStringList; msgStr: string; begin inherited; if not Patient.Inpatient then pnldif.Visible := False; OKPressed := False; FResult := False; FImmediatelyRelease := False; F1stClick := True; FCurrSpecialty := ''; AutoSizeDisabled := true; msgData := TStringList.Create; CallVistA('ORDDPAPI RLSMSG',[],msgData); for msgStr in msgData do begin memHelp.Lines.Add(msgStr); end; FreeAndNil(msgData); helpString := GetUserParam('OR RELEASE FORM HELP'); btnHelp.Visible := false; memHelp.Width := memHelp.Width + btnHelp.Width; if (helpString <> '') then begin btnHelp.Visible := true; memHelp.Width := memHelp.Width - btnHelp.Width; end; end; {=========================================================================================} { RetrieveValueFromIndex - Acts like old ValueFromIndex } {-----------------------------------------------------------------------------------------} { XE3 changed the Value From Index to include calculating with the delimiter character. } { This routine uses the old method for calculating ValueFromIndex from D2006 } {=========================================================================================} function RetrieveValueFromIndex(s: TStrings; Index: integer): string; begin if Index >= 0 then Result := Copy(s[Index], Length(s.Names[Index]) + 2, MaxInt) else Result := ''; end; procedure TfrmOrdersTS.cmdOKClick(Sender: TObject); var tempStr: String; begin inherited; if grpChoice.Tag = 0 then begin InfoBox('A release event has not been selected.', 'No Selection Made', MB_OK); Exit; end; if( not (fraEvntDelayList.mlstEvents.ItemIndex >= 0) ) and (radDelayed.Checked) then begin InfoBox('A release event must be selected.', 'No Selection Made', MB_OK); Exit; end; // tempStr := fraEvntDelayList.mlstEvents.Items.ValueFromIndex[fraEvntDelayList.mlstEvents.ItemIndex]; tempStr := RetrieveValueFromIndex(fraEvntDelayList.mlstEvents.Items, fraEvntDelayList.mlstEvents.ItemIndex); // CQ 21556 if(fraEvntDelayList.mlstEvents.ItemIndex >= 0) and (Length(Piece(tempStr,'^',2))<1)then begin InfoBox('Invalid release event selected.', 'No Selection Made', MB_OK); Exit; end; if (fraEvntDelayList.mlstEvents.ItemIndex >= 0) and F1stClick then begin fraEvntDelayList.CheckMatch; if fraEvntDelayList.MatchedCancel then begin OKPressed := False; Close; Exit; end; end; OKPressed := True; FResult := True; Close; end; procedure TfrmOrdersTS.btnHelpClick(Sender: TObject); begin inherited; // InfoBox(helpString,'Info', MB_OK); ShellExecute(0, 'OPEN', PChar(helpString), '', '', SW_SHOWNORMAL); end; procedure TfrmOrdersTS.cmdCancelClick(Sender: TObject); begin inherited; FResult := False; Close; end; procedure TfrmOrdersTS.radDelayedClick(Sender: TObject); begin inherited; fraEvntDelayList.Visible := True; fraEvntDelayList.DisplayEvntDelayList; grpChoice.Tag := 1; end; procedure TfrmOrdersTS.radReleaseNowClick(Sender: TObject); begin inherited; grpChoice.Tag := 1; if InfoBox('Would you like to close this window and return to the Orders Tab?', 'Confirmation', MB_OKCANCEL or MB_ICONQUESTION) = IDOK then begin FImmediatelyRelease := True; FResult := False; Close; end else begin fraEvntDelayList.mlstEvents.Items.Clear; FImmediatelyRelease := False; radReleaseNow.Checked := False; radDelayed.Checked := True; end; end; procedure TfrmOrdersTS.fraEvntDelayListcboEvntListChange(Sender: TObject); begin inherited; fraEvntDelayList.mlstEventsChange(Sender); F1stClick := False; if fraEvntDelayList.MatchedCancel then Close end; procedure TfrmOrdersTS.UMStillDelay(var message: TMessage); begin inherited; if grpChoice.Tag = 0 then begin InfoBox('A release event has not been selected.', 'No Selection Made', MB_OK); Exit; end; if(not (fraEvntDelayList.mlstEvents.ItemIndex >= 0)) and (radDelayed.Checked) then begin InfoBox('A release event must be selected.', 'No Selection Made', MB_OK); Exit; end; OKPressed := True; FResult := True; Close; end; procedure TfrmOrdersTS.fraEvntDelayListmlstEventsDblClick(Sender: TObject); begin inherited; if fraEvntDelayList.mlstEvents.ItemID > 0 then cmdOKClick(Self); end; procedure TfrmOrdersTS.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; SaveUserBounds(Self); Action := caFree; end; procedure TfrmOrdersTS.fraEvntDelayListmlstEventsChange(Sender: TObject); begin inherited; fraEvntDelayList.mlstEventsChange(Sender); if fraEvntDelayList.MatchedCancel then begin OKPressed := False; Close; Exit; end; end; procedure TfrmOrdersTS.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_RETURN then cmdOKClick(Self); end; procedure TfrmOrdersTS.FormResize(Sender: TObject); begin // inherited; end; end.
{*************************************************************** * * Project : MailDemo * Unit Name: Main * Purpose : * Version : 1.0 * Date : Sat 21 Apr 2001 - 15:54:11 * Author : Hadi Hari <hadi@pbe.com> * History : * ****************************************************************} unit Main; interface uses Graphics, Controls, Forms, Dialogs, Grids, Menus, ComCtrls, StdCtrls, ExtCtrls, ActnList, ImgList, Buttons, Windows, Messages, SysUtils, Classes, FileCtrl, IdSMTP, IdComponent, IdTCPConnection, IdTCPClient, IdMessageClient, IdPOP3, IdBaseComponent, IdMessage, ToolWin, IdAntiFreezeBase, IdAntiFreeze; type TfrmMain = class(TForm) ActionList1: TActionList; Actions1: TMenuItem; Button1: TBitBtn; Cc: TLabel; CheckMail: TAction; Checkmail1: TMenuItem; Date: TLabel; Delete: TAction; Deletecurrentmessage1: TMenuItem; Disconnect: TAction; Disconnect1: TMenuItem; Exit1: TMenuItem; From: TLabel; IdAntiFreeze1: TIdAntiFreeze; ImageList1: TImageList; Label1: TLabel; Label10: TLabel; Label11: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; lvHeaders: TListView; lvMessageParts: TListView; MainMenu1: TMainMenu; Memo1: TMemo; Msg: TIdMessage; N2: TMenuItem; N3: TMenuItem; Organization: TLabel; Panel1: TPanel; pnlBottom: TPanel; pnlBottomBottom: TPanel; pnlMain: TPanel; pnlAttachments: TPanel; pnlServerName: TPanel; pnlTop: TPanel; POP: TIdPOP3; Priority: TLabel; Purge: TAction; Purgemarkedmessages1: TMenuItem; Receipt: TLabel; Recipients: TLabel; Retrieve: TAction; Retrievecurrentmessage1: TMenuItem; SaveDialog1: TSaveDialog; Send: TAction; Send1: TMenuItem; Setup: TAction; Setup1: TMenuItem; Splitter1: TSplitter; StatusBar1: TStatusBar; StatusBar2: TStatusBar; Subject: TLabel; ToolBar1: TToolBar; ToolButton1: TToolButton; ToolButton10: TToolButton; ToolButton11: TToolButton; ToolButton12: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; ToolButton5: TToolButton; ToolButton6: TToolButton; ToolButton7: TToolButton; ToolButton8: TToolButton; ToolButton9: TToolButton; Selectfromdeletion1: TMenuItem; function FindAttachment(stFilename: string): integer; procedure Button1Click(Sender: TObject); procedure CheckMailExecute(Sender: TObject); procedure DeleteExecute(Sender: TObject); procedure DisconnectExecute(Sender: TObject); procedure Exit1Click(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure lvMessagePartsClick(Sender: TObject); procedure pnlServerNameClick(Sender: TObject); procedure PurgeExecute(Sender: TObject); procedure RetrieveExecute(Sender: TObject); procedure SendExecute(Sender: TObject); procedure SetupExecute(Sender: TObject); procedure ShowBusy(blBusy: boolean); procedure ShowFileStatus; procedure ShowStatus(stStatus: string); procedure lvHeadersDblClick(Sender: TObject); procedure Selectfromdeletion1Click(Sender: TObject); private { Private declarations } procedure RetrievePOPHeaders(inMsgCount: Integer); procedure ResetHeadersGrid; procedure ToggleStatus(const Status: Boolean); procedure ReadConfiguration; public { Public declarations } FAttachPath: string; FMsgCount, FMailBoxSize: integer; end; var frmMain: TfrmMain; Pop3ServerName: string; Pop3ServerPort: Integer; Pop3ServerUser: string; Pop3ServerPassword: string; SmtpServerName: string; SmtpServerPort: Integer; SmtpServerUser: string; SmtpServerPassword: string; SmtpAuthType: Integer; UserEmail: string; implementation uses Setup, MsgEditor, IniFiles; //, smtpauth; {$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF} procedure TfrmMain.ShowBusy(blBusy: boolean); begin if blBusy then screen.cursor := crHourglass else screen.cursor := crDefault; end; (* *) procedure TfrmMain.ShowStatus(stStatus: string); begin Statusbar1.Panels[1].text := stStatus; StatusBar1.Refresh; end; (* *) procedure TfrmMain.ShowFileStatus; begin Statusbar2.Panels[0].text := IntToStr(FMsgCount); Statusbar2.Panels[1].text := format('Mail takes up %dK on the server', [FMailBoxSize]); StatusBar1.Refresh; end; (* *) function TfrmMain.FindAttachment(stFilename: string): integer; var intIndex: Integer; found: boolean; begin intIndex := -1; result := -1; if (Msg.MessageParts.Count < 1) then exit; //no attachments (or anything else) found := false; stFilename := uppercase(stFilename); repeat inc(intIndex); if (Msg.MessageParts.Items[intIndex] is TIdAttachment) then begin //general attachment if stFilename = uppercase(TIdAttachment(Msg.MessageParts.Items[intIndex]).Filename) then found := true; end; until found or (intIndex > Pred(Msg.MessageParts.Count)); if found then result := intIndex else result := -1; end; (* *) procedure TfrmMain.Button1Click(Sender: TObject); var intIndex: integer; fname: string; intMSGIndex: integer; begin // Find selected for intIndex := 0 to lvMessageParts.Items.Count - 1 do if lvMessageParts.Items[intIndex].Selected then begin //now find which TIdAttachment it is in MSG intMSGIndex := FindAttachment(lvMessageParts.Items[intIndex].caption); if intMSGIndex > 0 then begin fname := FAttachPath + TIdAttachment(Msg.MessageParts.Items[intMSGIndex]).filename; SaveDialog1.FileName := fname; if SaveDialog1.Execute then begin Showbusy(true); TIdAttachment(Msg.MessageParts.Items[intMSGIndex]).SaveToFile(SaveDialog1.FileName); Showbusy(false); end; end; end; end; procedure TfrmMain.RetrievePOPHeaders(inMsgCount: Integer); var stTemp: string; intIndex: integer; itm: TListItem; begin stTemp := Statusbar1.Panels[1].text; lvHeaders.Items.Clear; for intIndex := 1 to inMsgCount do begin // Clear the message properties ShowStatus(format('Messsage %d of %d', [intIndex, inMsgCount])); Application.ProcessMessages; Msg.Clear; POP.RetrieveHeader(intIndex, Msg); // Add info to ListView itm := lvHeaders.Items.Add; itm.ImageIndex := 5; itm.Caption := Msg.Subject; itm.SubItems.Add(Msg.From.Text); itm.SubItems.Add(DateToStr(Msg.Date)); itm.SubItems.Add(IntToStr(POP.RetrieveMsgSize(intIndex))); itm.SubItems.Add('n/a'); // itm.SubItems.Add(POP.RetrieveUIDL(intIndex)); end; ShowStatus(stTemp); end; procedure TfrmMain.ResetHeadersGrid; begin lvHeaders.Items.Clear; end; procedure TfrmMain.FormActivate(Sender: TObject); begin {Set up authentication dialog-box} // frmSMTPAuthentication.cboAuthType.ItemIndex := Ord( frmMessageEditor.SMTP.AuthenticationType ); // frmSMTPAuthentication.edtAccount.Text := fmSetup.Account.Text; // frmSMTPAuthentication.edtPassword.Text := fmSetup.Password.Text; // frmSMTPAuthentication.EnableControls; ResetHeadersGrid; ToggleStatus(False); end; procedure TfrmMain.ToggleStatus(const Status: Boolean); begin CheckMail.Enabled := not Status; Retrieve.Enabled := Status; Delete.Enabled := Status; Purge.Enabled := Status; Disconnect.Enabled := Status; if Status then ShowStatus('Connected') else ShowStatus('Not connected'); end; procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction); begin Disconnect.Execute; end; procedure TfrmMain.CheckMailExecute(Sender: TObject); begin Showbusy(true); ShowStatus('Connecting....'); if POP.Connected then begin POP.Disconnect; end; POP.Host := Pop3ServerName; POP.Port := Pop3ServerPort; POP.UserID := Pop3ServerUser; POP.Password := Pop3ServerPassword; POP.Connect; ToggleStatus(True); FMsgCount := POP.CheckMessages; FMailBoxSize := POP.RetrieveMailBoxSize div 1024; ShowFileStatus; if FMsgCount > 0 then begin ShowFileStatus; RetrievePOPHeaders(FMsgCount); end else begin ShowStatus('No messages on server'); end; Showbusy(false); end; procedure TfrmMain.RetrieveExecute(Sender: TObject); var stTemp: string; intIndex: Integer; li: TListItem; begin stTemp := Statusbar1.Panels[1].text; if lvHeaders.Selected = nil then begin Exit; end; //initialise Showbusy(true); Msg.Clear; Memo1.Clear; lvMessageParts.Items.Clear; From.Caption := ''; Cc.Caption := ''; Subject.Caption := ''; Date.Caption := ''; Receipt.Caption := ''; Organization.Caption := ''; Priority.Caption := ''; pnlAttachments.visible := false; //get message and put into MSG ShowStatus('Retrieving message "' + lvHeaders.Selected.SubItems.Strings[3] + '"'); POP.Retrieve(lvHeaders.Selected.Index + 1, Msg); statusbar1.Panels[0].text := lvHeaders.Selected.SubItems.Strings[3]; //Setup fields on screen from MSG From.Caption := Msg.From.Text; Recipients.Caption := Msg.Recipients.EmailAddresses; Cc.Caption := Msg.CCList.EMailAddresses; Subject.Caption := Msg.Subject; Date.Caption := FormatDateTime('dd mmm yyyy hh:mm:ss', Msg.Date); Receipt.Caption := Msg.ReceiptRecipient.Text; Organization.Caption := Msg.Organization; Priority.Caption := IntToStr(Ord(Msg.Priority) + 1); //Setup attachments list ShowStatus('Decoding attachments (' + IntToStr(Msg.MessageParts.Count) + ')'); for intIndex := 0 to Pred(Msg.MessageParts.Count) do begin if (Msg.MessageParts.Items[intIndex] is TIdAttachment) then begin //general attachment pnlAttachments.visible := true; li := lvMessageParts.Items.Add; li.ImageIndex := 8; li.Caption := TIdAttachment(Msg.MessageParts.Items[intIndex]).Filename; // li.SubItems.Add(TIdAttachment(Msg.MessageParts.Items[intIndex]).ContentType); end else begin //body text if Msg.MessageParts.Items[intIndex] is TIdText then begin Memo1.Lines.Clear; Memo1.Lines.AddStrings(TIdText(Msg.MessageParts.Items[intIndex]).Body); end end; end; ShowStatus(stTemp); Showbusy(false); end; procedure TfrmMain.DeleteExecute(Sender: TObject); begin if lvHeaders.Selected <> nil then begin Showbusy(true); POP.Delete(lvHeaders.Selected.Index + 1); lvHeaders.Selected.ImageIndex := 3; Showbusy(false); end; end; procedure TfrmMain.PurgeExecute(Sender: TObject); begin POP.Disconnect; ToggleStatus(False); CheckMailExecute(Sender); end; procedure TfrmMain.DisconnectExecute(Sender: TObject); begin if POP.Connected then begin try POP.Reset; except ShowStatus('Your POP server doesn''t have Reset feature'); end; POP.Disconnect; ToggleStatus(False); end; end; procedure TfrmMain.SetupExecute(Sender: TObject); begin Application.CreateForm(TfmSetup, fmSetup); fmSetup.ShowModal; end; procedure TfrmMain.SendExecute(Sender: TObject); begin frmMessageEditor.ShowModal; end; procedure TfrmMain.lvMessagePartsClick(Sender: TObject); var i: Integer; begin {display message parts we selected} if lvMessageParts.Selected <> nil then begin if lvMessageParts.Selected.Index > Msg.MessageParts.Count then begin MessageDlg('Unknown index', mtInformation, [mbOK], 0); end else begin for i := 0 to Msg.MessageParts.Count - 1 do begin if Msg.MessageParts.Items[i] is TIdAttachment then begin if SaveDialog1.Execute then TIdAttachment(Msg.MessageParts.Items[i]).SaveToFile( SaveDialog1.FileName); break; end; end; end; end; end; procedure TfrmMain.Exit1Click(Sender: TObject); begin close; end; procedure TfrmMain.FormCreate(Sender: TObject); begin // read the configuration from ini file ReadConfiguration; name := 'frmMain'; //setup path to put attachments into FAttachPath := IncludeTrailingBackSlash(ExtractFileDir(Application.exename)); //starting directory FAttachPath := FAttachPath + 'Attach\'; if not DirectoryExists(FAttachPath) then ForceDirectories(FAttachPath); FMsgCount := 0; FMailBoxSize := 0; Showbusy(false); end; procedure TfrmMain.pnlServerNameClick(Sender: TObject); begin SetupExecute(Sender); //show setup screen end; procedure TfrmMain.ReadConfiguration; var MailIni: TIniFile; begin MailIni := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Mail.ini'); with MailIni do begin Pop3ServerName := ReadString('Pop3', 'ServerName', 'pop3.server.com'); Pop3ServerPort := StrToInt(ReadString('Pop3', 'ServerPort', '110')); Pop3ServerUser := ReadString('Pop3', 'ServerUser', 'your_login'); Pop3ServerPassword := ReadString('Pop3', 'ServerPassword', 'your_password'); SmtpServerName := ReadString('Smtp', 'ServerName', 'smtp.server.com'); SmtpServerPort := StrToInt(ReadString('Smtp', 'ServerPort', '25')); SmtpServerUser := ReadString('Smtp', 'ServerUser', 'your_login'); SmtpServerPassword := ReadString('Smtp', 'ServerPassword', 'your_password'); SmtpAuthType := ReadInteger('Smtp', 'SMTPAuthenticationType', 0); UserEmail := ReadString('Email', 'PersonalEmail', 'your@email.com'); end; MailIni.Free; end; procedure TfrmMain.lvHeadersDblClick(Sender: TObject); begin RetrieveExecute(Sender); end; procedure TfrmMain.Selectfromdeletion1Click(Sender: TObject); var i: integer; begin for i := 0 to lvHeaders.Items.Count - 1 do begin Showbusy(true); POP.Delete(i + 1); lvHeaders.Items[i].ImageIndex := 3; Showbusy(false); end; end; end.
unit uSatellite; ////////////////////////////////////////////////////////////////////////// // // 参考資料 // 1.天体の位置計算 増補版 著者:長沢工氏  発行:地人書館 // 2. Calsat32のホームぺージ 作者:相田政則氏(JR1HUO) // http://homepage1.nifty.com/aida/jr1huo_calsat32/index.html // ////////////////////////////////////////////////////////////////////////// { 用語 Orbital Elments: 軌道要素 Right Aceention of Ascending NODE(RAAN); 昇交点赤経(度)  Inclination: 軌道傾斜角(Rad) Argument of Perigee(ARGP): 近地点引数 Epoch: 元期 Eccentricity: 離心率 Mean Anomaly: 平均近点角(Rad) Mean Motion: 平均運動(rad/日) Decay Rate: 衰弱率 平均運動の変化 摂動1 Semi Major Axis: 長半径 EpochRev: 周回番号 } interface uses Classes, SysUtils, Dialogs, Math, DateUtils, System.UITypes; type //**********************************************************************// // // // 観測地点(運用地点)クラス // // // //**********************************************************************// TObservationPoint = record Longitude: double; // 経度 Latitude: double; // 緯度 Altitude: double; // 標高 TimeOffset: double; // 時差 LocalTimeStr: string; // JST等の文字列 end; //**********************************************************************// // // // 球面座標クラス    // // // //**********************************************************************// TSphericalCoord = record Azimuth: double; // 方位角 Elevation: double; // 仰角 Range: double; // 距離 end; //**********************************************************************// // // // 直交座標クラス    // // // //**********************************************************************// T2DCoordinates = record X: double; Y: double; end; T3DCoordinates = record X: double; Y: double; Z: double; end; //**********************************************************************// // // // 衛星の軌道要素クラス // // // //**********************************************************************// TOrbitalElments = record Satellite: String; // 衛星名 Epoch_Y: Integer; // 元期(年) Epoch_D: double; // 元期(連続日、時間) DecayRate: double; // n1: 衰弱率 Decay Rate, Drug 平均運動の変化 摂動1 Inclination: double; // i: 軌道傾斜角(Rad) Inclination RAAN: double; // Ω: 昇交点赤経(度)  Right Aceention of Ascending NODE Eccentricity: double; // e: 離心率 Eccentricity ARGP: double; // ω: 近地点引数 Argument of Perigee MeanAnomaly: double; // M or l: 平均近点角(Rad) Mean Anomaly MeanMotion: double; // n: 平均運動(rad/日) Mean Motion EpochRev:Integer; // 周回番号 Epoch: TDateTime; // 元期(年月日時分・・・) end; //**********************************************************************// // // // 衛星の軌道クラス   // // // //**********************************************************************// TOrbit = record Satellite: String; // 衛星名 Epoch_Y: Integer; // 元期(年) Epoch_D: double; // 元期(連続日、時間) DecayRate: double; // n1: 衰弱率 Decay Rate, Drug 平均運動の変化 摂動1 Inclination: double; // i: 軌道傾斜角(Rad) Inclination RAAN: double; // Ω: 昇交点赤経(度)  Right Aceention of Ascending NODE Eccentricity: double; // e: 離心率 Eccentricity ARGP: double; // ω: 近地点引数 Argument of Perigee MeanAnomaly: double; // M or l: 平均近点角(Rad) Mean Anomaly MeanMotion: double; // n: 平均運動(rad/日) Mean Motion EpochRev:Integer; // 周回番号 Epoch: TDateTime; // 元期 // ここまでは、 TOrbitalElmentsto同じ項目順 EpochMJD: Double; MeanMotionS: double; // n: 平均運動(rad/Sec) Mean Motion ElapsedTime: TDateTime; // 経過時間 EccentricAanomaly: double; // 離心近点角 MajorAxis: double; // 軌道長半径 MinorAxis: double; // 軌道短半径 PrecessionConst: double; // 歳差定数 OrbitalSurface: T2DCoordinates; // 軌道面内のx,y座標 EquatorialCoord: T3DCoordinates; // 地心赤道直交座標 GGeocentricCoord: T3DCoordinates; // G径地心直交座標 SatCoord: TSphericalCoord; // 衛星の方位角,仰角、距離 AngleMomentumRate: Double; NodePrecessionRate: double; PerigeePrecessionRate: double; end; //**********************************************************************// // // // 衛星の可視時間帯クラス // // // //**********************************************************************// TVisibleTimeSlot = record AosAz: double; MaxAz: double; MaxEl: double; LosAz: double; AosDateTime: TDateTime; MaxDateTime: TDateTime; LosDateTime: TDateTime; end; //**********************************************************************// // // // 軌道計算のクラス // // // //**********************************************************************// type TSatellite = class(TComponent) private { Private 宣言 } // 定数式で表せない定数。constructorで設定する GravityConst23: double; // 地心重力定数 の 2/3乗 EquatorRadius2: double; EarthEccentricty2: double; // 地球の離心率の2乗 PolarRadius: double; PolarRadius2: double; EarthLotation: double; // 地球の回転数(Rad/Day) EarthLotationD: double; // 回転数(Rad/Day) EarthLotationS: double; // 回転数(Rad/Sec) ALON, ALAT: double; // Spin Axis Attitude // Ax, Ay, Az: double; // Ox,Oy,Oz: double; // Ux,Uy,Uz: double; // Ex,Nx,Ey,Ny,Ez,Nz: double; // // 軌道計算(AOS,Los,Max)計算の為 // OrbitEle_N: TOrbitalElments; // 衛星の現在位置 Az_d, El_d: double; // 観測地点の中間計算値 // SinISinK, SinICosK, CosISinK, CosICosK: double; // 衛星の中間計算値 SinRAAN, CosRAAN, SinARGP, cosARGP: double; FObsPoint: TObservationPoint; FOrbitalElments: TOrbitalElments; FOrbit: TOrbit; FElementFile: string; FGreenwichSiderealTime: TDateTime; FEccentricAnomaly: double; FRadiusVector: double; FTrueAnormaly: double; FCartesianCoordinatesX: Double; FCartesianCoordinatesY: Double; FTVisibleTimeSlot: TVisibleTimeSlot; FVisibleTimeSlot: TVisibleTimeSlot; // FJCartesianCoord: TCartesianCoord; FGCartesianCoord: T3DCoordinates; FCenteredCartesianCoord: T3DCoordinates; procedure SetElementFile(const Value: string); procedure InitOrbitPlane; // procedure setGreenwichSiderealTime(const Value: read); // function SetOrbitaEle(FileName, Sat: string): boolean; procedure SetOrbitalElments(const Value: TOrbitalElments); public { Public 宣言 } property ElementFile: string read FElementFile write SetElementFile; property ObsPoint: TObservationPoint read FObsPoint; property OrbitalElments: TOrbitalElments read FOrbitalElments write SetOrbitalElments; property Orbit: TOrbit read FOrbit; property GCartesianCoord: T3DCoordinates read FGCartesianCoord; // 観測点G系地心直交座標 // property DebugKeplerEle: TOrbitalElments read FDebugKeplerEle write SetDebugKeplerEle; property VisibleTimeSlot: TVisibleTimeSlot read FVisibleTimeSlot; property GCenteredCartesianCoord: T3DCoordinates read FCenteredCartesianCoord; // G系測心直交座標系 property GreenwichSiderealTime: TDateTime read FGreenwichSiderealTime; // グリニッチ平均恒星時 property EccentricAnomaly: double read FEccentricAnomaly; //離心近点角 property TrueAnormaly: double read FTrueAnormaly; // 真近点角 property RadiusVector: double read FRadiusVector; // 動径 property CartesianCoordinatesX: Double read FCartesianCoordinatesX; // 衛星軌道面の位置直交座標 (近地点方向) property CartesianCoordinatesY: Double read FCartesianCoordinatesY; // 衛星軌道面の位置直交座標 (Xの反時計回り90度方向) constructor Create(AOwner: TComponent); override; function SetOrbitaEle(Sat: string): boolean; // function CalcGreenwichSiderealTime(const Value: TDateTime): TDateTime; // procedure CalcOrbitPlane(MajorAxis, Eccentricity, MeanAnomaly: double); procedure CalcAosLos(DT: TDateTime); procedure CalcOrbit(Ut: TDateTime); procedure SetObsPoint(Longitude, Latitude, Altitude, TimeOffset: Double; LocalTimeStr: string); procedure SetObsPoint1(ObsPoint: TObservationPoint); procedure CalcObsPoint(); end; function DateTimeToMJD(DT: TDateTime): double; function MJDToDateTime(MJD: Double): TDateTime; function Kepler(U0, E: double): Double; function UtcToGMeanSiderealTime(Ut: TDateTime): TDateTime; function GLToDeg(GL: String; var Lon,Lat: Double): boolean; const Pi2: double = 2 * pi; // 2 × PI RadDivDeg: double = 2 * pi / 360; // 1度あたりのラジアン値 UniversalGravityConst: Double = 6.67428E-11; // 万有引力の定数  m3/s2/kg GravityConst: Double = 3.986005E5; // 地心重力定数 or 地心引力定数 m3/s2 ZoneCoeff: double = 1.08263E-3; // ゾーン係数 InverseFlattering: double = 1 / 298.257224; // 地球逆扁平率 EquatorRadius: double = 6377.397155; // 地球(赤道)の半径 単位:km(WGS-84) EarthEccentricty: double = 0.081819191042; // 地球の離心率 MeanYear: double = 365.25; // (Days) TropicalYear: double = 365.2421874; // 回帰年、太陽年(Days) implementation constructor TSatellite.Create(AOwner: TComponent); begin inherited; // 定数の計算 GravityConst23 := Power(GravityConst, 2/3); // 地心重力定数 の 2/3乗 EquatorRadius2 := Sqr(EquatorRadius); PolarRadius := EquatorRadius * (1 - InverseFlattering); // 地球の極半径 PolarRadius2 := Sqr(PolarRadius); EarthEccentricty2 := Sqr(EarthEccentricty); // 地球の離心率の2乗 EarthLotation := Pi2 / TropicalYear; // 地球の回転数(Rad/Day) EarthLotationD := Pi2 + TropicalYear; // 回転数(Rad/Day) EarthLotationS := EarthLotationD / 24 / 60 /60; // 回転数(Rad/Sec) ALON := DegToRad(180); ALAT := DegToRad(0); // SAT Attitude // レコードの初期化 with FObsPoint do begin TimeOffset := 9; LocalTimeStr := 'JST'; end; with FOrbit do begin Satellite := ''; Epoch := StrToDatetime('2000/1/1'); EpochMJD := DateTimeToMJD(Epoch); end; end; ////////////////////////////////////////////////////////////////////////// // // NASA2Lineファイル名を設定する // ////////////////////////////////////////////////////////////////////////// procedure TSatellite.SetElementFile(const Value: string); begin FElementFile := Value; if not FileExists(FElementFile) then begin MessageDlg(FElementFile + ' Not found', mtError, [mbOk], 0); Exit; end; end; ////////////////////////////////////////////////////////////////////////// // // 観測地点のデータを設定・計算する // ////////////////////////////////////////////////////////////////////////// procedure TSatellite.SetObsPoint(Longitude, Latitude, Altitude, TimeOffset: Double; LocalTimeStr: string); begin FObsPoint.Longitude := Longitude; // 単位 : Rad FObsPoint.Latitude := Latitude; // 単位 : Rad FObsPoint.Altitude := Altitude; // 単位:km FObsPoint.TimeOffset := TimeOffset; // 日単位の時差 FObsPoint.LocalTimeStr := LocalTimeStr; // ローカルタイムの文字 CalcObsPoint end; procedure TSatellite.SetObsPoint1(ObsPoint: TObservationPoint); begin FObsPoint := ObsPoint; CalcObsPoint; end; procedure TSatellite.CalcObsPoint(); var N: double; SinLat, CosLat, SinLon, CosLon: double; begin; with FObsPoint do begin // 観測点をG系直交座標系へ変換 (P185) N := EquatorRadius / Sqrt(1 - EarthEccentricty2 * Sqr(sin(Latitude))); // 東西線曲率半径 SinLat := sin(Latitude); CosLat := cos(Latitude); SinLon := sin(Longitude); CosLon := cos(Longitude); end; // Property GCartesianCoordに結果を設定する with FGCartesianCoord do begin X := (N + FObsPoint.Altitude) * CosLat * CosLon;; Y := (N + FObsPoint.Altitude) * CosLat * SinLon; Z := (N * (1 - EarthEccentricty2) + FObsPoint.Altitude) * SinLat; end; end; /////////////////////////////////////////////////////////////////////////// // // サテライト名からNASA 2ラインを読み込み // 軌道要素データを設定する。 // /////////////////////////////////////////////////////////////////////////// function TSatellite.SetOrbitaEle(Sat: string): boolean; var F: TextFile; Line0: string; Line1: string; Line2: string; s: string; i: integer; begin result := true; // ファイルの存在を確認 if not FileExists(FElementFile) then begin result := false; MessageDlg('"' + FElementFile + '" not found', mtError, [mbOk], 0); Exit; end; // 軌道要素の読み込み Line1 := ''; Line2 := ''; AssignFile(F, FElementFile); { File selected in dialog } Reset(F); while not Eof(F) do begin Readln(F, s); { Read first line of file } s := Trim(s); if s = Sat then begin Line0 := s; Readln(F, Line1); { Read first line of file } Readln(F, Line2); { Read first line of file } break; end; end; CloseFile(F); if (Line1 = '') or (line2 = '') then begin MessageDlg('"' + Sat + '" not found in ' + FElementFile, mtError, [mbOk], 0); result := false; Exit; end; try // データは弧度値(Radian)に変換 with FOrbitalElments do begin Satellite := trim(Copy(Line0, 1, 24)); i := StrToInt(Copy(Line1, 19, 02)); // 元期 年 if i > 70 then Epoch_Y := i + 1900 else Epoch_Y := i + 2000; Epoch_D := StrToFloat(Copy(Line1, 21, 12)); // 元期 通算日 Epoch := StrToDateTime(IntToStr(Epoch_Y) + '/1/1') + Epoch_D; DecayRate := StrToFloat(Copy(Line1, 34, 10)) * Pi2; // Rad/Day MeanMotion := StrToFloat(Copy(Line2, 53, 11)) * Pi2; // 平均運動回転 Rad/Day DecayRate := StrToFloat(Copy(Line1, 34, 10)) * Pi2; // 平均運動の変化 Inclination := DegToRad(StrToFloat(Copy(Line2, 09, 08))); // 軌道傾斜角(Rad) RAAN := DegToRad(StrToFloat(Copy(Line2, 18, 08))); // 昇交点赤経(Rad) Eccentricity := StrToFloat('0.' + Copy(Line2, 27, 07)); // 離心率  Argp := DegToRad(StrToFloat(Copy(Line2, 35, 08))); // 近地点引数(Rad) MeanAnomaly := DegToRad(StrToFloat(Copy(Line2, 44, 08))); // 平均近点離角(Rad) EpochRev := StrToInt(Copy(Line2, 64, 05)); // 周回番号 // InitOrbitPlane; end; except result := false; exit; end; end; procedure TSatellite.SetOrbitalElments(const Value: TOrbitalElments); begin FOrbitalElments := Value; // InitOrbitPlane; end; procedure TSatellite.InitOrbitPlane(); var SinInc, CosInc: double; PC: double; begin with FOrbit do begin Satellite := FOrbitalElments.Satellite; Epoch_Y := FOrbitalElments.Epoch_Y; Epoch_D := FOrbitalElments.Epoch_D; Epoch := FOrbitalElments.Epoch; DecayRate := FOrbitalElments.DecayRate; MeanMotion := FOrbitalElments.MeanMotion; // 平均移動 Inclination := FOrbitalElments.Inclination; // 軌道傾斜角 RAAN := FOrbitalElments.RAAN; // 昇交点赤経 Eccentricity := FOrbitalElments.Eccentricity; // 離心率  Argp := FOrbitalElments.ARGP; // 近地点引数 MeanAnomaly := FOrbitalElments.MeanAnomaly; // 平均近点離角 EpochRev := FOrbitalElments.EpochRev; // 周回番号 MeanMotionS := MeanMotion / 86400; // 秒あたり平均運動 MajorAxis := Power(GravityConst / Sqr(MeanMotionS), 1/3); // 衛星の長半径 MinorAxis := MajorAxis * Sqrt(1 - Sqr(Eccentricity)); // 衛星の短半径 SinInc := Sin(Inclination); CosInc := Cos(Inclination); PC := EquatorRadius * MajorAxis/Sqr(MinorAxis); // Precession constant(歳差定数) rad/day PrecessionConst := 1.5 * ZoneCoeff * Sqr(PC) * MeanMotion; NodePrecessionRate := -PrecessionConst * CosInc; // Node precession rate, rad/day PerigeePrecessionRate := PrecessionConst * (5 * Sqr(CosInc) - 1) / 2; // Perigee precession rate, rad/day AngleMomentumRate := -2 * DecayRate / MeanMotion / 3; // Drag coeff. (Angular momentum rate)/(Ang mom) s^-1 end; //// 以下、太陽に関する処理だろう! 必要性? //// Sidereal and Solar data. Rarely needs changing. Valid to year ~2015 // YG := 2000; G0 := 98.9821; // GHAA, Year YG, Jan 0.0 // MAS0 := 356.0507; MASD := 0.98560028; // MA Sun and rate, deg, deg/day // INS := DegToRAD(23.4393); CNS := COS(INS); SNS := SIN(INS); // Sun's inclination // EQC1 :=0.03342; EQC2 := 0.00035; // Sun's Equation of centre terms // //// Bring Sun data to Satellite Epoch // TEG := FOrbit.Epoch - EncodeDate(YG, 1, 1) - 1; // Elapsed Time: Epoch - YG // GHAE := DegToRAD(G0) + TEG * EarthLotationS; // GHA Aries, epoch // MRSE := DegToRAD(G0) + TEG * EarthLotationS + PI; // Mean RA Sun at Sat epoch // MASE := DEgToRAD(MAS0 + MASD * TEG); // Mean MA Sun .. // Antenna unit vector in orbit plane coordinates. // CosALON := COS(ALON); SinALON := SIN(ALON); // CosALAT := COS(ALAT); SinALAT := SIN(ALAT); // Ax := -CosALAT * CosALON; Ay := -CosALAT * SinALON; Az := -SinALAT; end; procedure TSatellite.CalcOrbit(Ut: TDateTime); var Sx,Sy: double; Gs: double; CosGs, SinGs: double; Xs, Ys, Zs: double; Xg, Yg, Zg: double; CosIncl, SinIncl: double; CosLon, SinLon: double; CosLat, SinLat: double; W: double; // DC,DT,KD,KDP,MA: double; // DR: integer; begin InitOrbitPlane; with FOrbit do begin ElapsedTime := (Ut - Epoch); // エポックからの経過時間を計算 MeanMotion := MeanMotion + DecayRate * ElapsedTime / 2; EpochRev := EpochRev + Trunc(MeanMotion * (ElapsedTime + 1) / Pi2); // なぜ1日を加えないといけないか? W := 0.174 / Power((MajorAxis / EquatorRadius), 3.5 ) * ElapsedTime; ARGP := ARGP + W * (2 - 2.5 * Sqr(Sin(Inclination))); RAAN := RAAN - W * Cos(Inclination); MeanAnomaly := MeanAnomaly + MeanMotion * ElapsedTime; MeanAnomaly := Frac(MeanAnomaly / Pi2) * Pi2; // 0から2πに丸める // // DC := -2 * DecayRate / MeanMotion / 3; // DT := DC * ElapsedTime / 2; // Linear drag terms // KD := 1 + 4 * DT; // KDP := 1 - 7 * DT; // MA := FOrbitalElments.MeanAnomaly // + FOrbitalElments.MeanMotion * (1 - 3 * DT); // 平均近点角(Rad) // DR := Trunc(MA / Pi2); // 0から2πに丸める // EpochRev := EpochRev + DR; // なぜ1日を加えないといけないか? // Eccentricity := FOrbitalElments.Eccentricity; // MeanAnomaly := Frac(FOrbitalElments.MeanAnomaly / Pi2) * Pi2; // 0から2πに丸める // 平均近点角、離心率から離心近点角を求める EccentricAanomaly := Kepler(MeanAnomaly, Eccentricity); // ケプラーの方程式 // 軌道面内のx,y座標 Sx := MajorAxis * (cos(EccentricAanomaly) - Eccentricity); Sy := MajorAxis * SQRT(1 - Sqr(Eccentricity))* sin(EccentricAanomaly); OrbitalSurface.x := Sx; OrbitalSurface.y := Sy; // 地心赤道直交座標 CosRAAN := COS(RAAN); SinRAAN := SIN(RAAN); CosARGP := COS(ARGP); SinARGP := SIN(ARGP); CosIncl := COS(Inclination); SinIncl := SIN(Inclination); Xs := Sx * (CosRAAN * CosARGP - SinRAAN * CosIncl * SinARGP) - Sy * (CosRAAN * SinARGP + SinRAAN * CosIncl * CosARGP); Ys := Sx * (SinRAAN * CosArgp + CosRAAN * CosIncl * SinARGP) - Sy * (SinRAAN * SinARGP - CosRAAN * CosIncl * CosARGP); Zs := Sx * SinIncl * SinARGP + Sy * SinIncl * CosARGP; EquatorialCoord.X := Xs; EquatorialCoord.Y := Ys; EquatorialCoord.Z := Zs; Gs := Frac(UtcToGMeanSiderealTime(UT) / 12 * pi); // グリニッジ平均恒星時 時分秒をRadに変換 CosGs := COS(Gs); SinGs := SIN(Gs); Xg := Xs * CosGs + Ys * SinGs; // G系地心直交座標系を求める Yg := - Xs * SinGs + Ys * CosGs; Zg := Zs; GGeocentricCoord.X := Xg; GGeocentricCoord.Y := Yg; GGeocentricCoord.Z := Zg; // 地心赤道直交座標系にする // // Ud := Us - GCartesianCoord.X; // 地平直交座標系に変換する // Vd := Vs - GCartesianCoord.Y; // Wd := Ws - GCartesianCoord.Z; // CosLon := Cos(ObsPoint.Longitude); // SinLon := Sin(ObsPoint.Longitude); // CosLat := Cos(obsPoint.Latitude); // SinLat := Sin(ObsPoint.Latitude); // Xd := SinLat * CosLon * Ud + SinLat * SinLon * Vd - CosLat * Wd; // Yd := - SinLon * Ud + CosLon * Vd; // Zd := CosLat * CosLon * Ud + CosLat * SinLon * Vd + SinLat * Wd; // Rd := Sqrt(sqr(Xd) + sqr(Yd)); // // Az := ArcTan2(Yd, Xd); // Azimuth // if Xd < 0 then // AZ := AZ + pi; // EL := ArcSin(Zd / Rd); // Elevation // // FOrbit.Cordinate.X := Xd; // FOrbit.Cordinate.Y := Yd; // FOrbit.Cordinate.Z := Zd; // // SatCoord.Azimuth := Az; // SatCoord.Elevation := El; // SatCoord.Range := Rd; // // ////// Solve M = EA - EC*SIN(EA) for EA given M, by Newton's Method ////// EA := MeanAnomaly; ////// repeat ////// begin ////// CosEA := Cos(EA); SinEA := Sin(EA); ////// DNOM := 1 - Eccentricity * CosEA; ////// D := (EA - Eccentricity * SinEA - MeanAnomaly) / DNOM; ////// EA := EA - D; ////// end; ////// until (Abs(D) < 1E-5); //// //// A := MajorAxis * KD; //// B := MinorAxis * KD; //// RS := A * DNOM; // ? //// ////// Calc satellite position & velocity in plane of ellipse //// Sx := A * (CosEA - Eccentricity); Vx := -A * SinEA / DNOM * MeanMotionS; //// Sy := B * SinEA; Vy := B * CosEA / DNOM * MeanMotionS; //// //// ARGP := FOrbitalElments.ARGP + PerigeePrecessionRate * ElapsedTime * KDP; //// RAAN := FOrbitalElments.RAAN + NodePrecessionRate * ElapsedTime * KDP; //// //// CosRAAN := COS(RAAN); SinRAAN := SIN(RAAN); //// CosARGP := COS(ARGP); SinARGP := SIN(ARGP); ////// CosInc := COS(InClination); SinInc := SIN(InClination); // Initで処理している //// ////// 2260 REM Plane -> celestial coordinate transformation, [C] = [RAAN]*[IN]*[AP] ////// 天球座標変換 //// CXx := CosARGP * CosRAAN - SinARGP * CosInc * SinRAAN; //// CXy := -CosARGP * CosRAAN - CosARGP * CosInc * SinRAAN; //// CXz := SinInc * SinRAAN; //// CYx := CosARGP * SinRAAN + SinARGP * CosInc * CosRAAN; //// CYy := -SinARGP * SinRAAN + CosARGP * CosInc * CosRAAN; //// CYz := -SinInc * CosRAAN; //// CZx := SinARGP * SinInc; //// CZy := CosARGP * SinInc; //// CZz := CosInc; //// ////// Compute SATellite's position vector, ANTenna axis unit vector ////// and VELocity in CELESTIAL coordinates. (Note: Sz=0, Vz=0) ////// SATelliteの位置ベクトル、ANTenna軸の単位ベクトルを計算します //// SATx := Sx * CXx + Sy * CXy; ANTx := ax * CXx + ay * CXy + az * CXz; VELx := Vx * CXx + Vy * CXy; //// SATy := Sx * CYx + Sy * CYy; ANTy := ax * CYx + ay * CYy + az * CYz; VELy := Vx*CYx+Vy*CYy; //// SATz := Sx * CZx + Sy * CZy; ANTz := ax * CZx + ay * CZy + az * CZz; VELz := Vx*CZx+Vy*CZy; //// ////// Also express SAT,ANT and VEL in GEOCENTRIC coordinates: ////// SAT、ANT、VELを天動説座標で表現します //// GHAA := GHAE + WE * T; // GHA Aries at elapsed time T //// CosGHAA := COS(-GHAA); SinGHAA := SIN(-GHAA); //// Sx := SATx * CosGHAA - SATy * SinGHAA; Ax := ANTx * CosGHAA - ANTy * SinGHAA; Vx := VELx * CosGHAA - VELy * SinGHAA; //// Sy := SATx * SinGHAA + SATy * CosGHAA; Ay := ANTx * SinGHAA + ANTy * CosGHAA; Vy := VELx * SinGHAA + VELy * CosGHAA; //// Sz := SATz; Az := ANTz; Vz := VELz; //// ////// Compute and manipulate range/velocity/antenna vectors //// Rx := Sx - Ox; Ry := Sy - Oy; Rz := Sz - Oz; // Rangevec = Satvec - Obsvec //// R := SQRT(Sqr(Rx) + Sqr(Ry) + Sqr(Rz)); // Range magnitude //// Rx := Rx / R; Ry := Ry / R; Rz := Rz/R; // Normalise Range vector 正規化 //// U := Rx * Ux + Ry * Uy + Rz * Uz; // UP Component of unit range //// E := Rx * Ex + Ry * Ey; // EAST do (Ez=0) //// N := Rx * Nx + Ry * Ny + Rz * Nz; // NORTH do //// Az := ArcTan2(E, N); // Azimuth //// if AZ < 0 then //// AZ := AZ + pi; //// EL := ArcSin(U); // Elevation end; end; procedure TSatellite.CalcAosLos(DT: TDateTime); var UT: Tdatetime; i: integer; isAOS: boolean; Az, El: double; const Sec: double = 1 / 24 / 60 /60; // 秒/日 Minute: double = 1 / 24 / 60; // 分/日 begin with FVisibleTimeSlot do begin AosAz := 0; MaxAz := 0; LosAz := 0; MaxEl := 0; AosDateTime := 0; MaxDateTime := 0; LosDateTime := 0; isAOS := false; Ut := RecodeSecond(DT, 0); // 秒以下を切り捨て 2020-01-05 追加 for i := 0 to 3000 do // 300分(5時間)後までで最初のAOS等を計算する begin CalcOrbit(Ut); Az := Trunc(Az_d); El := Trunc(EL_d); if not isAOS then begin if (AosAz = 0) and (El >= 0) then // AOSの判断 begin AosAz := Az; AosDateTime := UT; // FEpochRev := OrbitEle_N.EpochRev; // atodeshusei; isAOS := true; end end else // AOSに達した後 begin if El > MaxEl then // Max Elの判断 begin MaxEl := El; MaxAz := Az; MaxDateTime := UT; end; if (LosAz = 0) and (El < 0) then // LOSの判断 begin LosAz := Az; LosDateTime := UT; Exit; end; end; Ut := Ut + Minute; end; end; end; //////////////////////////////////////////////////////////////////////////////// // // Utcからグリニッジ平均恒星時に変換する。 (P27,115) // //////////////////////////////////////////////////////////////////////////////// function UtcToGMeanSiderealTime(Ut: TDateTime): TDateTime; var Days, TU, Tg0: Double; begin // 1899/12/31 12:00 殻の経過日数(K)を求める // この式を適用できるのは、1900/3/1〜2100/2/28の期間のみ days := Ut - StrToDateTime('1899/12/31 12:00:00'); Tu := Days / 36525; // 平均太陽 mean sunを求める // w1 := StrToTime('06:38:45.836'); // w2 := 8640184.542/ 3600 / 24; // w3 := 0.0929 / 3600 / 24; // Tg0 := w1 + w2 + w3; // 平均太陽 mean sun // Tg0 := StrToTime('06:38:45.836') + 8640184.542/ 3600 / 24 * TU + 0.0929 / 3600 / 24 * TU * TU; // 上4行を1行にまとめる Tg0 := 0.276919398 + 100.002135902 * TU + 1.075E-6 * TU * TU; // 上行の置き換え result := Frac(Tg0); // resultは、時分秒単位 end; //////////////////////////////////////////////////////////////////////////////// // ユリウス恒星日を求めるには、DateUtilsのDateTimeToJulianDate関数で求める。 // 逆方向変換は、JulianDateToDateTime関数で求める。 //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // Delphi の TDateTime値を修正ユリウス日(Modeified Julian Day;MJD))に変換する。 // // Delphi の TDateTime 値の整数部は西暦 1899 年 12 月 30 日からの経過日数を示します。 // 小数部はその日の経過時間(24 時間制)です。 // // 修正ユリアス日は、1858年11月17日0時を起算開始日とした通算日 // 修正ユリアス日 = ユリアス日 − 2400000.5 の関係がある // // 通常 1899年12月30日 以前を計算対象としなければ、特にMJDに変換する必要ない // 1899年12月30日以前は、TDateTimeを調べなければ分からない (多分 大丈夫) // //////////////////////////////////////////////////////////////////////////////// function DateTimeToMJD(DT: TDateTime): double; begin Result := DateTimeToModifiedJulianDate(DT); end; function MJDToDateTime(MJD: Double): TDateTime; begin result := ModifiedJulianDateToDateTime(MJD); end; /////////////////////////////////////////////////////////////////////////// // // ケプラーの方程式で離心近点角(U)を求める // /////////////////////////////////////////////////////////////////////////// function Kepler(U0, E: double): Double; var U, UD: double; begin U := U0; Repeat UD := (U0 - U + E * sin(U)) / (1- E * cos(U)); U := U + UD Until IsZero(UD); result := U; end; function GLToDeg(GL: String; var Lon,Lat: Double): boolean; var s: string; w1,w2,w3: byte; begin s := GL; if length(GL) = 4 then s := s + 'AA'; w1 := ord(s[1]) - 65; w2 := ord(s[3]) - 48; w3 := ord(s[5]) - 65; Lon := w1 * 20 + w2 * 2 + (w3 / 12) - 180; w1 := ord(s[2]) - 65; w2 := ord(s[4]) - 48; w3 := ord(s[6]) - 65; Lat := w1 * 10 + w2 + (w3 / 24 ) - 90; Result := True; end; end.
unit untFCenterDM; interface uses SysUtils, Classes, DB, DBAccess, Uni, MemDS; type TdmFCenter = class(TDataModule) qryFOrderInfo: TUniQuery; qryFOrderInfoso_id: TIntegerField; qryFOrderInfoso_source: TStringField; qryFOrderInfosource_no: TStringField; qryFOrderInfom_id: TFloatField; qryFOrderInfotype: TFloatField; qryFOrderInfostatus: TFloatField; qryFOrderInfopayment_id: TFloatField; qryFOrderInfosend_type: TStringField; qryFOrderInfopayment_type: TFloatField; qryFOrderInfopayment_status: TFloatField; qryFOrderInfosub_date: TDateField; qryFOrderInfoconfirm_date: TDateField; qryFOrderInfoconfirm_by: TFloatField; qryFOrderInfoinvoice_id: TFloatField; qryFOrderInfosub_ip: TStringField; qryFOrderInfoprovince: TFloatField; qryFOrderInfocity: TFloatField; qryFOrderInfodistrict: TFloatField; qryFOrderInfoaddr: TStringField; qryFOrderInfoso_remark: TStringField; qryFOrderInfopost_code: TStringField; qryFOrderInforeceiver: TStringField; qryFOrderInfotel: TStringField; qryFOrderInfomobile: TStringField; qryFOrderInfocost_price: TFloatField; qryFOrderInfotax: TFloatField; qryFOrderInfop_amount: TFloatField; qryFOrderInfop_settle_amount: TFloatField; qryFOrderInfoship_amount: TFloatField; qryFOrderInfoship_settle_amount: TFloatField; qryFOrderInfoamount: TFloatField; qryFOrderInfosettle_amount: TFloatField; qryFOrderInforeturn_amount: TFloatField; qryFOrderInfofinal_amount: TFloatField; qryFOrderInfoship_order_number: TStringField; qryFOrderInfoscan_status: TFloatField; qryFOrderInfoship_remark: TStringField; qryFOrderInfosys_status: TFloatField; dsFOrderInfo: TUniDataSource; qryFOPList: TUniQuery; qryFOPListso_item_id: TIntegerField; qryFOPListso_id: TFloatField; qryFOPListso_no: TStringField; qryFOPListsku_id: TFloatField; qryFOPListp_id: TFloatField; qryFOPListp_sku: TStringField; qryFOPListp_sn: TStringField; qryFOPListp_ean: TStringField; qryFOPListp_number: TFloatField; qryFOPListp_cost_price: TFloatField; qryFOPListtax: TFloatField; qryFOPListsale_price: TFloatField; qryFOPListsale_amount: TFloatField; qryFOPListp_weight: TFloatField; qryFOPListsource: TStringField; qryFOPListreal_out_number: TFloatField; qryFOPListsys_status: TFloatField; qryFOPListpdt_name: TStringField; dsFOPList: TUniDataSource; qryFSBOList: TUniQuery; dsFSBOList: TUniDataSource; qryFSBOPList: TUniQuery; dsFSBOPList: TUniDataSource; qryFOrderInfoso_sn: TStringField; qryFOrderInfoRECEIVE_EMAIL: TStringField; qryProvince: TUniQuery; qryProvinceID: TFloatField; qryProvincePOSTCODE: TStringField; qryProvinceSTATESID: TStringField; qryProvinceCITYID: TStringField; qryProvinceADDRESSNAME: TStringField; qryProvinceADDRESSLEVEL: TStringField; dsProvince: TUniDataSource; qryCity: TUniQuery; qryCityID: TFloatField; qryCityPOSTCODE: TStringField; qryCitySTATESID: TStringField; qryCityCITYID: TStringField; qryCityADDRESSNAME: TStringField; qryCityADDRESSLEVEL: TStringField; dsCity: TUniDataSource; qryDistrict: TUniQuery; dsDistrict: TUniDataSource; qryPInfo: TUniQuery; qryPInfop_id: TIntegerField; qryPInfosku: TStringField; qryPInfosn: TStringField; qryPInfoean: TStringField; qryPInfotitle: TStringField; qryPInfoname: TStringField; qryPInfochineseN: TStringField; qryPInfoenglishN: TStringField; qryPInfoshortname: TStringField; qryPInfopic_path: TStringField; qryPInfotype: TFloatField; qryPInfostatus: TFloatField; qryPInfobrief: TStringField; qryPInfodescript: TMemoField; qryPInfobrand_id: TFloatField; qryPInfobcat_id: TStringField; qryPInfoscat_id: TStringField; qryPInfokeyword: TStringField; qryPInfotag: TStringField; qryPInfoscore: TFloatField; qryPInfospec: TStringField; qryPInfoorigin: TStringField; qryPInfoweight: TStringField; qryPInfofactory: TStringField; qryPInfosale_unit: TStringField; qryPInfocreate_by: TStringField; qryPInfocreate_date: TDateField; qryPInfolast_update_by: TStringField; qryPInfolast_update_date: TDateField; qryPInfosys_status: TFloatField; qryPInfop_price: TFloatField; qryFSBOListid: TIntegerField; qryFSBOListreturn_no: TStringField; qryFSBOListso_id: TIntegerField; qryFSBOListso_no: TStringField; qryFSBOListso_source: TStringField; qryFSBOListso_source_no: TStringField; qryFSBOListmem_id: TIntegerField; qryFSBOListstate: TIntegerField; qryFSBOListsubmit_date: TDateTimeField; qryFSBOListconfirm_date: TDateTimeField; qryFSBOListconfirm_by: TStringField; qryFSBOListso_memo: TStringField; qryFSBOListreturn_men: TStringField; qryFSBOListreturn_tel: TStringField; qryFSBOListreturn_mobile: TStringField; qryFSBOListreturn_email: TStringField; qryFSBOListreturn_amount: TFloatField; qryFSBOListreturn_price: TFloatField; qryFSBOListreturn_time: TDateTimeField; qryFSBOListreturn_settleup: TFloatField; qryFSBOListsys_state: TIntegerField; qryFSBOPListid: TIntegerField; qryFSBOPListrso_id: TIntegerField; qryFSBOPListrso_no: TStringField; qryFSBOPListp_id: TIntegerField; qryFSBOPListp_sku: TStringField; qryFSBOPListp_num: TIntegerField; qryFSBOPListp_price: TFloatField; qryFSBOPListp_amount: TFloatField; qryFSBOPListreal_input_num: TIntegerField; qryFSBOPListstate: TIntegerField; qryFSBOPListsys_state: TIntegerField; qryFSBOPListp_name: TStringField; qryFOrderInfosend_date: TStringField; qryFOrderInfoexpress_id: TIntegerField; qryExpressInfo: TUniQuery; qryExpressInfoid: TLargeintField; qryExpressInfoexpress_no: TStringField; qryExpressInfoexpress_name: TStringField; qryExpressInfoexpress_tel: TStringField; qryExpressInfoexpress_mobile: TStringField; qryExpressInfoexpress_fax: TStringField; qryExpressInfoexpressex_mail: TStringField; qryExpressInfoexpress_addr: TStringField; qryExpressInfoexpress_post: TFloatField; qryExpressInfoexpress_website: TStringField; qryExpressInfoexpress_msn: TStringField; qryExpressInfoexpress_qq: TStringField; qryExpressInfoexpress_create: TDateTimeField; qryExpressInfoexpress_info: TMemoField; qryExpressInfoexpress_interface: TStringField; qryExpressInfoexpress_model: TStringField; qryExpressInfocontract_linkmen: TStringField; qryExpressInfocontract_tel: TStringField; qryExpressInfocontract_mobile: TStringField; qryExpressInfocontract_email: TStringField; qryExpressInfocontract_fax: TStringField; qryExpressInfocontract_msn: TStringField; qryExpressInfocontract_qq: TStringField; qryExpressInfobusiness_linkmen: TStringField; qryExpressInfobusiness_tel: TStringField; qryExpressInfobusiness_mobile: TStringField; qryExpressInfobusiness_fax: TStringField; qryExpressInfobusiness_email: TStringField; qryExpressInfobusiness_msn: TStringField; qryExpressInfobusiness_qq: TStringField; qryExpressInfoaccounts_linkmen: TStringField; qryExpressInfoaccounts_tel: TStringField; qryExpressInfoaccounts_mobile: TStringField; qryExpressInfoaccounts_email: TStringField; qryExpressInfoaccounts_fax: TStringField; qryExpressInfoaccounts_msn: TStringField; qryExpressInfoaccounts_qq: TStringField; qryFOrderInfoexp_name: TStringField; qryMemInfo: TUniQuery; dsMemInfo: TUniDataSource; qryMemInfoemail: TStringField; qryMemInfonickname: TStringField; qryMemInfoname: TStringField; qryMemInfotel: TStringField; qryMemInfomobile: TStringField; qryMemInfom_id: TIntegerField; qryFOrderInfom_name: TStringField; qryFOrderInfom_mobile: TStringField; qryFOrderInfopreferential_price: TFloatField; qryDepotStat: TUniQuery; dsDepotStat: TUniDataSource; qryDepotStatsku: TStringField; qryDepotStatname: TStringField; qryDepotStatbrand_name: TStringField; qryDepotStatean: TStringField; qryDepotStatspec: TStringField; qryDepotStatcolor: TStringField; qryDepotStatp_size: TStringField; qryDepotStatstock: TFloatField; qryDepotStatdp_dpnum: TStringField; qryDepotStats_name: TStringField; qryDepotStatsort_n: TFloatField; qryDepotStatproduct_price: TFloatField; qryDepotStatsto_no: TStringField; qryDepotStatso_no: TStringField; qryDepotStatsupplier_contract: TStringField; qryFOrderInfocoupon_price: TFloatField; procedure priceGetText(Sender: TField; var Text: String; DisplayText: Boolean); procedure priceSetText(Sender: TField; const Text: String); private { Private declarations } public { Public declarations } end; var dmFCenter: TdmFCenter; implementation uses untCommonDm; {$R *.dfm} //获取商品价格 procedure TdmFCenter.priceGetText(Sender: TField; var Text: String; DisplayText: Boolean); begin Text := FormatFloat('0.00',Sender.AsFloat/100); end; //设置商品价格 procedure TdmFCenter.priceSetText(Sender: TField; const Text: String); begin Sender.AsFloat := StrToFloat(FormatFloat('0.00',StrToFloat(Text)))*100; end; end.
unit fNotePrt; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, fAutoSz, ORCtrls, StdCtrls, Mask, ORNet, ORFn, ComCtrls, VA508AccessibilityManager; type TfrmNotePrint = class(TfrmAutoSz) grpChooseCopy: TGroupBox; radChartCopy: TRadioButton; radWorkCopy: TRadioButton; grpDevice: TGroupBox; lblMargin: TLabel; lblLength: TLabel; txtRightMargin: TMaskEdit; txtPageLength: TMaskEdit; cmdOK: TButton; cmdCancel: TButton; lblNoteTitle: TMemo; cboDevice: TORComboBox; lblPrintTo: TLabel; dlgWinPrinter: TPrintDialog; chkDefault: TCheckBox; procedure cboDeviceNeedData(Sender: TObject; const StartFrom: String; Direction, InsertAt: Integer); procedure cboDeviceChange(Sender: TObject); procedure radChartCopyClick(Sender: TObject); procedure radWorkCopyClick(Sender: TObject); procedure cmdOKClick(Sender: TObject); procedure cmdCancelClick(Sender: TObject); private { Private declarations } FNote: Integer; FReportText: TRichEdit; procedure DisplaySelectDevice; public { Public declarations } end; procedure PrintNote(ANote: Longint; const ANoteTitle: string; MultiNotes: boolean = False); implementation {$R *.DFM} uses rCore, rTIU, rReports, uCore, Printers, uReports; const TX_NODEVICE = 'A device must be selected to print, or press ''Cancel'' to not print.'; TX_NODEVICE_CAP = 'Device Not Selected'; TX_ERR_CAP = 'Print Error'; PAGE_BREAK = '**PAGE BREAK**'; procedure PrintNote(ANote: Longint; const ANoteTitle: string; MultiNotes: boolean = False); { displays a form that prompts for a device and then prints the progress note } var frmNotePrint: TfrmNotePrint; DefPrt: string; aAllowToPrint: string; aAllowPrint: Integer; begin aAllowToPrint := AllowPrintOfNote(ANote); aAllowPrint := StrToIntDef(Piece(aAllowToPrint, '^', 1), 0); if aAllowPrint < 1 then begin InfoBox(Piece(aAllowToPrint, U, 2), 'Not Allowed to Print', MB_OK); Exit; end; frmNotePrint := TfrmNotePrint.Create(Application); try ResizeFormToFont(TForm(frmNotePrint)); with frmNotePrint do begin { check to see of Chart Print allowed outside of MAS } // if AllowChartPrintForNote(ANote) then if aAllowPrint = 2 then begin { This next code begs the question: Why are we even bothering to check radWorkCopy if we immediately check the other button? Short answer: it seems to wokr better Long answer: The checkboxes have to in some way register with the group they are in. If this doesn't happen, both will be initially included the tab order. This means that the first time tabbing through the controls, the work copy button would be tabbed to and selected after the chart copy. Tabbing through controls should not change the group selection. } radWorkCopy.Checked := True; radChartCopy.Checked := True; end else begin radChartCopy.Enabled := False; radWorkCopy.Checked := True; end; lblNoteTitle.Text := ANoteTitle; frmNotePrint.Caption := 'Print ' + Piece(Piece(ANoteTitle, #9, 2), ',', 1); FNote := ANote; DefPrt := GetDefaultPrinter(User.Duz, Encounter.Location); if User.CurrentPrinter = '' then User.CurrentPrinter := DefPrt; with cboDevice do begin if Printer.Printers.Count > 0 then begin Items.Add('WIN;Windows Printer^Windows Printer'); Items.Add('^--------------------VistA Printers----------------------'); end; if User.CurrentPrinter <> '' then begin InitLongList(Piece(User.CurrentPrinter, ';', 2)); SelectByID(User.CurrentPrinter); end else InitLongList(''); end; { if ((DefPrt = 'WIN;Windows Printer') and (User.CurrentPrinter = DefPrt)) then cmdOKClick(frmNotePrint) //CQ6660 //Commented out for CQ6660 //or //((User.CurrentPrinter <> '') and //(MultiNotes = True)) then //frmNotePrint.cmdOKClick(frmNotePrint) //end CQ6660 else } frmNotePrint.ShowModal; end; finally frmNotePrint.Release; end; end; procedure TfrmNotePrint.DisplaySelectDevice; begin with cboDevice, lblPrintTo do begin if radChartCopy.Checked then Caption := 'Print Chart Copy on: ' + Piece(ItemID, ';', 2); if radWorkCopy.Checked then Caption := 'Print Work Copy on: ' + Piece(ItemID, ';', 2); end; end; procedure TfrmNotePrint.cboDeviceNeedData(Sender: TObject; const StartFrom: string; Direction, InsertAt: Integer); begin inherited; cboDevice.ForDataUse(SubsetOfDevices(StartFrom, Direction)); end; procedure TfrmNotePrint.cboDeviceChange(Sender: TObject); begin inherited; with cboDevice do if ItemIndex > -1 then begin txtRightMargin.Text := Piece(Items[ItemIndex], '^', 4); txtPageLength.Text := Piece(Items[ItemIndex], '^', 5); DisplaySelectDevice; end; end; procedure TfrmNotePrint.radChartCopyClick(Sender: TObject); begin inherited; DisplaySelectDevice; end; procedure TfrmNotePrint.radWorkCopyClick(Sender: TObject); begin inherited; DisplaySelectDevice; end; procedure TfrmNotePrint.cmdOKClick(Sender: TObject); var ADevice, ErrMsg: string; ChartCopy: Boolean; RemoteSiteID: string; //for Remote site printing RemoteQuery: string; //for Remote site printing begin inherited; RemoteSiteID := ''; RemoteQuery := ''; if cboDevice.ItemID = '' then begin InfoBox(TX_NODEVICE, TX_NODEVICE_CAP, MB_OK); Exit; end; if radChartCopy.Checked then ChartCopy := True else ChartCopy := False; if Piece(cboDevice.ItemID, ';', 1) = 'WIN' then begin if dlgWinPrinter.Execute then begin FReportText := CreateReportTextComponent(Self); FastAssign(GetFormattedNote(FNote, ChartCopy), FReportText.Lines); PrintWindowsReport(FReportText, PAGE_BREAK, Self.Caption, ErrMsg); if Length(ErrMsg) > 0 then InfoBox(ErrMsg, TX_ERR_CAP, MB_OK); end end else begin ADevice := Piece(cboDevice.ItemID, ';', 2); PrintNoteToDevice(FNote, ADevice, ChartCopy, ErrMsg); if Length(ErrMsg) > 0 then InfoBox(ErrMsg, TX_ERR_CAP, MB_OK); end; if chkDefault.Checked then SaveDefaultPrinter(Piece(cboDevice.ItemID, ';', 1)); User.CurrentPrinter := cboDevice.ItemID; Close; end; procedure TfrmNotePrint.cmdCancelClick(Sender: TObject); begin inherited; Close; end; end.
unit WaitForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, dxSkinMetropolis, cxLabel, dxActivityIndicator; type TWaiting = class(TForm) WaitTitle: TcxLabel; aiProgress: TdxActivityIndicator; WaitMessage: TcxLabel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); strict private class var FException: Exception; class var FMode: Boolean; private class var WaitForm : TWaiting; class procedure OnTerminateTask(Sender: TObject); class procedure HandleException; class procedure DoHandleException; public class procedure Start(const ATitle: String; const ATask: TProc); class procedure Status(AMessage : String); end; var Waiting: TWaiting; implementation {$R *.dfm} procedure TWaiting.FormCreate(Sender: TObject); begin aiProgress.Active := True; end; procedure TWaiting.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; class procedure TWaiting.Start(const ATitle: String; const ATask: TProc); var T : TThread; begin if (not Assigned(WaitForm))then WaitForm := TWaiting.Create(nil); T := TThread.CreateAnonymousThread( procedure begin try ATask; except HandleException; end; end); T.OnTerminate := OnTerminateTask; T.Start; WaitForm.WaitTitle.Caption := ATitle; WaitForm.Update; WaitForm.ShowModal; DoHandleException; end; class procedure TWaiting.Status(AMessage: String); begin TThread.Synchronize(TThread.CurrentThread, procedure begin if (Assigned(WaitForm)) then begin WaitForm.aiProgress.Active := True; WaitForm.aiProgress.Update; WaitForm.WaitMessage.Caption := AMessage; WaitForm.Update; end; end); end; class procedure TWaiting.OnTerminateTask(Sender: TObject); begin if (Assigned(WaitForm)) then begin WaitForm.Close; WaitForm := nil; end; end; class procedure TWaiting.HandleException; begin FException := Exception(AcquireExceptionObject); end; class procedure TWaiting.DoHandleException; begin if (Assigned(FException)) then begin try if (FException is Exception) then raise FException at ReturnAddress; finally FException := nil; ReleaseExceptionObject; end; end; end; end.
unit UClient; interface type TClient = class private // The data fields of this new class ClientID : String; CallbackID : String; public // Properties to read these data values property UID : String read ClientID; property CID : String read CallbackID; // Constructor constructor Create(const ClientID : String; const CallbackID : String); end; implementation { TClient } constructor TClient.Create(const ClientID, CallbackID: String); begin self.ClientID := ClientID; self.CallbackID := CallbackID; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit System.Internal.ExcUtils; { This unit contains exception handling utility code that is used solely in the internal implementation of exception handling in the RTL. } interface uses System.SysUtils, System.SysConst; { If defined, we enable O/S hardware exception handling support on POSIX platforms that support it. } {$IF Defined(LINUX) or Defined(MACOS)} {$DEFINE ENABLE_SIGNAL_HANDLING} {$IFEND LINUX or MACOS} type TExceptType = (etDivByZero, etRangeError, etIntOverflow, etInvalidOp, etZeroDivide, etOverflow, etUnderflow, etInvalidCast, etAccessViolation, etPrivilege, etControlC, etStackOverflow, etVariantError, etAssertionFailed, etExternalException, etIntfCastError, etSafeCallException, etMonitorLockException, etNoMonitorSupportException {$IF defined(LINUX) or defined(MACOS)} , etQuit {$IFEND LINUX or MACOS} {$IFDEF POSIX} , etCodesetConversion {$ENDIF POSIX} , etNotImplemented ); TExceptRec = record EClass: TExceptType; EIdent: string; end; const ExceptTypes: array[TExceptType] of ExceptClass = ( EDivByZero, ERangeError, EIntOverflow, EInvalidOp, EZeroDivide, EOverflow, EUnderflow, EInvalidCast, EAccessViolation, EPrivilege, EControlC, EStackOverflow, EVariantError, EAssertionFailed, EExternalException, EIntfCastError, ESafecallException, EMonitorLockException, ENoMonitorSupportException {$IF defined(LINUX) or defined(MACOS)} , EQuit {$IFEND LINUX or MACOS} {$IFDEF POSIX} , ECodesetConversion {$ENDIF POSIX} , ENotImplemented ); // by using another indirection, the linker can actually eliminate all exception support if exceptions are not // referenced by the applicaiton. ExceptMap: array[Ord(reDivByZero)..Ord(High(TRuntimeError))] of TExceptRec = ( (EClass: etDivByZero; EIdent: SDivByZero), (EClass: etRangeError; EIdent: SRangeError), (EClass: etIntOverflow; EIdent: SIntOverflow), (EClass: etInvalidOp; EIdent: SInvalidOp), (EClass: etZeroDivide; EIdent: SZeroDivide), (EClass: etOverflow; EIdent: SOverflow), (EClass: etUnderflow; EIdent: SUnderflow), (EClass: etInvalidCast; EIdent: SInvalidCast), (EClass: etAccessViolation; EIdent: SAccessViolationNoArg), (EClass: etPrivilege; EIdent: SPrivilege), (EClass: etControlC; EIdent: SControlC), (EClass: etStackOverflow; EIdent: SStackOverflow), (EClass: etVariantError; EIdent: SInvalidVarCast), (EClass: etVariantError; EIdent: SInvalidVarOp), (EClass: etVariantError; EIdent: SDispatchError), (EClass: etVariantError; EIdent: SVarArrayCreate), (EClass: etVariantError; EIdent: SVarInvalid), (EClass: etVariantError; EIdent: SVarArrayBounds), (EClass: etAssertionFailed; EIdent: SAssertionFailed), (EClass: etExternalException; EIdent: SExternalException), (EClass: etIntfCastError; EIdent: SIntfCastError), (EClass: etSafecallException; EIdent: SSafecallException), (EClass: etMonitorLockException; EIdent: SMonitorLockException), (EClass: etNoMonitorSupportException; EIdent: SNoMonitorSupportException) {$IF Defined(LINUX) or Defined(MACOS)} , (EClass: etQuit; EIdent: SQuit) {$IFEND LINUX or MACOS} {$IFDEF POSIX} , (EClass: etCodesetConversion; EIdent: SCodesetConversionError) {$ENDIF POSIX} , (EClass: etNotImplemented; EIdent: SNotImplemented) ); {$IF Defined(LINUX) or Defined(MACOS)} function GetExceptionObject(ExceptionAddress: NativeUInt; AccessAddress: NativeUInt; ErrorCode: LongWord): Exception; {$IFEND LINUX or MACOS} {$IFDEF ENABLE_SIGNAL_HANDLING} { InquireSignal is used to determine the state of an OS signal handler. Pass it one of the RTL_SIG* constants, and it will return a TSignalState which will tell you if the signal has been hooked, not hooked, or overriden by some other module. You can use this function to determine if some other module has hijacked your signal handlers, should you wish to reinstall your own. This is a risky proposition under Linux, and is only recommended as a last resort. Do not pass RTL_SIGDEFAULT to this function. } function InquireSignal(RtlSigNum: Integer): TSignalState; { AbandonSignalHandler tells the RTL to leave a signal handler in place, even if we believe that we hooked it at startup time. Once you have called AbandonSignalHandler with a specific signal number, neither UnhookSignal nor the RTL will restore any previous signal handler under any condition. } procedure AbandonSignalHandler(RtlSigNum: Integer); { HookSignal is used to hook individual signals, or an RTL-defined default set of signals. It does not test whether a signal has already been hooked, so it should be used in conjunction with InquireSignal. It is exposed to enable users to hook signals in standalone libraries, or in the event that an external module hijacks the RTL installed signal handlers. Pass RTL_SIGDEFAULT if you want to hook all the signals that the RTL normally hooks at startup time. } procedure HookSignal(RtlSigNum: Integer); { UnhookSignal is used to remove signal handlers installed by HookSignal. It can remove individual signal handlers, or the RTL-defined default set of signals. If OnlyIfHooked is True, then we will only unhook the signal if the signal handler has been hooked, and has not since been overriden by some foreign handler. } procedure UnhookSignal(RtlSigNum: Integer; OnlyIfHooked: Boolean = True); { HookOSExceptions is used internally by thread support. DON'T call this function yourself. } procedure HookOSExceptions; procedure UnhookOSExceptions; { MapSignal is used internally as well. It maps a signal and associated context to an internal value that represents the type of Exception class to raise. } {$IF Defined(LINUX)} function MapSignal(SigNum: Integer; Context: Psigcontext_t): LongWord; {$ELSEIF Defined(MACOS)} function MapSignal(SigNum: Integer): LongWord; {$IFEND !MACOS} { SignalConverter is used internally to properly reinit the FPU and properly raise an external OS exception object. DON'T call this function yourself. } procedure SignalConverter(ExceptionEIP: LongWord; FaultAddr: LongWord; ErrorCode: LongWord); {$ENDIF ENABLE_SIGNAL_HANDLING} implementation {$IFDEF POSIX} uses {$IFDEF MACOS} System.Internal.MachExceptions, {$ENDIF} Posix.Base, Posix.Signal, Posix.Stdlib, Posix.Unistd, Posix.Pthread; function TlsGetValue(Key: Integer): Pointer; cdecl; external libpthread name _PU + 'pthread_getspecific'; {$ENDIF} {$IFDEF PIC} { Do not remove export or the begin block. } function GetGOT: Pointer; export; begin asm MOV Result,EBX end; end; {$ENDIF} {$IF Defined(LINUX) or Defined(MACOS)} function GetExceptionObject(ExceptionAddress: NativeUInt; AccessAddress: NativeUInt; ErrorCode: LongWord): Exception; begin case (ErrorCode and $ff) of 3..10, 12..21, 25: begin with ExceptMap[ErrorCode and $ff] do Result := ExceptTypes[EClass].Create(EIdent); end; 11: Result := EAccessViolation.CreateFmt(SAccessViolationArg2, [Pointer(ExceptionAddress), Pointer(AccessAddress)]); else // Result := EExternalException.CreateFmt(SExternalException, [P.ExceptionCode]); { Not quite right - we need the original trap code, but that's lost } Result := EExternalException.CreateFmt(SExternalException, [ErrorCode and $ff]); end; EExternal(Result).ExceptionAddress := ExceptionAddress; EExternal(Result).AccessAddress := AccessAddress; EExternal(Result).SignalNumber := ErrorCode shr 16; end; {$IFEND LINUX or MACOS} {$IFDEF ENABLE_SIGNAL_HANDLING} {$IFNDEF MACOS} {$IFDEF DEBUG} { Used for debugging the signal handlers. } procedure DumpContext(SigNum: Integer; context : Psigcontext_t); var Buff: array [0..128] of char; begin StrFmt(Buff, 'Context for signal: %d', [SigNum]); Writeln(Buff); StrFmt(Buff, 'CS = %04X DS = %04X ES = %04X FS = %04X GS = %04X SS = %04X', [context^.cs, context^.ds, context^.es, context^.fs, context^.gs, context^.ss]); WriteLn(Buff); StrFmt(Buff, 'EAX = %08X EBX = %08X ECX = %08X EDX = %08X', [context^.eax, context^.ebx, context^.ecx, context^.edx]); WriteLn(Buff); StrFmt(Buff, 'EDI = %08X ESI = %08X EBP = %08X ESP = %08X', [context^.edi, context^.esi, context^.ebp, context^.esp]); WriteLn(Buff); StrFmt(Buff, 'EIP = %08X EFLAGS = %08X ESP(signal) = %08X CR2 = %08X', [context^.eip, context^.eflags, context^.esp_at_signal, context^.cr2]); WriteLn(Buff); StrFmt(Buff, 'trapno = %d, err = %08x', [context^.trapno, context^.err]); WriteLn(Buff); end; {$ENDIF DEBUG} {$ENDIF !MACOS} { RaiseSignalException is called from SignalConverter, once we've made things look like there's a legitimate stack frame above us. Now we will just create an exception object, and raise it via a software raise. } procedure RaiseSignalException(ExceptionEIP: LongWord; FaultAddr: LongWord; ErrorCode: LongWord); begin raise GetExceptionObject(ExceptionEIP, FaultAddr, ErrorCode); end; { SignalConverter is where we come when a signal is raised that we want to convert to an exception. This function stands the best chance of being called with a useable stack frame behind it for the purpose of stack unwinding. We can't guarantee that, though. The stack was modified by the baseline signal handler to make it look as though we were called by the faulting instruction. That way the unwinder stands a chance of being able to clean things up. } procedure SignalConverter(ExceptionEIP: LongWord; FaultAddr: LongWord; ErrorCode: LongWord); asm { Here's the tricky part. We arrived here directly by virtue of our signal handler tweaking the execution context with our address. That means there's no return address on the stack. The unwinder needs to have a return address so that it can unwind past this function when we raise the Delphi exception. We will use the faulting instruction pointer as a fake return address. Because of the fencepost conditions in the Delphi unwinder, we need to have an address that is strictly greater than the actual faulting instruction, so we increment that address by one. This may be in the middle of an instruction, but we don't care, because we will never be returning to that address. Finally, the way that we get this address onto the stack is important. The compiler will generate unwind information for SignalConverter that will attempt to undo any stack modifications that are made by this function when unwinding past it. In this particular case, we don't want that to happen, so we use some assembly language tricks to get around the compiler noticing the stack modification. } MOV EBX, ESP // Get the current stack pointer SUB EBX, 4 // Effectively decrement the stack by 4 MOV ESP, EBX // by doing a move to ESP with a register value MOV [ESP], EAX // Store the instruction pointer into the new stack loc INC [ESP] // Increment by one to keep the unwinder happy { Reset the FPU, or things can go south down the line from here } FNINIT FWAIT {$IFDEF PIC} PUSH EAX PUSH ECX CALL GetGOT MOV EAX, [EAX].offset Default8087CW FLDCW [EAX] POP ECX POP EAX {$ELSE !PIC} FLDCW Default8087CW {$ENDIF !PIC} PUSH EBP MOV EBP, ESP {$IFDEF ALIGN_STACK} { On the Mac, we have to align the stack before we make this call. Note: Please see above for details on why ESP is modified in this way. } MOV EBX, ESP // Get the current stack pointer SUB EBX, 15 // align to 16 byte boundary AND EBX, $FFFFFFF0 MOV ESP, EBX // and reset ESP to the 16 byte aligned value {$ENDIF ALIGN_STACK} CALL RaiseSignalException end; { Under Linux, we crawl out from underneath the OS signal handler before we attempt to do anything with the signal. This is because the stack has a bunch of OS frames on there that we cannot possibly unwind from. So we use this routine to accomplish the dispatch, and then another routine to handle the language level of the exception handling. } procedure SignalDispatcher(SigNum: Integer; SigInfo: Psiginfo_t; UContext: Pointer); cdecl; {$IFDEF LINUX} type PGeneralRegisters = ^gregset_t; {$ENDIF LINUX} var mcontext: Pmcontext_t; {$IFDEF LINUX} GeneralRegisters: PGeneralRegisters; {$ENDIF LINUX} begin //DumpContext(SigNum, @context); { Some of the ways that we get here are can lead us to big trouble. For example, if the signal is SIGINT or SIGQUIT, these will commonly be raised to all threads in the process if the user generated them from the keyboard. This is handled well by the Delphi threads, but if a non-Delphi thread lets one of these get by unhandled, terrible things will happen. So we look for that case, and eat SIGINT and SIGQUIT that have been issued on threads that are not Delphi threads. If the signal is a SIGSEGV, or other fatal sort of signal, and the thread that we're running on is not a Delphi thread, then we are completely without options. We have no recovery means, and we have to take the app down hard, right away. } if TlsGetValue(TlsIndex) = nil then begin if (SigNum = SIGINT) or (SigNum = SIGQUIT) then Exit; RunError(232); end; { If we are processing another exception right now, we definitely do not want to be dispatching any exceptions that are async, like SIGINT and SIGQUIT. So we have check to see if OS signals are blocked. If they are, we have to eat this signal right now. } if AreOSExceptionsBlocked and ((SigNum = SIGINT) or (SigNum = SIGQUIT)) then Exit; { If someone wants to delay the handling of SIGINT or SIGQUIT until such time as it's safe to handle it, they set DeferUserInterrupts to True. Then we just set a global variable saying that a SIGINT or SIGQUIT was issued. It is the responsibility of some other body of code at this point to poll for changes to SIG(INT/QUIT)Issued } if DeferUserInterrupts then begin if SigNum = SIGINT then begin SIGINTIssued := True; Exit; end; if SigNum = SIGQUIT then begin SIGQUITIssued := True; Exit; end; end; BlockOSExceptions; {$IF Defined(LINUX)} mcontext := @Pucontext_t(UContext)^.uc_mcontext; // GeneralRegisters := @UContext^.uc_mcontext.gregs; mcontext^.gregs[REG_EAX] := mcontext^.gregs[REG_EIP]; mcontext^.gregs[REG_EDX] := mcontext^.cr2; mcontext^.gregs[REG_ECX] := MapSignal(SigNum, Psigcontext_t(@mcontext^.gregs)); mcontext^.gregs[REG_EIP] := LongWord(@SignalConverter); // GeneralRegisters^[REG_EAX] := GeneralRegisters^[REG_EIP]; // GeneralRegisters^[REG_EDX] := UContext^.uc_mcontext.cr2; // GeneralRegisters^[REG_ECX] := MapSignal(SigNum, PSigContext(GeneralRegisters)); // GeneralRegisters^[REG_EIP] := LongWord(@SignalConverter); {$ELSEIF Defined(MACOS)} mcontext := Pucontext_t(UContext)^.uc_mcontext; mcontext^.__ss.__eax := mcontext^.__ss.__eip; mcontext^.__ss.__edx := mcontext^.__es.__faultvaddr; mcontext^.__ss.__ecx := MapSignal(SigNum); mcontext^.__ss.__eip := UIntPtr(@SignalConverter); {$ELSE !LINUX and !MACOS} {$MESSAGE ERROR 'Unsupported platform for signal handling'} {$IFEND !LINUX and !MACOS} end; type TSignalMap = packed record SigNum: Integer; Abandon: Boolean; OldAction: sigaction_t; Hooked: Boolean; end; var Signals: array [0..RTL_SIGLAST] of TSignalMap = ( (SigNum: SIGINT;), {$IFDEF LINUX} (SigNum: SIGFPE;), (SigNum: SIGSEGV;), (SigNum: SIGILL;), (SigNum: SIGBUS;), {$ENDIF LINUX} (SigNum: SIGQUIT;) ); function InquireSignal(RtlSigNum: Integer): TSignalState; var Action: sigaction_t; begin if sigaction(Signals[RtlSigNum].SigNum, nil, @Action) = -1 then raise Exception.CreateRes(@SSigactionFailed); if (@Action.__sigaction_handler <> @SignalDispatcher) then begin if Signals[RtlSigNum].Hooked then Result := ssOverridden else Result := ssNotHooked; end else Result := ssHooked; end; procedure AbandonSignalHandler(RtlSigNum: Integer); var I: Integer; begin if RtlSigNum = RTL_SIGDEFAULT then begin for I := 0 to RTL_SIGLAST do AbandonSignalHandler(I); Exit; end; Signals[RtlSigNum].Abandon := True; end; procedure HookSignal(RtlSigNum: Integer); var Action: sigaction_t; I: Integer; begin if RtlSigNum = RTL_SIGDEFAULT then begin for I := 0 to RTL_SIGLAST do HookSignal(I); Exit; end; FillChar(Action, SizeOf(Action), 0); Action.__sigaction_handler := @SignalDispatcher; Action.sa_flags := SA_SIGINFO; sigaddset(Action.sa_mask, SIGINT); sigaddset(Action.sa_mask, SIGQUIT); if sigaction(Signals[RtlSigNum].SigNum, @Action, @Signals[RtlSigNum].OldAction) = -1 then raise Exception.CreateRes(@SSigactionFailed); Signals[RtlSigNum].Hooked := True; end; procedure UnhookSignal(RtlSigNum: Integer; OnlyIfHooked: Boolean); var I: Integer; begin if RtlSigNum = RTL_SIGDEFAULT then begin for I := 0 to RTL_SIGLAST do UnhookSignal(I, OnlyIfHooked); Exit; end; if not Signals[RtlSigNum].Abandon then begin if OnlyIfHooked and (InquireSignal(RtlSigNum) <> ssHooked) then Exit; if sigaction(Signals[RtlSigNum].SigNum, @Signals[RtlSigNum].OldAction, Nil) = -1 then raise Exception.CreateRes(@SSigactionFailed); Signals[RtlSigNum].Hooked := False; end; end; procedure UnhookOSExceptions; begin if not Assigned(HookOSExceptionsProc) then UnhookSignal(RTL_SIGDEFAULT, True); end; procedure HookOSExceptions; begin if Assigned(HookOSExceptionsProc) then HookOSExceptionsProc else begin {$IFDEF MACOS} if getenv('NO_DELPHI_MACH_EXCEPTIONS') = nil then MachExceptionsInit; {$ENDIF MACOS} HookSignal(RTL_SIGDEFAULT); end; end; {$IF Defined(LINUX)} function MapSignal(SigNum: Integer; Context: Psigcontext_t): LongWord; {$ELSEIF Defined(MACOS)} function MapSignal(SigNum: Integer): LongWord; {$IFEND !MACOS} var Err: TRuntimeError; begin case SigNum of SIGINT: { Control-C } Err := System.reControlBreak; SIGQUIT: { Quit key (Control-\) } Err := System.reQuit; {$IFDEF LINUX} SIGFPE: { Floating Point Error } Err := MapFPE(Context); SIGSEGV: { Segmentation Violation } Err := MapFault(Context); SIGILL: { Illegal Instruction } Err := MapFault(Context); SIGBUS: { Bus Error } Err := MapFault(Context); {$ENDIF LINUX} else Err := System.reExternalException; end; Result := LongWord(Err) or (LongWord(SigNum) shl 16); end; procedure PropagateSignals; var Exc: TObject; begin { If there is a current exception pending, then we're shutting down because it went unhandled. If that exception is the result of a signal, then we need to propagate that back out to the world as a real signal death. See the discussion at http://www2.cons.org/cracauer/sigint.html for more info. } Exc := ExceptObject; if (Exc <> nil) and (Exc is EExternal) then kill(getpid, EExternal(Exc).SignalNumber); end; {$ENDIF ENABLE_SIGNAL_HANDLING} initialization {$IFDEF ENABLE_SIGNAL_HANDLING} ExitProcessProc := PropagateSignals; {$ENDIF ENABLE_SIGNAL_HANDLING} end.
program max(input, output); const UNTEN = 0; { Array-Untergrenze } OBEN = 10; { Array-Obergrenze } type tIndex = UNTEN..OBEN; tFeld = array[tIndex] of integer; var auswahl : char; Feld : tFeld; Maximum : integer; function FeldMaxA ( var inFeld : tFeld; inUnten, inOben : tIndex) : integer; { bestimmt rekursiv das Maximum in einem Feld mit den Grenzen inUnten und inOben } var Mitte : tIndex; MaxL, MaxR : integer; begin if inUnten = inOben then FeldMaxA := inFeld[inUnten] else begin Mitte := (inUnten + inOben) div 2; MaxL := FeldMaxA (inFeld,inUnten,Mitte); MaxR := FeldMaxA (inFeld,Mitte+1,inOben); if MaxL > MaxR then FeldMaxA := MaxL else FeldMaxA := MaxR end end; { FeldMaxA } function FeldMaxB ( var inFeld : tFeld; inUnten, inOben : tIndex) : integer; { bestimmt rekursiv das Maximum in einem Feld mit den Grenzen inUnten und inOben } var Mitte : tIndex; MaxL, MaxR : integer; begin if inUnten = inOben then FeldMaxB := inFeld[inUnten] else begin Mitte := (inUnten + inOben) div 2; MaxL := FeldMaxB (inFeld,inUnten,Mitte); MaxR := FeldMaxB (inFeld,Mitte,inOben); if MaxL > MaxR then FeldMaxB := MaxL else FeldMaxB := MaxR end end; { FeldMaxB } function FeldMaxC ( var inFeld : tFeld; inUnten, inOben : tIndex) : integer; { bestimmt rekursiv das Maximum in einem Feld mit den Grenzen inUnten und inOben } var Mitte : tIndex; MaxL, MaxR : integer; begin if inUnten > inOben then FeldMaxC := inFeld[inUnten] else begin Mitte := (inUnten + inOben) div 2; MaxL := FeldMaxC (inFeld,inUnten,Mitte); MaxR := FeldMaxC (inFeld,Mitte+1,inOben); if MaxL > MaxR then FeldMaxC := MaxL else FeldMaxC := MaxR end end; { FeldMaxC } function FeldMaxD ( var inFeld : tFeld; inUnten, inOben : tIndex) : integer; { bestimmt rekursiv das Maximum in einem Feld mit den Grenzen inUnten und inOben } var Mitte : tIndex; MaxL, MaxR : integer; begin if inUnten > inOben then FeldMaxD := inFeld[inUnten] else begin Mitte := (inUnten + inOben) div 2; MaxL := FeldMaxD (inFeld,inUnten,Mitte); MaxR := FeldMaxD (inFeld,Mitte,inOben); if MaxL > MaxR then FeldMaxD := MaxL else FeldMaxD := MaxR end end; { FeldMaxD } function FeldMaxE ( var inFeld : tFeld; inUnten, inOben : tIndex) : integer; { bestimmt iterativ das Maximum in einem Feld mit den Grenzen inUnten und inOben } var i : tIndex; HilfMax : integer; { Hilfsvariable } begin HilfMax := 0; for i := inUnten to inOben do if inFeld[i] > HilfMax then HilfMax := inFeld[i]; FeldMaxE := HilfMax end; { FeldMaxE } begin Feld[0] := -2; Feld[1] := 2; Feld[2] := 20; Feld[3] := -20; Feld[4] := -123; Feld[5] := 23; Feld[6] := 222; Feld[7] := 15; Feld[8] := -10; Feld[9] := 16; Feld[10] := 161; writeln('Wählen Sie zwischen den Buchstaben A-E,'); writeln('um den Programmablauf zu verändern.'); read(auswahl); If (auswahl = 'A') Then { Richtige Lösung. } Maximum := FeldMaxA(Feld, UNTEN, OBEN) else If (auswahl = 'B') Then { Falsche Lösung, weil es bei MaxR zur Endlos-Schleife führt. Das Programm wird für MaxR nie beendet } Maximum := FeldMaxB(Feld, UNTEN, OBEN) else If (auswahl = 'C') Then { Falsche Lösung, weil es bei MaxL zur Endlos-Schleife führt. Exakt wie bei der Auswahl D } Maximum := FeldMaxC(Feld, UNTEN, OBEN) else If (auswahl = 'D') Then { Falsche Lösung, weil es bei MaxL zur Endlos-Schleife führt. Es wird nie inUnten > inOben sein! } Maximum := FeldMaxD(Feld, UNTEN, OBEN) else If (auswahl = 'E') Then begin { Falsche Lösung, da für die negativen Zahlen in dem Array immer 0 als Maximum-Wert zurückgegegben wird. } Maximum := FeldMaxE(Feld, UNTEN, OBEN); end; writeln('Max ist:', Maximum); end.
unit Universe; {$mode objfpc}{$H+}{$J-} interface uses Node; type { TUniverse } TUniverse = class private FGenerationCount: UInt64; FRoot: INode; public constructor Create; procedure Clear; procedure SetBit(const x, y: Integer); procedure RunStep; property Root: INode read FRoot; end; implementation { TUniverse } constructor TUniverse.Create; begin inherited; FRoot := TNode.Create; end; procedure TUniverse.Clear; begin FRoot := TNode.Create; end; procedure TUniverse.SetBit(const x, y: Integer); var MaxCoordinate: Integer; begin while (True) do begin MaxCoordinate := 1 shl (FRoot.Level - 1); if ((-MaxCoordinate <= x) and (x < MaxCoordinate - 1) and (-MaxCoordinate <= y) and (y < MaxCoordinate - 1)) then Break; FRoot := FRoot.ExpandUniverse; end; FRoot := FRoot.SetBit(x, y); end; procedure TUniverse.RunStep; begin while ((FRoot.Level < 3) or (FRoot.NW.Population <> FRoot.NW.SE.SE.Population) or (FRoot.NE.Population <> FRoot.NE.SW.SW.Population) or (FRoot.SW.Population <> FRoot.SW.NE.NE.Population) or (FRoot.SE.Population <> FRoot.SE.NW.NW.Population)) do FRoot := FRoot.ExpandUniverse; FRoot := FRoot.NextGeneration; Inc(FGenerationCount); end; end.
namespace RemObjects.SDK.CodeGen4; interface type JavaScriptRodlCodeGen = public class(RodlCodeGen) private fKnownTypes: Dictionary<String, String> := new Dictionary<String, String>; method _FixDataType(aValue: String): String; begin var l_lower := aValue.ToLowerInvariant; if fKnownTypes.ContainsKey(l_lower) then exit fKnownTypes[l_lower] else exit aValue; end; protected method GetGlobalName(library: RodlLibrary): String; override; empty; method AddGlobalConstants(file: CGCodeUnit; library: RodlLibrary); override; begin file.Initialization := new List<not nullable CGStatement>; var l_init := file.Initialization; var l_comment := new List<String>; l_comment.Add('This codegen depends on RemObjectsSDK.js'); l_comment.Add('Usage:'); l_comment.Add('var Channel = new RemObjects.SDK.HTTPClientChannel("http://localhost:8099/JSON");'); l_comment.Add('var Message = new RemObjects.SDK.JSONMessage();'); l_comment.Add('var Service = new NewService(Channel, Message);'); l_comment.Add('Service.Sum(1, 2,'); l_comment.Add(' function(result) {'); l_comment.Add(' alert(result);'); l_comment.Add(' },'); l_comment.Add(' function(msg) {alert(msg.getErrorMessage())}'); l_comment.Add(');'); l_init.Add(new CGCommentStatement(l_comment)); l_init.Add(new CGEmptyStatement()); var l_namespace := '__namespace'.AsNamedIdentifierExpression; var l_st: CGStatement := new CGAssignmentStatement( l_namespace, new CGSelfExpression() ); l_init.Add(l_st); var l_currnamespace := $"__{GetNamespace(library).Replace('.', '_')}__namespace"; var l_currnamespace_ne := l_currnamespace.AsNamedIdentifierExpression; l_st := new CGVariableDeclarationStatement( l_currnamespace, nil, new CGSelfExpression() ); l_init.Add(l_st); var l_namespace_le := GetNamespace(library).AsLiteralExpression; var l_parts := 'parts'.AsNamedIdentifierExpression; var l_current := 'current'.AsNamedIdentifierExpression; var l_ifthen := new CGBeginEndBlockStatement(); l_st := new CGVariableDeclarationStatement( 'parts', nil, new CGMethodCallExpression(l_namespace_le, 'split', [".".AsLiteralExpression.AsCallParameter]) ); l_ifthen.Statements.Add(l_st); l_st := new CGVariableDeclarationStatement( 'current', nil, new CGSelfExpression ); l_ifthen.Statements.Add(l_st); var l_for := new CGBeginEndBlockStatement(); var l_item := new CGArrayElementAccessExpression(l_current, [new CGArrayElementAccessExpression(l_parts, ['i'.AsNamedIdentifierExpression])]); l_st := new CGAssignmentStatement( l_item, new CGBinaryOperatorExpression( l_item, new CGNewInstanceExpression(new CGNilExpression), CGBinaryOperatorKind.LogicalOr) ); l_for.Statements.Add(l_st); l_st := new CGAssignmentStatement( l_current, l_item); l_for.Statements.Add(l_st); l_st := new CGForToLoopStatement('i', CGPredefinedTypeReference.Int32, 0.AsLiteralExpression, new CGBinaryOperatorExpression( new CGPropertyAccessExpression(l_parts, 'length'), 1.AsLiteralExpression, CGBinaryOperatorKind.Subtraction), l_for); l_ifthen.Statements.Add(l_st); l_st := new CGAssignmentStatement( l_namespace, l_current); l_ifthen.Statements.Add(l_st); l_st := new CGAssignmentStatement( l_currnamespace_ne, l_current); l_ifthen.Statements.Add(l_st); l_st := new CGIfThenElseStatement( new CGBinaryOperatorExpression( l_namespace_le, "".AsLiteralExpression, CGBinaryOperatorKind.NotEquals), l_ifthen ); l_init.Add(l_st); end; method GenerateEnum(file: CGCodeUnit; &library: RodlLibrary; entity: RodlEnum); override; begin var l_init := file.Initialization; l_init.Add(new CGEmptyStatement()); var l_namespace := '__namespace'.AsNamedIdentifierExpression; var l_name := SafeIdentifier(entity.Name); var l_namespace_name := new CGPropertyAccessExpression(l_namespace, l_name); l_init.Add(new CGSingleLineCommentStatement($"Enum: {l_name}")); var l_st := new CGAssignmentStatement( l_namespace_name, new CGLocalMethodStatement(l_name, [new CGAssignmentStatement( new CGPropertyAccessExpression(new CGSelfExpression, 'value'), new CGNilExpression)])); l_init.Add(l_st); var l_prototype := new CGPropertyAccessExpression(l_namespace_name, 'prototype'); l_st := new CGAssignmentStatement( l_prototype, new CGNewInstanceExpression( new CGNamedTypeReference('ROEnumType') &namespace(new CGNamespaceReference('RemObjects.SDK')) ) ); l_init.Add(l_st); var l_array := new CGArrayLiteralExpression([]); for each item in entity.Items do l_array.Elements.Add(item.Name.AsLiteralExpression); l_st := new CGAssignmentStatement( new CGPropertyAccessExpression(l_prototype, 'enumValues'), l_array ); l_init.Add(l_st); l_st := new CGAssignmentStatement( new CGPropertyAccessExpression(l_prototype, 'constructor'), l_namespace_name ); l_init.Add(l_st); l_st := new CGAssignmentStatement( new CGArrayElementAccessExpression( (new CGNamedTypeReference('RTTI') &namespace(new CGNamespaceReference('RemObjects.SDK'))).AsExpression, l_name.AsLiteralExpression), l_namespace_name ); l_init.Add(l_st); end; method GenerateStruct(file: CGCodeUnit; library: RodlLibrary; entity: RodlStruct); override; begin var l_init := file.Initialization; l_init.Add(new CGEmptyStatement()); var l_namespace := '__namespace'.AsNamedIdentifierExpression; var l_name := SafeIdentifier(entity.Name); var l_namespace_name := new CGPropertyAccessExpression(l_namespace, l_name); l_init.Add(new CGSingleLineCommentStatement($"Struct: {l_name}")); var l_st_list := new List<CGStatement>; for each item in entity.GetAllItems.OrderBy(b->b.Name) do l_st_list.Add(new CGAssignmentStatement( new CGPropertyAccessExpression(new CGSelfExpression(), SafeIdentifier(item.Name)), new CGNewInstanceExpression(new CGNilExpression, [new CGCallParameter(_FixDataType(item.DataType).AsLiteralExpression, 'dataType'), new CGCallParameter(new CGNilExpression, 'value')]))); var l_st := new CGAssignmentStatement( l_namespace_name, new CGLocalMethodStatement(l_name, l_st_list)); l_init.Add(l_st); var l_prototype := new CGPropertyAccessExpression(l_namespace_name, 'prototype'); l_st := new CGAssignmentStatement( l_prototype, new CGNewInstanceExpression( new CGNamedTypeReference('ROStructType') &namespace(new CGNamespaceReference('RemObjects.SDK')) ) ); l_init.Add(l_st); l_st := new CGAssignmentStatement( new CGPropertyAccessExpression(l_prototype, 'constructor'), l_namespace_name ); l_init.Add(l_st); l_st := new CGAssignmentStatement( new CGArrayElementAccessExpression( (new CGNamedTypeReference('RTTI') &namespace(new CGNamespaceReference('RemObjects.SDK'))).AsExpression, l_name.AsLiteralExpression), l_namespace_name ); l_init.Add(l_st); end; method GenerateArray(file: CGCodeUnit; library: RodlLibrary; entity: RodlArray); override; begin var l_init := file.Initialization; l_init.Add(new CGEmptyStatement()); var l_namespace := '__namespace'.AsNamedIdentifierExpression; var l_name := SafeIdentifier(entity.Name); var l_namespace_name := new CGPropertyAccessExpression(l_namespace, l_name); l_init.Add(new CGSingleLineCommentStatement($"Array: {l_name}")); var l_st := new CGAssignmentStatement( l_namespace_name, new CGLocalMethodStatement(l_name, [ new CGMethodCallExpression( new CGNamedTypeReference('ROArrayType') &namespace(new CGNamespaceReference('RemObjects.SDK')).AsExpression, 'call', [(new CGSelfExpression).AsCallParameter] ), new CGAssignmentStatement( new CGPropertyAccessExpression(new CGSelfExpression, 'elementType'), entity.ElementType.AsLiteralExpression) ])); l_init.Add(l_st); var l_prototype := new CGPropertyAccessExpression(l_namespace_name, 'prototype'); l_st := new CGAssignmentStatement( l_prototype, new CGNewInstanceExpression( new CGNamedTypeReference('ROArrayType') &namespace(new CGNamespaceReference('RemObjects.SDK')) ) ); l_init.Add(l_st); l_st := new CGAssignmentStatement( new CGPropertyAccessExpression(l_prototype, 'constructor'), l_namespace_name ); l_init.Add(l_st); l_st := new CGAssignmentStatement( new CGArrayElementAccessExpression( (new CGNamedTypeReference('RTTI') &namespace(new CGNamespaceReference('RemObjects.SDK'))).AsExpression, l_name.AsLiteralExpression), l_namespace_name ); l_init.Add(l_st); end; method GenerateException(file: CGCodeUnit; library: RodlLibrary; entity: RodlException); override; begin var l_init := file.Initialization; l_init.Add(new CGEmptyStatement()); var l_namespace := '__namespace'.AsNamedIdentifierExpression; var l_name := SafeIdentifier(entity.Name); var l_namespace_name := new CGPropertyAccessExpression(l_namespace, l_name); l_init.Add(new CGSingleLineCommentStatement($"Exception: {l_name}")); var l_st_list := new List<CGStatement>; l_st_list.Add(new CGMethodCallExpression( new CGNamedTypeReference('ROException') &namespace(new CGNamespaceReference('RemObjects.SDK')).AsExpression, 'call', [(new CGSelfExpression).AsCallParameter, 'e'.AsNamedIdentifierExpression.AsCallParameter] )); for each item in entity.Items do l_st_list.Add(new CGAssignmentStatement( new CGPropertyAccessExpression( new CGPropertyAccessExpression(new CGSelfExpression(), 'fields'), SafeIdentifier(item.Name)), new CGNewInstanceExpression(new CGNilExpression, [new CGCallParameter(_FixDataType(item.DataType).AsLiteralExpression, 'dataType'), new CGCallParameter(new CGNilExpression, 'value')]))); var l_st := new CGAssignmentStatement( l_namespace_name, new CGLocalMethodStatement(l_name, [new CGParameterDefinition('e')].ToList, l_st_list)); l_init.Add(l_st); var l_prototype := new CGPropertyAccessExpression(l_namespace_name, 'prototype'); l_st := new CGAssignmentStatement( l_prototype, new CGNewInstanceExpression( new CGNamedTypeReference('ROException') &namespace(new CGNamespaceReference('RemObjects.SDK')) ) ); l_init.Add(l_st); l_st := new CGAssignmentStatement( new CGArrayElementAccessExpression( (new CGNamedTypeReference('RTTI') &namespace(new CGNamespaceReference('RemObjects.SDK'))).AsExpression, l_name.AsLiteralExpression), l_namespace_name ); l_init.Add(l_st); end; method GenerateService(file: CGCodeUnit; library: RodlLibrary; entity: RodlService); override; begin var l_init := file.Initialization; l_init.Add(new CGEmptyStatement()); var l_namespace := '__namespace'.AsNamedIdentifierExpression; var l_name := SafeIdentifier(entity.Name); var l_namespace_name := new CGPropertyAccessExpression(l_namespace, l_name); l_init.Add(new CGSingleLineCommentStatement($"Service: {l_name}")); var l_serviceName := new CGPropertyAccessExpression(new CGSelfExpression, 'fServiceName'); var l_st: CGStatement; l_st := new CGAssignmentStatement( l_namespace_name, new CGLocalMethodStatement(l_name, [new CGParameterDefinition('__channel'), new CGParameterDefinition('__message'), new CGParameterDefinition('__service_name')], [new CGMethodCallExpression( new CGNamedTypeReference('ROService') &namespace(new CGNamespaceReference('RemObjects.SDK')).AsExpression, 'call', [(new CGSelfExpression).AsCallParameter, '__channel'.AsNamedIdentifierExpression.AsCallParameter, '__message'.AsNamedIdentifierExpression.AsCallParameter, '__service_name'.AsNamedIdentifierExpression.AsCallParameter] ), new CGAssignmentStatement( l_serviceName, new CGBinaryOperatorExpression( new CGBinaryOperatorExpression( l_serviceName, '__service_name'.AsNamedIdentifierExpression, CGBinaryOperatorKind.LogicalOr), l_name.AsLiteralExpression, CGBinaryOperatorKind.LogicalOr))] ) ); l_init.Add(l_st); var l_prototype := new CGPropertyAccessExpression(l_namespace_name, 'prototype'); if assigned(entity.AncestorEntity) then begin var l_AncestorNS := ''; if (entity.AncestorEntity <> nil) then begin if (entity.AncestorEntity.IsFromUsedRodl) and not String.IsNullOrEmpty(entity.AncestorEntity.FromUsedRodl.Includes.JavaScriptModule) then l_AncestorNS := entity.AncestorEntity.FromUsedRodl.Includes.JavaScriptModule; if not String.IsNullOrEmpty(l_AncestorNS) then l_AncestorNS := l_AncestorNS.Replace('.', '_') + '__'; end; l_AncestorNS := $"__{l_AncestorNS}namespace"; l_st := new CGAssignmentStatement( l_prototype, new CGNewInstanceExpression( new CGNamedTypeReference(SafeIdentifier(entity.AncestorName)) &namespace(new CGNamespaceReference(l_AncestorNS)) ) ); l_init.Add(l_st); end; for each op in entity.DefaultInterface.Items do begin var l_parameters := new List<CGParameterDefinition>; for each &param in op.Items.Where(b->b.ParamFlag in [ParamFlags.In, ParamFlags.InOut]) do l_parameters.Add(new CGParameterDefinition(SafeIdentifier(&param.Name))); l_parameters.Add(new CGParameterDefinition('__success')); l_parameters.Add(new CGParameterDefinition('__error')); var l_try := new List<CGStatement>; l_st := new CGVariableDeclarationStatement('msg', nil, new CGMethodCallExpression( new CGPropertyAccessExpression(new CGSelfExpression, 'fMessage'), 'clone' )); l_try.Add(l_st); var l_msg := 'msg'.AsNamedIdentifierExpression; l_st := new CGMethodCallExpression(l_msg, 'initialize', [l_serviceName.AsCallParameter, SafeIdentifier(op.Name).AsLiteralExpression.AsCallParameter]); l_try.Add(l_st); for each &param in op.Items.Where(b->b.ParamFlag in [ParamFlags.In, ParamFlags.InOut]) do begin l_st := new CGMethodCallExpression(l_msg, 'write', [&param.Name.AsLiteralExpression.AsCallParameter, _FixDataType(&param.DataType).AsLiteralExpression.AsCallParameter, SafeIdentifier(param.Name).AsNamedIdentifierExpression.AsCallParameter ]); l_try.Add(l_st); end; l_st := new CGMethodCallExpression(l_msg, 'finalize'); l_try.Add(l_st); var l_methodst := new List<CGStatement>; var l_message := '__message'.AsNamedIdentifierExpression; if assigned(op.Result) then begin l_st := new CGVariableDeclarationStatement('__result', nil, new CGMethodCallExpression(l_message, 'read', [op.Result.Name.AsLiteralExpression.AsCallParameter, _FixDataType(op.Result.DataType).AsLiteralExpression.AsCallParameter])); l_methodst.Add(l_st); end; for each &param in op.Items.Where(b->b.ParamFlag in [ParamFlags.InOut, ParamFlags.Out]) do begin l_st := new CGVariableDeclarationStatement($'__{SafeIdentifier(&param.Name)}', nil, new CGMethodCallExpression(l_msg, 'read', [&param.Name.AsLiteralExpression.AsCallParameter, _FixDataType(&param.DataType).AsLiteralExpression.AsCallParameter])); l_methodst.Add(l_st); end; var l_params1 := new List<CGCallParameter>; if assigned(op.Result) then l_params1.Add('__result'.AsNamedIdentifierExpression.AsCallParameter); for each &param in op.Items.Where(b->b.ParamFlag in [ParamFlags.InOut, ParamFlags.Out]) do l_params1.Add($'__{SafeIdentifier(&param.Name)}'.AsNamedIdentifierExpression.AsCallParameter); l_methodst.Add(new CGMethodCallExpression(nil, '__success', l_params1)); var l_func := new CGAnonymousMethodExpression([new CGParameterDefinition('__message')].ToList, l_methodst); l_st := new CGMethodCallExpression(new CGPropertyAccessExpression(new CGSelfExpression, 'fChannel'), 'dispatch', [l_msg.AsCallParameter, l_func.AsCallParameter, '__error'.AsNamedIdentifierExpression.AsCallParameter]); l_try.Add(l_st); var l_catch := new CGCatchBlockStatement('e'); l_catch.Statements.Add(new CGMethodCallExpression(nil, '__error', [l_msg.AsCallParameter, 'e'.AsNamedIdentifierExpression.AsCallParameter])); var l_trycatch := new CGTryFinallyCatchStatement(l_try); l_trycatch.CatchBlocks.Add(l_catch); l_st := new CGAssignmentStatement( new CGPropertyAccessExpression(l_prototype, SafeIdentifier(op.Name)), new CGAnonymousMethodExpression(l_parameters, [l_trycatch as CGStatement].ToList)); l_init.Add(l_st); end; end; method GenerateEventSink(file: CGCodeUnit; library: RodlLibrary; entity: RodlEventSink); override; begin var l_init := file.Initialization; l_init.Add(new CGEmptyStatement()); var l_namespace := '__namespace'.AsNamedIdentifierExpression; var l_name := SafeIdentifier(entity.Name); var l_namespace_name := new CGPropertyAccessExpression(l_namespace, l_name); l_init.Add(new CGSingleLineCommentStatement($"Event sink: {l_name}")); var l_st: CGStatement; var l_methodst :=new List<CGStatement>; for each op in entity.DefaultInterface.Items do begin var l_method_p :=new List<CGCallParameter>; for each &param in op.Items do begin var l_params := new List<CGCallParameter>; l_params.Add(new CGCallParameter(_FixDataType(&param.DataType).AsLiteralExpression, 'dataType')); l_params.Add(new CGCallParameter(new CGNilExpression, 'value')); l_method_p.Add(new CGCallParameter( new CGNewInstanceExpression(new CGNilExpression, l_params), &param.Name)); end; l_methodst.Add(new CGAssignmentStatement( new CGPropertyAccessExpression(new CGSelfExpression, op.Name), new CGNewInstanceExpression(new CGNilExpression, l_method_p))); end; l_st := new CGAssignmentStatement( l_namespace_name, new CGLocalMethodStatement(entity.Name, l_methodst )); l_init.Add(l_st); var l_prototype := new CGPropertyAccessExpression(l_namespace_name, 'prototype'); l_st := new CGAssignmentStatement( l_prototype, new CGNewInstanceExpression( new CGNamedTypeReference('ROEventSink') &namespace(new CGNamespaceReference('RemObjects.SDK')) ) ); l_init.Add(l_st); l_st := new CGAssignmentStatement( new CGPropertyAccessExpression(l_prototype, 'constructor'), l_namespace_name ); l_init.Add(l_st); l_st := new CGAssignmentStatement( new CGArrayElementAccessExpression( (new CGNamedTypeReference('RTTI') &namespace(new CGNamespaceReference('RemObjects.SDK'))).AsExpression, l_name.AsLiteralExpression), l_namespace_name ); l_init.Add(l_st); end; public constructor; begin fKnownTypes.Add('integer', 'Integer'); fKnownTypes.Add('datetime', 'DateTime'); fKnownTypes.Add('double', 'Double'); fKnownTypes.Add('currency', 'Currency'); fKnownTypes.Add('widestring', 'WideString'); fKnownTypes.Add('ansistring', 'AnsiString'); fKnownTypes.Add('int64', 'Int64'); fKnownTypes.Add('boolean', 'Boolean'); fKnownTypes.Add('variant', 'Variant'); fKnownTypes.Add('binary', 'Binary'); fKnownTypes.Add('xml', 'Xml'); fKnownTypes.Add('guid', 'Guid'); fKnownTypes.Add('decimal', 'Decimal'); fKnownTypes.Add('utf8string', 'Utf8String'); fKnownTypes.Add('xsdatetime', 'XsDateTime'); ReservedWords.Add('boolean'); ReservedWords.Add('break'); ReservedWords.Add('byte'); ReservedWords.Add('case'); ReservedWords.Add('catch'); ReservedWords.Add('char'); ReservedWords.Add('continue'); ReservedWords.Add('default'); ReservedWords.Add('delete'); ReservedWords.Add('do'); ReservedWords.Add('double'); ReservedWords.Add('else'); ReservedWords.Add('false'); ReservedWords.Add('final'); ReservedWords.Add('finally'); ReservedWords.Add('float'); ReservedWords.Add('for'); ReservedWords.Add('function'); ReservedWords.Add('if'); ReservedWords.Add('in'); ReservedWords.Add('instanceof'); ReservedWords.Add('int'); ReservedWords.Add('long'); ReservedWords.Add('new'); ReservedWords.Add('null'); ReservedWords.Add('return'); ReservedWords.Add('short'); ReservedWords.Add('switch'); ReservedWords.Add('this'); ReservedWords.Add('throw'); ReservedWords.Add('true'); ReservedWords.Add('try'); ReservedWords.Add('typeof'); ReservedWords.Add('var'); ReservedWords.Add('void'); ReservedWords.Add('while'); ReservedWords.Add('with'); end; end; implementation end.
unit Classe_Empresa; interface uses Classes, Dialogs, SysUtils, IniFiles, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.Stan.Intf, FireDAC.Stan.Option, Classe_EmpresaTributacao; type TEmpresa = class private FAtiva : Boolean; // EMP_BLOQUEADA varchar(1) NULL FNomeFantasia : String; // EMP_NOME_FANTASIA varchar(50) NULL FCodigoUniSystem : String; // EMP_CODIGO_UNISYSTEM varchar(10) NULL FRazaoSocial : String; // EMP_RAZAOSOCIAL varchar(30) NULL FPessoaJuridica : Boolean; // EMP_PESSOAJF varchar(1) NULL FEMP_PESSOAJF : String; FDataInicioAtividades : TDateTime; // EMP_INICIOATIVIDADES DATETIME NULL FDataInicioAtividadesString : String; FInscricaoEstadual : String; // EMP_INSCRICAO_ESTADUAL varchar(20) NULL FInscricaoMunicipal : String; // EMP_INSCRICAO_MUNICIPAL varchar(20) NULL FSUFRAMA : String; // EMP_SUFRAMA varchar(10) NULL FCNAE : String; // EMP_CNAE varchar(10) NULL FCNPJ : String; // EMP_CNPJ varchar(20) NULL FNIRE : String; // EMP_NIRE varchar(11) NULL FIESubstTributario : String; // EMP_INSCRICAO_ESTADUAL_ST varchar(20) NULL FEnderecoRua : String; // EMP_ENDERECO varchar(40) NULL FEnderecoCEP : String; // EMP_CEP varchar(20) NULL, FEnderecoNumero : String; // EMP_ENDERECO_NUMERO varchar(10) NULL, FEnderecoBairro : String; // EMP_BAIRRO varchar(50) NULL, FEnderecoComplemento : String; // EMP_ENDERECO_COMPLEMENTO varchar(60) NULL, FEnderecoMunicipio : String; // EMP_CIDADE varchar(40) NULL, FEnderecoMunicipioIBGE : String; // EMP_IBGECIDADE varchar(10) NULL, FEnderecoUF : String; // EMP_UF varchar(2) NULL, FEnderecoUFIBGE : String; // EMP_IBGEUF varchar(2) NULL FTelefone : String; // EMP_FONES varchar(40) NULL FCelular : String; // EMP_CELULAR varchar(40) NULL FWhatsApp : String; // EMP_WHATSAPP varchar(40) NULL FEmail : String; // EMP_EMAIL varchar(40) NULL FContribuinteIPI : Boolean; // EMP_CONTRIBUINTE_IPI integer null FResponsavelNome : String; // EMP_RESPONSAVEL_NOME varchar(40) NULL FResponsavelTelefone : String; // EMP_RESPONSAVEL_TELEFONE varchar(40) NULL FResponsavelCelular : String; // EMP_RESPONSAVEL_CELULAR varchar(40) NULL FResponsavelEmail : String; // EMP_RESPONSAVEL_EMAIL varchar(40) NULL FContadorEmpresa : String; // EMP_CONTADOR_EMPRESA VARCHAR(40) MULL FContadorResponsavel : String; // EMP_CONTADOR_RESPONSAVEL VARCHAR(40) MULL FContadorCNPJ : String; // EMP_CONTADOR_CNPJ VARCHAR(14) MULL FContadorCPF : String; // EMP_CONTADOR_CPF VARCHAR(11) MULL FContadorTelefone1 : String; // EMP_CONTADOR_TEL1 VARCHAR(20) MULL FContadorTelefone2 : String; // EMP_CONTADOR_TEL2 VARCHAR(20) MULL FContadorCRC : String; // EMP_CONTADOR_CRC VARCHAR(20) MULL FContadorCelular1 : String; // EMP_CONTADOR_CEL1 VARCHAR(20) MULL FContadorCelular2 : String; // EMP_CONTADOR_CEL2 VARCHAR(20) MULL FContadorEmail : String; // EMP_CONTADOR_EMAIL VARCHAR(40) MULL FDataCadastro : TDateTime; // EMP_DT DATETIME NULL FDataCadastroString : String; FTributacao : TTributosDeEmpresa; // FNomeDecente : String; // EMP_SEI LA O QUE..... //PASSO 3 FExiste : Boolean; procedure Preencher_Parametros_Empresa(pQuery:TFDQuery); function getFNomeFantasia: String; function getFExiste: Boolean; function getFCodigoUniSystem: String; function getFAtiva: Boolean; procedure setFAtiva(const Value: Boolean); procedure setFCodigoUniSystem(const Value: String); procedure setFNomeFantasia(const Value: String); function getFPessoaJuridica: Boolean; procedure setFPessoaJuridica(const Value: Boolean); function getFRazaoSocial: String; procedure setFRazaoSocial(const Value: String); function getFDataInicioAtividades: TDateTime; procedure setFDataInicioAtividades(const Value: TDateTime); function Insert:Boolean; function Update:Boolean; function DadosCorretos:Boolean; function NaoInformadoString(pCampo,pDescricao:String):Boolean; function getFInscricaoEstadual: String; procedure setFInscricaoEstadual(const Value: String); function getFSUFRAMA: String; procedure setFSUFRAMA(const Value: String); function getFCNAE: String; procedure setFCNAE(const Value: String); function getFCNPJ: String; procedure setFCNPJ(const Value: String); function getFInscricaoMunicipal: String; procedure setFInscricaoMunicipal(const Value: String); function getDataInicioAtividadesString: String; function getFNIRE: String; procedure setFNIRE(const Value: String); function getFIESubstTributario: String; procedure setFIESubstTributario(const Value: String); function getFEnderecoRua: String; procedure setFEnderecoRua(const Value: String); function getFEnderecoCEP: String; procedure setFEnderecoCEP(const Value: String); function getFEnderecoNumero: String; procedure setFEnderecoNumero(const Value: String); function getFEnderecoBairro: String; procedure setFEnderecoBairro(const Value: String); function getFEnderecoComplemento: String; procedure setFEnderecoComplemento(const Value: String); function getFEnderecoMunicipio: String; procedure setFEnderecoMunicipio(const Value: String); function getFEnderecoMunicipioIBGE: String; procedure setFEnderecoMunicipioIBGE(const Value: String); function getFEnderecoUF: String; procedure setFEnderecoUF(const Value: String); function getFContribuinteIPI: Boolean; procedure setFContribuinteIPI(const Value: Boolean); function getFCelular: String; function getFEmail: String; function getFEnderecoUFIBGE: String; function getFTelefone: String; function getFWhatsApp: String; procedure setFCelular(const Value: String); procedure setFEmail(const Value: String); procedure setFEnderecoUFIBGE(const Value: String); procedure setFTelefone(const Value: String); procedure setFWhatsApp(const Value: String); function getFResponsavelCelular: String; function getFResponsavelEmail: String; function getFResponsavelNome: String; function getFResponsavelTelefone: String; procedure setFResponsavelCelular(const Value: String); procedure setFResponsavelEmail(const Value: String); procedure setFResponsavelNome(const Value: String); procedure setFResponsavelTelefone(const Value: String); function getFContadorEmpresa: String; procedure setFContadorEmpresa(const Value: String); procedure setFContadorResponsavel(const Value: String); function getFContadorCNPJ: String; procedure setFContadorCNPJ(const Value: String); function getFContadorCPF: String; procedure setFContadorCPF(const Value: String); function getFContadorTelefone1: String; procedure setFContadorTelefone1(const Value: String); function getFContadorTelefone2: String; procedure setFContadorTelefone2(const Value: String); function getFContadorCRC: String; procedure setFContadorCRC(const Value: String); function getFContadorCelular1: String; procedure setFContadorCelular1(const Value: String); function getFContadorCelular2: String; procedure setFContadorCelular2(const Value: String); function getFContadorEmail: String; procedure setFContadorEmail(const Value: String); function getFContadorResponsavel: String; function getDataCadastroString: String; function getFDataCadastro: TDateTime; procedure setFDataCadastro(const Value: TDateTime); public constructor Create; destructor Destroy; override; property NomeFantasia : String read getFNomeFantasia write setFNomeFantasia; property RazaoSocial : String read getFRazaoSocial write setFRazaoSocial; property CodigoUniSystem : String read getFCodigoUniSystem write setFCodigoUniSystem; property DataInicioAtividades : TDateTime read getFDataInicioAtividades write setFDataInicioAtividades; property DataInicioAtividadesString : String read getDataInicioAtividadesString; property Ativa : Boolean read getFAtiva write setFAtiva; property PessoaJuridica : Boolean read getFPessoaJuridica write setFPessoaJuridica; property Existe : Boolean read getFExiste; property InscricaoEstadual : String read getFInscricaoEstadual write setFInscricaoEstadual; property InscricaoMunicipal : String read getFInscricaoMunicipal write setFInscricaoMunicipal; property SUFRAMA : String read getFSUFRAMA write setFSUFRAMA; property CNAE : String read getFCNAE write setFCNAE; property CNPJ : String read getFCNPJ write setFCNPJ; property NIRE : String read getFNIRE write setFNIRE; property IESubstTributario : String read getFIESubstTributario write setFIESubstTributario; property EnderecoRua : String read getFEnderecoRua write setFEnderecoRua; property EnderecoCEP : String read getFEnderecoCEP write setFEnderecoCEP; property EnderecoNumero : String read getFEnderecoNumero write setFEnderecoNumero; property EnderecoBairro : String read getFEnderecoBairro write setFEnderecoBairro; property EnderecoComplemento : String read getFEnderecoComplemento write setFEnderecoComplemento; property EnderecoMunicipio : String read getFEnderecoMunicipio write setFEnderecoMunicipio; property EnderecoMunicipioIBGE : String read getFEnderecoMunicipioIBGE write setFEnderecoMunicipioIBGE; property EnderecoUF : String read getFEnderecoUF write setFEnderecoUF; property EnderecoUFIBGE : String read getFEnderecoUFIBGE write setFEnderecoUFIBGE; property Telefone : String read getFTelefone write setFTelefone; property Celular : String read getFCelular write setFCelular; property WhatsApp : String read getFWhatsApp write setFWhatsApp; property Email : String read getFEmail write setFEmail; property ContribuinteIPI : Boolean read getFContribuinteIPI write setFContribuinteIPI; property ResponsavelNome : String read getFResponsavelNome write setFResponsavelNome; property ResponsavelTelefone : String read getFResponsavelTelefone write setFResponsavelTelefone; property ResponsavelCelular : String read getFResponsavelCelular write setFResponsavelCelular; property ResponsavelEmail : String read getFResponsavelEmail write setFResponsavelEmail; property ContadorEmpresa : String read getFContadorEmpresa write setFContadorEmpresa; property ContadorResponsavel : String read getFContadorResponsavel write setFContadorResponsavel; property ContadorCNPJ : String read getFContadorCNPJ write setFContadorCNPJ; property ContadorCPF : String read getFContadorCPF write setFContadorCPF; property ContadorTelefone1 : String read getFContadorTelefone1 write setFContadorTelefone1; property ContadorTelefone2 : String read getFContadorTelefone2 write setFContadorTelefone2; property ContadorCRC : String read getFContadorCRC write setFContadorCRC; property ContadorCelular1 : String read getFContadorCelular1 write setFContadorCelular1; property ContadorCelular2 : String read getFContadorCelular2 write setFContadorCelular2; property ContadorEmail : String read getFContadorEmail write setFContadorEmail; property DataCadastro : TDateTime read getFDataCadastro write setFDataCadastro; property DataCadastroString : String read getDataCadastroString; property Tributacao : TTributosDeEmpresa read FTributacao write FTributacao; //PASSO 4 procedure Abrir; Function Gravar:Boolean; end; implementation { TEmpresa } uses Funcoes; procedure TEmpresa.Abrir; var qLocal: TFDQuery; begin qLocal := TFDQuery.Create(nil); qLocal.ConnectionName :='X'; qLocal.Close; qLocal.SQL.Clear; qLocal.SQL.Add('SELECT * FROM EMPRESA_EMP'); qLocal.Open; FNomeFantasia := ''; FCodigoUniSystem:= ''; FRazaoSocial := ''; if qLocal.eof then begin FExiste:=False; qLocal.Free; exit; end; FExiste := True; FNomeFantasia := qLocal.FieldByName('EMP_NOME_FANTASIA' ).AsString; FRazaoSocial := qLocal.FieldByName('EMP_RAZAOSOCIAL' ).AsString; FDataInicioAtividades := qLocal.FieldByName('EMP_INICIOATIVIDADES' ).AsDateTime; FDataInicioAtividadesString := qLocal.FieldByName('EMP_INICIOATIVIDADES' ).AsString; FAtiva :=(qLocal.FieldByName('EMP_BLOQUEADA' ).AsString = 'N'); FPessoaJuridica :=(qLocal.FieldByName('EMP_PESSOAJF' ).AsString = 'J'); FInscricaoEstadual := qLocal.FieldByName('EMP_INSCRICAO_ESTADUAL' ).AsString; FInscricaoMunicipal := qLocal.FieldByName('EMP_INSCRICAO_MUNICIPAL' ).AsString; FSUFRAMA := qLocal.FieldByName('EMP_SUFRAMA' ).AsString; FCNAE := qLocal.FieldByName('EMP_CNAE' ).AsString; FCNPJ := qLocal.FieldByName('EMP_CNPJ' ).AsString; FNIRE := qLocal.FieldByName('EMP_NIRE' ).AsString; FIESubstTributario := qLocal.FieldByName('EMP_INSCRICAO_ESTADUAL_ST').AsString; FEnderecoRua := qLocal.FieldByName('EMP_ENDERECO' ).AsString; FEnderecoCEP := qLocal.FieldByName('EMP_CEP' ).AsString; FEnderecoNumero := qLocal.FieldByName('EMP_ENDERECO_NUMERO' ).AsString; FEnderecoBairro := qLocal.FieldByName('EMP_BAIRRO' ).AsString; FEnderecoComplemento := qLocal.FieldByname('EMP_ENDERECO_COMPLEMENTO' ).AsString; FEnderecoMunicipio := qLocal.FieldByname('EMP_CIDADE' ).AsString; FEnderecoMunicipioIBGE := qLocal.FieldByname('EMP_IBGECIDADE' ).AsString; FEnderecoUF := qLocal.FieldByname('EMP_UF' ).AsString; FEnderecoUFIBGE := qLocal.FieldByName('EMP_IBGEUF' ).AsString; FTelefone := qLocal.FieldByName('EMP_FONES' ).AsString; FCelular := qLocal.FieldByName('EMP_CELULAR' ).AsString; FWhatsApp := qLocal.FieldByName('EMP_WHATSAPP' ).AsString; FEmail := qLocal.FieldByName('EMP_EMAIL' ).AsString; FContribuinteIPI :=(qLocal.FieldByname('EMP_CONTRIBUINTE_IPI' ).AsInteger = 1); FResponsavelNome := qLocal.FieldByname('EMP_RESPONSAVEL_NOME' ).AsString; FResponsavelTelefone := qLocal.FieldByname('EMP_RESPONSAVEL_TELEFONE' ).AsString; FResponsavelCelular := qLocal.FieldByname('EMP_RESPONSAVEL_CELULAR' ).AsString; FResponsavelEmail := qLocal.FieldByname('EMP_RESPONSAVEL_EMAIL' ).AsString; FContadorEmpresa := qLocal.FieldByname('EMP_CONTADOR_EMPRESA' ).AsString; FContadorResponsavel := qLocal.FieldByname('EMP_CONTADOR_RESPONSAVEL' ).AsString; FContadorCNPJ := qLocal.FieldByname('EMP_CONTADOR_CNPJ' ).AsString; FContadorCPF := qLocal.FieldByname('EMP_CONTADOR_CPF' ).AsString; FContadorTelefone1 := qLocal.FieldByname('EMP_CONTADOR_TEL1' ).AsString; FContadorTelefone2 := qLocal.FieldByname('EMP_CONTADOR_TEL2' ).AsString; FContadorCRC := qLocal.FieldByname('EMP_CONTADOR_CRC' ).AsString; FContadorCelular1 := qLocal.FieldByname('EMP_CONTADOR_CEL1' ).AsString; FContadorCelular2 := qLocal.FieldByname('EMP_CONTADOR_CEL2' ).AsString; FContadorEmail := qLocal.FieldByname('EMP_CONTADOR_EMAIL' ).AsString; FTributacao.PIS.Cumulativo :=(qLocal.FieldByName('EMP_PIS_CUMULATIVO' ).AsInteger = 1); FTributacao.PIS.Aliquota := qLocal.FieldByName('EMP_PIS_ALIQUOTA' ).AsFloat; FDataCadastro := qLocal.FieldByName('EMP_DT' ).AsDateTime; FCodigoUniSystem := qLocal.FieldByName('EMP_CODIGO_UNISYSTEM' ).AsString; //PASSO 9 Qlocal.Free; end; constructor TEmpresa.Create; begin FTributacao := TTributosDeEmpresa.Create; end; function TEmpresa.DadosCorretos: Boolean; begin Result := False; // if NaoInformadoString(FNomeFantasia ,'Nome Fantasia' ) or // NaoInformadoString(FCodigoUniSystem,'Código Unisystem') or // NaoInformadoString(FRazaoSocial ,'Razão Social' ) then // exit; Result := True; end; destructor TEmpresa.Destroy; begin FTributacao.Free; inherited; end; function TEmpresa.getDataCadastroString: String; begin result := self.FDataCadastroString; end; function TEmpresa.getDataInicioAtividadesString: String; begin result := self.FDataInicioAtividadesString; end; function TEmpresa.getFAtiva: Boolean; begin result := FAtiva; end; function TEmpresa.getFSUFRAMA: String; begin result := Copy(self.FSUFRAMA,1,10); end; function TEmpresa.getFEmail: String; begin result := self.FEmail; end; function TEmpresa.getFTelefone: String; begin result := self.FTelefone; end; function TEmpresa.getFWhatsApp: String; begin result := self.FWhatsApp; end; function TEmpresa.getFEnderecoBairro: String; begin result := self.FEnderecoBairro; end; function TEmpresa.getFEnderecoCEP: String; begin result := self.FEnderecoCEP; end; function TEmpresa.getFEnderecoMunicipioIBGE: String; begin result := self.FEnderecoMunicipioIBGE; end; function TEmpresa.getFEnderecoComplemento: String; begin result := self.FEnderecoComplemento; end; function TEmpresa.getFEnderecoMunicipio: String; begin result := self.FEnderecoMunicipio; end; function TEmpresa.getFEnderecoNumero: String; begin result := self.FEnderecoNumero; end; function TEmpresa.getFCelular: String; begin result := self.FCelular; end; function TEmpresa.getFCNAE: String; begin result := self.FCNAE; end; function TEmpresa.getFCNPJ: String; begin result := self.FCNPJ; // FormataCPF_CGC(self.FCNPJ); end; function TEmpresa.getFCodigoUniSystem: String; begin result := self.FCodigoUniSystem; end; function TEmpresa.getFContribuinteIPI: Boolean; begin result := self.FContribuinteIPI end; function TEmpresa.getFDataCadastro: TDateTime; begin result := self.FDataCadastro; end; function TEmpresa.getFDataInicioAtividades: TDateTime; begin result := self.FDataInicioAtividades; end; function TEmpresa.getFEnderecoRua: String; begin result := self.FEnderecoRua; end; function TEmpresa.getFEnderecoUF: String; begin result:= self.FEnderecoUF; end; function TEmpresa.getFEnderecoUFIBGE: String; begin result := self.FEnderecoUFIBGE; end; function TEmpresa.getFExiste: Boolean; begin result := self.FExiste; end; function TEmpresa.getFIESubstTributario: String; begin result := self.FIESubstTributario; end; function TEmpresa.getFInscricaoEstadual: String; begin result := self.FInscricaoEstadual; end; function TEmpresa.getFInscricaoMunicipal: String; begin result := self.FInscricaoMunicipal; end; function TEmpresa.getFNIRE: String; begin result := self.FNIRE; end; function TEmpresa.getFNomeFantasia: String; begin result := self.FNomeFantasia; end; function TEmpresa.getFPessoaJuridica: Boolean; begin Result := self.FPessoaJuridica; end; function TEmpresa.getFRazaoSocial: String; begin Result := self.FRazaoSocial; end; function TEmpresa.getFResponsavelCelular: String; begin Result := self.FResponsavelCelular; end; function TEmpresa.getFResponsavelEmail: String; begin Result := self.FResponsavelEmail; end; function TEmpresa.getFResponsavelNome: String; begin Result := self.FResponsavelNome; end; function TEmpresa.getFResponsavelTelefone: String; begin Result := self.FResponsavelTelefone; end; function TEmpresa.Gravar:Boolean; begin result := False; if not DadosCorretos then exit; if not Existe then begin if not Insert then exit; end else begin if not Update then exit; end; Result := True; end; function TEmpresa.Insert:Boolean; var qLocal:TFDQuery; begin result := False; try qLocal := TFDQuery.Create(nil); qLocal.ConnectionName :='X'; qLocal.Close; qLocal.SQL.Clear; qLocal.SQL.Add('INSERT INTO EMPRESA_EMP '); qLocal.SQL.Add(' ( '); qLocal.SQL.Add(' EMP_NOME_FANTASIA, '); qLocal.SQL.Add(' EMP_RAZAOSOCIAL, '); qLocal.SQL.Add(' EMP_CODIGO_UNISYSTEM, '); qLocal.SQL.Add(' EMP_INICIOATIVIDADES, '); qLocal.SQL.Add(' EMP_BLOQUEADA, '); qLocal.SQL.Add(' EMP_PESSOAJF, '); qLocal.SQL.Add(' EMP_INSCRICAO_ESTADUAL, '); qLocal.SQL.Add(' EMP_INSCRICAO_MUNICIPAL, '); qLocal.SQL.Add(' EMP_SUFRAMA, '); qLocal.SQL.Add(' EMP_CNAE, '); qLocal.SQL.Add(' EMP_CNPJ, '); qLocal.SQL.Add(' EMP_NIRE, '); qLocal.SQL.Add(' EMP_INSCRICAO_ESTADUAL_ST, '); qLocal.SQL.Add(' EMP_ENDERECO, '); qLocal.SQL.Add(' EMP_CEP, '); qLocal.SQL.Add(' EMP_ENDERECO_NUMERO, '); qLocal.SQL.Add(' EMP_BAIRRO, '); qLocal.SQL.Add(' EMP_ENDERECO_COMPLEMENTO, '); qLocal.SQL.Add(' EMP_CIDADE, '); qLocal.SQL.Add(' EMP_IBGECIDADE, '); qLocal.SQL.Add(' EMP_UF, '); qLocal.SQL.Add(' EMP_IBGEUF, '); qLocal.SQL.Add(' EMP_FONES, '); qLocal.SQL.Add(' EMP_CELULAR, '); qLocal.SQL.Add(' EMP_WHATSAPP, '); qLocal.SQL.Add(' EMP_EMAIL, '); qLocal.SQL.Add(' EMP_CONTRIBUINTE_IPI, '); qLocal.SQL.Add(' EMP_RESPONSAVEL_NOME, '); qLocal.SQL.Add(' EMP_RESPONSAVEL_TELEFONE, '); qLocal.SQL.Add(' EMP_RESPONSAVEL_CELULAR, '); qLocal.SQL.Add(' EMP_RESPONSAVEL_EMAIL, '); qLocal.SQL.Add(' EMP_CONTADOR_EMPRESA, '); qLocal.SQL.Add(' EMP_CONTADOR_RESPONSAVEL, '); qLocal.SQL.Add(' EMP_CONTADOR_CNPJ, '); qLocal.SQL.Add(' EMP_CONTADOR_CPF, '); qLocal.SQL.Add(' EMP_CONTADOR_TEL1, '); qLocal.SQL.Add(' EMP_CONTADOR_TEL2, '); qLocal.SQL.Add(' EMP_CONTADOR_CRC, '); qLocal.SQL.Add(' EMP_CONTADOR_CEL1, '); qLocal.SQL.Add(' EMP_CONTADOR_CEL2, '); qLocal.SQL.Add(' EMP_CONTADOR_EMAIL, '); qLocal.SQL.Add(' EMP_DT, '); qLocal.SQL.Add(' EMP_PIS_CUMULATIVO, '); qLocal.SQL.Add(' EMP_PIS_ALIQUOTA '); qLocal.SQL.Add(' ) '); qLocal.SQL.Add('VALUES '); qLocal.SQL.Add(' ( '); qLocal.SQL.Add(' :EMP_NOME_FANTASIA, '); qLocal.SQL.Add(' :EMP_RAZAOSOCIAL, '); qLocal.SQL.Add(' :EMP_CODIGO_UNISYSTEM, '); qLocal.SQL.Add(' :EMP_INICIOATIVIDADES, '); qLocal.SQL.Add(' :EMP_BLOQUEADA, '); qLocal.SQL.Add(' :EMP_PESSOAJF, '); qLocal.SQL.Add(' :EMP_INSCRICAO_ESTADUAL, '); qLocal.SQL.Add(' :EMP_INSCRICAO_MUNICIPAL, '); qLocal.SQL.Add(' :EMP_SUFRAMA, '); qLocal.SQL.Add(' :EMP_CNAE, '); qLocal.SQL.Add(' :EMP_CNPJ, '); qLocal.SQL.Add(' :EMP_NIRE, '); qLocal.SQL.Add(' :EMP_INSCRICAO_ESTADUAL_ST, '); qLocal.SQL.Add(' :EMP_ENDERECO, '); qLocal.SQL.Add(' :EMP_CEP, '); qLocal.SQL.Add(' :EMP_ENDERECO_NUMERO, '); qLocal.SQL.Add(' :EMP_BAIRRO, '); qLocal.SQL.Add(' :EMP_ENDERECO_COMPLEMENTO, '); qLocal.SQL.Add(' :EMP_CIDADE, '); qLocal.SQL.Add(' :EMP_IBGECIDADE, '); qLocal.SQL.Add(' :EMP_UF, '); qLocal.SQL.Add(' :EMP_IBGEUF, '); qLocal.SQL.Add(' :EMP_FONES, '); qLocal.SQL.Add(' :EMP_CELULAR, '); qLocal.SQL.Add(' :EMP_WHATSAPP, '); qLocal.SQL.Add(' :EMP_EMAIL, '); qLocal.SQL.Add(' :EMP_CONTRIBUINTE_IPI, '); qLocal.SQL.Add(' :EMP_RESPONSAVEL_NOME, '); qLocal.SQL.Add(' :EMP_RESPONSAVEL_TELEFONE, '); qLocal.SQL.Add(' :EMP_RESPONSAVEL_CELULAR, '); qLocal.SQL.Add(' :EMP_RESPONSAVEL_EMAIL, '); qLocal.SQL.Add(' :EMP_CONTADOR_EMPRESA, '); qLocal.SQL.Add(' :EMP_CONTADOR_RESPONSAVEL, '); qLocal.SQL.Add(' :EMP_CONTADOR_CNPJ, '); qLocal.SQL.Add(' :EMP_CONTADOR_CPF, '); qLocal.SQL.Add(' :EMP_CONTADOR_TEL1, '); qLocal.SQL.Add(' :EMP_CONTADOR_TEL2, '); qLocal.SQL.Add(' :EMP_CONTADOR_CRC, '); qLocal.SQL.Add(' :EMP_CONTADOR_CEL1, '); qLocal.SQL.Add(' :EMP_CONTADOR_CEL2, '); qLocal.SQL.Add(' :EMP_CONTADOR_EMAIL, '); qLocal.SQL.Add(' :EMP_DT, '); qLocal.SQL.Add(' :EMP_PIS_CUMULATIVO, '); qLocal.SQL.Add(' :EMP_PIS_ALIQUOTA '); qLocal.SQL.Add(' ) '); //passo 11 Preencher_Parametros_Empresa(qLocal); qLocal.ExecSql; qLocal.Free; Log('Incluiu empresa '+ Empresa.FNomeFantasia); Result := True; except qLocal.Free; ShowMessage('Erro ao incluir Empresa'); LOGErros('Erro ao incluir Empresa'); end; end; procedure TEmpresa.Preencher_Parametros_Empresa(pQuery:TFDQuery); begin pQuery.ParamByName('EMP_PESSOAJF' ).AsString := FEMP_PESSOAJF; pQuery.ParamByName('EMP_NOME_FANTASIA' ).AsString := FNomeFantasia; pQuery.ParamByName('EMP_RAZAOSOCIAL' ).AsString := FRazaoSocial; pQuery.ParamByName('EMP_CODIGO_UNISYSTEM' ).AsString := FCodigoUniSystem; pQuery.ParamByName('EMP_INICIOATIVIDADES' ).AsDateTime := FDataInicioAtividades; if FAtiva then pQuery.ParamByName('EMP_BLOQUEADA' ).AsString := 'N' else pQuery.ParamByName('EMP_BLOQUEADA' ).AsString := 'S'; pQuery.ParamByName('EMP_INSCRICAO_ESTADUAL' ).AsString := FInscricaoEstadual; pQuery.ParamByName('EMP_INSCRICAO_MUNICIPAL' ).AsString := FInscricaoMunicipal; pQuery.ParamByName('EMP_SUFRAMA' ).AsString := FSUFRAMA; pQuery.ParamByName('EMP_CNAE' ).AsString := FCNAE; pQuery.ParamByName('EMP_CNPJ' ).AsString := FCNPJ; pQuery.ParamByName('EMP_NIRE' ).AsString := FNIRE; pQuery.ParamByName('EMP_INSCRICAO_ESTADUAL_ST').AsString := FIESubstTributario; pQuery.ParamByName('EMP_ENDERECO' ).AsString := FEnderecoRua; pQuery.ParamByName('EMP_CEP' ).AsString := FEnderecoCEP; pQuery.ParamByName('EMP_ENDERECO_NUMERO' ).AsString := FEnderecoNumero; pQuery.ParamByName('EMP_BAIRRO' ).AsString := FEnderecoBairro; pQuery.ParamByName('EMP_ENDERECO_COMPLEMENTO' ).AsString := FEnderecoComplemento; pQuery.ParamByName('EMP_CIDADE' ).AsString := FEnderecoMunicipio; pQuery.ParamByName('EMP_IBGECIDADE' ).AsString := FEnderecoMunicipioIBGE; pQuery.ParamByName('EMP_UF' ).AsString := FEnderecoUF; pQuery.ParamByName('EMP_IBGEUF' ).AsString := FEnderecoUFIBGE; pQuery.ParamByName('EMP_FONES' ).AsString := FTelefone; pQuery.ParamByName('EMP_CELULAR' ).AsString := FCelular; pQuery.ParamByName('EMP_WHATSAPP' ).AsString := FWhatsApp; pQuery.ParamByName('EMP_EMAIL' ).AsString := FEmail; pQuery.ParamByName('EMP_CONTRIBUINTE_IPI' ).AsInteger := f0ou1(FContribuinteIPI); pQuery.ParamByName('EMP_RESPONSAVEL_NOME' ).AsString := FResponsavelNome; pQuery.ParamByName('EMP_RESPONSAVEL_TELEFONE' ).AsString := FResponsavelTelefone; pQuery.ParamByName('EMP_RESPONSAVEL_CELULAR' ).AsString := FResponsavelCelular; pQuery.ParamByName('EMP_RESPONSAVEL_EMAIL' ).AsString := FResponsavelEmail; pQuery.ParamByName('EMP_CONTADOR_EMPRESA' ).AsString := FContadorEmpresa; pQuery.ParamByName('EMP_CONTADOR_RESPONSAVEL' ).AsString := FContadorResponsavel; pQuery.ParamByName('EMP_CONTADOR_CNPJ' ).AsString := FContadorCNPJ; pQuery.ParamByName('EMP_CONTADOR_CPF' ).AsString := FContadorCPF; pQuery.ParamByName('EMP_CONTADOR_TEL1' ).AsString := FContadorTelefone1; pQuery.ParamByName('EMP_CONTADOR_TEL2' ).AsString := FContadorTelefone2; pQuery.ParamByName('EMP_CONTADOR_CRC' ).AsString := FContadorCRC; pQuery.ParamByName('EMP_CONTADOR_CEL1' ).AsString := FContadorCelular1; pQuery.ParamByName('EMP_CONTADOR_CEL2' ).AsString := FContadorCelular2; pQuery.ParamByName('EMP_CONTADOR_EMAIL' ).AsString := FContadorEmail; pQuery.ParamByName('EMP_DT' ).AsDateTime := FDataCadastro; pQuery.ParamByName('EMP_CODIGO_UNISYSTEM' ).AsString := FCodigoUniSystem; pQuery.ParamByName('EMP_PIS_CUMULATIVO' ).AsInteger := f0ou1(FTributacao.PIS.Cumulativo); pQuery.ParamByName('EMP_PIS_ALIQUOTA' ).AsFloat := FTributacao.PIS.Aliquota; //passo12 end; function TEmpresa.NaoInformadoString(pCampo, pDescricao: String): Boolean; begin Result := False; if pCampo = '' then begin ShowMessage('Informe '+pDescricao); exit; end; Result := True; end; procedure TEmpresa.setFAtiva(const Value: Boolean); begin FAtiva := Value; end; procedure TEmpresa.setFSUFRAMA(const Value: String); begin FSUFRAMA := Copy(Value,1,11); end; procedure TEmpresa.setFEmail(const Value: String); begin FEmail := Copy(Value,1,40); end; procedure TEmpresa.setFTelefone(const Value: String); begin FTelefone := Copy(Value,1,40); end; procedure TEmpresa.setFWhatsApp(const Value: String); begin FWhatsApp := Copy(Value,1,40); end; procedure TEmpresa.setFEnderecoBairro(const Value: String); begin FEnderecoBairro := Copy(Value,1,50) end; procedure TEmpresa.setFEnderecoCEP(const Value: String); begin FEnderecoCEP := Copy(Value,1,20); end; procedure TEmpresa.setFEnderecoMunicipioIBGE(const Value: String); begin FEnderecoMunicipioIBGE := Copy(Value,1,10) end; procedure TEmpresa.setFEnderecoComplemento(const Value: String); begin FEnderecoComplemento := Copy(Value,1,60); end; procedure TEmpresa.setFEnderecoUFIBGE(const Value: String); begin FEnderecoUFIBGE := Copy(Value,1,2); end; procedure TEmpresa.setFEnderecoMunicipio(const Value: String); begin FEnderecoMunicipio := Copy(Value,1,40); end; procedure TEmpresa.setFEnderecoNumero(const Value: String); begin FEnderecoNumero := Copy(Value,1,10); end; procedure TEmpresa.setFCelular(const Value: String); begin FCelular := Copy(Value,1,40); end; procedure TEmpresa.setFCNAE(const Value: String); begin FCNAE := Copy(Value,1,10); end; procedure TEmpresa.setFCNPJ(const Value: String); begin FCNPJ := Copy(SoNumeros(Value),1,14) end; procedure TEmpresa.setFCodigoUniSystem(const Value: String); begin self.FCodigoUniSystem := Copy(Value,1,10); end; procedure TEmpresa.setFContribuinteIPI(const Value: Boolean); begin self.FContribuinteIPI := Value; end; procedure TEmpresa.setFDataCadastro(const Value: TDateTime); begin self.FDataCadastro := Value; end; procedure TEmpresa.setFDataInicioAtividades(const Value: TDateTime); begin self.FDataInicioAtividades := Value; end; procedure TEmpresa.setFEnderecoRua(const Value: String); begin self.FEnderecoRua := Value; end; procedure TEmpresa.setFEnderecoUF(const Value: String); begin self.FEnderecoUF := copy(value,1,2); end; procedure TEmpresa.setFIESubstTributario(const Value: String); begin self.FIESubstTributario := Copy(Value,1,20); end; procedure TEmpresa.setFInscricaoEstadual(const Value: String); begin self.FInscricaoEstadual := Copy(Value,1,20); end; procedure TEmpresa.setFInscricaoMunicipal(const Value: String); begin self.FInscricaoMunicipal := Copy(Value,1,20); end; procedure TEmpresa.setFNIRE(const Value: String); begin FNIRE := Copy(Value,1,11); end; procedure TEmpresa.setFNomeFantasia(const Value: String); begin FNomeFantasia := Copy(Value,1,50); end; procedure TEmpresa.setFPessoaJuridica(const Value: Boolean); begin FPessoaJuridica := Value; if value then self.FEMP_PESSOAJF := 'J' else self.FEMP_PESSOAJF := 'F'; end; procedure TEmpresa.setFRazaoSocial(const Value: String); begin FRazaoSocial := Copy(Value,1,30); end; procedure TEmpresa.setFResponsavelCelular(const Value: String); begin FResponsavelCelular := Copy(Value,1,40); end; procedure TEmpresa.setFResponsavelEmail(const Value: String); begin FResponsavelEmail := Copy(Value,1,40); end; procedure TEmpresa.setFResponsavelNome(const Value: String); begin FResponsavelNome := Copy(Value,1,40); end; procedure TEmpresa.setFResponsavelTelefone(const Value: String); begin FResponsavelTelefone := Copy(Value,1,40); end; function TEmpresa.Update:Boolean; var qLocal: TFDQuery; begin try qLocal := TFDQuery.Create(nil); qLocal.ConnectionName :='X'; qLocal.Close; qLocal.SQL.Clear; qLocal.SQL.Add('UPDATE EMPRESA_EMP '); qLocal.SQL.Add(' SET EMP_NOME_FANTASIA = :EMP_NOME_FANTASIA, '); qLocal.SQL.Add(' EMP_RAZAOSOCIAL = :EMP_RAZAOSOCIAL, '); qLocal.SQL.Add(' EMP_INICIOATIVIDADES = :EMP_INICIOATIVIDADES, '); qLocal.SQL.Add(' EMP_BLOQUEADA = :EMP_BLOQUEADA, '); qLocal.SQL.Add(' EMP_PESSOAJF = :EMP_PESSOAJF, '); qLocal.SQL.Add(' EMP_INSCRICAO_ESTADUAL = :EMP_INSCRICAO_ESTADUAL, '); qLocal.SQL.Add(' EMP_INSCRICAO_MUNICIPAL = :EMP_INSCRICAO_MUNICIPAL, '); qLocal.SQL.Add(' EMP_SUFRAMA = :EMP_SUFRAMA, '); qLocal.SQL.Add(' EMP_CNAE = :EMP_CNAE, '); qLocal.SQL.Add(' EMP_CNPJ = :EMP_CNPJ, '); qLocal.SQL.Add(' EMP_NIRE = :EMP_NIRE, '); qLocal.SQL.Add(' EMP_INSCRICAO_ESTADUAL_ST = :EMP_INSCRICAO_ESTADUAL_ST, '); qLocal.SQL.Add(' EMP_ENDERECO = :EMP_ENDERECO, '); qLocal.SQL.Add(' EMP_CEP = :EMP_CEP, '); qLocal.SQL.Add(' EMP_ENDERECO_NUMERO = :EMP_ENDERECO_NUMERO, '); qLocal.SQL.Add(' EMP_BAIRRO = :EMP_BAIRRO, '); qLocal.SQL.Add(' EMP_ENDERECO_COMPLEMENTO = :EMP_ENDERECO_COMPLEMENTO, '); qLocal.SQL.Add(' EMP_CIDADE = :EMP_CIDADE, '); qLocal.SQL.Add(' EMP_IBGECIDADE = :EMP_IBGECIDADE, '); qLocal.SQL.Add(' EMP_UF = :EMP_UF, '); qLocal.SQL.Add(' EMP_IBGEUF = :EMP_IBGEUF, '); qLocal.SQL.Add(' EMP_FONES = :EMP_FONES, '); qLocal.SQL.Add(' EMP_CELULAR = :EMP_CELULAR, '); qLocal.SQL.Add(' EMP_WHATSAPP = :EMP_WHATSAPP, '); qLocal.SQL.Add(' EMP_EMAIL = :EMP_EMAIL, '); qLocal.SQL.Add(' EMP_CONTRIBUINTE_IPI = :EMP_CONTRIBUINTE_IPI, '); qLocal.SQL.Add(' EMP_RESPONSAVEL_NOME = :EMP_RESPONSAVEL_NOME, '); qLocal.SQL.Add(' EMP_RESPONSAVEL_TELEFONE = :EMP_RESPONSAVEL_TELEFONE, '); qLocal.SQL.Add(' EMP_RESPONSAVEL_CELULAR = :EMP_RESPONSAVEL_CELULAR, '); qLocal.SQL.Add(' EMP_RESPONSAVEL_EMAIL = :EMP_RESPONSAVEL_EMAIL, '); qLocal.SQL.Add(' EMP_CONTADOR_EMPRESA = :EMP_CONTADOR_EMPRESA, '); qLocal.SQL.Add(' EMP_CONTADOR_RESPONSAVEL = :EMP_CONTADOR_RESPONSAVEL, '); qLocal.SQL.Add(' EMP_CONTADOR_CNPJ = :EMP_CONTADOR_CNPJ, '); qLocal.SQL.Add(' EMP_CONTADOR_CPF = :EMP_CONTADOR_CPF, '); qLocal.SQL.Add(' EMP_CONTADOR_TEL1 = :EMP_CONTADOR_TEL1, '); qLocal.SQL.Add(' EMP_CONTADOR_TEL2 = :EMP_CONTADOR_TEL2, '); qLocal.SQL.Add(' EMP_CONTADOR_CRC = :EMP_CONTADOR_CRC, '); qLocal.SQL.Add(' EMP_CONTADOR_CEL1 = :EMP_CONTADOR_CEL1, '); qLocal.SQL.Add(' EMP_CONTADOR_CEL2 = :EMP_CONTADOR_CEL2, '); qLocal.SQL.Add(' EMP_CONTADOR_EMAIL = :EMP_CONTADOR_EMAIL, '); qLocal.SQL.Add(' EMP_PIS_CUMULATIVO = :EMP_PIS_CUMULATIVO, '); qLocal.SQL.Add(' EMP_PIS_ALIQUOTA = :EMP_PIS_ALIQUOTA, '); qLocal.SQL.Add(' EMP_DT = :EMP_DT, '); qLocal.SQL.Add(' EMP_CODIGO_UNISYSTEM = :EMP_CODIGO_UNISYSTEM '); //passo11 Preencher_Parametros_Empresa(qLocal); qLocal.ExecSql; qLocal.Free; Log('Alterou empresa '+ Empresa.FNomeFantasia); Result := True; except qLocal.Free; ShowMessage('Erro ao alterar Empresa'); LogErros('Erro ao alterar Empresa'); end; end; function TEmpresa.getFContadorEmpresa: String; begin Result := self.FContadorEmpresa; end; procedure TEmpresa.setFContadorEmpresa(const Value: String); begin FContadorEmpresa := Copy(Value,1,40); end; function TEmpresa.getFContadorResponsavel: String; begin result := FContadorResponsavel; end; procedure TEmpresa.setFContadorResponsavel(const Value: String); begin FContadorEmpresa := Copy(Value,1,40); end; function TEmpresa.getFContadorCNPJ: String; begin Result := self.FContadorCNPJ; end; procedure TEmpresa.setFContadorCNPJ(const Value: String); begin FContadorCNPJ := Copy(Value,1,14); end; function TEmpresa.getFContadorCPF: String; begin Result := self.FContadorCPF; end; procedure TEmpresa.setFContadorCPF(const Value: String); begin FContadorCPF := Copy(Value,1,11); end; function TEmpresa.getFContadorTelefone1: String; begin Result := self.FContadorTelefone1; end; procedure TEmpresa.setFContadorTelefone1(const Value: String); begin FContadorTelefone1 := Copy(Value,1,40); end; function TEmpresa.getFContadorTelefone2: String; begin Result := self.FContadorTelefone2; end; procedure TEmpresa.setFContadorTelefone2(const Value: String); begin FContadorTelefone2 := Copy(Value,1,40); end; function TEmpresa.getFContadorCRC: String; begin Result := self.FContadorCRC; end; procedure TEmpresa.setFContadorCRC(const Value: String); begin FContadorCRC := Copy(Value,1,20); end; function TEmpresa.getFContadorCelular1: String; begin Result := self.FContadorCelular1; end; procedure TEmpresa.setFContadorCelular1(const Value: String); begin FContadorCelular1 := Copy(Value,1,40); end; function TEmpresa.getFContadorCelular2: String; begin Result := self.FContadorCelular2; end; procedure TEmpresa.setFContadorCelular2(const Value: String); begin FContadorCelular1 := Copy(Value,1,40); end; function TEmpresa.getFContadorEmail: String; begin Result := self.FContadorEmail; end; procedure TEmpresa.setFContadorEmail(const Value: String); begin FContadorEmail := Copy(Value,1,40); end; end.
unit UPubFunLib; interface uses ComObj, ActiveX, SysUtils, Forms, Windows; function CreateGUIDStr: string; function ShowConfirm(Text, Caption: string): Boolean; implementation function CreateGUIDStr: string; var lGuid: TGUID; begin CoCreateGUID(lGuid); Result := GUIDToString(lGuid); Result := StringReplace(Result, '-', '', [rfReplaceAll]); Result := Copy(Result, 2, Length(Result) - 2); end; function ShowConfirm(Text, Caption: string): Boolean; begin Result := Application.MessageBox(PWideChar(Text), PWideChar(Caption), MB_ICONQUESTION + MB_OKCANCEL) = IDOK; end; end.
PROGRAM Hello; var text: string; BEGIN (* Hello *) text := 'Hello World'; Writeln(text) END. (* Hello *)
unit ufrmSysUserAccessRight; interface {$I ThsERP.inc} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, StrUtils, Vcl.AppEvnts, Vcl.Menus, Vcl.Samples.Spin, Ths.Erp.Helper.Edit, Ths.Erp.Helper.Memo, Ths.Erp.Helper.ComboBox, ufrmBase, ufrmBaseInputDB; type TfrmSysUserAccessRight = class(TfrmBaseInputDB) cbbSourceName: TComboBox; cbbUserName: TComboBox; cbxIsAddRecord: TCheckBox; cbxIsDelete: TCheckBox; cbxIsRead: TCheckBox; cbxIsSpecial: TCheckBox; cbxIsUpdate: TCheckBox; lblIsAddRecord: TLabel; lblIsDelete: TLabel; lblIsRead: TLabel; lblIsSpecial: TLabel; lblIsUpdate: TLabel; lblSourceName: TLabel; lblUserName: TLabel; procedure FormCreate(Sender: TObject);override; procedure Repaint(); override; procedure RefreshData();override; private public protected published procedure FormShow(Sender: TObject); override; procedure btnAcceptClick(Sender: TObject); override; procedure FormDestroy(Sender: TObject); override; end; implementation uses Ths.Erp.Database.Table.SysUserAccessRight, Ths.Erp.Database.Table.SysUser, Ths.Erp.Database.Table.SysPermissionSource; {$R *.dfm} procedure TfrmSysUserAccessRight.btnAcceptClick(Sender: TObject); begin if (FormMode = ifmNewRecord) or (FormMode = ifmCopyNewRecord) or (FormMode = ifmUpdate) then begin if (ValidateInput) then begin TSysUserAccessRight(Table).UserName.Value := cbbUserName.Text; //TSysUserAccessRight(Table).PermissionCode.Value := cbbSourceName.Text; TSysUserAccessRight(Table).PermissionCode.Value := TSysPermissionSource(cbbSourceName.Items.Objects[cbbSourceName.ItemIndex]).SourceCode.Value; TSysUserAccessRight(Table).IsRead.Value := cbxIsRead.Checked; TSysUserAccessRight(Table).IsAddRecord.Value := cbxIsAddRecord.Checked; TSysUserAccessRight(Table).IsUpdate.Value := cbxIsUpdate.Checked; TSysUserAccessRight(Table).IsDelete.Value := cbxIsDelete.Checked; TSysUserAccessRight(Table).IsSpecial.Value := cbxIsSpecial.Checked; inherited; end; end else inherited; end; procedure TfrmSysUserAccessRight.FormCreate(Sender: TObject); var vUser: TSysUser; vPermissionSource: TSysPermissionSource; n1: Integer; begin TSysUserAccessRight(Table).UserName.SetControlProperty(Table.TableName, cbbUserName); TSysUserAccessRight(Table).PermissionCode.SetControlProperty(Table.TableName, cbbSourceName); inherited; cbbUserName.Clear; vUser := TSysUser.Create(Table.Database); try vUser.SelectToList('', False, False); for n1 := 0 to vUser.List.Count-1 do cbbUserName.Items.Add(TSysUser(vUser.List[n1]).UserName.Value); finally vUser.Free; end; cbbSourceName.Clear; vPermissionSource := TSysPermissionSource.Create(Table.Database); try vPermissionSource.SelectToList('', False, False); for n1 := 0 to vPermissionSource.List.Count-1 do cbbSourceName.Items.AddObject(TSysPermissionSource(vPermissionSource.List[n1]).SourceName.Value, TSysPermissionSource(vPermissionSource.List[n1]).Clone); finally vPermissionSource.Free; end; end; procedure TfrmSysUserAccessRight.FormDestroy(Sender: TObject); var n1: Integer; begin for n1 := cbbSourceName.Items.Count-1 downto 0 do if Assigned(cbbSourceName.Items.Objects[n1]) then cbbSourceName.Items.Objects[n1].Free; inherited; end; procedure TfrmSysUserAccessRight.FormShow(Sender: TObject); begin inherited; // end; procedure TfrmSysUserAccessRight.Repaint(); begin inherited; // end; procedure TfrmSysUserAccessRight.RefreshData(); var n1: Integer; begin //control içeriğini table class ile doldur cbbUserName.ItemIndex := cbbUserName.Items.IndexOf( TSysUserAccessRight(Table).UserName.Value ); for n1 := 0 to cbbSourceName.Items.Count-1 do if TSysPermissionSource(cbbSourceName.Items.Objects[n1]).SourceCode.Value = TSysUserAccessRight(Table).PermissionCode.Value then cbbSourceName.ItemIndex := n1; cbxIsRead.Checked := TSysUserAccessRight(Table).IsRead.Value; cbxIsAddRecord.Checked := TSysUserAccessRight(Table).IsAddRecord.Value; cbxIsUpdate.Checked := TSysUserAccessRight(Table).IsUpdate.Value; cbxIsDelete.Checked := TSysUserAccessRight(Table).IsDelete.Value; cbxIsSpecial.Checked := TSysUserAccessRight(Table).IsSpecial.Value; end; end.