text
stringlengths
14
6.51M
{ ***************************************************************************** * * * This file is part of the iPhone Laz Extension * * * * See the file COPYING.modifiedLGPL.txt, included in this distribution, * * for details about the copyright. * * * * 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. * * * ***************************************************************************** } unit iPhoneExtStr; {$mode objfpc}{$H+} interface resourcestring striPhoneProject = 'iPhone Project'; strStartAtXcode = 'Update Xcode project'; strRunSimulator = 'Run iPhone Simulator'; strPrjOptTitle = 'iPhone specific'; strPrjOptIsiPhone = 'is iPhone application project'; strPrjOptSDKver = 'SDK version:'; strPrjOptCheckSDK = 'Check available SDKs'; strPtrOptAppID = 'Application ID'; strPtrOptAppIDHint = 'It''s recommended by Apple to use domain-structured identifier i.e. "com.mycompany.myApplication"'; strXcodeUpdated = 'Xcode project updated'; strWNoSDKSelected = 'Warning: SDK is not selected using %s'; strWNoSDK = 'Warning: No SDK available. Linking might fail.'; strOpenXibAtIB = 'Open "%s" at Interface Builder'; strOpenAtIB = 'Open at Interface Builder'; implementation end.
unit UOrderedBlockAccountList; interface uses Classes, UBlockAccount; type { TOrderedBlockAccountList } TOrderedBlockAccountList = Class private FMaxBlockNumber : Integer; FList : TList; Function SaveBlockAccount(Const blockAccount : TBlockAccount; UpdateIfFound : Boolean) : Integer; public Constructor Create; Destructor Destroy; Override; Procedure Clear; Function AddIfNotExists(Const blockAccount : TBlockAccount) : Integer; Function Add(Const blockAccount : TBlockAccount) : Integer; Function Count : Integer; Function Get(index : Integer) : TBlockAccount; // Skybuck: moved to here to make it accessable to TPCSafeBox Function Find(const block_number: Cardinal; out Index: Integer): Boolean; Function MaxBlockNumber : Integer; End; implementation uses UMemBlockAccount, SysUtils; { TOrderedBlockAccountList } Type TOrderedBlockAccount = Record block : Cardinal; memBlock : TMemBlockAccount; end; POrderedBlockAccount = ^TOrderedBlockAccount; function TOrderedBlockAccountList.Find(const block_number: Cardinal; out Index: Integer): Boolean; var L, H, I: Integer; C : Int64; begin Result := False; L := 0; H := FList.Count - 1; while L <= H do begin I := (L + H) shr 1; C := Int64(POrderedBlockAccount(FList[I])^.block) - Int64(block_number); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin Result := True; L := I; end; end; end; Index := L; end; function TOrderedBlockAccountList.SaveBlockAccount(const blockAccount: TBlockAccount; UpdateIfFound: Boolean): Integer; Var P : POrderedBlockAccount; begin If Not Find(blockAccount.blockchainInfo.block,Result) then begin New(P); P^.block:=blockAccount.blockchainInfo.block; FList.Insert(Result,P); ToTMemBlockAccount(blockAccount,P^.memBlock); If blockAccount.blockchainInfo.block>FMaxBlockNumber then FMaxBlockNumber:=blockAccount.blockchainInfo.block; end else if (UpdateIfFound) then begin P := FList[Result]; ToTMemBlockAccount(blockAccount,P^.memBlock); end; end; constructor TOrderedBlockAccountList.Create; begin FList := TList.Create; FMaxBlockNumber:=-1; end; destructor TOrderedBlockAccountList.Destroy; begin Clear; FreeAndNil(FList); inherited Destroy; end; procedure TOrderedBlockAccountList.Clear; var P : POrderedBlockAccount; i : Integer; begin For i:=0 to FList.Count-1 do begin P := FList[i]; Dispose(P); end; FList.Clear; FMaxBlockNumber:=-1; end; function TOrderedBlockAccountList.AddIfNotExists(const blockAccount: TBlockAccount): Integer; begin SaveBlockAccount(blockAccount,False); end; function TOrderedBlockAccountList.Add(const blockAccount: TBlockAccount): Integer; begin SaveBlockAccount(blockAccount,True); end; function TOrderedBlockAccountList.Count: Integer; begin Result := FList.Count; end; function TOrderedBlockAccountList.Get(index: Integer): TBlockAccount; begin ToTBlockAccount(POrderedBlockAccount(FList[index])^.memBlock,POrderedBlockAccount(FList[index])^.block,Result); end; function TOrderedBlockAccountList.MaxBlockNumber: Integer; begin Result := FMaxBlockNumber; end; end.
unit clMalote; interface uses clConexao; type TMalote = Class(TObject) private function getData: TDateTime; function getDestino: String; function getDocumento: String; function getExpedidor: String; function getOrigem: String; function getOs: Integer; function getRecebedor: String; function getRoteiro: Integer; procedure setData(const Value: TDateTime); procedure setDestino(const Value: String); procedure setDocumento(const Value: String); procedure setExpedidor(const Value: String); procedure setOrigem(const Value: String); procedure setOs(const Value: Integer); procedure setRecebedor(const Value: String); procedure setRoteiro(const Value: Integer); function getLacre: Integer; procedure setLacre(const Value: Integer); constructor Create; destructor Destroy; protected _os: Integer; _roteiro: Integer; _data: TDateTime; _origem: String; _expedidor: String; _destino: String; _recebedor: String; _documento: String; _lacre: Integer; _conexao: TConexao; public property Os: Integer read getOs write setOs; property Roteiro: Integer read getRoteiro write setRoteiro; property Data: TDateTime read getData write setData; property Origem: String read getOrigem write setOrigem; property Expedidor: String read getExpedidor write setExpedidor; property Destino: String read getDestino write setDestino; property Recebedor: String read getRecebedor write setRecebedor; property Documento: String read getDocumento write setDocumento; property Lacre: Integer read getLacre write setLacre; function Validar(): Boolean; function Delete(filtro: String): Boolean; function getObject(id, filtro: String): Boolean; function getObjects(): Boolean; function Insert(): Boolean; function Update(): Boolean; function getField(campo, coluna: String): String; procedure MaxOS; procedure MaxRoteiro; end; const TABLENAME = 'TBCONTROLEMALOTES'; implementation uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB; { TMalote } constructor TMalote.Create; begin _conexao := TConexao.Create; if (not _conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conex„o ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); end; end; destructor TMalote.Destroy; begin _conexao.Free; end; function TMalote.getData: TDateTime; begin Result := _data; end; function TMalote.getDestino: String; begin Result := _destino; end; function TMalote.getDocumento: String; begin Result := _documento; end; function TMalote.getExpedidor: String; begin Result := _expedidor; end; function TMalote.getOrigem: String; begin Result := _origem; end; function TMalote.getOs: Integer; begin Result := _os; end; function TMalote.getRecebedor: String; begin Result := _recebedor; end; function TMalote.getRoteiro: Integer; begin Result := _roteiro; end; function TMalote.getLacre: Integer; begin Result := _lacre; end; function TMalote.Validar(): Boolean; begin Result := False; if TUtil.Empty(DateToStr(Self.Data)) then begin MessageDlg('Informe a data da OS.', mtWarning, [mbOK], 0); Exit; end; if TUtil.Empty(Self.Origem) then begin MessageDlg('Informe a Origem.', mtWarning, [mbOK], 0); Exit; end; if TUtil.Empty(Self.Expedidor) then begin MessageDlg('Informe o Expedidor.', mtWarning, [mbOK], 0); Exit; end; if TUtil.Empty(Self.Destino) then begin MessageDlg('Informe o Destino.', mtWarning, [mbOK], 0); Exit; end; if TUtil.Empty(Self.Recebedor) then begin MessageDlg('Informe o Recebedor.', mtWarning, [mbOK], 0); Exit; end; Result := True; end; function TMalote.Delete(filtro: String): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Add('DELETE FROM ' + TABLENAME); if filtro = 'OS' then begin SQL.Add('WHERE NUM_OS = :OS'); ParamByName('OS').AsInteger := Self.Os; end else if filtro = 'LACRE' then begin SQL.Add('WHERE NUM_LACRE = :LACRE'); ParamByName('LACRE').AsInteger := Self.Lacre; end else if filtro = 'DATA' then begin SQL.Add('WHERE DAT_OS = :DATA'); ParamByName('DATA').AsDate := Self.Data; end else if filtro = 'ROTEIRO' then begin SQL.Add('WHERE NUM_ROTEIRO = :ROTEIRO'); SQL.Add('AND NUM_OS = :OS'); ParamByName('ROTEIRO').AsInteger := Self.Roteiro; ParamByName('OS').AsInteger := Self.Os; end; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TMalote.getObjects(): Boolean; begin try Result := False; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then begin Result := True; end else begin dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TMalote.getObject(id, filtro: String): Boolean; begin try Result := False; if TUtil.Empty(id) then Exit; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if filtro = 'OS' then begin SQL.Add('WHERE NUM_OS = :OS'); ParamByName('OS').AsInteger := StrToInt(id); end else if filtro = 'LACRE' then begin SQL.Add('WHERE NUM_LACRE = :LACRE'); ParamByName('LACRE').AsInteger := StrToInt(id); end else if filtro = 'DATA' then begin SQL.Add('WHERE DAT_OS = :DATA'); ParamByName('DATA').AsDate := StrToDate(id); end else if filtro = 'ROTEIRO' then begin SQL.Add('WHERE NUM_ROTEIRO = :ROTEIRO'); SQL.Add('AND NUM_OS = :OS'); ParamByName('ROTEIRO').AsInteger := StrToInt(id); ParamByName('OS').AsInteger := Self.Os; end; dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then begin Self.Os := dm.QryGetObject.FieldByName('NUM_OS').AsInteger; Self.Roteiro := dm.QryGetObject.FieldByName('NUM_ROTEIRO').AsInteger; Self.Data := dm.QryGetObject.FieldByName('DAT_OS').AsDateTime; Self.Origem := dm.QryGetObject.FieldByName('DES_ORIGEM').AsString; Self.Expedidor := dm.QryGetObject.FieldByName('NOM_EXPEDIDOR').AsString; Self.Destino := dm.QryGetObject.FieldByName('DES_DESTINO').AsString; Self.Recebedor := dm.QryGetObject.FieldByName('NOM_RECEBEDOR').AsString; Self.Documento := dm.QryGetObject.FieldByName('DES_DOCUMENTO').AsString; Self.Lacre := dm.QryGetObject.FieldByName('NUM_LACRE').AsInteger; Result := True; end else begin dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TMalote.Insert(): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + '(' + 'NUM_OS, ' + 'NUM_ROTEIRO, ' + 'DAT_OS, ' + 'DES_ORIGEM, ' + 'NOM_EXPEDIDOR, ' + 'DES_DESTINO, ' + 'NOM_RECEBEDOR, ' + 'DES_DOCUMENTO, ' + 'NUM_LACRE) ' + 'VALUES (' + ':OS, ' + ':ROTEIRO, ' + ':DATA, ' + ':ORIGEM, ' + ':EXPEDIDOR, ' + ':DESTINO, ' + ':RECEBEDOR, ' + ':DOCUMENTO, ' + ':LACRE)'; ParamByName('OS').AsInteger := Self.Os; ParamByName('ROTEIRO').AsInteger := Self.Roteiro; ParamByName('DATA').AsDate := Self.Data; ParamByName('ORIGEM').AsString := Self.Origem; ParamByName('EXPEDIDOR').AsString := Self.Expedidor; ParamByName('DESTINO').AsString := Self.Destino; ParamByName('RECEBEDOR').AsString := Self.Recebedor; ParamByName('DOCUMENTO').AsString := Self.Documento; ParamByName('LACRE').AsInteger := Self.Lacre; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TMalote.Update(): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DAT_OS = :DATA, ' + 'DES_ORIGEM = :ORIGEM, ' + 'NOM_EXPEDIDOR = :EXPEDIDOR, ' + 'DES_DESTINO = :DESTINO, ' + 'NOM_RECEBEDOR = :RECEBEDOR, ' + 'DES_DOCUMENTO = :DOCUMENTO, ' + 'NUM_LACRE = :LACRE ' + 'WHERE ' + 'NUM_OS = :OS AND NUM_ROTEIRO = :ROTEIRO'; ParamByName('OS').AsInteger := Self.Os; ParamByName('ROTEIRO').AsInteger := Self.Roteiro; ParamByName('DATA').AsDate := Self.Data; ParamByName('ORIGEM').AsString := Self.Origem; ParamByName('EXPEDIDOR').AsString := Self.Expedidor; ParamByName('DESTINO').AsString := Self.Destino; ParamByName('RECEBEDOR').AsString := Self.Recebedor; ParamByName('DOCUMENTO').AsString := Self.Documento; ParamByName('LACRE').AsInteger := Self.Lacre; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TMalote.getField(campo, coluna: String): String; begin try Result := ''; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT ' + campo + ' FROM ' + TABLENAME; if coluna = 'OS' then begin SQL.Add('WHERE NUM_OS = :OS'); ParamByName('OS').AsInteger := Self.Os; end else if coluna = 'LACRE' then begin SQL.Add('WHERE NUM_LACRE = :LACRE'); ParamByName('LACRE').AsInteger := Self.Lacre; end else if coluna = 'DATA' then begin SQL.Add('WHERE DAT_OS = :DATA'); ParamByName('DATA').AsDate := Self.Data; end else if coluna = 'ROTEIRO' then begin SQL.Add('WHERE NUM_ROTEIRO = :ROTEIRO'); SQL.Add('AND NUM_OS = :OS'); ParamByName('ROTEIRO').AsInteger := Self.Roteiro; ParamByName('OS').AsInteger := Self.Os; end; dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then Result := dm.QryGetObject.FieldByName(campo).AsString; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; procedure TMalote.MaxOS; begin try with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT MAX(NUM_OS) AS OS FROM ' + TABLENAME; dm.ZConn.PingServer; Open; if not(IsEmpty) then First; end; Self.Os := (dm.QryGetObject.FieldByName('OS').AsInteger) + 1; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; procedure TMalote.MaxRoteiro; begin try with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT MAX(NUM_ROTEIRO) AS ROTEIRO FROM ' + TABLENAME + ' WHERE NUM_OS = :OS'; ParamByName('OS').AsInteger := Self.Os; dm.ZConn.PingServer; Open; if not(IsEmpty) then First; end; Self.Roteiro := (dm.QryGetObject.FieldByName('ROTEIRO').AsInteger) + 1; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; procedure TMalote.setData(const Value: TDateTime); begin _data := Value; end; procedure TMalote.setDestino(const Value: String); begin _destino := Value; end; procedure TMalote.setDocumento(const Value: String); begin _documento := Value; end; procedure TMalote.setExpedidor(const Value: String); begin _expedidor := Value; end; procedure TMalote.setOrigem(const Value: String); begin _origem := Value; end; procedure TMalote.setOs(const Value: Integer); begin _os := Value; end; procedure TMalote.setRecebedor(const Value: String); begin _recebedor := Value; end; procedure TMalote.setRoteiro(const Value: Integer); begin _roteiro := Value; end; procedure TMalote.setLacre(const Value: Integer); begin _lacre := Value; end; end.
(* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * 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 TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StPropEd.pas 4.04 *} {*********************************************************} {* SysTools: Property Editors *} {*********************************************************} {$I StDefine.inc} {$IFDEF FPC} {$MODE Delphi} {$ENDIF} unit StPropEd; interface uses Dialogs, {$IFnDEF FPC} DesignIntf, DesignEditors, {$ELSE} PropEdits, Delphi.PropEd, {$ENDIF} Forms, Controls; type TStFileNameProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; procedure Edit; override; end; TStGenericFileNameProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; procedure Edit; override; end; implementation function TStFileNameProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog]; end; procedure TStFileNameProperty.Edit; var Dlg : TOpenDialog; begin Dlg := TOpenDialog.Create(Application); try Dlg.DefaultExt := '*.exe'; Dlg.Filter := 'Executable Files (*.exe)|*.exe' + '|Dynamic Link Libraries (*.dll)|*.dll'; Dlg.FilterIndex := 0; Dlg.Options := []; if GetName = 'ShortcutFileName' then Dlg.Options := [ofNoDereferenceLinks]; Dlg.FileName := Value; if Dlg.Execute then Value := Dlg.FileName; finally Dlg.Free; end; end; function TStGenericFileNameProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog]; end; procedure TStGenericFileNameProperty.Edit; var Dlg : TOpenDialog; begin Dlg := TOpenDialog.Create(Application); try Dlg.DefaultExt := '*.*'; Dlg.Filter := 'Text files (*.txt)|*.txt' + '|Pascal files (.pas)|*.pas' + '|C++ files (*.cpp)|*.cpp' + '|All files (*.*)|*.*'; Dlg.FilterIndex := 0; Dlg.Options := []; Dlg.FileName := Value; if Dlg.Execute then Value := Dlg.FileName; finally Dlg.Free; end; end; end.
unit xn.Items.view; interface uses System.Generics.Collections, System.Generics.Defaults, System.SysUtils, xn.Items; type IxnItemsView<T> = interface(IxnItems<T>) ['{8E9D2328-F658-4FF9-ABB5-8E669E81EA26}'] procedure Fill; end; TxnItemsView<T> = class(TInterfacedObject, IxnItemsView<T>) strict protected fList: IxnItems<T>; fIndex: TList<integer>; procedure Init(aList: IxnItems<T>); virtual; procedure Fill; virtual; public constructor Create(aList: IxnItems<T>); virtual; destructor Destroy; override; function GetEnumerator: TEnumerator<T>; virtual; function Count: integer; virtual; function ItemGet(aIndex: integer): T; virtual; property Items[aIndex: integer]: T read ItemGet; default; end; TxnItemsViewEnumerator<T> = class(TEnumerator<T>) strict protected fList: TxnItemsView<T>; protected fIndex: integer; function DoGetCurrent: T; override; function DoMoveNext: boolean; override; public constructor Create(aList: TxnItemsView<T>); end; // *************************************************************************** // *************************************************************************** TxnItemsViewReverse<T> = class(TxnItemsView<T>) protected procedure Fill; override; end; // *************************************************************************** // *************************************************************************** TxnItemsViewFirst<T> = class(TxnItemsView<T>) private fCount: integer; protected procedure Fill; override; public constructor Create(aList: IxnItems<T>; aCount: integer); reintroduce; end; TxnItemsViewLast<T> = class(TxnItemsViewFirst<T>) protected procedure Fill; override; end; // *************************************************************************** // *************************************************************************** IxnItemsViewFilter<T> = interface(IxnItemsView<T>) ['{FA4D7BC5-FEDB-45AC-A797-E248D9CFF0FE}'] function Accept(aItem: T): boolean; end; TxnItemsViewFilter<T> = class(TxnItemsView<T>, IxnItemsViewFilter<T>) private fAccept: TFunc<T, boolean>; protected procedure Fill; override; public constructor Create(aList: IxnItems<T>; aAccept: TFunc<T, boolean>); reintroduce; function Accept(aItem: T): boolean; virtual; end; // *************************************************************************** // *************************************************************************** IxnItemsViewIndex<T> = interface(IxnItemsView<T>) ['{A9771804-6676-4F30-AE94-BFDCCF98E8F5}'] function Seek1(aItem: T): integer; function Seek2(aItem: T): integer; end; TxnItemsViewIndex<T> = class(TxnItemsView<T>, IxnItemsViewIndex<T>) private fComparer: iComparer<T>; protected procedure Fill; override; public constructor Create(aList: IxnItems<T>; aComparison: TComparison<T>); reintroduce; function Seek1(aItem: T): integer; virtual; function Seek2(aItem: T): integer; virtual; end; implementation { TxnItemsViewEnumerator<T> } constructor TxnItemsViewEnumerator<T>.Create(aList: TxnItemsView<T>); begin inherited Create; fIndex := -1; fList := aList; end; function TxnItemsViewEnumerator<T>.DoGetCurrent: T; begin Result := fList.Items[fIndex] end; function TxnItemsViewEnumerator<T>.DoMoveNext: boolean; begin Result := fIndex < fList.Count - 1; if Result then Inc(fIndex); end; { TxnItemsView<T> } function TxnItemsView<T>.Count: integer; begin Result := fIndex.Count end; constructor TxnItemsView<T>.Create(aList: IxnItems<T>); begin Init(aList); Fill; end; destructor TxnItemsView<T>.Destroy; begin fIndex.Free; inherited; end; procedure TxnItemsView<T>.Fill; var i: integer; begin fIndex.Clear; for i := 0 to fList.Count - 1 do fIndex.Add(i); end; function TxnItemsView<T>.GetEnumerator: TEnumerator<T>; begin Result := TxnItemsViewEnumerator<T>.Create(Self); end; procedure TxnItemsView<T>.Init(aList: IxnItems<T>); begin fList := aList; fIndex := TList<integer>.Create; end; function TxnItemsView<T>.ItemGet(aIndex: integer): T; begin Result := fList[fIndex[aIndex]] end; { TxnItemsViewReverse<T> } procedure TxnItemsViewReverse<T>.Fill; var i: integer; begin fIndex.Clear; for i := fList.Count - 1 downto 0 do fIndex.Add(i) end; { TxnItemsViewFirst<T> } constructor TxnItemsViewFirst<T>.Create(aList: IxnItems<T>; aCount: integer); begin Init(aList); fCount := aCount; Fill; end; procedure TxnItemsViewFirst<T>.Fill; var i: integer; n: integer; begin if fList.Count < fCount then n := fList.Count else n := fCount; fIndex.Clear; for i := 0 to n - 1 do fIndex.Add(i) end; { TxnItemsViewLast<T> } procedure TxnItemsViewLast<T>.Fill; var i: integer; n: integer; begin if fList.Count - fCount < 0 then n := 0 else n := fList.Count - fCount; fIndex.Clear; for i := n to fList.Count - 1 do fIndex.Add(i) end; { TxnItemsViewFilter<T> } function TxnItemsViewFilter<T>.Accept(aItem: T): boolean; begin Result := fAccept(aItem) end; constructor TxnItemsViewFilter<T>.Create(aList: IxnItems<T>; aAccept: TFunc<T, boolean>); begin Init(aList); fAccept := aAccept; Fill; end; procedure TxnItemsViewFilter<T>.Fill; var i: integer; begin fIndex.Clear; for i := 0 to fList.Count - 1 do if Accept(fList[i]) then fIndex.Add(i) end; { TxnItemsViewIndex<T> } constructor TxnItemsViewIndex<T>.Create(aList: IxnItems<T>; aComparison: TComparison<T>); begin Init(aList); fComparer := TComparer<T>.Construct(aComparison); Fill; end; procedure TxnItemsViewIndex<T>.Fill; var s: integer; i: integer; begin fIndex.Clear; for i := 0 to fList.Count - 1 do begin s := Seek2(fList[i]); if s = -1 then fIndex.Add(i) else fIndex.Insert(s, i) end; end; function TxnItemsViewIndex<T>.Seek1(aItem: T): integer; var iStart: integer; iStop: integer; iPivot: integer; iComparer: integer; begin // returns the actual index of the item in the list // -1 if the item is not found iStart := 0; iStop := fIndex.Count - 1; if fIndex.Count = 0 then exit(-1); Result := -1; while iStart <= iStop do begin iPivot := (iStart + iStop) div 2; iComparer := fComparer.Compare(Items[iPivot], aItem); if iComparer = 0 then exit(iPivot) else if iComparer > 0 then iStop := iPivot - 1 else iStart := iPivot + 1; end; end; function TxnItemsViewIndex<T>.Seek2(aItem: T): integer; var iStart: integer; iStop: integer; oStart: integer; oStop: integer; iPivot: integer; iComparer: integer; iOther: integer; begin // returns the expected index of the item in the list // -1 if the item is after the last item of the list iStart := 0; oStart := 0; iStop := fIndex.Count - 1; oStop := fIndex.Count - 1; if fIndex.Count = 0 then exit(0); Result := -1; while iStart <= iStop do begin iPivot := (iStart + iStop) div 2; iComparer := fComparer.Compare(Items[iPivot], aItem); if iComparer = 0 then exit(iPivot) else if iComparer > 0 then begin if iPivot > oStart then begin iOther := fComparer.Compare(Items[iPivot - 1], aItem); if iOther = 0 then exit(iPivot - 1) else if iOther < 0 then exit(iPivot); end; iStop := iPivot - 1 end else begin if iPivot < oStop then begin iOther := fComparer.Compare(Items[iPivot + 1], aItem); if iOther = 0 then exit(iPivot + 1) else if iOther > 0 then exit(iPivot + 1); end; iStart := iPivot + 1; end; end; if fComparer.Compare(Items[oStart], aItem) > 0 then exit(oStart); end; end.
unit DW.Firebase.Default; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses DW.Firebase.InstanceId, DW.Firebase.Messaging; type TPlatformFirebaseInstanceId = class(TCustomPlatformFirebaseInstanceId) protected function GetToken: string; override; procedure HandleTokenRefresh; function Start: Boolean; override; end; TPlatformFirebaseMessaging = class(TCustomPlatformFirebaseMessaging) protected procedure Connect; override; procedure Disconnect; override; procedure RequestAuthorization; override; procedure SubscribeToTopic(const ATopicName: string); override; procedure UnsubscribeFromTopic(const ATopicName: string); override; end; implementation { TPlatformFirebaseInstanceId } function TPlatformFirebaseInstanceId.GetToken: string; begin Result := ''; end; procedure TPlatformFirebaseInstanceId.HandleTokenRefresh; begin // end; function TPlatformFirebaseInstanceId.Start: Boolean; begin Result := False; end; { TPlatformFirebaseMessaging } procedure TPlatformFirebaseMessaging.Connect; begin // end; procedure TPlatformFirebaseMessaging.Disconnect; begin // end; procedure TPlatformFirebaseMessaging.RequestAuthorization; begin // end; procedure TPlatformFirebaseMessaging.SubscribeToTopic(const ATopicName: string); begin // end; procedure TPlatformFirebaseMessaging.UnsubscribeFromTopic(const ATopicName: string); begin // end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} unit ElTreeMemoComboEdit; interface uses Windows, Messages, Controls, Forms, SysUtils, Classes, {$ifdef VCL_6_USED} Types, {$endif} ElTree, ElHeader, ElTools, ElStrUtils, ElMemoCombo ; type TElTreeInplaceMemoComboEdit = class(TElTreeInplaceEditor) private SaveWndProc: TWndMethod; SaveMemoWndProc: TWndMethod; procedure EditorWndProc(var Message : TMessage); procedure MemoWndProc(var Message : TMessage); protected FEditor: TElMemoCombo; procedure DoStartOperation; override; procedure DoStopOperation(Accepted : boolean); override; function GetVisible: Boolean; override; procedure TriggerAfterOperation(var Accepted : boolean; var DefaultConversion : boolean); override; procedure TriggerBeforeOperation(var DefaultConversion : boolean); override; procedure SetEditorParent; override; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; property Editor: TElMemoCombo read FEditor; end; implementation constructor TElTreeInplaceMemoComboEdit.Create(AOwner : TComponent); begin inherited; FEditor := TElMemoCombo.Create(Self); FEditor.Visible := false; SaveWndProc := FEditor.WindowProc; FEditor.WindowProc := Self.EditorWndProc; SaveMemoWndProc := FEditor.GetMemo.WindowProc; FEditor.GetMemo.WindowProc := MemoWndProc; FTypes := [sftText, sftMemo]; end; destructor TElTreeInplaceMemoComboEdit.Destroy; begin FEditor.GetMemo.WindowProc := SaveMemoWndProc; FEditor.WindowProc := SaveWndProc; FEditor.Free; FEditor := nil; inherited; end; procedure TElTreeInplaceMemoComboEdit.DoStartOperation; begin FEditor.Visible := true; FEditor.SetFocus; end; procedure TElTreeInplaceMemoComboEdit.DoStopOperation(Accepted : boolean); begin FEditor.Drop(false); FEditor.Visible := false; FEditor.Parent := nil; inherited; end; type THackElTree = class(TCustomElTree); procedure TElTreeInplaceMemoComboEdit.MemoWndProc(var Message : TMessage); var InputValid : boolean; begin if (Message.Msg = WM_CANCELMODE) or (Message.Msg = CM_CANCELMODE) or (Message.Msg = WM_KILLFOCUS) then if FEditor.HandleAllocated and (TWMKillFocus(Message).FocusedWnd <> FEditor.Handle) then if FEditing then begin if THackElTree(Tree).ExplorerEditMode then begin InputValid := true; TriggerValidateResult(InputValid); CompleteOperation(InputValid); end else CompleteOperation(false); end; if Message.Msg = WM_KEYDOWN then begin if TWMKey(Message).CharCode = VK_ESCAPE then begin CompleteOperation(false); TWMKey(Message).CharCode := 0; exit; end else if TWMKey(Message).CharCode = VK_RETURN then begin if KeyDataToShiftState(TWMKey(Message).KeyData) = [] then begin InputValid := true; FEditing := false; TriggerValidateResult(InputValid); FEditing := true; if InputValid then begin FEditor.Drop(false); CompleteOperation(true); TWMKey(Message).CharCode := 0; exit; end else Editor.SetFocus; TWMKey(Message).CharCode := 0; end else if KeyDataToShiftState(TWMKey(Message).KeyData) = [ssCtrl] then begin //PostMessage(FEditor.GetMemo.Handle, WM_CHAR, TMessage(Message).wParam, TMessage(Message).lParam); TWMKey(Message).CharCode := 0; end; end end; SaveMemoWndProc(Message); end; procedure TElTreeInplaceMemoComboEdit.EditorWndProc(var Message : TMessage); var InputValid : boolean; begin if Message.Msg = WM_KEYDOWN then begin if KeyDataToShiftState(TWMKey(Message).KeyData) = [] then begin if TWMKey(Message).CharCode = VK_RETURN then begin InputValid := true; TriggerValidateResult(InputValid); if InputValid then CompleteOperation(true) else Editor.SetFocus; TWMKey(Message).CharCode := 0; exit; end else if TWMKey(Message).CharCode = VK_ESCAPE then begin CompleteOperation(false); TWMKey(Message).CharCode := 0; exit; end; end; end else if Message.Msg = WM_KILLFOCUS then if FEditor.GetMemo.HandleAllocated and (TWMKillFocus(Message).FocusedWnd <> 0) and (TWMKillFocus(Message).FocusedWnd <> FEditor.Handle) and (TWMKillFocus(Message).FocusedWnd <> FEditor.GetMemo.Handle) then if FEditing then begin if THackElTree(Tree).ExplorerEditMode then begin InputValid := true; TriggerValidateResult(InputValid); CompleteOperation(InputValid); end else CompleteOperation(false); end; SaveWndProc(Message); end; function TElTreeInplaceMemoComboEdit.GetVisible: Boolean; begin Result := FEditor.Visible; end; procedure TElTreeInplaceMemoComboEdit.TriggerAfterOperation(var Accepted : boolean; var DefaultConversion : boolean); begin FEditor.OnExit := nil; inherited; if DefaultConversion then ValueAsText := FEditor.Text; end; procedure TElTreeInplaceMemoComboEdit.TriggerBeforeOperation(var DefaultConversion : boolean); begin inherited; if DefaultConversion then FEditor.Text := ValueAsText; FEditor.BoundsRect := FCellRect; end; procedure TElTreeInplaceMemoComboEdit.SetEditorParent; begin FEditor.Parent := FTree.View; end; end.
unit CompOptions; { Inno Setup Copyright (C) 1997-2010 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Compiler Options form $jrsoftware: issrc/Projects/CompOptions.pas,v 1.26 2010/10/30 04:29:19 jr Exp $ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, UIStateForm, StdCtrls, ExtCtrls, NewStaticText; type TOptionsForm = class(TUIStateForm) OKButton: TButton; CancelButton: TButton; GroupBox1: TGroupBox; BackupCheck: TCheckBox; GroupBox2: TGroupBox; AssocButton: TButton; StartupCheck: TCheckBox; WizardCheck: TCheckBox; GroupBox3: TGroupBox; ChangeFontButton: TButton; FontPanel: TPanel; Label1: TNewStaticText; FontDialog: TFontDialog; UseSynHighCheck: TCheckBox; FullPathCheck: TCheckBox; CursorPastEOLCheck: TCheckBox; UndoAfterSaveCheck: TCheckBox; TabWidthEdit: TEdit; Label2: TNewStaticText; PauseOnDebuggerExceptionsCheck: TCheckBox; RunAsDifferentUserCheck: TCheckBox; AutosaveCheck: TCheckBox; WordWrapCheck: TCheckBox; AutoIndentCheck: TCheckBox; IndentationGuidesCheck: TCheckBox; UseTabCharacterCheck: TCheckBox; AutoCompleteCheck: TCheckBox; UnderlineErrorsCheck: TCheckBox; GutterLineNumbersCheck: TCheckBox; procedure AssocButtonClick(Sender: TObject); procedure ChangeFontButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure TabWidthEditChange(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation uses CmnFunc, CmnFunc2, CompForm, CompFileAssoc; {$R *.DFM} procedure TOptionsForm.FormCreate(Sender: TObject); begin InitFormFont(Self); { On Windows Vista, you can only select administrator accounts in a "Run as" dialog. On Windows 2000/XP/2003, you can select any account. Earlier versions of Windows don't support "Run as" at all, so disable the check box there. } if Win32MajorVersion >= 6 then RunAsDifferentUserCheck.Caption := 'Always &launch Setup/Uninstall as administrator' else RunAsDifferentUserCheck.Caption := 'Always &launch Setup/Uninstall as different user'; RunAsDifferentUserCheck.Enabled := (Win32MajorVersion >= 5); end; procedure TOptionsForm.AssocButtonClick(Sender: TObject); begin RegisterISSFileAssociation; MsgBox('The .iss extension was successfully associated with:'#13#10 + NewParamStr(0), 'Associate', mbInformation, MB_OK); end; procedure TOptionsForm.ChangeFontButtonClick(Sender: TObject); begin FontDialog.Font.Assign(FontPanel.Font); if FontDialog.Execute then FontPanel.Font.Assign(FontDialog.Font); end; procedure TOptionsForm.TabWidthEditChange(Sender: TObject); begin OKButton.Enabled := StrToIntDef(TabWidthEdit.Text, 0) > 0; end; end.
{ *************************************************************************** Copyright (c) 2016-2017 Kike Pérez Unit : Quick.AppService Description : Allow run app as console or service Author : Kike Pérez Version : 1.0 Created : 14/09/2017 Modified : 01/12/2017 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.AppService; {$i QuickLib.inc} interface {$IFNDEF FPC} {$IFDEF DELPHI2010_UP} {$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])} {$WEAKLINKRTTI ON} {$ENDIF} {$ENDIF} uses {$IFDEF MSWINDOWS} Windows, {$ENDIF} SysUtils, {$IFNDEF FPC} WinSvc, {$ENDIF} Quick.Commons; const DEF_SERVICENAME = 'QuickAppService'; DEF_DISPLAYNAME = 'QuickAppService'; NUM_OF_SERVICES = 2; type TSvcStatus = (ssStopped = SERVICE_STOPPED, ssStopping = SERVICE_STOP_PENDING, ssStartPending = SERVICE_START_PENDING, ssRunning = SERVICE_RUNNING, ssPaused = SERVICE_PAUSED); TSvcStartType = (stAuto = SERVICE_AUTO_START, stManual = SERVICE_DEMAND_START, stDisabled = SERVICE_DISABLED); TSvcInitializeEvent = procedure of object; {$IFDEF FPC} TSvcAnonMethod = procedure of object; {$ELSE} TSvcAnonMethod = reference to procedure; {$ENDIF} TSvcRemoveEvent = procedure of object; TAppService = class private fSCMHandle : SC_HANDLE; fSvHandle : SC_HANDLE; fServiceName : string; fDisplayName : string; fLoadOrderGroup : string; fDependencies : string; fDesktopInteraction : Boolean; fUsername : string; fUserPass : string; fStartType : TSvcStartType; fFileName : string; fSilent : Boolean; fStatus : TSvcStatus; fCanInstallWithOtherName : Boolean; fOnInitialize : TSvcInitializeEvent; fOnStart : TSvcAnonMethod; fOnStop : TSvcAnonMethod; fOnExecute : TSvcAnonMethod; fAfterRemove : TSvcRemoveEvent; procedure ReportSvcStatus(dwCurrentState, dwWin32ExitCode, dwWaitHint: DWORD); procedure Execute; procedure Help; procedure DoStop; public constructor Create; destructor Destroy; override; property ServiceName : string read fServiceName write fServiceName; property DisplayName : string read fDisplayName write fDisplayName; property LoadOrderGroup : string read fLoadOrderGroup write fLoadOrderGroup; property Dependencies : string read fDependencies write fDependencies; property DesktopInteraction : Boolean read fDesktopInteraction write fDesktopInteraction; property UserName : string read fUserName write fUserName; property UserPass : string read fUserPass write fUserPass; property StartType : TSvcStartType read fStartType write fStartType; property FileName : string read fFileName write fFileName; property Silent : Boolean read fSilent write fSilent; property CanInstallWithOtherName : Boolean read fCanInstallWithOtherName write fCanInstallWithOtherName; property Status : TSvcStatus read fStatus write fStatus; property OnStart : TSvcAnonMethod read fOnStart write fOnStart; property OnStop : TSvcAnonMethod read fOnStop write fOnStop; property OnExecute : TSvcAnonMethod read fOnExecute write fOnExecute; property OnInitialize : TSvcInitializeEvent read fOnInitialize write fOnInitialize; property AfterRemove : TSvcRemoveEvent read fAfterRemove write fAfterRemove; procedure Install; procedure Remove; procedure CheckParams; class function InstallParamsPresent : Boolean; class function ConsoleParamPresent : Boolean; class function IsRunningAsService : Boolean; class function IsRunningAsConsole : Boolean; end; var ServiceStatus : TServiceStatus; StatusHandle : SERVICE_STATUS_HANDLE; ServiceTable : array [0..NUM_OF_SERVICES] of TServiceTableEntry; ghSvcStopEvent: Cardinal; AppService : TAppService; implementation procedure ServiceCtrlHandler(Control: DWORD); stdcall; begin case Control of SERVICE_CONTROL_STOP: begin AppService.Status := TSvcStatus.ssStopping; SetEvent(ghSvcStopEvent); ServiceStatus.dwCurrentState := SERVICE_STOP_PENDING; SetServiceStatus(StatusHandle, ServiceStatus); end; SERVICE_CONTROL_PAUSE: begin AppService.Status := TSvcStatus.ssPaused; ServiceStatus.dwcurrentstate := SERVICE_PAUSED; SetServiceStatus(StatusHandle, ServiceStatus); end; SERVICE_CONTROL_CONTINUE: begin AppService.Status := TSvcStatus.ssRunning; ServiceStatus.dwCurrentState := SERVICE_RUNNING; SetServiceStatus(StatusHandle, ServiceStatus); end; SERVICE_CONTROL_INTERROGATE: SetServiceStatus(StatusHandle, ServiceStatus); SERVICE_CONTROL_SHUTDOWN: begin AppService.Status := TSvcStatus.ssStopped; AppService.DoStop; end; end; end; procedure RegisterService(dwArgc: DWORD; var lpszArgv: PChar); stdcall; begin ServiceStatus.dwServiceType := SERVICE_WIN32_OWN_PROCESS; ServiceStatus.dwCurrentState := SERVICE_START_PENDING; ServiceStatus.dwControlsAccepted := SERVICE_ACCEPT_STOP or SERVICE_ACCEPT_PAUSE_CONTINUE; ServiceStatus.dwServiceSpecificExitCode := 0; ServiceStatus.dwWin32ExitCode := 0; ServiceStatus.dwCheckPoint := 0; ServiceStatus.dwWaitHint := 0; StatusHandle := RegisterServiceCtrlHandler(PChar(AppService.ServiceName), @ServiceCtrlHandler); if StatusHandle <> 0 then begin AppService.ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0); try AppService.Status := TSvcStatus.ssRunning; AppService.Execute; finally AppService.ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0); end; end; end; constructor TAppService.Create; begin inherited; fServiceName := DEF_SERVICENAME; fDisplayName := DEF_DISPLAYNAME; fLoadOrderGroup := ''; fDependencies := ''; fDesktopInteraction := False; fUserName := ''; fUserPass := ''; fStartType := TSvcStartType.stAuto; fFileName := ParamStr(0); fSilent := True; fStatus := TSvcStatus.ssStopped; fCanInstallWithOtherName := False; fOnExecute := nil; IsQuickServiceApp := True; end; destructor TAppService.Destroy; begin fOnStart := nil; fOnStop := nil; fOnExecute := nil; if fSCMHandle <> 0 then CloseServiceHandle(fSCMHandle); if fSvHandle <> 0 then CloseServiceHandle(fSvHandle); inherited; end; procedure TAppService.ReportSvcStatus(dwCurrentState, dwWin32ExitCode, dwWaitHint: DWORD); begin //fill in the SERVICE_STATUS structure ServiceStatus.dwCurrentState := dwCurrentState; ServiceStatus.dwWin32ExitCode := dwWin32ExitCode; ServiceStatus.dwWaitHint := dwWaitHint; if dwCurrentState = SERVICE_START_PENDING then ServiceStatus.dwControlsAccepted := 0 else ServiceStatus.dwControlsAccepted := SERVICE_ACCEPT_STOP; case (dwCurrentState = SERVICE_RUNNING) or (dwCurrentState = SERVICE_STOPPED) of True: ServiceStatus.dwCheckPoint := 0; False: ServiceStatus.dwCheckPoint := 1; end; //report service status to SCM SetServiceStatus(StatusHandle,ServiceStatus); end; procedure TAppService.Execute; begin //we have to do something or service will stop ghSvcStopEvent := CreateEvent(nil,True,False,nil); if ghSvcStopEvent = 0 then begin ReportSvcStatus(SERVICE_STOPPED,NO_ERROR,0); Exit; end; if Assigned(fOnStart) then fOnStart; //report running status when initialization is complete ReportSvcStatus(SERVICE_RUNNING,NO_ERROR,0); //perform work until service stops while True do begin //external callback process if Assigned(fOnExecute) then fOnExecute; //check whether to stop the service. WaitForSingleObject(ghSvcStopEvent,INFINITE); ReportSvcStatus(SERVICE_STOPPED,NO_ERROR,0); Exit; end; end; procedure TAppService.DoStop; begin if Assigned(fOnStop) then fOnStop; end; procedure TAppService.Remove; const cRemoveMsg = 'Service "%s" removed successfully!'; var SCManager: SC_HANDLE; Service: SC_HANDLE; begin SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS); if SCManager = 0 then Exit; try Service := OpenService(SCManager,PChar(fServiceName),SERVICE_ALL_ACCESS); ControlService(Service,SERVICE_CONTROL_STOP,ServiceStatus); DeleteService(Service); CloseServiceHandle(Service); if fSilent then Writeln(Format(cRemoveMsg,[fServiceName])) else MessageBox(0,cRemoveMsg,PChar(fServiceName),MB_ICONINFORMATION or MB_OK or MB_TASKMODAL or MB_TOPMOST); finally CloseServiceHandle(SCManager); if Assigned(fAfterRemove) then fAfterRemove; end; end; procedure TAppService.Install; const cInstallMsg = 'Service "%s" installed successfully!'; cSCMError = 'Error trying to open SC Manager (you need admin permissions)'; var servicetype : Cardinal; starttype : Cardinal; svcloadgroup : PChar; svcdependencies : PChar; svcusername : PChar; svcuserpass : PChar; begin fSCMHandle := OpenSCManager(nil,nil,SC_MANAGER_ALL_ACCESS); if fSCMHandle = 0 then begin if fSilent then Writeln(cSCMError) else MessageBox(0,cSCMError,PChar(fServiceName),MB_ICONERROR or MB_OK or MB_TASKMODAL or MB_TOPMOST); Exit; end; //service interacts with desktop if fDesktopInteraction then servicetype := SERVICE_WIN32_OWN_PROCESS and SERVICE_INTERACTIVE_PROCESS else servicetype := SERVICE_WIN32_OWN_PROCESS; //service load order if fLoadOrderGroup.IsEmpty then svcloadgroup := nil else svcloadgroup := PChar(fLoadOrderGroup); //service dependencies if fDependencies.IsEmpty then svcdependencies := nil else svcdependencies := PChar(fDependencies); //service user name if fUserName.IsEmpty then svcusername := nil else svcusername := PChar(fUserName); //service user password if fUserPass.IsEmpty then svcuserpass := nil else svcuserpass := PChar(fUserPass); fSvHandle := CreateService(fSCMHandle, PChar(fServiceName), PChar(fDisplayName), SERVICE_ALL_ACCESS, servicetype, Cardinal(fStartType), SERVICE_ERROR_NORMAL, PChar(fFileName), svcloadgroup, nil, svcdependencies, svcusername, //user svcuserpass); //password if fSvHandle <> 0 then begin if fSilent then Writeln(Format(cInstallMsg,[fServiceName])) else MessageBox(0,cInstallMsg,PChar(fServiceName),MB_ICONINFORMATION or MB_OK or MB_TASKMODAL or MB_TOPMOST); end; end; procedure TAppService.Help; begin Writeln('HELP:'); if fCanInstallWithOtherName then begin Writeln(Format('%s [/instance:<Service name>] [/console] [/install] [/remove] [/h] [/help]',[ExtractFileName(ParamStr(0))])); WriteLn(' [/instance:<service name>]'+#9+'Install service with a custom name'); end else Writeln(Format('%s [/console] [/install] [/remove] [/h] [/help]',[ExtractFileName(ParamStr(0))])); WriteLn(' [/console]'+#9#9#9+'Force run as a console application (when runned from another service)'); WriteLn(' [/install]'+#9#9#9+'Install as a service'); WriteLn(' [/remove]'+#9#9#9+'Remove service'); WriteLn(' [/h /help]'+#9#9#9+'This help'); end; procedure TAppService.CheckParams; var svcname : string; begin if ParamCount > 0 then begin if (ParamFindSwitch('h')) or (ParamFindSwitch('help')) then Self.Help else if ParamFindSwitch('install') then begin if (fCanInstallWithOtherName) and (ParamGetSwitch('instance',svcname)) then begin fServiceName := svcname; fDisplayName := svcname; end; Self.Install; end else if ParamFindSwitch('remove') then begin if (fCanInstallWithOtherName) and (ParamGetSwitch('instance',svcname)) then begin fServiceName := svcname; fDisplayName := svcname; end; Self.Remove; end else if ParamFindSwitch('console') then begin Writeln('Forced console mode'); end else Writeln('Unknow parameter specified!'); end else begin //initialize as a service if Assigned(fOnInitialize) then fOnInitialize; ServiceTable[0].lpServiceName := PChar(fServiceName); ServiceTable[0].lpServiceProc := @RegisterService; ServiceTable[1].lpServiceName := nil; ServiceTable[1].lpServiceProc := nil; {$IFDEF FPC} StartServiceCtrlDispatcher(@ServiceTable[0]); {$ELSE} StartServiceCtrlDispatcher(ServiceTable[0]); {$ENDIF} end; end; class function TAppService.ConsoleParamPresent : Boolean; begin Result := ParamFindSwitch('console'); end; class function TAppService.InstallParamsPresent : Boolean; begin Result := (ParamFindSwitch('install') or ParamFindSwitch('remove') or ParamFindSwitch('help') or ParamFindSwitch('h')); end; class function TAppService.IsRunningAsService : Boolean; begin Result := (IsService and not ConsoleParamPresent) or InstallParamsPresent; end; class function TAppService.IsRunningAsConsole : Boolean; begin Result := (not IsService) or (ConsoleParamPresent); end; initialization AppService := TAppService.Create; finalization AppService.Free; end.
unit Sounds; interface uses Classes, SoundMixer, SoundTypes, TimerTypes, ShutDown; type PTargetInfo = ^TTargetInfo; TTargetInfo = record hearable : boolean; Target : ISoundTarget; end; type TSoundManager = class(TInterfacedObject, IShutDownTarget, ITickeable, ISoundManager) private fTargets : TList; fSoundMixer : TSoundMixer; function GetTargetInfo(const Target : ISoundTarget) : PTargetInfo; public constructor Create; destructor Destroy; override; private // IShutDownTarget procedure OnSuspend; procedure OnResume; function GetPriority : integer; procedure OnShutDown; private // ITickeable fLastUpdate : integer; fEnabled : boolean; fGlobalVolume : single; function Enabled : boolean; function Tick : integer; private // ISoundManager procedure AddTargets(const Targets : array of ISoundTarget); procedure RemoveTarget(const Target : ISoundTarget); procedure CheckRemoveTargets(Check : TSoundTargetCheck; info : array of const); procedure PlayTarget(const Target : ISoundTarget); procedure UpdateTarget(const Target : ISoundTarget); procedure StopTarget(const Target : ISoundTarget); procedure StartCaching; procedure StopCaching; procedure Clear; procedure PlayCachedSounds; procedure Reset; procedure SetGlobalVolume(volume : single); end; implementation uses Windows, TimerTicker; const cSoundsTimerInterval = 120; constructor TSoundManager.Create; begin inherited; fTargets := TList.Create; fSoundMixer := TSoundMixer.Create; AttachTickeable(Self); ShutDown.AttachTarget(Self); fEnabled := true; fGlobalVolume := 1; end; destructor TSoundManager.Destroy; begin ShutDown.DetachTarget(Self); DetachTickeable(Self); Clear; fSoundMixer.Free; fTargets.Free; inherited; end; procedure TSoundManager.OnSuspend; begin { fEnabled := false; fSoundMixer.PauseSounds; } end; procedure TSoundManager.OnResume; begin { fEnabled := fTargets.Count > 0; fSoundMixer.ResumeSounds; } end; function TSoundManager.GetPriority : integer; begin Result := 100; end; procedure TSoundManager.OnShutDown; begin fEnabled := false; //fSoundMixer.StopAllSounds end; function TSoundManager.Enabled : boolean; begin Result := fEnabled; end; function TSoundManager.Tick; procedure PlaySoundsTick; var i : integer; Target : ISoundTarget; sndinfo : TSoundInfo; //sndname : string; begin for i := 0 to pred(fTargets.Count) do begin Target := PTargetInfo(fTargets[i]).Target; { sndname := Target.GetSoundName; if pos('dogs.wav', sndname) <> 0 then } if Target.ShouldPlayNow then begin sndinfo.name := Target.GetSoundName; sndinfo.kind := Target.GetSoundKind; sndinfo.priority := Target.GetPriority; sndinfo.looped := Target.IsLooped; sndinfo.volume := Target.GetVolume*fGlobalVolume; sndinfo.pan := Target.GetPan; fSoundMixer.AddSounds(sndinfo); end; end; fSoundMixer.PlaySounds; end; var CurrentTicks : integer; ElapsedTicks : integer; FrameDelay : integer; begin CurrentTicks := GetTickCount; ElapsedTicks := CurrentTicks - fLastUpdate; FrameDelay := cSoundsTimerInterval; if ElapsedTicks >= FrameDelay then begin PlaySoundsTick; fLastUpdate := CurrentTicks; Result := FrameDelay; end else Result := FrameDelay - ElapsedTicks; end; procedure TSoundManager.AddTargets(const Targets : array of ISoundTarget); var i : integer; TargetInfo : PTargetInfo; begin for i := low(Targets) to high(Targets) do begin TargetInfo := GetTargetInfo(Targets[i]); if TargetInfo = nil then begin new(TargetInfo); TargetInfo.hearable := true; TargetInfo.Target := Targets[i]; fTargets.Add(TargetInfo); end else begin TargetInfo.hearable := true; with TargetInfo.Target do begin UpdateSoundParameters; fSoundMixer.ChangeSoundParams(GetSoundName, GetSoundKind, GetPan, GetVolume*fGlobalVolume); end; end; end; end; procedure TSoundManager.RemoveTarget(const Target : ISoundTarget); var TargetInfo : PTargetInfo; begin TargetInfo := GetTargetInfo(Target); if TargetInfo <> nil then begin StopTarget(Target); fTargets.Remove(TargetInfo); dispose(TargetInfo); end; end; procedure TSoundManager.CheckRemoveTargets(Check : TSoundTargetCheck; info : array of const); var i : integer; aux : PTargetInfo; begin for i := 0 to pred(fTargets.Count) do begin aux := PTargetInfo(fTargets[i]); if (aux <> nil) and Check(aux.Target, info) then begin fTargets[i] := nil; dispose(aux); end; end; fTargets.Pack; end; procedure TSoundManager.UpdateTarget(const Target : ISoundTarget); begin with Target do fSoundMixer.ChangeSoundParams(GetSoundName, GetSoundKind, GetPan, GetVolume*fGlobalVolume); end; procedure TSoundManager.StopTarget(const Target : ISoundTarget); begin with Target do fSoundMixer.StopPlayingSound(GetSoundName, GetSoundKind); end; procedure TSoundManager.PlayTarget(const Target :ISoundTarget); var sndinfo : TSoundInfo; begin sndinfo.name := Target.GetSoundName; sndinfo.kind := Target.GetSoundKind; sndinfo.priority := Target.GetPriority; sndinfo.looped := Target.IsLooped; sndinfo.volume := Target.GetVolume*fGlobalVolume; sndinfo.pan := Target.GetPan; fSoundMixer.AddSounds(sndinfo); end; procedure TSoundManager.StartCaching; var i : integer; TargetInfo : PTargetInfo; begin for i := 0 to pred(fTargets.Count) do begin TargetInfo := PTargetInfo(fTargets[i]); if TargetInfo.Target.IsCacheable then TargetInfo.hearable := false; end; end; procedure TSoundManager.StopCaching; var i : integer; TargetInfo : PTargetInfo; begin for i := 0 to pred(fTargets.Count) do begin TargetInfo := PTargetInfo(fTargets[i]); if not TargetInfo.hearable then begin with TargetInfo.Target do fSoundMixer.StopPlayingSound(GetSoundName, GetSoundKind); dispose(TargetInfo); fTargets[i] := nil; end; end; fTargets.Pack; end; procedure TSoundManager.Clear; var i : integer; TargetInfo : PTargetInfo; begin for i := 0 to pred(fTargets.Count) do begin TargetInfo := PTargetInfo(fTargets[i]); if TargetInfo <> nil then begin with TargetInfo.Target do fSoundMixer.StopPlayingSound(GetSoundName, GetSoundKind); dispose(TargetInfo); fTargets[i] := nil; end; end; fTargets.Pack; end; procedure TSoundManager.PlayCachedSounds; begin fSoundMixer.PlaySounds; end; procedure TSoundManager.Reset; begin Clear; fSoundMixer.ClearSoundCache; end; procedure TSoundManager.SetGlobalVolume(volume : single); var i : integer; SndTarget : ISoundTarget; begin fGlobalVolume := volume; for i := 0 to pred(fTargets.Count) do begin SndTarget := PTargetInfo(fTargets[i]).Target; with SndTarget do fSoundMixer.ChangeSoundParams(GetSoundName, GetSoundKind, GetPan, GetVolume*fGlobalVolume); end; end; function TSoundManager.GetTargetInfo(const Target : ISoundTarget) : PTargetInfo; var i : integer; TargetInfo : PTargetInfo; begin i := 0; TargetInfo := nil; while (i < fTargets.Count) and (TargetInfo = nil) do begin TargetInfo := PTargetInfo(fTargets[i]); if not TargetInfo.Target.IsEqualTo(Target) then begin TargetInfo := nil; inc(i); end; end; Result := TargetInfo; end; end.
unit ncsServerFilesDeliverer; // Модуль: "w:\common\components\rtl\Garant\cs\ncsServerFilesDeliverer.pas" // Стереотип: "SimpleClass" // Элемент модели: "TncsServerFilesDeliverer" MUID: (5810A0CC0383) {$Include w:\common\components\rtl\Garant\cs\CsDefine.inc} interface {$If NOT Defined(Nemesis)} uses l3IntfUses , l3ProtoObject , CsDataPipe , evdNcsTypes , Classes ; type PncsServerFilesDeliverer = ^TncsServerFilesDeliverer; TncsServerFilesDeliverer = class(Tl3ProtoObject) private f_Terminating: Boolean; f_Stopped: Boolean; f_DataPipe: TCsDataPipe; private function GetCommand: TncsDeliveryCommand; procedure SendStringList(aList: TStringList); procedure SendTasksList; procedure CorrectTargetFolder; procedure SetDeliveryResult; procedure CheckAlive; procedure SendFilesList; protected procedure FillTasksList(aList: TStringList); virtual; abstract; procedure DoCorrectTargetFolder(const aTaskID: AnsiString; const aNewFolder: AnsiString); virtual; abstract; procedure DoSetDeliveryResult(const aTaskID: AnsiString; aResult: TncsResultKind); virtual; abstract; procedure DoSendFilesList(const aTaskID: AnsiString; out theTargetFolder: AnsiString; aFilesList: TStringList; out theTotalSize: Int64); virtual; abstract; procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(aPipe: TCsDataPipe); reintroduce; procedure TerminateProcess; procedure ProcessCommands; protected property DataPipe: TCsDataPipe read f_DataPipe; end;//TncsServerFilesDeliverer {$IfEnd} // NOT Defined(Nemesis) implementation {$If NOT Defined(Nemesis)} uses l3ImplUses , SysUtils //#UC START# *5810A0CC0383impl_uses* //#UC END# *5810A0CC0383impl_uses* ; constructor TncsServerFilesDeliverer.Create(aPipe: TCsDataPipe); //#UC START# *5810A1E7027C_5810A0CC0383_var* //#UC END# *5810A1E7027C_5810A0CC0383_var* begin //#UC START# *5810A1E7027C_5810A0CC0383_impl* inherited Create; aPipe.SetRefTo(f_DataPipe); //#UC END# *5810A1E7027C_5810A0CC0383_impl* end;//TncsServerFilesDeliverer.Create function TncsServerFilesDeliverer.GetCommand: TncsDeliveryCommand; //#UC START# *5811A6F4011C_5810A0CC0383_var* //#UC END# *5811A6F4011C_5810A0CC0383_var* begin //#UC START# *5811A6F4011C_5810A0CC0383_impl* Result := TncsDeliveryCommand(DataPipe.ReadInteger); //#UC END# *5811A6F4011C_5810A0CC0383_impl* end;//TncsServerFilesDeliverer.GetCommand procedure TncsServerFilesDeliverer.SendStringList(aList: TStringList); //#UC START# *5811EF6E00F7_5810A0CC0383_var* var l_List: TStringList; l_IDX: Integer; //#UC END# *5811EF6E00F7_5810A0CC0383_var* begin //#UC START# *5811EF6E00F7_5810A0CC0383_impl* DataPipe.WriteInteger(aList.Count); for l_IDX := 0 to aList.Count - 1 do DataPipe.WriteLn(aList[l_IDX]); //#UC END# *5811EF6E00F7_5810A0CC0383_impl* end;//TncsServerFilesDeliverer.SendStringList procedure TncsServerFilesDeliverer.SendTasksList; //#UC START# *5811EF870053_5810A0CC0383_var* var l_List: TStringList; //#UC END# *5811EF870053_5810A0CC0383_var* begin //#UC START# *5811EF870053_5810A0CC0383_impl* l_List := TStringList.Create; try FillTasksList(l_List); SendStringList(l_List); DataPipe.WriteBufferFlush; finally FreeAndNil(l_List); end; //#UC END# *5811EF870053_5810A0CC0383_impl* end;//TncsServerFilesDeliverer.SendTasksList procedure TncsServerFilesDeliverer.CorrectTargetFolder; //#UC START# *58133D0403B9_5810A0CC0383_var* //#UC END# *58133D0403B9_5810A0CC0383_var* begin //#UC START# *58133D0403B9_5810A0CC0383_impl* DoCorrectTargetFolder(DataPipe.ReadLn, DataPipe.ReadLn); //#UC END# *58133D0403B9_5810A0CC0383_impl* end;//TncsServerFilesDeliverer.CorrectTargetFolder procedure TncsServerFilesDeliverer.SetDeliveryResult; //#UC START# *58133D11024D_5810A0CC0383_var* var l_TaskID: String; l_Result: Integer; //#UC END# *58133D11024D_5810A0CC0383_var* begin //#UC START# *58133D11024D_5810A0CC0383_impl* l_TaskID := DataPipe.ReadLn; l_Result := DataPipe.ReadInteger; DoSetDeliveryResult(l_TaskID, TncsResultKind(l_Result)); //#UC END# *58133D11024D_5810A0CC0383_impl* end;//TncsServerFilesDeliverer.SetDeliveryResult procedure TncsServerFilesDeliverer.CheckAlive; //#UC START# *58172EF8025B_5810A0CC0383_var* //#UC END# *58172EF8025B_5810A0CC0383_var* begin //#UC START# *58172EF8025B_5810A0CC0383_impl* if DataPipe.ReadBoolean then f_Terminating := True; DataPipe.WriteBoolean(f_Terminating); DataPipe.WriteBufferFlush; //#UC END# *58172EF8025B_5810A0CC0383_impl* end;//TncsServerFilesDeliverer.CheckAlive procedure TncsServerFilesDeliverer.SendFilesList; //#UC START# *581740D5014C_5810A0CC0383_var* var l_TargetFolder: String; l_FilesList: TStringList; l_TotalSize: Int64; //#UC END# *581740D5014C_5810A0CC0383_var* begin //#UC START# *581740D5014C_5810A0CC0383_impl* l_FilesList := TStringList.Create; try DoSendFilesList(DataPipe.ReadLn, l_TargetFolder, l_FilesList, l_TotalSize); DataPipe.WriteLn(l_TargetFolder); SendStringList(l_FilesList); DataPipe.WriteInt64(l_TotalSize); DataPipe.WriteBufferFlush; finally FreeAndNil(l_FilesList); end; //#UC END# *581740D5014C_5810A0CC0383_impl* end;//TncsServerFilesDeliverer.SendFilesList procedure TncsServerFilesDeliverer.TerminateProcess; //#UC START# *5811A63E0083_5810A0CC0383_var* //#UC END# *5811A63E0083_5810A0CC0383_var* begin //#UC START# *5811A63E0083_5810A0CC0383_impl* f_Terminating := True; //#UC END# *5811A63E0083_5810A0CC0383_impl* end;//TncsServerFilesDeliverer.TerminateProcess procedure TncsServerFilesDeliverer.ProcessCommands; //#UC START# *5811A656035A_5810A0CC0383_var* //#UC END# *5811A656035A_5810A0CC0383_var* begin //#UC START# *5811A656035A_5810A0CC0383_impl* while not f_Stopped do begin case GetCommand of ncs_dcGetTasksList: SendTasksList; ncs_dcGetFilesList: SendFilesList; // ncs_dcGetFileCRC // ncs_dcGetFile // ncs_dcSetProgress ncs_dcSetDeliveryResult: SetDeliveryResult; ncs_dcCorrectTargetFolder: CorrectTargetFolder; ncs_dcCheckAlive: CheckAlive; ncs_dcDoneProcess: f_Stopped := True; end; end; //#UC END# *5811A656035A_5810A0CC0383_impl* end;//TncsServerFilesDeliverer.ProcessCommands procedure TncsServerFilesDeliverer.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_5810A0CC0383_var* //#UC END# *479731C50290_5810A0CC0383_var* begin //#UC START# *479731C50290_5810A0CC0383_impl* FreeAndNil(f_DataPipe); inherited; //#UC END# *479731C50290_5810A0CC0383_impl* end;//TncsServerFilesDeliverer.Cleanup {$IfEnd} // NOT Defined(Nemesis) end.
unit API; interface uses System.SysUtils; Type TData = record ID: string[38]; DataType: String[80]; Name: String[80]; Author: String[80]; cost: String[80]; Other: String[80]; end; ptr = ^TElement; TElement = record next, prev: ptr; data: TData; end; TList = record Head, Tail: ptr; end; TDataArr = record DataArr: array of TData; end; var Info: TData; List: TList; procedure CreateNewEl(data: TData); procedure LoadList(var List: TList); procedure AddToEnd(var List: TList; var NewElement: ptr); procedure SaveList(const List: TList); procedure DeleteEl(data: TData); procedure ReplaceElData(data: TData); procedure FillDataArr(var FoundData: TDataArr; const Field: integer; const Value: string); function GenerateUUID: string; implementation procedure FillDataArr(var FoundData: TDataArr; const Field: integer; const Value: string); var List: TList; curr: ptr; i: integer; begin LoadList(List); curr := List.head; i := 0; while curr <> nil do begin case Field of 0: //Наименование begin if Value = curr.data.Name then begin Setlength(FoundData.DataArr, i + 1); FoundData.DataArr[high(FoundData.DataArr)].ID := curr.data.ID; FoundData.DataArr[high(FoundData.DataArr)].DataType := curr.data.DataType; FoundData.DataArr[high(FoundData.DataArr)].Name := curr.data.Name; FoundData.DataArr[high(FoundData.DataArr)].Author := curr.data.Author; FoundData.DataArr[high(FoundData.DataArr)].Cost := curr.data.Cost; FoundData.DataArr[high(FoundData.DataArr)].Other := curr.data.Other; inc(i); end; curr := curr.next; end; 1: //Автор begin if Value = curr.data.Author then begin Setlength(FoundData.DataArr, i + 1); FoundData.DataArr[high(FoundData.DataArr)].ID := curr.data.ID; FoundData.DataArr[high(FoundData.DataArr)].DataType := curr.data.DataType; FoundData.DataArr[high(FoundData.DataArr)].Name := curr.data.Name; FoundData.DataArr[high(FoundData.DataArr)].Author := curr.data.Author; FoundData.DataArr[high(FoundData.DataArr)].Cost := curr.data.Cost; FoundData.DataArr[high(FoundData.DataArr)].Other := curr.data.Other; inc(i); end; curr := curr.next; end; end; end; end; procedure CreateNewEl(data: TData); var List: TList; curr: ptr; begin LoadList(List); New(curr); curr.data := data; AddToEnd(List, curr); SaveList(List); end; procedure LoadList(var List: TList); var f: file of TData; tmp, curr: ptr; begin List.head := nil; List.tail := nil; AssignFile(f, 'Data.txt'); Reset(f); New(curr); if FileSize(f) <> 0 then begin Read(f, curr^.data); AddToEnd(List, curr); while not EOF(f) do begin tmp := curr; New(curr); Read(f, curr.data); AddToEnd(List, curr); tmp.next := curr; curr.prev := tmp; end; end; end; procedure AddToEnd(var List: TList; var NewElement: ptr); begin if List.head = nil then begin List.head := NewElement; List.tail := NewElement; NewElement.next := nil; NewElement.prev := nil; exit; end; NewElement.next := nil; NewElement.prev := List.tail; List.tail.next := NewElement; List.tail := NewElement; end; procedure SaveList(const List: TList); var f: file of TData; curr: ptr; begin AssignFile(f, 'Data.txt'); Rewrite(f); curr := List.head; while curr <> nil do begin Write(f, curr^.data); curr := curr^.next; end; end; procedure DeleteEl(data: TData); var List: TList; curr: ptr; begin LoadList(List); New(curr); curr := List.head; while curr <> nil do begin if curr.data.ID = data.ID then begin if (curr = List.head) and (curr.next = nil) then // удаление единственной записи begin Dispose(curr); List.head := nil; end else begin if curr = List.head then // удаление первой записи begin List.head := curr.next; curr.next.prev := nil; curr.next := nil; Dispose(curr); end else begin if curr.next = nil then // удаление последней записи begin curr.prev.next := nil; curr.prev := nil; Dispose(curr); end else begin // удаление любой другой записи curr.prev^.next := curr.next; curr.next^.prev := curr.prev; curr.prev := nil; curr.next := nil; Dispose(curr); end; end; end; end; curr := curr.next; end; SaveList(List); end; function GenerateUUID: string; var Uid: TGuid; Res: HResult; begin Res := CreateGuid(Uid); if Res = S_OK then begin Result := Guidtostring(Uid); end; end; procedure ReplaceElData(data: TData); Var List: TList; curr: Ptr; begin LoadList(List); New(curr); curr := List.head; while curr <> nil do begin if curr.data.ID = data.ID then begin curr.data := data; SaveList(List); exit; end; curr := curr.next; end; end; end.
unit Errores; interface resourcestring rsInformeNoEncontrado = 'Error! Informe no Encontrado'; rsErrorFechaVencida = 'FECHA de comprobante (%s) ' + #13 + 'corresponde a periodo CERRADO (%s)' + #13 + 'Debe Modificar la fecha. Imposible Continuar'; rsClienteSinPedido = 'Cliente NO tiene pedidos pendientes'; rsCompleteDatos = 'Falta completar datos de Registro'; rsNoEliminar = 'No se puede eliminar (%s) ya que Hay (%s) que la referencian'; rsDatosIncompletos = 'Por Favor, complete datos. (%s)'; rsValorNoCero = 'Valor Debe ser mayor a 0 (%s)'; rsCuitNoValido = 'CUIT es incorrecto. Revise por favor'; rsCantMaxArtSuperada = 'Cantidad Maxima (999) de Articulos superada'; rsTasaIVAIncorrecta = 'Error! Tasa de IVA Incorrecta!'; rsAsientoNoEncontrado = 'Asiento no encontrado para edicion'; rsCuentaNoEncontrada = 'Cuenta (%s) no encontrada.'; rsExisteValorReferencia = 'No se puede eliminar %s. Hay registros que requieren de el'; rsArticuloNoValido = 'Articulo %s no es valido'; rsCantidadCero = 'Cantidad no puede ser 0'; rsTasaIVA = 'No se pueden incluir en la misma factura articulos con distintas tasas de IVA'; rsPrecioNulo = 'Por favor, indique precio de venta'; rsErrorGrabacion = 'Error al grabar Factura'; rsClienteErroneo = 'Error. Cliente no es correcto'; rsFalsaCondicion = 'Error. Por favor, complete condicion de pago'; rsFaltaVendedor = 'Error. Por favor, complete vendedor'; rsFaltaLista = 'Error. Por favor, complete lista de precios'; rsFaltaDespacho = 'Error. Por favor, complete despacho'; rsPreciosConIVA = 'Los precios incluyen I.V.A.'; rsPreciosSinIVA = 'Los precios NO incluyen I.V.A.'; rsAplicacionVencida = 'Esta versión de demostración ha expirado' + #13 + 'Para continuar usándola debe registrarla' + #13 + #13 + 'Para registrarse por favor, dirijase a http://www.sisnob.com.ar' + #13 + 'o envie un mail a: admin@jesinor.com.ar'; implementation end.
unit slack; {$mode objfpc}{$H+} interface uses Classes, SysUtils, HTTPSend, ssl_openssl, fpjson, jsonparser; const SL_USERNAME = 'username'; SL_ICON_URL = 'icon_url'; SL_ICON_EMOJI = 'icon_emoji'; SL_TEXT = 'text'; SL_CHANNEL = 'channel'; SL_ATTACHMENTS = 'attachments'; // attachments SL_ATT_FALLBACK = 'fallback'; SL_ATT_COLOR = 'color'; SL_ATT_PRETEXT = 'pretext'; SL_ATT_AUTHOR_NAME = 'author_name'; SL_ATT_AUTHOR_LINK = 'author_link'; SL_ATT_AUTHOR_ICON = 'author_icon'; SL_ATT_TITLE = 'title'; SL_ATT_TITLE_LINK = 'title_link'; SL_ATT_TEXT = 'text'; SL_ATT_FIELDS = 'fields'; SL_ATT_IMAGE_URL = 'image_url'; SL_ATT_THUMB_URL = 'thumb_url'; SL_ATT_FOOTER = 'footer'; SL_ATT_FOOTER_ICON = 'footer_icon'; SL_ATT_TS = 'ts'; // fields SL_ATT_FIELD_TITLE = 'title'; SL_ATT_FIELD_VALUE = 'value'; SL_ATT_FIELD_SHORT = 'short'; type { TAttachmentField } TAttachmentField = class private FObject: TJSONObject; FShort: boolean; FTitle: string; FValue: string; procedure AddRec(ARecName: string; AJSONArray: TJSONArray); procedure SetShort(AValue: boolean); procedure SetTitle(AValue: string); procedure SetValue(AValue: string); public constructor Create; destructor Destroy; override; property Title: string read FTitle write SetTitle; property Value: string read FValue write SetValue; property Short: boolean read FShort write SetShort; function GetObject: TJSONObject; end; { TSlackAttachment } TSlackAttachment = class private FObject: TJSONObject; FFieldsArray: TJSONArray; FAuthorIcon: string; FAuthorLink: string; FAuthorName: string; FColor: string; FFooter: string; FFooterIcon: string; FImageUrl: string; FFallBack: string; FPreText: string; FText: string; FThunmUrl: string; FTitle: string; FTitleLink: string; procedure AddRec(ARecName, ARecValue: string); function GetObject: TJSONObject; procedure SetAuthorIcon(AValue: string); procedure SetAuthorLink(AValue: string); procedure SetAuthorName(AValue: string); procedure SetColor(AValue: string); procedure SetFallBack(AValue: string); procedure SetFooter(AValue: string); procedure SetFooterIcon(AValue: string); procedure SetImageUrl(AValue: string); procedure SetPreText(AValue: string); procedure SetText(AValue: string); procedure SetThumbUrl(AValue: string); procedure SetTitle(AValue: string); public constructor Create; destructor Destroy; override; procedure AddField(AField: TAttachmentField); property AttachmentObject: TJSONObject read GetObject; property FallBack: string read FFallBack write SetFallBack; property Color: string read FColor write SetColor; property PreText: string read FPreText write SetPreText; property AuthorLink: string read FAuthorLink write SetAuthorLink; property AuthorIcon: string read FAuthorIcon write SetAuthorIcon; property Title: string read FTitle write SetTitle; property TitleLink: string read FTitleLink write FTitleLink; property Text: string read FText write SetText; //property Fields: String property ImageUrl: string read FImageUrl write SetImageUrl; property ThumbUrl: string read FThunmUrl write SetThumbUrl; property Footer: string read FFooter write SetFooter; property FooterIcon: string read FFooterIcon write SetFooterIcon; property AuthorName: string read FAuthorName write SetAuthorName; end; // TSlackAttachmentsList = class(TObjectList) // end; { TSlackMessage } TSlackMessage = class private FWebhookUrl: string; FIconURL: string; FMessage: string; FUserName: string; FChannel: string; jObject: TJSONObject; FAttachmentArray: TJSONArray; procedure AddRec(ARecName: string; AJSONArray: TJSONArray); function GetJSONMessage: string; procedure SetChannel(AValue: string); procedure SetIconURL(AValue: string); procedure SetMessage(AValue: string); procedure SetUserName(AValue: string); public constructor Create(AWebhookURL: string); destructor Destroy; override; function SendMessage: boolean; procedure AddAttachment(AAttachment: TSlackAttachment); property UserName: string read FUserName write SetUserName; property JSONMessage: string read GetJSONMessage; property Message: string read FMessage write SetMessage; property IconURL: string read FIconURL write SetIconURL; property Channel: string read FChannel write SetChannel; end; { TSlack } implementation { TAttachmentField } procedure TAttachmentField.AddRec(ARecName: string; AJSONArray: TJSONArray); var dat: TJSONArray; begin dat := TJSONArray(FObject.Find(ARecName)); if Assigned(dat) then dat := AJSONArray else FObject.Add(ARecName, AJSONArray); end; procedure TAttachmentField.SetShort(AValue: boolean); begin if FShort = AValue then Exit; FShort := AValue; FObject.Add(SL_ATT_FIELD_SHORT, AValue); end; procedure TAttachmentField.SetTitle(AValue: string); begin if FTitle = AValue then Exit; FTitle := AValue; FObject.Add(SL_ATT_FIELD_TITLE, AValue); end; procedure TAttachmentField.SetValue(AValue: string); begin if FValue = AValue then Exit; FValue := AValue; FObject.Add(SL_ATT_FIELD_VALUE, AValue); end; constructor TAttachmentField.Create; begin FObject := TJSONObject.Create; end; destructor TAttachmentField.Destroy; begin try // FreeAndNil(FObject); except on e: Exception do ; end; inherited Destroy; end; function TAttachmentField.GetObject: TJSONObject; begin Result := FObject; end; { TSlackAttachment } procedure TSlackAttachment.SetFallBack(AValue: string); begin if FFallBack = AValue then Exit; FFallBack := AValue; AddRec(SL_ATT_FALLBACK, AValue); end; procedure TSlackAttachment.SetFooter(AValue: string); begin if FFooter = AValue then Exit; FFooter := AValue; AddRec(SL_ATT_FOOTER, AValue); end; procedure TSlackAttachment.SetFooterIcon(AValue: string); begin if FFooterIcon = AValue then Exit; FFooterIcon := AValue; AddRec(SL_ATT_FOOTER_ICON, AValue); end; procedure TSlackAttachment.SetImageUrl(AValue: string); begin if FImageUrl = AValue then Exit; FImageUrl := AValue; AddRec(SL_ATT_IMAGE_URL, AValue); end; procedure TSlackAttachment.SetPreText(AValue: string); begin if FPreText = AValue then Exit; FPreText := AValue; AddRec(SL_ATT_PRETEXT, AValue); end; procedure TSlackAttachment.SetText(AValue: string); begin if FText = AValue then Exit; FText := AValue; AddRec(SL_ATT_TEXT, AValue); end; procedure TSlackAttachment.SetThumbUrl(AValue: string); begin if FThunmUrl = AValue then Exit; FThunmUrl := AValue; AddRec(SL_ATT_THUMB_URL, AValue); end; procedure TSlackAttachment.SetTitle(AValue: string); begin if FTitle = AValue then Exit; FTitle := AValue; AddRec(SL_ATT_TITLE, AValue); end; procedure TSlackAttachment.AddRec(ARecName, ARecValue: string); var dat: TJSONData; begin dat := FObject.Find(ARecName); if Assigned(dat) then dat.Value := ARecValue else FObject.Add(ARecName, ARecValue); end; function TSlackAttachment.GetObject: TJSONObject; begin Result := FObject; end; procedure TSlackAttachment.SetAuthorIcon(AValue: string); begin if FAuthorIcon = AValue then Exit; FAuthorIcon := AValue; AddRec(SL_ATT_AUTHOR_ICON, AValue); end; procedure TSlackAttachment.SetAuthorLink(AValue: string); begin if FAuthorLink = AValue then Exit; FAuthorLink := AValue; AddRec(SL_ATT_AUTHOR_LINK, AValue); end; procedure TSlackAttachment.SetAuthorName(AValue: string); begin if FAuthorName = AValue then Exit; FAuthorName := AValue; AddRec(SL_ATT_COLOR, AValue); end; procedure TSlackAttachment.SetColor(AValue: string); begin if FColor = AValue then Exit; FColor := AValue; AddRec(SL_ATT_COLOR, AValue); end; constructor TSlackAttachment.Create; begin // FFieldsArray := TJSONArray.Create; FObject := TJSONObject.Create; end; destructor TSlackAttachment.Destroy; begin try FObject := nil; // FreeAndNil(FObject); except on e: Exception do ; end; try FFieldsArray := nil; // FreeAndNil(FFieldsArray); except on e: Exception do ; end; inherited Destroy; end; procedure TSlackAttachment.AddField(AField: TAttachmentField); var dat: TJSONData; begin if not Assigned(FFieldsArray) then begin FFieldsArray := TJSONArray.Create; FObject.Add(SL_ATT_FIELDS, FFieldsArray); end; FFieldsArray.Add(AField.GetObject); dat := nil; dat := FObject.Find(SL_ATT_FIELDS); if not assigned(dat) then FObject.Add(SL_ATT_FIELDS, FFieldsArray); end; procedure TSlackMessage.AddRec(ARecName: string; AJSONArray: TJSONArray); var dat: TJSONArray; begin dat := TJSONArray(jObject.Find(ARecName)); if Assigned(dat) then dat := AJSONArray else jObject.Add(ARecName, AJSONArray); end; { TSlackMessage } function TSlackMessage.GetJSONMessage: string; begin Result := jObject.AsJSON; Result := jObject.FormatJSON; end; procedure TSlackMessage.SetUserName(AValue: string); begin if FUserName = AValue then Exit; FUserName := AValue; jObject.Add(SL_USERNAME, AValue); end; procedure TSlackMessage.SetChannel(AValue: string); begin if FChannel = AValue then Exit; FChannel := AValue; jObject.Add(SL_CHANNEL, AValue); end; procedure TSlackMessage.SetIconURL(AValue: string); begin if FIconURL = AValue then Exit; FIconURL := AValue; jObject.Add(SL_ICON_URL, AValue); end; procedure TSlackMessage.SetMessage(AValue: string); begin if FMessage = AValue then Exit; FMessage := AValue; jObject.Add(SL_TEXT, AValue); end; function TSlackMessage.SendMessage: boolean; var bodyJson, Response: string; http: THTTPSend; Params: TStringStream; res: boolean; Data: TStringList; begin // Writeln('Start SendMessage'); bodyJson := 'payload=' + JSONMessage; http := THTTPSend.Create; http.Headers.Clear; http.Protocol := '1.1'; http.MimeType := 'application/json'; http.MimeType := 'application/x-www-form-urlencoded'; Params := TStringStream.Create(bodyJson); http.Document.LoadFromStream(Params); FreeAndNil(Params); // Writeln('Begin execute POST method'); res := http.HTTPMethod('POST', FWebhookURL); // writeln('------'); // writeln(FWebhookUrl); // writeln('Result of POST method: ', res); // writeln('------'); Response := ''; Data := TStringList.Create; try if res then begin Data.LoadFromStream(http.Document); Response := Data.Text; end; finally FreeAndNil(Data); FreeAndNil(http); end; Result := res; end; procedure TSlackMessage.AddAttachment(AAttachment: TSlackAttachment); begin if not Assigned(FAttachmentArray) then begin FAttachmentArray := TJSONArray.Create; AddRec(SL_ATTACHMENTS, FAttachmentArray); end; FAttachmentArray.Add(AAttachment.GetObject); // jObject.Add(SL_ATTACHMENTS, FAttachmentArray); end; constructor TSlackMessage.Create(AWebhookURL: string); begin FWebHookUrl := AWebhookURL; jObject := TJSONObject.Create; end; destructor TSlackMessage.Destroy; begin try FreeAndNil(jObject); except on e: Exception do ; end; try // FAttachmentArray := nil; // FreeAndNil(FAttachmentArray); except on e: Exception do ; end; inherited Destroy; end; { TSlack } end.
unit Entidade.CentroCusto; interface uses SimpleAttributes; type TCENTRO_CUSTO = class private FID_TIPO_CC: Integer; FDESCRICAO: string; FID: Integer; procedure SetDESCRICAO(const Value: string); procedure SetID(const Value: Integer); procedure SetID_TIPO_CC(const Value: Integer); published [PK,AutoInc] property ID: Integer read FID write SetID; property DESCRICAO: string read FDESCRICAO write SetDESCRICAO; property ID_TIPO_CC : Integer read FID_TIPO_CC write SetID_TIPO_CC; end; implementation { TCENTRO_CUSTO } procedure TCENTRO_CUSTO.SetDESCRICAO(const Value: string); begin FDESCRICAO := Value; end; procedure TCENTRO_CUSTO.SetID(const Value: Integer); begin FID := Value; end; procedure TCENTRO_CUSTO.SetID_TIPO_CC(const Value: Integer); begin FID_TIPO_CC := Value; end; end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Actions, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView.Types, FMX.StdCtrls, FMX.ListView, FMX.ActnList, FMX.Menus, FMX.StdActns, FMX.MediaLibrary.Actions, Fmx.Bind.GenData, Data.Bind.GenData, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.ObjectScope, PaxRunner, PaxProgram, PaxCompiler, FMX.Layouts, FMX.Memo, FMX.Controls.Presentation, ufrPlugins, PaxInterpreter; type TfMain = class(TForm) PrototypeBindSource: TPrototypeBindSource; pxcmplr: TPaxCompiler; pxpsclng: TPaxPascalLanguage; btnRun: TButton; actlst: TActionList; actLoadPlugins: TAction; actEditCurrent: TAction; actAddPlugin: TAction; actSavePlugins: TAction; TakePhotoFromLibraryAction: TTakePhotoFromLibraryAction; actOpenUrl: TAction; frplgns: TfrPlugins; pxprgrm: TPaxInterpreter; procedure actOpenPluginExecute(Sender: TObject); procedure btnRunClick(Sender: TObject); procedure pxcmplrUnknownDirective(Sender: TPaxCompiler; const Directive: string; var ok: Boolean); procedure pxprgrmCreateObject(Sender: TPaxRunner; Instance: TObject); private { Private declarations } CurrModule: String; public { Public declarations } end; var fMain: TfMain; implementation uses uPlugin, OpenViewUrl, PAXCOMP_SYS; {$R *.fmx} {------------------------------------------------------------------------------} procedure TfMain.actOpenPluginExecute(Sender: TObject); var plugin : TPlugin; P : Pointer; begin plugin := frplgns.CurrentPlugin; if not Assigned(plugin) then exit; case plugin.FType of 0: OpenViewUrl.OpenURL(plugin.FPath); 1: begin pxcmplr.Reset; pxcmplr.RegisterLanguage(pxpsclng); pxcmplr.AddModule('1', 'Pascal'); pxcmplr.AddCodeFromFile('1', plugin.FPath); if pxcmplr.Compile(pxprgrm) then begin P := pxprgrm.GetAddress('fMain'); if Assigned(P) then TfMain(P^) := Self; // change script-defind variable pxprgrm.Run; end else ShowMessage(pxcmplr.ErrorMessage[0]); end; end; end; {------------------------------------------------------------------------------} procedure TfMain.btnRunClick(Sender: TObject); begin actOpenPluginExecute(Sender); end; {------------------------------------------------------------------------------} procedure TfMain.pxcmplrUnknownDirective(Sender: TPaxCompiler; const Directive: string; var ok: Boolean); begin ok := true; CurrModule := Sender.CurrModuleName; end; {------------------------------------------------------------------------------} procedure TfMain.pxprgrmCreateObject(Sender: TPaxRunner; Instance: TObject); var P: PVmtMethodTable; begin P := GetMethodTable(Instance.ClassType); if Instance is TForm then Sender.LoadDFMFile(Instance, CurrModule + '.dfm'); end; {------------------------------------------------------------------------------} end.
unit DeviceLicenseResponseUnit; interface uses REST.Json.Types, GenericParametersUnit; type TDeviceLicenseResponse = class(TGenericParameters) private [JSONName('status')] FStatus: boolean; [JSONName('routes_planned_this_month')] FRoutesPlannedThisMonth: integer; [JSONName('routes_remaining_this_month')] FRoutesRemainingThisMonth: integer; public property Status: boolean read FStatus write FStatus; property RoutesPlannedThisMonth: integer read FRoutesPlannedThisMonth; property RoutesRemainingThisMonth: integer read FRoutesRemainingThisMonth; end; implementation end.
unit InfoPOLNOTSTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoPOLNOTSRecord = record PlenderID: String[4]; PModCount: SmallInt; Pprefix: String[3]; PPolicy: String[7]; End; TInfoPOLNOTSClass2 = class public PlenderID: String[4]; PModCount: SmallInt; Pprefix: String[3]; PPolicy: String[7]; End; // function CtoRInfoPOLNOTS(AClass:TInfoPOLNOTSClass):TInfoPOLNOTSRecord; // procedure RtoCInfoPOLNOTS(ARecord:TInfoPOLNOTSRecord;AClass:TInfoPOLNOTSClass); TInfoPOLNOTSBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoPOLNOTSRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoPOLNOTS = (InfoPOLNOTSPrimaryKey, InfoPOLNOTSPolicyNum); TInfoPOLNOTSTable = class( TDBISAMTableAU ) private FDFlenderID: TStringField; FDFModCount: TSmallIntField; FDFprefix: TStringField; FDFPolicy: TStringField; FDFNotes: TBlobField; procedure SetPlenderID(const Value: String); function GetPlenderID:String; procedure SetPModCount(const Value: SmallInt); function GetPModCount:SmallInt; procedure SetPprefix(const Value: String); function GetPprefix:String; procedure SetPPolicy(const Value: String); function GetPPolicy:String; procedure SetEnumIndex(Value: TEIInfoPOLNOTS); function GetEnumIndex: TEIInfoPOLNOTS; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoPOLNOTSRecord; procedure StoreDataBuffer(ABuffer:TInfoPOLNOTSRecord); property DFlenderID: TStringField read FDFlenderID; property DFModCount: TSmallIntField read FDFModCount; property DFprefix: TStringField read FDFprefix; property DFPolicy: TStringField read FDFPolicy; property DFNotes: TBlobField read FDFNotes; property PlenderID: String read GetPlenderID write SetPlenderID; property PModCount: SmallInt read GetPModCount write SetPModCount; property Pprefix: String read GetPprefix write SetPprefix; property PPolicy: String read GetPPolicy write SetPPolicy; published property Active write SetActive; property EnumIndex: TEIInfoPOLNOTS read GetEnumIndex write SetEnumIndex; end; { TInfoPOLNOTSTable } TInfoPOLNOTSQuery = class( TDBISAMQueryAU ) private FDFlenderID: TStringField; FDFModCount: TSmallIntField; FDFprefix: TStringField; FDFPolicy: TStringField; FDFNotes: TBlobField; procedure SetPlenderID(const Value: String); function GetPlenderID:String; procedure SetPModCount(const Value: SmallInt); function GetPModCount:SmallInt; procedure SetPprefix(const Value: String); function GetPprefix:String; procedure SetPPolicy(const Value: String); function GetPPolicy:String; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; public function GetDataBuffer:TInfoPOLNOTSRecord; procedure StoreDataBuffer(ABuffer:TInfoPOLNOTSRecord); property DFlenderID: TStringField read FDFlenderID; property DFModCount: TSmallIntField read FDFModCount; property DFprefix: TStringField read FDFprefix; property DFPolicy: TStringField read FDFPolicy; property DFNotes: TBlobField read FDFNotes; property PlenderID: String read GetPlenderID write SetPlenderID; property PModCount: SmallInt read GetPModCount write SetPModCount; property Pprefix: String read GetPprefix write SetPprefix; property PPolicy: String read GetPPolicy write SetPPolicy; published property Active write SetActive; end; { TInfoPOLNOTSTable } procedure Register; implementation procedure TInfoPOLNOTSTable.CreateFields; begin FDFlenderID := CreateField( 'lenderID' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; FDFprefix := CreateField( 'prefix' ) as TStringField; FDFPolicy := CreateField( 'Policy' ) as TStringField; FDFNotes := CreateField( 'Notes' ) as TBlobField; end; { TInfoPOLNOTSTable.CreateFields } procedure TInfoPOLNOTSTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoPOLNOTSTable.SetActive } procedure TInfoPOLNOTSTable.SetPlenderID(const Value: String); begin DFlenderID.Value := Value; end; function TInfoPOLNOTSTable.GetPlenderID:String; begin result := DFlenderID.Value; end; procedure TInfoPOLNOTSTable.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoPOLNOTSTable.GetPModCount:SmallInt; begin result := DFModCount.Value; end; procedure TInfoPOLNOTSTable.SetPprefix(const Value: String); begin DFprefix.Value := Value; end; function TInfoPOLNOTSTable.GetPprefix:String; begin result := DFprefix.Value; end; procedure TInfoPOLNOTSTable.SetPPolicy(const Value: String); begin DFPolicy.Value := Value; end; function TInfoPOLNOTSTable.GetPPolicy:String; begin result := DFPolicy.Value; end; procedure TInfoPOLNOTSTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('lenderID, String, 4, N'); Add('ModCount, SmallInt, 0, N'); Add('prefix, String, 3, N'); Add('Policy, String, 7, N'); Add('Notes, Memo, 0, N'); end; end; procedure TInfoPOLNOTSTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, lenderID;prefix;Policy, Y, Y, N, N'); Add('PolicyNum, lenderID;prefix;Policy, N, Y, Y, N'); end; end; procedure TInfoPOLNOTSTable.SetEnumIndex(Value: TEIInfoPOLNOTS); begin case Value of InfoPOLNOTSPrimaryKey : IndexName := ''; InfoPOLNOTSPolicyNum : IndexName := 'PolicyNum'; end; end; function TInfoPOLNOTSTable.GetDataBuffer:TInfoPOLNOTSRecord; var buf: TInfoPOLNOTSRecord; begin fillchar(buf, sizeof(buf), 0); buf.PlenderID := DFlenderID.Value; buf.PModCount := DFModCount.Value; buf.Pprefix := DFprefix.Value; buf.PPolicy := DFPolicy.Value; result := buf; end; procedure TInfoPOLNOTSTable.StoreDataBuffer(ABuffer:TInfoPOLNOTSRecord); begin DFlenderID.Value := ABuffer.PlenderID; DFModCount.Value := ABuffer.PModCount; DFprefix.Value := ABuffer.Pprefix; DFPolicy.Value := ABuffer.PPolicy; end; function TInfoPOLNOTSTable.GetEnumIndex: TEIInfoPOLNOTS; var iname : string; begin result := InfoPOLNOTSPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoPOLNOTSPrimaryKey; if iname = 'POLICYNUM' then result := InfoPOLNOTSPolicyNum; end; procedure TInfoPOLNOTSQuery.CreateFields; begin FDFlenderID := CreateField( 'lenderID' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; FDFprefix := CreateField( 'prefix' ) as TStringField; FDFPolicy := CreateField( 'Policy' ) as TStringField; FDFNotes := CreateField( 'Notes' ) as TBlobField; end; { TInfoPOLNOTSQuery.CreateFields } procedure TInfoPOLNOTSQuery.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoPOLNOTSQuery.SetActive } procedure TInfoPOLNOTSQuery.SetPlenderID(const Value: String); begin DFlenderID.Value := Value; end; function TInfoPOLNOTSQuery.GetPlenderID:String; begin result := DFlenderID.Value; end; procedure TInfoPOLNOTSQuery.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoPOLNOTSQuery.GetPModCount:SmallInt; begin result := DFModCount.Value; end; procedure TInfoPOLNOTSQuery.SetPprefix(const Value: String); begin DFprefix.Value := Value; end; function TInfoPOLNOTSQuery.GetPprefix:String; begin result := DFprefix.Value; end; procedure TInfoPOLNOTSQuery.SetPPolicy(const Value: String); begin DFPolicy.Value := Value; end; function TInfoPOLNOTSQuery.GetPPolicy:String; begin result := DFPolicy.Value; end; function TInfoPOLNOTSQuery.GetDataBuffer:TInfoPOLNOTSRecord; var buf: TInfoPOLNOTSRecord; begin fillchar(buf, sizeof(buf), 0); buf.PlenderID := DFlenderID.Value; buf.PModCount := DFModCount.Value; buf.Pprefix := DFprefix.Value; buf.PPolicy := DFPolicy.Value; result := buf; end; procedure TInfoPOLNOTSQuery.StoreDataBuffer(ABuffer:TInfoPOLNOTSRecord); begin DFlenderID.Value := ABuffer.PlenderID; DFModCount.Value := ABuffer.PModCount; DFprefix.Value := ABuffer.Pprefix; DFPolicy.Value := ABuffer.PPolicy; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoPOLNOTSTable, TInfoPOLNOTSQuery, TInfoPOLNOTSBuffer ] ); end; { Register } function TInfoPOLNOTSBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..4] of string = ('LENDERID','MODCOUNT','PREFIX','POLICY' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 4) and (flist[x] <> s) do inc(x); if x <= 4 then result := x else result := 0; end; function TInfoPOLNOTSBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftSmallInt; 3 : result := ftString; 4 : result := ftString; end; end; function TInfoPOLNOTSBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PlenderID; 2 : result := @Data.PModCount; 3 : result := @Data.Pprefix; 4 : result := @Data.PPolicy; end; end; end.
unit Tickservm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, IniFiles, WSocket, Menus, StdCtrls, ExtCtrls, ApSrvCli, RFormat, RBroker, ApServer, TTSDirectDaapi, TTSDaapiObjects, ProgramSettings, sButton, sLabel, sPanel, sMemo; const WM_APPSTARTUP = WM_USER + 1; type TServerForm = class(TForm) DisplayMemo: TsMemo; Panel1: TsPanel; ClientCountLabel: TsLabel; ObjectCountLabel: TsLabel; DisconnectAllButton: TsButton; RequestBroker1: TRequestBroker; AppServer1: TAppServer; Label1: TsLabel; Label2: TsLabel; ClearButton: TsButton; FunctionsButton: TsButton; ps1: TProgramSettings; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure DisconnectAllButtonClick(Sender: TObject); procedure AppServer1ClientConnected(Sender: TObject; CliWSocket : TClientWSocket); procedure AppServer1ClientClosed(Sender: TObject; CliWSocket : TClientWSocket); procedure AppServer1Display(Sender: TObject; Msg: String); procedure RequestBroker1ObjCreate(Sender: TObject; ServerObject: TServerObject); procedure RequestBroker1ObjDestroy(Sender: TObject; ServerObject: TServerObject); procedure ClearButtonClick(Sender: TObject); procedure FunctionsButtonClick(Sender: TObject); private { Déclarations privées } PrivDaapi : TTTSDirectDaapi; FInitialized : Boolean; FIniFileName : String; // FRequestBuffer : TMWBuffer; procedure WMAppStartup(var msg: TMessage); message WM_APPSTARTUP; function EnumServerFunctions(Sender: TObject; FunctionCode : String) : boolean; procedure StartDatabase; end; var ServerForm: TServerForm; implementation uses BaseIDaapiGlobal; {$R *.DFM} const SectionData = 'Data'; KeyPort = 'Port'; SectionWindow = 'Window'; KeyTop = 'Top'; KeyLeft = 'Left'; KeyWidth = 'Width'; KeyHeight = 'Height'; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TServerForm.FormCreate(Sender: TObject); begin { Build Ini file name } FIniFileName := LowerCase(ExtractFileName(Application.ExeName)); FIniFileName := ChangeFileExt(FiniFileName, '.ini'); { Initialize RequestBroker object } RequestBroker1.IniFileName := FIniFileName; // setup RequestBroker1.AddServerObject(TServerObjectGetSetupRecord1); RequestBroker1.AddServerObject(TServerObjectSetSetupRecord1); // lender RequestBroker1.AddServerObject(TServerObjectLendExists); RequestBroker1.AddServerObject(TServerObjectLendGetRecord); RequestBroker1.AddServerObject(TServerObjectLendUpdateRecord); RequestBroker1.AddServerObject(TServerObjectLendAddRecord); RequestBroker1.AddServerObject(TServerObjectLendDelete); RequestBroker1.AddServerObject(TServerObjectLendGetSelectList); // Reports RequestBroker1.AddServerObject(TServerObjectGetRunReportOptions); RequestBroker1.AddServerObject(TServerObjectGetReportHistory); RequestBroker1.AddServerObject(TServerObjectGetSavedReportList); RequestBroker1.AddServerObject(TServerObjectGetSavedReport); RequestBroker1.AddServerObject(TServerObjectSaveReportSettings); RequestBroker1.AddServerObject(TServerObjectSaveReportRun); RequestBroker1.AddServerObject(TServerObjectDeleteReportSettings); RequestBroker1.AddServerObject(TServerObjectRemoveOldReports); RequestBroker1.AddServerObject(TServerObjectReportAbort); RequestBroker1.AddServerObject(TServerObjectReportRun); RequestBroker1.AddServerObject(TServerObjectReportGetProgress); RequestBroker1.AddServerObject(TServerObjectReportGetStream); RequestBroker1.AddServerObject(TServerObjectNoticeScanUndo); // misc RequestBroker1.AddServerObject(TServerObjectLoanGetLoanCount); RequestBroker1.AddServerObject(TServerObjectCopyLender); RequestBroker1.AddServerObject(TServerObjectcopyLendcodes); RequestBroker1.AddServerObject(TServerObjectcopytables); // datacaddy RequestBroker1.AddServerObject(TServerObjectDCGetReview); RequestBroker1.AddServerObject(TServerObjectDCAddRecord); RequestBroker1.AddServerObject(TServerObjectDCUpdateRecord); RequestBroker1.AddServerObject(TServerObjectDCPerform); RequestBroker1.AddServerObject(TServerObjectDCGetRecord); RequestBroker1.AddServerObject(TServerObjectDCStop); // Version RequestBroker1.AddServerObject(TServerObjectGetDatabaseVersion); RequestBroker1.AddServerObject(TServerObjectSetDatabaseVersion); // Loan RequestBroker1.AddServerObject(TServerObjectLoanGetRecord); RequestBroker1.AddServerObject(TServerObjectLoanAddRecord); RequestBroker1.AddServerObject(TServerObjectLoanUpdateRecord); RequestBroker1.AddServerObject(TServerObjectLoanDelete); RequestBroker1.AddServerObject(TServerObjectLoanChangeNumber); RequestBroker1.AddServerObject(TServerObjectLoanChangeOfcr); RequestBroker1.AddServerObject(TServerObjectLoanCollCodeInUse); RequestBroker1.AddServerObject(TServerObjectLoanExists); RequestBroker1.AddServerObject(TServerObjectLoanGetLoanList); RequestBroker1.AddServerObject(TServerObjectLoanExportCifToLoans); RequestBroker1.AddServerObject(TServerObjectLoanGetNotes); RequestBroker1.AddServerObject(TServerObjectLoanUpdateNotes); RequestBroker1.AddServerObject(TServerObjectLoanGetModCount); RequestBroker1.AddServerObject(TServerObjectLoanGetNotesModCount); RequestBroker1.AddServerObject(TServerObjectLoanGetCollList); RequestBroker1.AddServerObject(TServerObjectUTLAddNew); // Collateral RequestBroker1.AddServerObject(TServerObjectNcolGetRecord); RequestBroker1.AddServerObject(TServerObjectNcolUpdateRecord); RequestBroker1.AddServerObject(TServerObjectNcolAddRecord); RequestBroker1.AddServerObject(TServerObjectNcolDeleteRecord); // Coll Codes RequestBroker1.AddServerObject(TServerObjectCollCheckIndivid); RequestBroker1.AddServerObject(TServerObjectCollGetCodeCount); RequestBroker1.AddServerObject(TServerObjectCollCheckCodes); RequestBroker1.AddServerObject(TServerObjectCollGetDesc); RequestBroker1.AddServerObject(TServerObjectCollGetList); RequestBroker1.AddServerObject(TServerObjectCollAddRecord); RequestBroker1.AddServerObject(TServerObjectCollGetCodeDescList); RequestBroker1.AddServerObject(TServerObjectCollGetRecord); RequestBroker1.AddServerObject(TServerObjectCollGetItemList); RequestBroker1.AddServerObject(TServerObjectCollSetItemList); RequestBroker1.AddServerObject(TServerObjectCollDeleteCode); RequestBroker1.AddServerObject(TServerObjectCollUpdateRate); // misc RequestBroker1.AddServerObject(TServerObjectUpdateCifBal); RequestBroker1.AddServerObject(TServerObjectInsertNameSearch); RequestBroker1.AddServerObject(TServerObjectNMSRRebuild); RequestBroker1.AddServerObject(TServerObjectListLoad); // Guar RequestBroker1.AddServerObject(TServerObjectGuarDeleteGuarantor); RequestBroker1.AddServerObject(TServerObjectGuarAddGuarantor); RequestBroker1.AddServerObject(TServerObjectGuarGetGuarantorList); RequestBroker1.AddServerObject(TServerObjectGuarGetLoanList); // Citm RequestBroker1.AddServerObject(TServerObjectCitmRequiredItem); // Titm RequestBroker1.AddServerObject(TServerObjectTitmDeleteCategory); RequestBroker1.AddServerObject(TServerObjectTitmGetModCount); RequestBroker1.AddServerObject(TServerObjectTitmGetList); RequestBroker1.AddServerObject(TServerObjectTitmItemExists); RequestBroker1.AddServerObject(TServerObjectTitmAddRecord); RequestBroker1.AddServerObject(TServerObjectTitmGetRecord); RequestBroker1.AddServerObject(TServerObjectTitmUpdateRecord); RequestBroker1.AddServerObject(TServerObjectTitmDelete); RequestBroker1.AddServerObject(TServerObjectTitmGetNotes); RequestBroker1.AddServerObject(TServerObjectTitmUpdateNote); RequestBroker1.AddServerObject(TServerObjectTitmChangeAllCats); RequestBroker1.AddServerObject(TServerObjectTitmCatInUse); // TDoc RequestBroker1.AddServerObject(TServerObjectTDocGetItems); RequestBroker1.AddServerObject(TServerObjectTDocGetRecord); RequestBroker1.AddServerObject(TServerObjectTDocDeleteRecord); RequestBroker1.AddServerObject(TServerObjectTDocSetRecord); RequestBroker1.AddServerObject(TServerObjectTDocGetImage); // Trak RequestBroker1.AddServerObject(TServerObjectTrakGetCodeCount); RequestBroker1.AddServerObject(TServerObjectTrakAddRecord); RequestBroker1.AddServerObject(TServerObjectTrakGetRecord); RequestBroker1.AddServerObject(TServerObjectTrakGetTemplate); RequestBroker1.AddServerObject(TServerObjectTrakTallyItems); RequestBroker1.AddServerObject(TServerObjectTrakGetCodeDescList); RequestBroker1.AddServerObject(TServerObjectTrakGetCodeList); RequestBroker1.AddServerObject(TServerObjectTrakCatExists); RequestBroker1.AddServerObject(TServerObjectTrakDelCat); RequestBroker1.AddServerObject(TServerObjectTrakGetNoticeList); // LDoc RequestBroker1.AddServerObject(TServerObjectLDocGetList); RequestBroker1.AddServerObject(TServerObjectLDocGetImage); RequestBroker1.AddServerObject(TServerObjectLDocAddImage); RequestBroker1.AddServerObject(TServerObjectLDocDeleteImage); RequestBroker1.AddServerObject(TServerObjectLDocUpdateDesc); // Divi RequestBroker1.AddServerObject(TServerObjectDiviAddRecord); RequestBroker1.AddServerObject(TServerObjectDiviGetCodeDescList); RequestBroker1.AddServerObject(TServerObjectDiviExists); RequestBroker1.AddServerObject(TServerObjectDiviGetRecord); RequestBroker1.AddServerObject(TServerObjectDiviDelete); RequestBroker1.AddServerObject(TServerObjectDiviGetCodeList); // Ofcr RequestBroker1.AddServerObject(TServerObjectOfcrAddRecord); RequestBroker1.AddServerObject(TServerObjectOfcrGetCodeDescList); RequestBroker1.AddServerObject(TServerObjectOfcrExists); RequestBroker1.AddServerObject(TServerObjectOfcrGetRecord); RequestBroker1.AddServerObject(TServerObjectOfcrDelete); RequestBroker1.AddServerObject(TServerObjectOfcrGetCodeList); // Brch RequestBroker1.AddServerObject(TServerObjectBrchAddRecord); RequestBroker1.AddServerObject(TServerObjectBrchGetCodeDescList); RequestBroker1.AddServerObject(TServerObjectBrchExists); RequestBroker1.AddServerObject(TServerObjectBrchGetRecord); RequestBroker1.AddServerObject(TServerObjectBrchDelete); RequestBroker1.AddServerObject(TServerObjectBrchGetCodeList); // Notc RequestBroker1.AddServerObject(TServerObjectNotcGetNoticeText); RequestBroker1.AddServerObject(TServerObjectNotcAddUpdtNoticeText); RequestBroker1.AddServerObject(TServerObjectNoteAddUpdtRecord); RequestBroker1.AddServerObject(TServerObjectNoteGetRecord); RequestBroker1.AddServerObject(TServerObjectNoteDelete); // Other RequestBroker1.AddServerObject(TServerObjectCIFBal); RequestBroker1.AddServerObject(TServerObjectNoNot); RequestBroker1.AddServerObject(TServerObjectDoRefresh); // search RequestBroker1.AddServerObject(TServerObjectSearchIt); RequestBroker1.AddServerObject(TServerObjectSearchGet); // version RequestBroker1.AddServerObject(TServerObjectCheckApplicationVersion); RequestBroker1.AddServerObject(TServerObjectSetApplicationVersion); // Pledge RequestBroker1.AddServerObject(TServerObjectPldgAddRecord); RequestBroker1.AddServerObject(TServerObjectPldgGetLoanList); RequestBroker1.AddServerObject(TServerObjectPldgGetLoanCollList); RequestBroker1.AddServerObject(TServerObjectPldgDeleteRecord); // Other RequestBroker1.AddServerObject(TServerObjectThreadCount); // RequestBroker1.AddServerObject(TServerObjectGETUPDATE); RequestBroker1.AddServerObject(TServerObjectLendGetList); RequestBroker1.AddServerObject(TServerObjectLendGetLendHeaders); RequestBroker1.AddServerObject(TServerObjectLendGetShortRecord); RequestBroker1.AddServerObject(TServerObjectLogClearFile); RequestBroker1.AddServerObject(TServerObjectLogGetCount); RequestBroker1.AddServerObject(TServerObjectLogGetRecord); RequestBroker1.AddServerObject(TServerObjectLogMessage); RequestBroker1.AddServerObject(TServerObjectSecureActivateInitial); RequestBroker1.AddServerObject(TServerObjectSecureActivateSerial); RequestBroker1.AddServerObject(TServerObjectSecureAutoRegister); RequestBroker1.AddServerObject(TServerObjectSecureCanAutoRegister); RequestBroker1.AddServerObject(TServerObjectSecureCheckRunCount); RequestBroker1.AddServerObject(TServerObjectSecureConnectUser); RequestBroker1.AddServerObject(TServerObjectSecureRegistered); RequestBroker1.AddServerObject(TServerObjectSecureSetAutoRegisterCount); RequestBroker1.AddServerObject(TServerObjectSecureSetNumberOfUsers); RequestBroker1.AddServerObject(TServerObjectSecureGetNumberOfUsers); RequestBroker1.AddServerObject(TServerObjectSecureSetNumberOfUses); RequestBroker1.AddServerObject(TServerObjectSecureWSActivated); RequestBroker1.AddServerObject(TServerObjectLendGrpGetNameList); RequestBroker1.AddServerObject(TServerObjectPermGrpGetNameList); RequestBroker1.AddServerObject(TServerObjectPermGrpGetRights); RequestBroker1.AddServerObject(TServerObjectPermGrpSetRights); RequestBroker1.AddServerObject(TServerObjectPermGrpDelGroup); RequestBroker1.AddServerObject(TServerObjectUserChangePassword); RequestBroker1.AddServerObject(TServerObjectUserValidateLogin); RequestBroker1.AddServerObject(TServerObjectUserAddRecord); RequestBroker1.AddServerObject(TServerObjectUserUpdateRecord); RequestBroker1.AddServerObject(TServerObjectUserDelete); RequestBroker1.AddServerObject(TServerObjectUserGetLogged); RequestBroker1.AddServerObject(TServerObjectUserGetNameList); RequestBroker1.AddServerObject(TServerObjectUserGetRecord); RequestBroker1.AddServerObject(TServerObjectUserLogin); RequestBroker1.AddServerObject(TServerObjectUserLogout); RequestBroker1.AddServerObject(TServerObjectUserNameIsUser); RequestBroker1.AddServerObject(TServerObjectUserGetUserID); RequestBroker1.AddServerObject(TServerObjectLogGetAll); RequestBroker1.AddServerObject(TServerObjectPasswordOptionsGetRecord); RequestBroker1.AddServerObject(TServerObjectPasswordOptionsAddRecord); RequestBroker1.AddServerObject(TServerObjectPasswordOptionsUpdateRecord); RequestBroker1.AddServerObject(TServerObjectPasswordOptionsDelete); RequestBroker1.AddServerObject(TServerObjectPasswordCheckEncryptionVersion); RequestBroker1.AddServerObject(TServerObjectWriteDefaultPasswordOptionsRecord); RequestBroker1.AddServerObject(TServerObjectPasswordDelete); //Cache Names RequestBroker1.AddServerObject(TServerObjectCacheNames); RequestBroker1.AddServerObject(TServerObjectCacheLoan); RequestBroker1.AddServerObject(TServerObjectCacheCIF); RequestBroker1.AddServerObject(TServerObjectCacheColl); RequestBroker1.AddServerObject(TServerObjectCacheRef); RequestBroker1.AddServerObject(TServerObjectCacheALL); { It's a good place to initialize TRequestBroker.UserData with for example } { a pointer to a dynamically allocated record or to an object. } { UserData is passed to ServerObjects instanciated by the broker. Using } { it, they can gain access to some global data or procedure, such as data } { base session. } { In this sample we use a TUserDataRecord record } ps1.ReadSettings; PrivDaapi := TTTSDirectDaapi.Create(self, ps1.DirWork); RequestBroker1.UserData := LongInt(PrivDaapi); StartDatabase; { Initialize user interface } ObjectCountLabel.Caption := '0'; ClientCountLabel.Caption := '0'; DisplayMemo.Clear; end; procedure TServerForm.StartDatabase; begin PrivDaapi.OpenBaseTables; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TServerForm.FormShow(Sender: TObject); begin if not FInitialized then begin FInitialized := TRUE; { We use a custom message to initialize things once the form } { is visible } PostMessage(Handle, WM_APPSTARTUP, 0, 0); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TServerForm.FormClose(Sender: TObject; var Action: TCloseAction); begin AppServer1.Stop; AppServer1.DisconnectAll; PrivDaapi.CloseBaseTables; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TServerForm.DisconnectAllButtonClick(Sender: TObject); begin AppServer1.DisconnectAll; ClientCountLabel.Caption := IntToStr(AppServer1.ClientCount); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This message handler is triggered by the FormShow event. We comes here } { only when the form is visible on screen. } procedure TServerForm.WMAppStartup(var msg: TMessage); var MainTitle : string; begin MainTitle := Caption; { Prevent the server from running twice } Update; { It's nice to have the form completely displayed } { Start the application server component } AppServer1.Port := ps1.ServerPort; AppServer1.Start; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { A new client has connected, update our user interface } procedure TServerForm.AppServer1ClientConnected( Sender : TObject; CliWSocket : TClientWSocket); var s : string; begin ClientCountLabel.Caption := IntToStr(AppServer1.ClientCount); s := CliWSocket.PeerAddr; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { A client has disconnected, update our user interface } procedure TServerForm.AppServer1ClientClosed( Sender : TObject; CliWSocket : TClientWSocket); begin ClientCountLabel.Caption := IntToStr(AppServer1.ClientCount - 1); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This event handler is called when the AppServer component has some info } { to display. This info can comes from one of the server components also. } procedure TServerForm.AppServer1Display(Sender: TObject; Msg: String); begin DisplayMemo.Lines.Add(Msg); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This event handler is called when the object request broker has just } { instanciated a server object to execute a user request. } procedure TServerForm.RequestBroker1ObjCreate(Sender: TObject; ServerObject: TServerObject); begin ObjectCountLabel.Caption := IntToStr(RequestBroker1.ObjectCount); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This event handler is called just before the object request broker } { destroy a server object after having executed a user request. } procedure TServerForm.RequestBroker1ObjDestroy(Sender: TObject; ServerObject: TServerObject); begin ObjectCountLabel.Caption := IntToStr(RequestBroker1.ObjectCount - 1); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TServerForm.ClearButtonClick(Sender: TObject); begin DisplayMemo.Clear; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This function is called back by the request broker for each function code } { he knows about when we ask to enumerate functions. } function TServerForm.EnumServerFunctions( Sender: TObject; FunctionCode : String) : boolean; begin DisplayMemo.Lines.Add(FunctionCode); Result := TRUE; { Continue to enumerate } end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TServerForm.FunctionsButtonClick(Sender: TObject); begin RequestBroker1.EnumServerFunctions(EnumServerFunctions); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
unit uGnRtti; interface uses Rtti, SysUtils, TypInfo; type TKoRtti = class(TObject) public end; EKoRtti = class(Exception); TKoRttiObjectHelper = class helper for TRttiObject strict private public function GetAttribute<T: class>: T; end; TKoValueHelper = record helper for TValue public function KoToString: string; procedure KoFromString(const AStrValue: string); end; implementation { TRttiObjectHelper } function TKoRttiObjectHelper.GetAttribute<T>: T; var Attr: TCustomAttribute; begin for Attr in Self.GetAttributes do begin if Attr.ClassNameIs(T.ClassName) then Exit(T(Attr)); end; Result := nil; end; { TKoValueHelper } procedure TKoValueHelper.KoFromString(const AStrValue: string); var I : Integer; begin case Self.Kind of tkWChar, tkLString, tkWString, tkString, tkChar, tkUString : Self := AStrValue; tkInteger, tkInt64 : Self := StrToInt(AStrValue); tkFloat : Self := StrToFloat(AStrValue); tkEnumeration: Self := TValue.FromOrdinal(Self.TypeInfo, GetEnumValue(Self.TypeInfo, AStrValue)); tkSet: begin i := StringToSet(Self.TypeInfo, AStrValue); TValue.Make(@i, Self.TypeInfo, Self); end; else raise EKoRtti.Create('Type not Supported'); end; end; function TKoValueHelper.KoToString: string; begin if Self.Kind in [tkWChar, tkLString, tkWString, tkString, tkChar, tkUString, tkInteger, tkInt64, tkFloat, tkEnumeration, tkSet] then Result := Self.ToString else raise EKoRtti.Create('Type not Supported'); end; end.
unit RealState.WebModule; interface uses System.SysUtils, System.Classes, Web.HTTPApp, MVCFramework, MVCFramework.Commons; type TRealStateWebModule = class(TWebModule) procedure WebModuleCreate(Sender: TObject); procedure WebModuleDestroy(Sender: TObject); private FMVC: TMVCEngine; procedure Configure(Config: TMVCConfig); procedure RegisterControllers; procedure RegisterMiddlewares; end; var WebModuleClass: TComponentClass = TRealStateWebModule; implementation {$R *.dfm} uses System.IOUtils, MVCFramework.Middleware.Compression, MVCFramework.Middleware.CORS, RealState.Agent.Controller, RealState.House.Controller; procedure TRealStateWebModule.WebModuleCreate(Sender: TObject); begin FMVC := TMVCEngine.Create(Self, Configure); RegisterControllers; RegisterMiddlewares; end; procedure TRealStateWebModule.WebModuleDestroy(Sender: TObject); begin FMVC.Free; end; procedure TRealStateWebModule.Configure(Config: TMVCConfig); begin // enable static files Config[TMVCConfigKey.DocumentRoot] := TPath.Combine(ExtractFilePath(GetModuleName(HInstance)), 'www'); // session timeout (0 means session cookie) Config[TMVCConfigKey.SessionTimeout] := '0'; // default content-type Config[TMVCConfigKey.DefaultContentType] := TMVCConstants.DEFAULT_CONTENT_TYPE; // default content charset Config[TMVCConfigKey.DefaultContentCharset] := TMVCConstants.DEFAULT_CONTENT_CHARSET; // unhandled actions are permitted? Config[TMVCConfigKey.AllowUnhandledAction] := 'false'; // default view file extension Config[TMVCConfigKey.DefaultViewFileExtension] := 'html'; // view path Config[TMVCConfigKey.ViewPath] := 'templates'; // Max Record Count for automatic Entities CRUD Config[TMVCConfigKey.MaxEntitiesRecordCount] := '20'; // Enable Server Signature in response Config[TMVCConfigKey.ExposeServerSignature] := 'true'; // Define a default URL for requests that don't map to a route or a file (useful for client side web app) Config[TMVCConfigKey.FallbackResource] := 'index.html'; end; procedure TRealStateWebModule.RegisterControllers; begin FMVC.AddController(TAgentController); FMVC.AddController(THouseController); end; procedure TRealStateWebModule.RegisterMiddlewares; begin // To enable compression (deflate, gzip) just add this middleware as the last one FMVC.AddMiddleware(TMVCCompressionMiddleware.Create); FMVC.AddMiddleware(TCORSMiddleware.Create); end; end.
unit Benjamim.Signature.Interfaces; interface Type iSignature = interface ['{9576A323-797D-414D-AFFB-0F3CCC567AFB}'] function Sign: string; function Verify: boolean; end; implementation end.
unit evdTypes; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "EVD" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/EVD/evdTypes.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<Interfaces::Category>> Shared Delphi::EVD::Types // // Базовые типы, используемые форматом EVD. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\EVD\evdDefine.inc} interface type TevIndentType = ( {* Выравнивание объекта по горизонтали. } ev_itLeft // по левому краю. , ev_itRight // по правому краю. , ev_itCenter // по центру. , ev_itWidth // по ширине. , ev_itPreformatted // "преформатированный". , ev_itNone );//TevIndentType TevPageOrientation = ( {* Ориентация страницы. } ev_poPortrait // книжная. , ev_poLandscape // альбомная. );//TevPageOrientation TevMergeStatus = ( {* признак объединения ячеек. } ev_msNone , ev_msHead , ev_msContinue );//TevMergeStatus TevVerticalAligment = ( {* Выравнивание объекта по вертикали. } ev_valTop , ev_valCenter , ev_valBottom );//TevVerticalAligment TevControlType = ( {* Тип контрола. } ev_ctLabel // метка с курсором в виде рамки , ev_ctEdit // обычный редактор , ev_ctCombo // выпадающий список , ev_ctButton // кнопка , ev_ctSpinedit // редактор с возможностью редактирования чисел , ev_ctCheckEdit // редактор с CheckBox , ev_ctEllipsesEdit // редактор с кнопкой , ev_ctRadioEdit // редактор с RadioButton , ev_ctCalEdit // редактор с выпадающим календарём , ev_ctCollapsedPanel // сворачивающая панель , ev_ctStateButton // кнопка с изменением состояния , ev_ctEmailEdit // редактор для ввода E-mail адреса (с проверкой) , ev_ctMemoEdit // многострочное поле ввода (не используется) , ev_ctPictureLabel // текст примечания с картинкой , ev_ctTextParaLabel // метка с обычным курсором , ev_ctPhoneEdit , ev_ctUnknown // неизвестный тип контрола );//TevControlType TevReqKind = ( {* Тип реквизита. } ev_rkSimple // обычный реквизит, допускающий редактировани (попадающий в модель) (ev_rkSimple). , ev_rkContext // контекстный атрибут, допускающий редактирование (попадающий в модель)(ev_rkContext). , ev_rkDescription // информационный атрибут (НЕ попадает в модель (ev_rkDescription). );//TevReqKind TevSubPlace = ( ev_spNoWhere , ev_spOnlyInContents , ev_spInContentsAndOnSubPanel , ev_spOnlyOnSubPanel );//TevSubPlace const { Hyperlink Const } CI_TOPIC = 65537; { для всех ссылок на документы } CI_BLOB = 65538; { для ссылок на двоичные объекты } CI_MULT = 65539; { для мультиссылок на документы/двоичные объекты } CI_REF = 65540; { для ссылок на внешние интернет-ресурсы } CI_FolderLink = 65544; CI_ExternalOperation = 65545; CI_PHARM_MULTI = 65547; { для мультиссылок на документы инфарма } CI_PIC = 65541; { для ссылок на внешние картинки } CI_SCRIPT = 65552; { Address Defaults } ev_NullAddressType = 0; ev_defAddressType = CI_TOPIC; type TevLinkViewKind = ( ev_lvkUnknown // Неизвестно , ev_lvkInternalValid // Внутри системы. Правильная , ev_lvkInternalInvalid // Внутри системы. На отсутствующую информацию , ev_lvkExternal // Наружу , ev_lvkInternalAbolished // Внутри системы. На утративший силу документ , ev_lvkInternalPreactive // Внутри системы. На не вступивший в силу документ , ev_lvkExternalENO // Внешнее приложение , ev_lvkInternalEdition // Редакция документа );//TevLinkViewKind const { Слои меток. } ev_sbtNone = 0; { несуществующий слой меток. } ev_sbtSub = 1; { слой Sub'ов. } ev_sbtMarker = 2; { слой закладок. } ev_sbtBookmark = 3; { слой именованных закладок (зарезервированно). } ev_sbtMark = 4; { слой вспомогательных значков (зарезервированно). } ev_sbtPara = 10; { параграф (псевдослой). } ev_sbtDocumentPlace = 11; { место в документе (псевдослой) см. [TevDocumentPlace]. } ev_sbtHyperlink = 12; { ссылка (псевдослой). } ev_sbtBySearcher = 14; { условие по Searcher'у (псевдослой). } type TevSubHandle = ev_sbtNone..ev_sbtBySearcher; {* Слои меток. } TevSubHandles = set of TevSubHandle; {* Слои меток. } TevDocumentPlace = ( {* Место в документе. } ev_dpNone // Нигде. , ev_dpEnd // В конце. );//TevDocumentPlace const { Sub Flags } ev_cUserCommentFlags = 2; { Флаги пользовательских комментариев } ev_cCommentsFlag = 1; { Флаги комментариев юристов } ev_cVersionCommentsFlag = 4; { Флаги версионных комментариев } type TevHFType = ( {* Тип колонтитула } evd_hftOrdinal , evd_hftLeft , evd_hftRight , evd_hftFirst );//TevHFType const ev_spInContents = [ev_spOnlyInContents, ev_spInContentsAndOnSubPanel]; {* Метка входит в оглавление } { Слои сегментов оформления } ev_slSuperposition = 0; { слой суперпозиции сегментов. } ev_slView = 1; { слой оформления. } ev_slHyperlinks = 2; { слой гиперссылок. } ev_slFoundWords = 3; { слой слов найденных по контексту. } ev_slFound = 4; { слой найденных слов (зарезервированно). } ev_slObjects = 5; { слой объектов, вставленных в параграф. } ev_slMistakes = 6; { слой сегментов для покраски опечаток. } ev_slDiff = 7; { Разница двух сравниваемых документов } type TevNormalSegLayerHandleP = ev_slView..ev_slMistakes; TevNormalSegLayerHandleSet = set of TevNormalSegLayerHandleP; const { Sub Const } POSITION_TYPE_PARA_ID = 2147483648; type TevBlockViewKind = ( ev_bvkNone , ev_bvkLeft , ev_bvkRight );//TevBlockViewKind implementation end.
// Original Author: Piotr Likus // Replace Components mapping list window unit GX_ReplaceCompMapList; interface uses Messages, Classes, Controls, Forms, ComCtrls, StdCtrls, ExtCtrls, Contnrs, ToolWin, ImgList, ActnList, GX_ReplaceCompData, GX_SharedImages, GX_ReplaceCompMapDets, GX_BaseForm; const UM_UPDATECOLS = WM_USER + 632; type TfmReplaceCompMapList = class(TfmBaseForm) pnlHeader: TPanel; lblGroup: TLabel; comGroupName: TComboBox; pnlMain: TPanel; pnlMappings: TPanel; lvMapItems: TListView; Actions: TActionList; actAdd: TAction; actEdit: TAction; actDelete: TAction; tbrReplacement: TToolBar; tbnAdd: TToolButton; tbnEdit: TToolButton; tbnDelete: TToolButton; actOpenGroupList: TAction; pnlToolSep: TPanel; tbrGroups: TToolBar; tbnGroups: TToolButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure comGroupNameChange(Sender: TObject); procedure btnOpenGroupListClick(Sender: TObject); procedure actAddExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure actDeleteExecute(Sender: TObject); procedure lvMapItemsDblClick(Sender: TObject); procedure lvMapItemsClick(Sender: TObject); procedure lvMapItemsColumnClick(Sender: TObject; Column: TListColumn); private FConfigData: TReplaceCompData; FSelectedGroup: string; FSortOnColumn: Integer; // counter from 1 (-1 means DESC) function ConfigurationKey: string; procedure LoadSettings; procedure SaveSettings; function SelectedGroupName: string; procedure LoadGroupList; procedure UpdateGroupSelection; procedure LoadMapList; procedure UpdateBtns; procedure UpdateColumnWidths; procedure UMUpdateCols(var Msg: TMessage); message UM_UPDATECOLS; function IsAllGroupSelected: Boolean; procedure AddMappingToListView(AMapItem: TCompRepMapItem); procedure RefreshAll; procedure ExecAdd(const GroupName: string); procedure ExecDelete; procedure ExecEdit(Item: TCompRepMapItem); function SelectedItem: TCompRepMapItem; function FindGroup(const GroupName: string): TCompRepMapGroupItem; function ExecDets(Item: TCompRepMapItem; DataAction: TDataAction): Boolean; procedure DeleteItem(Item: TCompRepMapItem); procedure RefreshItems; procedure LoadAll; procedure SortItems(ItemList: TObjectList; SortOnColumn: Integer); procedure AddItems(Group: TCompRepMapGroupItem; ItemList: TObjectList); procedure LoadItems(ItemList: TObjectList); public constructor Create(Owner: TComponent; ConfigData: TReplaceCompData); reintroduce; end; implementation uses SysUtils, Windows, Dialogs, Gx_GenericUtils, GX_ConfigurationInfo, GX_ReplaceCompMapGrpList; {$R *.dfm} resourcestring SAllItemsGroup = '< All groups >'; { TfmReplaceCompMapList } constructor TfmReplaceCompMapList.Create(Owner: TComponent; ConfigData: TReplaceCompData); begin inherited Create(Owner); FConfigData := ConfigData; FSortOnColumn := 1; LoadSettings; end; function TfmReplaceCompMapList.ConfigurationKey: string; begin Result := FConfigData.RootConfigurationKey + PathDelim + Self.ClassName + '\Window'; end; procedure TfmReplaceCompMapList.LoadSettings; var Settings: TGExpertsSettings; i: Integer; begin // Do not localize. Settings := TGExpertsSettings.Create; try Settings.LoadForm(Self, ConfigurationKey); FSelectedGroup := Settings.ReadString(ConfigurationKey, 'SelectedGrp', ''); // note: values < 0 are better stored as string FSortOnColumn := StrToIntDef(Settings.ReadString(ConfigurationKey, 'SortOnColumn', IntToStr(FSortOnColumn)), FSortOnColumn); for i := 0 to lvMapItems.Columns.Count-1 do lvMapItems.Columns[i].Width := Settings.ReadInteger(ConfigurationKey, 'Col'+IntToStr(i)+'.Width', lvMapItems.Columns[i].Width); finally FreeAndNil(Settings); end; EnsureFormVisible(Self); end; procedure TfmReplaceCompMapList.SaveSettings; var Settings: TGExpertsSettings; i: Integer; begin // Do not localize. Settings := TGExpertsSettings.Create; try if not (WindowState in [wsMinimized, wsMaximized]) then begin Settings.SaveForm(Self, ConfigurationKey); end; Settings.WriteString(ConfigurationKey, 'SelectedGrp', SelectedGroupName); // Note: Values < 0 are better stored as string Settings.WriteString(ConfigurationKey, 'SortOnColumn', IntToStr(FSortOnColumn)); for i := 0 to lvMapItems.Columns.Count-1 do Settings.WriteInteger(ConfigurationKey, 'Col'+IntToStr(i)+'.Width', lvMapItems.Columns[i].Width); finally FreeAndNil(Settings); end; end; procedure TfmReplaceCompMapList.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveSettings; end; procedure TfmReplaceCompMapList.FormCreate(Sender: TObject); begin SetToolbarGradient(tbrReplacement); SetToolbarGradient(tbrGroups); tbrGroups.Left := comGroupName.Left + comGroupName.Width + 4; tbrGroups.Top := comGroupName.Top; end; function TfmReplaceCompMapList.SelectedGroupName: string; begin if comGroupName.ItemIndex >= 0 then Result := comGroupName.Items[comGroupName.ItemIndex] else Result := ''; end; procedure TfmReplaceCompMapList.FormShow(Sender: TObject); begin comGroupName.ItemIndex := -1; LoadAll; end; procedure TfmReplaceCompMapList.RefreshItems; begin LoadMapList; UpdateBtns; end; procedure TfmReplaceCompMapList.LoadAll; begin LoadGroupList; UpdateGroupSelection; RefreshItems; end; procedure TfmReplaceCompMapList.RefreshAll; begin if (comGroupName.ItemIndex >= 0) and (Trim(comGroupName.Text)<>'') then FSelectedGroup := comGroupName.Text else FSelectedGroup := ''; LoadAll; end; procedure TfmReplaceCompMapList.LoadGroupList; var i: Integer; begin comGroupName.Items.Clear; comGroupName.Items.BeginUpdate; try for i := 0 to FConfigData.MapGroupList.Count-1 do comGroupName.Items.Add(FConfigData.MapGroupList[i].Name); comGroupName.Items.Insert(0, SAllItemsGroup); finally comGroupName.Items.EndUpdate; end; end; procedure TfmReplaceCompMapList.UpdateGroupSelection; begin if FSelectedGroup<>'' then comGroupName.ItemIndex := comGroupName.Items.IndexOf(FSelectedGroup) else if comGroupName.Items.Count > 0 then comGroupName.ItemIndex := 0; end; procedure TfmReplaceCompMapList.UpdateColumnWidths; begin PostMessage(Self.Handle, UM_UPDATECOLS, 0, 0) end; function TfmReplaceCompMapList.IsAllGroupSelected: Boolean; begin Result := (SelectedGroupName = SAllItemsGroup); end; procedure TfmReplaceCompMapList.LoadMapList; var i, Idx: Integer; ItemList: TObjectList; begin lvMapItems.Items.BeginUpdate; try lvMapItems.Items.Clear; ItemList := TObjectList.Create; try ItemList.OwnsObjects := False; if IsAllGroupSelected then begin for i := 0 to FConfigData.MapGroupList.Count-1 do AddItems(FConfigData.MapGroupList[i], ItemList); end else begin Idx := FConfigData.MapGroupList.IndexOf(SelectedGroupName); if Idx >= 0 then AddItems(FConfigData.MapGroupList[Idx], ItemList); end; SortItems(ItemList, FSortOnColumn); LoadItems(ItemList); finally FreeAndNil(ItemList); end; UpdateColumnWidths; lvMapItems.Invalidate; finally lvMapItems.Items.EndUpdate; end; end; procedure TfmReplaceCompMapList.AddItems(Group: TCompRepMapGroupItem; ItemList: TObjectList); var i: Integer; begin for i := 0 to Group.Items.Count-1 do ItemList.Add(Group.Items[i]); end; procedure TfmReplaceCompMapList.SortItems(ItemList: TObjectList; SortOnColumn: Integer); var SortedItemList: TStringList; i: Integer; NativeItem: TCompRepMapItem; ColumnText: string; AbsSortColumn: Integer; begin Assert(not ItemList.OwnsObjects); AbsSortColumn := Abs(SortOnColumn); SortedItemList := TStringList.Create; try SortedItemList.Sorted := True; SortedItemList.Duplicates := dupAccept; for i := 0 to ItemList.Count-1 do begin NativeItem := (ItemList[i] as TCompRepMapItem); case AbsSortColumn of 2: ColumnText := NativeItem.SourceText; 3: ColumnText := NativeItem.DestText; else ColumnText := NativeItem.GroupName; end; SortedItemList.AddObject(ColumnText, NativeItem); end; ItemList.Clear; if AbsSortColumn <> SortOnColumn then begin for i :=SortedItemList.Count-1 downto 0 do ItemList.Add(SortedItemList.Objects[i]) end else begin for i := 0 to SortedItemList.Count-1 do ItemList.Add(SortedItemList.Objects[i]); end; finally FreeAndNil(SortedItemList); end; end; procedure TfmReplaceCompMapList.LoadItems(ItemList: TObjectList); var i: Integer; begin for i := 0 to ItemList.Count-1 do AddMappingToListView(ItemList[i] as TCompRepMapItem); end; procedure TfmReplaceCompMapList.AddMappingToListView(AMapItem: TCompRepMapItem); var ListItem: TListItem; begin ListItem := lvMapItems.Items.Add; ListItem.Caption := AMapItem.GroupName; ListItem.SubItems.Add(AMapItem.SourceText); ListItem.SubItems.Add(AMapItem.DestText); ListItem.Data := AMapItem; end; procedure TfmReplaceCompMapList.UpdateBtns; begin actEdit.Enabled := (lvMapItems.SelCount = 1); actDelete.Enabled := (lvMapItems.SelCount > 0); actAdd.Enabled := (SelectedGroupName<>''); end; procedure TfmReplaceCompMapList.UMUpdateCols(var Msg: TMessage); begin // Hacks to get the listview columns sizing right on startup lvMapItems.Width := lvMapItems.Width + 1; end; procedure TfmReplaceCompMapList.comGroupNameChange(Sender: TObject); begin LoadMapList; end; procedure TfmReplaceCompMapList.btnOpenGroupListClick(Sender: TObject); var Dlg: TfmReplaceCompMapGrpList; begin Dlg := TfmReplaceCompMapGrpList.Create(nil, FConfigData); try Dlg.Icon := Self.Icon; if Dlg.ShowModal = mrOK then FConfigData.SaveData else FConfigData.ReloadData; RefreshAll; finally FreeAndNil(Dlg); end; end; procedure TfmReplaceCompMapList.actAddExecute(Sender: TObject); begin if IsAllGroupSelected then ExecAdd('') else ExecAdd(SelectedGroupName); end; function TfmReplaceCompMapList.FindGroup(const GroupName: string): TCompRepMapGroupItem; begin Result := FConfigData.MapGroupList.FindObject(GroupName) as TCompRepMapGroupItem; end; function TfmReplaceCompMapList.ExecDets(Item: TCompRepMapItem; DataAction: TDataAction): Boolean; var Dlg: TfmReplaceCompMapDets; begin Dlg := TfmReplaceCompMapDets.Create(nil, FConfigData, Item, DataAction); try Dlg.Icon := Self.Icon; Result := Dlg.Execute; if Result then begin FConfigData.SaveData; RefreshAll; end; finally FreeAndNil(Dlg); end; end; procedure TfmReplaceCompMapList.ExecAdd(const GroupName: string); var Item: TCompRepMapItem; begin Item := TCompRepMapItem.Create; try if GroupName <> '' then Item.Group := FindGroup(GroupName); if ExecDets(Item, daInsert) then RefreshItems; except FreeAndNil(Item); end; end; procedure TfmReplaceCompMapList.ExecEdit(Item: TCompRepMapItem); begin if ExecDets(Item, daEdit) then RefreshItems; end; procedure TfmReplaceCompMapList.DeleteItem(Item: TCompRepMapItem); begin if Assigned(Item) then begin Item.Group.ExtractItem(Item); FreeAndNil(Item); end; end; procedure TfmReplaceCompMapList.ExecDelete; var i: Integer; begin for i := lvMapItems.Items.Count-1 downto 0 do if lvMapItems.Items[i].Selected then DeleteItem(TCompRepMapItem(lvMapItems.Items[i].Data)); ListViewDeleteSelected(lvMapItems); end; function TfmReplaceCompMapList.SelectedItem: TCompRepMapItem; begin if lvMapItems.SelCount <> 1 then Result := nil else Result := TCompRepMapItem(lvMapItems.Selected.Data); end; procedure TfmReplaceCompMapList.actEditExecute(Sender: TObject); var Item: TCompRepMapItem; begin Item := SelectedItem; if Assigned(Item) then ExecEdit(Item); end; procedure TfmReplaceCompMapList.actDeleteExecute(Sender: TObject); resourcestring SConfirmDelete = 'Are you sure you want to delete selected item(s)?'; begin if MessageDlg(SConfirmDelete, mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin ExecDelete; RefreshItems; end; end; procedure TfmReplaceCompMapList.lvMapItemsDblClick(Sender: TObject); begin if actEdit.Enabled then actEdit.Execute; end; procedure TfmReplaceCompMapList.lvMapItemsClick(Sender: TObject); begin UpdateBtns; end; procedure TfmReplaceCompMapList.lvMapItemsColumnClick(Sender: TObject; Column: TListColumn); var i: Integer; Cursor: IInterface; begin i := Column.Index; if i >= 0 then begin Cursor := TempHourGlassCursor; Inc(i); if Abs(FSortOnColumn) = i then FSortOnColumn := -FSortOnColumn else FSortOnColumn := i; RefreshAll; end; end; end.
unit Fichas; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ActnList, Menus, ComCtrls, ExtCtrls, ImgList, Db, DBTables, StdActns, DBActns, ToolWin, StdCtrls, Grids, Wwdbigrd, Wwdbgrid, Buttons, wwdblook, JvFormPlacement, JvComponentBase, ADODB, System.Actions; const csVALIDAR = 'Por favor complete TEJEDOR, ARTICULO y CANTIDAD' + #13 + ' Son datos obligatorios '; type TEstado = ( teNuevo, teEdit, teInac ); TFFichas = class(TForm) MainMenu1: TMainMenu; ImageList1: TImageList; ActionList1: TActionList; StatusBar1: TStatusBar; Ventana1: TMenuItem; Salir: TAction; Imprimir: TAction; DataSetDelete1: TDataSetDelete; DataSetEdit1: TDataSetEdit; DataSetFirst1: TDataSetFirst; DataSetInsert1: TDataSetInsert; DataSetLast1: TDataSetLast; DataSetNext1: TDataSetNext; DataSetPrior1: TDataSetPrior; DataSetRefresh1: TDataSetRefresh; EditCopy1: TEditCopy; EditCut1: TEditCut; EditPaste1: TEditPaste; Editar1: TMenuItem; Salir1: TMenuItem; Copiar1: TMenuItem; Cortar1: TMenuItem; Pegar1: TMenuItem; Navegar1: TMenuItem; Primero1: TMenuItem; Anterior1: TMenuItem; Siguiente1: TMenuItem; Ultimo1: TMenuItem; N1: TMenuItem; Borrar1: TMenuItem; Ayuda1: TMenuItem; Ayuda: TAction; Ayuda2: TMenuItem; Panel1: TPanel; ScrollBox1: TScrollBox; CoolBar1: TCoolBar; PageScroller1: TPageScroller; ToolBar1: TToolBar; ToolButton1: TToolButton; DFichas: TDataSource; Grilla: TwwDBGrid; LookTeje: TwwDBLookupCombo; LookMaqu: TwwDBLookupCombo; LookArti: TwwDBLookupCombo; LookOper: TwwDBLookupCombo; LookVuelta: TwwDBLookupCombo; N2: TMenuItem; IngTeje: TAction; Maquinas: TAction; Opera: TAction; Tejedores1: TMenuItem; Maquinas1: TMenuItem; Operarios1: TMenuItem; PopupMenu1: TPopupMenu; Tejedores2: TMenuItem; Operarios2: TMenuItem; Maquinas2: TMenuItem; Cancela: TAction; Grabar: TAction; Editar: TAction; SelFec: TAction; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; ToolButton5: TToolButton; ToolButton6: TToolButton; ToolButton7: TToolButton; N3: TMenuItem; SeleccionarFechas1: TMenuItem; LookColor: TwwDBLookupCombo; AnulalaEdicion1: TMenuItem; Grabar1: TMenuItem; ToolButton8: TToolButton; ToolButton9: TToolButton; ToolButton10: TToolButton; ToolButton11: TToolButton; ToolButton12: TToolButton; ToolButton13: TToolButton; JvFormPlacement1: TJvFormStorage; QIngFich: TADOQuery; QIngFichFECHA: TDateTimeField; QIngFichTURNO: TSmallintField; QIngFichMAQUINA: TStringField; QIngFichTEJEDOR: TStringField; QIngFichARTICULO: TStringField; QIngFichCOLOR: TStringField; QIngFichCANTIDAD: TFloatField; QIngFichSEGUNDA: TFloatField; QIngFichCOSTURA: TFloatField; QIngFichNOMBRE: TStringField; QIngFichVUELTA: TStringField; QIngFichNUMERO: TAutoIncField; procedure SalirExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormActivate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure IngTejeExecute(Sender: TObject); procedure MaquinasExecute(Sender: TObject); procedure OperaExecute(Sender: TObject); procedure SelFecExecute(Sender: TObject); procedure QIngFichBeforePost(DataSet: TDataSet); procedure QIngFichNewRecord(DataSet: TDataSet); procedure QIngFichAfterPost(DataSet: TDataSet); procedure GrabarExecute(Sender: TObject); procedure CancelaExecute(Sender: TObject); procedure GrillaKeyPress(Sender: TObject; var Key: Char); private { Private declarations } Turno: integer; FFFin: TDateTime; FFIni, FFecha: TDateTime; procedure Requery; procedure SetFFin(const Value: TDateTime); procedure SetFIni(const Value: TDateTime); procedure SetearSesion; // procedure NuevoTurno; public { Public declarations } procedure EnHint( Sender: TObject ); property FIni: TDateTime read FFIni write SetFIni; property FFin: TDateTime read FFFin write SetFFin; end; var FFichas: TFFichas; implementation uses SelFechas, DataMod, IngTeje, IngMaqu, IngOper, Main, Utiles; {$R *.DFM} procedure TFFichas.SalirExecute(Sender: TObject); begin Close; end; procedure TFFichas.FormClose(Sender: TObject; var Action: TCloseAction); begin Application.OnHint := nil; with Dm do begin TArti.Close; QSelTeje.Close; QSelMaqu.Close; QSelOper.Close; QSelColor.Close; end; end; procedure TFFichas.EnHint(Sender: TObject); begin StatusBar1.SimpleText := Application.Hint; end; procedure TFFichas.FormActivate(Sender: TObject); begin Application.OnHint := EnHint; end; procedure TFFichas.FormCreate(Sender: TObject); begin SetearSesion; with Dm do begin TArti.Open; QSelTeje.open; QSelMaqu.open; QSelOper.open; QSelColor.Open; end; FFIni := date-1; FFFin := date-1; FFecha := FFIni; Requery; end; procedure TFFichas.Requery; begin with QIngFich do try DisableControls; Close; parameters.paramByName( 'FECI' ).value := FIni; parameters.paramByName( 'FECF' ).value := FFin; Open; finally EnableControls; end; end; procedure TFFichas.IngTejeExecute(Sender: TObject); begin Screen.Cursor := crHourGlass; FIngTeje := TFIngTeje.create( application ); try FIngTeje.ShowModal; finally FIngTeje.free; Screen.Cursor := crDefault; end; end; procedure TFFichas.MaquinasExecute(Sender: TObject); begin Screen.Cursor := crHourGlass; FIngMaqu := TFIngMaqu.create( application ); try FIngMaqu.ShowModal; finally FIngMaqu.free; Screen.Cursor := crDefault; end; end; procedure TFFichas.OperaExecute(Sender: TObject); begin Screen.Cursor := crHourGlass; FIngOper := TFIngOper.create( application ); try FIngOper.ShowModal; finally FIngOper.free; Screen.Cursor := crDefault; end; end; procedure TFFichas.SetFFin(const Value: TDateTime); begin FFFin := Value; end; procedure TFFichas.SetFIni(const Value: TDateTime); begin FFIni := Value; end; procedure TFFichas.SelFecExecute(Sender: TObject); begin with TSelFechasDlg.create( application ) do try FecIni.date := FFIni; FecFin.date := FFFin; ShowModal; if ModalResult = mrOK then begin FFIni := Fecini.date; FFFin := FecFin.date; Requery; end; finally free; Screen.Cursor := crDefault; end; end; procedure TFFichas.QIngFichBeforePost(DataSet: TDataSet); begin if QIngFICHMAQUINA.value = '' then raise exception.create( 'Por favor, seleccione MAQUINA' ); if ( QIngFICHTEJEDOR.value = '' ) or ( QIngFICHARTICULO.value = '' ) or ( QIngFICHCANTIDAD.value = 0 ) or ( QIngFICHFECHA.value = 0 ) or ( QIngFICHTURNO.value < 1 ) or ( QIngFICHTURNO.value > 3 ) then raise exception.create( csVALIDAR ); end; procedure TFFichas.QIngFichNewRecord(DataSet: TDataSet); begin QIngFichSEGUNDA.value := 0; QIngFichFECHA.value := FFecha; QIngFichTURNO.value := Turno; Grilla.SelectedIndex := 0; end; procedure TFFichas.QIngFichAfterPost(DataSet: TDataSet); begin FFecha := QIngFichFECHA.value; Turno := QIngFichTURNO.value; end; procedure TFFichas.GrabarExecute(Sender: TObject); begin QIngFich.post; end; procedure TFFichas.CancelaExecute(Sender: TObject); begin QIngFich.Cancel; end; procedure TFFichas.GrillaKeyPress(Sender: TObject; var Key: Char); begin if Key in [ ',','.' ] then Key := Utiles.decimalSeparator; end; procedure TFFichas.SetearSesion; begin end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} (* Version History 12/05/2002 Fixed formatting of time in countdown mode *) unit ElClock; interface uses Windows, Messages, SysUtils, Classes, Controls, ExtCtrls, ElTools, ElList, ElStrUtils, Graphics, ElPanel, {$ifdef VCL_6_USED} Types, {$endif} Menus; type TElClock = class(TElPanel) protected FTimerPaused : Boolean; FStartTime : TDateTime; FPauseTime : TDateTime; FIsTimer : Boolean; FTimerActive : Boolean; FShowDate : Boolean; FShowHint : boolean; FTimer : TTimer; FTZone : TTImeZoneInformation; FLocal : Boolean; FSeconds : boolean; FAMPM : boolean; FCaption : string; FUseBias : Boolean; FBias : Integer; FShowWeekDay : Boolean; FUseCustomFormat : Boolean; FCustomFormat : string; FShowDaysInTimer : Boolean; FCountdownActive : Boolean; FOnCountdownDone : TNotifyEvent; FOnCountdownTick : TNotifyEvent; FCountdownPaused : Boolean; FCountdownTime : Integer; FSaveCDTime : Integer; FIsCountdown : boolean; FDummyStr : TElFString; procedure SetIsCountdown(newValue : boolean); procedure SetCountdownTime(newValue : Integer); procedure SetCountdownPaused(newValue : Boolean); procedure SetCountdownActive(newValue : Boolean); procedure SetShowDaysInTimer(newValue : Boolean); procedure SetUseCustomFormat(newValue : Boolean); procedure SetCustomFormat(newValue : string); procedure SetShowWeekDay(newValue : Boolean); procedure SetUseBias(newValue : Boolean); procedure SetBias(newValue : Integer); function GetTimer : boolean; procedure SetTimer(value : boolean); procedure OnTimer(Sender : TObject); procedure WMMouseMove(var Msg : TWMMouseMove); message WM_MOUSEMOVE; procedure WMLButtonDown(var Msg : TMessage); message WM_LBUTTONDOWN; procedure WMLButtonUp(var Msg : TWMLButtonUp); message WM_LBUTTONUP; procedure SetShowDate(newValue : Boolean); procedure SetShowHint(newValue : Boolean); procedure SetIsTimer(newValue : Boolean); function GetTimeElapsed : TDateTime; procedure SetTimerActive(newValue : Boolean); procedure SetTimerPaused(newValue : Boolean); procedure CreateTimer; procedure PaintBorders(Canvas : TCanvas; var R : TRect); procedure Paint; override; procedure InheritedPaint; procedure TriggerCountdownDoneEvent; virtual; procedure TriggerCountdownTickEvent; virtual; {$ifdef VCL_4_USED} function CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; override; {$endif} public { Public declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure Kick; virtual; procedure GetTime(var Time : TSystemTime); virtual; procedure ResetTimer; property TimeElapsed : TDateTime read GetTimeElapsed; property TimeZone : TTimeZoneInformation read FTZone write FTZone; published property Caption: TElFString read FDummyStr; property LocalTime : boolean read FLocal write FLocal default true; property ShowWeekDay : Boolean read FShowWeekDay write SetShowWeekDay; property ShowSeconds : boolean read FSeconds write FSeconds; property ShowDate : Boolean read FShowDate write SetShowDate; { Published } property AM_PM : boolean read FAMPM write FAMPM; property Labels : boolean read FShowHint write SetShowHint; property UseBias : Boolean read FUseBias write SetUseBias; property Bias : Integer read FBias write SetBias; property UseCustomFormat : Boolean read FUseCustomFormat write SetUseCustomFormat; property CustomFormat : string read FCustomFormat write SetCustomFormat; property IsTimer : Boolean read FIsTimer write SetIsTimer; property TimerActive : Boolean read FTimerActive write SetTimerActive; property TimerPaused : Boolean read FTimerPaused write SetTimerPaused default False; property ShowDaysInTimer : Boolean read FShowDaysInTimer write SetShowDaysInTimer; property IsCountdown : boolean read FIsCountdown write SetIsCountdown; property CountdownTime : Integer read FCountdownTime write SetCountdownTime; property CountdownActive : Boolean read FCountdownActive write SetCountdownActive; property CountdownPaused : Boolean read FCountdownPaused write SetCountdownPaused; property UseTimer : Boolean read GetTimer write SetTimer default true; property OnCountdownDone : TNotifyEvent read FOnCountdownDone write FOnCountdownDone; property OnCountdownTick : TNotifyEvent read FOnCountdownTick write FOnCountdownTick; property Align; property Alignment; property BevelInner default bvLowered; property BevelOuter default bvRaised; property BevelWidth; property BorderWidth; property BorderStyle; property Color; property Ctl3D; property Cursor; property Font; property Hint; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property OnClick; property OnDblClick; property OnMouseMove; property OnMouseDown; property OnMouseUp; property OnDragOver; property OnDragDrop; property OnEndDrag; property OnStartDrag; property OnResize; {$IFDEF VCL_4_USED} property Anchors; property Action; property Constraints; property DockOrientation; property Floating; property BevelKind; property DoubleBuffered; property DragKind; {$ENDIF} private end; type PShortTZ = ^TShortTZ; TShortTZ = packed record Bias, StandardBias, DayLightBias : LongInt; wReserved1, // year field StdMonth, StdDayOfWeek, StdDay, StdHour, StdMinute, StdSecond, wReserved2, // msec field wReserved3, // year field DLMonth, DLDayOfWeek, DLDay, DLHour, DLMinute, DLSecond, wReserved4 // msec field : word; end; PTimeZoneInfo = ^TTimeZoneInfo; TTimeZoneInfo = record KeyName : string; DisplayName : string; DltName : string; StdName : string; MapID : string; TimeZone : TTimeZoneInformation; STimeZone : TShortTZ; end; function RetrieveTimeZoneInfo(TimeZoneInfoList : TElList) : boolean; procedure ShortTZToTimeZoneInfo(ShortTZ : TShortTZ; var TZInfo : TTimeZoneInfo); function TranslateTZDate(ADate : TSystemTime) : string; var FDL : boolean; SysTimeZones : TElList; implementation uses ElVCLUtils; constructor TElClock.Create(AOwner : TComponent); begin inherited; BevelInner := bvLowered; BevelOuter := bvRaised; FLocal := true; UseTimer := true; FCustomFormat := 'DD xx'; end; destructor TElClock.Destroy; begin if FTimer <> nil then begin FTimer.Free; FTimer := nil; end; inherited; end; procedure TElClock.GetTime(var Time : TSystemTime); var LocalTime : TSystemTime; begin if FLocal then GetLocalTime(Time) else begin GetSystemTime(LocalTime); Time := LocalTime; UTCToZoneLocal(@FTZone, LocalTime, Time); if UseBias then DateTimeToSystemTime(IncTime(SystemTimeToDateTime(Time), 0, FBias, 0, 0), Time); end; end; procedure TElClock.Kick; var CurTime : TSystemTime; Buffer : pchar; s, s1, s2 : string; DT : TDateTime; begin {$ifdef VCL_4_USED} if HandleAllocated then AdjustSize; {$endif} if IsTimer then begin if FTimerActive then begin if FTimerPaused then DT := FPauseTime - FStartTime else DT := Now - FStartTime; end else begin DT := 0; end; if ShowDaysInTimer then begin FCaption := IntToStr(Round(DT)) + '.'; end else begin FCaption := ''; end; FCaption := FCaption + TimeToStr(Frac(DT)); Repaint; exit; end else if IsCountDown then begin if FCountdownActive then begin if FCountdownPaused then DT := FStartTime - FPauseTime else begin DT := FStartTime - Now; end; FCountDownTime := Trunc(DT * 86400); if not FCountDownPaused then TriggerCountdownTickEvent; if (DT = 0) or (Now > FStartTime) then begin TriggerCountdownDoneEvent; CountdownActive := false; end; end else DT := CountdownTime / 86400; FCaption := FormatDateTime('hh:nn:ss', Frac(DT)); Invalidate; exit; end; GetMem(Buffer, 100); GetTime(CurTime); if UseCustomFormat then begin DT := SystemTimeToDateTime(CurTime); FCaption := ElTools.GetFormattedTimeString(DT, CustomFormat); end else begin if not FAMPM then begin s := IntToStr(CurTime.wHour); if Length(s) = 1 then S2 := '0' + s else S2 := s; s := IntToStr(CurTime.wMinute); if Length(s) = 1 then S2 := S2 + ':0' + s else S2 := S2 + ':' + s; if ShowSeconds then begin s := IntToStr(CurTime.wSecond); if Length(s) = 1 then S2 := S2 + ':0' + s else S2 := S2 + ':' + s; end; end else begin s := IntToStr(CurTime.wHour mod 12); if CurTime.wHour = 0 then s := '12'; S2 := s; s := IntToStr(CurTime.wMinute); if Length(s) = 1 then S2 := S2 + ':0' + s else S2 := S2 + ':' + s; if ShowSeconds then begin s := IntToStr(CurTime.wSecond); if Length(s) = 1 then S2 := S2 + ':0' + s else S2 := S2 + ':' + s; end; if (CurTime.wHour div 12 = 0) then S2 := S2 + ' AM' else S2 := S2 + ' PM'; end; GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, @CurTime, nil, Buffer, 100); S1 := StrPas(Buffer); if FPressed then FCaption := S1 else begin if FShowWeekDay then CurTime.wDayOfWeek := SysUtils.DayOfWeek(SystemTimeToDateTime(CurTime)) - 1; if FShowWeekDay and FShowDate then S1 := ShortDayNames[CurTime.wDayOfWeek + 1] + ', ' + S1; FCaption := S2; if FShowDate then FCaption := FCaption + #13#10 + S1; if FShowWeekDay and (not FShowDate) then FCaption := FCaption + #13#10 + LongDayNames[CurTime.wDayOfWeek + 1]; end; end; if Labels then FCaption := FCaption + #13#10 + Hint; FreeMem(Buffer, 100); end; procedure TElClock.OnTimer(Sender : TObject); begin if FIsTimer then begin if (not FTimerPaused) and FTimerActive then Kick; end else Kick; Repaint; end; procedure TElClock.CreateTimer; begin FTimer := TTimer.Create(self); FTimer.Interval := 1000; FTimer.OnTimer := OnTimer; FTimer.Enabled := true; end; function TElClock.GetTimer : boolean; begin result := Assigned(FTimer); end; procedure TElClock.SetTimer(value : boolean); begin if value <> Assigned(FTimer) then begin if value then CreateTimer else begin FTimer.Free; FTimer := nil; end; end; end; procedure TElClock.WMLButtonDown(var Msg : TMessage); { private } begin inherited; if (not ShowDate) then begin Kick; Repaint; end; end; { WMLButtonDown } procedure TElClock.WMLButtonUp(var Msg : TWMLButtonUp); { private } begin inherited; Kick; Repaint; end; { WMLButtonUp } procedure TElClock.SetShowHint(newValue : Boolean); begin if (FShowHint <> newValue) then begin FShowHint := newValue; Kick; Repaint; end; { if } end; { SetShowDate } procedure TElClock.SetShowDate(newValue : Boolean); begin if (FShowDate <> newValue) then begin FShowDate := newValue; Kick; Repaint; end; { if } end; { SetShowDate } procedure TElClock.PaintBorders(Canvas : TCanvas; var R : TRect); var TopColor, BottomColor : TColor; const Alignments : array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER); procedure AdjustColors(Bevel : TPanelBevel); begin TopColor := clBtnHighlight; if Bevel = bvLowered then TopColor := clBtnShadow; BottomColor := clBtnShadow; if Bevel = bvLowered then BottomColor := clBtnHighlight; end; begin if BevelOuter <> bvNone then begin AdjustColors(BevelOuter); Frame3D(Canvas, R, TopColor, BottomColor, BevelWidth); end; Frame3D(Canvas, R, Color, Color, BorderWidth); if BevelInner <> bvNone then begin AdjustColors(BevelInner); Frame3D(Canvas, R, TopColor, BottomColor, BevelWidth); end; end; procedure TElClock.InheritedPaint; begin inherited Paint; end; procedure TElClock.Paint; { public } var R : TRect; AL : integer; begin inherited; R := ClientRect; if BevelInner <> bvNone then InflateRect(R, -BevelWidth, -BevelWidth); if BevelOuter <> bvNone then InflateRect(R, -BevelWidth, -BevelWidth); Canvas.Brush.Style := bsClear; case Alignment of taCenter : AL := DT_CENTER; taRightJustify : AL := DT_RIGHT; else AL := DT_LEFT; end; if Pos(#13#10, FCaption) = 0 then AL := AL or DT_SINGLELINE; DrawText(Canvas.Handle, PChar(FCaption), -1, R, DT_VCENTER or DT_NOCLIP or DT_EXPANDTABS or DT_NOPREFIX or AL); end; { Paint } procedure TElClock.SetIsTimer(newValue : Boolean); begin if (FIsTimer <> newValue) then begin FIsTimer := newValue; if FIsTimer then begin FStartTime := Now; isCountdown := false; end; end; {if} Kick; Repaint; end; function TElClock.GetTimeElapsed : TDateTime; begin result := Now - FStartTime; end; procedure TElClock.SetTimerActive(newValue : Boolean); begin if (FTimerActive <> newValue) then begin FTimerActive := newValue; ResetTimer; end; {if} if IsTimer then begin Kick; Repaint; end; end; procedure TElClock.ResetTimer; begin FStartTime := Now; FPauseTime := FStartTime; Kick; Repaint; end; procedure TElClock.SetTimerPaused(newValue : Boolean); begin if (FTimerPaused <> newValue) then begin FTimerPaused := newValue; if NewValue then begin FPauseTime := Now; end else begin FStartTime := FStartTime + (Now - FPauseTime); Kick; Repaint; end; end; end; {SetTimerPaused} procedure TElClock.SetUseBias(newValue : Boolean); begin if (FUseBias <> newValue) then begin FUseBias := newValue; if not IsTimer then begin Kick; Repaint; end; end; {if} end; procedure TElClock.SetBias(newValue : Integer); begin if (FBias <> newValue) then begin FBias := newValue; if not IsTimer then begin Kick; Repaint; end; end; {if} end; procedure TElClock.SetShowWeekDay(newValue : Boolean); begin if (FShowWeekDay <> newValue) then begin FShowWeekDay := newValue; if FShowDate then begin Kick; Repaint; end; end; {if} end; {SetShowWeekDay} procedure TElClock.SetUseCustomFormat(newValue : Boolean); begin if (FUseCustomFormat <> newValue) then begin FUseCustomFormat := newValue; Kick; Repaint; end; {if} end; {SetUseCustomFormat} procedure TElClock.SetCustomFormat(newValue : string); begin if (FCustomFormat <> newValue) then begin FCustomFormat := newValue; Kick; Repaint; end; {if} end; {SetCustomFormat} procedure TElClock.SetShowDaysInTimer(newValue : Boolean); begin if (FShowDaysInTimer <> newValue) then begin FShowDaysInTimer := newValue; if FIsTimer then begin Kick; Repaint; end; end; {if} end; procedure TElClock.SetIsCountdown(newValue : boolean); begin if (FIsCountdown <> newValue) then begin FIsCountdown := newValue; if FIsCountdown then begin FStartTime := Now + CountdownTime / 86400; IsTimer := false; end; Kick; Repaint; end; {if} end; procedure TElClock.SetCountdownTime(newValue : Integer); begin if (FCountdownTime <> newValue) then begin FCountdownTime := newValue; FSaveCDTime := FCountdownTime; FStartTime := Now + CountdownTime / 86400; end; {if} end; procedure TElClock.SetCountdownPaused(newValue : Boolean); begin if (FCountdownPaused <> newValue) then begin FCountdownPaused := newValue; if NewValue then begin FPauseTime := Now; end else begin FStartTime := FStartTime + (Now - FPauseTime); Kick; Repaint; end; end; {if} end; procedure TElClock.TriggerCountdownDoneEvent; begin if (assigned(FOnCountdownDone)) then FOnCountdownDone(Self); CountdownTime := FSaveCDTime; end; procedure TElClock.SetCountdownActive(newValue : Boolean); begin if (FCountdownActive <> newValue) then begin if newValue then begin FStartTime := Now + CountdownTime / 86400; FSaveCDTime := CountdownTime; end else CountdownTime := FSaveCDTime; FCountdownActive := newValue; Kick; Repaint; end; {if} end; procedure TElClock.TriggerCountdownTickEvent; { Triggers the OnCountdownTick event. This is a virtual method (descendants of this component can override it). } begin if (assigned(FOnCountdownTick)) then FOnCountdownTick(Self); end; { TriggerCountdownTickEvent } procedure TElClock.WMMouseMove(var Msg : TWMMouseMove); { private } var b : boolean; begin b := Movable and FPressed; inherited; if b then begin Kick; Repaint; end; end; { WMMouseMove } {$ifdef VCL_4_USED} function TElClock.CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; var R : TRect; AL : integer; x, y : integer; begin if HandleAllocated then begin SetRectEmpty(R); Canvas.Brush.Style := bsClear; case Alignment of taCenter : AL := DT_CENTER; taRightJustify : AL := DT_RIGHT; else AL := DT_LEFT; end; if Pos(#13#10, FCaption) = 0 then AL := AL or DT_SINGLELINE; DrawText(Canvas.Handle, PChar(FCaption), -1, R, DT_CALCRECT or DT_VCENTER or DT_NOCLIP or DT_EXPANDTABS or DT_NOPREFIX or AL); x := R.Right - R.Left + 2; y := R.Bottom - R.Top + 2; if BevelInner <> bvNone then begin inc(x, BevelWidth); inc(y, BevelWidth); end; if BevelOuter <> bvNone then begin inc(x, BevelWidth); inc(y, BevelWidth); end; NewWidth := x; NewHeight := y; end; Result := True; end; {$endif} procedure ShortTZToTimeZoneInfo(ShortTZ : TShortTZ; var TZInfo : TTimeZoneInfo); begin TZInfo.TimeZone.Bias := ShortTZ.Bias; TZInfo.TimeZone.StandardBias := ShortTZ.StandardBias; TZInfo.TimeZone.DaylightBias := ShortTZ.DaylightBias; MoveMemory(@TZInfo.TimeZone.StandardDate, @(ShortTZ.wReserved1), sizeof(TSystemTime)); MoveMemory(@TZInfo.TimeZone.DaylightDate, @(ShortTZ.wReserved3), sizeof(TSystemTime)); end; function TranslateTZDate(ADate : TSystemTime) : string; const ACounts : array[1..5] of string = ('First', 'Second', 'Third', 'Fourth', 'Last'); ADays : array[0..6] of string = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); AMonthes : array[1..12] of string = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); begin result := ACounts[ADate.wDay] + ' ' + ADays[ADate.wDayOfWeek] + ' of ' + AMonthes[ADate.wMonth] + ' at ' + TimeToStr(EncodeTime(ADate.wHour, ADate.wMinute, ADate.wSecond, 0)); end; function RetrieveTimeZoneInfo; type PByte = ^byte; var KeyStr, SubKeyStr : string; Key, SubKey : HKey; ptz : PTimeZoneInfo; res : DWORD; i : integer; b1 : PChar; b2 : PByte; bufsize : DWORD; atime : TFileTime; begin {$IFDEF ZONE_DEBUG} MessageBox(0, PChar('Reading time zones'), nil, 0); {$ENDIF} result := false; try if IsWinNT then KeyStr := 'Software\Microsoft\Windows NT\CurrentVersion\Time Zones' else KeyStr := 'Software\Microsoft\Windows\CurrentVersion\Time Zones'; if RegOpenKeyEx(HKEY_LOCAL_MACHINE, pchar(KeyStr), 0, KEY_READ, Key) <> ERROR_SUCCESS then begin MessageBox(0, 'Failed to open TimeZone key', '', 0); exit; end; i := 0; repeat New(PTZ); GetMem(b1, 100); BufSize := 100; res := RegEnumKeyEx(Key, i, b1 {key name}, BufSize, nil, nil, nil, @atime); if res = ERROR_SUCCESS then begin PTZ.KeyName := StrPas(B1); SubKeyStr := PTZ.KeyName; if RegOpenKeyEx(Key, PChar(SubKeyStr), 0, KEY_READ, SubKey) = ERROR_SUCCESS then begin GetMem(b2, 100); BufSize := 100; if RegQueryValueEx(SubKey, 'MapID', nil, nil, @(byte(B2^)), @BufSize) = ERROR_SUCCESS then PTZ.MapID := StrPas(PChar(B2)) else begin {$IFDEF ZONE_DEBUG} MessageBox(0, PChar('Failed to retrieve MapID of this zone: ' + SubKeyStr), nil, 0); {$ENDIF} end; BufSize := 100; if RegQueryValueEx(SubKey, 'Display', nil, nil, @(byte(B2^)), @BufSize) = ERROR_SUCCESS then PTZ.DisplayName := StrPas(PChar(B2)) else begin {$IFDEF ZONE_DEBUG} MessageBox(0, PChar('Failed to retrieve Display of this zone: ' + SubKeyStr), nil, 0); {$ENDIF} end; BufSize := sizeof(PTZ.STimeZone); if RegQueryValueEx(SubKey, 'TZI', nil, nil, @PTZ.STimeZone, @BufSize) = ERROR_SUCCESS then ShortTZToTimeZoneInfo(PTZ.STimeZone, PTZ^) else begin {$IFDEF ZONE_DEBUG} MessageBox(0, PChar('Failed to retrieve TZI of this zone: ' + SubKeyStr), nil, 0); {$ENDIF} end; BufSize := 100; if RegQueryValueEx(SubKey, 'Dlt', nil, nil, @(byte(B2^)), @BufSize) = ERROR_SUCCESS then PTZ.DltName := StrPas(PChar(B2)) else begin {$IFDEF ZONE_DEBUG} MessageBox(0, PChar('Failed to retrieve Dlt of this zone: ' + SubKeyStr), nil, 0); {$ENDIF} end; BufSize := 100; if RegQueryValueEx(SubKey, 'Std', nil, nil, @(byte(B2^)), @BufSize) = ERROR_SUCCESS then PTZ.StdName := StrPas(PChar(B2)) else begin {$IFDEF ZONE_DEBUG} MessageBox(0, PChar('Failed to retrieve Std of this zone: ' + SubKeyStr), nil, 0); {$ENDIF} end; RegCloseKey(SubKey); FreeMem(b2); end else begin {$IFDEF ZONE_DEBUG} MessageBox(0, PChar('Failed to retrieve any information at all about this zone: ' + SubKeyStr), nil, 0); {$ENDIF} end; TimeZoneInfoList.Add(PTZ); end else begin {$IFDEF ZONE_DEBUG} MessageBox(0, PChar('Failed to query time zone ' + IntToStr(i)), nil, 0); {$ENDIF} Dispose(PTZ); end; inc(i); FreeMem(b1, 100); until RES = ERROR_NO_MORE_ITEMS; RegCloseKey(Key); //MessageBox(0, PChar('Total items: ' + IntToStr(TimeZoneInfoList.Count)), '', 0); result := true; except on E : EOutOfMemory do result := false; end; end; {$warnings off} var i : integer; initialization FDL := false; SysTimeZones := TElList.Create; RetrieveTimezoneInfo(SysTimeZones); finalization for i := 0 to SysTimeZones.Count - 1 do Dispose(PTimeZoneInfo(SysTimezones[i])); SysTimeZones.Free; end.
//** Основное изображение. unit uSCR; interface uses Windows, Graphics, // Own units UCommon, uHint; //** Отрисовка основного изображения. type TSCR = class(THODObject) private FHint: THint; HoldHint: Boolean; procedure SetHint(const Value: THint); public //** Основное изображение. BG: TBitmap; //** Отрисовка основного изображения. procedure Display; procedure DisplayHint; //** Конструктор. constructor Create; //** Деструктор. destructor Destroy; override; property Hint: THint read FHint write SetHint; end; var //** Основное изображение. SCR: TSCR; //** Дескриптор основного изображения. BGDC: HDC; implementation uses uGUI, uMap, uMain, uBar, uUtils; { TSCR } constructor TSCR.Create; begin // Буфер BG := TBitMap.Create; BG.Width := 800; BG.Height := 600; end; destructor TSCR.Destroy; begin BG.Free; inherited; end; procedure TSCR.Display; begin // Заливаем фон черным цветом BitBlt(BG.Canvas.Handle, 0, 0, BG.Width, BG.Height, 0, 0, 0, BLACKNESS); if not IsMenu and IsGame then begin Map.Display(); // Отображаем карту Bar.Render(); // Отображаем интерфейс end; end; procedure TSCR.DisplayHint; begin if Assigned(Hint) then begin Hint.Draw(); if not HoldHint then Hint := nil; HoldHint := False; end; end; procedure TSCR.SetHint(const Value: THint); begin FHint := Value; if Assigned(Value) then HoldHint := True; end; initialization SCR := TSCR.Create; BGDC := GetDC(SCR.BG.Handle); finalization SCR.Free; DeleteDC(BGDC); end.
unit ErrorListDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TErrorListDialog = class(TComponent) private FLabelCaption: string; FBoxCaption: string; FItems: TStringList; procedure SetBoxCaption(const Value: string); procedure SetLabelCaption(const Value: string); procedure SetItems(const Value: TStringList); { Private declarations } protected { Protected declarations } public { Public declarations } constructor create(AOwner:TComponent);override; destructor Destroy;override; procedure Execute; published { Published declarations } property Items:TStringList read FItems write SetItems; property BoxCaption:string read FBoxCaption write SetBoxCaption; property LabelCaption:string read FLabelCaption write SetLabelCaption; end; procedure Register; implementation uses ErrorListForm; procedure Register; begin RegisterComponents('FFS Common', [TErrorListDialog]); end; { TErrorListDialog } constructor TErrorListDialog.create(AOwner: TComponent); begin inherited; FItems := TStringList.create; end; destructor TErrorListDialog.Destroy; begin FItems.Free; inherited; end; procedure TErrorListDialog.Execute; var frmErrorList : TfrmErrorList; begin frmErrorList := TfrmErrorList.Create(self); frmErrorList.Caption := BoxCaption; frmErrorList.Label1.Caption := LabelCaption; frmErrorList.ListBox1.Clear; frmErrorList.ListBox1.Lines.AddStrings(Items); frmErrorList.ShowModal; frmErrorList.Free; end; procedure TErrorListDialog.SetBoxCaption(const Value: string); begin FBoxCaption := Value; end; procedure TErrorListDialog.SetItems(const Value: TStringList); begin FItems.Assign(value); end; procedure TErrorListDialog.SetLabelCaption(const Value: string); begin FLabelCaption := Value; end; end.
unit uCompras; interface uses FireDAc.Comp.Client, FireDAc.Stan.Param, Data.DB, FireDAc.DApt; type TCompras = class private FConexao : TFDConnection; FCP_NUMERO: Integer; FCP_QTDE: Double; FCP_EMPRESA: Integer; FCP_DATA: TDateTime; FCP_PRODUTO: Integer; procedure SetCP_DATA(const Value: TDateTime); procedure SetCP_EMPRESA(const Value: Integer); procedure SetCP_NUMERO(const Value: Integer); procedure SetCP_PRODUTO(const Value: Integer); procedure SetCP_QTDE(const Value: Double); public Constructor Create(poConexao: TFDConnection); virtual; Destructor Destroy(); override; function Insert : String; function Delete : String; published property CP_EMPRESA : Integer read FCP_EMPRESA write SetCP_EMPRESA; property CP_NUMERO : Integer read FCP_NUMERO write SetCP_NUMERO; property CP_PRODUTO : Integer read FCP_PRODUTO write SetCP_PRODUTO; property CP_DATA : TDateTime read FCP_DATA write SetCP_DATA; property CP_QTDE : Double read FCP_QTDE write SetCP_QTDE; end; implementation { TCompras } constructor TCompras.Create(poConexao: TFDConnection); begin FConexao := poConexao; end; function TCompras.Delete: String; begin end; destructor TCompras.Destroy; begin inherited; end; function TCompras.Insert: String; begin end; procedure TCompras.SetCP_DATA(const Value: TDateTime); begin FCP_DATA := Value; end; procedure TCompras.SetCP_EMPRESA(const Value: Integer); begin FCP_EMPRESA := Value; end; procedure TCompras.SetCP_NUMERO(const Value: Integer); begin FCP_NUMERO := Value; end; procedure TCompras.SetCP_PRODUTO(const Value: Integer); begin FCP_PRODUTO := Value; end; procedure TCompras.SetCP_QTDE(const Value: Double); begin FCP_QTDE := Value; end; end.
unit uWcxArchiveExecuteOperation; {$mode objfpc}{$H+} interface uses Classes, SysUtils, uFile, uFileSource, uFileSourceExecuteOperation, uWcxArchiveFileSource; type { TWcxArchiveExecuteOperation } TWcxArchiveExecuteOperation = class(TFileSourceExecuteOperation) private FWcxArchiveFileSource: IWcxArchiveFileSource; public {en @param(aTargetFileSource File source where the file should be executed.) @param(aExecutableFile File that should be executed.) @param(aCurrentPath Path of the file source where the execution should take place.) } constructor Create(aTargetFileSource: IFileSource; var aExecutableFile: TFile; aCurrentPath, aVerb: String); override; procedure Initialize; override; procedure MainExecute; override; procedure Finalize; override; end; implementation uses fPackInfoDlg; constructor TWcxArchiveExecuteOperation.Create( aTargetFileSource: IFileSource; var aExecutableFile: TFile; aCurrentPath, aVerb: String); begin FWcxArchiveFileSource := aTargetFileSource as IWcxArchiveFileSource; inherited Create(aTargetFileSource, aExecutableFile, aCurrentPath, aVerb); end; procedure TWcxArchiveExecuteOperation.Initialize; begin end; procedure TWcxArchiveExecuteOperation.MainExecute; begin FExecuteOperationResult:= ShowPackInfoDlg(FWcxArchiveFileSource, ExecutableFile); end; procedure TWcxArchiveExecuteOperation.Finalize; begin end; end.
Пример из жизни. Пусть мы хотим сделать "компонент", который наследуется от TClienDataSet и добавляет ему некие "прелестные фичи". Вариант "в лоб" TmySmartDataSet = class(TClientDataSet) constructor Create(anOwner : TComponent; тут много разных дополнительных параметров); reintroduce; ... inherited Create(anOwner); тут эти параметры используются Сделали? Отлично! И тут мы задумались о том, "а как нам "подсказать" будущему пользователю нашего "компонента", что в Design-Time его создавать не надо, и НАДО звать НАШ "кошерный" конструктор. И ТОЛЬКО его. По-моему - решение на поверхности. TmySmartDataSet = class(TObject) constructor Create(anOwner : TComponent; тут много разных дополнительных параметров); reintroduce; private FInnerSmartDataSet : TClientDataSet; public InnerSmartDataSet : TClientDataSet read FInnerSmartDataSet; implementation TmySmartDataSetImplementation = class(TClientDataSet) тут переопределяем ПОВЕДЕНИЕ ... FInnerSmartDataSet := TmySmartDataSetImplementation.Create(anOwner); inherited Create; тут эти параметры используются, чтобы довесить "чудные штучки" и "поднастроить" FInnerSmartDataSet Создаём так: l_MySmartDataSet := TmySmartDataSet.Create(anOwner, тут остальные "чудные" параметры); SomeDataSource.DataSet := l_MySmartDataSet.InnerSmartDataSet; Идея понятна?
{ id:rz109291 PROG:frac1 LANG:PASCAL } { USER: r z [rz109291] TASK: frac1 LANG: PASCAL Compiling... Compile: OK Executing... Test 1: TEST OK [0.000 secs, 624 KB] Test 2: TEST OK [0.000 secs, 624 KB] Test 3: TEST OK [0.000 secs, 624 KB] Test 4: TEST OK [0.000 secs, 624 KB] Test 5: TEST OK [0.000 secs, 624 KB] Test 6: TEST OK [0.000 secs, 624 KB] Test 7: TEST OK [0.000 secs, 624 KB] Test 8: TEST OK [0.000 secs, 624 KB] Test 9: TEST OK [0.000 secs, 624 KB] Test 10: TEST OK [0.000 secs, 624 KB] Test 11: TEST OK [0.000 secs, 624 KB] All tests OK. Your program ('frac1') produced all correct answers! This is your submission #2 for this problem. Congratulations! } var data:array[0..30000]of extended; a,b:array[0..30000]of byte; i,j,n,m,l,r:longint; function gcd(a,b:longint):longint; var t:longint; begin if a=0 then exit(b); if b=0 then exit(a); exit(gcd(b,a mod b)); end; procedure qsort(s,t:longint); var k:extended; i,j,u:longint; y:extended; begin i:=s;j:=t;k:=data[(s+t)shr 1]; repeat while data[j]>k do dec(j); while data[i]<k do inc(i); if (i<=j) then begin u:=a[i];a[i]:=a[j];a[j]:=u; u:=b[i];b[i]:=b[j];b[j]:=u; y:=data[i];data[i]:=data[j];data[j]:=y; inc(i);dec(j); end; until i>=j; if (i<t) then qsort(i,t); if (s<j) then qsort(s,j); end; begin assign(input,'frac1.in');reset(input);assign(output,'frac1.out');rewrite(output); readln(n); l:=0;r:=0; for i:=1 to n do//·Öĸ for j:=0 to i do//·Ö×Ó if gcd(i,j)=1 then begin inc(r); a[r]:=j; b[r]:=i; data[r]:=j/i; end; qsort(1,r); for i:=1 to r do writeln(a[i],'/',b[i]); close(output);close(input); end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpBerBitString; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, ClpCryptoLibTypes, ClpAsn1OutputStream, ClpBerOutputStream, ClpDerOutputStream, ClpIProxiedInterface, ClpDerBitString, ClpIBerBitString, ClpAsn1Tags; type TBerBitString = class(TDerBitString, IBerBitString) public constructor Create(const data: TCryptoLibByteArray; padBits: Int32); overload; constructor Create(const data: TCryptoLibByteArray); overload; constructor Create(namedBits: Int32); overload; constructor Create(const obj: IAsn1Encodable); overload; procedure Encode(const derOut: TStream); override; end; implementation { TBerBitString } constructor TBerBitString.Create(const data: TCryptoLibByteArray); begin Inherited Create(data); end; constructor TBerBitString.Create(const data: TCryptoLibByteArray; padBits: Int32); begin Inherited Create(data, padBits); end; constructor TBerBitString.Create(const obj: IAsn1Encodable); begin Inherited Create(obj); end; constructor TBerBitString.Create(namedBits: Int32); begin Inherited Create(namedBits); end; procedure TBerBitString.Encode(const derOut: TStream); begin if ((derOut is TAsn1OutputStream) or (derOut is TBerOutputStream)) then begin (derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.BitString, Byte(mPadBits), mData); end else begin Inherited Encode(derOut); end; end; end.
{$I tdl_dire.inc} {$IFDEF USEOVERLAYS} {$O+,F+} {$ENDIF} unit tdl_hand; { Contains logic and data structures necessary to implement file handlers. - EXTRACTION handlers decompress archive files into cache directories. - EXECUTION handlers directly run programs, or launch a helper program to handle the chosen file. Implementation notes: - Execution handlers always switch to the supplied directory before operating, to try to avoid exceeding DOS directory length/depth limits. } interface uses DOS, objects; type fSplitRec=record P:PathStr; D:DirStr; N:NameStr; E:ExtStr; end; handlerType=(null,extraction,execution); PHandler=^THandler; THandler=object(TObject) PUBLIC category:handlerType; extension:extStr; Template:dirStr; {string template from handlers.ini} FullPath:dirStr; {full path to utility} Description:dirStr; {user-friendly description} UserMessage:string; {optional short message to user} Constructor Init(ext:extStr;cat:handlerType;temp,fullp,desc:dirStr;usermsg:string); Destructor Done; VIRTUAL; end; PHandlers=^THandlers; THandlers=object(TCollection) PUBLIC defaultHandler:integer; Constructor Init(hfile:string); Destructor Done; VIRTUAL; Function Exists(ext:extStr):handlerType; Function handle(ext:extStr;_src,_dst:string):boolean; end; var Handlers:PHandlers; implementation uses spawno, support, totFAST, inifiles, tdl_conf, tdl_cons; Constructor THandler.Init; begin Inherited Init; extension:=ext; category:=cat; template:=temp; FullPath:=fullp; description:=desc; userMessage:=usermsg; end; Destructor THandler.Done; begin Inherited Done; end; Constructor THandlers.Init; const INIBufSize=18*512*2; {enough to hold an entire 1.44MB track} var h:PHandler; t:THandler; ini:PINIfile; iniresult:PINIResultType; s,util,section,upath:string; first:boolean; b:byte; begin if config^.swapping then init_spawno(fileCache^.path,swap_all,32,0); {Init the collection with 32 to start and 256 max. Anyone needing >256 handlers needs to consider a change of lifestyle.} Inherited Init(32,256); {Populate collection with contents of handlers.ini} if not fileexists(hfile) then fatalerror(1,'Handler config '+hfile+' not found'); ini:=new(PINIFile,init(hfile,readfile,INIBufSize)); if ini=NIL then begin fatalerror(2,'Problem opening handler INI file: '+hfile); exit; end; {read and parse. Template for what we are reading:} (* [ARC;SEA] type=extraction launcher=pkunpak.exe %s %d locations=utils;distro\utils;c:\utils\common *) {read first line} first:=true; INIResult:=ini^.ReadNextItem; if INIResult=nil then fatalerror(3,'Initial INI read failed'); while (INIResult<>nil) do begin INIResult:=ini^.ReadNextItem; {won't go past section header unless we ACK} if (ini^.newSection) then begin; if not first then begin {fill in the rest of the fields, verify input, etc.} {determine base utility filename. Handle special case of just '%s'.} util:=t.template; if (pos('%',util)=0) then fatalerror(4,'Handler launcher string "'+util+'" malformed'); if util<>'%s' then begin system.delete(util,pos(' ',util),length(util)); {remove it from the template string} system.delete(t.template,1,length(util)); {Section: Fully-qualify the utilty by searching for it and recording full path to it} s:=util; {System-set COMSPEC is always valid, so use if appropriate} if upstring(util)='COMMAND.COM' then util:=GetEnv('COMSPEC') else begin {Go looking for utility in system path} util:=FSearch(s,GetEnv('PATH')); {If not found, go looking in user-supplied path in TDL.INI} if util='' then util:=FSearch(s,upath); end; if util='' then fatalerror(5,s+' handler not found in '+upath); {add drive letter to convert relative path to absolute path} if pos(':',util)=0 then begin getdir(0,s); util:=StdPath(s)+util; end; end; {commit as many as are separated by semicolons} while section<>'' do begin t.extension:=section; byte(t.extension[0]):=3; if util='%s' then t.fullpath:='' else t.fullpath:=util; if config^.edebug then writeln('Assuming handler ',t.extension,' is at ',t.fullpath); h:=new(PHandler,init(t.extension,t.category,t.template,t.fullpath,t.description,t.usermessage)); Insert(h); system.delete(section,1,4); {remove "XXX;" and do it again} end; end; {start building new handler with each line read} ini^.ACKSection; {reset optional fields} t.description:=''; t.usermessage:=''; section:=INIResult^.section; first:=false; {Now that we've read a line and committed a section, are we at the end? Do we need to keep going? If not, abort} if INIResult^.Section='END' then break; continue; end; with INIResult^ do begin if upstring(key)='TYPE' then begin if upstring(value)='EXTRACTION' then t.category:=extraction else t.category:=execution; end; if upstring(key)='LAUNCHER' then t.template:=value; if upstring(key)='LOCATIONS' then upath:=value; if upstring(key)='DESCRIPTION' then t.description:=value; if upstring(key)='USERMESSAGE' then t.userMessage:=value; end; end; dispose(ini,done); if config^.edebug then begin writeln('Handler registration finished, hit ENTER to continue.'); readln; end; {Now that we have our handlers, look for the ??? handler and set that to the default.} defaultHandler:=-1; for b:=0 to Count-1 do if PHandler(at(b))^.extension='???' then begin defaultHandler:=b; break; end; end; Destructor THandlers.Done; begin Inherited Done; end; Function THandlers.Exists(ext:extStr):handlerType; var w:word; begin Exists:=null; for w:=0 to Count-1 do begin if PHandler(at(w))^.extension=ext then begin Exists:=PHandler(at(w))^.category; break; end; end; end; Function THandlers.handle(ext:extStr;_src,_dst:string):boolean; {$DEFINE DEBUGLAUNCH} { src and dst must always be fully-qualified (ie. c:\dir\file.ext or c:\dir\); Extraction handlers do this: 1. chdir to where the helper program is 2. run utility program template with %s=src and %d=dst Execution handlers do this: 1. chdir: - if %s present, chdir to %d and run template - if %f present, chdir to where helper program is and run template %f is for helper "programs" that are really batch files that run many progs. Note: There is a lot fo "if msgConsole<>nil then" checking because we have to call this before the message console is set up. This is irritating, but it's a lot less irritating than having to resolve the circular dependency between the message console and the screen driver. } const spawnErrorTail:string[23]=' failure; Error code = '; var tmpsplit,src,dst:fSplitRec; execParm:string; {execution template} execHead:string; hid:integer; oldDir,wrkDir:string; result:boolean; temps:string; retval:integer; {heap manipulation} OldHeapEnd,NewHeapEnd:Word; mError:Integer; begin if msgConsole<>nil then msgConsole^.logmsg(info,'Entering handler framework: '+ext); result:=false; src.p:=_src; dst.p:=stdPath(_dst); with src do fsplit(p,d,n,e); with dst do fsplit(p,d,n,e); {find handler index} {there's a reason why this is Count instead of Count-1 but I can't remember why :-( } for hid:=0 to Count do begin if hid=Count then die('Unregistered handler: '+ext); if PHandler(at(hid))^.extension=ext then break; end; if PHandler(at(hid))^.userMessage<>'' then popUserMessage(info,PHandler(at(hid))^.userMessage); execHead:=PHandler(at(hid))^.fullpath; execParm:=PHandler(at(hid))^.template; {Replace variables in the launch template. %s and %f are handled differently -- see handlers.ini or above for info} case PHandler(at(hid))^.category of execution:begin if pos('%s',execParm)<>0 then strReplace(execParm,'%s',src.n+src.e); if pos('%f',execParm)<>0 then begin strReplace(execParm,'%f',src.p); {replace with full path} dst.p:=PHandler(at(hid))^.fullpath; {grab full path to helper util} with dst do fsplit(p,d,n,e); {ensure that dst.d = helper util path} execHead:=dst.n+dst.e; end; {Bare .exe/.coms don't have handler utils -- set up the exec for them. An empty header of '' is the indicator we chose to signify this.} if execHead='' then begin execHead:=execParm; execParm:=''; end; wrkDir:=dst.d; {check for batch files -- must run them with 'command.com','/c b.bat'} if (pos('.bat',execHead)<>0) or (pos('.BAT',execHead)<>0) then begin execParm:='/c '+execHead+execParm; execHead:=GetEnv('COMSPEC'); end; end; extraction:begin strReplace(execParm,'%s',src.n+src.e); strReplace(execParm,'%d',dst.d); wrkDir:=src.d; end; end; if msgConsole<>nil then msgConsole^.logmsg(info,'Execution template: '+execParm); GetDir(0,oldDir); temps:='Switching to '+wrkDir+' to execute '+execHead+execParm; if msgConsole<>nil then msgConsole^.logmsg(info,temps); {TP's CHDIR can't handle subdirectories with trailing slashes; weird. It requires them on root dirs though, like "c:\". Dumb fix:} if (length(wrkdir)<>3) and (wrkdir[length(wrkdir)]='\') then system.delete(wrkdir,length(wrkdir),1); chdir(wrkDir); {$IFDEF DPMI} !This code is not compatible with protected-mode compilation targets! {$ENDIF} {determine end of actual memory used} NewHeapEnd:=Seg(HeapPtr^)-PrefixSeg; OldHeapEnd:=Seg(HeapEnd^)-PrefixSeg; {resize our own DOS memory block to end of USED heap} asm mov ah,4Ah mov bx,NewHeapEnd mov es,PrefixSeg int 21h jnc @EXIT mov mError,ax @EXIT: end; {asm} swapvectors; if config^.swapping then retval:=spawn(execHead,execParm,0) else exec(execHead,execParm); swapvectors; {resize it back to the end of TOTAL heap} asm mov ah,4Ah mov bx,OldHeapEnd mov es,PrefixSeg Int 21h jnc @EXIT mov mError,ax @EXIT: end; {asm} {Handle error codes: -1 means a SPAWNO error, and 1..255 is error returned from the callee} if config^.swapping then begin result:=(retval=0); if result=false then if retval=-1 then begin if msgConsole<>nil then msgConsole^.logmsg(tdl_cons.error,'Swapping'+spawnErrorTail+inttostr(spawno_error)); case spawno_error of enotfound :temps:=enotfoundErrmsg; enopath :temps:=enopathErrmsg; emfile :temps:=emfileErrmsg; eaccess :temps:=eaccessErrmsg; ebadf :temps:=ebadfErrmsg; econtr :temps:=econtrErrmsg; enomem :temps:=enomemErrmsg; einvdat :temps:=einvdatErrmsg; enodev :temps:=enodevErrmsg; einval :temps:=einvalErrmsg; e2big :temps:=e2bigErrmsg; ewritefault:temps:=ewritefaultErrmsg; end; if msgConsole<>nil then msgConsole^.logmsg(tdl_cons.error,temps); end else begin if msgConsole<>nil then msgConsole^.logmsg(tdl_cons.error,'EXEC'+spawnErrorTail+inttostr(retval)); end; {not swapping, pass along error} end else begin result:=(DOSError=0); if result=false then if msgConsole<>nil then msgConsole^.logmsg(tdl_cons.error,'EXEC'+spawnErrorTail+inttostr(DOSError)) end; if msgConsole<>nil then msgConsole^.logmsg(info,'Switching back to '+wrkdir); chdir(oldDir); if msgConsole<>nil then msgConsole^.logmsg(info,'Saving DOS screen contents'); if DOSScreen<>nil then DOSScreen^.Save; handle:=result; end; end.
unit GameControl; interface uses Math, TypeControl; type TGame = class private FRandomSeed: Int64; FTickCount: LongInt; FWorldWidth: Double; FWorldHeight: Double; FFogOfWarEnabled: Boolean; FVictoryScore: LongInt; FFacilityCaptureScore: LongInt; FVehicleEliminationScore: LongInt; FActionDetectionInterval: LongInt; FBaseActionCount: LongInt; FAdditionalActionCountPerControlCenter: LongInt; FMaxUnitGroup: LongInt; FTerrainWeatherMapColumnCount: LongInt; FTerrainWeatherMapRowCount: LongInt; FPlainTerrainVisionFactor: Double; FPlainTerrainStealthFactor: Double; FPlainTerrainSpeedFactor: Double; FSwampTerrainVisionFactor: Double; FSwampTerrainStealthFactor: Double; FSwampTerrainSpeedFactor: Double; FForestTerrainVisionFactor: Double; FForestTerrainStealthFactor: Double; FForestTerrainSpeedFactor: Double; FClearWeatherVisionFactor: Double; FClearWeatherStealthFactor: Double; FClearWeatherSpeedFactor: Double; FCloudWeatherVisionFactor: Double; FCloudWeatherStealthFactor: Double; FCloudWeatherSpeedFactor: Double; FRainWeatherVisionFactor: Double; FRainWeatherStealthFactor: Double; FRainWeatherSpeedFactor: Double; FVehicleRadius: Double; FTankDurability: LongInt; FTankSpeed: Double; FTankVisionRange: Double; FTankGroundAttackRange: Double; FTankAerialAttackRange: Double; FTankGroundDamage: LongInt; FTankAerialDamage: LongInt; FTankGroundDefence: LongInt; FTankAerialDefence: LongInt; FTankAttackCooldownTicks: LongInt; FTankProductionCost: LongInt; FIfvDurability: LongInt; FIfvSpeed: Double; FIfvVisionRange: Double; FIfvGroundAttackRange: Double; FIfvAerialAttackRange: Double; FIfvGroundDamage: LongInt; FIfvAerialDamage: LongInt; FIfvGroundDefence: LongInt; FIfvAerialDefence: LongInt; FIfvAttackCooldownTicks: LongInt; FIfvProductionCost: LongInt; FArrvDurability: LongInt; FArrvSpeed: Double; FArrvVisionRange: Double; FArrvGroundDefence: LongInt; FArrvAerialDefence: LongInt; FArrvProductionCost: LongInt; FArrvRepairRange: Double; FArrvRepairSpeed: Double; FHelicopterDurability: LongInt; FHelicopterSpeed: Double; FHelicopterVisionRange: Double; FHelicopterGroundAttackRange: Double; FHelicopterAerialAttackRange: Double; FHelicopterGroundDamage: LongInt; FHelicopterAerialDamage: LongInt; FHelicopterGroundDefence: LongInt; FHelicopterAerialDefence: LongInt; FHelicopterAttackCooldownTicks: LongInt; FHelicopterProductionCost: LongInt; FFighterDurability: LongInt; FFighterSpeed: Double; FFighterVisionRange: Double; FFighterGroundAttackRange: Double; FFighterAerialAttackRange: Double; FFighterGroundDamage: LongInt; FFighterAerialDamage: LongInt; FFighterGroundDefence: LongInt; FFighterAerialDefence: LongInt; FFighterAttackCooldownTicks: LongInt; FFighterProductionCost: LongInt; FMaxFacilityCapturePoints: Double; FFacilityCapturePointsPerVehiclePerTick: Double; FFacilityWidth: Double; FFacilityHeight: Double; FBaseTacticalNuclearStrikeCooldown: LongInt; FTacticalNuclearStrikeCooldownDecreasePerControlCenter: LongInt; FMaxTacticalNuclearStrikeDamage: Double; FTacticalNuclearStrikeRadius: Double; FTacticalNuclearStrikeDelay: LongInt; public constructor Create(const randomSeed: Int64; const tickCount: LongInt; const worldWidth: Double; const worldHeight: Double; const fogOfWarEnabled: Boolean; const victoryScore: LongInt; const facilityCaptureScore: LongInt; const vehicleEliminationScore: LongInt; const actionDetectionInterval: LongInt; const baseActionCount: LongInt; const additionalActionCountPerControlCenter: LongInt; const maxUnitGroup: LongInt; const terrainWeatherMapColumnCount: LongInt; const terrainWeatherMapRowCount: LongInt; const plainTerrainVisionFactor: Double; const plainTerrainStealthFactor: Double; const plainTerrainSpeedFactor: Double; const swampTerrainVisionFactor: Double; const swampTerrainStealthFactor: Double; const swampTerrainSpeedFactor: Double; const forestTerrainVisionFactor: Double; const forestTerrainStealthFactor: Double; const forestTerrainSpeedFactor: Double; const clearWeatherVisionFactor: Double; const clearWeatherStealthFactor: Double; const clearWeatherSpeedFactor: Double; const cloudWeatherVisionFactor: Double; const cloudWeatherStealthFactor: Double; const cloudWeatherSpeedFactor: Double; const rainWeatherVisionFactor: Double; const rainWeatherStealthFactor: Double; const rainWeatherSpeedFactor: Double; const vehicleRadius: Double; const tankDurability: LongInt; const tankSpeed: Double; const tankVisionRange: Double; const tankGroundAttackRange: Double; const tankAerialAttackRange: Double; const tankGroundDamage: LongInt; const tankAerialDamage: LongInt; const tankGroundDefence: LongInt; const tankAerialDefence: LongInt; const tankAttackCooldownTicks: LongInt; const tankProductionCost: LongInt; const ifvDurability: LongInt; const ifvSpeed: Double; const ifvVisionRange: Double; const ifvGroundAttackRange: Double; const ifvAerialAttackRange: Double; const ifvGroundDamage: LongInt; const ifvAerialDamage: LongInt; const ifvGroundDefence: LongInt; const ifvAerialDefence: LongInt; const ifvAttackCooldownTicks: LongInt; const ifvProductionCost: LongInt; const arrvDurability: LongInt; const arrvSpeed: Double; const arrvVisionRange: Double; const arrvGroundDefence: LongInt; const arrvAerialDefence: LongInt; const arrvProductionCost: LongInt; const arrvRepairRange: Double; const arrvRepairSpeed: Double; const helicopterDurability: LongInt; const helicopterSpeed: Double; const helicopterVisionRange: Double; const helicopterGroundAttackRange: Double; const helicopterAerialAttackRange: Double; const helicopterGroundDamage: LongInt; const helicopterAerialDamage: LongInt; const helicopterGroundDefence: LongInt; const helicopterAerialDefence: LongInt; const helicopterAttackCooldownTicks: LongInt; const helicopterProductionCost: LongInt; const fighterDurability: LongInt; const fighterSpeed: Double; const fighterVisionRange: Double; const fighterGroundAttackRange: Double; const fighterAerialAttackRange: Double; const fighterGroundDamage: LongInt; const fighterAerialDamage: LongInt; const fighterGroundDefence: LongInt; const fighterAerialDefence: LongInt; const fighterAttackCooldownTicks: LongInt; const fighterProductionCost: LongInt; const maxFacilityCapturePoints: Double; const facilityCapturePointsPerVehiclePerTick: Double; const facilityWidth: Double; const facilityHeight: Double; const baseTacticalNuclearStrikeCooldown: LongInt; const tacticalNuclearStrikeCooldownDecreasePerControlCenter: LongInt; const maxTacticalNuclearStrikeDamage: Double; const tacticalNuclearStrikeRadius: Double; const tacticalNuclearStrikeDelay: LongInt); function GetRandomSeed: Int64; property RandomSeed: Int64 read GetRandomSeed; function GetTickCount: LongInt; property TickCount: LongInt read GetTickCount; function GetWorldWidth: Double; property WorldWidth: Double read GetWorldWidth; function GetWorldHeight: Double; property WorldHeight: Double read GetWorldHeight; function GetFogOfWarEnabled: Boolean; property IsFogOfWarEnabled: Boolean read GetFogOfWarEnabled; function GetVictoryScore: LongInt; property VictoryScore: LongInt read GetVictoryScore; function GetFacilityCaptureScore: LongInt; property FacilityCaptureScore: LongInt read GetFacilityCaptureScore; function GetVehicleEliminationScore: LongInt; property VehicleEliminationScore: LongInt read GetVehicleEliminationScore; function GetActionDetectionInterval: LongInt; property ActionDetectionInterval: LongInt read GetActionDetectionInterval; function GetBaseActionCount: LongInt; property BaseActionCount: LongInt read GetBaseActionCount; function GetAdditionalActionCountPerControlCenter: LongInt; property AdditionalActionCountPerControlCenter: LongInt read GetAdditionalActionCountPerControlCenter; function GetMaxUnitGroup: LongInt; property MaxUnitGroup: LongInt read GetMaxUnitGroup; function GetTerrainWeatherMapColumnCount: LongInt; property TerrainWeatherMapColumnCount: LongInt read GetTerrainWeatherMapColumnCount; function GetTerrainWeatherMapRowCount: LongInt; property TerrainWeatherMapRowCount: LongInt read GetTerrainWeatherMapRowCount; function GetPlainTerrainVisionFactor: Double; property PlainTerrainVisionFactor: Double read GetPlainTerrainVisionFactor; function GetPlainTerrainStealthFactor: Double; property PlainTerrainStealthFactor: Double read GetPlainTerrainStealthFactor; function GetPlainTerrainSpeedFactor: Double; property PlainTerrainSpeedFactor: Double read GetPlainTerrainSpeedFactor; function GetSwampTerrainVisionFactor: Double; property SwampTerrainVisionFactor: Double read GetSwampTerrainVisionFactor; function GetSwampTerrainStealthFactor: Double; property SwampTerrainStealthFactor: Double read GetSwampTerrainStealthFactor; function GetSwampTerrainSpeedFactor: Double; property SwampTerrainSpeedFactor: Double read GetSwampTerrainSpeedFactor; function GetForestTerrainVisionFactor: Double; property ForestTerrainVisionFactor: Double read GetForestTerrainVisionFactor; function GetForestTerrainStealthFactor: Double; property ForestTerrainStealthFactor: Double read GetForestTerrainStealthFactor; function GetForestTerrainSpeedFactor: Double; property ForestTerrainSpeedFactor: Double read GetForestTerrainSpeedFactor; function GetClearWeatherVisionFactor: Double; property ClearWeatherVisionFactor: Double read GetClearWeatherVisionFactor; function GetClearWeatherStealthFactor: Double; property ClearWeatherStealthFactor: Double read GetClearWeatherStealthFactor; function GetClearWeatherSpeedFactor: Double; property ClearWeatherSpeedFactor: Double read GetClearWeatherSpeedFactor; function GetCloudWeatherVisionFactor: Double; property CloudWeatherVisionFactor: Double read GetCloudWeatherVisionFactor; function GetCloudWeatherStealthFactor: Double; property CloudWeatherStealthFactor: Double read GetCloudWeatherStealthFactor; function GetCloudWeatherSpeedFactor: Double; property CloudWeatherSpeedFactor: Double read GetCloudWeatherSpeedFactor; function GetRainWeatherVisionFactor: Double; property RainWeatherVisionFactor: Double read GetRainWeatherVisionFactor; function GetRainWeatherStealthFactor: Double; property RainWeatherStealthFactor: Double read GetRainWeatherStealthFactor; function GetRainWeatherSpeedFactor: Double; property RainWeatherSpeedFactor: Double read GetRainWeatherSpeedFactor; function GetVehicleRadius: Double; property VehicleRadius: Double read GetVehicleRadius; function GetTankDurability: LongInt; property TankDurability: LongInt read GetTankDurability; function GetTankSpeed: Double; property TankSpeed: Double read GetTankSpeed; function GetTankVisionRange: Double; property TankVisionRange: Double read GetTankVisionRange; function GetTankGroundAttackRange: Double; property TankGroundAttackRange: Double read GetTankGroundAttackRange; function GetTankAerialAttackRange: Double; property TankAerialAttackRange: Double read GetTankAerialAttackRange; function GetTankGroundDamage: LongInt; property TankGroundDamage: LongInt read GetTankGroundDamage; function GetTankAerialDamage: LongInt; property TankAerialDamage: LongInt read GetTankAerialDamage; function GetTankGroundDefence: LongInt; property TankGroundDefence: LongInt read GetTankGroundDefence; function GetTankAerialDefence: LongInt; property TankAerialDefence: LongInt read GetTankAerialDefence; function GetTankAttackCooldownTicks: LongInt; property TankAttackCooldownTicks: LongInt read GetTankAttackCooldownTicks; function GetTankProductionCost: LongInt; property TankProductionCost: LongInt read GetTankProductionCost; function GetIfvDurability: LongInt; property IfvDurability: LongInt read GetIfvDurability; function GetIfvSpeed: Double; property IfvSpeed: Double read GetIfvSpeed; function GetIfvVisionRange: Double; property IfvVisionRange: Double read GetIfvVisionRange; function GetIfvGroundAttackRange: Double; property IfvGroundAttackRange: Double read GetIfvGroundAttackRange; function GetIfvAerialAttackRange: Double; property IfvAerialAttackRange: Double read GetIfvAerialAttackRange; function GetIfvGroundDamage: LongInt; property IfvGroundDamage: LongInt read GetIfvGroundDamage; function GetIfvAerialDamage: LongInt; property IfvAerialDamage: LongInt read GetIfvAerialDamage; function GetIfvGroundDefence: LongInt; property IfvGroundDefence: LongInt read GetIfvGroundDefence; function GetIfvAerialDefence: LongInt; property IfvAerialDefence: LongInt read GetIfvAerialDefence; function GetIfvAttackCooldownTicks: LongInt; property IfvAttackCooldownTicks: LongInt read GetIfvAttackCooldownTicks; function GetIfvProductionCost: LongInt; property IfvProductionCost: LongInt read GetIfvProductionCost; function GetArrvDurability: LongInt; property ArrvDurability: LongInt read GetArrvDurability; function GetArrvSpeed: Double; property ArrvSpeed: Double read GetArrvSpeed; function GetArrvVisionRange: Double; property ArrvVisionRange: Double read GetArrvVisionRange; function GetArrvGroundDefence: LongInt; property ArrvGroundDefence: LongInt read GetArrvGroundDefence; function GetArrvAerialDefence: LongInt; property ArrvAerialDefence: LongInt read GetArrvAerialDefence; function GetArrvProductionCost: LongInt; property ArrvProductionCost: LongInt read GetArrvProductionCost; function GetArrvRepairRange: Double; property ArrvRepairRange: Double read GetArrvRepairRange; function GetArrvRepairSpeed: Double; property ArrvRepairSpeed: Double read GetArrvRepairSpeed; function GetHelicopterDurability: LongInt; property HelicopterDurability: LongInt read GetHelicopterDurability; function GetHelicopterSpeed: Double; property HelicopterSpeed: Double read GetHelicopterSpeed; function GetHelicopterVisionRange: Double; property HelicopterVisionRange: Double read GetHelicopterVisionRange; function GetHelicopterGroundAttackRange: Double; property HelicopterGroundAttackRange: Double read GetHelicopterGroundAttackRange; function GetHelicopterAerialAttackRange: Double; property HelicopterAerialAttackRange: Double read GetHelicopterAerialAttackRange; function GetHelicopterGroundDamage: LongInt; property HelicopterGroundDamage: LongInt read GetHelicopterGroundDamage; function GetHelicopterAerialDamage: LongInt; property HelicopterAerialDamage: LongInt read GetHelicopterAerialDamage; function GetHelicopterGroundDefence: LongInt; property HelicopterGroundDefence: LongInt read GetHelicopterGroundDefence; function GetHelicopterAerialDefence: LongInt; property HelicopterAerialDefence: LongInt read GetHelicopterAerialDefence; function GetHelicopterAttackCooldownTicks: LongInt; property HelicopterAttackCooldownTicks: LongInt read GetHelicopterAttackCooldownTicks; function GetHelicopterProductionCost: LongInt; property HelicopterProductionCost: LongInt read GetHelicopterProductionCost; function GetFighterDurability: LongInt; property FighterDurability: LongInt read GetFighterDurability; function GetFighterSpeed: Double; property FighterSpeed: Double read GetFighterSpeed; function GetFighterVisionRange: Double; property FighterVisionRange: Double read GetFighterVisionRange; function GetFighterGroundAttackRange: Double; property FighterGroundAttackRange: Double read GetFighterGroundAttackRange; function GetFighterAerialAttackRange: Double; property FighterAerialAttackRange: Double read GetFighterAerialAttackRange; function GetFighterGroundDamage: LongInt; property FighterGroundDamage: LongInt read GetFighterGroundDamage; function GetFighterAerialDamage: LongInt; property FighterAerialDamage: LongInt read GetFighterAerialDamage; function GetFighterGroundDefence: LongInt; property FighterGroundDefence: LongInt read GetFighterGroundDefence; function GetFighterAerialDefence: LongInt; property FighterAerialDefence: LongInt read GetFighterAerialDefence; function GetFighterAttackCooldownTicks: LongInt; property FighterAttackCooldownTicks: LongInt read GetFighterAttackCooldownTicks; function GetFighterProductionCost: LongInt; property FighterProductionCost: LongInt read GetFighterProductionCost; function GetMaxFacilityCapturePoints: Double; property MaxFacilityCapturePoints: Double read GetMaxFacilityCapturePoints; function GetFacilityCapturePointsPerVehiclePerTick: Double; property FacilityCapturePointsPerVehiclePerTick: Double read GetFacilityCapturePointsPerVehiclePerTick; function GetFacilityWidth: Double; property FacilityWidth: Double read GetFacilityWidth; function GetFacilityHeight: Double; property FacilityHeight: Double read GetFacilityHeight; function GetBaseTacticalNuclearStrikeCooldown: LongInt; property BaseTacticalNuclearStrikeCooldown: LongInt read GetBaseTacticalNuclearStrikeCooldown; function GetTacticalNuclearStrikeCooldownDecreasePerControlCenter: LongInt; property TacticalNuclearStrikeCooldownDecreasePerControlCenter: LongInt read GetTacticalNuclearStrikeCooldownDecreasePerControlCenter; function GetMaxTacticalNuclearStrikeDamage: Double; property MaxTacticalNuclearStrikeDamage: Double read GetMaxTacticalNuclearStrikeDamage; function GetTacticalNuclearStrikeRadius: Double; property TacticalNuclearStrikeRadius: Double read GetTacticalNuclearStrikeRadius; function GetTacticalNuclearStrikeDelay: LongInt; property TacticalNuclearStrikeDelay: LongInt read GetTacticalNuclearStrikeDelay; destructor Destroy; override; end; TGameArray = array of TGame; implementation constructor TGame.Create(const randomSeed: Int64; const tickCount: LongInt; const worldWidth: Double; const worldHeight: Double; const fogOfWarEnabled: Boolean; const victoryScore: LongInt; const facilityCaptureScore: LongInt; const vehicleEliminationScore: LongInt; const actionDetectionInterval: LongInt; const baseActionCount: LongInt; const additionalActionCountPerControlCenter: LongInt; const maxUnitGroup: LongInt; const terrainWeatherMapColumnCount: LongInt; const terrainWeatherMapRowCount: LongInt; const plainTerrainVisionFactor: Double; const plainTerrainStealthFactor: Double; const plainTerrainSpeedFactor: Double; const swampTerrainVisionFactor: Double; const swampTerrainStealthFactor: Double; const swampTerrainSpeedFactor: Double; const forestTerrainVisionFactor: Double; const forestTerrainStealthFactor: Double; const forestTerrainSpeedFactor: Double; const clearWeatherVisionFactor: Double; const clearWeatherStealthFactor: Double; const clearWeatherSpeedFactor: Double; const cloudWeatherVisionFactor: Double; const cloudWeatherStealthFactor: Double; const cloudWeatherSpeedFactor: Double; const rainWeatherVisionFactor: Double; const rainWeatherStealthFactor: Double; const rainWeatherSpeedFactor: Double; const vehicleRadius: Double; const tankDurability: LongInt; const tankSpeed: Double; const tankVisionRange: Double; const tankGroundAttackRange: Double; const tankAerialAttackRange: Double; const tankGroundDamage: LongInt; const tankAerialDamage: LongInt; const tankGroundDefence: LongInt; const tankAerialDefence: LongInt; const tankAttackCooldownTicks: LongInt; const tankProductionCost: LongInt; const ifvDurability: LongInt; const ifvSpeed: Double; const ifvVisionRange: Double; const ifvGroundAttackRange: Double; const ifvAerialAttackRange: Double; const ifvGroundDamage: LongInt; const ifvAerialDamage: LongInt; const ifvGroundDefence: LongInt; const ifvAerialDefence: LongInt; const ifvAttackCooldownTicks: LongInt; const ifvProductionCost: LongInt; const arrvDurability: LongInt; const arrvSpeed: Double; const arrvVisionRange: Double; const arrvGroundDefence: LongInt; const arrvAerialDefence: LongInt; const arrvProductionCost: LongInt; const arrvRepairRange: Double; const arrvRepairSpeed: Double; const helicopterDurability: LongInt; const helicopterSpeed: Double; const helicopterVisionRange: Double; const helicopterGroundAttackRange: Double; const helicopterAerialAttackRange: Double; const helicopterGroundDamage: LongInt; const helicopterAerialDamage: LongInt; const helicopterGroundDefence: LongInt; const helicopterAerialDefence: LongInt; const helicopterAttackCooldownTicks: LongInt; const helicopterProductionCost: LongInt; const fighterDurability: LongInt; const fighterSpeed: Double; const fighterVisionRange: Double; const fighterGroundAttackRange: Double; const fighterAerialAttackRange: Double; const fighterGroundDamage: LongInt; const fighterAerialDamage: LongInt; const fighterGroundDefence: LongInt; const fighterAerialDefence: LongInt; const fighterAttackCooldownTicks: LongInt; const fighterProductionCost: LongInt; const maxFacilityCapturePoints: Double; const facilityCapturePointsPerVehiclePerTick: Double; const facilityWidth: Double; const facilityHeight: Double; const baseTacticalNuclearStrikeCooldown: LongInt; const tacticalNuclearStrikeCooldownDecreasePerControlCenter: LongInt; const maxTacticalNuclearStrikeDamage: Double; const tacticalNuclearStrikeRadius: Double; const tacticalNuclearStrikeDelay: LongInt); begin FRandomSeed := randomSeed; FTickCount := tickCount; FWorldWidth := worldWidth; FWorldHeight := worldHeight; FFogOfWarEnabled := fogOfWarEnabled; FVictoryScore := victoryScore; FFacilityCaptureScore := facilityCaptureScore; FVehicleEliminationScore := vehicleEliminationScore; FActionDetectionInterval := actionDetectionInterval; FBaseActionCount := baseActionCount; FAdditionalActionCountPerControlCenter := additionalActionCountPerControlCenter; FMaxUnitGroup := maxUnitGroup; FTerrainWeatherMapColumnCount := terrainWeatherMapColumnCount; FTerrainWeatherMapRowCount := terrainWeatherMapRowCount; FPlainTerrainVisionFactor := plainTerrainVisionFactor; FPlainTerrainStealthFactor := plainTerrainStealthFactor; FPlainTerrainSpeedFactor := plainTerrainSpeedFactor; FSwampTerrainVisionFactor := swampTerrainVisionFactor; FSwampTerrainStealthFactor := swampTerrainStealthFactor; FSwampTerrainSpeedFactor := swampTerrainSpeedFactor; FForestTerrainVisionFactor := forestTerrainVisionFactor; FForestTerrainStealthFactor := forestTerrainStealthFactor; FForestTerrainSpeedFactor := forestTerrainSpeedFactor; FClearWeatherVisionFactor := clearWeatherVisionFactor; FClearWeatherStealthFactor := clearWeatherStealthFactor; FClearWeatherSpeedFactor := clearWeatherSpeedFactor; FCloudWeatherVisionFactor := cloudWeatherVisionFactor; FCloudWeatherStealthFactor := cloudWeatherStealthFactor; FCloudWeatherSpeedFactor := cloudWeatherSpeedFactor; FRainWeatherVisionFactor := rainWeatherVisionFactor; FRainWeatherStealthFactor := rainWeatherStealthFactor; FRainWeatherSpeedFactor := rainWeatherSpeedFactor; FVehicleRadius := vehicleRadius; FTankDurability := tankDurability; FTankSpeed := tankSpeed; FTankVisionRange := tankVisionRange; FTankGroundAttackRange := tankGroundAttackRange; FTankAerialAttackRange := tankAerialAttackRange; FTankGroundDamage := tankGroundDamage; FTankAerialDamage := tankAerialDamage; FTankGroundDefence := tankGroundDefence; FTankAerialDefence := tankAerialDefence; FTankAttackCooldownTicks := tankAttackCooldownTicks; FTankProductionCost := tankProductionCost; FIfvDurability := ifvDurability; FIfvSpeed := ifvSpeed; FIfvVisionRange := ifvVisionRange; FIfvGroundAttackRange := ifvGroundAttackRange; FIfvAerialAttackRange := ifvAerialAttackRange; FIfvGroundDamage := ifvGroundDamage; FIfvAerialDamage := ifvAerialDamage; FIfvGroundDefence := ifvGroundDefence; FIfvAerialDefence := ifvAerialDefence; FIfvAttackCooldownTicks := ifvAttackCooldownTicks; FIfvProductionCost := ifvProductionCost; FArrvDurability := arrvDurability; FArrvSpeed := arrvSpeed; FArrvVisionRange := arrvVisionRange; FArrvGroundDefence := arrvGroundDefence; FArrvAerialDefence := arrvAerialDefence; FArrvProductionCost := arrvProductionCost; FArrvRepairRange := arrvRepairRange; FArrvRepairSpeed := arrvRepairSpeed; FHelicopterDurability := helicopterDurability; FHelicopterSpeed := helicopterSpeed; FHelicopterVisionRange := helicopterVisionRange; FHelicopterGroundAttackRange := helicopterGroundAttackRange; FHelicopterAerialAttackRange := helicopterAerialAttackRange; FHelicopterGroundDamage := helicopterGroundDamage; FHelicopterAerialDamage := helicopterAerialDamage; FHelicopterGroundDefence := helicopterGroundDefence; FHelicopterAerialDefence := helicopterAerialDefence; FHelicopterAttackCooldownTicks := helicopterAttackCooldownTicks; FHelicopterProductionCost := helicopterProductionCost; FFighterDurability := fighterDurability; FFighterSpeed := fighterSpeed; FFighterVisionRange := fighterVisionRange; FFighterGroundAttackRange := fighterGroundAttackRange; FFighterAerialAttackRange := fighterAerialAttackRange; FFighterGroundDamage := fighterGroundDamage; FFighterAerialDamage := fighterAerialDamage; FFighterGroundDefence := fighterGroundDefence; FFighterAerialDefence := fighterAerialDefence; FFighterAttackCooldownTicks := fighterAttackCooldownTicks; FFighterProductionCost := fighterProductionCost; FMaxFacilityCapturePoints := maxFacilityCapturePoints; FFacilityCapturePointsPerVehiclePerTick := facilityCapturePointsPerVehiclePerTick; FFacilityWidth := facilityWidth; FFacilityHeight := facilityHeight; FBaseTacticalNuclearStrikeCooldown := baseTacticalNuclearStrikeCooldown; FTacticalNuclearStrikeCooldownDecreasePerControlCenter := tacticalNuclearStrikeCooldownDecreasePerControlCenter; FMaxTacticalNuclearStrikeDamage := maxTacticalNuclearStrikeDamage; FTacticalNuclearStrikeRadius := tacticalNuclearStrikeRadius; FTacticalNuclearStrikeDelay := tacticalNuclearStrikeDelay; end; function TGame.GetRandomSeed: Int64; begin result := FRandomSeed; end; function TGame.GetTickCount: LongInt; begin result := FTickCount; end; function TGame.GetWorldWidth: Double; begin result := FWorldWidth; end; function TGame.GetWorldHeight: Double; begin result := FWorldHeight; end; function TGame.GetFogOfWarEnabled: Boolean; begin result := FFogOfWarEnabled; end; function TGame.GetVictoryScore: LongInt; begin result := FVictoryScore; end; function TGame.GetFacilityCaptureScore: LongInt; begin result := FFacilityCaptureScore; end; function TGame.GetVehicleEliminationScore: LongInt; begin result := FVehicleEliminationScore; end; function TGame.GetActionDetectionInterval: LongInt; begin result := FActionDetectionInterval; end; function TGame.GetBaseActionCount: LongInt; begin result := FBaseActionCount; end; function TGame.GetAdditionalActionCountPerControlCenter: LongInt; begin result := FAdditionalActionCountPerControlCenter; end; function TGame.GetMaxUnitGroup: LongInt; begin result := FMaxUnitGroup; end; function TGame.GetTerrainWeatherMapColumnCount: LongInt; begin result := FTerrainWeatherMapColumnCount; end; function TGame.GetTerrainWeatherMapRowCount: LongInt; begin result := FTerrainWeatherMapRowCount; end; function TGame.GetPlainTerrainVisionFactor: Double; begin result := FPlainTerrainVisionFactor; end; function TGame.GetPlainTerrainStealthFactor: Double; begin result := FPlainTerrainStealthFactor; end; function TGame.GetPlainTerrainSpeedFactor: Double; begin result := FPlainTerrainSpeedFactor; end; function TGame.GetSwampTerrainVisionFactor: Double; begin result := FSwampTerrainVisionFactor; end; function TGame.GetSwampTerrainStealthFactor: Double; begin result := FSwampTerrainStealthFactor; end; function TGame.GetSwampTerrainSpeedFactor: Double; begin result := FSwampTerrainSpeedFactor; end; function TGame.GetForestTerrainVisionFactor: Double; begin result := FForestTerrainVisionFactor; end; function TGame.GetForestTerrainStealthFactor: Double; begin result := FForestTerrainStealthFactor; end; function TGame.GetForestTerrainSpeedFactor: Double; begin result := FForestTerrainSpeedFactor; end; function TGame.GetClearWeatherVisionFactor: Double; begin result := FClearWeatherVisionFactor; end; function TGame.GetClearWeatherStealthFactor: Double; begin result := FClearWeatherStealthFactor; end; function TGame.GetClearWeatherSpeedFactor: Double; begin result := FClearWeatherSpeedFactor; end; function TGame.GetCloudWeatherVisionFactor: Double; begin result := FCloudWeatherVisionFactor; end; function TGame.GetCloudWeatherStealthFactor: Double; begin result := FCloudWeatherStealthFactor; end; function TGame.GetCloudWeatherSpeedFactor: Double; begin result := FCloudWeatherSpeedFactor; end; function TGame.GetRainWeatherVisionFactor: Double; begin result := FRainWeatherVisionFactor; end; function TGame.GetRainWeatherStealthFactor: Double; begin result := FRainWeatherStealthFactor; end; function TGame.GetRainWeatherSpeedFactor: Double; begin result := FRainWeatherSpeedFactor; end; function TGame.GetVehicleRadius: Double; begin result := FVehicleRadius; end; function TGame.GetTankDurability: LongInt; begin result := FTankDurability; end; function TGame.GetTankSpeed: Double; begin result := FTankSpeed; end; function TGame.GetTankVisionRange: Double; begin result := FTankVisionRange; end; function TGame.GetTankGroundAttackRange: Double; begin result := FTankGroundAttackRange; end; function TGame.GetTankAerialAttackRange: Double; begin result := FTankAerialAttackRange; end; function TGame.GetTankGroundDamage: LongInt; begin result := FTankGroundDamage; end; function TGame.GetTankAerialDamage: LongInt; begin result := FTankAerialDamage; end; function TGame.GetTankGroundDefence: LongInt; begin result := FTankGroundDefence; end; function TGame.GetTankAerialDefence: LongInt; begin result := FTankAerialDefence; end; function TGame.GetTankAttackCooldownTicks: LongInt; begin result := FTankAttackCooldownTicks; end; function TGame.GetTankProductionCost: LongInt; begin result := FTankProductionCost; end; function TGame.GetIfvDurability: LongInt; begin result := FIfvDurability; end; function TGame.GetIfvSpeed: Double; begin result := FIfvSpeed; end; function TGame.GetIfvVisionRange: Double; begin result := FIfvVisionRange; end; function TGame.GetIfvGroundAttackRange: Double; begin result := FIfvGroundAttackRange; end; function TGame.GetIfvAerialAttackRange: Double; begin result := FIfvAerialAttackRange; end; function TGame.GetIfvGroundDamage: LongInt; begin result := FIfvGroundDamage; end; function TGame.GetIfvAerialDamage: LongInt; begin result := FIfvAerialDamage; end; function TGame.GetIfvGroundDefence: LongInt; begin result := FIfvGroundDefence; end; function TGame.GetIfvAerialDefence: LongInt; begin result := FIfvAerialDefence; end; function TGame.GetIfvAttackCooldownTicks: LongInt; begin result := FIfvAttackCooldownTicks; end; function TGame.GetIfvProductionCost: LongInt; begin result := FIfvProductionCost; end; function TGame.GetArrvDurability: LongInt; begin result := FArrvDurability; end; function TGame.GetArrvSpeed: Double; begin result := FArrvSpeed; end; function TGame.GetArrvVisionRange: Double; begin result := FArrvVisionRange; end; function TGame.GetArrvGroundDefence: LongInt; begin result := FArrvGroundDefence; end; function TGame.GetArrvAerialDefence: LongInt; begin result := FArrvAerialDefence; end; function TGame.GetArrvProductionCost: LongInt; begin result := FArrvProductionCost; end; function TGame.GetArrvRepairRange: Double; begin result := FArrvRepairRange; end; function TGame.GetArrvRepairSpeed: Double; begin result := FArrvRepairSpeed; end; function TGame.GetHelicopterDurability: LongInt; begin result := FHelicopterDurability; end; function TGame.GetHelicopterSpeed: Double; begin result := FHelicopterSpeed; end; function TGame.GetHelicopterVisionRange: Double; begin result := FHelicopterVisionRange; end; function TGame.GetHelicopterGroundAttackRange: Double; begin result := FHelicopterGroundAttackRange; end; function TGame.GetHelicopterAerialAttackRange: Double; begin result := FHelicopterAerialAttackRange; end; function TGame.GetHelicopterGroundDamage: LongInt; begin result := FHelicopterGroundDamage; end; function TGame.GetHelicopterAerialDamage: LongInt; begin result := FHelicopterAerialDamage; end; function TGame.GetHelicopterGroundDefence: LongInt; begin result := FHelicopterGroundDefence; end; function TGame.GetHelicopterAerialDefence: LongInt; begin result := FHelicopterAerialDefence; end; function TGame.GetHelicopterAttackCooldownTicks: LongInt; begin result := FHelicopterAttackCooldownTicks; end; function TGame.GetHelicopterProductionCost: LongInt; begin result := FHelicopterProductionCost; end; function TGame.GetFighterDurability: LongInt; begin result := FFighterDurability; end; function TGame.GetFighterSpeed: Double; begin result := FFighterSpeed; end; function TGame.GetFighterVisionRange: Double; begin result := FFighterVisionRange; end; function TGame.GetFighterGroundAttackRange: Double; begin result := FFighterGroundAttackRange; end; function TGame.GetFighterAerialAttackRange: Double; begin result := FFighterAerialAttackRange; end; function TGame.GetFighterGroundDamage: LongInt; begin result := FFighterGroundDamage; end; function TGame.GetFighterAerialDamage: LongInt; begin result := FFighterAerialDamage; end; function TGame.GetFighterGroundDefence: LongInt; begin result := FFighterGroundDefence; end; function TGame.GetFighterAerialDefence: LongInt; begin result := FFighterAerialDefence; end; function TGame.GetFighterAttackCooldownTicks: LongInt; begin result := FFighterAttackCooldownTicks; end; function TGame.GetFighterProductionCost: LongInt; begin result := FFighterProductionCost; end; function TGame.GetMaxFacilityCapturePoints: Double; begin result := FMaxFacilityCapturePoints; end; function TGame.GetFacilityCapturePointsPerVehiclePerTick: Double; begin result := FFacilityCapturePointsPerVehiclePerTick; end; function TGame.GetFacilityWidth: Double; begin result := FFacilityWidth; end; function TGame.GetFacilityHeight: Double; begin result := FFacilityHeight; end; function TGame.GetBaseTacticalNuclearStrikeCooldown: LongInt; begin result := FBaseTacticalNuclearStrikeCooldown; end; function TGame.GetTacticalNuclearStrikeCooldownDecreasePerControlCenter: LongInt; begin result := FTacticalNuclearStrikeCooldownDecreasePerControlCenter; end; function TGame.GetMaxTacticalNuclearStrikeDamage: Double; begin result := FMaxTacticalNuclearStrikeDamage; end; function TGame.GetTacticalNuclearStrikeRadius: Double; begin result := FTacticalNuclearStrikeRadius; end; function TGame.GetTacticalNuclearStrikeDelay: LongInt; begin result := FTacticalNuclearStrikeDelay; end; destructor TGame.Destroy; begin inherited; end; end.
unit jc.IniFile; interface uses IniFiles, Classes, jc.Libs.Interfaces; type TJcIniFile = class(TInterfacedObject, IJcIniFile) private FIniFile: TIniFile; FFileName: string; public constructor Create(AFileName: String); destructor Destroy; override; class function New(AFileName: String = '') : IJcIniFile; class function Get(AFileName: String = '') : IJcIniFile; function FileName(const Value: string): IJcIniFile; function AddSection(const Section, Values: string): IJcIniFile; function AddString(const Section, Ident, Value: string): IJcIniFile; function AddInteger(const Section, Ident: string; Value: integer): IJcIniFile; function AddBoolean(const Section, Ident: string; Value: Boolean): IJcIniFile; function DeleteKey(const Section, Ident: String): IJcIniFile; function DeleteSection(const Section: String): IJcIniFile; function GetSections(var Sections: TStrings): IJcIniFile; function GetSectionValues(const Section: String; Strings: TStrings): IJcIniFile; function GetString(const Section, Ident, Default: string): string; function GetInteger(const Section, Ident: string; Default: integer): integer; function GetBoolean(const Section, Ident: string; Default: Boolean): Boolean; end; implementation uses Forms, SysUtils; { TJcIniFile } class function TJcIniFile.New(AFileName: String = ''): IJcIniFile; begin Result := Self.Create(AFileName); end; class function TJcIniFile.Get(AFileName: String): IJcIniFile; begin Result := Self.Create(AFileName); end; constructor TJcIniFile.Create(AFileName: String); begin if AFileName <> '' then FileName(AFileName); end; destructor TJcIniFile.Destroy; begin if Assigned(FIniFile) then FreeAndNil(FIniFile); inherited; end; function TJcIniFile.FileName(const Value: string): IJcIniFile; begin result := self; FFileName := Value; if Assigned(FIniFile) then FreeAndNil(FIniFile); FIniFile := TIniFile.Create(FFileName); end; function TJcIniFile.AddSection(const Section, Values: string): IJcIniFile; var vValues: TStrings; vI: Integer; begin result := self; DeleteSection(Section); vValues := TStringList.Create; vValues.Text := Values; try for vI := 0 to vValues.Count-1 do self.AddString(Section, vValues.Names[vI], vValues.ValueFromIndex[vI]); finally vValues.Free; end; end; function TJcIniFile.AddString(const Section, Ident, Value: string): IJcIniFile; begin result := self; FIniFile.WriteString(Section, Ident, Value); end; function TJcIniFile.AddInteger(const Section, Ident: string; Value: integer): IJcIniFile; begin result := self; FIniFile.WriteInteger(Section, Ident, Value); end; function TJcIniFile.AddBoolean(const Section, Ident: string; Value: Boolean): IJcIniFile; begin FIniFile.WriteBool(Section, Ident, Value); result := self; end; function TJcIniFile.DeleteKey(const Section, Ident: String): IJcIniFile; begin FIniFile.DeleteKey(Section, Ident); result := self; end; function TJcIniFile.DeleteSection(const Section: String): IJcIniFile; begin FIniFile.EraseSection(Section); result := self; end; function TJcIniFile.GetSections(var Sections: TStrings): IJcIniFile; begin result := self; FIniFile.ReadSections(Sections); end; function TJcIniFile.GetSectionValues(const Section: String; Strings: TStrings): IJcIniFile; begin result := self; FIniFile.ReadSectionValues(Section, Strings); end; function TJcIniFile.GetString(const Section, Ident, Default: string): string; begin try Result := FIniFile.ReadString(Section, Ident, Default); except Result := Default; end; end; function TJcIniFile.GetInteger(const Section, Ident: string; Default: integer): integer; begin Result := FIniFile.ReadInteger(Section, Ident, Default); end; function TJcIniFile.GetBoolean(const Section, Ident: string; Default: Boolean): Boolean; begin try Result := FIniFile.ReadBool(Section, Ident, Default); except Result := Default; end; end; end.
unit Constants; interface const NotFound = -1; InvalidParamTypeError = 'O tipo do parâmetro informado (%s) é inválido.'#13#10'Utilize apenas os tipos varString, varOleStr, varUString, varSmallInt, varInteger, varBoolean, varShortInt, varByte, varWord, varLongWord, varInt64, varUInt64.'; ScenarioRegex = '^(\s*)Cenário:\s'; FeatureRegex: UTF8String = '^(\s|)*Funcionalidade:\s*'; StepRegex: UTF8String = '^(\s*)(Dado|Quando|Então|E|Mas)\s.*'; StepValidWord: UTF8String = '^(\s*)(Dado|Quando|Então|E|Mas)\b'; FirstWordRegex: UTF8String = '\b\w*\b'; InvalidStepIdentifierError = 'A linha %d começa com uma palavra chave desconhecida (%s).'; SugestedActionToStepError = 'Os passos devem começar com: Dado, Quando, E, Então, e Mas'; InvalidStepDefinition = 'O passo da linha %d deve conter mais do que apenas uma palavra.'; InvalidFeature = 'A feature ''%s'' não começa com a palavra Funcionalidade: seguida de seu título na primeira linha.'; SugestionToStepInitialize = '%s... ?!'; SugestionToFeatureInitialize = 'Exemplo: Funcionalidade: Aqui vai o título da sua funcionalidade.'; InvalidFeatureFileName = 'O arquivo que você tentou carregar (%s) não existe.'; SugestionToInvalidFeatureName = 'Tente carregar um arquivo que exista :)'; implementation end.
{ Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit LogViewer.MessageFilter.View; { User interface for message filter treeview. } interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, VirtualTrees, DDuce.Logger.Interfaces, DDuce.Components.VirtualTrees.Node, LogViewer.MessageList.Settings, LogViewer.MessageFilter.Data; type TFilterNode = TVTNode<TFilterData>; type TfrmMessageFilter = class(TForm) pnlMessageFilter : TPanel; private FTree : TVirtualStringTree; FImageList : TImageList; FSettings : TMessageListSettings; protected procedure BuildTree; {$REGION 'event handlers'} procedure FTreeGetText( Sender : TBaseVirtualTree; Node : PVirtualNode; Column : TColumnIndex; TextType : TVSTTextType; var CellText : string ); procedure FTreeGetImageIndex( Sender : TBaseVirtualTree; Node : PVirtualNode; Kind : TVTImageKind; Column : TColumnIndex; var Ghosted : Boolean; var ImageIndex : TImageIndex ); procedure FTreeFocusChanged( Sender : TBaseVirtualTree; Node : PVirtualNode; Column : TColumnIndex ); procedure FTreeFreeNode( Sender: TBaseVirtualTree; Node: PVirtualNode ); procedure FTreeChecked( Sender : TBaseVirtualTree; Node : PVirtualNode ); procedure FSettingsChanged(Sender: TObject); {$ENDREGION} function UpdateChildren( ANode : TFilterNode; ACheckState : TCheckState ): Boolean; function UpdateParent( ANode : TFilterNode; ACheckState : TCheckState ): Boolean; public constructor Create( AOwner : TComponent; ASettings : TMessageListSettings; AImageList : TImageList ); reintroduce; virtual; procedure AfterConstruction; override; procedure BeforeDestruction; override; end; implementation {$R *.dfm} uses System.StrUtils, Spring, DDuce.Factories.VirtualTrees, DDuce.Logger, LogViewer.Resources; {$REGION 'construction and destruction'} procedure TfrmMessageFilter.AfterConstruction; begin inherited AfterConstruction; FTree := TVirtualStringTreeFactory.CreateTree(Self, pnlMessageFilter); FTree.OnGetText := FTreeGetText; FTree.OnGetImageIndex := FTreeGetImageIndex; FTree.OnFreeNode := FTreeFreeNode; FTree.OnFocusChanged := FTreeFocusChanged; FTree.OnChecked := FTreeChecked; FTree.Header.Options := FTree.Header.Options - [hoVisible]; FTree.TreeOptions.PaintOptions := FTree.TreeOptions.PaintOptions + [toShowTreeLines]; FTree.TreeOptions.SelectionOptions := FTree.TreeOptions.SelectionOptions + [toMultiSelect]; FTree.Margins.Right := 0; FTree.Images := FImageList; FTree.StateImages := FImageList; BuildTree; end; constructor TfrmMessageFilter.Create(AOwner: TComponent; ASettings: TMessageListSettings; AImageList: TImageList); begin inherited Create(AOwner); Guard.CheckNotNull(ASettings, 'ASettings'); Guard.CheckNotNull(AImageList, 'AImageList'); FSettings := ASettings; FImageList := AImageList; end; procedure TfrmMessageFilter.BeforeDestruction; begin FTree.Free; inherited BeforeDestruction; end; {$ENDREGION} {$REGION 'event handlers'} procedure TfrmMessageFilter.FSettingsChanged(Sender: TObject); begin // end; procedure TfrmMessageFilter.FTreeChecked(Sender: TBaseVirtualTree; Node: PVirtualNode); var FN : TFilterNode; I : Integer; begin FN := Sender.GetNodeData<TFilterNode>(Node); if FN.VNode.CheckState.IsChecked then begin FSettings.VisibleMessageTypes := FSettings.VisibleMessageTypes + FN.Data.MessageTypes; if MatchText(FN.Data.Caption, ['SQL', 'INI', 'JSON']) then FSettings.VisibleValueTypes.Add(FN.Data.Caption); end else begin FSettings.VisibleMessageTypes := FSettings.VisibleMessageTypes - FN.Data.MessageTypes; if MatchText(FN.Data.Caption, ['SQL', 'INI', 'JSON']) then begin I := FSettings.VisibleValueTypes.IndexOf(FN.Data.Caption); if I <> -1 then begin FSettings.VisibleValueTypes.Delete(I); end; end; end; Logger.SendStrings(FSettings.VisibleValueTypes); UpdateChildren(FN, FN.VNode.CheckState); UpdateParent(FN, FN.VNode.CheckState); end; procedure TfrmMessageFilter.FTreeFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); begin // end; procedure TfrmMessageFilter.FTreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); var FN : TFilterNode; begin FN := Sender.GetNodeData<TFilterNode>(Node); FN.Free; end; procedure TfrmMessageFilter.FTreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: TImageIndex); var FN : TFilterNode; begin if Kind in [ikNormal, ikSelected] then begin FN := Sender.GetNodeData<TFilterNode>(Node); if Assigned(FN) and Assigned(FN.Data) then ImageIndex := FN.ImageIndex; end; end; procedure TfrmMessageFilter.FTreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var FN : TFilterNode; begin FN := Sender.GetNodeData<TFilterNode>(Node); if Assigned(FN) and Assigned(FN.Data) then CellText := FN.Data.Caption; end; {$ENDREGION} {$REGION 'protected methods'} procedure TfrmMessageFilter.BuildTree; var LNode : TFilterNode; function AddNode( ACaption : string; AImageIndex : Integer = -1; AMessageTypes : TLogMessageTypes = [] ): TFilterNode; begin if Assigned(LNode) then begin Result := LNode.Add(TFilterData.Create(ACaption, AMessageTypes)); end else begin Result := TFilterNode.Create(FTree, TFilterData.Create(ACaption, AMessageTypes)); end; Result.ImageIndex := AImageIndex; Result.CheckType := ctCheckBox; if AMessageTypes * FSettings.VisibleMessageTypes = AMessageTypes then Result.CheckState := csCheckedNormal; end; begin LNode := nil; LNode := AddNode(SNotificationMessages, -1, [lmtInfo, lmtWarning, lmtError]); AddNode(SInfo, 0, [lmtInfo]); AddNode(SWarning, 2, [lmtWarning]); AddNode(SError, 1, [lmtError]); LNode := nil; LNode := AddNode(SValueMessages, - 1, [lmtValue, lmtStrings, lmtComponent, lmtColor, lmtAlphaColor, lmtPersistent, lmtInterface, lmtObject, lmtDataSet, lmtAction, lmtBitmap, lmtScreenshot, lmtException]); AddNode(SValue, 19, [lmtValue]); AddNode(SStrings, 8, [lmtStrings]); AddNode(SComponent, 10, [lmtComponent]); AddNode(SColor, 22, [lmtColor, lmtAlphaColor]); AddNode(SPersistent, 16, [lmtPersistent]); AddNode(SInterface, 17, [lmtInterface]); AddNode(SObject, 18, [lmtObject]); AddNode(SDataSet, 20, [lmtDataSet]); AddNode(SAction, 21, [lmtAction]); AddNode(SBitmap, 12, [lmtBitmap]); AddNode(SScreenshot, 12, [lmtScreenshot]); AddNode(SException, 11, [lmtException]); LNode := nil; LNode := AddNode(STextMessages, 24); AddNode('SQL', 27, [lmtText]); AddNode('XML', 28, [lmtText]); AddNode('INI', 0, [lmtText]); AddNode('JSON', 26, [lmtText]); FSettings.VisibleValueTypes.Add('SQL'); FSettings.VisibleValueTypes.Add('XML'); FSettings.VisibleValueTypes.Add('INI'); FSettings.VisibleValueTypes.Add('JSON'); Logger.SendStrings(FSettings.VisibleValueTypes); LNode := nil; LNode := AddNode( STraceMessages, 25, [lmtCheckpoint, lmtCounter, lmtEnterMethod, lmtLeaveMethod] ); AddNode(SCheckpoint, 7, [lmtCheckpoint]); AddNode(SCounter, 23, [lmtCounter]); LNode := AddNode(STrackMethod, 9, [lmtEnterMethod, lmtLeaveMethod]); AddNode(SEnter, 4, [lmtEnterMethod]); AddNode(SLeave, 5, [lmtLeaveMethod]); FTree.FullExpand; end; { Updates checkbox state of children if applicable. } function TfrmMessageFilter.UpdateChildren(ANode: TFilterNode; ACheckState: TCheckState): Boolean; var N : TFilterNode; I : Integer; begin if ANode.ChildCount > 0 then begin for I := 0 to ANode.ChildCount - 1 do begin N := ANode.Items[I]; N.CheckState := ACheckState; FTree.RepaintNode(N.VNode); UpdateChildren(N, ACheckState); end; Result := True; end else Result := False; end; function TfrmMessageFilter.UpdateParent(ANode: TFilterNode; ACheckState: TCheckState): Boolean; var LFirstChild : PVirtualNode; LLastChild : PVirtualNode; N : PVirtualNode; B : Boolean; begin Logger.Track(Self, 'UpdateParent'); if Assigned(ANode) and Assigned(ANode.VNode) and Assigned(ANode.VNode.Parent) then begin LFirstChild := ANode.VNode.Parent.FirstChild; LLastChild := ANode.VNode.Parent.LastChild; N := LFirstChild; B := Assigned(N) and (N.CheckState = ACheckState); while B and (N <> LLastChild) do begin N := N.NextSibling; B := B and Assigned(N) and (N.CheckState = ACheckState); end; if B then begin ANode.VNode.Parent.CheckState := ACheckState; end else begin ANode.VNode.Parent.CheckState := csMixedNormal; end; FTree.RepaintNode(ANode.VNode.Parent); Result := B; end else Result := False; end; {$ENDREGION} end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.TypInfo, Vcl.ExtCtrls, Vcl.ComCtrls; type TPessoa = class(Tpersistent) private FIdade: Integer; FNome: String; FData: TDateTime; procedure SetData(const Value: TDateTime); procedure SetIdade(const Value: Integer); procedure SetNome(const Value: String); published property Nome: String read FNome write SetNome; property Idade: Integer read FIdade write SetIdade; property Data: TDateTime read FData write SetData; end; type TBindRec = record obj: TPersistent; prop: String; valor: variant; data: TDateTime; end; type TProc = function (objOrig, objDest: TBindRec):boolean of object; type TBind = class private _objOrigem: TBindRec; _objDestino: TBindRec; function _execute(objOrig, objDest: TBindRec): Boolean; public Execute :Tproc; constructor Create(objOrigem: TbindRec; objDestino:TbindRec); end; type TBindController = class private _binds : Array of Tbind; _timer: TTimer; procedure onTimer(Sender: TObject); public constructor Create(); procedure Add(bind: Tbind); end; type TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; Label1: TLabel; Label2: TLabel; Edit2: TEdit; TrackBar1: TTrackBar; ProgressBar1: TProgressBar; Edit3: TEdit; Edit4: TEdit; Button2: TButton; DateTimePicker1: TDateTimePicker; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } BindController : TBindController; public { Public declarations } pessoa: TPessoa; function ConversaoData(objOrig, objDest: TBindRec):Boolean; end; var Form1: TForm1; implementation {$R *.dfm} { TBind } constructor TBind.Create(objOrigem: TbindRec; objDestino: TbindRec); begin _objOrigem := objOrigem; _objDestino := objDestino; execute := _execute; end; function TBind._execute(objOrig, objDest: TBindRec): Boolean; var value: variant; begin try value := GetPropValue( objOrig.obj, objOrig.prop ); SetPropValue(objDest.obj, objDest.prop, value); result := True; except result := false; end; end; { TBindController } procedure TBindController.Add(bind: Tbind); var pos: integer; begin pos := length( _binds )+1; SetLength(_binds, pos); _binds[pos-1] := bind; end; constructor TBindController.Create; begin _timer := TTimer.Create(nil); _timer.OnTimer := ontimer; _timer.Interval := 100; end; procedure TBindController.onTimer(Sender: TObject); var i: integer; begin for i := 0 to Length(_binds)-1 do begin _binds[i].Execute(_binds[i]._objOrigem, _binds[i]._objDestino); end; end; procedure TForm1.Button1Click(Sender: TObject); var bind: Tbind; origem, destino: TBindRec; function NewBindRec(obj: TPersistent; Prop: String):TBindRec; begin result.obj := obj; result.prop := prop; end; function NewBind(objOrigem: TPersistent; propOrigem: String; objDestino: TPersistent; propDestino: String): TBind; begin result := TBind.Create( newbindrec(objOrigem, PropOrigem), newbindrec(objDestino, PropDestino)); end; begin BindController := TBindController.Create; pessoa := TPessoa.Create; BindController.Add(newbind(edit1,'text', pessoa,'nome')); BindController.Add(newbind(TrackBar1,'position', pessoa,'idade')); bind := newbind(edit3,'text', pessoa,'data'); bind.Execute := ConversaoData; BindController.Add(bind); BindController.Add(newbind(pessoa,'nome', label1,'caption')); BindController.Add(newbind(pessoa,'Idade', label2,'caption')); BindController.Add(newbind(pessoa,'data', DateTimePicker1,'date')); bindcontroller.Add(newbind(pessoa,'idade', ProgressBar1,'position')); // origem.obj := edit1; // origem.prop := 'text'; // // destino.obj := label1; // destino.prop := 'caption'; // // bind := tbind.Create( origem, destino ); // // BindController.Add( bind ); // bindcontroller.Add( tbind.Create(newBindRec(edit2,'text'), newbindrec(label2,'caption')) ); // bindController.Add( newBind( edit1, 'text', self, 'caption' ) ); // bindcontroller.Add( newBind(TrackBar1, 'position', ProgressBar1, 'position') ); // // BindController.Add( newbind(edit3,'text',edit4, 'text') ); end; { Tpessoas } procedure TPessoa.SetData(const Value: TDateTime); begin FData := Value; end; procedure TPessoa.SetIdade(const Value: Integer); begin FIdade := Value; end; procedure TPessoa.SetNome(const Value: String); begin FNome := Value; end; procedure TForm1.Button2Click(Sender: TObject); begin showmessage(pessoa.Nome); end; function TForm1.ConversaoData(objOrig, objDest: TBindRec): Boolean; var value: variant; begin try value := GetPropValue( objOrig.obj, objOrig.prop ); SetPropValue(objDest.obj, objDest.prop, StrToDate( value ) ); result := True; except result := false; end; end; end.
unit QuickExportSetup; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,save_txt_dialog; type TQuickExportSetupForm = class(TForm) SkipDescr: TCheckBox; WordWrap: TCheckBox; IndentEdit: TEdit; Hyph: TCheckBox; Indent: TCheckBox; WidthEdit: TEdit; EncodingsList: TComboBox; BRTypeList: TComboBox; Label1: TLabel; Label2: TLabel; Button1: TButton; Button2: TButton; IgnoreStrongC: TCheckBox; IgnoreItalicC: TCheckBox; procedure FormCreate(Sender: TObject); procedure WordWrapClick(Sender: TObject); procedure WordWrapKeyPress(Sender: TObject; var Key: Char); procedure IndentClick(Sender: TObject); procedure IndentKeyPress(Sender: TObject; var Key: Char); procedure Button1Click(Sender: TObject); procedure WidthEditChange(Sender: TObject); private { Private declarations } ParentHandle:THandle; Key:String; public { Public declarations } constructor CreateWithForeighnParent(AParent:THandle;AKey:String); procedure CreateParams(var Params: TCreateParams); override; end; var QuickExportSetupForm: TQuickExportSetupForm; const QuickSetupKey=RegistryKey+'\quick\'; implementation uses Registry; {$R *.dfm} constructor TQuickExportSetupForm.CreateWithForeighnParent; Begin ParentHandle:=AParent; Key:=QuickSetupKey+AKey; create(Nil); end; procedure TQuickExportSetupForm.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.WndParent := ParentHandle; end; procedure TQuickExportSetupForm.FormCreate(Sender: TObject); Var I:Integer; VerInfo:TOSVersionInfo; Reg:TRegistry; begin EncodingsList.AddItem('ANSI system default codepage',Pointer(CP_ACP)); EncodingsList.AddItem('OEM system default codepage',Pointer(CP_OEMCP)); EncodingsList.AddItem('MAC system default codepage',Pointer(CP_MACCP)); VerInfo.dwOSVersionInfoSize:=SizeOf(VerInfo); GetVersionEx(VerInfo); if VerInfo.dwPlatformId=VER_PLATFORM_WIN32_NT then EncodingsList.AddItem('UTF-8',Pointer(CP_UTF8));// For WinNT only EncodingsList.AddItem('UTF-16',Pointer(CP_UTF16)); For I:=1 to EncCount do EncodingsList.AddItem(IntToStr(SupportedEncodings[i].CP)+' - '+SupportedEncodings[i].Name, Pointer(SupportedEncodings[i].CP)); For I:=1 to BrCount do BRTypeList.AddItem(BRTypes[I].Name,Nil); BRTypeList.ItemIndex:=0; EncodingsList.ItemIndex:=0; Reg:=TRegistry.Create(KEY_READ); Try Try if Reg.OpenKeyReadOnly(Key) then Begin WordWrap.Checked:=Reg.ReadBool('Word wrap'); SkipDescr.Checked:=Reg.ReadBool('Skip description'); Indent.Checked:=Reg.ReadBool('Do indent para'); Hyph.Checked:=Reg.ReadBool('Hyphenate'); WidthEdit.Text:=IntToStr(Reg.ReadInteger('Text width')); IndentEdit.Text:=Reg.ReadString('Indent text'); EncodingsList.ItemIndex:=EncodingsList.Items.IndexOfObject(Pointer(Reg.ReadInteger('File codepage'))); BRTypeList.ItemIndex:=Reg.ReadInteger('Line breaks type'); IgnoreStrongC.Checked:=Reg.ReadBool('Ignore strong'); IgnoreItalicC.Checked:=Reg.ReadBool('Ignore emphasis'); end; Finally Reg.Free; end; Except end; WordWrapClick(Nil); IndentClick(Nil); end; procedure TQuickExportSetupForm.WordWrapClick(Sender: TObject); begin WidthEdit.Enabled:=WordWrap.Checked; Hyph.Enabled:=WordWrap.Checked; end; procedure TQuickExportSetupForm.WordWrapKeyPress(Sender: TObject; var Key: Char); begin WordWrapClick(Nil); end; procedure TQuickExportSetupForm.IndentClick(Sender: TObject); begin IndentEdit.Enabled:=Indent.Checked; end; procedure TQuickExportSetupForm.IndentKeyPress(Sender: TObject; var Key: Char); begin IndentClick(Nil); end; procedure TQuickExportSetupForm.Button1Click(Sender: TObject); Var Reg:TRegistry; begin Reg:=TRegistry.Create(KEY_ALL_ACCESS); Try if Reg.OpenKey(Key,True) then Begin Reg.WriteBool('Word wrap',WordWrap.Checked); Reg.WriteBool('Skip description',SkipDescr.Checked); Reg.WriteBool('Do indent para',Indent.Checked); Reg.WriteBool('Hyphenate',Hyph.Checked); Reg.WriteInteger('Text width',StrToInt(WidthEdit.Text)); Reg.WriteString('Indent text',IndentEdit.Text); Reg.WriteInteger('File codepage',Integer(EncodingsList.Items.Objects[EncodingsList.ItemIndex])); Reg.WriteInteger('Line breaks type',BRTypeList.ItemIndex); Reg.WriteBool('Ignore strong',IgnoreStrongC.Checked); Reg.WriteBool('Ignore emphasis',IgnoreItalicC.Checked); end; Finally Reg.Free; end; end; procedure TQuickExportSetupForm.WidthEditChange(Sender: TObject); begin try StrToInt(WidthEdit.Text); except WidthEdit.Text:='80'; end; end; end.
unit dcNDateEditBtn; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, rxToolEdit, rxDateUtil, datacontroller, db, FFSUtils, ffstypes, stooledit, sConst, sPopupClndr; type TDateStorageFormat = (dsfMMDDYYYY, dsfYYYYMMDD); // TdcNDateEditBtn = class(TsDateEdit) TdcNDateEditBtn = class(TsCustomDateEdit) private OldReadonly: boolean; FNonDates: TFFSNonDates; FFormatting: Boolean; fdcLink: TdcLink; FClearing: boolean; FStorageFormat: TDateStorageFormat; FOnF3: TNotifyEvent; //july 2012 function GetDataBufIndex: integer; procedure SetDataBufIndex(const Value: integer); procedure SetClearing(const Value: boolean); procedure SetNonDates(const Value: TFFSNonDates); function DateIsBlank(s: string): boolean; procedure SetDate(Value: TDateTime); constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CheckValidDate2; procedure SetStorageFormat(const Value: TDateStorageFormat); function GetDataController: TDataController; function GetDataField: string; function getDataSource: TDataSource; procedure setDataController(const Value: TDataController); procedure SetDataField(const Value: string); procedure SetDatasource(const Value: TDataSource); property Clearing: boolean read FClearing write SetClearing; procedure SetOnF3(const Value: TNotifyEvent); protected property Formatting: Boolean read FFormatting; procedure KeyPress(var Key: Char); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure ReadData(sender: TObject); procedure WriteData(sender: TObject); procedure ClearData(sender: TObject); procedure Change; override; procedure DoEnter; override; procedure DoExit; override; published // new property BlanksChar; property CalendarHints; property CheckOnExit; property ClickKey; property Date; property DefaultToday; property DialogTitle; property MaxDate; property MinDate; property PopupAlign; property PopupHeight; property PopupWidth; property StartOfWeek; property Text; property Weekends; property WeekendColor; property YearDigits; //new property NonDates: TFFSNonDates read FNonDates write SetNonDates; property DataController: TDataController read GetDataController write setDataController; property DataField: string read GetDataField write SetDataField; property DataSource: TDataSource read getDataSource write SetDatasource; property DataBufIndex: integer read GetDataBufIndex write SetDataBufIndex; property OnF3:TNotifyEvent read FOnF3 write SetOnF3; //july2012 public property StorageFormat: TDateStorageFormat read FStorageFormat write SetStorageFormat; {:@event} // property OnChange; end; procedure Register; implementation uses StrUtils; const DateEditMask = '!99/99/9999;1;'; procedure Register; begin RegisterComponents('FFSNew', [TdcNDateEditBtn]); end; function NvlDate(DateValue, DefaultValue: TDateTime): TDateTime; begin if (DateValue = NullDate) or (DateValue = BadDate) then Result := DefaultValue else Result := DateValue; end; { TdcNDateEditBtn } procedure TdcNDateEditBtn.Change; begin //inherited; if assigned(fdclink.datacontroller) then if not clearing then fdclink.BeginEdit; inherited; //july2012 end; procedure TdcNDateEditBtn.CheckValidDate2; var okdate: boolean; dt: TFFSDate; begin try FFormatting := True; try dt := ffsutils.ConvertToDate(Text); if dt = baddate then raise EInvalidDateException.Create('Invalid Date Entered'); SetDate(dt); finally FFormatting := False; end; except okdate := false; if (ndCont in nondates) and (copy(text, 1, 1) = copy(dvStrings[ndCont], 1, 1)) then okdate := true; if (ndWaived in nondates) and (copy(text, 1, 1) = copy(dvStrings[ndWaived], 1, 1)) then okdate := true; if (ndHist in nondates) and (copy(text, 1, 1) = copy(dvStrings[ndHist], 1, 1)) then okdate := true; if (ndNA in nondates) and (copy(text, 1, 1) = copy(dvStrings[ndNA], 1, 1)) then okdate := true; if (ndSatisfied in nondates) and (copy(text, 1, 1) = copy(dvStrings[ndSatisfied], 1, 1)) then okdate := true; if DateisBlank(Text) then // = ' / / ' then // //JUL 2012 begin EditMask := ''; Text := ''; Okdate := true; end; if not okdate then begin if CanFocus then SetFocus; EditMask := DateEditMask; raise; end; end; end; procedure TdcNDateEditBtn.ClearData(sender: TObject); begin clearing := true; editmask := ''; text := ''; clearing := false; end; constructor TdcNDateEditBtn.Create(AOwner: TComponent); begin // inherited; inherited Create(AOwner); CheckValidDate2; { if not DefaultToday or DateIsBlank(Text) then begin EditMask := ''; Text := ''; end; } fdclink := tdclink.create(self); fdclink.OnReadData := ReadData; fdclink.OnWriteData := WriteData; fdclink.OnClearData := ClearData; fStorageFormat := dsfMMDDYYYY; end; function TdcNDateEditBtn.DateIsBlank(s: string): boolean; var x: integer; nb: boolean; begin nb := false; for x := 1 to length(s) do begin if not (s[x] in [' ', '/']) then nb := true; end; result := not nb; end; destructor TdcNDateEditBtn.Destroy; begin fdclink.free; inherited Destroy; end; procedure TdcNDateEditBtn.DoEnter; begin // OldReadOnly := ReadOnly; if Assigned(FDCLink.DataController) then begin if DataController.ReadOnly then ReadOnly := true; end; {if not readonly then begin if (EditType in [etString, etUppercase, etMixedCase, etLowerCase, etPassword]) and (maskFormat > mtNone) then text := StripMask(Text, maskFormat); end; } end; procedure TdcNDateEditBtn.DoExit; begin { if not readonly then begin if (EditType in [etString, etUppercase, etMixedCase, etLowerCase, etPassword]) and (maskFormat > mtNone) then text := AddMask(Text, maskFormat); end; } // ReadOnly := OldReadOnly; end; function TdcNDateEditBtn.GetDataBufIndex: integer; begin result := 0; if assigned(fdclink.Datacontroller) then if assigned(fdclink.datacontroller.databuf) then result := fdclink.datacontroller.databuf.FieldNameToIndex(fdclink.FieldName); end; function TdcNDateEditBtn.GetDataController: TDataController; begin result := fdcLink.DataController; end; function TdcNDateEditBtn.GetDataField: string; begin result := fdclink.FieldName; end; function TdcNDateEditBtn.getDataSource: TDataSource; begin result := fdclink.DataSource; end; procedure TdcNDateEditBtn.KeyDown(var Key: Word; Shift: TShiftState); var s: string; n, ok: integer; begin { if (Key in [VK_PRIOR, VK_NEXT, VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN, VK_ADD, VK_SUBTRACT]) then //and PopupVisible then begin if readonly then begin key := 0; exit; end; // TFFSPopupWindow(FPopup).KeyDown(Key, Shift); Key := 0; end else}if DirectInput then begin if readonly then begin key := 0; exit; end; case Key of Ord('A'): if (shift = []) then begin s := ''; if inputquery('Advance Date by Months', 'Number of months to advance', s) then begin val(s, n, ok); if ok = 0 then ApplyDate(IncMonth(NvlDate(Date, Now), n)); SelectAll; end; Key := 0; end; Ord('Q'): if (shift = [ssShift]) or (shift = []) then begin if shift = [ssShift] then ApplyDate(IncMonth(NvlDate(Date, Now), -3)) else ApplyDate(IncMonth(NvlDate(Date, Now), 3)); SelectAll; key := 0; end; Ord('Y'): if (shift = [ssShift]) or (shift = []) then begin if shift = [ssShift] then ApplyDate(IncMonth(NvlDate(Date, Now), -12)) else ApplyDate(IncMonth(NvlDate(Date, Now), 12)); SelectAll; key := 0; end; Ord('M'): if (shift = [ssShift]) or (shift = []) then begin if shift = [ssShift] then ApplyDate(IncMonth(NvlDate(Date, Now), -1)) else ApplyDate(IncMonth(NvlDate(Date, Now), 1)); SelectAll; key := 0; end; Ord('D'): if (shift = [ssShift]) or (shift = []) then begin if shift = [ssShift] then ApplyDate(NvlDate(Date, Now) - 1) else ApplyDate(NvlDate(Date, Now) + 1); SelectAll; key := 0; end; VK_PRIOR: if (shift = [ssCtrl]) or (shift = []) then begin if shift = [ssCtrl] then ApplyDate(IncMonth(NvlDate(Date, Now), -12)) else ApplyDate(IncMonth(NvlDate(Date, Now), -1)); SelectAll; Key := 0; end; VK_NEXT: if (shift = [ssCtrl]) or (shift = []) then begin if shift = [ssCtrl] then ApplyDate(IncMonth(NvlDate(Date, Now), 12)) else ApplyDate(IncMonth(NvlDate(Date, Now), 1)); SelectAll; Key := 0; end; VK_UP, VK_SUBTRACT: if (shift = []) then begin ApplyDate(NvlDate(Date, Now) - 1); SelectAll; Key := 0; end; VK_DOWN, VK_ADD: if (shift = []) then begin ApplyDate(NvlDate(Date, Now) + 1); SelectAll; Key := 0; end; {VK_DELETE, VK_BACK: if (shift = []) then begin if editmask = '' then begin text := ''; key := 0; end else begin // if (sellength = 10) and (editmask = DateEditMask) then if editmask = DateEditMask then begin EditMask := ''; Text := ''; key := 0; end; end; end; } end; end; inherited KeyDown(Key, Shift); end; procedure TdcNDateEditBtn.KeyPress(var Key: Char); procedure UpdateValue(var akey: char); begin // if Self.DroppedDown then PopupCloseUp(self, false); EditMask := ''; case upcase(akey) of 'C': text := dvStrings[ndCont]; 'W': text := dvStrings[ndWaived]; 'H': text := dvStrings[ndHist]; 'N': text := dvStrings[ndNA]; //'O' : text := dvStrings[ndOpen]; 'S': text := dvStrings[ndSatisfied]; //'X' : text := dvStrings[ndNewLoan]; end; SelectAll; akey := #0; end; // begin if not readonly then begin if key = ' ' then key := 'T'; // default space to TODAY case upcase(key) of 'C': if ndCont in nondates then UpdateValue(Key) else key := #0; 'W': if ndWaived in nondates then UpdateValue(Key) else key := #0; 'H': if ndHist in nondates then UpdateValue(Key) else key := #0; 'N': if ndNA in nondates then UpdateValue(Key) else key := #0; 'S': if ndSatisfied in nondates then UpdateValue(Key) else key := #0; 'T', '0'..'9': begin if EditMask <> DateEditMask then begin text := EmptyStr; EditMask := DateEditMask; end; end; #13: CheckValidDate2; else if not Self.DroppedDown then key := #0; end; // if (Key in ['T', 't', '+', '-']) and self.DroppedDown then begin TsPopupCalendar(FPopupWindow).FCalendar.FGrid.KeyPress(Key); Key := #0; end else if DirectInput then begin case upcase(key) of 'T': begin ApplyDate(Trunc(Now)); Key := #0; end; end; end; end; inherited KeyPress(key); end; procedure TdcNDateEditBtn.ReadData(sender: TObject); var originalData: string; begin if not assigned(fdclink.DataController) then exit; OriginalData := ''; if (DataBufIndex = 0) and (DataField <> '') then OriginalData := fdcLink.DataController.dcStrings.StrVal[DataField] else if assigned(fdclink.datacontroller.databuf) then OriginalData := fdclink.datacontroller.databuf.AsString[DataBufIndex]; if (OriginalData > '') then begin if not (Originaldata[1] in ['0'..'9']) then editmask := '' else editmask := dateEditMask; if (StorageFormat = dsfYYYYMMDD) then begin if OriginalData[1] in ['0'..'9'] then OriginalData := copy(OriginalData, 5, 2) + '/' + copy(originaldata, 7, 2) + '/' + copy(originaldata, 1, 4); end; end else editmask := ''; text := OriginalData; try CheckValidDate2; except end; end; procedure TdcNDateEditBtn.SetClearing(const Value: boolean); begin FClearing := Value; end; procedure TdcNDateEditBtn.SetDataBufIndex(const Value: integer); begin end; procedure TdcNDateEditBtn.setDataController(const Value: TDataController); begin fdcLink.datacontroller := value; end; procedure TdcNDateEditBtn.SetDataField(const Value: string); begin fdclink.FieldName := value; end; procedure TdcNDateEditBtn.SetDatasource(const Value: TDataSource); begin // intentionally blank end; procedure TdcNDateEditBtn.SetDate(Value: TDateTime); var D: TDateTime; begin if not rxDateUtil.ValidDate(Value) or (Value = NullDate) then begin if DefaultToday then Value := SysUtils.Date else Value := NullDate; end; D := self.Date; if Value = NullDate then begin Text := ''; EditMask := ''; end else begin EditMask := DateEditMask; Text := ffsutils.DateToShortString(value); // FormatDateTime(sDateFormat, Value); end; Modified := D <> Date; end; procedure TdcNDateEditBtn.SetNonDates(const Value: TFFSNonDates); begin FNonDates := Value; end; procedure TdcNDateEditBtn.SetOnF3(const Value: TNotifyEvent); begin FOnF3 := Value; end; procedure TdcNDateEditBtn.SetStorageFormat( const Value: TDateStorageFormat); begin FStorageFormat := Value; end; procedure TdcNDateEditBtn.WriteData(sender: TObject); var s: string; begin if not assigned(fdclink.DataController) then exit; if ValidDate(self.Date) and (self.date <> NULLDATE) then begin case StorageFormat of dsfMMDDYYYY: s := FormatDateTime('mm/dd/yyyy', self.date); dsfYYYYMMDD: s := FormatDateTime('yyyymmdd', self.date); end; end else s := text; if (DataBufIndex = 0) and (DataField <> '') then fdcLink.DataController.dcStrings.StrVal[DataField] := s else if assigned(fdclink.datacontroller.databuf) then fdclink.datacontroller.databuf.asString[DataBufIndex] := s; end; end.
{ Module containing the default SST library routines for manipulating the * output character stream. Pointers to these routines are installed in the * SST_W call table by SST_INIT. All the state that these routines manipulate * other than the output lines themselves is in the global record SST_OUT. * This is declared in SST.INS.PAS. } module sst_out_module; define sst_out_allow_break; define sst_out_append; define sst_out_appendn; define sst_out_appends; define sst_out_append_sym_name; define sst_out_blank_line; define sst_out_break; define sst_out_comment_end; define sst_out_comment_set; define sst_out_comment_start; define sst_out_delimit; define sst_out_indent; define sst_out_line_close; define sst_out_line_insert; define sst_out_line_new; define sst_out_line_new_cont; define sst_out_name; define sst_out_name_sym; define sst_out_notify_src_range; define sst_out_tab_indent; define sst_out_undent; define sst_out_undent_all; define sst_out_write; %include 'sst2.ins.pas'; { ************************************************************************** * * Subroutine SST_OUT_ALLOW_BREAK * * Indicate that a line break is allowed at the current position, if needed * later. The line break will occurr at this position if more characters are * appended to the current line and the resulting line length would exceed * the WRAP_LEN parameter. } procedure sst_out_allow_break; {allow line break at current position} begin case sst_out.dyn_p^.wpos of {where is write position rel to curr line ?} sst_wpos_before_k, {before start of current line} sst_wpos_after_k: begin {after end of current line} return; {nothing to break} end; end; {done with special handling write pos cases} if sst_out.dyn_p^.str_p^.s.len > 0 then begin {anything here to break ?} sst_out.dyn_p^.break_len := {save where this line would end} sst_out.dyn_p^.str_p^.s.len; sst_out.dyn_p^.break_start := {save source for first char on new line} sst_out.dyn_p^.break_len + 1; end; end; { ************************************************************************** * * Subroutine SST_OUT_APPEND (STR_H, STR) * * Append more characters to the end of the current line. If the new line * length would exceed the WRAP_LEN parameter, then the line is broken at * the last break set. It is an error if the line can't be broken and its * length would exceed its max length (characters would be lost). * * STR_H is the handle to a range of source characters that these output * characters are related to. STR is the string of output characters to * append to the current line. } procedure sst_out_append ( {append string to current output line} in str: univ string_var_arg_t); {the string to append} begin sst_w.appendn^ (str.str, str.len); {append the characters} end; { ************************************************************************** * * Subroutine SST_OUT_APPENDN (CHARS, N_CHARS) * * Append characters at the current write position. If the new line * length would exceed the WRAP_LEN parameter, then the line is broken at * the last break set. It is an error if the line can't be broken and its * length would exceed its max length (characters would be lost). * * CHARS is the array of characters to append to the current line. * N_CHARS is the number of characters in CHARS. } procedure sst_out_appendn ( {append N characters to current output line} in chars: univ string; {the characters to append} in n_chars: string_index_t); {the number of characters to append} var olen: string_index_t; {length of resulting output line} wl: sys_int_machine_t; {WRAP_LEN after taking comment into account} begin with sst_out.dyn_p^: dyn do begin {DYN is dynamic output writing state block} case dyn.wpos of {where is write position rel to curr line ?} sst_wpos_before_k, {before start of current line} sst_wpos_after_k: begin {after end of current line} sst_w.line_insert^; {create new line to append characters to} end; end; {done with special handling pos cases} olen := dyn.str_p^.s.len + n_chars; {length if just did append} wl := sst_out.wrap_len; {init max line length before wrapping} if dyn.comm.len > 0 then begin {this line has an end of line comment ?} wl := min(wl, sst_out.comm_pos); {adjust wrap length for comment} end; if olen > wl then begin {need to break line before new characters ?} sst_w.break^; {break curr line onto continuation line} olen := {update resulting line len after doing break} dyn.str_p^.s.len + n_chars; end; {done breaking to continuation line} if olen > dyn.str_p^.s.max then begin {current line overflow ?} sys_message_bomb ('sst', 'out_line_too_long', nil, 0); end; string_appendn (dyn.str_p^.s, chars, n_chars); {append the chars to line} end; {done with DYN abbreviation} end; { ************************************************************************** * * Subroutine SST_OUT_APPENDS (S) * * Append the string S to the current output line. Trailing blanks in S * will be ignored. } procedure sst_out_appends ( {append string to current output line} in s: string); {string to append, trailing blanks ignored} var s2: string_var8192_t; {scratch string} begin s2.max := sizeof(s2.str); {init local var string} string_vstring (s2, s, sizeof(s)); {convert input string to a var string} sst_w.appendn^ (s2.str, s2.len); end; { ************************************************************************** * * Subroutine SST_OUT_APPEND_SYM_NAME (SYM) * * Append the output name of the symbol SYM at the current position. * It is an error if the output name does not already exist. } procedure sst_out_append_sym_name ( {append symbol output name to curr position} in sym: sst_symbol_t); {symbol descriptor to write name of} const max_msg_parms = 1; {max parameters we can pass to a message} var str: string_var4_t; {scratch output name when blank} sym_p: sst_symbol_p_t; msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin if sym.name_out_p = nil then begin {symbol has no output name ?} str.max := sizeof(str.str); {init local var string} if sym.name_in_p <> nil then begin {input name exists} sys_msg_parm_vstr (msg_parm[1], sym.name_in_p^); end else begin {no input name exists} str.len := 0; sys_msg_parm_vstr (msg_parm[1], str); end ; sys_message_parms ('sst', 'out_name_none', msg_parm, 1); writeln ('Symbol flags are:'); if sst_symflag_def_k in sym.flags then writeln (' def'); if sst_symflag_used_k in sym.flags then writeln (' used'); if sst_symflag_following_k in sym.flags then writeln (' following'); if sst_symflag_following_dt_k in sym.flags then writeln (' following_dt'); if sst_symflag_followed_k in sym.flags then writeln (' followed'); if sst_symflag_writing_k in sym.flags then writeln (' writing'); if sst_symflag_writing_dt_k in sym.flags then writeln (' writing_dt'); if sst_symflag_written_k in sym.flags then writeln (' written'); if sst_symflag_created_k in sym.flags then writeln (' created'); if sst_symflag_intrinsic_in_k in sym.flags then writeln (' intrinsic_in'); if sst_symflag_intrinsic_out_k in sym.flags then writeln (' intrinsic_out'); if sst_symflag_global_k in sym.flags then writeln (' global'); if sst_symflag_extern_k in sym.flags then writeln (' extern'); if sst_symflag_defnow_k in sym.flags then writeln (' defnow'); if sst_symflag_ok_sname_k in sym.flags then writeln (' ok_sname'); sym_p := addr(sym); sst_w.name_sym^ (sym_p^); {make output name for symbol} end; sst_w.append^ (sym.name_out_p^); {append the symbol's output name} end; { ************************************************************************** * * Subroutine SST_OUT_BREAK * * Cause a break at the current break point of the current output line. * A new continuation line will be created, and initialized with * the characters on the current line after the break point. The new line * will be initialized to not have a break point. A call to this routine * will have no effect if there is no break point on the current line. } procedure sst_out_break; {break line at current position} var comm_ofs: sys_int_machine_t; {commented char offset from first broken char} comm: string_var80_t; {comment if moved to new line} moved: string_var256_t; {string moved to next line} begin comm.max := sizeof(comm.str); {init local var strings} moved.max := sizeof(moved.str); with sst_out.dyn_p^: dyn do begin {DYN is dynamic output state for this line} case dyn.wpos of {where is write position rel to curr line ?} sst_wpos_before_k, {before start of current line} sst_wpos_after_k: begin {after end of current line} return; {nothing to break} end; end; {done with special handling write pos cases} if dyn.break_len <= 0 then return; {no break point exists ?} { * The line will definately be broken. } comm.len := 0; {init to no comment moved from old line} comm_ofs := {offset of commented char into moved chars} dyn.commented_pos - dyn.break_start; if {need to move comment to new line ?} (dyn.comm.len > 0) and {comment exists on old line ?} (comm_ofs >= 0) {comment belongs to char that will be moved ?} then begin string_copy (dyn.comm, comm); {save comment string} dyn.comm.len := 0; {pretend old line has no comment} end; moved.len := 0; {init moved characters to empty} string_appendn ( {save characters to move to next line} moved, {string to save characters in} dyn.str_p^.s.str[dyn.break_start], {start of string to move} dyn.str_p^.s.len - dyn.break_start + 1); {number of characters to save} dyn.str_p^.s.len := dyn.break_len; {truncate line to before break} dyn.break_len := 0; {reset to no break on this line} dyn.break_start := 0; { * The current line has been truncated to before the break. The characters * to wrap to the next line are in MOVED. } sst_w.line_new_cont^; {create and init continuation line} comm_ofs := dyn.str_p^.s.len + comm_ofs; {make char pos of commented char} sst_w.append^ (moved); {copy moved characters to new line} if comm.len > 0 then begin {need to restore comment to new line ?} string_copy (comm, dyn.comm); {set comment text} dyn.commented_pos := comm_ofs; {set index of commented character} end; end; {done with DYN abbreviation} end; { ************************************************************************** * * Subroutine SST_OUT_BLANK_LINE * * Make sure the current position is immediately following a blank line. * A new blank line will be created only if one is not already there. * Although this will create a blank line at the start of the file, the * SST_OUT_WRITE routine will ignore such blank lines. A blank line needs * to be put there, since other text may be inserted before it later. * * This routine is useful when you want to leave a blank line, but aren't * sure if there may already be one there. } procedure sst_out_blank_line; {make sure preceeding line is blank} label wpos_end; begin with sst_out.dyn_p^: dyn do begin {DYN is dynamic part of current output state} case dyn.wpos of { * The writing position is before the start of the current line. } sst_wpos_before_k: begin if (dyn.str_p <> nil) and then {a current line exists ?} (dyn.str_p^.prev_p <> nil) and then {a previous line exists ?} (dyn.str_p^.prev_p^.s.len <= 0) {previous line is blank ?} then return; {nothing to do, blank line already there} sst_w.line_insert^; {insert blank line before curr position} dyn.wpos := sst_wpos_after_k; {position to after the blank line} end; { * The writing position is at the end of the current line. } sst_wpos_end_k: begin wpos_end: {common code for write pos end/after cases} if dyn.str_p^.next_p <> nil then begin {"next" line really exists ?} if dyn.str_p^.next_p^.s.len <= 0 then begin {next line is blank ?} dyn.str_p := dyn.str_p^.next_p; {position to after end of the blank line} dyn.break_start := 0; dyn.break_len := 0; dyn.wpos := sst_wpos_after_k; return; end; end; end; { * The writing position is after the end of the current line. } sst_wpos_after_k: begin if dyn.str_p^.s.len <= 0 then return; {already positioned after a blank line ?} goto wpos_end; {to common code with write position at end} end; end; {end of writing position cases} { * The current position is not immediately following a blank line. Create * a blank line and put the current write position after the end of it. } sst_w.line_insert^; {create new blank line} dyn.wpos := sst_wpos_after_k; {position to after the blank line} end; {end of DYN abbreviation} end; { ************************************************************************** * * Subroutine SST_OUT_COMMENT_END * * Write whatever characters are required to close an end of line comment. * The back end may replace this routine if complicated logic is required. * This version just writes the comment end string found in the * static write position block. } procedure sst_out_comment_end; {write end of comment string} begin sst_w.append^ (sst_out.comm_end); end; { ************************************************************************** * * Subroutine SST_OUT_COMMENT_SET (S) * * Set the body of the end of line comment for this line. The comment * will be associated with the next character written on this line. } procedure sst_out_comment_set ( {set comment to correspond to next char} in s: univ string_var_arg_t); {body of comment string} var wl_save: sys_int_machine_t; {saved copy of WRAP_LEN} begin if s.len <= 0 then return; {no comment to set ?} with sst_out.dyn_p^: dyn do begin {DYN is dynamic output writing state block} wl_save := sst_out.wrap_len; {save existing WRAP_LEN value} sst_out.wrap_len := sst_out.comm_pos; {set to where we would like comment to start} sst_w.appendn^ ('', 0); {do break, if needed to obey WRAP_LEN} sst_out.wrap_len := wl_save; {restore old WRAP_LEN value} { * The current line has been broken, if possible, to not stick out past * where we would like to start the comment. The writing position is * definately set to END. } if dyn.comm.len > 0 then begin {there is already a comment for this line ?} sst_w.line_new_cont^; {create new continuation line for comment} end; string_copy (s, dyn.comm); {save comment body for this line} dyn.commented_pos := dyn.str_p^.s.len + 1; {save index of commented character} end; {done with DYN abbreviation} end; { ************************************************************************** * * Subroutine SST_OUT_COMMENT_START * * Write whatever characters are required to start an end of line comment. * The back end may replace this routine if complicated logic is required. * This version just writes the comment start string found in the * static write position block. } procedure sst_out_comment_start; {write start of comment string} begin sst_w.append^ (sst_out.comm_start); end; { ************************************************************************** * * Subroutine SST_OUT_DELIMIT * * Indicate that either a delimiter is to be written to the current position, * or a line break should occur here. Multiple consecutive calls to this * routine will have no effect. } procedure sst_out_delimit; {write delim or break line before next output} const delim_string = ' '; {delimiter string} var wl: sys_int_machine_t; {WRAP_LEN after taking comment into account} begin with sst_out.dyn_p^: dyn do begin {DYN is dynamic part of current output state} case dyn.wpos of {where is write position rel to curr line ?} sst_wpos_before_k, {before start of current line} sst_wpos_after_k: begin {after end of current line} return; {already at a line break} end; end; {done with special handling write pos cases} if {delimiter/break already flagged ?} (dyn.break_len > 0) and {break exists on this line ?} (dyn.break_start - dyn.break_len > 1) and {break is a delimiter ?} (dyn.break_start > dyn.str_p^.s.len) {break is at end of line ?} then return; sst_w.allow_break^; {allow break at current end of line} wl := sst_out.wrap_len; {init max line length before wrapping} if dyn.comm.len > 0 then begin {this line has an end of line comment ?} wl := min(wl, sst_out.comm_pos); {adjust wrap length for comment} end; if dyn.str_p^.s.len < wl then begin {won't automatically break ?} string_appendn (dyn.str_p^.s, delim_string, sizeof(delim_string)); {add delim} dyn.break_start := dyn.str_p^.s.len + 1; {break will skip over delimiter} end; end; {done with DYN abbreviation} end; { ************************************************************************** * * Subroutine SST_OUT_INDENT * * Increase the current indentation level by one. The number of spaces per * indentation level is SST_OUT.INDENT_SIZE. } procedure sst_out_indent; {increase indentation by one level} begin sst_out.dyn_p^.indent_level := sst_out.dyn_p^.indent_level + 1; {set new indentation level} if sst_out.dyn_p^.indent_level > 0 then begin sst_out.dyn_p^.indent_chars := {indent more chars for this level} sst_out.dyn_p^.indent_chars + sst_out.indent_size; end; end; { ************************************************************************** * * Subroutine SST_OUT_LINE_CLOSE * * Close out the current line. Future append operations will go onto a * new line. } procedure sst_out_line_close; {close current line} begin with sst_out.dyn_p^: dyn do begin {DYN is dynamic part of current output state} case dyn.wpos of sst_wpos_before_k, {position is before or after current line} sst_wpos_after_k: begin sst_w.line_insert^; end; end; {end of special handling write pos cases} dyn.wpos := sst_wpos_after_k; {write position is after end of this line} end; {done with DYN abbreviation} end; { ************************************************************************** * * Subroutine SST_OUT_LINE_INSERT * * Insert a new line at the current position. The new line will be made * current, and the writing position will be set at the end of the new line. } procedure sst_out_line_insert; {insert line after curr, new becomes curr} var ent_p: string_chain_ent_p_t; {points to chain entry for new line} begin with sst_out.dyn_p^: dyn do begin {DYN is dynamic part of current output state} util_mem_grab (sizeof(ent_p^), sst_out.mem_p^, false, ent_p); {alloc mem for new line} ent_p^.s.max := sizeof(ent_p^.s.str); {init new var string} ent_p^.s.len := 0; case dyn.wpos of { * The current position is before the start of the current line. * Link the new line to before the current line. } sst_wpos_before_k: begin if dyn.str_p = nil then begin {new line is first one in file} ent_p^.prev_p := nil; ent_p^.next_p := nil; sst_out.first_str_p := ent_p; {save pointer to first line in file} end else begin {there is an existing current line} ent_p^.prev_p := dyn.str_p^.prev_p; ent_p^.next_p := dyn.str_p; if ent_p^.prev_p = nil then begin {this line was inserted at start of list} sst_out.first_str_p := ent_p; {update pointer to first line in file} end else begin {there is an old line before the new line} ent_p^.prev_p^.next_p := ent_p; end ; dyn.str_p^.prev_p := ent_p; end ; end; { * The current position is at or after the end of the current line. * Link the new line to after the current line. Any pending comment * must be taken care of before moving to the new line. } sst_wpos_end_k, sst_wpos_after_k: begin if dyn.comm.len > 0 then begin {this line is tagged with a comment ?} dyn.break_len := 0; {no more breaks allowed this line} dyn.break_start := 0; dyn.wpos := sst_wpos_end_k; {allow appends to this line} string_append1 (dyn.str_p^.s, ' '); while (dyn.str_p^.s.len < (sst_out.comm_pos - 1)) do begin string_append1 (dyn.str_p^.s, ' '); {tab to comment start} end; sst_w.comment_start^; {write start of comment syntax} sst_w.append^ (dyn.comm); {write body of comment} sst_w.comment_end^; {write end of comment syntax} end; ent_p^.next_p := dyn.str_p^.next_p; ent_p^.prev_p := dyn.str_p; if ent_p^.next_p <> nil then begin {there is a line after new line ?} ent_p^.next_p^.prev_p := ent_p; end; dyn.str_p^.next_p := ent_p; end; end; {end of writing position cases} { * The new line has been created and linked into the chain. } dyn.str_p := ent_p; {make the new line the current line} dyn.break_len := 0; {init write position to end of new line} dyn.break_start := 0; dyn.wpos := sst_wpos_end_k; dyn.comm.max := sizeof(dyn.comm.str); dyn.comm.len := 0; dyn.commented_pos := 0; end; {done with DYN abbreviation} end; { ************************************************************************** * * Subroutine SST_OUT_LINE_NEW * * Create a new line after the current line. The new line will be initialized * as a non-continuation source code line. } procedure sst_out_line_new; {set up so next char goes on next line} begin sst_w.line_insert^; end; { ************************************************************************** * * Subroutine SST_OUT_LINE_NEW_CONT * * Create a new line after the current line and initialize it ready to * put more characters on it from the statement already started on previous * lines. } procedure sst_out_line_new_cont; {set up for next line is continuation line} begin sst_w.line_insert^; {create raw new line} sst_w.tab_indent^; {tab to after indentation} end; { ************************************************************************** * * Subroutine SST_OUT_NAME ( * NAME_IN, NAME_IN_LEN, EXT, EXT_LEN, RENAME, NAME_OUT, POS) * * Convert the input source symbol name in NAME_IN,NAME_IN_LEN to the output * source symbol name in NAME_OUT. EXT,EXT_LEN specifies the suffix, if any, * the output name must have. RENAME indicates whether the name may be * changed to make it unique. It may have one of the following values: * * SST_RENAME_NONE_K * * The name will not be changed from the one derived with the basic * rename rules. It is an error if the name would have been renamed * under the rules for SST_RENAME_SCOPE_K, below. This rename rule * is useful for "renaming" global symbols, since we aren't free to * change the name. * * SST_RENAME_NCHECK_K * * This renaming rule is the same as SST_RENAME_SCOPE_K, below, except * that no uniqueness check is done in the current scope. Special * symbol names and reserved names are still checked. POS will not * be valid. * * SST_RENAME_SCOPE_K * * The name will be changed, if necessary, to make it unique in the current * scope. It will also be renamed to avoid matching the name of some * symbol types in the line of scopes from the current to the most global. * These special symbol types are data types, and intrinsic symbols to * the back end, and symbol names explicitly flagged as reserved in the * config file. * * SST_RENAME_ALL_K * * The name will be changed, if necessary, to make it unique in all the scopes * from the current in line to the most global. * * POS is the returned position handle of where the name would go in the * symbol table for the current scope. POS is not valid if RENAME is set to * SST_RENAME_NCHECK_K. } procedure sst_out_name ( {make output symbol name from input name} in name_in: univ string; {input symbol name characters} in name_in_len: string_index_t; {number of characters in NAME_IN} in ext: univ string; {output name suffix, if any} in ext_len: string_index_t; {number of characters in EXT} in rename: sst_rename_k_t; {what kind of re-naming is allowed} in out name_out: univ string_var_arg_t; {resulting output source symbol name} out pos: string_hash_pos_t); {pos handle where name goes in symbol table} const max_msg_parms = 3; {max parameters we can pass to a message} var seq: sys_int_machine_t; {current sequence number for name} name_start: string_var80_t; {name before sequence number} name_seq: string_var32_t; {sequence number string} name_end: string_var80_t; {name after sequence number} token: string_var80_t; {scratch string for number conversion} chopt: sys_int_machine_t; {total characters need to chop from name} choph: sys_int_machine_t; {number chars need to chop here} i, j: sys_int_machine_t; {loop counters and scratch integers} pos_local: string_hash_pos_t; {scratch position handle} pos_p: ^string_hash_pos_t; {pointer to position handle for synonym} scope_p: sst_scope_p_t; {points to current scope trying name in} sym_pp: sst_symbol_pp_t; {points to hash table user data area} sym_p: sst_symbol_p_t; {points to symbol descriptor of hash entry} found: boolean; {TRUE if found name in hash table} c: char; {scratch character} str_h: syo_string_t; {handle to source chars for error message} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; label suffix_nfnd, lead_ok, next_name; begin name_start.max := sizeof(name_start.str); {init local var strings} name_seq.max := sizeof(name_seq.str); name_end.max := sizeof(name_end.str); token.max := sizeof(token.str); string_vstring (name_start, name_in, name_in_len); {make raw var string input name} string_vstring (name_end, ext, ext_len); {make raw name suffix} if rename <> sst_rename_none_k then begin {allowed to change name at all ?} case sst_config.charcase of {what is the output character case rule ?} syo_charcase_down_k: begin string_downcase (name_start); string_downcase (name_end); end; syo_charcase_up_k: begin string_upcase (name_start); string_upcase (name_end); end; end; {end of charcase cases} end; {done adjusting name's character case} if {need to get rid of dollar signs ?} (sst_config.os = sys_os_aix_k) and {IBM AIX operating system ?} (sst_config.lang = sst_lang_c_k) {C output language ?} then begin for i := 1 to name_start.len do begin {once for each character in name} if name_start.str[i] = '$' then name_start.str[i] := '_'; end; end; {done with IBM AIX C special case} if name_start.len > name_end.len then begin {NAME_START could have suffix ?} j := name_start.len; for i := name_end.len downto 1 do begin {scan backwards thru suffix} if name_start.str[j] <> name_end.str[i] {end of NAME_START not match suffix ?} then goto suffix_nfnd; j := j - 1; {advance NAME_START char index} end; {back here to check next suffix character} name_start.len := {remove suffix from NAME_START} name_start.len - name_end.len; end; suffix_nfnd: {jump here if NAME_START not ended in suffix} { * NAME_START definately does not end in the suffix now. It has been removed * if it was there before. The suffix is now in NAME_END. * * Now keep trying new names until one of them is found to be unique in the * line of scopes from the current to the root scope. The first name will * be the name end and start stuck together. After that, a sequence number * will be inserted between the name start and end. If the name is too long, * then the start name will be shortened from the last character backwards, * until it is only one character in length. After that, the suffix will * be shortened from its first character forwards. If the remaining name * is still too long, then it is an error. If the start name ends in an * underscore, then the sequence number will always be inserted. * * This behavior may be modified by the RENAME flag. * * Now check that leading name character is legal. } if name_start.len < 1 then goto lead_ok; {prefix is empty ?} c := name_start.str[1]; {get name start character} if (c >= 'A') and (c <= 'Z') then goto lead_ok; {upper case letter} if (c >= 'a') and (c <= 'z') then goto lead_ok; {lower case letter} if c = '_' then goto lead_ok; if c = '$' then goto lead_ok; { * The leading name character is not legal. } if rename = sst_rename_none_k then begin {not allowed to change name ?} string_append (name_start, name_end); {make composite name for error message} sys_message_bomb ('sst', 'out_name_illegal', msg_parm, 1); end; string_copy (name_start, token); {make temp copy of name start} case sst_config.charcase of {what is the output character case rule ?} syo_charcase_up_k: begin string_vstring (name_start, 'N', 1); end; otherwise string_vstring (name_start, 'n', 1); end; string_append (name_start, token); {make new name start with character inserted} lead_ok: {done messing with leading character} if {name indicates to always have seq number ?} (rename <> sst_rename_none_k) and (name_start.len >= 1) and then (name_start.str[name_start.len] = '_') then begin {there will always be a sequence number} seq := 0; {one less than first sequence number to try} name_start.len := name_start.len - 1; {truncate "_", will be added with seqnum} end else begin {first try will be without sequence number} seq := -1; end ; if name_start.len <= 0 then begin {start of name is empty string ?} string_appendn (name_start, 'xxx', 3); {pick arbitrary start of name} end; next_name: {back here to try name with new seq number} seq := seq + 1; {make sequence number for this try} name_seq.len := 0; {init inserted sequence number string length} if seq > 0 then begin {need to make full sequence number string ?} if rename = sst_rename_none_k then begin {not allowed to make new name ?} string_hash_ent_atpos ( {get info about synonym entry} pos_p^, {position handle to hash table entry} sym_p, {unused pointer to hash entry name} sym_pp); {returned pointer to hash entry data area} sym_p := sym_pp^; {get pointer to synonim symbol descriptor} str_h.first_char := sym_p^.char_h; {get handle to start of other symbol} str_h.last_char := str_h.first_char; sys_msg_parm_vstr (msg_parm[1], name_out); syo_error (str_h, 'sst', 'out_name_used', msg_parm, 1); end; string_append1 (name_seq, '_'); string_f_int (token, seq); string_append (name_seq, token); end; chopt := max(0, {number of chars to shorten name by} name_start.len + name_seq.len + name_end.len - sst_config.sym_len_max); { * If name is too long, try to chop characters from NAME_START. } if chopt > 0 then begin {need to shorten total name ?} choph := min(chopt, name_start.len - 1); {number of chars we can chop here} name_start.len := {chop characters from name before seq number} name_start.len - choph; chopt := chopt - choph; {less characters left to chop off} end; { * If name is still too long, try to chop characters from NAME_END. } if chopt > 0 then begin {still need to shorten total name ?} choph := min(chopt, name_end.len); {number of chars we can chop here} name_end.len := {set new length of NAME_END} name_end.len - choph; j := choph + 1; {init index of first source char} for i := 1 to name_end.len do begin {once for each char to move} name_end.str[i] := name_end.str[j]; {move this character} end; {back to move next char in NAME_END} chopt := chopt - choph; {less characters left to chop off} end; string_copy (name_start, name_out); {build full name string for this try} string_append (name_out, name_seq); string_append (name_out, name_end); { * If name is still too long, then there is nothing more we can do to fix * it. This is now an error. } if chopt > 0 then begin {name still too long ?} string_vstring (name_start, name_in, name_in_len); {make raw var string input name} string_vstring (name_end, ext, ext_len); {make raw name suffix} sys_msg_parm_vstr (msg_parm[1], name_start); sys_msg_parm_vstr (msg_parm[2], name_end); sys_msg_parm_vstr (msg_parm[3], name_out); sys_message_bomb ('sst', 'out_name_too_long', msg_parm, 3); end; { * The current output name to try is in NAME_OUT. } scope_p := sst_scope_p; {init current scope to most local} while scope_p <> nil do begin {loop thru the scopes from local to global} if scope_p = sst_scope_p then begin {we are looking for name in most local scope} if rename = sst_rename_ncheck_k then begin {no supposed to check current scope} found := false; end else begin {OK to check uniqueness in current scope} string_hash_pos_lookup ( {look up name in output symbol table} scope_p^.hash_out_h, {hash table handle} name_out, {symbol name} pos, {returned position handle, back to caller} found); {returned TRUE if name existed here} pos_p := addr(pos); {set pointer to position handle used} end ; end else begin {not looking in table where symbol goes later} string_hash_pos_lookup ( {look up name in output symbol table} scope_p^.hash_out_h, {hash table handle} name_out, {symbol name} pos_local, {returned hash table position handle} found); {returned TRUE if name existed here} pos_p := addr(pos_local); {set pointer to position handle used} end ; if found then begin {current name found in this scope ?} case rename of sst_rename_none_k, sst_rename_ncheck_k, sst_rename_scope_k: begin if scope_p = sst_scope_p then begin {we just looked in current scope ?} goto next_name; {must be completely unique in this scope} end; string_hash_ent_atpos ( {get data about this hash table entry} pos_local, {position handle to hash table entry} sym_p, {unused pointer to hash entry name} sym_pp); {returned pointer to hash entry data area} sym_p := sym_pp^; {get pointer to descriptor for this symbol} if sym_p = nil {this symbol is explicitly reserved name ?} then goto next_name; {can't allow same name as reserved name} case sym_p^.symtype of {what kind of symbol is this ?} sst_symtype_dtype_k, {symbol is a data type} sst_symtype_back_k: begin {symbol is intrinsic to output language} goto next_name; {can't allow conflict with these symbols} end; end; {OK to have same name as remaining sym types} end; sst_rename_all_k: begin {must be completely unique over all scopes} goto next_name; {this name no good, try another} end; otherwise sys_msg_parm_int (msg_parm[1], ord(rename)); sys_message_bomb ('sst', 'rename_unknown', msg_parm, 1); end; {end of RENAME method cases} end; {done handling name was found in this scope} scope_p := scope_p^.parent_p; {advance to next most global symbol table} end; {back and check for name in new scope} end; { ************************************************************************** * * Subroutine SST_OUT_NAME_SYM (SYM) * * Set the output source name for the symbol SYM. * This subroutine has no effect if the output symbol name already exists. } procedure sst_out_name_sym ( {set output name for an existing symbol} in out sym: sst_symbol_t); {NOP if symbol already has output name} const max_msg_parms = 1; {max parameters we can pass to a message} var suffix: string_var80_t; {symbol name suffix, if any} pos: string_hash_pos_t; {handle to output name symbol table position} sym_pp: sst_symbol_pp_t; {pointer to hash entry user data area} dt_p: sst_dtype_p_t; {points to root data type descriptor} name_out: string_var132_t; {final output symbol name} rename: sst_rename_k_t; {symbol re-naming strategy flag} scope_old_p: sst_scope_p_t; {saved copy of current scope pointer} names_old_p: sst_scope_p_t; {saved copy of current namespace pointer} name_in: string_var32_t; {used when no input name given} no_in_name: boolean; {TRUE if no input name existed} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; label name_dtype; begin if sym.name_out_p <> nil then return; {output name already set ?} suffix.max := sizeof(suffix.str); {init local var strings} name_out.max := sizeof(name_out.str); name_in.max := sizeof(name_in.str); no_in_name := false; {init to explicit input name was given} if sym.name_in_p = nil then begin {no explicit input name exists} name_in.len := 0; case sym.symtype of sst_symtype_const_k: string_appendn (name_in, 'const', 5); sst_symtype_enum_k: string_appendn (name_in, 'enum', 4); sst_symtype_dtype_k: begin {symbol is name of a data type} dt_p := sym.dtype_dtype_p; {resolve base data type} name_dtype: {jump here to base name on data type} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; case dt_p^.dtype of {what data type is this ?} sst_dtype_int_k: string_appendn (name_in, 'int', 3); sst_dtype_enum_k: string_appendn (name_in, 'enum', 4); sst_dtype_float_k: string_appendn (name_in, 'float', 5); sst_dtype_bool_k: string_appendn (name_in, 'bool', 4); sst_dtype_char_k: string_appendn (name_in, 'char', 4); sst_dtype_rec_k: string_appendn (name_in, 'rec', 3); sst_dtype_array_k: begin if dt_p^.ar_string then begin string_appendn (name_in, 'string', 6); string_f_int (suffix, dt_p^.ar_ind_n); {make string length number} string_append (name_in, suffix); end else begin string_appendn (name_in, 'array', 5); end ; end; sst_dtype_set_k: string_appendn (name_in, 'set', 3); sst_dtype_range_k: string_appendn (name_in, 'range', 5); sst_dtype_proc_k: string_appendn (name_in, 'proc', 4); sst_dtype_pnt_k: string_appendn (name_in, 'pnt', 3); otherwise {none of the above data types} string_appendn (name_in, 'unk', 3); end; {end of data type cases} end; {end of symbol is data type case} sst_symtype_field_k: string_appendn (name_in, 'field', 5); sst_symtype_var_k: begin {symbol is a variable} dt_p := sym.var_dtype_p; goto name_dtype; {base name on variable's data type} end; sst_symtype_abbrev_k: string_appendn (name_in, 'abbrev', 6); sst_symtype_proc_k: string_appendn (name_in, 'proc', 4); sst_symtype_prog_k: string_appendn (name_in, 'prog', 4); sst_symtype_com_k: string_appendn (name_in, 'com', 3); sst_symtype_module_k: string_appendn (name_in, 'module', 6); sst_symtype_label_k: string_appendn (name_in, 'label', 5); sst_symtype_front_k: string_appendn (name_in, 'front', 5); sst_symtype_back_k: string_appendn (name_in, 'back', 4); otherwise sys_msg_parm_int (msg_parm[1], ord(sym.symtype)); sys_message_bomb ('sst', 'symbol_type_unknown', msg_parm, 1); end; sym.name_in_p := univ_ptr(addr(name_in)); no_in_name := true; {flag that we created input name} end; rename := sst_rename_all_k; {init to want unique name in all scopes} case sym.symtype of {what kind of symbol is this ?} sst_symtype_field_k: begin {symbol is field name of a record} rename := sst_rename_scope_k; {make unique only within its record} end; sst_symtype_var_k: begin {symbol is a variable} if (sym.var_proc_p <> nil) and {symbol is function return value ?} (sym.var_arg_p = nil) then begin if sym.var_proc_p^.sym_p^.name_out_p = nil then begin {rout not yet named ?} sst_w.name_sym^ (sym.var_proc_p^.sym_p^); {make output name for function} end; if sst_config.lang <> sst_lang_c_k then begin {not C language output ?} sym.name_out_p := sym.var_proc_p^.sym_p^.name_out_p; {use func's output name} return; end; end; {done handling function return value var} end; end; {end of symbol types with special handling} if sst_symflag_global_k in sym.flags then begin {symbol is globally known ?} rename := sst_rename_none_k; {can't rename global symbols} end; if no_in_name then begin {symbol output name was created here ?} rename := sst_rename_all_k; {make these names unique everywhere} end; suffix.len := 0; {init to no special suffix required} if {use special unique name in output sym name ?} (rename = sst_rename_all_k) and {supposed to be unique over all scopes ?} (sst_symflag_created_k in sym.flags) and {symbol created by back end ?} (sst_oname_unique.len > 0) {unique name suffix requested ?} then begin string_append1 (suffix, '_'); string_append (suffix, sst_oname_unique); end; case sym.symtype of {check symbol types that require suffixes} sst_symtype_const_k, sst_symtype_enum_k: string_append (suffix, sst_config.suffix_const); sst_symtype_dtype_k: string_append (suffix, sst_config.suffix_dtype); end; {end of special symbol type cases} scope_old_p := sst_scope_p; {save current scope and namespace pointers} names_old_p := sst_names_p; sst_scope_p := sym.scope_p; {save scope to that of symbol} sst_names_p := sst_scope_p; sst_w.name^ ( {make final output symbol name} sym.name_in_p^.str, sym.name_in_p^.len, {input name and length} suffix.str, suffix.len, {suffix string and length} rename, {TRUE if allowed to re-name symbol} name_out, {returned final output symbol name} pos); {output symbol table position handle} sst_scope_p := scope_old_p; {restore current scope and namespace pointers} sst_names_p := names_old_p; if no_in_name then begin {did we create input name here ?} sym.name_in_p := nil; {restore symbol descriptor to the way it was} end; string_hash_ent_add ( {add name to output symbol table} pos, sym.name_out_p, sym_pp); sym_pp^ := addr(sym); {point hash table entry to symbol descriptor} end; { ************************************************************************** * * Subroutine SST_OUT_NOTIFY_SRC_RANGE (STR_H) * * Indicate the input source code character range that subsequent output * characters will be related to. This currently does nothing, but is * intended to eventually handle bringing comments from the input to * the output files. } procedure sst_out_notify_src_range ( {declare source chars range for new output} in str_h: syo_string_t); {new out chars related to these in chars} begin sst_out.dyn_p^.str_h := str_h; end; { ************************************************************************** * * Subroutine SST_OUT_TAB_INDENT * * Tab the character position in the current line to after the indentation * characters. The number of indentation characters is given by * SST_OUT.INDENT_CHARS. This value is usually controlled thru subroutines * SST_W.INDENT^ and SST_W.UNDENT^. } procedure sst_out_tab_indent; {tab to current indentation level} const indent_char = ' '; {character used for indentation} var tab_pos: sys_int_machine_t; {final string length after tab} i: sys_int_machine_t; {string write index} begin with sst_out.dyn_p^: dyn do begin {DYN is dynamic part of current output state} case dyn.wpos of sst_wpos_before_k, {position is before or after current line} sst_wpos_after_k: begin sst_w.line_insert^; end; end; {end of special handling write pos cases} tab_pos := max(dyn.str_p^.s.len, min(dyn.str_p^.s.max, {final string len} dyn.indent_chars)); for i := dyn.str_p^.s.len+1 to tab_pos do begin {once for each char to add} dyn.str_p^.s.str[i] := indent_char; end; dyn.str_p^.s.len := tab_pos; {set new string length} end; {done with DYN abbreviation} end; { ************************************************************************** * * Subroutine SST_OUT_UNDENT * * Decrease the current indentation level by one. The number of spaces per * indentation level is SST_OUT.INDENT_SIZE. } procedure sst_out_undent; {decrease indentation by one level} begin with sst_out.dyn_p^: dyn do begin {DYN is dynamic part of current output state} if dyn.indent_level > 0 then begin dyn.indent_chars := {indent more chars for this level} dyn.indent_chars - sst_out.indent_size; end; dyn.indent_level := dyn.indent_level - 1; {set new indentation level} end; {done with DYN abbreviation} end; { ************************************************************************** * * Subroutine SST_OUT_UNDENT_ALL * * Reset the indentation level to none, and the number of current indentation * characters to none. This call destroys any previous indentation state. } procedure sst_out_undent_all; {reset to no indentation level} begin sst_out.dyn_p^.indent_level := 0; sst_out.dyn_p^.indent_chars := 0; end; { ************************************************************************** * * Subroutine SST_OUT_WRITE (CONN, STAT) * * Write all the output lines to a file. CONN is the connection handle of * the stream to write the lines to. } procedure sst_out_write ( {write output lines from memory to file} in out conn: file_conn_t; {connection handle to output file} out stat: sys_err_t); {completion status code} var str_p: string_chain_ent_p_t; {points to current output line} beginning: boolean; {TRUE if not written any line to file yet} label next_line; begin str_p := sst_out.first_str_p; {init current line to first output line} beginning := true; {init to not written anything to file yet} while str_p <> nil do begin {once for each line in linked list} string_unpad (str_p^.s); {delete trailing spaces from this line} if beginning and (str_p^.s.len <= 0) {blank line at beginning of file ?} then goto next_line; {ignore blank lines at beginning} file_write_text (str_p^.s, conn, stat); {write this line to output file} if sys_error(stat) then return; beginning := false; {no longer at beginning of file} next_line: {jump here to advance to line in chain} str_p := str_p^.next_p; {advance to next output line} end; {back and process new output line} end;
unit ProgramSettings; interface uses Windows, Messages, SysUtils, Forms, IOUtils, ShlObj, FFSUtils, FFSTypes, Xml.XMLDoc, Xml.XMLIntf, System.Classes; type TProgramSettings = class(Tcomponent) private FRegistryKey: string; FServerIP: string; FServerPort: string; fSettingsKeyName: String; procedure SetRegistryKey(const Value: string); procedure SetDirWork(const Value: string); procedure SetServerIP(const Value: string); procedure SetServerPort(const Value: string); function GetDirWork: string; function GetSettingsFilePath: String; procedure SetSettingsKeyName(const Value: String); { Private declarations } protected { Protected declarations } public constructor Create(AOwner: TComponent); override; procedure SaveSettings; procedure ReadSettings; property SettingsFilePath: String read GetSettingsFilePath; property SettingsKeyName: String read fSettingsKeyName write SetSettingsKeyName; published { Published declarations } property RegistryKey:string read FRegistryKey write SetRegistryKey; property DirWork:string read GetDirWork write SetDirWork; property ServerIP: string read FServerIP write SetServerIP; property ServerPort: string read FServerPort write SetServerPort; end; TFFSDirectory = (drData, drReports, drToDo, drDone, drLtrAddOn, drUpdate, drExport, drUserRpts, drCacheReports, drCacheExport); TFFSDirSet = set of TFFSDirectory; function Dir(ADir:TFFSDirectory;DoRaise:boolean=true):string; function DirTemp:string; function DirExe:string; procedure MakeDirs(ASet:TFFSDirSet); procedure SetBaseDir(ABaseDir:string); procedure Register; implementation uses registry; var FBaseDir:string; procedure Register; begin RegisterComponents('FFS Common', [TProgramSettings]); end; constructor TProgramSettings.Create(AOwner: TComponent); begin inherited; // Initialize the XML key name to be used. Can be changed later {$IFDEF SERVER} SettingsKeyName := 'ServerSettings'; {$ELSE} SettingsKeyName := 'ClientSettings'; {$ENDIF} end; { TProgramSettings } function TProgramSettings.GetDirWork: string; begin result := FBaseDir; end; function TProgramSettings.GetSettingsFilePath: String; begin Result := GetShellFolderPath(CSIDL_COMMON_APPDATA) + '\AccuSystems\Tickler.xml' end; procedure TProgramSettings.ReadSettings; var reg : TRegistry; OkKey: boolean; XML: IXMLDocument; Node1: IXMLNode; begin try // VG 310818: The new settings location is in an XML file. Try to read it first and skip the old registry if XML exists if FileExists(SettingsFilePath) then begin DirWork := ''; ServerIP := ''; ServerPort := ''; XML := NewXMLDocument; XML.Options := [doNodeAutoCreate]; XML.LoadFromFile(SettingsFilePath); Node1 := XML.DocumentElement.ChildNodes[SettingsKeyName]; if Assigned(Node1) then begin DirWork := Node1.Attributes['DataDirectory']; ServerIP := Node1.Attributes['ServerIP']; ServerPort := Node1.Attributes['ServerPort']; end; Exit; end; except on E: Exception do raise Exception.CreateFmt('Unable to load XML settings: %s', [E.Message]); end; reg := TRegistry.Create; try // The server reads only from HKLM, while the client tries both HKCU and HKLM {$IFDEF SERVER} reg.RootKey := HKEY_LOCAL_MACHINE; OkKey := reg.OpenKey(RegistryKey, false); {$ELSE} reg.RootKey := HKEY_CURRENT_USER; OkKey := reg.OpenKey(RegistryKey, false); if not OkKey then begin reg.RootKey := HKEY_LOCAL_MACHINE; OkKey := reg.OpenKey(RegistryKey, false); end; {$ENDIF} if OkKey then begin try DirWork := reg.ReadString('DataDirectory'); except DirWork := ''; end; try FServerIP := reg.ReadString('ServerIP'); except FServerIP := ''; end; try FServerPort := reg.ReadString('ServerPort'); except FServerPort := ''; end; reg.CloseKey; end else raise exception.create('No Such Key ' + RegistryKey ); finally reg.free; end; end; procedure TProgramSettings.SaveSettings; var XML: IXMLDocument; Node1: IXMLNode; Reg: TRegistry; begin try XML := NewXMLDocument; XML.Options := [doNodeAutoCreate, doNodeAutoIndent]; if FileExists(SettingsFilePath) then XML.LoadFromFile(SettingsFilePath); if XML.DocumentElement = nil then XML.DocumentElement := XML.CreateNode('Tickler'); Node1 := XML.DocumentElement.ChildNodes[SettingsKeyName]; Node1.Attributes['DataDirectory'] := DirWork; Node1.Attributes['ServerIP'] := ServerIP; Node1.Attributes['ServerPort'] := ServerPort; ForceDirectories(ExtractFilePath(SettingsFilePath)); XML.SaveToFile(SettingsFilePath); except on E: Exception do raise Exception.CreateFmt('Unable to save XML settings: %s', [E.Message]); end; // VG 200918: As part of the migration to XML settings, delete the old registry ones, after the XML is saved // The code below can be removed after some time when all clients have been moved to the new versions Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.DeleteKey(RegistryKey); Reg.RootKey := HKEY_CURRENT_USER; Reg.DeleteKey(RegistryKey); finally Reg.Free end; end; procedure TProgramSettings.SetDirWork(const Value: string); begin if Value.IsEmpty then SetBaseDir(Value) else SetBaseDir(IncludeTrailingBackslash(Value)); end; procedure TProgramSettings.SetRegistryKey(const Value: string); begin FRegistryKey := Value; end; procedure TProgramSettings.SetServerIP(const Value: string); begin FServerIP := Value; end; procedure TProgramSettings.SetServerPort(const Value: string); begin FServerPort := Value; end; procedure TProgramSettings.SetSettingsKeyName(const Value: String); begin if Value.IsEmpty then raise Exception.Create('The settings key name can not be empty'); fSettingsKeyName := Value.Trim; end; function Dirs(ADir:TFFSDirectory):string; begin result := ''; case ADir of drData : result := 'Data'; drReports : result := 'Reports'; drToDo : result := 'ToDo'; drDone : result := 'Done'; drLtrAddOn : result := 'LtrAddOn'; drUpdate : result := 'Update'; drExport : result := 'Export'; end; end; function DirTemp: string; begin Result := IncludeTrailingPathDelimiter(TPath.GetTempPath); end; function Dir(ADir:TFFSDirectory;DoRaise:boolean=true):string; var s : string; begin result := ''; s := IncludeTrailingBackslash(ExtractFileDir(Application.ExeName)); case ADir of {$ifdef THINVER} drReports : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drData : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drToDo : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drDone : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drUpdate : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drExport : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drLtrAddOn : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; {$else} drReports : result := FBaseDir + Dirs(ADir); drData : result := FBaseDir + Dirs(ADir); drToDo : result := FBaseDir + Dirs(ADir); drDone : result := FBaseDir + Dirs(ADir); drUpdate : result := FBaseDir + Dirs(ADir); drExport : result := FBaseDir + Dirs(ADir); drLtrAddOn : result := FBaseDir + Dirs(ADir); {$endif} end; result := IncludeTrailingBackslash(result); if (not DirectoryExists(result)) and (DoRaise) then raise Exception.Create(Format('Tickler: Directory (%s) does not exist',[result])); end; procedure MakeDirs(ASet:TFFSDirSet); var x : TFFSDirectory; s : string; begin if Aset = [] then begin for x := drData to drUpdate do // any reason not to create them all? begin s := Dir(x,false); if not DirectoryExists(s) then ForceDirectories(s); end; end else begin for x := low(TFFSDirectory) to high(TFFSDirectory) do begin if x in ASet then begin s := Dir(x,false); if not DirectoryExists(s) then ForceDirectories(s); end; end; end; end; function DirExe:string; begin result := IncludeTrailingBackslash(ExtractFileDir(Application.ExeName)); end; procedure SetBaseDir(ABaseDir:string); begin FBaseDir := ABaseDir; end; initialization FBaseDir := ''; end.
unit Trenink; (* Trida TTrenink *) interface uses Graphics, SysUtils, Hlavicka, Cviceni, CviceniSNakresem, MyUtils; type TTrenink = class private FDelka:Integer; FHlavicka:THlavicka; FRozcvicka,FRozchytani,FFyzicka,FZacvicka,FHra:TCviceni; FCvik1,FCvik2,FCvik3,FCvik4:TCviceniSNakresem; public procedure CasNaHru(Sender: TObject); procedure VykresliNaCanvas(Canvas:TCanvas; sirka,vyska:integer); constructor Create(); property Delka:Integer read FDelka write FDelka; property Hlavicka:THlavicka read FHlavicka write FHlavicka; property Rozcvicka:TCviceni read FRozcvicka write FRozcvicka; property Rozchytani:TCviceni read FRozchytani write FRozchytani; property Cvik1:TCviceniSNakresem read FCvik1 write FCvik1; property Cvik2:TCviceniSNakresem read FCvik2 write FCvik2; property Cvik3:TCviceniSNakresem read FCvik3 write FCvik3; property Cvik4:TCviceniSNakresem read FCvik4 write FCvik4; property Hra:TCviceni read FHra write FHra; property Fyzicka:TCviceni read FFyzicka write FFyzicka; property Zacvicka:TCviceni read FZacvicka write FZacvicka; end; implementation (* procedure TTrenink.VykresliNaCanvas FUNKCE: Do zadaneho Canvasu vykresli PLAN TRENINKU... ARGUMENTY: Cvs - Canvas do ktereho se ma kreslit sirka - sirka plochy do ktere se kresli vyska - vyska plochy do ktere se kresli *) procedure TTrenink.VykresliNaCanvas(Canvas:TCanvas; sirka,vyska:integer); var dilek_x,dilek_y,nakres_x,nakres_y,now_y:integer; begin dilek_x:=round(sirka/190); dilek_y:=round(vyska/265); nakres_x:=(sirka-2*dilek_x) div 4; nakres_y:=round(nakres_x*1.875); with Canvas do begin now_y:=dilek_y*3; Pen.Color := clBlack; Font.Name:='Arial'; {vytvoreni vnejsiho oramovani} Pen.Width := dilek_x; Rectangle(0, 0, Sirka, Vyska); {vypsani hlavicky} Hlavicka.Vykresli(Canvas,Sirka,Vyska,now_y); {vytvoreni delici cary mezi hlavickou a nakresy/popisy cv.} now_y:=now_y+dilek_y*3; Pen.Width := dilek_x*2; MoveTo(0,now_y); LineTo(Sirka,now_y); {vykresleni nakresu cviceni} now_y:=now_y+dilek_y*7; Cvik1.VykresliNakres(Canvas,nakres_x,nakres_y,dilek_x,now_y); Cvik2.VykresliNakres(Canvas,nakres_x,nakres_y,dilek_x+nakres_x,now_y); Cvik3.VykresliNakres(Canvas,nakres_x,nakres_y,dilek_x+2*nakres_x,now_y); Cvik4.VykresliNakres(Canvas,nakres_x,nakres_y,dilek_x+3*nakres_x,now_y); {vypsani popisu cviceni} now_y:=now_y+nakres_y+dilek_y*7; Rozcvicka.VykresliPopis(Canvas,Sirka,Vyska,now_y); Rozchytani.VykresliPopis(Canvas,Sirka,Vyska,now_y); Cvik1.VykresliPopis(Canvas,Sirka,Vyska,now_y); Cvik2.VykresliPopis(Canvas,Sirka,Vyska,now_y); Cvik3.VykresliPopis(Canvas,Sirka,Vyska,now_y); Cvik4.VykresliPopis(Canvas,Sirka,Vyska,now_y); Hra.VykresliPopis(Canvas,Sirka,Vyska,now_y); Fyzicka.VykresliPopis(Canvas,Sirka,Vyska,now_y); Zacvicka.VykresliPopis(Canvas,Sirka,Vyska,now_y); end; end; (* procedure TTrenink.CasNaHru FUNKCE: Spocita kolik casu zbyva na hru vzdy kdyz se zmeni delka nektereho z cviceni *) procedure TTrenink.CasNaHru(Sender: TObject); begin Hra.Delka:=Delka - Rozcvicka.Delka - Rozchytani.Delka - Cvik1.Delka - Cvik2.Delka - Cvik3.Delka - Cvik4.Delka - Fyzicka.Delka - Zacvicka.Delka; end; constructor TTrenink.Create(); begin Delka:=120; Hlavicka:=THlavicka.Create; Rozcvicka:=TCviceni.Create(nil); Rozchytani:=TCviceni.Create(nil); Cvik1:=TCviceniSNakresem.Create(nil); Cvik2:=TCviceniSNakresem.Create(nil); Cvik3:=TCviceniSNakresem.Create(nil); Cvik4:=TCviceniSNakresem.Create(nil); Hra:=TCviceni.Create(nil); Fyzicka:=TCviceni.Create(nil); Zacvicka:=TCviceni.Create(nil); Rozcvicka.Nazev:='Rozběhání a protažení:'; Rozchytani.Nazev:='Základní rozchytání brankářů:'; Fyzicka.Nazev:='Trénink fyzické kondice:'; Zacvicka.Nazev:='Závěrečný výklus:'; Hra.Nazev:='Hra:'; Cvik1.Nazev:='Cvičení 1:'; Cvik2.Nazev:='Cvičení 2:'; Cvik3.Nazev:='Cvičení 3:'; Cvik4.Nazev:='Cvičení 4:'; Rozcvicka.OnExit:=CasNaHru; Rozchytani.OnExit:=CasNaHru; Cvik1.OnExit:=CasNaHru; Cvik2.OnExit:=CasNaHru; Cvik3.OnExit:=CasNaHru; Cvik4.OnExit:=CasNaHru; Fyzicka.OnExit:=CasNaHru; Zacvicka.OnExit:=CasNaHru; Hra.Minut.Enabled:=false; Hra.Minut.Width:=30; Hra.Minut.Left:=Hra.Minut.Left-5; end; end.
unit Popup_2D_Info; { Version vom 15.9.2018 } {$mode delphi} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Grids, ValEdit, StdCtrls, defaults; type { TForm_2D_Info } TForm_2D_Info = class(TForm) List_PixInfo: TValueListEditor; List_ParNames: TValueListEditor; List_LatLong: TValueListEditor; List_Statistics: TStringGrid; procedure FormCreate(Sender: TObject); procedure ShowPixInfo(Sender: TObject); procedure ShowStatistics(Sender: TObject); private procedure ShowBandInfo(Sender: TObject); public end; var Form_2D_Info: TForm_2D_Info; implementation {$R *.lfm} procedure TForm_2D_Info.FormCreate(Sender: TObject); begin ShowPixInfo(Sender); ShowStatistics(Sender); List_ParNames.visible:=FALSE; List_Statistics.visible:=FALSE; if AnsiUpperCase(ExtractFileExt(HSI_img^.FName))='.FIT' then begin List_ParNames.visible:=TRUE; ShowBandInfo(Sender); end; end; procedure TForm_2D_Info.ShowPixInfo(Sender: TObject); { Show pixel values at cursor position. } begin with List_PixInfo do begin Top:=List_LatLong.Top + List_LatLong.Height + 8; if flag_3bands then RowCount:=4 else RowCount:=2; Height:=RowCount*DefaultRowHeight+4; AutoAdjustColumns; end; end; procedure TForm_2D_Info.ShowBandInfo(Sender: TObject); { Display parameter names of files *.FIT. } var b : integer; begin with List_ParNames do begin Left:=List_LatLong.Left + List_LatLong.width + 8; if List_PixInfo.width > List_LatLong.width then Left:=List_PixInfo.Left + List_PixInfo.width + 8; RowCount:=1; for b:=1 to Channel_number do InsertRow(inttostr(b), bandname[b], TRUE); Height:=RowCount*DefaultRowHeight+4; AutoAdjustColumns; end; end; procedure TForm_2D_Info.ShowStatistics(Sender: TObject); { Show mean and standard deviation of selected area. } { Handling of StringGrids is described here: http://wiki.lazarus.freepascal.org/Grids_Reference_Page#procedure_AutoSizeColumn.28aCol:_Integer.29.3B } var i, w : integer; begin with List_Statistics do begin if flag_3bands then RowCount:=4 else RowCount:=2; Height:=RowCount*DefaultRowHeight+4; AutoAdjustColumns; w:=0; for i:=0 to ColCount-1 do w:=w+columns[i].Width; Width:=w+4; Top:=List_PixInfo.Top + List_PixInfo.Height + 8; end; end; end.
unit Thread.ImportarPlanilhaEntradaCarriers; interface uses System.Classes, Dialogs, Windows, Forms, SysUtils, Messages, Controls, System.DateUtils, System.StrUtils, Generics.Collections, Model.PlanilhaEntradaCarriers, Control.Clientes, Control.DestinosTransportes, Control.EntregadoresExpressas, Control.Entregas, Control.PlanilhaEntradaCarriers, Control.Sistema, FireDAC.Comp.Client, Common.ENum; type Thread_ImportarPlanilhaEntradaCarriers = class(TThread) private { Private declarations } destinos : TDestinosTransportesControl; entregas: TEntregasControl; planilha : TPlanilhaEntradaCarriersControl; planilhas : TObjectList<TPlanilhaEntradaCarriers>; clientes : TClientesControl; entregadores : TEntregadoresExpressasControl; sMensagem: String; FdPos: Double; bCancel : Boolean; iPos : Integer; iLinha : Integer; protected procedure Execute; override; procedure AtualizaLog; procedure AtualizaProgress; procedure TerminaProcesso; procedure IniciaProcesso; procedure SetupClass(FDQuery: TFDQuery); public FFile: String; iCodigoCliente: Integer; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure Thread_ImportarPlanilhaEntradaEntregas.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } { Thread_ImportarPlanilhaEntradaEntregas } uses Common.Utils, Global.Parametros, View.ImportarPedidos; procedure Thread_ImportarPlanilhaEntradaCarriers.Execute; var Contador, I, LinhasTotal, iRet: Integer; Linha, campo, codigo, sMess, sData: String; d: Real; aParam: array of Variant; iTotal : Integer; iCodCliente : Integer; FDQuery : TFDQuery; FDQuery1 : TFDQuery; begin Synchronize(IniciaProcesso); entregas := TEntregasControl.Create; planilha := TPlanilhaEntradaCarriersControl.Create; planilhas := TObjectList<TPlanilhaEntradaCarriers>.Create; destinos := TDestinosTransportesControl.Create; entregadores := TEntregadoresExpressasControl.Create; try try // Carregando o arquivo ... planilhas := planilha.GetPlanilha(FFile); if planilhas.Count > 0 then begin iPos := 0; FdPos := 0; iTotal := planilhas.Count; FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery; FDQuery1 := TSistemaControl.GetInstance.Conexao.ReturnQuery; for I := 0 to planilhas.Count - 1 do begin SetLength(aParam,2); aParam[0] := 'NN'; aParam[1] := FormatFloat('00000000000', StrToIntDef(planilhas[i].IDVolume,0)); FDQuery := entregas.Localizar(aParam); Finalize(aParam); if FDQuery.IsEmpty then begin SetLength(aParam,2); aParam[0] := 'FANTASIA'; aParam[1] := planilhas[i].Motorista; FDQuery1 := entregadores.Localizar(aParam); entregas.Entregas.Entregador := 1; if not FDQuery1.IsEmpty then begin entregas.Entregas.Distribuidor := FDQuery1.FieldByName('COD_AGENTE').AsInteger; entregas.Entregas.Entregador := FDQuery1.FieldByName('COD_ENTREGADOR').AsInteger; end else begin entregas.Entregas.Distribuidor := 1; entregas.Entregas.Entregador := 781; end; Finalize(aParam); FDQuery1.Close; clientes := TClientesControl.Create; entregas.Entregas.Cliente := 0; SetLength(aParam,2); aParam[0] := 'NOME'; aParam[1] := '%' + Trim(planilhas[i].Embarcador) + ' (CARRIERS)%'; FDQuery1 := clientes.Localizar(aParam); if not FDQuery1.IsEmpty then begin FDQuery1.First; entregas.Entregas.Cliente := FDQuery1.FieldByName('COD_CLIENTE').AsInteger; end; clientes.Free; FDQuery1.Close; entregas.Entregas.NN := FormatFloat('00000000000', StrToIntDef(planilhas[i].IDVolume,0)); entregas.Entregas.NF := planilhas[I].NF; entregas.Entregas.Consumidor := planilhas[I].Destinatario; entregas.Entregas.Retorno := FormatFloat('00000000000', StrToIntDef(planilhas[i].NREntrega,0)); entregas.Entregas.Endereco := planilhas[I].Endereco; entregas.Entregas.Complemento := ''; entregas.Entregas.Bairro := planilhas[I].Bairro; entregas.Entregas.Cidade := planilhas[I].Municipio; entregas.Entregas.Cep := planilhas[I].CEP; entregas.Entregas.Telefone := ''; if planilhas[I].Coleta <> '00/00/0000' then entregas.Entregas.Expedicao := StrToDate(planilhas[I].Coleta); entregas.Entregas.Previsao := StrToDate(planilhas[I].Viagem); entregas.Entregas.Status := 909; if planilhas[i].Ocorrencia = 'REALIZADA' then begin entregas.Entregas.Baixa := StrToDate(planilhas[i].DataEntrega); entregas.Entregas.Entrega := StrToDate(planilhas[i].DataEntrega); entregas.Entregas.Baixado := 'S'; if entregas.Entregas.Previsao < entregas.Entregas.Entrega then begin entregas.Entregas.Atraso := DaysBetween(entregas.Entregas.Previsao,entregas.Entregas.Entrega); end else begin entregas.Entregas.Atraso := 0; end; end else begin entregas.Entregas.Baixado := 'N'; end; entregas.Entregas.VerbaEntregador := 0; entregas.Entregas.VerbaFranquia := 0; entregas.Entregas.PesoReal := StrToFloatDef(planilhas[I].Peso,0); entregas.Entregas.PesoCobrado := StrToFloatDef(planilhas[I].Peso,0); entregas.Entregas.Volumes := StrToInt(planilhas[I].Volumes); entregas.Entregas.VolumesExtra := 0; entregas.Entregas.ValorVolumes := 0; entregas.Entregas.Atraso := 0; entregas.Entregas.Container := '0'; entregas.Entregas.ValorProduto := StrToFloatDef(planilhas[I].Valor,0); entregas.Entregas.Atribuicao := StrToDate(planilhas[I].Viagem); entregas.Entregas.Altura := 0; entregas.Entregas.Largura := 0; entregas.Entregas.Comprimento := 0; entregas.Entregas.Rastreio := '> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' inserido por importação por ' + Global.Parametros.pUser_Name; entregas.Entregas.Pedido := planilhas[I].Pedido; entregas.Entregas.CodCliente := iCodigoCliente; entregas.Entregas.Acao := tacIncluir; if not entregas.Gravar then begin sMensagem := 'Erro ao Incluir os dados do NN ' + entregas.Entregas.NN + ' !'; Synchronize(AtualizaLog); end; end else begin SetupClass(FDQuery); entregas.Entregas.Status := 909; if planilhas[i].Ocorrencia = 'REALIZADA' then begin entregas.Entregas.Baixa := StrToDate(planilhas[i].DataEntrega); entregas.Entregas.Entrega := StrToDate(planilhas[i].DataEntrega); entregas.Entregas.Baixado := 'S'; if entregas.Entregas.Previsao < entregas.Entregas.Entrega then begin entregas.Entregas.Atraso := DaysBetween(entregas.Entregas.Previsao,entregas.Entregas.Entrega); end else begin entregas.Entregas.Atraso := 0; end; end else begin entregas.Entregas.Baixado := 'N'; end; entregas.Entregas.Rastreio := entregas.Entregas.Rastreio + #13 + '> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' atualizado por importação por ' + Global.Parametros.pUser_Name; entregas.Entregas.Acao := tacAlterar; if not entregas.Gravar then begin sMensagem := 'Erro ao alterar os dados do NN ' + entregas.Entregas.NN + ' !'; Synchronize(AtualizaLog); end; end; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; if not(Self.Terminated) then begin Synchronize(AtualizaProgress); end else begin Abort; end; end; end; Except on E: Exception do begin Application.MessageBox(PChar('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message), 'Erro', MB_OK + MB_ICONERROR); bCancel := True; end; end; finally if bCancel then begin sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importação cancelada ...'; Synchronize(AtualizaLog); Application.MessageBox('Importação cancelada!', 'Importação de Entregas', MB_OK + MB_ICONWARNING); end else begin sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importação concluída com sucesso'; Synchronize(AtualizaLog); Application.MessageBox('Importação concluída com sucesso!', 'Importação de Entregas', MB_OK + MB_ICONINFORMATION); end; Synchronize(TerminaProcesso); entregas.Free; planilha.Free; planilhas.Free; destinos.Free; entregadores.Free; end; end; procedure Thread_ImportarPlanilhaEntradaCarriers.IniciaProcesso; begin bCancel := False; view_ImportarPedidos.actCancelar.Enabled := True; view_ImportarPedidos.actFechar.Enabled := False; view_ImportarPedidos.actImportar.Enabled := False; view_ImportarPedidos.actAbrirArquivo.Enabled := False; view_ImportarPedidos.dxLayoutItem8.Visible := True; sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' iniciando importação do arquivo ' + FFile; AtualizaLog; end; procedure Thread_ImportarPlanilhaEntradaCarriers.SetupClass(FDQuery: TFDQuery); begin entregas.Entregas.Distribuidor := FDQuery.FieldByName('COD_AGENTE').AsInteger; entregas.Entregas.Entregador := FDQuery.FieldByName('COD_ENTREGADOR').AsInteger; entregas.Entregas.NN := FDQuery.FieldByName('NUM_NOSSONUMERO').AsString; entregas.Entregas.NF := FDQuery.FieldByName('NUM_NF').AsString; entregas.Entregas.Cliente := FDQuery.FieldByName('COD_CLIENTE').AsInteger; entregas.Entregas.Consumidor := FDQuery.FieldByName('NOM_CONSUMIDOR').AsString; entregas.Entregas.Endereco := FDQuery.FieldByName('DES_ENDERECO').AsString; entregas.Entregas.Complemento := FDQuery.FieldByName('DES_COMPLEMENTO').AsString; entregas.Entregas.Bairro := FDQuery.FieldByName('DES_BAIRRO').AsString; entregas.Entregas.Cidade := FDQuery.FieldByName('NOM_CIDADE').AsString; entregas.Entregas.Cep := FDQuery.FieldByName('NUM_CEP').AsString; entregas.Entregas.Telefone := FDQuery.FieldByName('NUM_TELEFONE').AsString ; entregas.Entregas.Expedicao := FDQuery.FieldByName('DAT_EXPEDICAO').AsDateTime; entregas.Entregas.Previsao := FDQuery.FieldByName('DAT_PREV_DISTRIBUICAO').AsDateTime; entregas.Entregas.Status := FDQuery.FieldByName('COD_STATUS').AsInteger; entregas.Entregas.Baixado := FDQuery.FieldByName('DOM_BAIXADO').AsString; entregas.Entregas.VerbaEntregador := FDQuery.FieldByName('VAL_VERBA_ENTREGADOR').AsFloat; entregas.Entregas.VerbaFranquia := FDQuery.FieldByName('VAL_VERBA_FRANQUIA').AsFloat; entregas.Entregas.PesoReal := FDQuery.FieldByName('QTD_PESO_REAL').AsFloat; entregas.Entregas.PesoCobrado := FDQuery.FieldByName('QTD_PESO_COBRADO').AsFloat; entregas.Entregas.Volumes := FDQuery.FieldByName('QTD_VOLUMES').AsInteger; entregas.Entregas.VolumesExtra := FDQuery.FieldByName('QTD_VOLUMES_EXTRA').AsFloat; entregas.Entregas.ValorVolumes := FDQuery.FieldByName('VAL_VOLUMES_EXTRA').AsFloat; entregas.Entregas.Atraso := FDQuery.FieldByName('QTD_DIAS_ATRASO').AsInteger; entregas.Entregas.Container := FDQuery.FieldByName('NUM_CONTAINER').AsString; entregas.Entregas.ValorProduto := FDQuery.FieldByName('VAL_PRODUTO').AsFloat; entregas.Entregas.Atribuicao := FDQuery.FieldByName('DAT_ATRIBUICAO').AsDateTime; entregas.Entregas.Altura := FDQuery.FieldByName('QTD_ALTURA').AsInteger; entregas.Entregas.Largura := FDQuery.FieldByName('QTD_LARGURA').AsInteger; entregas.Entregas.Comprimento := FDQuery.FieldByName('QTD_COMPRIMENTO').AsInteger; entregas.Entregas.Rastreio := FDQuery.FieldByName('DES_RASTREIO').AsString; entregas.Entregas.Pedido := FDQuery.FieldByName('NUM_PEDIDO').AsString; entregas.Entregas.Retorno := FDQuery.FieldByName('DES_RETORNO').AsString; entregas.Entregas.CodCliente := FDQuery.FieldByName('COD_CLIENTE_EMPRESA').AsInteger; end; procedure Thread_ImportarPlanilhaEntradaCarriers.AtualizaLog; begin view_ImportarPedidos.memLOG.Lines.Add(sMensagem); view_ImportarPedidos.memLOG.Lines.Add(''); iLinha := view_ImportarPedidos.memLOG.Lines.Count - 1; view_ImportarPedidos.memLOG.Refresh; end; procedure Thread_ImportarPlanilhaEntradaCarriers.AtualizaProgress; begin view_ImportarPedidos.pbImportacao.Position := FdPos; view_ImportarPedidos.pbImportacao.Properties.Text := FormatFloat('0.00%',FdPos); view_ImportarPedidos.pbImportacao.Refresh; view_ImportarPedidos.memLOG.Lines[iLinha] := ' >>> ' + IntToStr(iPos) + ' registros processados'; view_ImportarPedidos.memLOG.Refresh; if not(view_ImportarPedidos.actCancelar.Visible) then begin view_ImportarPedidos.actCancelar.Visible := True; view_ImportarPedidos.actFechar.Enabled := False; view_ImportarPedidos.actImportar.Enabled := False; end; end; procedure Thread_ImportarPlanilhaEntradaCarriers.TerminaProcesso; begin view_ImportarPedidos.actCancelar.Enabled := False; view_ImportarPedidos.actFechar.Enabled := True; view_ImportarPedidos.actImportar.Enabled := True; view_ImportarPedidos.actAbrirArquivo.Enabled := True; view_ImportarPedidos.edtArquivo.Clear; view_ImportarPedidos.pbImportacao.Position := 0; view_ImportarPedidos.pbImportacao.Clear; view_ImportarPedidos.dxLayoutItem8.Visible := False; view_ImportarPedidos.cboCliente.ItemIndex := 0; end; end.
unit NtUtils.Exec.Wmi; interface uses NtUtils.Exec; type TExecCallWmi = class(TInterfacedObject, IExecMethod) function Supports(Parameter: TExecParam): Boolean; function Execute(ParamSet: IExecProvider): TProcessInfo; end; implementation uses Winapi.ActiveX, System.Win.ComObj, System.SysUtils, Ntapi.ntpsapi, Winapi.ProcessThreadsApi, NtUtils.Exec.Win32, NtUtils.Tokens.Impersonate, NtUtils.Objects, NtUtils.Exceptions; function GetWMIObject(const objectName: String): IDispatch; var chEaten: Integer; BindCtx: IBindCtx; Moniker: IMoniker; begin OleCheck(CreateBindCtx(0, BindCtx)); OleCheck(MkParseDisplayName(BindCtx, StringToOleStr(objectName), chEaten, Moniker)); OleCheck(Moniker.BindToObject(BindCtx, nil, IDispatch, Result)); end; function PrepareProcessStartup(ParamSet: IExecProvider): OleVariant; var Flags: Cardinal; begin Result := GetWMIObject('winmgmts:Win32_ProcessStartup'); // For some reason when specifing Win32_ProcessStartup.CreateFlags // processes would not start without CREATE_BREAKAWAY_FROM_JOB. Flags := CREATE_BREAKAWAY_FROM_JOB; if ParamSet.Provides(ppCreateSuspended) and ParamSet.CreateSuspended then Flags := Flags or CREATE_SUSPENDED; Result.CreateFlags := Flags; if ParamSet.Provides(ppShowWindowMode) then Result.ShowWindow := ParamSet.ShowWindowMode; end; function PrepareCurrentDir(ParamSet: IExecProvider): String; begin if ParamSet.Provides(ppCurrentDirectory) then Result := ParamSet.CurrentDircetory else Result := GetCurrentDir; end; { TExecCallWmi } function TExecCallWmi.Execute(ParamSet: IExecProvider): TProcessInfo; var objProcess: OleVariant; hOldToken: THandle; ProcessId: Integer; begin if ParamSet.Provides(ppToken) then begin // Backup current impersonation hOldToken := NtxBackupImpersonation(NtCurrentThread); // Impersonate the passed token NtxImpersonateAnyToken(ParamSet.Token).RaiseOnError; end; try objProcess := GetWMIObject('winmgmts:Win32_Process'); objProcess.Create( PrepareCommandLine(ParamSet), PrepareCurrentDir(ParamSet), PrepareProcessStartup(ParamSet), ProcessId ); finally // Revert impersonation if ParamSet.Provides(ppToken) then begin NtxRestoreImpersonation(NtCurrentThread, hOldToken); if hOldToken <> 0 then NtxSafeClose(hOldToken); end; end; // Only process ID is available to return to the caller FillChar(Result, SizeOf(Result), 0); Result.dwProcessId := Cardinal(ProcessId); end; function TExecCallWmi.Supports(Parameter: TExecParam): Boolean; begin case Parameter of ppParameters, ppCurrentDirectory, ppToken, ppCreateSuspended, ppShowWindowMode: Result := True; else Result := False; end; end; end.
unit AmountRateWinApp; interface uses BaseWinApp, BaseStockApp, StockInstantDataAccess; type TAmountRateApp = class(TBaseStockApp) protected fLastStockInstant: TDBStockInstant; fCurrentStockInstant: TDBStockInstant; public constructor Create(AppClassId: AnsiString); override; destructor Destroy; override; function Initialize: Boolean; override; procedure Finalize; override; procedure Run; override; property LastStockInstant: TDBStockInstant read fLastStockInstant; property CurrentStockInstant: TDBStockInstant read fCurrentStockInstant; end; var GlobalApp: TAmountRateApp = nil; implementation uses SysUtils, define_datasrc, define_dealstore_file, AmountRateWindow; { TStockFloatApp } constructor TAmountRateApp.Create(AppClassId: AnsiString); begin inherited; fLastStockInstant := nil; fCurrentStockInstant := nil; end; destructor TAmountRateApp.Destroy; begin inherited; end; function TAmountRateApp.Initialize: Boolean; var tmpPathUrl: AnsiString; tmpFileUrl: AnsiString; tmpDay: Integer; tmpDayOfWeek: Integer; i: integer; begin inherited Initialize; Result := false; InitializeDBStockItem; if nil <> StockItemDB then begin if 0 < StockItemDB.RecordCount then begin fLastStockInstant := TDBStockInstant.Create(FilePath_DBType_Item, DataSrc_Sina); tmpDay := Trunc(now()) - 1; tmpDayOfWeek := DayOfWeek(tmpDay); if 1 = tmpDayOfWeek then tmpDay := tmpDay - 2; if 6 = tmpDayOfWeek then tmpDay := tmpDay - 1; tmpPathUrl := Self.Path.DataBasePath[FilePath_DBType_Item, FilePath_DataType_InstantData, 0]; tmpFileUrl := tmpPathUrl + Copy(FormatDateTime('yyyymmdd', tmpDay), 5, MaxInt) + '.' + FileExt_StockInstant; if not FileExists(tmpFileUrl) then begin tmpFileUrl := tmpPathUrl + Copy(FormatDateTime('yyyymmdd', tmpDay), 7, MaxInt) + '.' + FileExt_StockInstant; end; if FileExists(tmpFileUrl) then begin LoadDBStockInstant(StockItemDB, fLastStockInstant, tmpFileUrl); if 0 < fLastStockInstant.RecordCount then begin fCurrentStockInstant := TDBStockInstant.Create(FilePath_DBType_Item, DataSrc_Sina); for i := 0 to StockItemDB.RecordCount - 1 do begin if 0 <> StockItemDB.Items[i].EndDealDate then Continue; fCurrentStockInstant.AddItem(StockItemDB.Items[i]); end; Result := CreateAmountRateWindow(Self); end; end; end; end; end; procedure TAmountRateApp.Finalize; begin if nil <> fCurrentStockInstant then FreeAndNil(fCurrentStockInstant); if nil <> fLastStockInstant then FreeAndNil(fLastStockInstant); inherited; end; procedure TAmountRateApp.Run; begin inherited; ShowAmountRateWindow; RunAppMsgLoop; end; end.
unit fw_calc; {$MODE Delphi} { Calculates spectra in forward mode. Version vom 22.8.2019 } interface uses defaults; procedure calc_T_WV; procedure calc_T_O3; procedure calc_Tr_GC; procedure calc_omega_a; procedure calc_M; procedure calc_Fa; procedure calc_tau_a_GC; procedure calc_T_as; procedure calc_Ed_GreggCarder; procedure calc_a; procedure calc_b; procedure calc_omega_b; procedure calc_R_rs; procedure calc_R; procedure calc_Rrs_surface; procedure calc_Kd; procedure calc_kL_uW; procedure calc_Lu; procedure calc_R_rs_below; procedure calc_R_bottom; procedure calc_KE_uW(sun:double); procedure calc_KE_uB(sun:double); procedure calc_f_factor; procedure calc_Rrs_F(z, zB, flu, A_phy, A_DOM: double); procedure calc_test; implementation uses SysUtils, misc, privates, math, gui; { Downwelling irradiance; model of Gregg and Carder (1990): W. W. Gregg, K. L. Carder, "A simple spectral solar irradiance model for cloudless maritime atmospheres," Limnol. Oceanogr. 35, 1657-1675 (1990) } procedure calc_omega_a; { Aerosol single scattering albedo } begin omega_a:=(-0.0032*AM+0.972)*exp(3.06E-4*RH); end; procedure calc_Fa; { Aerosol forward scattering probability } var B1, B2, B3 : double; argument : double; begin if alpha.fw<0 then argument:=1-0.82 else if alpha.fw>1.2 then argument:=1-0.65 else argument:=1+0.1417*alpha.fw-0.82; if argument<nenner_min then argument:=nenner_min; B3:=ln(argument); B2:=B3*(0.0783+B3*(-0.3824-0.5874*B3)); B1:=B3*(1.459+B3*(0.1595+0.4129*B3)); F_a:=1-0.5*exp((B1+B2*cos(sun.fw*pi/180))*cos(sun.fw*pi/180)); end; procedure calc_M; { Air mass. The equation given in Gregg and Carder (1990), which was taken from Kasten (1965), is outdated. Kasten and Young (1989) provide updated numerical values a = 0.50572, b = 6.07995°, c = 1.6364. These replace the old values a = 0.15, b = 3.885°, c = 1.253. } var nenner : double; begin nenner:=cos(sun.fw*pi/180)+0.50572*power((96.07995-sun.fw),-1.6364); if abs(nenner)<nenner_min then nenner:=nenner_min; GC_M:=1/nenner; end; procedure calc_M_ozone; { Atmospheric path length of ozone} var nenner : double; begin nenner:=sqrt(sqr(cos(sun.fw*pi/180))+0.007); if abs(nenner)<nenner_min then nenner:=nenner_min; M_oz:=1.0035/nenner; end; procedure calc_Tr_GC; { Transmittance of atmosphere caused by Rayleigh scattering, eq. (2.27); Gregg and Carder (1990) } var k : integer; nenner : double; sq : double; M : double; { atmospheric path length corrected for pressure } begin M:=GC_M*GC_P/1013.25; for k:=1 to Channel_number do begin sq:=sqr(x^.y[k]/1000); nenner:=115.6406*sq*sq-1.335*sq; if abs(nenner)<nenner_min then nenner:=nenner_min; GC_T_r^.y[k] := exp(-M/nenner); end; GC_T_r^.ParText:='Transmittance of the atmosphere after Rayleigh scattering'; GC_T_r^.sim:=TRUE; end; procedure calc_tau_a_GC; { Aerosol optical thickness; Gregg and Carder (1990) } var k : integer; begin for k:=1 to Channel_number do GC_tau_a^.y[k]:= beta.fw*power(x^.y[k]/Lambda_a, -alpha.fw); GC_tau_a^.ParText:='Aerosol optical thickness'; GC_tau_a^.sim:=TRUE; end; procedure calc_T_as; { Atmospheric transmittance after aerosol scattering, eq. (2.29); Gregg and Carder (1990) } var k : integer; begin for k:=1 to Channel_number do GC_T_as^.y[k]:= exp(-omega_a*GC_tau_a^.y[k]*GC_M); GC_T_as^.ParText:='Transmittance of the atmosphere after aerosol scattering'; GC_T_as^.sim:=TRUE; end; procedure calc_T_aa; { Atmospheric transmittance after aerosol absorption, eq. (2.28); Gregg and Carder (1990) } var k : integer; begin for k:=1 to Channel_number do GC_T_aa^.y[k]:= exp(-(1-omega_a)*GC_tau_a^.y[k]*GC_M); GC_T_aa^.ParText:='Transmittance of the atmosphere after aerosol absorption'; GC_T_aa^.sim:=TRUE; end; procedure calc_T_o2; { Atmospheric transmittance after oxygen absorption, eq. (2.31); Gregg and Carder (1990) } var k : integer; argument : double; M : double; { atmospheric path length corrected for pressure } begin M:=GC_M*GC_P/1013.25; for k:=1 to Channel_number do begin argument:=-1.41*aO2^.y[k]*M/power(1+118.3*aO2^.y[k]*M,0.45); if argument>exp_max then argument:=exp_max; GC_T_o2^.y[k]:=exp(argument); end; GC_T_o2^.ParText:='Transmittance of the atmosphere after oxygen absorption'; GC_T_o2^.sim:=TRUE; end; procedure calc_T_o3; { Atmospheric transmittance after ozone absorption, eq. (2.30); Gregg and Carder (1990) } var k : integer; argument : double; begin calc_M_ozone; for k:=1 to Channel_number do begin argument:=-aO3^.y[k]*M_oz*H_oz.fw; if argument>exp_max then argument:=exp_max; GC_T_o3^.y[k]:=exp(argument); end; GC_T_o3^.ParText:='Transmittance of the atmosphere after ozone absorption'; GC_T_o3^.sim:=TRUE; end; procedure calc_T_WV; { Atmospheric transmittance after water vapor absorption, eq. (2.32); Gregg and Carder (1990) } var argument : double; k : integer; begin for k:=1 to Channel_number do begin argument:=-0.2385*aWV^.y[k]*WV.fw*GC_M/power(1+20.07*aWV^.y[k]*WV.fw*GC_M,0.45); if argument>exp_max then argument:=exp_max; GC_T_WV^.y[k]:=exp(argument); end; GC_T_WV^.ParText:='Transmittance of the atmosphere after water vapor absorption'; GC_T_WV^.sim:=TRUE; end; procedure calc_Edd; { Direct downwelling irradiance, eq. (2.24); Gregg and Carder (1990) } var k : integer; sz_air : double; rho : double; begin sz_air :=sun.fw*pi/180; if flag_fresnel_sun then rho:=Fresnel(sun.fw) else rho:=rho_dd.fw; for k:=1 to Channel_number do begin GC_Edd^.y[k]:=f_dd.fw*E0^.y[k]*sun_earth*cos(sz_air)* GC_T_r^.y[k]*GC_T_aa^.y[k]*GC_T_o2^.y[k]*GC_T_o3^.y[k]* GC_T_WV^.y[k]*GC_T_as^.y[k]; if not flag_above then GC_Edd^.y[k]:=GC_Edd^.y[k]*exp(-Kdd^.y[k]*z.fw)*r_theta_fw*(1-rho); end; if dsmpl>0 then resample_Rect(GC_Edd^); GC_Edd^.ParText:='Downwelling direct irradiance (mW m^-2 nm^-1)'; GC_Edd^.sim:=TRUE; end; procedure calc_Eds; { Diffuse downwelling irradiance, eqs. (2.25) and (2.26); Gregg and Carder (1990) } var k : integer; rho : double; sz_air : double; begin sz_air :=sun.fw*pi/180; if flag_calc_rho_ds then rho:=rho_diffuse(sz_air) else rho:=rho_ds.fw; for k:=1 to Channel_number do begin GC_Edsr^.y[k]:=0.5*E0^.y[k]*sun_earth*cos(sz_air)* GC_T_aa^.y[k]*GC_T_o2^.y[k]*GC_T_o3^.y[k]*GC_T_WV^.y[k]* (1-power(GC_T_r^.y[k],0.95)); GC_Edsa^.y[k]:=E0^.y[k]*sun_earth*cos(sz_air)*GC_T_aa^.y[k]* GC_T_o2^.y[k]*GC_T_o3^.y[k]*GC_T_WV^.y[k]* power(GC_T_r^.y[k],1.5)*(1-GC_T_as^.y[k])*F_a; end; { Average irradiance spectra above water for consistency with Hydrolight. Note: this averaging accounts for non-linearity of E with concentrations of atmospheric components, but not with concentrations of water constituents. } if dsmpl>0 then resample_Rect(GC_Edsr^); if dsmpl>0 then resample_Rect(GC_Edsa^); for k:=1 to Channel_number do begin if not flag_above then begin GC_Edsa^.y[k]:=GC_Edsa^.y[k]*exp(-Kds^.y[k]*z.fw)*r_theta_fw*(1-rho); GC_Edsr^.y[k]:=GC_Edsr^.y[k]*exp(-Kds^.y[k]*z.fw)*r_theta_fw*(1-rho); end; GC_Eds^.y[k]:=f_ds.fw*GC_Edsr^.y[k] + f_ds.fw*GC_Edsa^.y[k]; { Upwelling irradiance reflected at the water surface in downward direction } if not flag_above then GC_Eds^.y[k]:=GC_Eds^.y[k] * (1 + f_ds.fw *rho_Eu*R^.y[k]*(1+r_d^.y[k])); end; GC_Edsr^.ParText:='Downwelling irradiance due to Rayleigh scattering (mW m^-2 nm^-1)'; GC_Edsa^.ParText:='Downwelling irradiance due to aerosol scattering (mW m^-2 nm^-1)'; GC_Eds^.ParText :='Downwelling diffuse irradiance (mW m^-2 nm^-1)'; GC_Edsr^.sim:=TRUE; GC_Edsa^.sim:=TRUE; GC_Eds^.sim :=TRUE; end; procedure calc_rd0; { Ratio of direct to diffuse Ed component just below water surface, see WASI manual eq. (2.37) } var k : integer; nenner : double; begin for k:=1 to Channel_number do begin nenner:=f_ds.fw* (1-power(GC_T_r^.y[k],0.95)+2*power(GC_T_r^.y[k],1.5)* (1-GC_T_as^.y[k])*F_a)*(1-rho_ds.fw); if abs(nenner)<nenner_min then nenner:=nenner_min; r_d^.y[k]:=f_dd.fw*2*GC_T_r^.y[k]*GC_T_as^.y[k]*(1-rho_dd.fw)/nenner; end; r_d^.ParText:='Ratio of direct to diffuse downwelling irradiance just below water surface'; r_d^.sim:=TRUE; end; procedure calc_rd; { Ratio of direct to diffuse Ed component } var k : integer; nenner : double; begin for k:=1 to Channel_number do begin nenner:=GC_Eds^.y[k]; if abs(nenner)<nenner_min then nenner:=nenner_min; r_d^.y[k]:=GC_Edd^.y[k]/nenner; end; r_d^.ParText:='Ratio of direct to diffuse downwelling irradiance'; r_d^.sim:=TRUE; end; procedure calc_Ed_GC; { Downwelling irradiance, Gregg and Carder (1990) } var k : integer; begin for k:=1 to Channel_number do Ed^.y[k]:=GC_Edd^.y[k]+GC_Eds^.y[k]; Ed^.ParText:='Downwelling irradiance (mW m^-2 nm^-1)'; Ed^.sim:=TRUE; end; procedure calc_Ed_GreggCarder; var flag_merk : boolean; Fluo_merk : Attr_spec; begin flag_merk:=flag_fluo; Fluo_merk:=RrsF^; flag_fluo:=FALSE; if not flag_above then calc_Kd; calc_omega_a; { omega_a, Single scattering albedo } calc_Fa; { F_a, Aerosol forward scattering probability } calc_M; { GC_M, Air mass } calc_Tr_GC; { GC_T_r, Rayleigh scattering transmittance } calc_tau_a_GC; { GC_tau_a, Aerosol optical thickness } calc_T_as; { GC_T_as, Aerosol scattering transmittance } calc_T_aa; { GC_T_aa, Aerosol absorption transmittance } calc_T_o2; { GC_T_o2, Oxygen absorption transmittance } calc_T_o3; { GC_T_o3, Ozone absorption transmittance } calc_T_WV; { GC_T_WV, Water vapour transmittance } if not flag_use_R then calc_R; calc_rd0; { r_d(0-), Ratio of direct to diffuse Ed component } calc_Edd; { GC_Edd, Direct downwelling irradiance } calc_Eds; { GC_Eds, Diffuse downwelling irradiance } calc_Ed_GC; { Ed, Downwelling irradiance } calc_rd; { r_d, Ratio of direct to diffuse Ed component } flag_fluo:=flag_merk; RrsF^:=Fluo_merk; end; { Absorption } procedure calc_a_WC; { Absorption of water constituents } var i, k : integer; lna : double; C_NAP : double; begin if (not flag_public) and flag_aph_C and (c[0].fw>nenner_min) then begin for k:=1 to Channel_number do begin { Calculate specific phytoplankton absorption as a function of CHL concentration. Reference: P. Ylöstalo, K. Kallio and J. Seppälä (2014): Absorption properties of in-water constituents and their variation among various lake types in the boreal region. Remote Sensing of Environment 148, 190-205. } if (aphA^.y[k]>nenner_min) then begin lna:=ln(aphA^.y[k]) - aphB^.y[k] * ln(c[0].fw); aP[0]^.y[k]:=exp(lna); end else aP[0]^.y[k]:=0; end; aP[0]^.ParText:='Specific absorption (m^2/mg) (Simulated spectrum)'; end; C_NAP:=C_X.fw + C_Mie.fw; Chl_a:=0; for i:=0 to 5 do Chl_a:=Chl_a+c[i].fw; for k:=1 to Channel_number do begin aP_calc^.y[k]:=0; for i:=0 to 5 do aP_calc^.y[k]:=aP_calc^.y[k] + C[i].fw*aP[i]^.y[k]; aNAP_calc^.y[k]:=C_NAP * aNAP440 * aNAP^.y[k]; aCDOM_calc^.y[k]:=C_Y.fw * aY^.y[k]; a^.y[k]:=aP_calc^.y[k] + aNAP_calc^.y[k] + aCDOM_calc^.y[k]; end; a^.ParText:= 'Absorption of water constituents (m^-1)'; a^.sim:=TRUE; aP_calc^.ParText:='Phytoplankton absorption (m^-1)'; aP_calc^.sim:=TRUE; aNAP_calc^.ParText:='Non-algal particle absorption (m^-1)'; aNAP_calc^.sim:=TRUE; aCDOM_calc^.ParText:='CDOM absorption (m^-1)'; aCDOM_calc^.sim:=TRUE; end; procedure calc_a; { Absorption of water } var k : integer; begin calc_a_WC; if flag_aW or (spec_type<>S_a) then begin for k:=1 to Channel_number do a^.y[k]:=a^.y[k]+ aW^.y[k] + (T_W.fw-T_W0)*dadT^.y[k]; a^.ParText:= 'Absorption coefficient (m^-1)'; a^.sim:=TRUE; end; end; procedure calc_bb; { Backscattering } var k : integer; cc, fak : double; begin if flag_CXisC0 then cc:=C[0].fw else cc:=C_X.fw; if flag_bX_linear then fak:=bb_X else begin { b_bL* = A C^B (Morel 1980) } if cc>nenner_min then fak:=bbX_A*exp(bbX_B*ln(cc)) else fak:=bbX_A; end; for k:=1 to Channel_number do begin bb_phy^.y[k] := Chl_a * bbs_phy.fw * bPhyN^.y[k]; bb_NAP^.y[k] := cc * fak * bXN^.y[k] + C_Mie.fw * bbMie^.y[k]; bb^.y[k] := bbW^.y[k] + bb_phy^.y[k] + bb_NAP^.y[k]; end; bb^.ParText:= 'Backscattering coefficient (m^-1)'; bb^.sim:=TRUE; bb_phy^.ParText:= 'Phytoplankton backscattering coefficient (m^-1)'; bb_phy^.sim:=TRUE; bb_NAP^.ParText:= 'Non-algal particle backscattering coefficient (m^-1)'; bb_NAP^.sim:=TRUE; end; procedure calc_b; { Scattering } var k : integer; cc : double; begin if flag_CXisC0 then cc:=C[0].fw else cc:=C_X.fw; for k:=1 to Channel_number do b^.y[k] := 2*bbW^.y[k] + cc * b_X * bXN^.y[k] + C_Mie.fw * bMie^.y[k]; b^.ParText:= 'Scattering coefficient (m^-1)'; b^.sim:=TRUE; end; procedure calc_omega_b; { Backscattering albedo } var k : integer; begin calc_a; calc_bb; for k:=1 to Channel_number do if Model_R=0 then omega_b^.y[k] := bb^.y[k] / (a^.y[k] + bb.y[k]) // Gordon et al. (1975) else omega_b^.y[k] := bb^.y[k] / a^.y[k]; // Prieur (1976) omega_b^.ParText:= 'omega_b = bb / (a+bb)'; omega_b^.sim:=TRUE; end; procedure calc_f_factor; { Factor f of irradiance reflectance spectrum } var k : integer; begin calc_omega_b; for k:=1 to Channel_number do begin f_R^.y[k]:=calc_f(omega_b^.y[k], bbW^.y[k]/bb^.y[k], sun.fw); // in unit misc if f_rs^.sim then Q_f^.y[k]:=calc_Q_f(f_rs^.y[k], f_R^.y[k]); end; f_R^.ParText:='f factor'; f_R^.sim:=TRUE; if f_rs^.sim then Q_f^.ParText:='Q factor (sr)'; if f_rs^.sim then Q_f^.sim:=TRUE; end; { Fluorescence } procedure calculate_Ed_Ed0(zz:double); { Downwelling irradiance at depth zz and just beneath water surface. Used for fluorescence calculation. } var temp_flag : boolean; temp_z : double; begin temp_flag :=flag_above; temp_z :=z.fw; flag_above:=FALSE; z.fw :=0; calc_Ed_GreggCarder; Ed0^:=Ed^; Ed0^.ParText:='Downwelling irradiance just beneath water surface (mW m^-2 nm^-1)'; Ed0^.sim:=TRUE; z.fw :=zz; calc_Ed_GreggCarder; { Ed at depth z } flag_above:=temp_flag; { restore flag_above } z.fw :=temp_z; { restore z.fw } end; function calc_Lf(ex, em: integer; z, zB, A_chl, A_phy, A_DOM: double): double; { Calculate fluorescence radiance as integral over water layer from depth z to depth zB. ex, em are the channels of excitation and emission wavelength, the A's are the fluorescence amplitudes. } var layer : double; // Depth integral of water layer nenner : double; // Denominator; avoid division by zero Lf_chl : double; // Fluorescence radiance caused by chl-a Lf_phy : double; // Fluorescence radiance caused by phytoplankton Lf_DOM : double; // Fluorescence radiance caused by dissolved organic matter begin if (A_chl>0) and (x^.y[ex]>=PAR_min) and (x^.y[ex]<=PAR_max) then Lf_chl:=Gauss(x^.y[em]-Lambda_f0, Sigma_f0, A_chl) else Lf_chl:=0; (* Deactivated until EEMs of Anna are properly implemented if not flag_public then begin if A_phy>0 then Lf_phy:=A_phy*EEM_ph.EEM[em,ex] else Lf_phy:=0; if A_DOM>0 then Lf_DOM:=A_DOM*EEM_DOM.EEM[em,ex] else Lf_DOM:=0; end else begin *) Lf_phy:=0; Lf_DOM:=0; (* end; *) if flag_above then // sensor above water, z=0 layer:=abs(1-exp(-(Kd^.y[ex]+kL_uW^.y[em])*zB)) else // sensor in water, z>0 layer:=abs(exp(-Kd^.y[ex]*z)-exp(-(Kd^.y[ex]*zB-kL_uW^.y[em])*(zB-z))); nenner:=4*pi*x^.y[em]*(Kd^.y[ex]+kL_uW^.y[em]); if abs(nenner)<nenner_min then nenner:=nenner_min; calc_Lf:=(Lf_chl + Lf_phy + Lf_DOM) * f_EO * Ed0^.y[ex] * x^.y[ex] / nenner; end; procedure calc_Lf_layer(z, zB, flu, A_phy, A_DOM: double); { Calculate fluorescence radiance spectrum Lf^.y[em] for channels em. Excitation is integrated over the channels [1, em]. } var ex : integer; // Channel number of excitation wavelength em : integer; // Channel number of emission wavelength dex : double; // Excitation wavelength interval Ac : double; // Amplitude of chl-a fluorescence begin calculate_Ed_Ed0(z); // Calculate spectra Ed0^ at depth 0 and Ed^ at depth z if kL_uW^.sim=FALSE then calc_kL_uW; // calculate spectrum kL_uW^ if Kd^.sim=FALSE then calc_Kd; // calculate spectra Kd^, Kdd^, Kds^ for em:=1 to Channel_number do begin Lf^.y[em]:=0; // initialize spectrum Lf^ for ex:=1 to em-1 do begin dex:=x^.y[ex+1]-x^.y[ex]; Ac:=flu*Q_a*ap_calc^.y[ex]; Lf^.y[em]:=Lf^.y[em]+calc_Lf(ex,em,z,zB,Ac,A_phy,A_DOM)*dex; end; end; Lf^.ParText:='Fluorescence component of upwelling radiance (mW m^-2 nm^-1 sr^-1)'; Lf^.Sim:=TRUE; end; procedure calc_Rrs_F(z, zB, flu, A_phy, A_DOM: double); { Fluorescence component of radiance reflectance, eq. (2.47) } var em : integer; // channel number of emission nenner : double; // Denominator; avoid division by zero begin set_zero(RrsF^); if flag_fluo then begin if (spec_type=S_Rrs) or (spec_type=S_R) or (spec_type=S_Lup) then calc_Lf_layer(z, zB, flu, A_phy, A_DOM); for em:=1 to Channel_number do begin nenner:=Ed^.y[em]; if abs(nenner)<nenner_min then nenner:=nenner_min; RrsF^.y[em]:=Lf^.y[em]/nenner; if RrsF^.y[em]>10 then RrsF^.y[em]:=10; // avoid scaling problem end; RrsF^.ParText:='Fluorescence component of radiance reflectance (1/sr)'; end else RrsF^.ParText:=''; RrsF^.sim:=TRUE; end; procedure calc_R_deep; { Subsurface irradiance reflectance of deep water, eq. (2.14) } var k : integer; begin calc_f_factor; if flag_fluo then calc_Rrs_F(z.fw, zB.fw, fluo.fw, dummy.fw, test.fw); { Fluorescence } for k:=1 to Channel_number do R^.y[k]:= f_R^.y[k]*omega_b^.y[k] + Q.fw*RrsF^.y[k]; R^.ParText:='Irradiance reflectance'; R^.sim:=TRUE; end; procedure calc_Ls; { Sky radiance reflected at the surface, eq. (2.42) } var k : integer; begin if not flag_use_Ls then for k:=1 to Channel_number do begin Ls^.y[k]:= g_dd.fw * GC_Edd^.y[k] + g_dsr.fw * GC_Edsr^.y[k] + g_dsa.fw * GC_Edsa^.y[k]; Ls^.ParText:='Sky radiance (mW m^-2 nm^-1 sr^-1)'; Ls^.sim:=TRUE; end; { otherwise measured spectrum Ls is taken } end; { Reflectance } procedure calc_Rrs_surface; { Specular reflections at the surface, eq. (2.13a) or eq. (2.13b) } var k : integer; nenner : double; begin if flag_surf_fw then begin { wavelength dependent surface reflections } calc_Ed_GreggCarder; calc_Ls; for k:=1 to Channel_number do begin nenner:=Ed^.y[k]; if abs(nenner)<nenner_min then nenner:=nenner_min; Rrs_surf^.y[k]:= rho_L.fw * Ls^.y[k] / nenner; if flag_MP then Rrs_surf^.y[k]:=Rrs_surf^.y[k]+rho_L.fw * fA[4].fw; end; end else for k:=1 to Channel_number do { constant surface reflections } Rrs_surf^.y[k]:= rho_L.fw / pi; Rrs_surf^.ParText:='Surface reflectance (1/sr)'; Rrs_surf^.sim:=TRUE; end; procedure calc_R_bottom; { Bottom reflectance, eq. (2.21) for L sensors, eq. (2.22) for E sensors } var k, i : integer; sum : double; begin if flag_L then { L sensor: R_rs_bottom } for k:=1 to Channel_number do begin sum:=0; for i:=0 to 5 do sum:=sum + fA[i].fw*BRDF[i]*albedo[i]^.y[k]; bottom^.y[k]:= sum; bottom^.ParText:='Bottom radiance reflectance (1/sr)'; end else { E sensor: R_bottom = bottom albedo} for k:=1 to Channel_number do begin sum:=0; for i:=0 to 5 do sum:=sum + fA[i].fw*albedo[i]^.y[k]; bottom^.y[k]:= sum; bottom^.ParText:='Bottom albedo'; end; bottom^.sim:=TRUE; end; procedure calc_Kd; { Attenuation coefficients of downwelling irradiance: Kd = attenuation of Ed, eq. (2.17) Kdd = attenuation of Edd, eq. (2.55) Kds = attenuation of Eds, eq. (2.56) } var k, i : integer; sz_water : double; sz_cos : double; sz_1cos : double; lds : double; z99 : double; eu : double; begin calc_a; calc_b; calc_bb; sz_water :=arcsin(sin(sun.fw*pi/180)/nW); sz_cos := cos(sz_water); if abs(sz_cos)>nenner_min then sz_1cos:=1/sz_cos else sz_1cos:=1; if (sun.fw<90) and(view.fw=-1) then r_theta_fw:=sz_cos/cos(sun.fw*pi/180) else r_theta_fw:=1; lds:=lds0+lds1*(1-sz_cos); if p_Ed>0 then z99:=-ln(p_Ed/100) else z99:=0; i:=0; eu:=0; Kd^.avg:=0; for k:=1 to Channel_number do begin Kd^.y[k]:=(a^.y[k]+bb^.y[k])*ld*sz_1cos; if model_Kdd=0 then Kdd^.y[k]:=(a^.y[k]+bb^.y[k])*ldd*sz_1cos else Kdd^.y[k]:=ldda*a^.y[k]*sz_1cos + lddb*bb^.y[k]; Kds^.y[k]:=(a^.y[k]+bb^.y[k])*lds; if abs(Kd^.y[k])>nenner_min then z_Ed^.y[k]:=z99/Kd^.y[k] else z_Ed^.y[k]:=999; if (x^.y[k]>=PAR_min) and (x^.y[k]<=PAR_max) and (abs(Kd^.y[k])>nenner_min) then begin inc(i); eu:=eu + z_Ed^.y[k]; Kd^.avg:=Kd^.avg + Kd^.y[k]; end; end; if i>0 then begin eu:=eu/i; Kd^.avg:=Kd^.avg/i; end; Kd^.ParText :='Diffuse attenuation coefficient (1/m)'; Kdd^.ParText:='Attenuation coefficient of direct irradiance (1/m)'; Kds^.ParText:='Attenuation coefficient of diffuse irradiance (1/m)'; z_Ed^.ParText:='Depth (m) where ' + IntToStr(p_Ed) + ' % of downwelling irradiance remains.'; if (i>0) and (p_Ed=1) then z_Ed^.ParText:=z_Ed^.ParText + ' Euphotic depth: ' + FloatToStrF(eu, ffFixed, 5, 2) + ' m' else if i>0 then z_Ed^.ParText:=z_Ed^.ParText + ' Average over PAR: ' + FloatToStrF(eu, ffFixed, 5, 2) + ' m'; Kd^.sim :=TRUE; Kdd^.sim:=TRUE; Kds^.sim:=TRUE; end; procedure calc_KE_uW(sun:double); { KE_uW = attenuation of upwelling irradiance backscattered in the water, eq. (2.6) } var k : integer; mue_sun : double; begin mue_sun:=K2W/cos(arcsin(sin(sun*pi/180)/nW)); for k:=1 to Channel_number do KE_uW^.y[k]:=(a^.y[k]+bb^.y[k])*exp(K1W*ln(1+omega_b.y[k]))*(1+mue_sun); KE_uW^.ParText:='Diffuse attenuation of upwelling irradiance backscattered in water (1/m)'; KE_uW^.sim:=TRUE; end; procedure calc_KE_uB(sun:double); { KE_uB = attenuation of upwelling irradiance reflected at the bottom, eq. (2.7) } var k : integer; mue_sun : double; begin mue_sun:=K2B/cos(arcsin(sin(sun*pi/180)/nW)); for k:=1 to Channel_number do KE_uB^.y[k]:=(a^.y[k]+bb^.y[k])*exp(K1B*ln(1+omega_b^.y[k]))*(1+mue_sun); KE_uB^.ParText:='Diffuse attenuation of upwelling irradiance reflected from the bottom (1/m)'; KE_uB^.sim:=TRUE; end; procedure calc_kL_uW; { kL_uW = attenuation of upwelling radiance backscattered in the water, eq. (2.9) } var k : integer; mue_sun : double; mue_view : double; begin mue_sun :=K2Wrs/cos(arcsin(sin(sun.fw*pi/180)/nW)); mue_view:=1/cos(arcsin(sin(view.fw*pi/180)/nW)); for k:=1 to Channel_number do kL_uW^.y[k]:=(a^.y[k]+bb^.y[k])*mue_view*exp(K1Wrs*ln(1+omega_b^.y[k]))*(1+mue_sun); kL_uW^.ParText:='Attenuation of upwelling radiance backscattered in water (1/m)'; kL_uW^.sim:=TRUE; end; procedure calc_kL_uB; { kL_uB = attenuation of upwelling radiance reflected at the bottom, eq. (2.10) } var k : integer; mue_sun : double; mue_view : double; begin mue_sun :=K2Brs/cos(arcsin(sin(sun.fw*pi/180)/nW)); mue_view:=1/cos(arcsin(sin(view.fw*pi/180)/nW)); for k:=1 to Channel_number do kL_uB^.y[k]:=(a^.y[k]+bb^.y[k])*mue_view*exp(K1Brs*ln(1+omega_b^.y[k]))*(1+mue_sun); kL_uB^.ParText:='Attenuation of upwelling radiance reflected from the bottom (1/m)'; kL_uB^.sim:=TRUE; end; procedure calc_R_shallow; { Irradiance reflectance below surface for shallow water, eq. (2.16). } { Algorithm of Albert and Mobley (2003) } var k : integer; zz : double; begin flag_L:=FALSE; calc_R_bottom; calc_Kd; calc_KE_uW(sun.fw); calc_KE_uB(sun.fw); zz:=zB.fw; if (zB.fw-z.fw>0.001) then zz:=zz-z.fw else zz:=0.001; for k:=1 to Channel_number do R^.y[k]:=R^.y[k] * (1-A1*exp(-(Kd^.y[k] + KE_uW^.y[k])*zz)) + A2 * bottom^.y[k] * exp(-(Kd^.y[k] + KE_uB^.y[k])*zz); R^.ParText:='Irradiance reflectance'; R^.sim:=TRUE; end; procedure calc_R_rs_deep_below; { Radiance reflectance below surface for deep water } var k : integer; begin if Model_R_rsB<2 then begin // R_rs = f_rs * omega_b + R_rs,F for k:=1 to Channel_number do begin f_rs^.y[k] :=calc_f_rs(omega_b^.y[k], bbW^.y[k]/bb^.y[k], sun.fw, view.fw, Q.fw); r_rs^.y[k] :=f_rs^.y[k] * omega_b^.y[k] + RrsF^.y[k]; if f_R^.sim then Q_f^.y[k]:=calc_Q_f(f_rs^.y[k], f_R^.y[k]); end; f_rs^.ParText:='f_rs factor'; f_rs^.sim:=TRUE; end else begin // R_rs = R / Q if not flag_use_R then calc_R_deep; for k:=1 to Channel_number do r_rs^.y[k]:= R^.y[k]/Q.fw; end; r_rs^.ParText:='Radiance reflectance (sr^-1)'; r_rs^.sim:=TRUE; if f_R^.sim then Q_f^.ParText:='Q factor (sr)'; if f_R^.sim then Q_f^.sim:=TRUE; end; procedure calc_R_rs_shallow_below; { Radiance reflectance below surface for shallow water, eq. (2.19) } { Algorithm of Albert and Mobley (2003) } var k : integer; zz : double; begin flag_L:=TRUE; calc_R_bottom; calc_Kd; calc_kL_uW; calc_kL_uB; zz:=zB.fw; if abs(zB.fw-z.fw)>0.001 then zz:=zz-z.fw else zz:=0.001; for k:=1 to Channel_number do r_rs^.y[k]:=r_rs^.y[k] * (1-A1rs*exp(-(Kd^.y[k] + kL_uW^.y[k])*zz)) + A2rs * bottom^.y[k] * exp(-(Kd^.y[k] + kL_uB^.y[k])*zz); r_rs^.ParText:='Radiance reflectance (sr^-1)'; r_rs^.sim:=TRUE; end; procedure calc_r_rs_below; { Radiance reflectance below surface } begin calc_omega_b; calc_R_rs_deep_below; if flag_shallow then calc_R_rs_shallow_below; end; procedure use_R_rs_below; { Underwater term of r_rs(0+) for Model_R_rsA = 0} var k : integer; nenner : double; begin calc_R_rs_below; for k:=1 to Channel_number do begin nenner:=1-rho_Eu*Q.fw*r_rs^.y[k]; { Q nicht, wenn model_f=4 ? } if abs(nenner)<nenner_min then nenner:=nenner_min; r_rs^.y[k]:= r_rs^.y[k]/nenner; end; r_rs^.ParText:='Radiance reflectance (sr^-1)'; r_rs^.sim:=TRUE; end; procedure use_R; { Underwater term of R_rs(0+) for Model_R_rsA = 1} var k : integer; nenner : double; begin if not flag_use_R then calc_R; for k:=1 to Channel_number do begin nenner:=Q.fw * (1-rho_Eu*R^.y[k]); { Q nicht, wenn model_f=4 ? } if abs(nenner)<nenner_min then nenner:=nenner_min; r_rs^.y[k]:= R^.y[k]/nenner; end; r_rs^.ParText:='Radiance reflectance (sr^-1)'; r_rs^.sim:=TRUE; end; procedure use_both; { Underwater term of R_rs(0+) for Model_R_rsA = 2} var k : integer; nenner : double; begin if not flag_use_R then calc_R; calc_r_rs_below; for k:=1 to Channel_number do begin nenner:=1-rho_Eu*R^.y[k]; if abs(nenner)<nenner_min then nenner:=nenner_min; r_rs^.y[k]:= r_rs^.y[k]/nenner; end; r_rs^.ParText:='Radiance reflectance (sr^-1)'; r_rs^.sim:=TRUE; end; procedure calc_R_rs_above; { Radiance reflectance above surface } var k : integer; begin case Model_R_rsA of 0 : use_R_rs_below; 1 : use_R; 2 : use_both; end; calc_Rrs_surface; if (sun.fw<90) and(view.fw=-1) then r_theta_fw := cos(arcsin(sin(sun.fw*pi/180)/nW)) / cos(sun.fw*pi/180) else r_theta_fw:=1; for k:=1 to Channel_number do begin Rrs^.y[k] := (1-rho_Ed)*(1-rho_Lu)/sqr(nW)*r_theta_fw*r_rs^.y[k]; r_rs^.y[k]:= Rrs^.y[k] + Rrs_surf^.y[k]; end; Rrs^.ParText:='Remote sensing reflectance (sr^-1)'; r_rs^.ParText:='Radiance reflectance (sr^-1)'; Rrs^.sim:=TRUE; r_rs^.sim:=TRUE; end; procedure calc_R; { Irradiance reflectance } var merk_z : double; begin merk_z:=z.fw; if flag_above then z.fw:=0; calc_R_deep; if flag_shallow then calc_R_shallow; z.fw:=merk_z; f_R^.sim:=TRUE; end; procedure calc_r_rs; { Radiance reflectance } var k : integer; merk_z : double; begin merk_z:=z.fw; if flag_above then z.fw:=0; if flag_fluo then calc_Rrs_F(z.fw, zB.fw, fluo.fw, dummy.fw, test.fw); { Fluorescence } if flag_above then calc_R_rs_above else calc_R_rs_below; if flag_mult_Rrs then for k:=1 to Channel_number do r_rs^.y[k]:=Rrs_factor*r_rs^.y[k]; { mixed pixel, eq. (2.56)} if abs(1-f_nw.fw)>nenner_min then for k:=1 to Channel_number do r_rs^.y[k]:=(1-f_nw.fw)*r_rs^.y[k]+f_nw.fw*a_nw^.y[k]/pi; r_rs^.ParText:='Radiance reflectance (sr^-1)'; r_rs^.sim:=TRUE; z.fw:=merk_z; end; procedure calc_Lu_below; { Upwelling radiance below surface. } var k : integer; merk_z : double; merk_flag : boolean; begin merk_z:=z.fw; merk_flag:=flag_above; if flag_above then z.fw:=0; { flag_above:=FALSE; } if flag_fluo then calc_Rrs_F(z.fw, zB.fw, fluo.fw, dummy.fw, test.fw) { Fluorescence } else calc_Ed_GreggCarder; calc_r_rs_below; for k:=1 to Channel_number do Lu^.y[k]:= Ed^.y[k]*r_rs^.y[k]+Lf^.y[k]; Lu^.ParText:='Upwelling radiance (mW m^-2 nm^-1 sr^-1)'; Lu^.sim:=TRUE; z.fw:=merk_z; flag_above:=merk_flag; end; procedure calc_Lr; { Radiance reflected at the water surface. } var k : integer; begin if not flag_use_Ls then begin if flag_surf_fw then calc_Ls else calc_Ed_GreggCarder; end; { else measurement of Ls or Ed is taken } for k:=1 to Channel_number do begin if flag_surf_fw then Lr^.y[k]:=rho_L.fw * Ls^.y[k] else Lr^.y[k]:=rho_L.fw * Ed^.y[k]/pi; end; Lr^.ParText:='Radiance reflected at the water surface (mW m^-2 nm^-1 sr^-1)'; Lr^.sim:=TRUE; end; procedure calc_Lu_above; { Upwelling radiance above surface (eq. 2.61). } var k : integer; begin calc_Lr; for k:=1 to Channel_number do Lu^.y[k]:= (1-rho_Lu)/sqr(nW)*Lu^.y[k] + Lr^.y[k]; { Mixed pixel (eq. 2.73) } if abs(f_nw.fw)>nenner_min then for k:=1 to Channel_number do Lu^.y[k]:=(1-f_nw.fw)*Lu^.y[k] + f_nw.fw*Ed^.y[k]*a_nw^.y[k]/pi; Lu^.ParText:='Upwelling radiance (mW m^-2 nm^-1 sr^-1)'; Lu^.sim:=TRUE; end; procedure calc_Lu; { Upwelling radiance } begin calc_Lu_below; if flag_above then calc_Lu_above; end; { **************************************************************************** } procedure calc_test; begin if not flag_public then calc_DESIS; // in unit privates end; end.
unit u_codesect; {$mode objfpc}{$H+} interface uses Classes, SysUtils, u_global, u_consts, u_writers; type TCodeSection = class(TObject) public Lines: TStringList; Constants: TConstantManager; Outp: TMemoryStream; constructor Create(sl: TStringList; cnsts: TConstantManager); destructor Destroy; override; procedure ParseSection; procedure GenerateCode(Stream: TStream); end; implementation {** Code section **} constructor TCodeSection.Create(sl: TStringList; cnsts: TConstantManager); begin Outp := TMemoryStream.Create; Lines := sl; Constants := cnsts; inherited Create; end; destructor TCodeSection.Destroy; begin Outp.Free; inherited Destroy; end; type TComand = ( {** for stack **} bcPH, // [top] = [var] bcPK, // [var] = [top] bcPP, // pop bcSDP, // stkdrop bcSWP, // [top] <-> [top-1] {** jump's **} bcJP, // jump [top] bcJZ, // [top] == 0 ? jp [top-1] bcJN, // [top] <> 0 ? jp [top-1] bcJC, // jp [top] & push callback point as ip+1 bcJR, // jp to last callback point & rem last callback point {** for untyped's **} bcEQ, // [top] == [top-1] ? [top] = 1 : [top] = 0 bcBG, // [top] > [top-1] ? [top] = 1 : [top] = 0 bcBE, // [top] >= [top-1] ? [top] = 1 : [top] = 0 bcNOT, // [top] = ![top] bcAND, // [top] = [top] and [top-1] bcOR, // [top] = [top] or [top-1] bcXOR, // [top] = [top] xor [top-1] bcSHR, // [top] = [top] shr [top-1] bcSHL, // [top] = [top] shl [top-1] bcNEG, // [top] = -[top] bcINC, // [top]++ bcDEC, // [top]-- bcADD, // [top] = [top] + [top-1] bcSUB, // [top] = [top] - [top-1] bcMUL, // [top] = [top] * [top-1] bcDIV, // [top] = [top] / [top-1] bcMOD, // [top] = [top] % [top-1] bcIDIV, // [top] = [top] \ [top-1] bcMV, // [top]^ = [top-1]^ bcMVBP, // [top]^^ = [top-1]^ bcGVBP, // [top]^ = [top-1]^^ bcMVP, // [top]^ = [top-1] {** memory operation's **} bcMS, // memory map size = [top] bcNW, // [top] = @new bcMC, // copy [top] bcMD, // double [top] bcRM, // rem @[top] bcNA, // [top] = @new array[ [top] ] of pointer bcTF, // [top] = typeof( [top] ) bcTMC, // [top].type = type of class bcSF, // [top] = sizeof( [top] ) {** array's **} bcAL, // length( [top] as array ) bcSL, // setlength( [top] as array, {stack} ) bcPA, // push ([top] as array)[top-1] bcSA, // peek [top-2] -> ([top] as array)[top-1] {** memory grabber **} bcGPM, // add pointer to TMem to grabber task-list bcGC, // run grabber {** constant's **} bcPHC, // push copy of const bcPHCP, // push pointer to original const {** external call's **} bcPHEXMP, // push pointer to external method bcINV, // call external method bcINVBP, // call external method by pointer [top] {** for thread's **} bcPHN, // push null bcCTHR, // [top] = thread(method = [top], arg = [top+1]):id bcSTHR, // suspendthread(id = [top]) bcRTHR, // resumethread(id = [top]) bcTTHR, // terminatethread(id = [top]) bcTHSP, // set thread priority {** for try..catch..finally block's **} bcTR, // try @block_catch = [top], @block_end = [top+1] bcTRS, // success exit from try/catch block bcTRR, // raise exception, message = [top] {** for string's **} bcSTRD, // strdel bcCHORD, bcORDCH, {** [!] directly memory operations **} bcALLC, //alloc memory bcRALLC, //realloc memory bcDISP, //dispose memory bcGTB, //get byte bcSTB, //set byte bcCBP, //mem copy bcRWBP, //read word bcWWBP, //write word bcRIBP, //read int bcWIBP, //write int bcRFBP, //read float bcWFBP, //write float bcRSBP, //read string bcWSBP, //write string bcTHREXT,//stop code execution bcDBP//, //debug method call //bcCOPST ); procedure TCodeSection.ParseSection; var p1, p2: cardinal; s: string; begin //writeln('Executable code generation...'); p1 := 0; p2 := 0; while p2 < Lines.Count do begin s := Lines[p2]; if (s[length(s)] = ':') then begin Constants.AddConstCardinal(copy(s, 1, length(s) - 1), p1); Lines.Delete(p2); Dec(p2); Dec(p1); end; if (Tk(s, 1) = 'push') or (Tk(s, 1) = 'peek') or (Tk(s, 1) = 'pushc') or (Tk(s, 1) = 'pushm') or (Tk(s, 1) = 'pushcp') then Inc(p1, 5) else if Length(s) > 0 then Inc(p1); Inc(p2); end; while Lines.Count > 0 do begin s := Lines[0]; Lines.Delete(0); if Tk(s, 1) = 'push' then begin Outp.WriteByte(byte(bcPH)); St_WriteCardinal(Outp, StrToQWord(Tk(s, 2))); s := ''; end else if Tk(s, 1) = 'peek' then begin Outp.WriteByte(byte(bcPK)); St_WriteCardinal(Outp, StrToQWord(Tk(s, 2))); s := ''; end else if Tk(s, 1) = 'pushc' then begin Outp.WriteByte(byte(bcPHC)); St_WriteCardinal(Outp, Constants.GetAddr(Tk(s, 2))); s := ''; end else if Tk(s, 1) = 'pushm' then begin Outp.WriteByte(byte(bcPHEXMP)); St_WriteCardinal(Outp, Constants.GetAddr(Tk(s, 2))); s := ''; end else if Tk(s, 1) = 'pushcp' then begin Outp.WriteByte(byte(bcPHCP)); St_WriteCardinal(Outp, Constants.GetAddr(Tk(s, 2))); s := ''; end else if Tk(s, 1) = 'pop' then Outp.WriteByte(byte(bcPP)) else if Tk(s, 1) = 'stkdrop' then Outp.WriteByte(byte(bcSDP)) else if Tk(s, 1) = 'swp' then Outp.WriteByte(byte(bcSWP)) else if Tk(s, 1) = 'jp' then Outp.WriteByte(byte(bcJP)) else if Tk(s, 1) = 'jz' then Outp.WriteByte(byte(bcJZ)) else if Tk(s, 1) = 'jn' then Outp.WriteByte(byte(bcJN)) else if Tk(s, 1) = 'jc' then Outp.WriteByte(byte(bcJC)) else if Tk(s, 1) = 'jr' then Outp.WriteByte(byte(bcJR)) else if Tk(s, 1) = 'eq' then Outp.WriteByte(byte(bcEQ)) else if Tk(s, 1) = 'bg' then Outp.WriteByte(byte(bcBG)) else if Tk(s, 1) = 'be' then Outp.WriteByte(byte(bcBE)) else if Tk(s, 1) = 'not' then Outp.WriteByte(byte(bcNOT)) else if Tk(s, 1) = 'and' then Outp.WriteByte(byte(bcAND)) else if Tk(s, 1) = 'or' then Outp.WriteByte(byte(bcOR)) else if Tk(s, 1) = 'xor' then Outp.WriteByte(byte(bcXOR)) else if Tk(s, 1) = 'shr' then Outp.WriteByte(byte(bcSHR)) else if Tk(s, 1) = 'shl' then Outp.WriteByte(byte(bcSHL)) else if Tk(s, 1) = 'neg' then Outp.WriteByte(byte(bcNEG)) else if Tk(s, 1) = 'inc' then Outp.WriteByte(byte(bcINC)) else if Tk(s, 1) = 'dec' then Outp.WriteByte(byte(bcDEC)) else if Tk(s, 1) = 'add' then Outp.WriteByte(byte(bcADD)) else if Tk(s, 1) = 'sub' then Outp.WriteByte(byte(bcSUB)) else if Tk(s, 1) = 'mul' then Outp.WriteByte(byte(bcMUL)) else if Tk(s, 1) = 'div' then Outp.WriteByte(byte(bcDIV)) else if Tk(s, 1) = 'mod' then Outp.WriteByte(byte(bcMOD)) else if Tk(s, 1) = 'idiv' then Outp.WriteByte(byte(bcIDIV)) else if Tk(s, 1) = 'mov' then Outp.WriteByte(byte(bcMV)) else if Tk(s, 1) = 'movbp' then Outp.WriteByte(byte(bcMVBP)) else if Tk(s, 1) = 'gvbp' then Outp.WriteByte(byte(bcGVBP)) else if Tk(s, 1) = 'movp' then Outp.WriteByte(byte(bcMVP)) else if Tk(s, 1) = 'msz' then Outp.WriteByte(byte(bcMS)) else if Tk(s, 1) = 'new' then Outp.WriteByte(byte(bcNW)) else if Tk(s, 1) = 'copy' then Outp.WriteByte(byte(bcMC)) else if Tk(s, 1) = 'pcopy' then Outp.WriteByte(byte(bcMD)) else if Tk(s, 1) = 'rem' then Outp.WriteByte(byte(bcRM)) else if Tk(s, 1) = 'newa' then Outp.WriteByte(byte(bcNA)) else if Tk(s, 1) = 'typeof' then Outp.WriteByte(byte(bcTF)) else if Tk(s, 1) = 'typemarkclass' then Outp.WriteByte(byte(bcTMC)) else if Tk(s, 1) = 'sizeof' then Outp.WriteByte(byte(bcSF)) else if Tk(s, 1) = 'alen' then Outp.WriteByte(byte(bcAL)) else if Tk(s, 1) = 'salen' then Outp.WriteByte(byte(bcSL)) else if Tk(s, 1) = 'pushai' then Outp.WriteByte(byte(bcPA)) else if Tk(s, 1) = 'peekai' then Outp.WriteByte(byte(bcSA)) else if Tk(s, 1) = 'gpm' then Outp.WriteByte(byte(bcGPM)) else if Tk(s, 1) = 'gc' then Outp.WriteByte(byte(bcGC)) else if Tk(s, 1) = 'invoke' then Outp.WriteByte(byte(bcINV)) else if Tk(s, 1) = 'invokebp' then Outp.WriteByte(byte(bcINVBP)) else if Tk(s, 1) = 'pushn' then Outp.WriteByte(byte(bcPHN)) else if Tk(s, 1) = 'cthr' then Outp.WriteByte(byte(bcCTHR)) else if Tk(s, 1) = 'sthr' then Outp.WriteByte(byte(bcSTHR)) else if Tk(s, 1) = 'rthr' then Outp.WriteByte(byte(bcRTHR)) else if Tk(s, 1) = 'tthr' then Outp.WriteByte(byte(bcTTHR)) else if Tk(s, 1) = 'thsp' then Outp.WriteByte(byte(bcTHSP)) else if Tk(s, 1) = 'tr' then Outp.WriteByte(byte(bcTR)) else if Tk(s, 1) = 'trs' then Outp.WriteByte(byte(bcTRS)) else if Tk(s, 1) = 'trr' then Outp.WriteByte(byte(bcTRR)) else if Tk(s, 1) = 'strd' then Outp.WriteByte(byte(bcSTRD)) else if Tk(s, 1) = 'chord' then Outp.WriteByte(byte(bcCHORD)) else if Tk(s, 1) = 'ordch' then Outp.WriteByte(byte(bcORDCH)) else if Tk(s, 1) = 'allc' then Outp.WriteByte(byte(bcALLC)) else if Tk(s, 1) = 'rallc' then Outp.WriteByte(byte(bcRALLC)) else if Tk(s, 1) = 'disp' then Outp.WriteByte(byte(bcDISP)) else if Tk(s, 1) = 'gtb' then Outp.WriteByte(byte(bcGTB)) else if Tk(s, 1) = 'stb' then Outp.WriteByte(byte(bcSTB)) else if Tk(s, 1) = 'cbp' then Outp.WriteByte(byte(bcCBP)) else if Tk(s, 1) = 'rwbp' then Outp.WriteByte(byte(bcRWBP)) else if Tk(s, 1) = 'wwbp' then Outp.WriteByte(byte(bcWWBP)) else if Tk(s, 1) = 'ribp' then Outp.WriteByte(byte(bcRIBP)) else if Tk(s, 1) = 'wibp' then Outp.WriteByte(byte(bcWIBP)) else if Tk(s, 1) = 'rfbp' then Outp.WriteByte(byte(bcRFBP)) else if Tk(s, 1) = 'wfbp' then Outp.WriteByte(byte(bcWFBP)) else if Tk(s, 1) = 'rsbp' then Outp.WriteByte(byte(bcRSBP)) else if Tk(s, 1) = 'wsbp' then Outp.WriteByte(byte(bcWSBP)) else if Tk(s, 1) = 'threxit' then Outp.WriteByte(byte(bcTHREXT)) else if Tk(s, 1) = 'dbgbreakpoint' then Outp.WriteByte(byte(bcDBP)) else {if Tk(s, 1) = 'copst' then Outp.WriteByte(byte(bcCOPST)) else} if Length(s) > 0 then AsmError('Invalid token in line: "' + s + '"'); end; end; procedure TCodeSection.GenerateCode(Stream: TStream); begin Stream.WriteBuffer(Outp.Memory^, Outp.Size); end; end.
unit AuthorizationService; interface uses JunoApi4Delphi.Interfaces, RESTRequest4D, AuthorizationToken, REST.JSON, System.JSON; type TAuthorizationService = class(TInterfacedObject, iAuthorizationService) private FParent : iJunoApi4DelphiConig; FAuthenticationToken : TAuthorizationToken; procedure Refresh; public constructor Create(Parent : iJunoApi4DelphiConig); destructor Destroy; override; class function New(Parent : iJunoApi4DelphiConig) : iAuthorizationService; function Token : String; function AuthorizationHeader : String; end; const AUTHORIZATION_HEADER = 'Authorization'; BEARER = 'Bearer '; OAUTH_TOKEN_ENDPOINT = '/oauth/token'; implementation uses JunoApi4DelphiManager, REST.Types, System.SysUtils; { TAuthorizationService } function TAuthorizationService.AuthorizationHeader: String; begin end; constructor TAuthorizationService.Create(Parent : iJunoApi4DelphiConig); begin FParent := Parent; Refresh; end; destructor TAuthorizationService.Destroy; begin inherited; end; class function TAuthorizationService.New(Parent : iJunoApi4DelphiConig) : iAuthorizationService; begin Result := Self.Create(Parent); end; procedure TAuthorizationService.Refresh; var JSONObj : TJSONObject; begin JsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes( TRequest.New.BaseURL(FParent.AuthorizationEndpoint + OAUTH_TOKEN_ENDPOINT) .Accept('application/json') .BasicAuthentication(FParent.ClientId,FParent.ClientSecret) .AddParam('Content-Type','application/x-www-form-urlencoded',pkGETorPOST) .AddParam('grant_type','client_credentials',pkREQUESTBODY) .Post.Content), 0) as TJSONObject; FAuthenticationToken := TJson.JsonToObject<TAuthorizationToken>(JsonObj); end; function TAuthorizationService.Token: String; begin Result := 'Bearer ' + FAuthenticationToken.access_token; end; end.
namespace Sugar; interface {$IF COOPER} extension method java.lang.Object.«ToString»: java.lang.String; extension method java.lang.Object.«Equals»(aOther: Object): Boolean; extension method java.lang.Object.GetHashCode: Integer; {$ELSEIF TOFFEE} extension method Foundation.NSObject.ToString: Foundation.NSString; extension method Foundation.NSObject.Equals(Obj: Object): Boolean; extension method Foundation.NSObject.GetHashCode: Integer; {$ENDIF} implementation {$IF COOPER} extension method java.lang.Object.«ToString»: java.lang.String; begin result := «toString»(); end; extension method java.lang.Object.«Equals»(aOther: Object): Boolean; begin result := self.equals(aOther) end; extension method java.lang.Object.GetHashCode: Integer; begin result := hashCode; end; {$ELSEIF TOFFEE} extension method Foundation.NSObject.ToString: Foundation.NSString; begin result := description; end; extension method Foundation.NSObject.Equals(Obj: Object): Boolean; begin result := isEqual(Obj); end; extension method Foundation.NSObject.GetHashCode: Integer; begin result := hash; end; {$ENDIF} end.
// -------------------------------------------------------------------------- // Archivo del Proyecto Ventas // Página del proyecto: http://sourceforge.net/projects/ventas // -------------------------------------------------------------------------- // Este archivo puede ser distribuido y/o modificado bajo lo terminos de la // Licencia Pública General versión 2 como es publicada por la Free Software // Fundation, Inc. // -------------------------------------------------------------------------- unit ReportesXPagar; interface uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QButtons, QExtCtrls, IniFiles, rpcompobase, rpclxreport, QcurrEdit; type TfrmReportesXPagar = class(TForm) grpDeptos: TGroupBox; lblDesde: TLabel; lblHasta: TLabel; rdoTodo: TRadioButton; rdoRango: TRadioButton; grpFechas: TGroupBox; Label2: TLabel; Label11: TLabel; txtDiaIni: TEdit; Label30: TLabel; txtMesIni: TEdit; Label31: TLabel; txtAnioIni: TEdit; txtDiaFin: TEdit; Label1: TLabel; txtMesFin: TEdit; Label3: TLabel; txtAnioFin: TEdit; btnImprimir: TBitBtn; rptReportes: TCLXReport; btnCancelar: TBitBtn; pnlProveedor: TPanel; txtClienteIni: TEdit; txtClienteFin: TEdit; chkPreliminar: TCheckBox; rdoVencidos: TRadioButton; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure rdoTodoClick(Sender: TObject); procedure Numero (Sender: TObject; var Key: Char); procedure btnImprimirClick(Sender: TObject); procedure chkPreliminarClick(Sender: TObject); procedure Salta(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure txtAnioIniExit(Sender: TObject); procedure txtAnioFinExit(Sender: TObject); procedure txtDiaIniExit(Sender: TObject); private sFechaIni, sFechaFin : string; procedure RecuperaConfig; function VerificaDatos : boolean; function VerificaFechas(sFecha : string):boolean; function VerificaRangos : boolean; procedure ImprimePagosGenerales; procedure ImprimeVencidos; procedure Rellena(Sender: TObject); public end; var frmReportesXPagar: TfrmReportesXPagar; implementation uses dm; {$R *.xfm} procedure TfrmReportesXPagar.FormShow(Sender: TObject); begin rdoTodoClick(Sender); end; procedure TfrmReportesXPagar.RecuperaConfig; var iniArchivo : TIniFile; sIzq, sArriba, sValor : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); with iniArchivo do begin //Recupera la posición Y de la ventana sArriba := ReadString('RepXPagar', 'Posy', ''); //Recupera la posición X de la ventana sIzq := ReadString('RepXPagar', 'Posx', ''); if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin Left := StrToInt(sIzq); Top := StrToInt(sArriba); end; //Recupera la fecha inicial sValor := ReadString('RepXPagar', 'FechaIni', ''); if (Length(sValor) > 0) then begin txtDiaIni.Text := Copy(sValor,1,2); txtMesIni.Text := Copy(sValor,4,2); txtAnioIni.Text := Copy(sValor,7,4); end; //Recupera la fecha final sValor := ReadString('RepXPagar', 'FechaFin', ''); if (Length(sValor) > 0) then begin txtDiaFin.Text := Copy(sValor,1,2); txtMesFin.Text := Copy(sValor,4,2); txtAnioFin.Text := Copy(sValor,7,4); end; Free; end; end; procedure TfrmReportesXPagar.FormClose(Sender: TObject; var Action: TCloseAction); var iniArchivo : TIniFile; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); with iniArchivo do begin // Registra la posición y de la ventana WriteString('RepXPagar', 'Posy', IntToStr(Top)); // Registra la posición X de la ventana WriteString('RepXPagar', 'Posx', IntToStr(Left)); // Registra la fecha inicial WriteString('RepXPagar', 'FechaIni', txtDiaIni.Text + '/' + txtMesIni.Text + '/' + txtAnioIni.Text); // Registra la fecha final WriteString('RepXPagar', 'FechaFin', txtDiaFin.Text + '/' + txtMesFin.Text + '/' + txtAnioFin.Text); Free; end; end; procedure TfrmReportesXPagar.rdoTodoClick(Sender: TObject); begin if (rdoTodo.Checked) then begin rdoRango.Checked := False; rdoVencidos.Checked := False; end else if (rdoRango.Checked) then begin rdoTodo.Checked := False; rdoVencidos.Checked := False; end else begin rdoTodo.Checked := False; rdoRango.Checked := False; end; lblDesde.Enabled := rdoRango.Checked; lblHasta.Enabled := rdoRango.Checked; pnlProveedor.Enabled := rdoRango.Checked; grpFechas.Enabled := not rdoVencidos.Checked; end; procedure TfrmReportesXPagar.Numero(Sender: TObject; var Key: Char); begin if not (Key in ['0'..'9',#8]) then Key := #0; end; procedure TfrmReportesXPagar.chkPreliminarClick(Sender: TObject); begin rptReportes.Preview := chkPreliminar.Checked; end; procedure TfrmReportesXPagar.btnImprimirClick(Sender: TObject); begin if VerificaDatos then if (rdoVencidos.Checked) then ImprimeVencidos else ImprimePagosGenerales; end; function TfrmReportesXPagar.VerificaDatos : boolean; begin Result:= true; sFechaIni := txtMesIni.Text + '/' + txtDiaIni.Text + '/' + txtAnioIni.Text; sFechaFin := txtMesFin.Text + '/' + txtDiaFin.Text + '/' + txtAnioFin.Text; if(not VerificaFechas(txtDiaIni.Text + '/' + txtMesIni.Text + '/' + txtAnioIni.Text)) then begin Application.MessageBox('Introduce una fecha válida','Error',[smbOK],smsCritical); txtDiaIni.SetFocus; Result := false; end else if(not VerificaFechas(txtDiaFin.Text + '/' + txtMesFin.Text + '/' + txtAnioFin.Text)) then begin Application.MessageBox('Introduce una fecha válida','Error',[smbOK],smsCritical); txtDiaFin.SetFocus; Result := false; end else if not VerificaRangos then Result := false; end; function TfrmReportesXPagar.VerificaFechas(sFecha : string):boolean; var dteFecha : TDateTime; begin Result:=true; if(not TryStrToDate(sFecha,dteFecha)) then Result:=false; end; function TfrmReportesXPagar.VerificaRangos : boolean; begin Result:= true; if rdoRango.Checked then if (Length(txtClienteIni.Text)=0) or (Length(txtClienteFin.Text)=0) then begin Result := false; Application.MessageBox('Introduce un rango válido para los clientes','Error',[smbOK],smsCritical); end; end; procedure TfrmReportesXPagar.ImprimePagosGenerales; var iniArchivo : TIniFile; sArchivo : String; sDirReportes : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', ''); if not (Length(sDirReportes) > 0) then sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\'; sArchivo := iniArchivo.ReadString('Reportes', 'XPagarPagosGenerales', ''); if (Length(sArchivo) > 0) then begin rptReportes.FileName := sDirReportes + sArchivo; rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection; rptReportes.Report.Params.ParamByName('FECHAINI').AsString := sFechaIni; rptReportes.Report.Params.ParamByName('FECHAFIN').AsString := sFechaFin; if(rdoTodo.Checked) then begin rptReportes.Report.Params.ParamByName('PROVEEDORINI').AsString := ''; rptReportes.Report.Params.ParamByName('PROVEEDORFIN').AsString := 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ'; end else begin rptReportes.Report.Params.ParamByName('PROVEEDORINI').AsString := txtClienteIni.Text; rptReportes.Report.Params.ParamByName('PROVEEDORFIN').AsString := txtClienteFin.Text; end; rptReportes.Execute; end else Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical); end; procedure TfrmReportesXPagar.ImprimeVencidos; var iniArchivo : TIniFile; sArchivo : String; sDirReportes : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', ''); if not (Length(sDirReportes) > 0) then sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\'; sArchivo := iniArchivo.ReadString('Reportes', 'XPagarVencidos', ''); if (Length(sArchivo) > 0) then begin rptReportes.FileName := sDirReportes + sArchivo; rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection; rptReportes.Report.Params.ParamByName('FECHAACTUAL').AsString := FormatDateTime('mm/dd/yyyy',Date); rptReportes.Execute; end else Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical); end; procedure TfrmReportesXPagar.Salta(Sender: TObject; var Key: Word; Shift: TShiftState); begin {Inicio (36), Fin (35), Izquierda (37), derecha (39), arriba (38), abajo (40)} if(Key >= 30) and (Key <= 122) and (Key <> 35) and (Key <> 36) and not ((Key >= 37) and (Key <= 40)) then if( Length((Sender as TEdit).Text) = (Sender as TEdit).MaxLength) then SelectNext(Sender as TWidgetControl, true, true); end; procedure TfrmReportesXPagar.FormCreate(Sender: TObject); begin RecuperaConfig; end; procedure TfrmReportesXPagar.txtAnioIniExit(Sender: TObject); begin txtAnioIni.Text := Trim(txtAnioIni.Text); if(Length(txtAnioIni.Text) < 4) and (Length(txtAnioIni.Text) > 0) then txtAnioIni.Text := IntToStr(StrToInt(txtAnioIni.Text) + 2000); end; procedure TfrmReportesXPagar.txtAnioFinExit(Sender: TObject); begin txtAnioFin.Text := Trim(txtAnioFin.Text); if(Length(txtAnioFin.Text) < 4) and (Length(txtAnioFin.Text) > 0) then txtAnioFin.Text := IntToStr(StrToInt(txtAnioFin.Text) + 2000); end; procedure TfrmReportesXPagar.Rellena(Sender: TObject); var i : integer; begin for i := Length((Sender as TEdit).Text) to (Sender as TEdit).MaxLength - 1 do (Sender as TEdit).Text := '0' + (Sender as TEdit).Text; end; procedure TfrmReportesXPagar.txtDiaIniExit(Sender: TObject); begin Rellena(Sender) end; end.
unit EmulatorDevice; // Emulator device, implements IBaseRequestOnlyDevice (look into BaseDevice.pas) // There are no commands, it just generate random data. interface uses BaseDevice, SysUtils, ExtCtrls, Classes, Forms; type TEmulatorDevice = class (TInterfacedObject, IBaseRequestOnlyDevice) public Constructor Create(mainForm : TForm); function GetName() : string; function IsConnected() : boolean; procedure Connect(connectionCallback: IConnectionCallback); function GetInputLinesNumber() : integer; function ReadFromInputLine(lineNumber: integer; var output : TBytesArray) : boolean; function GetMaxInputLinesNumberPerRequest () : integer; function ReadFromInputLines(var lineNumbers : TLineIndexesArray; var output : TBytesArray) : boolean; function GetCommandsNumber() : integer; function GetCommandInfo(commandNumber : integer) : ICommandInfo; function GetMinimumValInInputLine(lineNumber : integer) : integer; function GetMaximumValInInputLine(lineNumber : integer) : integer; procedure Disconnect; procedure ShowAbout; private connected : boolean; connectionCallback : IConnectionCallback; timer : TTimer; connectionProgress : integer; connecting : boolean; procedure OnTimer(Sender: TObject); end; implementation { TEmulatorDevice } procedure TEmulatorDevice.Connect(connectionCallback: IConnectionCallback); begin connecting := true; self.connectionProgress := 0; self.connectionCallback := connectionCallback; self.connectionCallback.OnConnectionProgress(connectionProgress); self.connectionCallback.OnConnectionStatusMessage('connecting'); timer.Enabled := true; end; constructor TEmulatorDevice.Create(mainForm : TForm); begin connecting := false; connectionProgress := 0; timer := TTimer.Create(mainForm); timer.Interval := 500; timer.Enabled := false; timer.OnTimer := OnTimer; self.connected := false; end; procedure TEmulatorDevice.Disconnect; begin self.connecting := false; self.timer.Enabled := false; self.connected := false; end; function TEmulatorDevice.GetCommandInfo( commandNumber: integer): ICommandInfo; begin end; function TEmulatorDevice.GetCommandsNumber: integer; begin Result := 0; end; function TEmulatorDevice.GetInputLinesNumber: integer; begin Result := 5; end; function TEmulatorDevice.GetMaximumValInInputLine( lineNumber: integer): integer; begin Result := 62; end; function TEmulatorDevice.GetMaxInputLinesNumberPerRequest: integer; begin Result := 4; end; function TEmulatorDevice.GetMinimumValInInputLine( lineNumber: integer): integer; begin Result := 10; end; function TEmulatorDevice.GetName: string; begin Result := 'Emulator'; end; function TEmulatorDevice.IsConnected: boolean; begin Result := connected; end; procedure TEmulatorDevice.OnTimer(Sender: TObject); begin self.connectionProgress := self.connectionProgress + 10; if (connectionProgress >= 100) then begin self.connected := true; self.timer.Enabled := false; self.connectionCallback.OnConnected; end else self.connectionCallback.OnConnectionProgress(connectionProgress); end; function TEmulatorDevice.ReadFromInputLine(lineNumber: integer; var output: TBytesArray): boolean; begin Sleep(30); SetLength(output, 1); output[0] := Random(51) + 10; Result := true; end; function TEmulatorDevice.ReadFromInputLines(var lineNumbers: TLineIndexesArray; var output: TBytesArray): boolean; var i : integer; begin Sleep(50); SetLength(output, Length(lineNumbers)); for i := 0 to Length(lineNumbers) -1 do output[i] := Random(51) + 10; Result := true; end; procedure TEmulatorDevice.ShowAbout; begin end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA 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 3 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, see <http://www.gnu.org/licenses/>. } unit frmTableColumns; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, MemDS, DBAccess, Ora, cxGroupBox, cxRadioGroup, cxDBEdit, cxTextEdit, StdCtrls, cxControls, cxContainer, cxEdit, cxGraphics, cxPC, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxMemo, cxCheckBox, cxSpinEdit, cxImageComboBox, Menus, cxLookAndFeelPainters, cxRichEdit, cxButtons, ExtCtrls, OraScript, jpeg, GenelDM; type TTableColumnsFrm = class(TForm) QTableColumns: TOraQuery; QTableColumnsTABLE_NAME: TStringField; QTableColumnsCOLUMN_NAME: TStringField; QTableColumnsDATA_TYPE: TStringField; QTableColumnsDATA_TYPE_MOD: TStringField; QTableColumnsDATA_TYPE_OWNER: TStringField; QTableColumnsDATA_LENGTH: TFloatField; QTableColumnsDATA_PRECISION: TFloatField; QTableColumnsDATA_SCALE: TFloatField; QTableColumnsNULLABLE: TStringField; QTableColumnsCOLUMN_ID: TFloatField; QTableColumnsDEFAULT_LENGTH: TFloatField; QTableColumnsDATA_DEFAULT: TMemoField; QTableColumnsNUM_DISTINCT: TFloatField; QTableColumnsLOW_VALUE: TVarBytesField; QTableColumnsHIGH_VALUE: TVarBytesField; QTableColumnsDENSITY: TFloatField; QTableColumnsNUM_NULLS: TFloatField; QTableColumnsNUM_BUCKETS: TFloatField; QTableColumnsLAST_ANALYZED: TDateTimeField; QTableColumnsSAMPLE_SIZE: TFloatField; QTableColumnsCHARACTER_SET_NAME: TStringField; QTableColumnsCHAR_COL_DECL_LENGTH: TFloatField; QTableColumnsGLOBAL_STATS: TStringField; QTableColumnsUSER_STATS: TStringField; QTableColumnsAVG_COL_LEN: TFloatField; QTableColumnsCHAR_LENGTH: TFloatField; QTableColumnsCHAR_USED: TStringField; QTableColumnsV80_FMT_IMAGE: TStringField; QTableColumnsDATA_UPGRADED: TStringField; QTableColumnsCOMMENTS: TStringField; dsTableColumns: TDataSource; qUserDataType: TOraQuery; dsUserDataType: TDataSource; qUserDataTypeTYPE_NAME: TStringField; qForeignTable: TOraQuery; dsForeignTable: TDataSource; dsForeignColumn: TDataSource; qForeignColumn: TOraQuery; qForeignTableTABLE_NAME: TStringField; qForeignColumnCOLUMN_NAME: TStringField; dsExceptionTable: TDataSource; qExceptionTable: TOraQuery; StringField3: TStringField; pc: TcxPageControl; tsDataType: TcxTabSheet; tsCheck: TcxTabSheet; Label10: TLabel; edtCheckName: TcxTextEdit; cxGroupBox3: TcxGroupBox; edtCheckCondition: TcxMemo; tsForeign: TcxTabSheet; tsDDL: TcxTabSheet; edtColumnDDL: TcxRichEdit; cxGroupBox1: TcxGroupBox; btnCancel: TcxButton; btnExecute: TcxButton; cxGroupBox5: TcxGroupBox; Label4: TLabel; Label5: TLabel; Label6: TLabel; lblDataType: TLabel; Label8: TLabel; Label9: TLabel; Label1: TLabel; Label2: TLabel; edtDefaultValue: TcxTextEdit; memComment: TcxMemo; edtOracleDataSize: TcxSpinEdit; edtOracleDataScale: TcxSpinEdit; icUserDataType: TcxLookupComboBox; cboxNullable: TcxCheckBox; rgroupSizeType: TcxRadioGroup; edtColumnName: TcxTextEdit; edtTableName: TcxTextEdit; cxGroupBox2: TcxGroupBox; Label3: TLabel; rgroupColumnType: TcxRadioGroup; lcDataTypeSchema: TcxLookupComboBox; icOracleDataType: TcxImageComboBox; cxGroupBox6: TcxGroupBox; Label12: TLabel; Label16: TLabel; Label17: TLabel; Label13: TLabel; Label14: TLabel; Label15: TLabel; Label19: TLabel; edtForeignName: TcxTextEdit; cboxStatus: TcxImageComboBox; cboxValidation: TcxImageComboBox; cxGroupBox4: TcxGroupBox; lcExceptionOwner: TcxLookupComboBox; lcExceptionTable: TcxLookupComboBox; lcForeignTable: TcxLookupComboBox; lcForeignSchema: TcxLookupComboBox; lcForeinColumn: TcxLookupComboBox; cboxDeleteRule: TcxImageComboBox; cboxDeferrable: TcxImageComboBox; chkDeferrable: TcxCheckBox; procedure rgroupColumnTypePropertiesChange(Sender: TObject); procedure icOracleDataTypePropertiesEditValueChanged(Sender: TObject); procedure lcDataTypeSchemaPropertiesEditValueChanged(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure lcForeignSchemaPropertiesEditValueChanged(Sender: TObject); procedure lcForeignTablePropertiesEditValueChanged(Sender: TObject); procedure tsDDLShow(Sender: TObject); procedure chkDeferrablePropertiesEditValueChanged(Sender: TObject); procedure lcExceptionOwnerPropertiesEditValueChanged(Sender: TObject); procedure btnExecuteClick(Sender: TObject); private { Private declarations } FOraSession: TOraSession; FTableName, FOwnerName, FColumnName: string; procedure SetDataType(userType: boolean); procedure GetForeignKeyDetail; procedure GetTableColumnDetail; function ConvertDataType: string; function GenerateDDL: string; public { Public declarations } procedure Init(TableName, OwnerName, ColumnName: string; OraSession: TOraSession); end; var TableColumnsFrm: TTableColumnsFrm; implementation {$R *.dfm} uses frmSchemaBrowser, OraScripts, Util, OraTable, OraStorage, DBQuery, VisualOptions; procedure TTableColumnsFrm.Init(TableName, OwnerName, ColumnName: string; OraSession: TOraSession); begin TableColumnsFrm := TTableColumnsFrm.Create(Application); Self := TableColumnsFrm; DMGenel.ChangeLanguage(self); ChangeVisualGUI(self); FTableName := TableName; FOwnerName := OwnerName; FColumnName := ColumnName; FOraSession := OraSession; edtTableName.Text := FTableName; edtColumnName.Text := FColumnName; pc.ActivePage := tsDataType; QTableColumns.Session := FOraSession; qUserDataType.Session := FOraSession; dmGenel.ReLoad(FOraSession); SetDataType(false); if ColumnName <> '' then begin tsCheck.TabVisible := false; tsForeign.TabVisible := false; end else begin qForeignTable.Session := FOraSession; qForeignColumn.Session := FOraSession; qExceptionTable.Session := FOraSession; GetForeignKeyDetail; end; GetTableColumnDetail; ShowModal; Free; end; procedure TTableColumnsFrm.btnCancelClick(Sender: TObject); begin close; end; procedure TTableColumnsFrm.GetTableColumnDetail; begin if FColumnName = '' then Caption := 'Add Column to '+FOwnerName+'.'+FTableName else Caption := 'Modify Column on '+FColumnName; if FColumnName = '' then exit; QTableColumns.SQL.Text := GetTableColumns(FTableName, FOwnerName, FColumnName); QTableColumns.Open; if QTableColumns.FieldByName('DATA_TYPE_OWNER').AsString <> '' then begin rgroupColumnType.ItemIndex := 1; lcDataTypeSchema.EditValue := QTableColumns.FieldByName('DATA_TYPE_OWNER').AsString; icUserDataType.EditValue := QTableColumns.FieldByName('DATA_TYPE').AsString; end else begin rgroupColumnType.ItemIndex := 0; icOracleDataType.EditValue := QTableColumns.FieldByName('DATA_TYPE').AsString; lcDataTypeSchema.EditValue := ''; end; if copy(GetColumnType(QTableColumns.FieldByName('DATA_TYPE').AsString),1,3) = '100' then begin edtOracleDataSize.Value := QTableColumns.FieldByName('DATA_LENGTH').AsFloat; end; if copy(GetColumnType(QTableColumns.FieldByName('DATA_TYPE').AsString),1,3) = '011' then begin edtOracleDataSize.Value := QTableColumns.FieldByName('DATA_PRECISION').AsFloat; edtOracleDataScale.Value := QTableColumns.FieldByName('DATA_SCALE').AsFloat; end; cboxNullable.Checked := QTableColumns.FieldByName('NULLABLE').AsString = 'Y'; edtDefaultValue.Text := QTableColumns.FieldByName('DATA_DEFAULT').AsString; memComment.Text := QTableColumns.FieldByName('comments').AsString; end; procedure TTableColumnsFrm.rgroupColumnTypePropertiesChange( Sender: TObject); begin SetDataType(rgroupColumnType.ItemIndex = 1); end; procedure TTableColumnsFrm.SetDataType(userType: boolean); begin lcDataTypeSchema.Enabled := userType; icUserDataType.Enabled := userType; icOracleDataType.Enabled := not userType; edtOracleDataSize.Enabled := not userType; edtOracleDataScale.Enabled := not userType; if userType then begin rgroupColumnType.ItemIndex := 1; end else begin rgroupColumnType.ItemIndex := 0; lcDataTypeSchema.EditValue := ''; end; icOracleDataTypePropertiesEditValueChanged(self); end; procedure TTableColumnsFrm.icOracleDataTypePropertiesEditValueChanged( Sender: TObject); begin if rgroupColumnType.ItemIndex = 1 then exit; edtOracleDataSize.Enabled := false; edtOracleDataSize.Value := 0; edtOracleDataScale.Enabled := false; edtOracleDataScale.Value := 0; if icOracleDataType.EditValue = Null then exit; if copy(GetColumnType(icOracleDataType.EditValue),1,3) = '100' then begin edtOracleDataSize.Enabled := true; end; if copy(GetColumnType(icOracleDataType.EditValue),1,3) = '011' then begin edtOracleDataSize.Enabled := true; edtOracleDataScale.Enabled := true; end; rgroupSizeType.Visible := copy(GetColumnType(icOracleDataType.EditValue),4,1) = '1'; end; procedure TTableColumnsFrm.chkDeferrablePropertiesEditValueChanged( Sender: TObject); begin cboxDeferrable.Enabled := chkDeferrable.Checked; end; procedure TTableColumnsFrm.lcDataTypeSchemaPropertiesEditValueChanged( Sender: TObject); begin qUserDataType.close; qUserDataType.SQL.Text := GetUserTypes(lcDataTypeSchema.Text); qUserDataType.Open; end; procedure TTableColumnsFrm.GetForeignKeyDetail; begin { qForeignSchema.close; qForeignSchema.SQL.Text := GetUsers; qForeignSchema.Open; qExceptionOwner.close; qExceptionOwner.SQL.Text := GetUsers; qExceptionOwner.Open;} end; procedure TTableColumnsFrm.lcForeignSchemaPropertiesEditValueChanged( Sender: TObject); begin qForeignTable.close; qForeignColumn.close; if lcForeignSchema.Text = '' then exit; qForeignTable.SQL.Text := GetTables(lcForeignSchema.Text); qForeignTable.Open; end; procedure TTableColumnsFrm.lcForeignTablePropertiesEditValueChanged( Sender: TObject); begin qForeignColumn.close; if lcForeignTable.Text = '' then exit; qForeignColumn.SQL.Text := GetTableColumns(lcForeignTable.Text, lcForeignSchema.Text, ''); qForeignColumn.Open; end; procedure TTableColumnsFrm.lcExceptionOwnerPropertiesEditValueChanged( Sender: TObject); begin qExceptionTable.Close; if lcExceptionOwner.Text = '' then exit; qExceptionTable.close; qExceptionTable.SQL.Text := GetTables(lcExceptionOwner.Text); qExceptionTable.Open; end; function TTableColumnsFrm.ConvertDataType: string; begin result := icOracleDataType.Text; if copy(GetColumnType(icOracleDataType.EditValue),1,3) = '100' then begin result := result + '('+edtOracleDataSize.Text; if copy(GetColumnType(icOracleDataType.EditValue),4,1) = '1' then begin if rgroupSizeType.ItemIndex = 0 then result := result + ' BYTE' else result := result + ' CHAR'; end; result := result + ')'; end; if copy(GetColumnType(icOracleDataType.EditValue),1,3) = '011' then begin result := result + '('+edtOracleDataSize.Text+','+edtOracleDataScale.Text+')'; end; end; procedure TTableColumnsFrm.tsDDLShow(Sender: TObject); begin edtColumnDDL.Text := GenerateDDL; end; function TTableColumnsFrm.GenerateDDL: string; var ddl, alterMode: string; begin edtColumnDDL.Text := ''; if edtcolumnName.Text = '' then begin MessageDlg('Column name must be specified', mtWarning, [mbOk], 0); exit; end; if (icOracleDataType.Text = '') and (rgroupColumnType.ItemIndex = 0) then begin MessageDlg('Column type must be specified', mtWarning, [mbOk], 0); exit; end; if (icUserDataType.Text = '') and (rgroupColumnType.ItemIndex = 1) then begin MessageDlg('Column user type must be specified', mtWarning, [mbOk], 0); exit; end; if (edtForeignName.Text <> '') and (lcForeignTable.Text = '') then begin MessageDlg('Foreign key table must be specified', mtWarning, [mbOk], 0); exit; end; if (edtForeignName.Text <> '') and (lcForeinColumn.Text = '') then begin MessageDlg('Foreign key column must be specified', mtWarning, [mbOk], 0); exit; end; if (lcForeignTable.Text <> '') and (edtForeignName.Text = '') then begin MessageDlg('Foreign key name must be specified', mtWarning, [mbOk], 0); exit; end; if (edtCheckCondition.Text<> '') and (edtCheckName.Text = '') then begin MessageDlg('Check Constraint name must be specified', mtWarning, [mbOk], 0); exit; end; ddl := 'ALTER TABLE '+FOwnerName+'.'+FTableName+ln; if FColumnName = '' then alterMode := 'ADD' else alterMode := 'MODIFY'; if rgroupColumnType.ItemIndex = 0 then ddl := ddl + alterMode +' ('+edtColumnName.Text +' '+ ConvertDataType else ddl := ddl +'ADD ('+edtColumnName.Text +' '+ lcDataTypeSchema.Text+'.'+icUserDataType.Text; if edtDefaultValue.Text <> '' then ddl := ddl + ' DEFAULT '+ edtDefaultValue.Text; if edtCheckCondition.Text <> '' then ddl := ddl + ' CONSTRAINT '+edtCheckName.Text+ ' CHECK ('+edtCheckCondition.Text+')'; ddl := ddl +');'+ln+ln; if edtForeignName.Text <> '' then begin ddl := ddl +'ALTER TABLE '+FOwnerName+'.'+FTableName+ln +'ADD CONSTRAINT '+edtForeignName.Text+ln +'FOREIGN KEY'+ln +' ('+edtColumnName.Text+')'+ln +'REFERENCES'+ln +' '+lcForeignSchema.Text+'.'+lcForeignTable.Text+ln +' ('+lcForeinColumn.Text+')'+ln; if cboxStatus.Text = 'Disable' then ddl := ddl + 'DISABLE'+ln; if cboxValidation.Text = 'Validate' then ddl := ddl + 'VALIDATE'+ln else ddl := ddl + 'NOVALIDATE'+ln; if chkDeferrable.Checked then begin ddl := ddl + 'DEFERRABLE'+ln; if cboxDeferrable.Text = 'Initially Immediate' then ddl := ddl + 'INITIALLY IMMEDIATE'+ln else ddl := ddl + 'INITIALLY DEFERRED'+ln; end; if lcExceptionTable.Text <> '' then ddl := ddl + 'EXCEPTIONS INTO '+lcExceptionOwner.Text+'.'+lcExceptionTable.Text+ln; ddl := ddl + ';'; end; ddl := ddl +ln; if memComment.Text <> '' then ddl := ddl +'COMMENT ON COLUMN'+ln +FOwnerName+'.'+FTableName+'.'+edtColumnName.Text +' IS '+ln +Str(memComment.Text)+';'+ln; result := ddl; end; procedure TTableColumnsFrm.btnExecuteClick(Sender: TObject); begin if ExecSQL(GenerateDDL,'Column Created', FOraSession) then close; end; end.
(* * iocp c/s 服务基本类型常量等 *) unit iocp_base; // // 全部 record 不要用 packed 类型,读写速度更快。 // interface {$I in_iocp.inc} uses {$IFDEF DELPHI_XE7UP} Winapi.Windows, System.Classes, {$ELSE} Windows, Classes, {$ENDIF} iocp_Winsock2, iocp_wsExt, iocp_zlib; type // 收发内存块的用途 TIODataType = ( ioAccept, // 连接 ioReceive, // 接收 ioSend, // 发送 {$IFDEF TRANSMIT_FILE} ioTransmit, // TransmitFile 发送 {$ENDIF} ioPush, // 推送 ioDelete, // 被在线删除 ioTimeOut, // 超时 ioRefuse // 拒绝服务 ); // TLinkRec.data 存放的数据类型 TObjectType = ( otEnvData, // 客户端工作环境空间 otTaskInf, // 发送数据描述信息 otIOData, // IO 结构数据 // ============================================= otIOCPSocket, // TIOCPSocket 对象 otHttpSocket, // THttpSocket 对象 otStreamSocket, // TStreamSocket 对象 otWebSocket, // TWebSocket 对象(保留) otIOCPBroker // 代理对象 ); // 客户端传输协议 TClientComProtocol = TObjectType; // 双向链表 结构 PLinkRec = ^TLinkRec; TLinkRec = record {$IFDEF DEBUG_MODE} No: Integer; // 节点编号 {$ENDIF} Data: Pointer; // 存放任何类型数据 Prev, Next: PLinkRec; // 前后一节点 Auto: Boolean; // 是否由 SetLength 自动生成 InUsed: Boolean; // 是否占用 end; // 单 IO 数据结构(见:_WSABUF) PPerIOData = ^TPerIOData; TPerIOData = record Overlapped: TOverlapped; // 必须放在第一位置 Data: TWsaBuf; // 缓存大小、地址 IOType: TIODataType; // 用途分类 Owner: TObject; // 宿主:TBaseSocket Node: PLinkRec; // 保存对应的 PLinkRec,方便回收 end; // 操作类型 // v2.0 取消协议 TServiceType,根据操作类型确定协议, // 扩展操作类型时要注意范围,见: // TBusiWorker.Execute、TRecvThread.HandleInMainThread TActionType = ( // stEcho:响应服务 atUnknown, //0 未知 // stCertify:认证服务 atUserLogin, // 登录 atUserLogout, // 断开、登出 atUserRegister, // 注册用户 atUserModify, // 修改密码 atUserDelete, // 删除用户 atUserQuery, // 查询在线客户端 atUserState, // 查询用户状态 // stMessage:文本消息服务 atTextSend, // 文本消息 ++ atTextPush, // 发消息给其他客户端 atTextBroadcast, // 广播 atTextGetMsg, // 取离线消息 atTextFileList, // 取离线消息文件列表 // stFile:文件服务 atFileList, // 列出目录、文件 atFileSetDir, // 设置当前目录 atFileRename, // 重命名文件 atFileRenameDir, // 重命名目录 atFileDelete, // 删除文件 atFileDeleteDir, // 删除目录 atFileMakeDir, // 新建目录 atFileDownload, // 下载文件 atFileUpload, // 上传文件 atFileDownChunk, // 下载一段文件(断点下载) atFileUpChunk, // 上传一段文件(断点上传) atFileUpShare, // 上传到临时路径,共享 atFileDownShare, // 下载临时路径的共享文件 // stDatabase:数据库服务 atDBGetConns, // 查询数据库类型 atDBConnect, // 数据库连接 atDBExecSQL, // 执行 SQL atDBExecQuery, // 数据库查询 atDBExecStoredProc, // 执行存储过程 atDBApplyUpdates, // Delta 更新数据库 // stCustom:自定义 atCallFunction, // 调用远程函数 atCustomAction, // 自定义(TCustomClient 操作) // 服务端内部操作 atAfterReceive, // 接收附件完毕 atAfterSend, // 发送附件完毕 atDisconnect, // 非登出的断开 atServerEvent // 服务器事件 ); // 操作结果/状态 TActionResult = ( // ===== 客户端操作结果 ===== arUnknown, // 未定 arOK, // 成功/允许 arFail, // 失败 arCancel, // 取消/拒绝 // 对象状态 arEmpty, // 内容为空 arExists, // 已存在 arMissing, // 不存在/丢失 arOccupied, // 被占用 arOutDate, // 文件/凭证过期 // 数据传输状态 arAccept, // 接收 arRefuse, // 拒绝服务 arRequest, // 请求 // 用户状态/操作 arLogout, // 登出 arOnline, // 在线 arOffline, // 离线(未登录) arDeleted, // 被删除,断开 arTimeOut, // 超时关闭 // ===== 异常操作结果 ===== arErrAnalyse, // 变量解析异常 arErrBusy, // 系统繁忙 arErrHash, // 服务端校验码错误 arErrHashEx, // 客户端校验码错误 arErrInit, // 初始化异常 arErrNoAnswer, // 无应答 arErrPush, // 推送异常 arErrUser, // 非法用户 arErrWork // 执行任务异常 ); // C/S 消息部分 TMessagePart = ( mdtHead, // 消息头 mdtEntity, // 实体内容 mdtAttachment // 附近内容 ); // C/S 数据校验类型 TDataCheckType = ( ctNone, // 无校验 ctMD5, // MD 5 ctMurmurHash // MurmurHash ); // C/S 消息包状态 TMessagePackState = ( msDefault, // 用户提交 msAutoPost, // 自动提交 msCancel // 取消操作 ); {$IFDEF WIN_64} IOCP_LARGE_INTEGER = Int64; // 64 bits {$ELSE} IOCP_LARGE_INTEGER = Integer; // 32 bits {$ENDIF} {$IFDEF DELPHI_7} TServerSocket = Int64; TMessageOwner = Int64; TMurmurHash = Int64; {$ELSE} TServerSocket = UInt64; TMessageOwner = UInt64; // 兼容 64+32 位系统 TMurmurHash = UInt64; {$ENDIF} PMurmurHash = ^TMurmurHash; TFileSize = Int64; // 支持大文件 TIOCPMsgId = Int64; // 64 位 TActionTarget = Cardinal; // 操作目的对象 // 首消息包的协议头 // 修改时必须同时修改 THeaderPack 的对应字段 PMsgHead = ^TMsgHead; TMsgHead = record Owner: TMessageOwner; // 所有者(组件) SessionId: Cardinal; // 认证/登录 ID MsgId: TIOCPMsgId; // 消息 ID DataSize: Cardinal; // 变量型消息的原始长度(主体) AttachSize: TFileSize; // 文件、流长度(附件) Offset: TFileSize; // 断点续传的位移 OffsetEnd: TFileSize; // 断点续传的结束位移 CheckType: TDataCheckType; // 校验类型 VarCount: Cardinal; // 变量型消息的变量/元素个数 ZipLevel: TZipLevel; // 主体的压缩率 Target: TActionTarget; // 目的对象类型 Action: TActionType; // 操作分类 ActResult: TActionResult; // 操作结果 end; // ============= StreamSocket 相关 ============= // InIOCP 数据流接收状态 TIOCPStreamState = ( issUnknown, // 纯数据流(如设备状态) issInitial, // InIOCP 类型流 issBegin, // InIOCP 流开始接收 issSubsequent, // InIOCP 流后续数据 issComplete // InIOCP 流接收完成 ); // InIOCP 数据流类型 TIOCPDataType = ( idtBuffer, idtString, idtMemStream, idtFileStream ); // InIOCP 流协议,存放:InIOCP_STREAM_SOCKET PStreamProtocol = ^TStreamProtocol; TStreamProtocol = array[0..19] of AnsiChar; PIOCPStreamSize = ^TIOCPStreamSize; TIOCPStreamSize = Int64; // =============== WebSocket 相关 =============== // 操作类型 TWSOpCode = ( ocContinuation = 0, ocText = 1, ocBiary = 2, ocClose = 8, ocPing = 9, ocPong = 10 ); // 消息类型 TWSMsgType = ( mtDefault, // 标准 WebSocket 协议消息 mtJSON, // 扩展的 JSON 消息 mtAttachment // 扩展的附件流 ); // 广播的目的类型 TBroadcastType = ( btUnknown, // 不广播 btAllClient, // 给全部客户端 btAdminOnly // 只给管理员 ); PByteAry = ^TByteAry; TByteAry = array of Byte; // 掩码 PWSMask = ^TWSMask; TWSMask = array[0..3] of Byte; // WebSocket 帧的结构头 PWebSocketFrame = ^TWebSocketFrame; TWebSocketFrame = array[0..9] of AnsiChar; // 2+8 // 存放标志字段的空间 PInIOCPJSONField = ^TInIOCPJSONField; TInIOCPJSONField = array[0..18] of AnsiChar; // ======================================== // 双字节、三字节类型 PDblChars = ^TDblChars; TDblChars = array[0..1] of AnsiChar; PThrChars = ^TThrChars; TThrChars = array[0..2] of AnsiChar; // =============== 代理服务 =============== // 代理模式(位置) TProxyType = ( ptDefault, ptOuter ); // 传输协议 TTransportProtocol = ( tpNone, tpHTTP ); TSocketBrokerType = ( stDefault, stOuterSocket, stWebSocket ); // 内部连接标志(对应InIOCP_INNER_SOCKET) PInIOCPInnerSocket = ^TInIOCPInnerSocket; TInIOCPInnerSocket = array[0..18] of AnsiChar; // =============== 元素/变量/字段/参数 =============== // 数据流转换的描述信息 // 元素/变量/字段/参数类型(不要调位置) TElementType = ( // *11 etNull, // 空值 etBoolean, // 逻辑 etCardinal, // 无符号整型 etFloat, // 浮点型 etInteger, // 整型 etInt64, // 64 位整数 // 以下转 JSON 时当字符串 etDateTime, // 时间日期 8 字节 // 以下为可变长度,顺序不能变 etBuffer, // 内存引用 etString, // 字符串 etRecord, // 记录引用 etStream, // 流引用 etVariant // 变型(用 etString 方式存储) ); // 在列表存储时的信息 PListVariable = ^TListVariable; TListVariable = record EleType: TElementType; NameSize: SmallInt; case Integer of 0: (BooleanValue: Boolean); 1: (IntegerValue: Integer); 2: (CardinalValue: Cardinal); 3: (Int64Value: Int64); 4: (FloatValue: Double); 5: (DateTimeValue: TDateTime); 6: (DataSize: Integer; Data: Pointer); // 用于文本、流等变长类型数据 end; // 在传输流中的描述信息 PStreamVariable = ^TStreamVariable; TStreamVariable = record EleType: TElementType; NameSize: SmallInt; // 紧接着:Name + DataSize + DataContent end; // =============== 任务发送 信息 =============== // 待发送数据信息 // 前四字段不能改位置,与 TTransmitFileBuffers 的一致 PTransmitTask = ^TTransmitTask; TTransmitTask = record Head: Pointer; // 先发送的数据 HeadLength: DWORD; Tail: Pointer; // 最后发送的数据 TailLength: DWORD; // 数据源(释放用) Handle: THandle; // 文件句柄 RefStr: AnsiString; // 字符串 Stream: TStream; // 流对象,对应 Head Stream2: TStream; // 流对象 2,对应 Tail // 长度,位移 Size: TFileSize; // 大小 Offset: TFileSize; // 开始位置 OffsetEnd: TFileSize; // 结束位置 ObjType: TClass; // 对象类 AutoFree: Boolean; // 自动释放流 end; // =============== 客户端/业务环境 信息 =============== // 角色/权限 TClientRole = ( crUnknown = 0, // 未登录用户 crClient = 1, // 普通 crAdmin = 8, // 管理员 crSuper = 9 // 超级管理员 ); // 用户基本信息 // 双字节环境 String[n] 也是单字节 TNameString = string[30]; PClientInfo = ^TClientInfo; TClientInfo = record Socket: TServerSocket; // TIOCPSocket,兼容 64+32 位系统 Group: TNameString; // 分组 Name: TNameString; // 名称 LoginTime: TDateTime; // 登录时间 LogoutTime: TDateTime; // 登出时间 PeerIPPort: TNameString; // IP:Port Role: TClientRole; // 角色、权限 Tag: TNameString; // 其他信息 end; // 用户工作环境 PEnvironmentVar = ^TEnvironmentVar; TEnvironmentVar = record BaseInf: TClientInfo; // 基本信息 WorkDir: string[128]; // 工作路径 IniDirLen: Integer; // 初始路径长度(防超边用) DBConnection: Integer; // 数模连接编号 ReuseSession: Boolean; // 重用认证(不释放) end; // 防攻击记录 PAttackInfo = ^TAttackInfo; TAttackInfo = record PeerIP: String[20]; // 客户端 IP TickCount: Int64; // 更新的 UTC/_FILETIME 时间 Count: Integer; // 接入次数 end; // ==================== 凭证/安全 ==================== PCertifyNumber = ^TCertifyNumber; TCertifyNumber = record case Integer of 0: (Session: Cardinal); 1: (DayCount: SmallInt; Timeout: SmallInt); end; // ==================== 线程、流量统计 ==================== // 全部 工作线程 的概况结构 PWorkThreadSummary = ^TWorkThreadSummary; TWorkThreadSummary = record ThreadCount: LongInt; // 总数 WorkingCount: LongInt; // 工作数 ActiveCount: LongInt; // 活动数 PackCount: LongInt; // 处理数据包数 PackInCount: LongInt; // 收到数据包数 PackOutCount: LongInt; // 发送数据包数 ByteCount: LongInt; // 单位时间收发字节数 ByteInCount: LongInt; // 单位时间接收字节数 ByteOutCount: LongInt; // 单位时间发出字节数 end; TWorkThreadMaxInf = record MaxPackIn: LongInt; // 收到最大数据包数 MaxPackOut: LongInt; // 发出的最大数据包数 MaxByteIn: LongInt; // 每秒接收的最大字节数 MaxByteOut: LongInt; // 每秒发出的最大字节数 end; // 单一 工作线程 的明细结构 PWorkThreadDetail = ^TWorkThreadDetail; TWorkThreadDetail = record Working: Boolean; // 工作状态 Index: Integer; // 编号 PackCount: LongInt; // 处理数据包 PackInCount: LongInt; // 收到数据包 PackOutCount: LongInt; // 发送数据包 ByteCount: LongInt; // 单位时间收发字节数 ByteInCount: LongInt; // 单位时间接收字节数 ByteOutCount: LongInt; // 单位时间发出字节数 end; const // 服务状态 SERVER_STOPED = $00; // 停止 SERVER_RUNNING = $10; // 运行 SERVER_IGNORED = $20; // 忽略,不处理 SOCKET_LOCK_FAIL = 0; // 加锁失败 SOCKET_LOCK_OK = 1; // 加锁成功 SOCKET_LOCK_CLOSE = 2; // 已经关闭、放弃操作 IO_BUFFER_SIZE = 8192; // 服务端收发缓存长度(优化分块发送,不能大于65535,否则异常) IO_BUFFER_SIZE_2 = 32768; // 客户端收发缓存长度 4096 * 8 DEFAULT_SVC_PORT = 12302; // 默认端口 MAX_CLIENT_COUNT = 500; // 预设客户端连接数 MAX_FILE_VAR_SIZE = 5120000; // 文件型变量的最大长度 5M SESSION_TIMEOUT = 30; // 短连接凭证的有效时间,30 分钟 OPTIMIZE_INTERVAL = 30000; // 优化间隔(30秒) WAIT_MILLISECONDS = 60000; // 客户端发出数据后等待反馈的时间 INVALID_FILE_HANDLE = 0; // 无效的文件句柄(不用 INVALID_HANDLE_VALUE) // 断点传输每次最大发送长度 // 大数值传输速度快,但竞争网络资源多 MAX_CHUNK_SIZE = 65536; // 64k MAX_CHECKCODE_SIZE = 52800000; // 文件大于 52.8M 时,取消校验(大文件非常耗时)! OFFLINE_MSG_FLAG = 2356795438; // 离线消息文件的开始标志 MAX_TRANSMIT_SIZE = 2147483646 - 1024; // TransmitFile() 最大发送长度 HASH_CODE_SIZE = SizeOf(TMurmurHash); // Hash 长度 MSG_HEAD_SIZE = SizeOf(TMsgHead); // 信息头长度 POINTER_SIZE = SizeOf(Pointer); // 指针长度 STREAM_VAR_SIZE = SizeOf(TStreamVariable);// 传输流的变量描述长度 CLIENT_DATA_SIZE = SizeOf(TClientInfo); // 客户端信息长度 // 待发数据描述大小 TASK_SPACE_SIZE = SizeOf(TTransmitTask) - SizeOf(TClass) - SizeOf(Boolean); // Socket 地址大小 ADDRESS_SIZE_16 = SizeOf(TSockAddr) + 16; // Echo 操作 ECHO_SVC_ACTIONS = [atUnknown, atAfterReceive, atAfterSend, atServerEvent]; // 断点续传操作 FILE_CHUNK_ACTIONS = [atFileDownChunk, atFileUpChunk]; // C/S 模式标志 IOCP_SOCKET_FLAG = AnsiString('IOCP/2.8'#32); IOCP_SOCKET_FLEN = Cardinal(Length(IOCP_SOCKET_FLAG)); IOCP_SOCKET_SIZE = IOCP_SOCKET_FLEN + MSG_HEAD_SIZE; // C/S 模式取消任务 IOCP_SOCKET_CANCEL = AnsiString('IOCP/2.8 CANCEL'); IOCP_CANCEL_LENGTH = DWORD(Length(IOCP_SOCKET_CANCEL)); // 点对点、广播消息最大长度,HASH_CODE_SIZE * 4 = 2 个 MD5 长度 BROADCAST_MAX_SIZE = IO_BUFFER_SIZE - IOCP_SOCKET_SIZE - HASH_CODE_SIZE * 4; // ============== InIOCP 流协议 ================== // 协议标志 InIOCP_STREAM_SOCKET = 'InIOCP_STREAM_SOCKET'; // ================ webSocekt ==================== // WebSocekt 的 MAGIC-GUID(不能修改!) WSOCKET_MAGIC_GUID = AnsiString('258EAFA5-E914-47DA-95CA-C5AB0DC85B11'); // WebSocket 的操作代码集 TWSOpCodeSet = [ocContinuation, ocText, ocBiary, ocClose, ocPing, ocPong]; // InIOCP 扩展 WebSocket 的 JSON 首字段,长度=19(不要改) // 见:TBaseJSON.WriteExtraFields INIOCP_JSON_FLAG = AnsiString('{"_InIOCP_Ver":2.8,'); INIOCP_JSON_FLAG_LEN = Length(INIOCP_JSON_FLAG); // ================ 代理服务 ==================== InIOCP_INNER_SOCKET = AnsiString('InIOCP_INNER_SOCKET'); implementation uses SysUtils; var _WSAResult: Integer = 1; procedure _InitEnvironment; var WSAData: TWSAData; begin // 初始化 Socket 环境,设置时间日期分隔符 _WSAResult := iocp_Winsock2.WSAStartup(WINSOCK_VERSION, WSAData); {$IFDEF DELPHI_XE} // xe 或更高版本 FormatSettings.DateSeparator := '-'; FormatSettings.TimeSeparator := ':'; FormatSettings.ShortDateFormat := 'yyyy-mm-dd'; {$ELSE} DateSeparator := '-'; TimeSeparator := ':'; ShortDateFormat := 'yyyy-mm-dd'; {$ENDIF} end; procedure _WSACleanUp; begin // 清除 Socket 环境 if (_WSAResult = 0) then iocp_Winsock2.WSACleanUp; end; initialization _InitEnvironment; finalization _WSACleanUp; end.
{$MODE OBJFPC} {$R-,Q-,S-,I-} {$OPTIMIZATION LEVEL2} {$INLINE ON} program Garden; const InputFile = 'GARDEN.INP'; OutputFile = 'GARDEN.OUT'; maxMN = 2000; maxP = maxMN + maxMN; infty = 1E+100; eps = 1E-10; type TArr = array[1..maxMN] of Extended; TBit1D = array[1..maxP] of Extended; var fi, fo: TextFile; a, b: TArr; tree: array[1..maxMN] of TBit1D; m, n, p: Integer; len, h: Extended; procedure Enter; var i: Integer; begin ReadLn(fi, len, h); len := len + eps; ReadLn(fi, m); for i := 1 to m do Read(fi, a[i]); ReadLn(fi, n); for i := 1 to n do Read(fi, b[i]); ReadLn(fi); end; function Distance(a, b: Extended): Extended; inline; begin Result := Sqrt(Sqr(b - a) + Sqr(h)); end; function Maximize(var target: Extended; value: Extended): Boolean; inline; begin Result := target < value; if Result then target := value; end; procedure Sort(var a: TArr; n: Integer); procedure QSort(L, H: Integer); var i, j: Integer; pivot: extended; begin repeat if L >= H then Exit; i := L + Random(H - L + 1); pivot := a[i]; a[i] := a[L]; i := L; j := H; repeat while (a[j] > pivot) and (i < j) do Dec(j); if i < j then begin a[i] := a[j]; Inc(i); end else Break; while (a[i] < pivot) and (i < j) do Inc(i); if i < j then begin a[j] := a[i]; Dec(j); end else Break; until i = j; a[i] := pivot; QSort(L, i - 1); L := i + 1; until false; end; begin QSort(1, n); end; procedure UpdateY(var bit: TBit1D; y: Integer; value: Extended); begin while y <= p do begin if not Maximize(bit[y], value) then Break; Inc(y, y and -y); end; end; procedure Update(x, y: Integer; value: Extended); begin while x <= n do begin UpdateY(tree[x], y, value); Inc(x, x and -x); end; end; function FindY(const bit: TBit1D; threshold: Extended): Integer; var y, next, mask: Integer; begin mask := 1; while mask shl 1 <= p do mask := mask shl 1; y := 0; Result := maxP; while mask > 0 do begin if next <= p then begin next := y + mask; if bit[next] >= threshold then Result := next else y := next; end; mask := mask shr 1; end; end; function Find(x: Integer; threshold: Extended): Integer; var resz: Integer; begin Result := maxP + 1; while x > 0 do begin resz := FindY(tree[x], threshold); if Result > resz then Result := resz; x := x and Pred(x); end; end; function Optimize: Integer; var x, y, z: Integer; d, f, g: Extended; res: Integer; nosol: Boolean; begin p := m + n; for y := 1 to n do for z := 1 to p do tree[y, z] := -infty; nosol := True; res := -2; for x := 1 to m do for y := 1 to n do begin d := Distance(a[x], b[y]); if 2 * d <= len then nosol := False else Continue; f := a[x] + b[y] + d; z := x + y; Update(y, z, a[x] + b[y] - d); z := Find(y, f - len); if x + y - z > res then res := x + y - z; end; if nosol then Exit(0); Result := res + 2; end; procedure SolveAll; var itest, ntest: Integer; begin ReadLn(fi, ntest); for itest := 1 to ntest do begin Enter; Sort(a, m); Sort(b, n); WriteLn(fo, Optimize); end; end; begin AssignFile(fi, InputFile); Reset(fi); AssignFile(fo, OutputFile); Rewrite(fo); try SolveAll; finally CloseFile(fi); CloseFile(fo); end; end.
unit MFichas.Controller.Venda.Metodos.VenderItem; interface uses MFichas.Controller.Venda.Interfaces, MFichas.Model.Venda.Interfaces, MFichas.Model.Item; type TControllerVendaMetodosVenderItem = class(TInterfacedObject, iControllerVendaMetodosVenderItem) private [weak] FParent : iControllerVenda; FModel : iModelVenda; FCodigo : String; FQuantidade: Double; FValor : Currency; constructor Create(AParent: iControllerVenda; AModel: iModelVenda); public destructor Destroy; override; class function New(AParent: iControllerVenda; AModel: iModelVenda): iControllerVendaMetodosVenderItem; function Codigo(ACodigo: String) : iControllerVendaMetodosVenderItem; function Quantidade(AQuantidade: Double): iControllerVendaMetodosVenderItem; function Valor(AValor: Currency) : iControllerVendaMetodosVenderItem; function Executar : iControllerVendaMetodosVenderItem; function &End : iControllerVendaMetodos; end; implementation { TControllerVendaMetodosVenderItem } function TControllerVendaMetodosVenderItem.Codigo( ACodigo: String): iControllerVendaMetodosVenderItem; begin Result := Self; FCodigo := ACodigo; end; function TControllerVendaMetodosVenderItem.&End: iControllerVendaMetodos; begin Result := FParent.Metodos; end; constructor TControllerVendaMetodosVenderItem.Create(AParent: iControllerVenda; AModel: iModelVenda); begin FParent := AParent; FModel := AModel; end; destructor TControllerVendaMetodosVenderItem.Destroy; begin inherited; end; function TControllerVendaMetodosVenderItem.Executar: iControllerVendaMetodosVenderItem; begin Result := Self; FModel .Item .Iterator .Add( TModelItem.New(FModel) .Metodos .Vender .Codigo(FCodigo) .Quantidade(FQuantidade) .Valor(FValor) .&End .&End ) .&End; end; class function TControllerVendaMetodosVenderItem.New(AParent: iControllerVenda; AModel: iModelVenda): iControllerVendaMetodosVenderItem; begin Result := Self.Create(AParent, AModel); end; function TControllerVendaMetodosVenderItem.Quantidade( AQuantidade: Double): iControllerVendaMetodosVenderItem; begin Result := Self; FQuantidade := AQuantidade; end; function TControllerVendaMetodosVenderItem.Valor( AValor: Currency): iControllerVendaMetodosVenderItem; begin Result := Self; FValor := AValor; end; end.
unit NavigationInterfaces; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/NavigationInterfaces.pas" // Начат: 09.10.2009 19:06 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<Interfaces::Category>> F1 Core::Base Operations::View::NavigationInterfaces // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses DocumentUnit, ExternalOperationUnit, l3Interfaces {$If not defined(NoVCM)} , vcmInterfaces {$IfEnd} //not NoVCM , bsTypes, DocumentAndListInterfaces, nevNavigation, DocumentInterfaces, bsTypesNew ; type IbsHyperLinkProcessorHelper = interface(IUnknown) ['{61BEA4A9-16C3-4533-93D0-67B0AD286DCF}'] function MakeContainer: IvcmContainer; {* Создать параметры на которых будут делаться вызовы операций } function MakeNewMainWindow: IvcmContainer; {* Открыть новое главное окно и вернуть параметры для него } function ProcessExternalOperation(const anOperation: IExternalOperation): Boolean; procedure CheckLinkInfo(const aLink: IevHyperlink); function MakeLinkDocInfo(const aDocument: IDocument; aPointType: TDocumentPositionType; aSub: Cardinal): IdeDocInfo; function ProcessLocalLink(const aDocument: IDocument; aPointType: TDocumentPositionType; aSub: Cardinal): Boolean; end;//IbsHyperLinkProcessorHelper InsOpenDocOnNumberData = interface(IUnknown) {* Данные для открытия документа по номеру } ['{2892E567-2A20-435A-92CB-E234BAF0E258}'] function Get_DocID: Integer; procedure Set_DocID(aValue: Integer); function Get_PosID: Integer; procedure Set_PosID(aValue: Integer); function Get_Internal: Boolean; procedure Set_Internal(aValue: Boolean); function Get_History: Il3CString; procedure Set_History(const aValue: Il3CString); function Get_Done: Boolean; procedure Set_Done(aValue: Boolean); function Get_PosType: TDocumentPositionType; procedure Set_PosType(aValue: TDocumentPositionType); property DocID: Integer read Get_DocID write Set_DocID; property PosID: Integer read Get_PosID write Set_PosID; property Internal: Boolean read Get_Internal write Set_Internal; property History: Il3CString read Get_History write Set_History; property Done: Boolean read Get_Done write Set_Done; property PosType: TDocumentPositionType read Get_PosType write Set_PosType; end;//InsOpenDocOnNumberData {$IfEnd} //not Admin AND not Monitorings implementation end.
unit QFLikeTextLoad_Form; {* Форма для работы с КЗ } // Модуль: "w:\common\components\gui\Garant\Daily\Forms\QFLikeTextLoad_Form.pas" // Стереотип: "VCMForm" // Элемент модели: "QFLikeTextLoad" MUID: (4CA090120212) // Имя типа: "TQFLikeTextLoadForm" {$Include w:\common\components\gui\sdotDefine.inc} interface {$If Defined(nsTest) AND NOT Defined(NoVCM)} uses l3IntfUses , PrimTextLoad_Form , evQueryCardInt , evTextSource , evQueryCardEditor , evCustomTextSource , evCustomEditor , vcmInterfaces , vcmEntities ; const fm_QFLikeTextLoadForm: TvcmFormDescriptor = (rFormID : (rName : 'QFLikeTextLoadForm'; rID : 0); rFactory : nil); {* Идентификатор формы TQFLikeTextLoadForm } type TQFLikeTextLoadForm = class; QFLikeTextLoadFormDef = interface {* Идентификатор формы QFLikeTextLoad } ['{41C944FD-8129-43F8-89E8-75E7D231D870}'] end;//QFLikeTextLoadFormDef TQFLikeTextLoadForm = {final} class(TPrimTextLoadForm, QFLikeTextLoadFormDef) {* Форма для работы с КЗ } Entities : TvcmEntities; private f_QueryCard: IevQueryCard; f_TextSource: TevTextSource; f_Text: TevQueryCardEditor; protected function pm_GetTextSource: TevCustomTextSource; override; function pm_GetText: TevCustomEditor; override; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitControls; override; {* Процедура инициализации контролов. Для перекрытия в потомках } procedure MakeControls; override; public procedure AfterLoad; override; public property TextSource: TevTextSource read f_TextSource; property Text: TevQueryCardEditor read f_Text; end;//TQFLikeTextLoadForm {$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM) implementation {$If Defined(nsTest) AND NOT Defined(NoVCM)} uses l3ImplUses , evQueryDocumentContainer , evControlContainerEX , nevTools , l3InterfacesMisc {$If NOT Defined(NoScripts)} , TtfwClassRef_Proxy {$IfEnd} // NOT Defined(NoScripts) , QFLikeTextLoad_ut_QFLikeTextLoad_UserType {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} , QFLikeTextLoadKeywordsPack {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) ; {$R *.DFM} function TQFLikeTextLoadForm.pm_GetTextSource: TevCustomTextSource; //#UC START# *4C9B21D20187_4CA090120212get_var* //#UC END# *4C9B21D20187_4CA090120212get_var* begin //#UC START# *4C9B21D20187_4CA090120212get_impl* Result := TextSource; //#UC END# *4C9B21D20187_4CA090120212get_impl* end;//TQFLikeTextLoadForm.pm_GetTextSource function TQFLikeTextLoadForm.pm_GetText: TevCustomEditor; //#UC START# *4C9B21E400A4_4CA090120212get_var* //#UC END# *4C9B21E400A4_4CA090120212get_var* begin //#UC START# *4C9B21E400A4_4CA090120212get_impl* Result := Text; //#UC END# *4C9B21E400A4_4CA090120212get_impl* end;//TQFLikeTextLoadForm.pm_GetText procedure TQFLikeTextLoadForm.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4CA090120212_var* //#UC END# *479731C50290_4CA090120212_var* begin //#UC START# *479731C50290_4CA090120212_impl* inherited; f_QueryCard := nil; //#UC END# *479731C50290_4CA090120212_impl* end;//TQFLikeTextLoadForm.Cleanup procedure TQFLikeTextLoadForm.InitControls; {* Процедура инициализации контролов. Для перекрытия в потомках } //#UC START# *4A8E8F2E0195_4CA090120212_var* //#UC END# *4A8E8F2E0195_4CA090120212_var* begin //#UC START# *4A8E8F2E0195_4CA090120212_impl* inherited; f_TextSource.DocumentContainer := TevQueryDocumentContainer.Make; //#UC END# *4A8E8F2E0195_4CA090120212_impl* end;//TQFLikeTextLoadForm.InitControls procedure TQFLikeTextLoadForm.AfterLoad; //#UC START# *4F15435202B5_4CA090120212_var* var l_Cont: InevQueryDocumentContainer; //#UC END# *4F15435202B5_4CA090120212_var* begin //#UC START# *4F15435202B5_4CA090120212_impl* f_QueryCard := TevControlContainerEX.Make; if l3IOk(f_TextSource.DocumentContainer.QueryInterface(InevQueryDocumentContainer, l_Cont)) then f_QueryCard.LinkView(l_Cont); //#UC END# *4F15435202B5_4CA090120212_impl* end;//TQFLikeTextLoadForm.AfterLoad procedure TQFLikeTextLoadForm.MakeControls; begin inherited; with AddUsertype(ut_QFLikeTextLoadName, str_ut_QFLikeTextLoadCaption, str_ut_QFLikeTextLoadCaption, False, -1, -1, '', nil, nil, nil, vcm_ccNone) do begin end;//with AddUsertype(ut_QFLikeTextLoadName f_TextSource := TevTextSource.Create(Self); f_TextSource.Name := 'TextSource'; f_Text := TevQueryCardEditor.Create(Self); f_Text.Name := 'Text'; f_Text.Parent := Self; end;//TQFLikeTextLoadForm.MakeControls initialization fm_QFLikeTextLoadForm.SetFactory(TQFLikeTextLoadForm.Make); {* Регистрация фабрики формы QFLikeTextLoad } {$If NOT Defined(NoScripts)} TtfwClassRef.Register(TQFLikeTextLoadForm); {* Регистрация QFLikeTextLoad } {$IfEnd} // NOT Defined(NoScripts) {$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM) end.
unit pgInterfaces; // Модуль: "w:\common\components\rtl\Garant\PG\pgInterfaces.pas" // Стереотип: "Interfaces" // Элемент модели: "pgInterfaces" MUID: (55DAD4150001) {$Include w:\common\components\rtl\Garant\PG\pgDefine.inc} interface {$If Defined(UsePostgres)} uses l3IntfUses , daTypes , daInterfaces , ddAppConfig , l3Date , SysUtils ; const c_DefaultPostgresPort = 5432; type IpgParamsStorage = interface(IdaParamsStorage) ['{6C19DDA2-B6B6-4D74-B18D-DA7D80F4BEC5}'] function Get_DataServerHostName: AnsiString; procedure Set_DataServerHostName(const aValue: AnsiString); function Get_DataServerPort: Integer; procedure Set_DataServerPort(aValue: Integer); property DataServerHostName: AnsiString read Get_DataServerHostName write Set_DataServerHostName; property DataServerPort: Integer read Get_DataServerPort write Set_DataServerPort; end;//IpgParamsStorage IpgDataConverter = interface(IdaDataConverter) ['{E5C309A7-632D-4345-92DF-9CA08F824EA7}'] function ToInteger(aData: Pointer): Integer; function ToLargeInt(aData: Pointer): LargeInt; function ToStDate(aData: Pointer): TStDate; function ToStTime(aData: Pointer): TStTime; function ToString(aData: Pointer): AnsiString; function ToByte(aData: Pointer): Byte; end;//IpgDataConverter EPgError = class(Exception) end;//EPgError EpgLockError = class(EPgError) end;//EpgLockError IpgConnectionListener = interface ['{5011A29E-C541-42EA-9245-83926F9FCA72}'] procedure AfterConnect; procedure BeforeDisconnect; end;//IpgConnectionListener EpgInnerTransactionFailed = class(EPgError) end;//EpgInnerTransactionFailed {$IfEnd} // Defined(UsePostgres) implementation {$If Defined(UsePostgres)} uses l3ImplUses {$If NOT Defined(NoScripts)} , TtfwTypeRegistrator_Proxy {$IfEnd} // NOT Defined(NoScripts) ; initialization {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(EPgError)); {* Регистрация типа EPgError } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(EpgLockError)); {* Регистрация типа EpgLockError } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(EpgInnerTransactionFailed)); {* Регистрация типа EpgInnerTransactionFailed } {$IfEnd} // NOT Defined(NoScripts) {$IfEnd} // Defined(UsePostgres) end.
unit MFichas.Model.Caixa.Metodos.Factory; interface uses MFichas.Model.Caixa.Interfaces, MFichas.Model.Caixa.Metodos.Interfaces, MFichas.Model.Caixa.Metodos.Abrir, MFichas.Model.Caixa.Metodos.Fechar, MFichas.Model.Caixa.Metodos.Suprimento, MFichas.Model.Caixa.Metodos.Sangria; type TModelCaixaMetodosFactory = class(TInterfacedObject, iModelCaixaMetodosFactory) private constructor Create; public destructor Destroy; override; class function New: iModelCaixaMetodosFactory; function CaixaMetodoAbrir(AParent: iModelCaixa) : iModelCaixaMetodosAbrir; function CaixaMetodoFechar(AParent: iModelCaixa) : iModelCaixaMetodosFechar; function CaixaMetodoSuprimento(AParent: iModelCaixa): iModelCaixaMetodosSuprimento; function CaixaMetodoSangria (AParent: iModelCaixa): iModelCaixaMetodosSangria; end; implementation { TModelCaixaMetodosFactory } function TModelCaixaMetodosFactory.CaixaMetodoAbrir(AParent: iModelCaixa): iModelCaixaMetodosAbrir; begin Result := TModelCaixaMetodosAbrir.New(AParent); end; function TModelCaixaMetodosFactory.CaixaMetodoFechar(AParent: iModelCaixa): iModelCaixaMetodosFechar; begin Result := TModelCaixaMetodosFechar.New(AParent); end; function TModelCaixaMetodosFactory.CaixaMetodoSangria(AParent: iModelCaixa): iModelCaixaMetodosSangria; begin Result := TModelCaixaMetodosSangria.New(AParent); end; function TModelCaixaMetodosFactory.CaixaMetodoSuprimento(AParent: iModelCaixa): iModelCaixaMetodosSuprimento; begin Result := TModelCaixaMetodosSuprimento.New(AParent); end; constructor TModelCaixaMetodosFactory.Create; begin end; destructor TModelCaixaMetodosFactory.Destroy; begin inherited; end; class function TModelCaixaMetodosFactory.New: iModelCaixaMetodosFactory; begin Result := Self.Create; end; end.
unit UpdateOrderUnit; interface uses SysUtils, BaseExampleUnit, OrderUnit; type TUpdateOrder = class(TBaseExample) public procedure Execute(Order: TOrder); end; implementation procedure TUpdateOrder.Execute(Order: TOrder); var ErrorString: String; UpdatedOrder: TOrder; begin UpdatedOrder := Route4MeManager.Order.Update(Order, ErrorString); try WriteLn(''); if (UpdatedOrder <> nil) then WriteLn('UpdateOrder executed successfully') else WriteLn(Format('UpdateOrder error: "%s"', [ErrorString])); finally FreeAndNil(UpdatedOrder); end; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, dbugintf; type { TfrmMain } TfrmMain = class(TForm) btnDemo: TButton; Memo1: TMemo; procedure btnDemoClick(Sender: TObject); procedure FormShow(Sender: TObject); private public end; const DS=DirectorySeparator; LE=LineEnding; var frmMain: TfrmMain; implementation {$R *.lfm} { TfrmMain } procedure TfrmMain.btnDemoClick(Sender: TObject); var i: integer; begin Memo1.Append('Start Demo...'); SendDateTime('Date/Time: ', Now); SendSeparator; SendMethodEnter('btnDemoClick'); SendDebugEx('Demo Info', dlInformation); SendDebugEx('Demo Warning', dlWarning); SendDebugEx('Demo Error', dlError); SendSeparator; SendDebugFmt('Demo Fmt: %s=%d', ['value',69]); SendSeparator; SendDebugFmtEx('Demo: %s', ['a message'], dlInformation); SendDebugFmtEx('Demo: %s', ['a warning'], dlWarning); SendDebugFmtEx('Demo: %s', ['an error'], dlError); SendSeparator; SetDebuggingEnabled(False); for i:=1 to 10 do SendDebugFmt('Disabled count: %d', [i]); //will not show in debug viewer SetDebuggingEnabled(True); for i:=1 to 10 do SendDebugFmt('Enabled count: %d', [i]); SendMethodExit('btnDemoClick'); SendSeparator; SendDateTime('Date/Time: ', Now); Memo1.Append('End Demo.'); end; procedure TfrmMain.FormShow(Sender: TObject); begin Memo1.Append('Press [Demo] then watch the Debug Message Viewer...'); SendBoolean('GetDebuggingEnabled', GetDebuggingEnabled); SendSeparator; end; end.
unit Cautious_Edit; interface uses Classes, Controls,stdCtrls,messages,TypInfo,expression_lib; type TCautiousEditClass=class of TCautiousEdit; TCautiousEdit=class(TEdit) private fAllowExpressions: Boolean; backupHint: string; fSeemsNormal: boolean; fControlToDisable: TControl; fonValidateResult: TNotifyEvent; fonDestroy: TNotifyEvent; procedure SetOnValidateResult(value: TNotifyEvent); procedure SetControlToDisable(value:TControl); procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED; procedure SetZeroFlag(Writer: TWriter); procedure LoadZeroFlag(Reader: TReader); protected procedure DefineProperties(Filer: TFiler); override; procedure SetExpressionRoot(value: TComponent); virtual; function GetExpressionRoot: TComponent; virtual; public constructor Create(owner: TComponent); override; destructor Destroy; override; procedure Change; override; procedure DoDestroy; procedure Notification(aComponent: TComponent; operation: TOperation); override; procedure TurnRed(explain: string); procedure ReturnToNormal; property SeemsNormal: boolean read fSeemsNormal; property ExpressionRootComponent: TComponent read GetExpressionRoot write SetExpressionRoot; published property ControlToDisable: TControl read fControlToDisable write SetControlToDisable; property OnValidateResult: TNotifyEvent read fonValidateResult write SetOnValidateResult; property OnDestroy: TNotifyEvent read fonDestroy write fonDestroy; property AllowExpressions: boolean read fAllowExpressions write fAllowExpressions default true; end; TVariantEdit = class(TCautiousEdit) private fExpression: TVariantExpression; function get_value: Variant; procedure set_value(value: Variant); protected procedure SetExpressionRoot(value: TComponent); override; function GetExpressionRoot: TComponent; override; public constructor Create(Owner: TComponent); override; procedure Change; override; function isValid: boolean; property Expression: TVariantExpression read fExpression; published property value: Variant read get_value write set_value; end; procedure Register; procedure EnableControl(ControlToDisable: TControl; Field: TObject); procedure DisableControl(ControlToDisable: TControl; Field: TObject); implementation uses new_phys_unit_lib,sysUtils,Contnrs,graphics; (* General procedures *) var CautiousControlList: TBucketList; procedure EnableControl(ControlToDisable: TControl; Field: TObject); var list: TList; i: Integer; begin if CautiousControllist.Exists(ControlToDisable) then begin list:=TList(CautiousControllist[ControlToDisable]); i:=list.IndexOf(Field); if i>-1 then begin list.Remove(Field); if list.Count=0 then begin list.Free; CautiousControllist.Remove(ControlToDisable); ControlToDisable.Enabled:=true; end; end; end; end; procedure DisableControl(ControlToDisable: TControl; Field: TObject); var ListOfPointers: TList; begin //этот элемент может появиться впервые, и это не должно воспр. как ошибка if CautiousControllist.Exists(ControlToDisable) then begin //все есть, надо найти и добавить ListOfPointers:=TList(CautiousControlList[ControlToDisable]); if ListOfPointers.IndexOf(Field)=-1 then ListOfPointers.Add(Field); end else begin ListOfPointers:=TList.Create; ListOfPointers.Add(Field); CautiousControlList.Add(ControlToDisable,ListOfPointers); //создали новый список, для данной кнопки, и добавили в него один указатель end; ControlToDisable.Enabled:=false; //очевидно же! end; (* TCautiousEdit *) constructor TCautiousEdit.Create(owner: TComponent); begin inherited Create(owner); backupHint:=Hint; fSeemsNormal:=true; AllowExpressions:=true; end; destructor TCautiousEdit.Destroy; begin DoDestroy; inherited Destroy; end; procedure TCautiousEdit.DoDestroy; begin if Assigned(fOnDestroy) then fOnDestroy(self); end; procedure TCautiousEdit.SetControlToDisable(value: TControl); begin if Assigned(fControlToDisable) then begin EnableControl(fControlToDisable,self); fControlToDisable.RemoveFreeNotification(self); end; fControlToDisable:=value; if Assigned(value) then begin value.FreeNotification(self); Change; end; end; procedure TCautiousEdit.Change; begin if Assigned(OnValidateResult) and enabled then OnValidateResult(self); if Assigned(OnChange) then OnChange(self); end; procedure TCautiousEdit.SetOnValidateResult(value: TNotifyEvent); begin fonValidateResult:=value; Change; end; procedure TCautiousEdit.Notification(aComponent: TComponent; operation: TOperation); begin if (operation=opRemove) and (aComponent=fControlToDisable) then fControlToDisable:=nil; inherited; end; procedure TCautiousEdit.CMEnabledChanged(var Message: TMessage); begin if (not enabled) and Assigned(ControlToDisable) then EnableControl(ControlToDisable,self); //то есть, отключенное поле ввода не должно мешать нажатию на кнопку if enabled then Change; //поле снова ввели в строй, проверим - не пора ль снова выругаться? inherited; end; procedure TCautiousEdit.TurnRed(explain: string); begin if SeemsNormal then begin Color:=clRed; backupHint:=Hint; fSeemsNormal:=false; end; Hint:=explain; if Assigned(ControlToDisable) then DisableControl(ControlToDisable,self); end; procedure TCautiousEdit.ReturnToNormal; begin if not seemsNormal then begin Color:=clWhite; Hint:=backupHint; fSeemsNormal:=true; end; if Assigned(ControlToDisable) then EnableControl(ControlToDisable,self); end; procedure TCautiousEdit.DefineProperties(Filer: TFiler); begin Filer.DefineProperty('IsEmpty',LoadZeroFlag,SetZeroFlag,(text='') and (csDesigning in ComponentState)); end; procedure TCautiousEdit.SetZeroFlag(Writer: TWriter); begin Writer.WriteBoolean(true); end; procedure TCautiousEdit.LoadZeroFlag(Reader: TReader); begin if Reader.ReadBoolean then text:=''; end; procedure TCautiousEdit.SetExpressionRoot(value: TComponent); begin // nothing end; function TCautiousEdit.GetExpressionRoot: TComponent; begin Result:=nil; end; (* TVariantEdit *) function TVariantEdit.get_value: Variant; begin // if AllowExpressions then begin expression.SetString(text); if expression.isCorrect then Result:=expression.getVariantValue //не гарантируется отсутствие ошибок, тем не менее else begin Result:=0; if not (csDesigning in self.ComponentState) then Raise Exception.CreateFMT('TFloatLabel: %s',[expression.errorMsg]); end; // end // else // Result:=PhysUnitCreate(text); end; procedure TVariantEdit.Change; var res: Variant; resourcestring FloatEditNotARealNumberMsg = 'Не является действительным числом'; begin if AllowExpressions then begin expression.SetString(text); if expression.isCorrect then ReturnToNormal else TurnRed(expression.errorMsg); end else if TryPhysUnitCreate(text,res) then ReturnToNormal else TurnRed(res); inherited Change; end; procedure TVariantEdit.set_value(value: Variant); begin text:=value; end; constructor TVariantEdit.Create(owner: TComponent); begin inherited Create(owner); fExpression:=TVariantExpression.create(self); if (csDesigning in ComponentState) then value:=StrToFloat('0'); end; function TVariantEdit.isValid: Boolean; var t: Variant; begin if AllowExpressions then begin expression.SetString(text); Result:=expression.isCorrect; end else Result:=TryPhysUnitCreate(text,t); end; procedure TVariantEdit.SetExpressionRoot(value: TComponent); begin Expression.SetRootComponent(value); end; function TVariantEdit.GetExpressionRoot: TComponent; begin Result:=nil; end; (* General procedures *) procedure Register; begin RegisterComponents('CautiousEdit', [TCautiousEdit,TVariantEdit]); end; procedure free_em_all(AInfo, AItem, AData: Pointer; out AContinue: Boolean); begin TList(AData).Free; AContinue:=true; end; initialization CautiousControlList:=TBucketList.Create(); finalization CautiousControlList.ForEach(free_em_all); CautiousControlList.Free; end.
unit TTSJOBTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSJOBRecord = record PAutoInc: Integer; PLenderNum: String[4]; PType: Integer; PSetting : String[100]; PPeriod: String[1]; PPer_Type: integer; PStart: String[20]; PStop: String[20]; PStopStatus: String[10]; PUserID: String[10]; PDescription: String[100]; PControlStatus: String[10]; PControlMsg: String[100]; PControlScanMsg: String[50]; PImmediatePrint: String[1]; PServerPrinter: String[100]; End; TTTSJOBBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSJOBRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSJOB = (TTSJOBPrimaryKey, TTSJOBByLenderType); TTTSJOBTable = class( TDBISAMTableAU ) private FDFAutoInc: TAutoIncField; FDFLenderNum: TStringField; FDFType: TIntegerField; FDFSetting: TStringField; FDFPeriod: TStringField; FDFPer_Type: TIntegerField; FDFStart: TStringField; FDFStop: TStringField; FDFStopStatus: TStringField; FDFUserID: TStringField; FDFDescription: TStringField; FDFOptions: TBlobField; FDFControlStatus: TStringField; FDFControlMsg: TStringField; FDFControlScanMsg: TStringField; FDFImmediatePrint: TStringField; FDFServerPrinter: TStringField; FDFLenderList: TBlobField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPType(const Value: Integer); function GetPType:Integer; procedure SetPSetting(const Value: String); function GetPSetting:String; procedure SetPPeriod(const Value: String); function GetPPeriod:String; procedure SetPPer_Type(const Value: Integer); function GetPPer_Type:Integer; procedure SetPStart(const Value: String); function GetPStart:String; procedure SetPStop(const Value: String); function GetPStop:String; procedure SetPStopStatus(const Value: String); function GetPStopStatus:String; procedure SetPUserID(const Value: String); function GetPUserID:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPControlStatus(const Value: String); function GetPControlStatus:String; procedure SetPControlMsg(const Value: String); function GetPControlMsg:String; procedure SetPControlScanMsg(const Value: String); function GetPControlScanMsg:String; procedure SetPImmediatePrint(const Value: String); function GetPImmediatePrint:String; procedure SetPServerPrinter(const Value: String); function GetPServerPrinter:String; procedure SetEnumIndex(Value: TEITTSJOB); function GetEnumIndex: TEITTSJOB; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSJOBRecord; procedure StoreDataBuffer(ABuffer:TTTSJOBRecord); property DFAutoInc: TAutoIncField read FDFAutoInc; property DFLenderNum: TStringField read FDFLenderNum; property DFType: TIntegerField read FDFType; property DFSetting: TStringField read FDFSetting; property DFPeriod: TStringField read FDFPeriod; property DFPer_type: TIntegerField read FDFPer_type; property DFStart: TStringField read FDFStart; property DFStop: TStringField read FDFStop; property DFStopStatus: TStringField read FDFStopStatus; property DFUserID: TStringField read FDFUserID; property DFDescription: TStringField read FDFDescription; property DFOptions: TBlobField read FDFOptions; property DFControlStatus: TStringField read FDFControlStatus; property DFControlMsg: TStringField read FDFControlMsg; property DFControlScanMsg: TStringField read FDFControlScanMsg; property DFImmediatePrint: TStringField read FDFImmediatePrint; property DFServerPrinter: TStringField read FDFServerPrinter; property DFLenderList: TBlobField read FDFLenderList; Property PPeriod : string read getPPeriod write SetPPeriod; Property PPer_type: Integer read getPPer_Type write SetPPer_Type; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PType: Integer read GetPType write SetPType; property PStart: String read GetPStart write SetPStart; property PStop: String read GetPStop write SetPStop; property PStopStatus: String read GetPStopStatus write SetPStopStatus; property PUserID: String read GetPUserID write SetPUserID; property PDescription: String read GetPDescription write SetPDescription; property PControlStatus: String read GetPControlStatus write SetPControlStatus; property PControlMsg: String read GetPControlMsg write SetPControlMsg; property PControlScanMsg: String read GetPControlScanMsg write SetPControlScanMsg; property PImmediatePrint: String read GetPImmediatePrint write SetPImmediatePrint; property PServerPrinter: String read GetPServerPrinter write SetPServerPrinter; published property Active write SetActive; property EnumIndex: TEITTSJOB read GetEnumIndex write SetEnumIndex; end; { TTTSJOBTable } procedure Register; implementation procedure TTTSJOBTable.CreateFields; begin FDFAutoInc := CreateField( 'AutoInc' ) as TAutoIncField; FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFType := CreateField( 'Type' ) as TIntegerField; FDFSetting := CreateField( 'Setting') as TStringField; FDFPeriod := CreateField( 'Period' ) as TStringField; FDFPer_Type := CreateField( 'Per_Type' ) as TIntegerField; FDFStart := CreateField( 'Start' ) as TStringField; FDFStop := CreateField( 'Stop' ) as TStringField; FDFStopStatus := CreateField( 'StopStatus' ) as TStringField; FDFUserID := CreateField( 'UserID' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFOptions := CreateField( 'Options' ) as TBlobField; FDFControlStatus := CreateField( 'ControlStatus' ) as TStringField; FDFControlMsg := CreateField( 'ControlMsg' ) as TStringField; FDFControlScanMsg := CreateField( 'ControlScanMsg' ) as TStringField; FDFImmediatePrint := CreateField('ImmediatePrint' ) as TStringField; FDFServerPrinter := CreateField('ServerPrinter') as TStringField; FDFLenderList := CreateField( 'LenderList' ) as TBlobField; end; { TTTSJOBTable.CreateFields } procedure TTTSJOBTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSJOBTable.SetActive } procedure TTTSJOBTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSJOBTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSJOBTable.SetPType(const Value: Integer); begin DFType.Value := Value; end; function TTTSJOBTable.GetPType:Integer; begin result := DFType.Value; end; procedure TTTSJOBTable.SetPStart(const Value: String); begin DFStart.Value := Value; end; function TTTSJOBTable.GetPStart:String; begin result := DFStart.Value; end; procedure TTTSJOBTable.SetPStop(const Value: String); begin DFStop.Value := Value; end; function TTTSJOBTable.GetPStop:String; begin result := DFStop.Value; end; procedure TTTSJOBTable.SetPStopStatus(const Value: String); begin DFStopStatus.Value := Value; end; function TTTSJOBTable.GetPStopStatus:String; begin result := DFStopStatus.Value; end; procedure TTTSJOBTable.SetPUserID(const Value: String); begin DFUserID.Value := Value; end; function TTTSJOBTable.GetPUserID:String; begin result := DFUserID.Value; end; procedure TTTSJOBTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TTTSJOBTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TTTSJOBTable.SetPControlStatus(const Value: String); begin DFControlStatus.Value := Value; end; function TTTSJOBTable.GetPControlStatus:String; begin result := DFControlStatus.Value; end; procedure TTTSJOBTable.SetPControlMsg(const Value: String); begin DFControlMsg.Value := Value; end; function TTTSJOBTable.GetPControlMsg:String; begin result := DFControlMsg.Value; end; procedure TTTSJOBTable.SetPControlScanMsg(const Value: String); begin DFControlScanMsg.Value := Value; end; function TTTSJOBTable.GetPControlScanMsg:String; begin result := DFControlScanMsg.Value; end; procedure TTTSJOBTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('AutoInc, AutoInc, 0, N'); Add('LenderNum, String, 4, N'); Add('Type, Integer, 0, N'); Add('Setting, String, 100, N'); Add('Period, String, 1, N'); Add('Per_Type, Integer, 0, N'); Add('Start, String, 20, N'); Add('Stop, String, 20, N'); Add('StopStatus, String, 10, N'); Add('UserID, String, 10, N'); Add('Description, String, 100, N'); Add('Options, Memo, 0, N'); Add('ControlStatus, String, 10, N'); Add('ControlMsg, String, 100, N'); Add('ControlScanMsg, String, 50, N'); Add('ImmediatePrint, String, 1, N'); Add('ServerPrinter, String, 100, N'); Add('LenderList, Memo, 0, N'); end; end; procedure TTTSJOBTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, AutoInc, Y, Y, N, N'); Add('ByLenderType, LenderNum;Type;AutoInc, N, N, N, Y'); end; end; procedure TTTSJOBTable.SetEnumIndex(Value: TEITTSJOB); begin case Value of TTSJOBPrimaryKey : IndexName := ''; TTSJOBByLenderType : IndexName := 'ByLenderType'; end; end; function TTTSJOBTable.GetDataBuffer:TTTSJOBRecord; var buf: TTTSJOBRecord; begin fillchar(buf, sizeof(buf), 0); buf.PAutoInc := DFAutoInc.Value; buf.PLenderNum := DFLenderNum.Value; buf.PType := DFType.Value; buf.PSetting := DFSetting.Value; buf.PPeriod := DFPeriod.Value; buf.PPer_Type := DFPer_Type.Value; buf.PStart := DFStart.Value; buf.PStop := DFStop.Value; buf.PStopStatus := DFStopStatus.Value; buf.PUserID := DFUserID.Value; buf.PDescription := DFDescription.Value; buf.PControlStatus := DFControlStatus.Value; buf.PControlMsg := DFControlMsg.Value; buf.PControlScanMsg := DFControlScanMsg.Value; buf.PImmediatePrint := DFImmediatePrint.Value; buf.PServerPrinter := DFServerPrinter.Value; result := buf; end; procedure TTTSJOBTable.StoreDataBuffer(ABuffer:TTTSJOBRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFType.Value := ABuffer.PType; DFSetting.Value := Abuffer.PSetting; DFPeriod.Value := ABuffer.PPEriod; DFPer_Type.Value := ABuffer.PPer_Type; DFStart.Value := ABuffer.PStart; DFStop.Value := ABuffer.PStop; DFStopStatus.Value := ABuffer.PStopStatus; DFUserID.Value := ABuffer.PUserID; DFDescription.Value := ABuffer.PDescription; DFControlStatus.Value := ABuffer.PControlStatus; DFControlMsg.Value := ABuffer.PControlMsg; DFControlScanMsg.Value := ABuffer.PControlScanMsg; DFImmediatePrint.Value := ABuffer.PImmediatePrint; DFServerPrinter.Value := Abuffer.PServerPrinter; end; function TTTSJOBTable.GetEnumIndex: TEITTSJOB; var iname : string; begin result := TTSJOBPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSJOBPrimaryKey; if iname = 'BYLENDERTYPE' then result := TTSJOBByLenderType; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSJOBTable, TTTSJOBBuffer ] ); end; { Register } function TTTSJOBBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..16] of string = ('AUTOINC','LENDERNUM' ,'TYPE','SETTING','PERIOD','Per_Type','START','STOP','STOPSTATUS' ,'USERID','DESCRIPTION','CONTROLSTATUS','CONTROLMSG' ,'CONTROLSCANMSG','IMMEDIATEPRINT','SERVERPRINTER' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 16) and (flist[x] <> s) do inc(x); if x <= 16 then result := x else result := 0; end; function TTTSJOBBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftAutoInc; 2 : result := ftString; 3 : result := ftInteger; 4 : result := ftString; 5 : result := ftString; 6 : result := ftInteger; 7 : result := ftString; 8 : result := ftString; 9 : result := ftString; 10 : result := ftString; 11 : result := ftString; 12 : result := ftString; 13 : result := ftString; 14 : result := ftString; 15 : result := ftString; 16 : result := ftString; end; end; function TTTSJOBBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PAutoInc; 2 : result := @Data.PLenderNum; 3 : result := @Data.PType; 4 : result := @Data.PSetting ; 5 : result := @Data.PPeriod; 6 : result := @Data.PPer_type; 7 : result := @Data.PStart; 8 : result := @Data.PStop; 9 : result := @Data.PStopStatus; 10 : result := @Data.PUserID; 11 : result := @Data.PDescription; 12 : result := @Data.PControlStatus; 13 : result := @Data.PControlMsg; 14 : result := @Data.PControlScanMsg; 15 : result := @Data.PImmediatePrint; 16 : result := @Data.PServerPrinter; end; end; function TTTSJOBTable.GetPPer_Type: Integer; begin result := DFPer_Type.Value; end; function TTTSJOBTable.GetPPeriod: String; begin result := DFPeriod.Value; end; procedure TTTSJOBTable.SetPPer_Type(const Value: Integer); begin DFPer_Type.Value := Value; end; procedure TTTSJOBTable.SetPPeriod(const Value: String); begin DFPeriod.Value := Value; end; function TTTSJOBTable.GetPSetting: String; begin result := DFSetting.Value; end; procedure TTTSJOBTable.SetPSetting(const Value: String); begin DFSetting.Value := Value; end; function TTTSJOBTable.GetPImmediatePrint: String; begin result := DFImmediatePrint.Value; end; function TTTSJOBTable.GetPServerPrinter: String; begin result := DFServerPrinter.Value; end; procedure TTTSJOBTable.SetPImmediatePrint(const Value: String); begin DFImmediatePrint.Value:= Value; end; procedure TTTSJOBTable.SetPServerPrinter(const Value: String); begin DFServerPrinter.Value := Value; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpBsiObjectIdentifiers; {$I ..\..\Include\CryptoLib.inc} interface uses ClpDerObjectIdentifier, ClpIDerObjectIdentifier; type TBsiObjectIdentifiers = class abstract(TObject) strict private /// <remarks>See https://www.bsi.bund.de/cae/servlet/contentblob/471398/publicationFile/30615/BSI-TR-03111_pdf.pdf</remarks> class var FIsBooted: Boolean; Fbsi_de, Fid_ecc, Fecdsa_plain_signatures, Fecdsa_plain_SHA1, Fecdsa_plain_SHA224, Fecdsa_plain_SHA256, Fecdsa_plain_SHA384, Fecdsa_plain_SHA512, Fecdsa_plain_RIPEMD160: IDerObjectIdentifier; class function Getbsi_de: IDerObjectIdentifier; static; inline; class function Getecdsa_plain_RIPEMD160: IDerObjectIdentifier; static; inline; class function Getecdsa_plain_SHA1: IDerObjectIdentifier; static; inline; class function Getecdsa_plain_SHA224: IDerObjectIdentifier; static; inline; class function Getecdsa_plain_SHA256: IDerObjectIdentifier; static; inline; class function Getecdsa_plain_SHA384: IDerObjectIdentifier; static; inline; class function Getecdsa_plain_SHA512: IDerObjectIdentifier; static; inline; class function Getecdsa_plain_signatures: IDerObjectIdentifier; static; inline; class function Getid_ecc: IDerObjectIdentifier; static; inline; class constructor BsiObjectIdentifiers(); public class property bsi_de: IDerObjectIdentifier read Getbsi_de; class property id_ecc: IDerObjectIdentifier read Getid_ecc; class property ecdsa_plain_signatures: IDerObjectIdentifier read Getecdsa_plain_signatures; class property ecdsa_plain_SHA1: IDerObjectIdentifier read Getecdsa_plain_SHA1; class property ecdsa_plain_SHA224: IDerObjectIdentifier read Getecdsa_plain_SHA224; class property ecdsa_plain_SHA256: IDerObjectIdentifier read Getecdsa_plain_SHA256; class property ecdsa_plain_SHA384: IDerObjectIdentifier read Getecdsa_plain_SHA384; class property ecdsa_plain_SHA512: IDerObjectIdentifier read Getecdsa_plain_SHA512; class property ecdsa_plain_RIPEMD160: IDerObjectIdentifier read Getecdsa_plain_RIPEMD160; class procedure Boot(); static; end; implementation { TBsiObjectIdentifiers } class procedure TBsiObjectIdentifiers.Boot; begin if not FIsBooted then begin Fbsi_de := TDerObjectIdentifier.Create('0.4.0.127.0.7'); // /* 0.4.0.127.0.7.1.1 */ Fid_ecc := Fbsi_de.Branch('1.1'); // /* 0.4.0.127.0.7.1.1.4.1 */ Fecdsa_plain_signatures := Fid_ecc.Branch('4.1'); // /* 0.4.0.127.0.7.1.1.4.1.1 */ Fecdsa_plain_SHA1 := Fecdsa_plain_signatures.Branch('1'); // /* 0.4.0.127.0.7.1.1.4.1.2 */ Fecdsa_plain_SHA224 := Fecdsa_plain_signatures.Branch('2'); // /* 0.4.0.127.0.7.1.1.4.1.3 */ Fecdsa_plain_SHA256 := Fecdsa_plain_signatures.Branch('3'); // /* 0.4.0.127.0.7.1.1.4.1.4 */ Fecdsa_plain_SHA384 := Fecdsa_plain_signatures.Branch('4'); // /* 0.4.0.127.0.7.1.1.4.1.5 */ Fecdsa_plain_SHA512 := Fecdsa_plain_signatures.Branch('5'); // /* 0.4.0.127.0.7.1.1.4.1.6 */ Fecdsa_plain_RIPEMD160 := Fecdsa_plain_signatures.Branch('6'); FIsBooted := True; end; end; class constructor TBsiObjectIdentifiers.BsiObjectIdentifiers; begin TBsiObjectIdentifiers.Boot; end; class function TBsiObjectIdentifiers.Getbsi_de: IDerObjectIdentifier; begin result := Fbsi_de; end; class function TBsiObjectIdentifiers.Getecdsa_plain_RIPEMD160 : IDerObjectIdentifier; begin result := Fecdsa_plain_RIPEMD160; end; class function TBsiObjectIdentifiers.Getecdsa_plain_SHA1: IDerObjectIdentifier; begin result := Fecdsa_plain_SHA1; end; class function TBsiObjectIdentifiers.Getecdsa_plain_SHA224 : IDerObjectIdentifier; begin result := Fecdsa_plain_SHA224; end; class function TBsiObjectIdentifiers.Getecdsa_plain_SHA256 : IDerObjectIdentifier; begin result := Fecdsa_plain_SHA256; end; class function TBsiObjectIdentifiers.Getecdsa_plain_SHA384 : IDerObjectIdentifier; begin result := Fecdsa_plain_SHA384; end; class function TBsiObjectIdentifiers.Getecdsa_plain_SHA512 : IDerObjectIdentifier; begin result := Fecdsa_plain_SHA512; end; class function TBsiObjectIdentifiers.Getecdsa_plain_signatures : IDerObjectIdentifier; begin result := Fecdsa_plain_signatures; end; class function TBsiObjectIdentifiers.Getid_ecc: IDerObjectIdentifier; begin result := Fid_ecc; end; end.
unit CleanArch_EmbrConf.Core.UserCase.Impl.GetParkingLot; interface uses CleanArch_EmbrConf.Core.UserCase.Interfaces, CleanArch_EmbrConf.Core.Repository.Interfaces, CleanArch_EmbrConf.Core.Entity.Interfaces, System.JSON; type TGetParkingLot = class(TInterfacedObject, iGetParkingLot) private FParent: iParkingLotRepository; public constructor Create(Parent : iParkingLotRepository); destructor Destroy; override; class function New(Parent : iParkingLotRepository) : iGetParkingLot; function Execute(Code : String) : iParkingLot; end; implementation constructor TGetParkingLot.Create(Parent : iParkingLotRepository); begin FParent := Parent; end; destructor TGetParkingLot.Destroy; begin inherited; end; function TGetParkingLot.Execute(Code : String) : iParkingLot; begin Result := FParent.getParkingLot(code); end; class function TGetParkingLot.New(Parent : iParkingLotRepository) : iGetParkingLot; begin Result := Self.Create(Parent); end; end.
You must specify the -p option with the path to the policy file.
{-------------------------------------------------- Progressive Path Tracing --------------------------------------------------- This unit contains the TPathTracer class, which is the only class that directly interacts with the interface. It's responsible for managing the worker threads and interfacing with all the other classes. -------------------------------------------------------------------------------------------------------------------------------} unit PathTracer; interface uses Windows, SysUtils, Classes, Graphics, VectorMath, VectorTypes, SceneManager, Utils, Math, Camera, MaterialTypes; type { A global threadinfo structure sent to each worker thread. } TWorkerSettings = record PManager: PSceneManager; PCamera: PCamera; PData: Pointer; PFlag: Pointer; PSampleCount: Pointer; DataLength: Longword; Width, Height, Stride, Batch: Longword; end; { A worker thread, responsible for tracing rays over and over until hell freezes over (or the user gets bored). } TWorkerThread = class(TThread) private FWorkerSettings: TWorkerSettings; FWorkerIndex: Longword; public constructor Create(CreateSuspended: Boolean; AWorkerSettings: TWorkerSettings; AWorkerIndex: Longword); reintroduce; destructor Destroy; override; procedure Execute; override; end; { The main class which controls everything indirectly. } TPathTracer = class private FSamples: Double; FWidth, FHeight: Longword; FManager: TSceneManager; FCamera: TCamera; FWorkers: array of TWorkerThread; FData: array of TRGBColor; FSampleCount: array of Longword; FWorkerFlags: array of Boolean; function GetSuspended: Boolean; public constructor Create(CreateSuspended: Boolean; WorkerCount, Depth, BatchSize, Width, Height: Longword; SceneFile: String); reintroduce; destructor Destroy; override; procedure Acquire(Bitmap: TBitmap); procedure Suspend; procedure Resume; property SampleCount: Double read FSamples; property Suspended: Boolean read GetSuspended; end; implementation constructor TWorkerThread.Create(CreateSuspended: Boolean; AWorkerSettings: TWorkerSettings; AWorkerIndex: Longword); begin { Set some members. } inherited Create(CreateSuspended); FreeOnTerminate := True; Priority := tpLowest; FWorkerIndex := AWorkerIndex; FWorkerSettings := AWorkerSettings; end; destructor TWorkerThread.Destroy; begin { Indicate the thread died by setting its flag to true. } PBoolean(Ptr(Longword(FWorkerSettings.PFlag) + FWorkerIndex))^ := True; inherited; end; procedure TWorkerThread.Execute; Var I, J: Integer; N: Longword; U, V: Double; P: PRGBColor; Ray: TRay; begin { Set the first pixel. } N := FWorkerIndex; { Iterate over all the pixels one by one. } repeat { Retrieve the correct camera ray. } U := (N mod FWorkerSettings.Width) / (FWorkerSettings.Width - 1); V := (N div FWorkerSettings.Height) / (FWorkerSettings.Height - 1); Ray := FWorkerSettings.PCamera^.TraceCameraRay(1 - U, V); { Add a sample for this pixel. } for J := 0 to FWorkerSettings.Batch - 1 do for I := 0 to 399 do if FWorkerSettings.PManager^.Raytrace(Ray, I, FWorkerIndex) then begin P := PRGBColor(Ptr(Longword(FWorkerSettings.PData) + N * SizeOf(TRGBColor))); P^ := AddColor(P^, Spectrum[I]); end; { Increment the sample count. } Inc(PLongword(Ptr(Longword(FWorkerSettings.PSampleCount) + N * SizeOf(Longword)))^, FWorkerSettings.Batch); { Go to the next pixel. } Inc(N, FWorkerSettings.Stride); if N >= FWorkerSettings.Width * FWorkerSettings.Height then N := FWorkerIndex; until Terminated; end; constructor TPathTracer.Create(CreateSuspended: Boolean; WorkerCount, Depth, BatchSize, Width, Height: Longword; SceneFile: String); Var I: Integer; H, M, Len: Longword; P: Pointer; WorkerSettings: TWorkerSettings; begin { Set some members. } inherited Create; FSamples := NaN; FWidth := Width; FHeight := Height; SetLength(FWorkers, WorkerCount); SetLength(FWorkerFlags, WorkerCount); ZeroMemory(@FWorkerFlags[0], WorkerCount); { Open the scene file and read the camera position and target at the beginning. } P := MapFile(SceneFile, H, M, Len); FCamera := TCamera.Create(PVector(P)^, PVector(Ptr(Longword(P) + SizeOf(TVector)))^, FWidth / FHeight); IncPtr(P, SizeOf(TVector) * 2); { Create the scene manager, passing the scene file pointer. } FManager := TSceneManager.Create(Depth, WorkerCount, P); { Release the scene file. } DecPtr(P, SizeOf(TVector) * 2); UnmapFile(H, M, P); { Allocate the data array and set it to zero. } SetLength(FData, FWidth * FHeight); ZeroMemory(@FData[0], FWidth * FHeight * SizeOf(TRGBColor)); SetLength(FSampleCount, FWidth * FHeight); ZeroMemory(@FSampleCount[0], FWidth * FHeight * SizeOf(Longword)); { Fill in the threadinfo structure. } with WorkerSettings do begin PManager := @FManager; PCamera := @FCamera; PData := @FData[0]; PSampleCount := @FSampleCount[0]; PFlag := @FWorkerFlags[0]; DataLength := FWidth * FHeight * SizeOf(TRGBColor); Width := FWidth; Height := FHeight; Stride := Length(FWorkers); Batch := BatchSize; end; { Create all the threads. } for I := 0 to High(FWorkers) do FWorkers[I] := TWorkerThread.Create(CreateSuspended, WorkerSettings, I); end; destructor TPathTracer.Destroy; Var I: Integer; Flag: Boolean; begin try { First we resume, then terminate all threads. } for I := 0 to High(FWorkers) do begin FWorkers[I].Suspended := False; FWorkers[I].Terminate; end; { We wait until all threads have died, to avoid destroying shared objects that are still in use. } repeat Flag := True; for I := 0 to High(FWorkerFlags) do if not FWorkerFlags[I] then begin Flag := False; Break; end; until Flag; finally { At that point we free everything. } FCamera.Free; FManager.Free; inherited; end; end; { Suspends all the threads. } procedure TPathTracer.Suspend; Var I: Integer; begin for I := 0 to High(FWorkers) do FWorkers[I].Suspended := True; end; { Resumes all the threads. } procedure TPathTracer.Resume; Var I: Integer; begin for I := 0 to High(FWorkers) do FWorkers[I].Suspended := False; end; { Acquires the current render state into a bitmap. } procedure TPathTracer.Acquire(Bitmap: TBitmap); Var N: Longword; P: PRGBQUAD; E: Pointer; begin { Set the bitmap dimensions. } FSamples := 0; Bitmap.Width := FWidth; Bitmap.Height := FHeight; Bitmap.PixelFormat := pf32bit; { Fill in the bitmap. } P := Bitmap.ScanLine[Bitmap.Height - 1]; E := Ptr(Longword(P) + FWidth * FHeight * 4); N := 0; while P <> E do begin { Perform sample count calculation here (might as well). } FSamples := FSamples + FSampleCount[N] / (FWidth * FHeight); if FSampleCount[N] = 0 then begin P^.rgbRed := 0; P^.rgbGreen := 0; P^.rgbBlue := 0; end else begin { Gamma and spectral correction (the spectrum used isn't perfect and favours the red and green components, giving everything a yellow-ish hue). } P^.rgbRed := Round(Max(Min(Power(FData[N].R / FSampleCount[N], 1 / 2.2) / (220 / 198), 1), 0) * 255); P^.rgbGreen := Round(Max(Min(Power(FData[N].G / FSampleCount[N], 1 / 2.2) / (209 / 198), 1), 0) * 255); P^.rgbBlue := Round(Max(Min(Power(FData[N].B / FSampleCount[N], 1 / 2.2) / (166 / 198), 1), 0) * 255); end; Inc(N); Inc(P); end; end; { Getter which returns whether the threads are suspended or not. Since all threads are (hopefully) in the same state, and there is at least one worker thread, we can just check the first one. } function TPathTracer.GetSuspended: Boolean; begin Result := FWorkers[0].Suspended; end; end.
{ File: HIToolbox/ControlDefinitions.h Contains: Definitions of controls provided by the Control Manager Version: HIToolbox-219.4.81~2 Copyright: © 1999-2005 by Apple Computer, Inc., all rights reserved. Bugs?: For bug reports, consult the following page on the World Wide Web: http://www.freepascal.org/bugs.html } { Pascal Translation Updated: Peter N Lewis, <peter@stairways.com.au>, August 2005 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit ControlDefinitions; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,TextEdit,AXUIElement,AEDataModel,CFBase,Events,Quickdraw,Icons,CFData,CFDictionary,DateTimeUtils,Drag,TextCommon,Appearance,CarbonEvents,Controls,Lists,MacHelp,Menus,CFString; {$ALIGN MAC68K} { * ControlDefinitions.h * * Discussion: * System software supplies a variety of controls for your * applications to use. They are described herein. } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ Resource Types } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} const kControlTabListResType = FourCharCode('tab#'); { used for tab control (Appearance 1.0 and later)} kControlListDescResType = FourCharCode('ldes'); { used for list box control (Appearance 1.0 and later)} {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ Check Box Values } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} const kControlCheckBoxUncheckedValue = 0; kControlCheckBoxCheckedValue = 1; kControlCheckBoxMixedValue = 2; {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ Radio Button Values } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} const kControlRadioButtonUncheckedValue = 0; kControlRadioButtonCheckedValue = 1; kControlRadioButtonMixedValue = 2; {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ Pop-Up Menu Control Constants } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { Variant codes for the System 7 pop-up menu} const popupFixedWidth = 1 shl 0; popupVariableWidth = 1 shl 1; popupUseAddResMenu = 1 shl 2; popupUseWFont = 1 shl 3; { Menu label styles for the System 7 pop-up menu} const popupTitleBold = 1 shl 8; popupTitleItalic = 1 shl 9; popupTitleUnderline = 1 shl 10; popupTitleOutline = 1 shl 11; popupTitleShadow = 1 shl 12; popupTitleCondense = 1 shl 13; popupTitleExtend = 1 shl 14; popupTitleNoStyle = 1 shl 15; { Menu label justifications for the System 7 pop-up menu} const popupTitleLeftJust = $00000000; popupTitleCenterJust = $00000001; popupTitleRightJust = $000000FF; {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ Control Definition IDΥs } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { Standard System 7 procIDs} const pushButProc = 0; checkBoxProc = 1; radioButProc = 2; scrollBarProc = 16; popupMenuProc = 1008; {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ Control Part Codes } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} const kControlLabelPart = 1; kControlMenuPart = 2; kControlTrianglePart = 4; kControlEditTextPart = 5; { Appearance 1.0 and later} kControlPicturePart = 6; { Appearance 1.0 and later} kControlIconPart = 7; { Appearance 1.0 and later} kControlClockPart = 8; { Appearance 1.0 and later} kControlListBoxPart = 24; { Appearance 1.0 and later} kControlListBoxDoubleClickPart = 25; { Appearance 1.0 and later} kControlImageWellPart = 26; { Appearance 1.0 and later} kControlRadioGroupPart = 27; { Appearance 1.0.2 and later} kControlButtonPart = 10; kControlCheckBoxPart = 11; kControlRadioButtonPart = 11; kControlUpButtonPart = kAppearancePartUpButton; kControlDownButtonPart = kAppearancePartDownButton; kControlPageUpPart = kAppearancePartPageUpArea; kControlPageDownPart = kAppearancePartPageDownArea; kControlClockHourDayPart = 9; { Appearance 1.1 and later} kControlClockMinuteMonthPart = 10; { Appearance 1.1 and later} kControlClockSecondYearPart = 11; { Appearance 1.1 and later} kControlClockAMPMPart = 12; { Appearance 1.1 and later} kControlDataBrowserPart = 24; { CarbonLib 1.0 and later} kControlDataBrowserDraggedPart = 25; { CarbonLib 1.0 and later} {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ Control Types and IDΥs available only with Appearance 1.0 and later } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ BEVEL BUTTON INTERFACE (CDEF 2) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { Bevel buttons allow you to control the content type (pict/icon/etc.), the behavior } { (pushbutton/toggle/sticky), and the bevel size. You also have the option of } { attaching a menu to it. When a menu is present, you can specify which way the } { popup arrow is facing (down or right). } { This is all made possible by overloading the Min, Max, and Value parameters for the } { control, as well as adjusting the variant. Here's the breakdown of what goes where: } { Parameter What Goes Here } { ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ } { Min Hi Byte = Behavior, Lo Byte = content type. } { Max ResID for resource-based content types. } { Value MenuID to attach, 0 = no menu, please. } { The variant is broken down into two halfs. The low 2 bits control the bevel type. } { Bit 2 controls the popup arrow direction (if a menu is present) and bit 3 controls } { whether or not to use the control's owning window's font. } { Constants for all you need to put this together are below. The values for behaviors } { are set up so that you can simply add them to the content type and pass them into } { the Min parameter of NewControl. } { An example call: } { control = NewControl( window, &bounds, "\p", true, 0, kControlContentIconSuiteRes + } { kBehaviorToggles, myIconSuiteID, bevelButtonSmallBevelProc, } { 0L ); } { Attaching a menu: } { control = NewControl( window, &bounds, "\p", true, kMyMenuID, } { kControlContentIconSuiteRes, myIconSuiteID, bevelButtonSmallBevelProc + } { kBevelButtonMenuOnRight, 0L ); } { This will attach menu ID kMyMenuID to the button, with the popup arrow facing right.} { This also puts the menu up to the right of the button. You can also specify that a } { menu can have multiple items checked at once by adding kBehaviorMultiValueMenus } { into the Min parameter. If you do use multivalue menus, the GetBevelButtonMenuValue } { helper function will return the last item chosen from the menu, whether or not it } { was checked. } { NOTE: Bevel buttons with menus actually have *two* values. The value of the } { button (on/off), and the value of the menu. The menu value can be gotten } { with the GetBevelButtonMenuValue helper function. } { Handle-based Content } { ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ } { You can create your control and then set the content to an existing handle to an } { icon suite, etc. using the macros below. Please keep in mind that resource-based } { content is owned by the control, handle-based content is owned by you. The CDEF will} { not try to dispose of handle-based content. If you are changing the content type of } { the button on the fly, you must make sure that if you are replacing a handle- } { based content with a resource-based content to properly dispose of the handle, } { else a memory leak will ensue. } { Textual Content } { ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ } { Please note that if a bevel button gets its textual content from the title } { of the control. To alter the textual content of a bevel button, use the } { SetControlTitle[WithCFString] API. } { Bevel Button Proc IDs } const kControlBevelButtonSmallBevelProc = 32; kControlBevelButtonNormalBevelProc = 33; kControlBevelButtonLargeBevelProc = 34; { Add these variant codes to kBevelButtonSmallBevelProc to change the type of button } const kControlBevelButtonSmallBevelVariant = 0; kControlBevelButtonNormalBevelVariant = 1 shl 0; kControlBevelButtonLargeBevelVariant = 1 shl 1; kControlBevelButtonMenuOnRightVariant = 1 shl 2; { Bevel Thicknesses } type ControlBevelThickness = UInt16; const kControlBevelButtonSmallBevel = 0; kControlBevelButtonNormalBevel = 1; kControlBevelButtonLargeBevel = 2; { Behaviors of bevel buttons. These are set up so you can add } { them together with the content types. } const kControlBehaviorPushbutton = 0; kControlBehaviorToggles = $0100; kControlBehaviorSticky = $0200; kControlBehaviorSingleValueMenu = 0; kControlBehaviorMultiValueMenu = $4000; { only makes sense when a menu is attached.} kControlBehaviorOffsetContents = $8000; { Behaviors for 1.0.1 or later } const kControlBehaviorCommandMenu = $2000; { menu holds commands, not choices. Overrides multi-value bit.} type ControlBevelButtonBehavior = UInt16; type ControlBevelButtonMenuBehavior = UInt16; { Bevel Button Menu Placements } type ControlBevelButtonMenuPlacement = UInt16; const kControlBevelButtonMenuOnBottom = 0; kControlBevelButtonMenuOnRight = 1 shl 2; { Control Kind Tag } const kControlKindBevelButton = FourCharCode('bevl'); { The HIObject class ID for the HIBevelButton class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIBevelButtonClassID CFSTRP('com.apple.HIBevelButton')} {$endc} { Creation API: Carbon Only } { * CreateBevelButtonControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateBevelButtonControl( window: WindowRef; const (*var*) boundsRect: Rect; title: CFStringRef; thickness: ControlBevelThickness; behavior: ControlBevelButtonBehavior; info: ControlButtonContentInfoPtr; menuID: SInt16; menuBehavior: ControlBevelButtonMenuBehavior; menuPlacement: ControlBevelButtonMenuPlacement; var outControl: ControlRef ): OSStatus; external name '_CreateBevelButtonControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Graphic Alignments } type ControlButtonGraphicAlignment = SInt16; const kControlBevelButtonAlignSysDirection = -1; { only left or right} kControlBevelButtonAlignCenter = 0; kControlBevelButtonAlignLeft = 1; kControlBevelButtonAlignRight = 2; kControlBevelButtonAlignTop = 3; kControlBevelButtonAlignBottom = 4; kControlBevelButtonAlignTopLeft = 5; kControlBevelButtonAlignBottomLeft = 6; kControlBevelButtonAlignTopRight = 7; kControlBevelButtonAlignBottomRight = 8; { Text Alignments } type ControlButtonTextAlignment = SInt16; const kControlBevelButtonAlignTextSysDirection = teFlushDefault; kControlBevelButtonAlignTextCenter = teCenter; kControlBevelButtonAlignTextFlushRight = teFlushRight; kControlBevelButtonAlignTextFlushLeft = teFlushLeft; { Text Placements } type ControlButtonTextPlacement = SInt16; const kControlBevelButtonPlaceSysDirection = -1; { if graphic on right, then on left} kControlBevelButtonPlaceNormally = 0; kControlBevelButtonPlaceToRightOfGraphic = 1; kControlBevelButtonPlaceToLeftOfGraphic = 2; kControlBevelButtonPlaceBelowGraphic = 3; kControlBevelButtonPlaceAboveGraphic = 4; { Data tags supported by the bevel button controls } const kControlBevelButtonContentTag = FourCharCode('cont'); { ButtonContentInfo} kControlBevelButtonTransformTag = FourCharCode('tran'); { IconTransformType} kControlBevelButtonTextAlignTag = FourCharCode('tali'); { ButtonTextAlignment} kControlBevelButtonTextOffsetTag = FourCharCode('toff'); { SInt16} kControlBevelButtonGraphicAlignTag = FourCharCode('gali'); { ButtonGraphicAlignment} kControlBevelButtonGraphicOffsetTag = FourCharCode('goff'); { Point} kControlBevelButtonTextPlaceTag = FourCharCode('tplc'); { ButtonTextPlacement} kControlBevelButtonMenuValueTag = FourCharCode('mval'); { SInt16} kControlBevelButtonMenuHandleTag = FourCharCode('mhnd'); { MenuRef} kControlBevelButtonMenuRefTag = FourCharCode('mhnd'); { MenuRef} kControlBevelButtonCenterPopupGlyphTag = FourCharCode('pglc'); { Boolean: true = center, false = bottom right} { These are tags in 1.0.1 or later } const kControlBevelButtonLastMenuTag = FourCharCode('lmnu'); { SInt16: menuID of last menu item selected from} kControlBevelButtonMenuDelayTag = FourCharCode('mdly'); { SInt32: ticks to delay before menu appears} { tags available with Appearance 1.1 or later } const { Boolean: True = if an icon of the ideal size for} { the button isn't available, scale a larger or} { smaller icon to the ideal size. False = don't} { scale; draw a smaller icon or clip a larger icon.} { Default is false. Only applies to IconSuites and} kControlBevelButtonScaleIconTag = FourCharCode('scal'); { IconRefs.} { tags available in Mac OS X and later } const kControlBevelButtonOwnedMenuRefTag = FourCharCode('omrf'); { MenuRef (control will dispose)} kControlBevelButtonKindTag = FourCharCode('bebk'); { ThemeButtonKind ( kTheme[Small,Medium,Large,Rounded]BevelButton )} { * Summary: * Tags available with Mac OS X 10.3 or later } const { * Passed data is an Boolean. Gets or sets whether or not the * associated menu is a multi-value menu or not. True means that the * menu can have multiple selections. } kControlBevelButtonIsMultiValueMenuTag = FourCharCode('mult'); { Helper routines are available only thru the shared library/glue. } { * GetBevelButtonMenuValue() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: in AppearanceLib 1.0 and later } function GetBevelButtonMenuValue( inButton: ControlRef; var outValue: SInt16 ): OSErr; external name '_GetBevelButtonMenuValue'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetBevelButtonMenuValue() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: in AppearanceLib 1.0 and later } function SetBevelButtonMenuValue( inButton: ControlRef; inValue: SInt16 ): OSErr; external name '_SetBevelButtonMenuValue'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetBevelButtonMenuHandle() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: in AppearanceLib 1.0 and later } function GetBevelButtonMenuHandle( inButton: ControlRef; var outHandle: MenuHandle ): OSErr; external name '_GetBevelButtonMenuHandle'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) function GetBevelButtonMenuRef__NAME__GetBevelButtonMenuHandle( possibleWindow: WindowRef ): Boolean; external name '_GetBevelButtonMenuRef__NAME__GetBevelButtonMenuHandle'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetBevelButtonContentInfo() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: in AppearanceLib 1.0 and later } function GetBevelButtonContentInfo( inButton: ControlRef; outContent: ControlButtonContentInfoPtr ): OSErr; external name '_GetBevelButtonContentInfo'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetBevelButtonContentInfo() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: in AppearanceLib 1.0 and later } function SetBevelButtonContentInfo( inButton: ControlRef; inContent: ControlButtonContentInfoPtr ): OSErr; external name '_SetBevelButtonContentInfo'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetBevelButtonTransform() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: in AppearanceLib 1.0 and later } function SetBevelButtonTransform( inButton: ControlRef; transform: IconTransformType ): OSErr; external name '_SetBevelButtonTransform'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetBevelButtonGraphicAlignment() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: in AppearanceLib 1.0 and later } function SetBevelButtonGraphicAlignment( inButton: ControlRef; inAlign: ControlButtonGraphicAlignment; inHOffset: SInt16; inVOffset: SInt16 ): OSErr; external name '_SetBevelButtonGraphicAlignment'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetBevelButtonTextAlignment() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: in AppearanceLib 1.0 and later } function SetBevelButtonTextAlignment( inButton: ControlRef; inAlign: ControlButtonTextAlignment; inHOffset: SInt16 ): OSErr; external name '_SetBevelButtonTextAlignment'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetBevelButtonTextPlacement() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: in AppearanceLib 1.0 and later } function SetBevelButtonTextPlacement( inButton: ControlRef; inWhere: ControlButtonTextPlacement ): OSErr; external name '_SetBevelButtonTextPlacement'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ SLIDER (CDEF 3) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { There are several variants that control the behavior of the slider control. Any } { combination of the following three constants can be added to the basic CDEF ID } { (kSliderProc). } { Variants: } { kSliderLiveFeedback Slider does not use "ghosted" indicator when tracking. } { ActionProc is called (set via SetControlAction) as the } { indicator is dragged. The value is updated so that the } { actionproc can adjust some other property based on the } { value each time the action proc is called. If no action } { proc is installed, it reverts to the ghost indicator. } { kSliderHasTickMarks Slider is drawn with 'tick marks'. The control } { rectangle must be large enough to accomidate the tick } { marks. } { kSliderReverseDirection Slider thumb points in opposite direction than normal. } { If the slider is vertical, the thumb will point to the } { left, if the slider is horizontal, the thumb will point } { upwards. } { kSliderNonDirectional This option overrides the kSliderReverseDirection and } { kSliderHasTickMarks variants. It creates an indicator } { which is rectangular and doesn't point in any direction } { like the normal indicator does. } { Mac OS X has a "Scroll to here" option in the General pane of System Preferences } { which allows users to click in the page up/down regions of a slider and have the } { thumb/indicator jump directly to the clicked position, which alters the value of } { the slider and moves any associated content appropriately. As long as the mouse } { button is held down, the click is treated as though the user had clicked in the } { thumb/indicator in the first place. } { If you want the sliders in your application to work with the "Scroll to here" } { option, you must do the following: } { 1. Create live-tracking sliders, not sliders that show a "ghost" thumb when you } { click on it. You can request live-tracking sliders by passing true in the } { liveTracking parameter to CreateSliderControl. If you create sliders with } { NewControl, use the kControlSliderLiveFeedback variant. } { 2. Write an appropriate ControlActionProc and associate it with your slider via } { the SetControlAction API. This allows your application to update its content } { appropriately when the live-tracking slider is clicked. } { 3. When calling HandleControlClick or TrackControl, pass -1 in the action proc } { parameter. This is a request for the Control Manager to use the action proc you } { associated with your control in step 2. If you rely on the standard window event } { handler to do your control tracking, this step is handled for you automatically. } { Slider proc ID and variants } const kControlSliderProc = 48; kControlSliderLiveFeedback = 1 shl 0; kControlSliderHasTickMarks = 1 shl 1; kControlSliderReverseDirection = 1 shl 2; kControlSliderNonDirectional = 1 shl 3; { Slider Orientation } type ControlSliderOrientation = UInt16; const kControlSliderPointsDownOrRight = 0; kControlSliderPointsUpOrLeft = 1; kControlSliderDoesNotPoint = 2; { Control Kind Tag } const kControlKindSlider = FourCharCode('sldr'); { The HIObject class ID for the HISlider class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHISliderClassID CFSTRP('com.apple.HISlider')} {$endc} { Creation API: Carbon Only } { * CreateSliderControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateSliderControl( window: WindowRef; const (*var*) boundsRect: Rect; value: SInt32; minimum: SInt32; maximum: SInt32; orientation: ControlSliderOrientation; numTickMarks: UInt16; liveTracking: Boolean; liveTrackingProc: ControlActionUPP; var outControl: ControlRef ): OSStatus; external name '_CreateSliderControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ DISCLOSURE TRIANGLE (CDEF 4) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { This control can be used as either left or right facing. It can also handle its own } { tracking if you wish. This means that when the 'autotoggle' variant is used, if the } { user clicks the control, it's state will change automatically from open to closed } { and vice-versa depending on its initial state. After a successful call to Track- } { Control, you can just check the current value to see what state it was switched to. } { Triangle proc IDs } const kControlTriangleProc = 64; kControlTriangleLeftFacingProc = 65; kControlTriangleAutoToggleProc = 66; kControlTriangleLeftFacingAutoToggleProc = 67; type ControlDisclosureTriangleOrientation = UInt16; const kControlDisclosureTrianglePointDefault = 0; { points right on a left-to-right script system (Mac OS X and later or CarbonLib 1.5 and later only)} kControlDisclosureTrianglePointRight = 1; kControlDisclosureTrianglePointLeft = 2; { Control Kind Tag } const kControlKindDisclosureTriangle = FourCharCode('dist'); { The HIObject class ID for the HIDisclosureTriangle class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIDisclosureTriangleClassID CFSTRP('com.apple.HIDisclosureTriangle')} {$endc} { * CreateDisclosureTriangleControl() * * Summary: * Creates a Disclosure Triangle control at a specific position in * the specified window. * * Discussion: * Disclosure Triangles are small controls that give the user a way * to toggle the visibility of information or other user interface. * When information is in a hidden state, a Disclosure Triangle is * considered "closed" and should point to the right (or sometimes * to the left). When the user clicks on it, the Disclosure Triangle * rotates downwards into the "open" state. The application should * repond by revealing the appropriate information or interface. On * Mac OS X, a root control will be created for the window if one * does not already exist. If a root control exists for the window, * the Disclosure Triangle control will be embedded into it. * * Mac OS X threading: * Not thread safe * * Parameters: * * inWindow: * The WindowRef into which the Disclosure Triangle will be * created. * * inBoundsRect: * The desired position (in coordinates local to the window's * port) for the Disclosure Triangle. * * inOrientation: * The direction the Disclosure Triangle should point when it is * "closed". Passing kControlDisclosureTrianglePointDefault is * only legal as of Mac OS X and CarbonLib 1.5. * * inTitle: * The title for the Disclosure Triangle. The title will only be * displayed if the inDrawTitle parameter is true. Title display * only works on Mac OS X. * * inInitialValue: * The starting value determines whether the Disclosure Triangle * is initially in its "open" or "closed" state. The value 0 * represents the "closed" state and 1 represents the "open" state. * * inDrawTitle: * A Boolean indicating whether the Disclosure Triangle should * draw its title next to the widget. Title display only works on * Mac OS X. * * inAutoToggles: * A Boolean indicating whether the Disclosure Triangle should * change its own value (from "open" to "closed" and vice-versa) * automatically when it is clicked on. * * outControl: * On successful output, outControl will contain a reference to * the Disclosure Triangle control. * * Result: * An OSStatus code indicating success or failure. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateDisclosureTriangleControl( inWindow: WindowRef; const (*var*) inBoundsRect: Rect; inOrientation: ControlDisclosureTriangleOrientation; inTitle: CFStringRef; inInitialValue: SInt32; inDrawTitle: Boolean; inAutoToggles: Boolean; var outControl: ControlRef ): OSStatus; external name '_CreateDisclosureTriangleControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Tagged data supported by disclosure triangles } const kControlTriangleLastValueTag = FourCharCode('last'); { SInt16} { Helper routines are available only thru the shared library/glue. } { * SetDisclosureTriangleLastValue() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: in AppearanceLib 1.0 and later } function SetDisclosureTriangleLastValue( inTabControl: ControlRef; inValue: SInt16 ): OSErr; external name '_SetDisclosureTriangleLastValue'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ PROGRESS INDICATOR (CDEF 5) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { This CDEF implements both determinate and indeterminate progress bars. To switch, } { just use SetControlData to set the indeterminate flag to make it indeterminate. Any } { animation will automatically be handled by the toolbox on an event timer. } { We also use this same CDEF for Relevance bars. At this time this control does not } { idle. } { Progress Bar proc IDs } const kControlProgressBarProc = 80; kControlRelevanceBarProc = 81; { Control Kind Tag } const kControlKindProgressBar = FourCharCode('prgb'); kControlKindRelevanceBar = FourCharCode('relb'); { The HIObject class ID for the HIProgressBar class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIProgressBarClassID CFSTRP('com.apple.HIProgressBar')} {$endc} { Creation API: Carbon only } { * CreateProgressBarControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateProgressBarControl( window: WindowRef; const (*var*) boundsRect: Rect; value: SInt32; minimum: SInt32; maximum: SInt32; indeterminate: Boolean; var outControl: ControlRef ): OSStatus; external name '_CreateProgressBarControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { The HIObject class ID for the HIRelevanceBar class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIRelevanceBarClassID CFSTRP('com.apple.HIRelevanceBar')} {$endc} { * CreateRelevanceBarControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.0 and later * Non-Carbon CFM: not available } function CreateRelevanceBarControl( window: WindowRef; const (*var*) boundsRect: Rect; value: SInt32; minimum: SInt32; maximum: SInt32; var outControl: ControlRef ): OSStatus; external name '_CreateRelevanceBarControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Tagged data supported by progress bars } const kControlProgressBarIndeterminateTag = FourCharCode('inde'); { Boolean} kControlProgressBarAnimatingTag = FourCharCode('anim'); { Boolean} {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ LITTLE ARROWS (CDEF 6) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { This control implements the little up and down arrows you'd see in the Memory } { control panel for adjusting the cache size. } { Little Arrows proc IDs } const kControlLittleArrowsProc = 96; { Control Kind Tag } const kControlKindLittleArrows = FourCharCode('larr'); { * Summary: * Tags available with Mac OS X 10.3 or later } const { * Passed data is an SInt32. Gets or sets the increment value of the * control. } kControlLittleArrowsIncrementValueTag = FourCharCode('incr'); { The HIObject class ID for the HILittleArrows class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHILittleArrowsClassID CFSTRP('com.apple.HILittleArrows')} {$endc} { Creation API: Carbon only } { * CreateLittleArrowsControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateLittleArrowsControl( window: WindowRef; const (*var*) boundsRect: Rect; value: SInt32; minimum: SInt32; maximum: SInt32; increment: SInt32; var outControl: ControlRef ): OSStatus; external name '_CreateLittleArrowsControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ CHASING ARROWS (CDEF 7) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { This control will automatically animate via an event loop timer. } { Chasing Arrows proc IDs } const kControlChasingArrowsProc = 112; { Control Kind Tag } const kControlKindChasingArrows = FourCharCode('carr'); { The HIObject class ID for the HIChasingArrows class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIChasingArrowsClassID CFSTRP('com.apple.HIChasingArrows')} {$endc} { Creation API: Carbon only } { * CreateChasingArrowsControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateChasingArrowsControl( window: WindowRef; const (*var*) boundsRect: Rect; var outControl: ControlRef ): OSStatus; external name '_CreateChasingArrowsControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Tagged data supported by the Chasing Arrows control } const kControlChasingArrowsAnimatingTag = FourCharCode('anim'); { Boolean} {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ TABS (CDEF 8) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { Tabs use an auxiliary resource (tab#) to hold tab information such as the tab name } { and an icon suite ID for each tab. } { The ID of the tab# resource that you wish to associate with a tab control should } { be passed in as the Value parameter of the control. If you are using GetNewControl, } { then the Value slot in the CNTL resource should have the ID of the 'tab#' resource } { on creation. } { Passing zero in for the tab# resource tells the control not to read in a tab# res. } { You can then use SetControlMaximum to add tabs, followed by a call to SetControlData} { with the kControlTabInfoTag, passing in a pointer to a ControlTabInfoRec. This sets } { the name and optionally an icon for a tab. Pass the 1-based tab index as the part } { code parameter to SetControlData to indicate the tab that you want to modify. } { Accessibility Notes: Those of you who wish to customize the accessibility } { information provided for individual tabs of a tabs control -- by handling various } { kEventClassAccessibility Carbon Events, by calling } { HIObjectSetAuxiliaryAccessibilityAttribute, etc. -- need to know how to interpret } { and/or build AXUIElementRefs that represent individual tabs. The AXUIElement } { representing an individual tab will/must be constructed using the tab control's } { ControlRef and the UInt64 identifier of the one-based index of the tab the element } { refers to. As usual, a UInt64 identifier of zero represents the tabs control as a } { whole. You must neither interpret nor create tab control elements whose identifiers } { are greater than the count of tabs in the tabs control. } { Tabs proc IDs } const kControlTabLargeProc = 128; { Large tab size, north facing } kControlTabSmallProc = 129; { Small tab size, north facing } kControlTabLargeNorthProc = 128; { Large tab size, north facing } kControlTabSmallNorthProc = 129; { Small tab size, north facing } kControlTabLargeSouthProc = 130; { Large tab size, south facing } kControlTabSmallSouthProc = 131; { Small tab size, south facing } kControlTabLargeEastProc = 132; { Large tab size, east facing } kControlTabSmallEastProc = 133; { Small tab size, east facing } kControlTabLargeWestProc = 134; { Large tab size, west facing } kControlTabSmallWestProc = 135; { Small tab size, west facing } { Tab Directions } type ControlTabDirection = UInt16; const kControlTabDirectionNorth = 0; kControlTabDirectionSouth = 1; kControlTabDirectionEast = 2; kControlTabDirectionWest = 3; { Tab Sizes } type ControlTabSize = UInt16; const kControlTabSizeLarge = kControlSizeNormal; kControlTabSizeSmall = kControlSizeSmall; kControlTabSizeMini = kControlSizeMini; { Control Tab Entry - used during creation } { Note that the client is responsible for allocating/providing } { the ControlButtonContentInfo and string storage for this } { structure. } type ControlTabEntry = record icon: ControlButtonContentInfoPtr; name: CFStringRef; enabled: Boolean; end; { Control Kind Tag } const kControlKindTabs = FourCharCode('tabs'); { The HIObject class ID for the HITabbedView class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHITabbedViewClassID CFSTRP('com.apple.HITabbedView')} {$endc} { Creation API: Carbon only } { * CreateTabsControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateTabsControl( window: WindowRef; const (*var*) boundsRect: Rect; size: ControlTabSize; direction: ControlTabDirection; numTabs: UInt16; const (*var*) tabArray: ControlTabEntry; var outControl: ControlRef ): OSStatus; external name '_CreateTabsControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Tagged data supported by tabs } const kControlTabContentRectTag = FourCharCode('rect'); { Rect} kControlTabEnabledFlagTag = FourCharCode('enab'); { Boolean} kControlTabFontStyleTag = kControlFontStyleTag; { ControlFontStyleRec} { New tags in 1.0.1 or later } const kControlTabInfoTag = FourCharCode('tabi'); { ControlTabInfoRec} { New tags in X 10.1 or later } const kControlTabImageContentTag = FourCharCode('cont'); { ControlButtonContentInfo} const kControlTabInfoVersionZero = 0; { ControlTabInfoRec} kControlTabInfoVersionOne = 1; { ControlTabInfoRecV1} type ControlTabInfoRecPtr = ^ControlTabInfoRec; ControlTabInfoRec = record version: SInt16; { version of this structure.} iconSuiteID: SInt16; { icon suite to use. Zero indicates no icon} name: Str255; { name to be displayed on the tab} end; type ControlTabInfoRecV1Ptr = ^ControlTabInfoRecV1; ControlTabInfoRecV1 = record version: SInt16; { version of this structure. == kControlTabInfoVersionOne} iconSuiteID: SInt16; { icon suite to use. Zero indicates no icon} name: CFStringRef; { name to be displayed on the tab. Will be retained so caller} { should always release it.} end; { Helper routines are available only thru the shared library/glue. } { * GetTabContentRect() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: in AppearanceLib 1.0 and later } function GetTabContentRect( inTabControl: ControlRef; var outContentRect: Rect ): OSErr; external name '_GetTabContentRect'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetTabEnabled() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: in AppearanceLib 1.0 and later } function SetTabEnabled( inTabControl: ControlRef; inTabToHilite: SInt16; inEnabled: Boolean ): OSErr; external name '_SetTabEnabled'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ VISUAL SEPARATOR (CDEF 9) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { Separator lines determine their orientation (horizontal or vertical) automatically } { based on the relative height and width of their contrlRect. } { Visual separator proc IDs } const kControlSeparatorLineProc = 144; { Control Kind Tag } const kControlKindSeparator = FourCharCode('sepa'); { The HIObject class ID for the HIVisualSeparator class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIVisualSeparatorClassID CFSTRP('com.apple.HIVisualSeparator')} {$endc} { Creation API: Carbon only } { * CreateSeparatorControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateSeparatorControl( window: WindowRef; const (*var*) boundsRect: Rect; var outControl: ControlRef ): OSStatus; external name '_CreateSeparatorControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ GROUP BOX (CDEF 10) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { The group box CDEF can be use in several ways. It can have no title, a text title, } { a check box as the title, or a popup button as a title. There are two versions of } { group boxes, primary and secondary, which look slightly different. } { Group Box proc IDs } const kControlGroupBoxTextTitleProc = 160; kControlGroupBoxCheckBoxProc = 161; kControlGroupBoxPopupButtonProc = 162; kControlGroupBoxSecondaryTextTitleProc = 164; kControlGroupBoxSecondaryCheckBoxProc = 165; kControlGroupBoxSecondaryPopupButtonProc = 166; { Control Kind Tag } const kControlKindGroupBox = FourCharCode('grpb'); kControlKindCheckGroupBox = FourCharCode('cgrp'); kControlKindPopupGroupBox = FourCharCode('pgrp'); { The HIObject class ID for the HIGroupBox class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIGroupBoxClassID CFSTRP('com.apple.HIGroupBox')} {$endc} { The HIObject class ID for the HICheckBoxGroup class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHICheckBoxGroupClassID CFSTRP('com.apple.HICheckBoxGroup')} {$endc} { Creation APIs: Carbon only } { * CreateGroupBoxControl() * * Summary: * Creates a group box control. * * Mac OS X threading: * Not thread safe * * Parameters: * * window: * The window that should contain the control. * * boundsRect: * The bounding box of the control. * * title: * The title of the control. * * primary: * Whether to create a primary or secondary group box. * * outControl: * On exit, contains the new control. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateGroupBoxControl( window: WindowRef; const (*var*) boundsRect: Rect; title: CFStringRef; primary: Boolean; var outControl: ControlRef ): OSStatus; external name '_CreateGroupBoxControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * CreateCheckGroupBoxControl() * * Summary: * Creates a group box control that has a check box as its title. * * Mac OS X threading: * Not thread safe * * Parameters: * * window: * The window that should contain the control. * * boundsRect: * The bounding box of the control. * * title: * The title of the control (used as the title of the check box). * * initialValue: * The initial value of the check box. * * primary: * Whether to create a primary or secondary group box. * * autoToggle: * Whether to create an auto-toggling check box. Auto-toggling * check box titles are only supported on Mac OS X; this parameter * must be false when used with CarbonLib. * * outControl: * On exit, contains the new control. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateCheckGroupBoxControl( window: WindowRef; const (*var*) boundsRect: Rect; title: CFStringRef; initialValue: SInt32; primary: Boolean; autoToggle: Boolean; var outControl: ControlRef ): OSStatus; external name '_CreateCheckGroupBoxControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * CreatePopupGroupBoxControl() * * Summary: * Creates a group box control that has a popup button as its title. * * Mac OS X threading: * Not thread safe * * Parameters: * * window: * The window that should contain the control. * * boundsRect: * The bounding box of the control. * * title: * The title of the control (used as the title of the popup * button). * * primary: * Whether to create a primary or secondary group box. * * menuID: * The menu ID of the menu to be displayed by the popup button. * * variableWidth: * Whether the popup button should have a variable-width title. * Fixed-width titles are only supported by Mac OS X; this * parameter must be true when used with CarbonLib. * * titleWidth: * The width in pixels of the popup button title. * * titleJustification: * The justification of the popup button title. Use one of the * TextEdit justification constants here (teFlushDefault, * teCenter, teFlushRight, or teFlushLeft). * * titleStyle: * The QuickDraw text style of the popup button title. * * outControl: * On exit, contains the new control. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreatePopupGroupBoxControl( window: WindowRef; const (*var*) boundsRect: Rect; title: CFStringRef; primary: Boolean; menuID: SInt16; variableWidth: Boolean; titleWidth: SInt16; titleJustification: SInt16; titleStyle: Style; var outControl: ControlRef ): OSStatus; external name '_CreatePopupGroupBoxControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Tagged data supported by group box } const kControlGroupBoxMenuHandleTag = FourCharCode('mhan'); { MenuRef (popup title only)} kControlGroupBoxMenuRefTag = FourCharCode('mhan'); { MenuRef (popup title only)} kControlGroupBoxFontStyleTag = kControlFontStyleTag; { ControlFontStyleRec} { tags available with Appearance 1.1 or later } const kControlGroupBoxTitleRectTag = FourCharCode('trec'); { Rect. Rectangle that the title text/control is drawn in. (get only)} { * Summary: * Tags available with Mac OS X 10.3 or later } const { * Passed data is a Rect. Returns the full rectangle that content is * drawn in (get only). This is slightly different than the content * region, as it also includes the frame drawn around the content. } kControlGroupBoxFrameRectTag = FourCharCode('frec'); {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ IMAGE WELL (CDEF 11) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { Image Wells allow you to control the content type (pict/icon/etc.) shown in the } { well. } { This is made possible by overloading the Min and Value parameters for the control. } { Parameter What Goes Here } { ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ } { Min content type (see constants for bevel buttons) } { Value Resource ID of content type, if resource-based. } { Handle-based Content } { ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ } { You can create your control and then set the content to an existing handle to an } { icon suite, etc. using the macros below. Please keep in mind that resource-based } { content is owned by the control, handle-based content is owned by you. The CDEF will} { not try to dispose of handle-based content. If you are changing the content type of } { the button on the fly, you must make sure that if you are replacing a handle- } { based content with a resource-based content to properly dispose of the handle, } { else a memory leak will ensue. } { Image Well proc IDs } const kControlImageWellProc = 176; { Control Kind Tag } const kControlKindImageWell = FourCharCode('well'); { The HIObject class ID for the HIImageWell class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIImageWellClassID CFSTRP('com.apple.HIImageWell')} {$endc} { Creation API: Carbon only } { * CreateImageWellControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateImageWellControl( window: WindowRef; const (*var*) boundsRect: Rect; const (*var*) info: ControlButtonContentInfo; var outControl: ControlRef ): OSStatus; external name '_CreateImageWellControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Tagged data supported by image wells } const kControlImageWellContentTag = FourCharCode('cont'); { ButtonContentInfo} kControlImageWellTransformTag = FourCharCode('tran'); { IconTransformType} kControlImageWellIsDragDestinationTag = FourCharCode('drag'); { Boolean} { Helper routines are available only thru the shared library/glue. } { * GetImageWellContentInfo() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: in AppearanceLib 1.0 and later } function GetImageWellContentInfo( inButton: ControlRef; outContent: ControlButtonContentInfoPtr ): OSErr; external name '_GetImageWellContentInfo'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetImageWellContentInfo() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: in AppearanceLib 1.0 and later } function SetImageWellContentInfo( inButton: ControlRef; inContent: ControlButtonContentInfoPtr ): OSErr; external name '_SetImageWellContentInfo'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetImageWellTransform() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: in AppearanceLib 1.0 and later } function SetImageWellTransform( inButton: ControlRef; inTransform: IconTransformType ): OSErr; external name '_SetImageWellTransform'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ POPUP ARROW (CDEF 12) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { The popup arrow CDEF is used to draw the small arrow normally associated with a } { popup control. The arrow can point in four directions, and a small or large version } { can be used. This control is provided to allow clients to draw the arrow in a } { normalized fashion which will take advantage of themes automatically. } { Popup Arrow proc IDs } const kControlPopupArrowEastProc = 192; kControlPopupArrowWestProc = 193; kControlPopupArrowNorthProc = 194; kControlPopupArrowSouthProc = 195; kControlPopupArrowSmallEastProc = 196; kControlPopupArrowSmallWestProc = 197; kControlPopupArrowSmallNorthProc = 198; kControlPopupArrowSmallSouthProc = 199; { Popup Arrow Orientations } const kControlPopupArrowOrientationEast = 0; kControlPopupArrowOrientationWest = 1; kControlPopupArrowOrientationNorth = 2; kControlPopupArrowOrientationSouth = 3; type ControlPopupArrowOrientation = UInt16; { Popup Arrow Size } const kControlPopupArrowSizeNormal = 0; kControlPopupArrowSizeSmall = 1; type ControlPopupArrowSize = UInt16; { Control Kind Tag } const kControlKindPopupArrow = FourCharCode('parr'); { * CreatePopupArrowControl() * * Summary: * Creates a popup arrow control. * * Mac OS X threading: * Not thread safe * * Parameters: * * window: * The window that should contain the control. May be NULL on 10.3 * and later. * * boundsRect: * The bounding box of the control. * * orientation: * The orientation of the control. * * size: * The size of the control. * * outControl: * On exit, contains the new control. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreatePopupArrowControl( window: WindowRef { can be NULL }; const (*var*) boundsRect: Rect; orientation: ControlPopupArrowOrientation; size: ControlPopupArrowSize; var outControl: ControlRef ): OSStatus; external name '_CreatePopupArrowControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ PLACARD (CDEF 14) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { Placard proc IDs } const kControlPlacardProc = 224; { Control Kind Tag } const kControlKindPlacard = FourCharCode('plac'); { The HIObject class ID for the HIPlacardView class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIPlacardViewClassID CFSTRP('com.apple.HIPlacardView')} {$endc} { * CreatePlacardControl() * * Summary: * Creates a placard control. * * Mac OS X threading: * Not thread safe * * Parameters: * * window: * The window that should contain the control. May be NULL on 10.3 * and later. * * boundsRect: * The bounding box of the control. * * outControl: * On exit, contains the new control. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreatePlacardControl( window: WindowRef { can be NULL }; const (*var*) boundsRect: Rect; var outControl: ControlRef ): OSStatus; external name '_CreatePlacardControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ CLOCK (CDEF 15) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { NOTE: You can specify more options in the Value paramter when creating the clock. } { See below. } { NOTE: Under Appearance 1.1, the clock control knows and returns more part codes. } { The new clock-specific part codes are defined with the other control parts. } { Besides these clock-specific parts, we also return kControlUpButtonPart } { and kControlDownButtonPart when they hit the up and down arrows. } { The new part codes give you more flexibility for focusing and hit testing. } { The original kControlClockPart is still valid. When hit testing, it means } { that some non-editable area of the clock's whitespace has been clicked. } { When focusing a currently unfocused clock, it changes the focus to the } { first part; it is the same as passing kControlFocusNextPart. When } { re-focusing a focused clock, it will not change the focus at all. } { Clock proc IDs } const kControlClockTimeProc = 240; kControlClockTimeSecondsProc = 241; kControlClockDateProc = 242; kControlClockMonthYearProc = 243; { Clock Types } type ControlClockType = UInt16; const kControlClockTypeHourMinute = 0; kControlClockTypeHourMinuteSecond = 1; kControlClockTypeMonthDayYear = 2; kControlClockTypeMonthYear = 3; { Clock Flags } { These flags can be passed into 'value' field on creation of the control. } { Value is set to 0 after control is created. } type ControlClockFlags = UInt32; const kControlClockFlagStandard = 0; { editable, non-live} kControlClockNoFlags = 0; kControlClockFlagDisplayOnly = 1; { add this to become non-editable} kControlClockIsDisplayOnly = 1; kControlClockFlagLive = 2; { automatically shows current time on idle. only valid with display only.} kControlClockIsLive = 2; { Control Kind Tag } const kControlKindClock = FourCharCode('clck'); { The HIObject class ID for the HIClock class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIClockViewClassID CFSTRP('com.apple.HIClock')} {$endc} { Creation API: Carbon only } { * CreateClockControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateClockControl( window: WindowRef; const (*var*) boundsRect: Rect; clockType: ControlClockType; clockFlags: ControlClockFlags; var outControl: ControlRef ): OSStatus; external name '_CreateClockControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Tagged data supported by clocks } const kControlClockLongDateTag = FourCharCode('date'); { LongDateRec} kControlClockFontStyleTag = kControlFontStyleTag; { ControlFontStyleRec} kControlClockAnimatingTag = FourCharCode('anim'); { Boolean} {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ USER PANE (CDEF 16) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { User panes have two primary purposes: to allow easy implementation of a custom } { control by the developer, and to provide a generic container for embedding other } { controls. } { In Carbon, with the advent of Carbon-event-based controls, you may find it easier } { to simply write a new control from scratch than to customize a user pane control. } { The set of callbacks provided by the user pane will not be extended to support } { new Control Manager features; instead, you should just write a real control. } { User panes do not, by default, support embedding. If you try to embed a control } { into a user pane, you will get back errControlIsNotEmbedder. You can make a user } { pane support embedding by passing the kControlSupportsEmbedding flag in the 'value' } { parameter when you create the control. } { User panes support the following overloaded control initialization options: } { Parameter What Goes Here } { ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ } { Value Control feature flags } { User Pane proc IDs } const kControlUserPaneProc = 256; { Control Kind Tag } const kControlKindUserPane = FourCharCode('upan'); { The HIObject class ID for the HIUserPane class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIUserPaneClassID CFSTRP('com.apple.HIUserPane')} {$endc} { Creation API: Carbon only } { * CreateUserPaneControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateUserPaneControl( window: WindowRef; const (*var*) boundsRect: Rect; features: UInt32; var outControl: ControlRef ): OSStatus; external name '_CreateUserPaneControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Tagged data supported by user panes } { Currently, they are all proc ptrs for doing things like drawing and hit testing, etc. } const kControlUserItemDrawProcTag = FourCharCode('uidp'); { UserItemUPP} kControlUserPaneDrawProcTag = FourCharCode('draw'); { ControlUserPaneDrawUPP} kControlUserPaneHitTestProcTag = FourCharCode('hitt'); { ControlUserPaneHitTestUPP} kControlUserPaneTrackingProcTag = FourCharCode('trak'); { ControlUserPaneTrackingUPP} kControlUserPaneIdleProcTag = FourCharCode('idle'); { ControlUserPaneIdleUPP} kControlUserPaneKeyDownProcTag = FourCharCode('keyd'); { ControlUserPaneKeyDownUPP} kControlUserPaneActivateProcTag = FourCharCode('acti'); { ControlUserPaneActivateUPP} kControlUserPaneFocusProcTag = FourCharCode('foci'); { ControlUserPaneFocusUPP} kControlUserPaneBackgroundProcTag = FourCharCode('back'); { ControlUserPaneBackgroundUPP} type ControlUserPaneDrawProcPtr = procedure( control: ControlRef; part: SInt16 ); type ControlUserPaneHitTestProcPtr = function( control: ControlRef; where: Point ): ControlPartCode; type ControlUserPaneTrackingProcPtr = function( control: ControlRef; startPt: Point; actionProc: ControlActionUPP ): ControlPartCode; type ControlUserPaneIdleProcPtr = procedure( control: ControlRef ); type ControlUserPaneKeyDownProcPtr = function( control: ControlRef; keyCode: SInt16; charCode: SInt16; modifiers: SInt16 ): ControlPartCode; type ControlUserPaneActivateProcPtr = procedure( control: ControlRef; activating: Boolean ); type ControlUserPaneFocusProcPtr = function( control: ControlRef; action: ControlFocusPart ): ControlPartCode; type ControlUserPaneBackgroundProcPtr = procedure( control: ControlRef; info: ControlBackgroundPtr ); type ControlUserPaneDrawUPP = ControlUserPaneDrawProcPtr; type ControlUserPaneHitTestUPP = ControlUserPaneHitTestProcPtr; type ControlUserPaneTrackingUPP = ControlUserPaneTrackingProcPtr; type ControlUserPaneIdleUPP = ControlUserPaneIdleProcPtr; type ControlUserPaneKeyDownUPP = ControlUserPaneKeyDownProcPtr; type ControlUserPaneActivateUPP = ControlUserPaneActivateProcPtr; type ControlUserPaneFocusUPP = ControlUserPaneFocusProcPtr; type ControlUserPaneBackgroundUPP = ControlUserPaneBackgroundProcPtr; { * NewControlUserPaneDrawUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } function NewControlUserPaneDrawUPP( userRoutine: ControlUserPaneDrawProcPtr ): ControlUserPaneDrawUPP; external name '_NewControlUserPaneDrawUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewControlUserPaneHitTestUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } function NewControlUserPaneHitTestUPP( userRoutine: ControlUserPaneHitTestProcPtr ): ControlUserPaneHitTestUPP; external name '_NewControlUserPaneHitTestUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewControlUserPaneTrackingUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } function NewControlUserPaneTrackingUPP( userRoutine: ControlUserPaneTrackingProcPtr ): ControlUserPaneTrackingUPP; external name '_NewControlUserPaneTrackingUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewControlUserPaneIdleUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } function NewControlUserPaneIdleUPP( userRoutine: ControlUserPaneIdleProcPtr ): ControlUserPaneIdleUPP; external name '_NewControlUserPaneIdleUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewControlUserPaneKeyDownUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } function NewControlUserPaneKeyDownUPP( userRoutine: ControlUserPaneKeyDownProcPtr ): ControlUserPaneKeyDownUPP; external name '_NewControlUserPaneKeyDownUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewControlUserPaneActivateUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } function NewControlUserPaneActivateUPP( userRoutine: ControlUserPaneActivateProcPtr ): ControlUserPaneActivateUPP; external name '_NewControlUserPaneActivateUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewControlUserPaneFocusUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } function NewControlUserPaneFocusUPP( userRoutine: ControlUserPaneFocusProcPtr ): ControlUserPaneFocusUPP; external name '_NewControlUserPaneFocusUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewControlUserPaneBackgroundUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } function NewControlUserPaneBackgroundUPP( userRoutine: ControlUserPaneBackgroundProcPtr ): ControlUserPaneBackgroundUPP; external name '_NewControlUserPaneBackgroundUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeControlUserPaneDrawUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } procedure DisposeControlUserPaneDrawUPP( userUPP: ControlUserPaneDrawUPP ); external name '_DisposeControlUserPaneDrawUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeControlUserPaneHitTestUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } procedure DisposeControlUserPaneHitTestUPP( userUPP: ControlUserPaneHitTestUPP ); external name '_DisposeControlUserPaneHitTestUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeControlUserPaneTrackingUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } procedure DisposeControlUserPaneTrackingUPP( userUPP: ControlUserPaneTrackingUPP ); external name '_DisposeControlUserPaneTrackingUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeControlUserPaneIdleUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } procedure DisposeControlUserPaneIdleUPP( userUPP: ControlUserPaneIdleUPP ); external name '_DisposeControlUserPaneIdleUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeControlUserPaneKeyDownUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } procedure DisposeControlUserPaneKeyDownUPP( userUPP: ControlUserPaneKeyDownUPP ); external name '_DisposeControlUserPaneKeyDownUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeControlUserPaneActivateUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } procedure DisposeControlUserPaneActivateUPP( userUPP: ControlUserPaneActivateUPP ); external name '_DisposeControlUserPaneActivateUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeControlUserPaneFocusUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } procedure DisposeControlUserPaneFocusUPP( userUPP: ControlUserPaneFocusUPP ); external name '_DisposeControlUserPaneFocusUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeControlUserPaneBackgroundUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } procedure DisposeControlUserPaneBackgroundUPP( userUPP: ControlUserPaneBackgroundUPP ); external name '_DisposeControlUserPaneBackgroundUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeControlUserPaneDrawUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } procedure InvokeControlUserPaneDrawUPP( control: ControlRef; part: SInt16; userUPP: ControlUserPaneDrawUPP ); external name '_InvokeControlUserPaneDrawUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeControlUserPaneHitTestUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } function InvokeControlUserPaneHitTestUPP( control: ControlRef; where: Point; userUPP: ControlUserPaneHitTestUPP ): ControlPartCode; external name '_InvokeControlUserPaneHitTestUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeControlUserPaneTrackingUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } function InvokeControlUserPaneTrackingUPP( control: ControlRef; startPt: Point; actionProc: ControlActionUPP; userUPP: ControlUserPaneTrackingUPP ): ControlPartCode; external name '_InvokeControlUserPaneTrackingUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeControlUserPaneIdleUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } procedure InvokeControlUserPaneIdleUPP( control: ControlRef; userUPP: ControlUserPaneIdleUPP ); external name '_InvokeControlUserPaneIdleUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeControlUserPaneKeyDownUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } function InvokeControlUserPaneKeyDownUPP( control: ControlRef; keyCode: SInt16; charCode: SInt16; modifiers: SInt16; userUPP: ControlUserPaneKeyDownUPP ): ControlPartCode; external name '_InvokeControlUserPaneKeyDownUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeControlUserPaneActivateUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } procedure InvokeControlUserPaneActivateUPP( control: ControlRef; activating: Boolean; userUPP: ControlUserPaneActivateUPP ); external name '_InvokeControlUserPaneActivateUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeControlUserPaneFocusUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } function InvokeControlUserPaneFocusUPP( control: ControlRef; action: ControlFocusPart; userUPP: ControlUserPaneFocusUPP ): ControlPartCode; external name '_InvokeControlUserPaneFocusUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeControlUserPaneBackgroundUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } procedure InvokeControlUserPaneBackgroundUPP( control: ControlRef; info: ControlBackgroundPtr; userUPP: ControlUserPaneBackgroundUPP ); external name '_InvokeControlUserPaneBackgroundUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ ₯ EDIT TEXT (CDEF 17) ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ } { Edit Text proc IDs } const kControlEditTextProc = 272; kControlEditTextPasswordProc = 274; { proc IDs available with Appearance 1.1 or later } const kControlEditTextInlineInputProc = 276; { Can't combine with the other variants} { Control Kind Tag } const kControlKindEditText = FourCharCode('etxt'); { * CreateEditTextControl() *** DEPRECATED *** * * Deprecated: * Use CreateEditUnicodeTextControl API instead. * * Summary: * Creates a new edit text control. * * Discussion: * This control is a legacy control. It is deprecated in favor of * the EditUnicodeText control, which handles Unicode and draws its * text using antialiasing. * * Mac OS X threading: * Not thread safe * * Parameters: * * window: * The window in which the control should be placed. May be NULL * in 10.3 and later. * * boundsRect: * The bounds of the control, in local coordinates of the window. * * text: * The text of the control. May be NULL. * * isPassword: * A Boolean indicating whether the field is to be used as a * password field. Passing false indicates that the field is to * display entered text normally. True means that the field will * be used as a password field and any text typed into the field * will be displayed only as bullets. * * useInlineInput: * A Boolean indicating whether or not the control is to accept * inline input. Pass true to to accept inline input, otherwise * pass false. * * style: * The control's font style, size, color, and so on. May be NULL. * * outControl: * On exit, contains the new control (if noErr is returned as the * result code). * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework but deprecated in 10.4 * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateEditTextControl( window: WindowRef; const (*var*) boundsRect: Rect; text: CFStringRef { can be NULL }; isPassword: Boolean; useInlineInput: Boolean; {const} style: ControlFontStyleRecPtr { can be NULL }; var outControl: ControlRef ): OSStatus; external name '_CreateEditTextControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4 *) { Tagged data supported by edit text } const kControlEditTextStyleTag = kControlFontStyleTag; { ControlFontStyleRec} kControlEditTextTextTag = FourCharCode('text'); { Buffer of chars - you supply the buffer} kControlEditTextTEHandleTag = FourCharCode('than'); { The TEHandle of the text edit record} kControlEditTextKeyFilterTag = kControlKeyFilterTag; kControlEditTextSelectionTag = FourCharCode('sele'); { ControlEditTextSelectionRec} kControlEditTextPasswordTag = FourCharCode('pass'); { The clear text password text} kControlEditTextCharCount = FourCharCode('chrc'); { Count of characters in the control's text} { tags available with Appearance 1.1 or later } const kControlEditTextKeyScriptBehaviorTag = FourCharCode('kscr'); { ControlKeyScriptBehavior. Defaults to "PrefersRoman" for password fields,} { or "AllowAnyScript" for non-password fields.} kControlEditTextLockedTag = FourCharCode('lock'); { Boolean. Locking disables editability.} kControlEditTextFixedTextTag = FourCharCode('ftxt'); { Like the normal text tag, but fixes inline input first} kControlEditTextValidationProcTag = FourCharCode('vali'); { ControlEditTextValidationUPP. Called when a key filter can't be: after cut, paste, etc.} kControlEditTextInlinePreUpdateProcTag = FourCharCode('prup'); { TSMTEPreUpdateUPP and TSMTEPostUpdateUpp. For use with inline input variant...} kControlEditTextInlinePostUpdateProcTag = FourCharCode('poup'); { ...The refCon parameter will contain the ControlRef.} { * Discussion: * EditText ControlData tags available with MacOSX and later. } const { * Extract the content of the edit text field as a CFString. Don't * forget that you own the returned CFStringRef and are responsible * for CFReleasing it. } kControlEditTextCFStringTag = FourCharCode('cfst'); { CFStringRef (Also available on CarbonLib 1.5)} { * Extract the content of the edit text field as a CFString, if it is * a password field. Don't forget that you own the returned * CFStringRef and are responsible for CFReleasing it. } kControlEditTextPasswordCFStringTag = FourCharCode('pwcf'); { CFStringRef} { Structure for getting the edit text selection } type ControlEditTextSelectionRecPtr = ^ControlEditTextSelectionRec; ControlEditTextSelectionRec = record selStart: SInt16; selEnd: SInt16; end; type ControlEditTextSelectionPtr = ControlEditTextSelectionRecPtr; type ControlEditTextValidationProcPtr = procedure( control: ControlRef ); type ControlEditTextValidationUPP = ControlEditTextValidationProcPtr; { * NewControlEditTextValidationUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } function NewControlEditTextValidationUPP( userRoutine: ControlEditTextValidationProcPtr ): ControlEditTextValidationUPP; external name '_NewControlEditTextValidationUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeControlEditTextValidationUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } procedure DisposeControlEditTextValidationUPP( userUPP: ControlEditTextValidationUPP ); external name '_DisposeControlEditTextValidationUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeControlEditTextValidationUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.0 and later * Non-Carbon CFM: available as macro/inline } procedure InvokeControlEditTextValidationUPP( control: ControlRef; userUPP: ControlEditTextValidationUPP ); external name '_InvokeControlEditTextValidationUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ STATIC TEXT (CDEF 18) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { Static Text proc IDs } const kControlStaticTextProc = 288; { Control Kind Tag } const kControlKindStaticText = FourCharCode('stxt'); { The HIObject class ID for the HIStaticTextView class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIStaticTextViewClassID CFSTRP('com.apple.HIStaticTextView')} {$endc} { Creation API: Carbon only } { * CreateStaticTextControl() * * Summary: * Creates a new static text control. * * Mac OS X threading: * Not thread safe * * Parameters: * * window: * The window in which the control should be placed. May be NULL * in 10.3 and later. * * boundsRect: * The bounds of the control, in local coordinates of the window. * * text: * The text of the control. May be NULL. * * style: * The control's font style, size, color, and so on. May be NULL. * * outControl: * On exit, contains the new control. * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateStaticTextControl( window: WindowRef { can be NULL }; const (*var*) boundsRect: Rect; text: CFStringRef { can be NULL }; {const} style: ControlFontStyleRecPtr { can be NULL }; var outControl: ControlRef ): OSStatus; external name '_CreateStaticTextControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * Summary: * Tagged data supported by the static text control } const { * Used to get or set the control's current text style. Data is of * type ControlFontStyleRec. Available with Appearance Manager 1.0 * (Mac OS 8.0) and later. } kControlStaticTextStyleTag = kControlFontStyleTag; { * Used to get or set the control's current text. Data is an array of * chars. Generally you should used GetControlDataSize to determine * the length of the text, and allocate a buffer of that length, * before calling GetControlData with this selector. Deprecated in * Carbon in favor of kControlStaticTextCFStringTag. Available with * Appearance Manager 1.0 (Mac OS 8.0) and later. } kControlStaticTextTextTag = FourCharCode('text'); { * Used to get the height of the control's text. May not be used with * SetControlData. Data is of type SInt16. Available with Appearance * Manager 1.0 (Mac OS 8.0) and later. } kControlStaticTextTextHeightTag = FourCharCode('thei'); { * Used to get or set the control's text truncation style. Data is of * type TruncCode; pass a truncation code of -1 to indication no * truncation. Available with Appearance Manager 1.1 (Mac OS 8.5) and * later. Truncation will not occur unless * kControlStaticTextIsMultilineTag is set to false. } kControlStaticTextTruncTag = FourCharCode('trun'); { * Used to get or set the control's current text. Data is of type * CFStringRef. When setting the text, the control will retain the * string, so you may release the string after calling * SetControlData; if the string is mutable, the control will make a * copy of the string, so any changes to the string after calling * SetControlData will not affect the control. When getting the text, * the control retains the string before returning it to you, so you * must release the string after you are done with it. Available in * CarbonLib 1.5 and Mac OS X 10.0 and later. } kControlStaticTextCFStringTag = FourCharCode('cfst'); { * Used to get or set whether the control draws its text in multiple * lines if the text is too wide for the control bounds. If false, * then the control always draws the text in a single line. Data is * of type Boolean. Available in Mac OS X 10.1 and later. } kControlStaticTextIsMultilineTag = FourCharCode('stim'); {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ PICTURE CONTROL (CDEF 19) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { Value parameter should contain the ID of the picture you wish to display when } { creating controls of this type. If you don't want the control tracked at all, use } { the 'no track' variant. } { Picture control proc IDs } const kControlPictureProc = 304; kControlPictureNoTrackProc = 305; { immediately returns kControlPicturePart} { Control Kind Tag } const kControlKindPicture = FourCharCode('pict'); { * CreatePictureControl() * * Summary: * Creates a picture control. * * Mac OS X threading: * Not thread safe * * Parameters: * * window: * The window that should contain the control. May be NULL on 10.3 * and later. * * boundsRect: * The bounding box of the control. * * content: * The descriptor for the picture you want the control to display. * * dontTrack: * A Boolean value indicating whether the control should hilite * when it is clicked on. False means hilite and track the mouse. * * outControl: * On exit, contains the new control. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreatePictureControl( window: WindowRef { can be NULL }; const (*var*) boundsRect: Rect; const (*var*) content: ControlButtonContentInfo; dontTrack: Boolean; var outControl: ControlRef ): OSStatus; external name '_CreatePictureControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Tagged data supported by picture controls } const kControlPictureHandleTag = FourCharCode('pich'); { PicHandle} {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ ICON CONTROL (CDEF 20) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { Value parameter should contain the ID of the ICON or cicn you wish to display when } { creating controls of this type. If you don't want the control tracked at all, use } { the 'no track' variant. } { Icon control proc IDs } const kControlIconProc = 320; kControlIconNoTrackProc = 321; { immediately returns kControlIconPart} kControlIconSuiteProc = 322; kControlIconSuiteNoTrackProc = 323; { immediately returns kControlIconPart} const { icon ref controls may have either an icon, color icon, icon suite, or icon ref.} { for data other than icon, you must set the data by passing a} { ControlButtonContentInfo to SetControlData} kControlIconRefProc = 324; kControlIconRefNoTrackProc = 325; { immediately returns kControlIconPart} { Control Kind Tag } const kControlKindIcon = FourCharCode('icon'); { The HIObject class ID for the HIIconView class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIIconViewClassID CFSTRP('com.apple.HIIconView')} {$endc} { * CreateIconControl() * * Summary: * Creates an Icon control at a specific position in the specified * window. * * Discussion: * Icon controls display an icon that (optionally) hilites when * clicked on. On Mac OS X, a root control will be created for the * window if one does not already exist. If a root control exists * for the window, the Icon control will be embedded into it. * * Mac OS X threading: * Not thread safe * * Parameters: * * inWindow: * The WindowRef into which the Icon control will be created. May * be NULL on 10.3 and later. * * inBoundsRect: * The desired position (in coordinates local to the window's * port) for the Icon control. * * inIconContent: * The descriptor for the icon you want the control to display. * Mac OS X and CarbonLib 1.5 (and beyond) support all of the icon * content types. Prior to CarbonLib 1.5, the only content types * that are properly respected are kControlContentIconSuiteRes, * kControlContentCIconRes, and kControlContentICONRes. * * inDontTrack: * A Boolean value indicating whether the control should hilite * when it is clicked on. False means hilite and track the mouse. * * outControl: * On successful output, outControl will contain a reference to * the Icon control. * * Result: * An OSStatus code indicating success or failure. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateIconControl( inWindow: WindowRef { can be NULL }; const (*var*) inBoundsRect: Rect; const (*var*) inIconContent: ControlButtonContentInfo; inDontTrack: Boolean; var outControl: ControlRef ): OSStatus; external name '_CreateIconControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Tagged data supported by icon controls } const kControlIconTransformTag = FourCharCode('trfm'); { IconTransformType} kControlIconAlignmentTag = FourCharCode('algn'); { IconAlignmentType} { Tags available with appearance 1.1 or later } const kControlIconResourceIDTag = FourCharCode('ires'); { SInt16 resource ID of icon to use} kControlIconContentTag = FourCharCode('cont'); { accepts a ControlButtonContentInfo} {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ WINDOW HEADER (CDEF 21) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { Window Header proc IDs } const kControlWindowHeaderProc = 336; { normal header} kControlWindowListViewHeaderProc = 337; { variant for list views - no bottom line} { Control Kind Tag } const kControlKindWindowHeader = FourCharCode('whed'); { * Summary: * Tags available with Mac OS X 10.3 or later } const { * Passed data is a Boolean. Set to true if the control is to draw * as a list header. } kControlWindowHeaderIsListHeaderTag = FourCharCode('islh'); { The HIObject class ID for the HIWindowHeaderView class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIWindowHeaderViewClassID CFSTRP('com.apple.HIWindowHeaderView')} {$endc} { Creation API: Carbon Only } { * CreateWindowHeaderControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateWindowHeaderControl( window: WindowRef; const (*var*) boundsRect: Rect; isListHeader: Boolean; var outControl: ControlRef ): OSStatus; external name '_CreateWindowHeaderControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ LIST BOX (CDEF 22) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { Lists use an auxiliary resource to define their format. The resource type used is } { 'ldes' and a definition for it can be found in Appearance.r. The resource ID for } { the ldes is passed in the 'value' parameter when creating the control. You may pass } { zero in value. This tells the List Box control to not use a resource. The list will } { be created with default values, and will use the standard LDEF (0). You can change } { the list by getting the list handle. You can set the LDEF to use by using the tag } { below (kControlListBoxLDEFTag) } { List Box proc IDs } const kControlListBoxProc = 352; kControlListBoxAutoSizeProc = 353; { Control Kind Tag } const kControlKindListBox = FourCharCode('lbox'); { Creation API: Carbon Only } { * CreateListBoxControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateListBoxControl( window: WindowRef; const (*var*) boundsRect: Rect; autoSize: Boolean; numRows: SInt16; numColumns: SInt16; horizScroll: Boolean; vertScroll: Boolean; cellHeight: SInt16; cellWidth: SInt16; hasGrowSpace: Boolean; const (*var*) listDef: ListDefSpec; var outControl: ControlRef ): OSStatus; external name '_CreateListBoxControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Tagged data supported by list box } const kControlListBoxListHandleTag = FourCharCode('lhan'); { ListHandle} kControlListBoxKeyFilterTag = kControlKeyFilterTag; { ControlKeyFilterUPP} kControlListBoxFontStyleTag = kControlFontStyleTag; { ControlFontStyleRec} { New tags in 1.0.1 or later } const kControlListBoxDoubleClickTag = FourCharCode('dblc'); { Boolean. Was last click a double-click?} kControlListBoxLDEFTag = FourCharCode('ldef'); { SInt16. ID of LDEF to use.} {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ PUSH BUTTON (CDEF 23) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { The new standard checkbox and radio button controls support a "mixed" value that } { indicates that the current setting contains a mixed set of on and off values. The } { control value used to display this indication is defined in Controls.h: } { kControlCheckBoxMixedValue = 2 } { Two new variants of the standard pushbutton have been added to the standard control } { suite that draw a color icon next to the control title. One variant draws the icon } { on the left side, the other draws it on the right side (when the system justifica- } { tion is right to left, these are reversed). } { When either of the icon pushbuttons are created, the contrlMax field of the control } { record is used to determine the ID of the 'cicn' resource drawn in the pushbutton. } { In addition, a push button can now be told to draw with a default outline using the } { SetControlData routine with the kControlPushButtonDefaultTag below. } { A push button may also be marked using the kControlPushButtonCancelTag. This has } { no visible representation, but does cause the button to play the CancelButton theme } { sound instead of the regular pushbutton theme sound when pressed. } { Theme Push Button/Check Box/Radio Button proc IDs } const kControlPushButtonProc = 368; kControlCheckBoxProc = 369; kControlRadioButtonProc = 370; kControlPushButLeftIconProc = 374; { Standard pushbutton with left-side icon} kControlPushButRightIconProc = 375; { Standard pushbutton with right-side icon} { Variants with Appearance 1.1 or later } const kControlCheckBoxAutoToggleProc = 371; kControlRadioButtonAutoToggleProc = 372; { Push Button Icon Alignments } type ControlPushButtonIconAlignment = UInt16; const kControlPushButtonIconOnLeft = 6; kControlPushButtonIconOnRight = 7; { Control Kind Tag } const kControlKindPushButton = FourCharCode('push'); kControlKindPushIconButton = FourCharCode('picn'); kControlKindRadioButton = FourCharCode('rdio'); kControlKindCheckBox = FourCharCode('cbox'); { The HIObject class ID for the HIPushButton class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIPushButtonClassID CFSTRP('com.apple.HIPushButton')} {$endc} { The HIObject class ID for the HICheckBox class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHICheckBoxClassID CFSTRP('com.apple.HICheckBox')} {$endc} { The HIObject class ID for the HIRadioButton class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIRadioButtonClassID CFSTRP('com.apple.HIRadioButton')} {$endc} { Creation APIs: Carbon Only } { * CreatePushButtonControl() * * Summary: * Creates a push button control. * * Mac OS X threading: * Not thread safe * * Parameters: * * window: * The window that should contain the control. May be NULL on 10.3 * and later. * * boundsRect: * The bounds of the control, in local coordinates of the window. * * title: * The control title. May be NULL. * * outControl: * On exit, contains the new control. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreatePushButtonControl( window: WindowRef; const (*var*) boundsRect: Rect; title: CFStringRef { can be NULL }; var outControl: ControlRef ): OSStatus; external name '_CreatePushButtonControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * CreatePushButtonWithIconControl() * * Summary: * Creates a push button control containing an icon or other * graphical content. * * Mac OS X threading: * Not thread safe * * Parameters: * * window: * The window that should contain the control. May be NULL on 10.3 * and later. * * boundsRect: * The bounds of the control, in local coordinates of the window. * * title: * The control title. May be NULL. * * icon: * The control graphic content. * * iconAlignment: * The alignment of the control graphic content. * * outControl: * On exit, contains the new control. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreatePushButtonWithIconControl( window: WindowRef; const (*var*) boundsRect: Rect; title: CFStringRef { can be NULL }; var icon: ControlButtonContentInfo; iconAlignment: ControlPushButtonIconAlignment; var outControl: ControlRef ): OSStatus; external name '_CreatePushButtonWithIconControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * CreateRadioButtonControl() * * Summary: * Creates a radio button control. * * Mac OS X threading: * Not thread safe * * Parameters: * * window: * The window that should contain the control. May be NULL on 10.3 * and later. * * boundsRect: * The bounds of the control, in local coordinates of the window. * * title: * The control title. May be NULL. * * initialValue: * The initial value of the control. Should be zero (off), one * (on), or two (mixed). The control is automatically given a * minimum value of zero and a maximum value of two. * * autoToggle: * Whether this control should have auto-toggle behavior. If true, * the control will automatically toggle between on and off states * when clicked. This parameter should be false if the control * will be embedded into a radio group control; in that case, the * radio group will handle setting the correct control value in * response to a click. * * outControl: * On exit, contains the new control. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateRadioButtonControl( window: WindowRef; const (*var*) boundsRect: Rect; title: CFStringRef { can be NULL }; initialValue: SInt32; autoToggle: Boolean; var outControl: ControlRef ): OSStatus; external name '_CreateRadioButtonControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * CreateCheckBoxControl() * * Summary: * Creates a checkbox control. * * Mac OS X threading: * Not thread safe * * Parameters: * * window: * The window that should contain the control. May be NULL on 10.3 * and later. * * boundsRect: * The bounds of the control, in local coordinates of the window. * * title: * The control title. May be NULL. * * initialValue: * The initial value of the control. Should be zero (off), one * (on), or two (mixed). The control is automatically given a * minimum value of zero and a maximum value of two. * * autoToggle: * Whether this control should have auto-toggle behavior. If true, * the control will automatically toggle between on and off states * when clicked. * * outControl: * On exit, contains the new control. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateCheckBoxControl( window: WindowRef; const (*var*) boundsRect: Rect; title: CFStringRef { can be NULL }; initialValue: SInt32; autoToggle: Boolean; var outControl: ControlRef ): OSStatus; external name '_CreateCheckBoxControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Tagged data supported by standard buttons } const kControlPushButtonDefaultTag = FourCharCode('dflt'); { default ring flag} kControlPushButtonCancelTag = FourCharCode('cncl'); { cancel button flag (1.1 and later)} {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ SCROLL BAR (CDEF 24) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { This is the new Appearance scroll bar. } { Mac OS X has a "Scroll to here" option in the General pane of System Preferences } { which allows users to click in the page up/down regions of a scroll bar and have } { the thumb/indicator jump directly to the clicked position, which alters the value } { of the scroll bar and moves the scrolled content appropriately. As long as the } { mouse button is held down, the click is treated as though the user had clicked in } { the thumb/indicator in the first place. } { If you want the scroll bars in your application to work with the "Scroll to here" } { option, you must do the following: } { 1. Create live-tracking scroll bars, not scroll bars that show a "ghost" thumb } { when you click on it. You can request live-tracking scroll bars by passing true } { in the liveTracking parameter to CreateScrollBarControl. If you create scroll bars } { with NewControl, use the kControlScrollBarLiveProc. } { 2. Write an appropriate ControlActionProc and associate it with your scroll bar } { via the SetControlAction API. This allows your application to update its content } { appropriately when the live-tracking scroll bar is clicked. } { 3. When calling HandleControlClick or TrackControl, pass -1 in the action proc } { parameter. This is a request for the Control Manager to use the action proc you } { associated with your control in step 2. If you rely on the standard window event } { handler to do your control tracking, this step is handled for you automatically. } { Theme Scroll Bar proc IDs } const kControlScrollBarProc = 384; { normal scroll bar} kControlScrollBarLiveProc = 386; { live scrolling variant} { Control Kind Tag } const kControlKindScrollBar = FourCharCode('sbar'); { The HIObject class ID for the HIScrollBar class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIScrollBarClassID CFSTRP('com.apple.HIScrollBar')} {$endc} { * CreateScrollBarControl() * * Summary: * Creates a scroll bar control. * * Discussion: * This creation API is available in Carbon only. * * Mac OS X threading: * Not thread safe * * Parameters: * * window: * The window that should contain the control. May be NULL on 10.3 * and later. * * boundsRect: * The bounding box of the control. * * value: * The initial value of the control. * * minimum: * The minimum value of the control. * * maximum: * The maximum value of the control. * * viewSize: * The size of the visible area of the scroll bar content. * * liveTracking: * A Boolean indicating whether or not live tracking is enabled * for this scroll bar. If set to true and a valid * liveTrackingProc is also passed in, the callback will be called * repeatedly as the thumb is moved during tracking. If set to * false, a semi-transparent thumb called a "ghost thumb" will * draw and no live tracking will occur. * * liveTrackingProc: * If liveTracking is on, a ControlActionUPP callback to be called * as the control live tracks. This callback is called repeatedly * as the scroll thumb is moved during tracking. * * outControl: * On exit, contains the new control. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateScrollBarControl( window: WindowRef; const (*var*) boundsRect: Rect; value: SInt32; minimum: SInt32; maximum: SInt32; viewSize: SInt32; liveTracking: Boolean; liveTrackingProc: ControlActionUPP; var outControl: ControlRef ): OSStatus; external name '_CreateScrollBarControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { These tags are available in Mac OS X or later } const kControlScrollBarShowsArrowsTag = FourCharCode('arro'); { Boolean whether or not to draw the scroll arrows} {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ POPUP BUTTON (CDEF 25) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { This is the new Appearance Popup Button. It takes the same variants and does the } { same overloading as the previous popup menu control. There are some differences: } { Passing in a menu ID of -12345 causes the popup not to try and get the menu from a } { resource. Instead, you can build the menu and later stuff the MenuRef field in } { the popup data information. } { You can pass -1 in the Max parameter to have the control calculate the width of the } { title on its own instead of guessing and then tweaking to get it right. It adds the } { appropriate amount of space between the title and the popup. } { Theme Popup Button proc IDs } const kControlPopupButtonProc = 400; kControlPopupFixedWidthVariant = 1 shl 0; kControlPopupVariableWidthVariant = 1 shl 1; kControlPopupUseAddResMenuVariant = 1 shl 2; kControlPopupUseWFontVariant = kControlUsesOwningWindowsFontVariant; { Control Kind Tag } const kControlKindPopupButton = FourCharCode('popb'); { The HIObject class ID for the HIPopupButton class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIPopupButtonClassID CFSTRP('com.apple.HIPopupButton')} {$endc} { * CreatePopupButtonControl() * * Summary: * Creates a popup button control. * * Mac OS X threading: * Not thread safe * * Parameters: * * window: * The window that should contain the control. May be NULL on 10.3 * and later. * * boundsRect: * The bounding box of the control. * * title: * The title of the control. * * menuID: * The ID of a menu that should be used by the control. A menu * with this ID should be inserted into the menubar with * InsertMenu(menu, kInsertHierarchicalMenu). You can also pass * -12345 to have the control delay its acquisition of a menu; in * this case, you can build the menu and later provide it to the * control with SetControlData and kControlPopupButtonMenuRefTag * or kControlPopupButtonOwnedMenuRefTag. * * variableWidth: * Whether the width of the control is allowed to vary according * to the width of the selected menu item text, or should remain * fixed to the original control bounds width. * * titleWidth: * The width of the title. * * titleJustification: * The justification of the title. * * titleStyle: * A QuickDraw style bitfield indicating the font style of the * title. * * outControl: * On exit, contains the new control. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreatePopupButtonControl( window: WindowRef { can be NULL }; const (*var*) boundsRect: Rect; title: CFStringRef; menuID: SInt16; variableWidth: Boolean; titleWidth: SInt16; titleJustification: SInt16; titleStyle: Style; var outControl: ControlRef ): OSStatus; external name '_CreatePopupButtonControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { These tags are available in 1.0.1 or later of Appearance } const kControlPopupButtonMenuHandleTag = FourCharCode('mhan'); { MenuRef} kControlPopupButtonMenuRefTag = FourCharCode('mhan'); { MenuRef} kControlPopupButtonMenuIDTag = FourCharCode('mnid'); { SInt16} { These tags are available in 1.1 or later of Appearance } const kControlPopupButtonExtraHeightTag = FourCharCode('exht'); { SInt16 - extra vertical whitespace within the button} kControlPopupButtonOwnedMenuRefTag = FourCharCode('omrf'); { MenuRef} { These tags are available in Mac OS X } const kControlPopupButtonCheckCurrentTag = FourCharCode('chck'); { Boolean - whether the popup puts a checkmark next to the current item (defaults to true)} {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ RADIO GROUP (CDEF 26) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { This control implements a radio group. It is an embedding control and can therefore } { only be used when a control hierarchy is established for its owning window. You } { should only embed radio buttons within it. As radio buttons are embedded into it, } { the group sets up its value, min, and max to represent the number of embedded items.} { The current value of the control is the index of the sub-control that is the current} { 'on' radio button. To get the current radio button control handle, you can use the } { control manager call GetIndSubControl, passing in the value of the radio group. } { Note that when creating radio buttons for use in a radio group control, you should } { not use the autoToggle version of the radio button. The radio group control will } { handling toggling the radio button values itself; auto-toggle radio buttons do not } { work properly in a radio group control on Mac OS 9. } { NOTE: This control is only available with Appearance 1.0.1. } { Radio Group Proc ID } const kControlRadioGroupProc = 416; { Control Kind Tag } const kControlKindRadioGroup = FourCharCode('rgrp'); { The HIObject class ID for the HIRadioGroup class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIRadioGroupClassID CFSTRP('com.apple.HIRadioGroup')} {$endc} { Creation API: Carbon Only } { * CreateRadioGroupControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateRadioGroupControl( window: WindowRef; const (*var*) boundsRect: Rect; var outControl: ControlRef ): OSStatus; external name '_CreateRadioGroupControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ SCROLL TEXT BOX (CDEF 27) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { This control implements a scrolling box of (non-editable) text. This is useful for } { credits in about boxes, etc. } { The standard version of this control has a scroll bar, but the autoscrolling } { variant does not. The autoscrolling variant needs two pieces of information to } { work: delay (in ticks) before the scrolling starts, and time (in ticks) between } { scrolls. It will scroll one pixel at a time, unless changed via SetControlData. } { Parameter What Goes Here } { ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ } { Value Resource ID of 'TEXT'/'styl' content. } { Min Scroll start delay (in ticks) . } { Max Delay (in ticks) between scrolls. } { NOTE: This control is only available with Appearance 1.1. } { Scroll Text Box Proc IDs } const kControlScrollTextBoxProc = 432; kControlScrollTextBoxAutoScrollProc = 433; { Control Kind Tag } const kControlKindScrollingTextBox = FourCharCode('stbx'); { Creation API: Carbon Only } { * CreateScrollingTextBoxControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateScrollingTextBoxControl( window: WindowRef; const (*var*) boundsRect: Rect; contentResID: SInt16; autoScroll: Boolean; delayBeforeAutoScroll: UInt32; delayBetweenAutoScroll: UInt32; autoScrollAmount: UInt16; var outControl: ControlRef ): OSStatus; external name '_CreateScrollingTextBoxControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Tagged data supported by Scroll Text Box } const kControlScrollTextBoxDelayBeforeAutoScrollTag = FourCharCode('stdl'); { UInt32 (ticks until autoscrolling starts)} kControlScrollTextBoxDelayBetweenAutoScrollTag = FourCharCode('scdl'); { UInt32 (ticks between scrolls)} kControlScrollTextBoxAutoScrollAmountTag = FourCharCode('samt'); { UInt16 (pixels per scroll) -- defaults to 1} kControlScrollTextBoxContentsTag = FourCharCode('tres'); { SInt16 (resource ID of 'TEXT'/'styl') -- write only!} kControlScrollTextBoxAnimatingTag = FourCharCode('anim'); { Boolean (whether the text box should auto-scroll)} {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ DISCLOSURE BUTTON } { (CDEF 30) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { The HIObject class ID for the HIDisclosureButton class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIDisclosureButtonClassID CFSTRP('com.apple.HIDisclosureButton')} {$endc} { * CreateDisclosureButtonControl() * * Summary: * Creates a new instance of the Disclosure Button Control. * * Discussion: * CreateDisclosureButtonControl is preferred over NewControl * because it allows you to specify the exact set of parameters * required to create the control without overloading parameter * semantics. The initial minimum of the Disclosure Button will be * kControlDisclosureButtonClosed, and the maximum will be * kControlDisclosureButtonDisclosed. * * Mac OS X threading: * Not thread safe * * Parameters: * * inWindow: * The WindowRef in which to create the control. * * inBoundsRect: * The bounding rectangle for the control. The height of the * control is fixed and the control will be centered vertically * within the rectangle you specify. * * inValue: * The initial value; either kControlDisclosureButtonClosed or * kControlDisclosureButtonDisclosed. * * inAutoToggles: * A boolean value indicating whether its value should change * automatically after tracking the mouse. * * outControl: * On successful exit, this will contain the new control. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.0 and later * Non-Carbon CFM: not available } function CreateDisclosureButtonControl( inWindow: WindowRef; const (*var*) inBoundsRect: Rect; inValue: SInt32; inAutoToggles: Boolean; var outControl: ControlRef ): OSStatus; external name '_CreateDisclosureButtonControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Control Kind Tag } const kControlKindDisclosureButton = FourCharCode('disb'); { * Discussion: * Disclosure Button Values } const { * The control be drawn suggesting a closed state. } kControlDisclosureButtonClosed = 0; { * The control will be drawn suggesting an open state. } kControlDisclosureButtonDisclosed = 1; {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ ROUND BUTTON } { (CDEF 31) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { * ControlRoundButtonSize * * Discussion: * Button Sizes } type ControlRoundButtonSize = SInt16; const { * A 20 pixel diameter button. } kControlRoundButtonNormalSize = kControlSizeNormal; { * A 25 pixel diameter button. } kControlRoundButtonLargeSize = kControlSizeLarge; { Data tags supported by the round button controls } const kControlRoundButtonContentTag = FourCharCode('cont'); { ControlButtonContentInfo} kControlRoundButtonSizeTag = kControlSizeTag; { ControlRoundButtonSize} { Control Kind Tag } const kControlKindRoundButton = FourCharCode('rndb'); { The HIObject class ID for the HIRoundButton class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIRoundButtonClassID CFSTRP('com.apple.HIRoundButton')} {$endc} { * CreateRoundButtonControl() * * Summary: * Creates a new instance of the Round Button Control. * * Discussion: * CreateRoundButtonControl is preferred over NewControl because it * allows you to specify the exact set of parameters required to * create the control without overloading parameter semantics. * * Mac OS X threading: * Not thread safe * * Parameters: * * inWindow: * The WindowRef in which to create the control. May be NULL in * 10.3 and later. * * inBoundsRect: * The bounding rectangle for the control. The height and width of * the control is fixed (specified by the ControlRoundButtonSize * parameter) and the control will be centered within the * rectangle you specify. * * inSize: * The button size; either kControlRoundButtonNormalSize or * kControlRoundButtonLargeSize. * * inContent: * Any optional content displayed in the button. Currently only * kControlContentIconRef is supported. May be NULL. * * outControl: * On successful exit, this will contain the new control. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.0 and later * Non-Carbon CFM: not available } function CreateRoundButtonControl( inWindow: WindowRef { can be NULL }; const (*var*) inBoundsRect: Rect; inSize: ControlRoundButtonSize; inContent: ControlButtonContentInfoPtr { can be NULL }; var outControl: ControlRef ): OSStatus; external name '_CreateRoundButtonControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ DATA BROWSER } { (CDEF 29) } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { This control implements a user interface component for browsing (optionally) } { hiearchical data structures. The browser supports multiple presentation styles } { including, but not limited to: } { kDataBrowserListView - items and item properties in } { multi-column (optionally outline) format } { kDataBrowserColumnView - in-place browsing using fixed navigation columns } { The browser manages all view styles through a single high-level interface. } { The high-level interface makes the following assumptions: } { - Items have unique 32-bit identifiers (0 is reserved) } { - Items have two kinds of named and typed properties: } { - Predefined attribute properties ( < 1024 ) } { (including some display properties) } { - Client-defined display properties ( >= 1024 ) } { - Some items are containers of other items } { - Items may be sorted by any property } { Because a browser doesn't know all details about the type of objects it manages, } { some implementation responsibility is best handled by its client. The client must } { provide a set of callback routines which define the item hierarchy and help to } { populate the browser with items. The client may also provide callbacks for handling } { custom data types and doing low-level event management. } { The API is subdivided into a "universal" set of routines that applies to all view } { styles, and a set of routines unique to each view style. kDataBrowserListView and } { kDataBrowserColumnView share an (internal) TableView abstract base class. The } { TableView formatting options and API applies to both of these view styles. } { NOTE: This control is only available with CarbonLib 1.1. } { NOTE: This control must be created with the CreateDataBrowserControl API in } { CarbonLib 1.1 through 1.4. In Mac OS X and CarbonLib 1.5 and later, you } { may use the control's procID (29) to create the control with NewControl } { or with a 'CNTL' resource. } { The HIObject class ID for the HIDataBrowser class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHIDataBrowserClassID CFSTRP('com.apple.HIDataBrowser')} {$endc} { Control Kind Tag } const kControlKindDataBrowser = FourCharCode('datb'); { Error Codes } const errDataBrowserNotConfigured = -4970; errDataBrowserItemNotFound = -4971; errDataBrowserItemNotAdded = -4975; errDataBrowserPropertyNotFound = -4972; errDataBrowserInvalidPropertyPart = -4973; errDataBrowserInvalidPropertyData = -4974; errDataBrowserPropertyNotSupported = -4979; { Return from DataBrowserGetSetItemDataProc } const { Generic Control Tags } kControlDataBrowserIncludesFrameAndFocusTag = FourCharCode('brdr'); { Boolean } kControlDataBrowserKeyFilterTag = kControlEditTextKeyFilterTag; kControlDataBrowserEditTextKeyFilterTag = kControlDataBrowserKeyFilterTag; kControlDataBrowserEditTextValidationProcTag = kControlEditTextValidationProcTag; { Data Browser View Styles } type DataBrowserViewStyle = OSType; const kDataBrowserNoView = FourCharCode('????'); { Error State } kDataBrowserListView = FourCharCode('lstv'); kDataBrowserColumnView = FourCharCode('clmv'); { Selection Flags } type DataBrowserSelectionFlags = UInt32; const kDataBrowserDragSelect = 1 shl 0; { Ε ListMgr lNoRect } kDataBrowserSelectOnlyOne = 1 shl 1; { Ε ListMgr lOnlyOne } kDataBrowserResetSelection = 1 shl 2; { Ε ListMgr lNoExtend } kDataBrowserCmdTogglesSelection = 1 shl 3; { Ε ListMgr lUseSense } kDataBrowserNoDisjointSelection = 1 shl 4; { Ε ListMgr lNoDisjoint } kDataBrowserAlwaysExtendSelection = 1 shl 5; { Ε ListMgr lExtendDrag } kDataBrowserNeverEmptySelectionSet = 1 shl 6; { Ε ListMgr lNoNilHilite } { Data Browser Sorting } type DataBrowserSortOrder = UInt16; const kDataBrowserOrderUndefined = 0; { Not currently supported } kDataBrowserOrderIncreasing = 1; kDataBrowserOrderDecreasing = 2; { Data Browser Item Management } type DataBrowserItemID = UInt32; DataBrowserItemIDPtr = ^DataBrowserItemID; const kDataBrowserNoItem = 0; { Reserved DataBrowserItemID } type DataBrowserItemState = UInt32; const kDataBrowserItemNoState = 0; kDataBrowserItemAnyState = $FFFFFFFF; kDataBrowserItemIsSelected = 1 shl 0; kDataBrowserContainerIsOpen = 1 shl 1; kDataBrowserItemIsDragTarget = 1 shl 2; { During a drag operation } { Options for use with RevealDataBrowserItem } type DataBrowserRevealOptions = UInt8; const kDataBrowserRevealOnly = 0; kDataBrowserRevealAndCenterInView = 1 shl 0; kDataBrowserRevealWithoutSelecting = 1 shl 1; { Set operations for use with SetDataBrowserSelectedItems } type DataBrowserSetOption = UInt32; const kDataBrowserItemsAdd = 0; { add specified items to existing set } kDataBrowserItemsAssign = 1; { assign destination set to specified items } kDataBrowserItemsToggle = 2; { toggle membership state of specified items } kDataBrowserItemsRemove = 3; { remove specified items from existing set } { Commands for use with MoveDataBrowserSelectionAnchor } type DataBrowserSelectionAnchorDirection = UInt32; const kDataBrowserSelectionAnchorUp = 0; kDataBrowserSelectionAnchorDown = 1; kDataBrowserSelectionAnchorLeft = 2; kDataBrowserSelectionAnchorRight = 3; { Edit menu command IDs for use with Enable/ExecuteDataBrowserEditCommand } type DataBrowserEditCommand = UInt32; const kDataBrowserEditMsgUndo = kHICommandUndo; kDataBrowserEditMsgRedo = kHICommandRedo; kDataBrowserEditMsgCut = kHICommandCut; kDataBrowserEditMsgCopy = kHICommandCopy; kDataBrowserEditMsgPaste = kHICommandPaste; kDataBrowserEditMsgClear = kHICommandClear; kDataBrowserEditMsgSelectAll = kHICommandSelectAll; { Notifications used in DataBrowserItemNotificationProcPtr } type DataBrowserItemNotification = UInt32; const kDataBrowserItemAdded = 1; { The specified item has been added to the browser } kDataBrowserItemRemoved = 2; { The specified item has been removed from the browser } kDataBrowserEditStarted = 3; { Starting an EditText session for specified item } kDataBrowserEditStopped = 4; { Stopping an EditText session for specified item } kDataBrowserItemSelected = 5; { Item has just been added to the selection set } kDataBrowserItemDeselected = 6; { Item has just been removed from the selection set } kDataBrowserItemDoubleClicked = 7; kDataBrowserContainerOpened = 8; { Container is open } kDataBrowserContainerClosing = 9; { Container is about to close (and will real soon now, y'all) } kDataBrowserContainerClosed = 10; { Container is closed (y'all come back now!) } kDataBrowserContainerSorting = 11; { Container is about to be sorted (lock any volatile properties) } kDataBrowserContainerSorted = 12; { Container has been sorted (you may release any property locks) } kDataBrowserUserToggledContainer = 16; { _User_ requested container open/close state to be toggled } kDataBrowserTargetChanged = 15; { The target has changed to the specified item } kDataBrowserUserStateChanged = 13; { The user has reformatted the view for the target } kDataBrowserSelectionSetChanged = 14; { The selection set has been modified (net result may be the same) } { * DataBrowserPropertyID * * Discussion: * Properties with values 0 through 1023 are reserved for Apple's * use. Values greater than or equal to 1024 are for client use. } type DataBrowserPropertyID = UInt32; const { Predefined attribute properties, optional & non-display unless otherwise stated } kDataBrowserItemNoProperty = 0; { The anti-property (no associated data) } kDataBrowserItemIsActiveProperty = 1; { Boolean typed data (defaults to true) } kDataBrowserItemIsSelectableProperty = 2; { Boolean typed data (defaults to true) } kDataBrowserItemIsEditableProperty = 3; { Boolean typed data (defaults to false, used for editable properties) } kDataBrowserItemIsContainerProperty = 4; { Boolean typed data (defaults to false) } kDataBrowserContainerIsOpenableProperty = 5; { Boolean typed data (defaults to true) } kDataBrowserContainerIsClosableProperty = 6; { Boolean typed data (defaults to true) } kDataBrowserContainerIsSortableProperty = 7; { Boolean typed data (defaults to true) } kDataBrowserItemSelfIdentityProperty = 8; { kDataBrowserIconAndTextType (display property; ColumnView only) } { * kDataBrowserContainerAliasIDProperty is sent to your * DataBrowserItemDataProcPtr callback to give you a chance to follow * an alias or symlink that the item might represent. If the incoming * item is an alias to another item, you can call * SetDataBrowserItemDataItemID to let Data Browser know which other * item the incoming item points to. * * This is only sent from column view, and your support for it is * optional. It allows Data Browser to be more memory efficient with * its internal storage. If a given container item is an alias to an * item whose contents are already displayed in an existing column * view column, the contents can be shared between those two columns. } kDataBrowserContainerAliasIDProperty = 9; { DataBrowserItemID (alias/symlink an item to a container item) } { * kDataBrowserColumnViewPreviewProperty is sent to various callbacks * to give you a chance to draw or track in the preview column of * column view. * * You can also pass kDataBrowserColumnViewPreviewProperty in the * property parameter of RevealDataBrowserItem in conjunction with * the appropriate DataBrowserItemID of the item whose preview is * being displayed when you want to make sure the preview column is * visible to the user. * * kDataBrowserColumnViewPreviewProperty is only supported in column * view. } kDataBrowserColumnViewPreviewProperty = 10; { kDataBrowserCustomType (display property; ColumnView only) } { * kDataBrowserItemParentContainerProperty is sent to your * DataBrowserItemDataProcPtr callback when Data Browser needs to * know the parent container item for a given item. * * In column view, this allows the internals of SetDataBrowserTarget * to work. The target is the container whose contents you wish to * display, which is the rightmost column in column view. However, * unlike SetDataBrowserColumnViewPath, SetDataBrowserTarget doesn't * offer a way for you to communicate the DataBrowserItemIDs of the * rest of the column containers, so SetDataBrowserTarget needs to * ask for them explicitly by asking for the container's parent, then * the container's parent's parent, and so on. * * In list view, this allows you to pass a non-container to * SetDataBrowserTarget. In this situation, Data Browser will ask you * for the parent of the target so it knows which container to * display the contents of in the list view. * * In both list and column views, your DataBrowserItemDataProcPtr * callback might be called with * kDataBrowserItemParentContainerProperty at a variety of other * times, so you should be sure to support this property if your Data * Browser displays a containment hierarchy. } kDataBrowserItemParentContainerProperty = 11; { DataBrowserItemID (the parent of the specified item, used by ColumnView) } { DataBrowser Property Types (for display properties; i.e. ListView columns) } { These are primarily presentation types (or styles) although } { they also imply a particular set of primitive types or structures. } type DataBrowserPropertyType = OSType; const { == Corresponding data type or structure == } kDataBrowserCustomType = $3F3F3F3F; { No associated data, custom callbacks used } kDataBrowserIconType = FourCharCode('icnr'); { IconRef, IconTransformType, RGBColor } kDataBrowserTextType = FourCharCode('text'); { CFStringRef } kDataBrowserDateTimeType = FourCharCode('date'); { DateTime or LongDateTime } kDataBrowserSliderType = FourCharCode('sldr'); { Min, Max, Value } kDataBrowserCheckboxType = FourCharCode('chbx'); { ThemeButtonValue } kDataBrowserProgressBarType = FourCharCode('prog'); { Min, Max, Value } kDataBrowserRelevanceRankType = FourCharCode('rank'); { Min, Max, Value } kDataBrowserPopupMenuType = FourCharCode('menu'); { MenuRef, Value } kDataBrowserIconAndTextType = FourCharCode('ticn'); { IconRef, CFStringRef, etc } { DataBrowser Property Parts } { Visual components of a property type. } { For use with GetDataBrowserItemPartBounds. } type DataBrowserPropertyPart = OSType; const kDataBrowserPropertyEnclosingPart = 0; kDataBrowserPropertyContentPart = FourCharCode('----'); kDataBrowserPropertyDisclosurePart = FourCharCode('disc'); kDataBrowserPropertyTextPart = kDataBrowserTextType; kDataBrowserPropertyIconPart = kDataBrowserIconType; kDataBrowserPropertySliderPart = kDataBrowserSliderType; kDataBrowserPropertyCheckboxPart = kDataBrowserCheckboxType; kDataBrowserPropertyProgressBarPart = kDataBrowserProgressBarType; kDataBrowserPropertyRelevanceRankPart = kDataBrowserRelevanceRankType; { Modify appearance/behavior of display properties } type DataBrowserPropertyFlags = UInt32; { Low 8 bits apply to all property types } const kDataBrowserUniversalPropertyFlagsMask = $FF; kDataBrowserPropertyIsMutable = 1 shl 0; kDataBrowserDefaultPropertyFlags = 0 shl 0; kDataBrowserUniversalPropertyFlags = kDataBrowserUniversalPropertyFlagsMask; { support for an old name} kDataBrowserPropertyIsEditable = kDataBrowserPropertyIsMutable; { support for an old name} { Next 8 bits contain property-specific modifiers } { * Summary: * Data Browser Property Flags } const kDataBrowserPropertyFlagsOffset = 8; kDataBrowserPropertyFlagsMask = $FF shl kDataBrowserPropertyFlagsOffset; kDataBrowserCheckboxTriState = 1 shl kDataBrowserPropertyFlagsOffset; { kDataBrowserCheckboxType} kDataBrowserDateTimeRelative = 1 shl (kDataBrowserPropertyFlagsOffset); { kDataBrowserDateTimeType } kDataBrowserDateTimeDateOnly = 1 shl (kDataBrowserPropertyFlagsOffset + 1); { kDataBrowserDateTimeType } kDataBrowserDateTimeTimeOnly = 1 shl (kDataBrowserPropertyFlagsOffset + 2); { kDataBrowserDateTimeType } kDataBrowserDateTimeSecondsToo = 1 shl (kDataBrowserPropertyFlagsOffset + 3); { kDataBrowserDateTimeType } kDataBrowserSliderPlainThumb = kThemeThumbPlain shl kDataBrowserPropertyFlagsOffset; { kDataBrowserSliderType } kDataBrowserSliderUpwardThumb = kThemeThumbUpward shl kDataBrowserPropertyFlagsOffset; { kDataBrowserSliderType } kDataBrowserSliderDownwardThumb = kThemeThumbDownward shl kDataBrowserPropertyFlagsOffset; { kDataBrowserSliderType } kDataBrowserDoNotTruncateText = 3 shl kDataBrowserPropertyFlagsOffset; { kDataBrowserTextType && kDataBrowserIconAndTextType } kDataBrowserTruncateTextAtEnd = 2 shl kDataBrowserPropertyFlagsOffset; { kDataBrowserTextType && kDataBrowserIconAndTextType } kDataBrowserTruncateTextMiddle = 0 shl kDataBrowserPropertyFlagsOffset; { kDataBrowserTextType && kDataBrowserIconAndTextType } kDataBrowserTruncateTextAtStart = 1 shl kDataBrowserPropertyFlagsOffset; { kDataBrowserTextType && kDataBrowserIconAndTextType } { * This flag is only for use with columns of type * kDataBrowserPopupMenuType. This flag indicates that the popup be * drawn in a sleek buttonless fashion. The text will be drawn next * to a popup glyph, and the whole cell will be clickable. Available * on 10.4 and later. } kDataBrowserPopupMenuButtonless = 1 shl kDataBrowserPropertyFlagsOffset; { kDataBrowserPopupMenuType} kDataBrowserPropertyModificationFlags = kDataBrowserPropertyFlagsMask; { support for an old name} kDataBrowserRelativeDateTime = kDataBrowserDateTimeRelative; { support for an old name} { Next 8 bits contain viewStyle-specific modifiers See individual ViewStyle sections below for flag definitions } const kDataBrowserViewSpecificFlagsOffset = 16; kDataBrowserViewSpecificFlagsMask = $FF shl kDataBrowserViewSpecificFlagsOffset; kDataBrowserViewSpecificPropertyFlags = kDataBrowserViewSpecificFlagsMask; { support for an old name} { High 8 bits are reserved for client application use } const kDataBrowserClientPropertyFlagsOffset = 24; kDataBrowserClientPropertyFlagsMask = $FF000000; { Client defined property description } type DataBrowserPropertyDescPtr = ^DataBrowserPropertyDesc; DataBrowserPropertyDesc = record propertyID: DataBrowserPropertyID; propertyType: DataBrowserPropertyType; propertyFlags: DataBrowserPropertyFlags; end; { Callback definition for use with ForEachDataBrowserItem } type DataBrowserItemProcPtr = procedure( item: DataBrowserItemID; state: DataBrowserItemState; clientData: UnivPtr ); type DataBrowserItemUPP = DataBrowserItemProcPtr; { * NewDataBrowserItemUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserItemUPP( userRoutine: DataBrowserItemProcPtr ): DataBrowserItemUPP; external name '_NewDataBrowserItemUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeDataBrowserItemUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserItemUPP( userUPP: DataBrowserItemUPP ); external name '_DisposeDataBrowserItemUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeDataBrowserItemUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure InvokeDataBrowserItemUPP( item: DataBrowserItemID; state: DataBrowserItemState; clientData: UnivPtr; userUPP: DataBrowserItemUPP ); external name '_InvokeDataBrowserItemUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Creation/Configuration } { * CreateDataBrowserControl() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CreateDataBrowserControl( window: WindowRef; const (*var*) boundsRect: Rect; style: DataBrowserViewStyle; var outControl: ControlRef ): OSStatus; external name '_CreateDataBrowserControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserViewStyle() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserViewStyle( browser: ControlRef; var style: DataBrowserViewStyle ): OSStatus; external name '_GetDataBrowserViewStyle'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserViewStyle() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserViewStyle( browser: ControlRef; style: DataBrowserViewStyle ): OSStatus; external name '_SetDataBrowserViewStyle'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * Summary: * Data Browser attributes * * Discussion: * For use with DataBrowserChangeAttributes and * DataBrowserGetAttributes. Available in Mac OS X 10.4 and later. } const { * A constant with value zero; the lack of any attributes. } kDataBrowserAttributeNone = 0; { * In Column View, this Data Browser is allowed to resize the owning * window whenever necessary. This includes, but is not necessarily * limited to, situations where column resize operations need more * visible space in the window. If you turn this attribute on, your * window must tolerate being resized behind your app's back. If your * window needs to react to bounds changes, use a * kEventWindowBoundsChanged event handler. If you need to constrain * your window's minimum and maximum bounds, use * kEventWindowGetMinimum/MaximumSize handlers, the * SetWindowResizeLimits API, or something similar. } kDataBrowserAttributeColumnViewResizeWindow = 1 shl 0; { * In List View, this Data Browser should draw alternating row * background colors. } kDataBrowserAttributeListViewAlternatingRowColors = 1 shl 1; { * In List View, this Data Browser should draw a vertical line * between the columns. } kDataBrowserAttributeListViewDrawColumnDividers = 1 shl 2; { * DataBrowserChangeAttributes() * * Summary: * Set the attributes for the given Data Browser. * * Mac OS X threading: * Not thread safe * * Parameters: * * inDataBrowser: * The Data Browser whose attributes to change. * * inAttributesToSet: * The attributes to set. * * inAttributesToClear: * The attributes to clear. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function DataBrowserChangeAttributes( inDataBrowser: ControlRef; inAttributesToSet: OptionBits; inAttributesToClear: OptionBits ): OSStatus; external name '_DataBrowserChangeAttributes'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * DataBrowserGetAttributes() * * Summary: * Returns the attributes of a given Data Browser. * * Mac OS X threading: * Not thread safe * * Parameters: * * inDataBrowser: * The Data Browser whose attributes to query. * * outAttributes: * On exit, will contain the attributes of the Data Browser. This * parameter cannot be NULL. * * Result: * An operating system status code. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function DataBrowserGetAttributes( inDataBrowser: ControlRef; var outAttributes: OptionBits ): OSStatus; external name '_DataBrowserGetAttributes'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * Summary: * DataBrowserMetric values * * Discussion: * For use with DataBrowserSetMetric. } const { * The content (icon, text, etc.) within a cell is drawn a certain * amount in from the left & right edges of the cell. This metric * governs the amount of inset. } kDataBrowserMetricCellContentInset = 1; { * This metric controls the space between the icon and text within a * column of type kDataBrowserIconAndTextType. } kDataBrowserMetricIconAndTextGap = 2; { * In List View only, this metric is similar to * kDataBrowserMetricCellContentInset, but it only affects the * disclosure column and it only affects the side of the cell that * displays the disclosure triangle. In other words, this metric is * used instead of (not in addition to) * DataBrowserMetricCellContentInset for one side of the disclosure * column. } kDataBrowserMetricDisclosureColumnEdgeInset = 3; { * In List View only, this metric controls the amount of space * between the disclosure triangle and the cell's content. } kDataBrowserMetricDisclosureTriangleAndContentGap = 4; { * In List View only, this metric controls the amount of space in the * disclosure column for each level of indentation in progressively * deeper hierarchies of disclosed items. } kDataBrowserMetricDisclosureColumnPerDepthGap = 5; kDataBrowserMetricLast = kDataBrowserMetricDisclosureColumnPerDepthGap; type DataBrowserMetric = UInt32; { * DataBrowserSetMetric() * * Summary: * Sets a value for a specified Data Browser metric. * * Mac OS X threading: * Not thread safe * * Parameters: * * inDataBrowser: * The Data Browser instance whose metric is being changed. * * inMetric: * The DataBrowserMetric whose value is being changed. * * inUseDefaultValue: * A Boolean indicating whether you want the Data Browser instance * to revert to the default value for the metric. If you pass * true, inValue will be ignored and a suitable default value will * be used. If you pass false, inValue will be used as the value * of the metric. * * inValue: * When you pass false for inUseDefaultValue, this parameter is * the value to use for the metric. * * Result: * An operating system status code. If the incoming ControlRef isn't * a Data Browser instance, or if the incoming metric isn't known, * this function will return paramErr. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function DataBrowserSetMetric( inDataBrowser: ControlRef; inMetric: DataBrowserMetric; inUseDefaultValue: Boolean; inValue: Float32 ): OSStatus; external name '_DataBrowserSetMetric'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * DataBrowserGetMetric() * * Summary: * Gets the value for a specified Data Browser metric. * * Mac OS X threading: * Not thread safe * * Parameters: * * inDataBrowser: * The Data Browser instance whose metric value to get. * * inMetric: * The DataBrowserMetric value to get. * * outUsingDefaultValue: * On exit, this is a Boolean indicating whether the metric's * value is determined by Data Browser's default values. You may * pass NULL if you don't need this information. * * outValue: * On exit, this is the value of the metric. * * Result: * An operating system status code. If the incoming ControlRef isn't * a Data Browser instance, or if the incoming metric isn't known, * this function will return paramErr. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function DataBrowserGetMetric( inDataBrowser: ControlRef; inMetric: DataBrowserMetric; outUsingDefaultValue: BooleanPtr { can be NULL }; var outValue: Float32 ): OSStatus; external name '_DataBrowserGetMetric'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Item Manipulation } { Passing NULL for "items" argument to RemoveDataBrowserItems and } { UpdateDataBrowserItems refers to all items in the specified container. } { Passing NULL for "items" argument to AddDataBrowserItems means } { "generate IDs starting from 1." } { * AddDataBrowserItems() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function AddDataBrowserItems( browser: ControlRef; container: DataBrowserItemID; numItems: UInt32; {const} items: DataBrowserItemIDPtr { can be NULL }; preSortProperty: DataBrowserPropertyID ): OSStatus; external name '_AddDataBrowserItems'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * RemoveDataBrowserItems() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function RemoveDataBrowserItems( browser: ControlRef; container: DataBrowserItemID; numItems: UInt32; {const} items: DataBrowserItemIDPtr { can be NULL }; preSortProperty: DataBrowserPropertyID ): OSStatus; external name '_RemoveDataBrowserItems'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * UpdateDataBrowserItems() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function UpdateDataBrowserItems( browser: ControlRef; container: DataBrowserItemID; numItems: UInt32; {const} items: DataBrowserItemIDPtr { can be NULL }; preSortProperty: DataBrowserPropertyID; propertyID: DataBrowserPropertyID ): OSStatus; external name '_UpdateDataBrowserItems'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Edit Menu Enabling and Handling } { * EnableDataBrowserEditCommand() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function EnableDataBrowserEditCommand( browser: ControlRef; command: DataBrowserEditCommand ): Boolean; external name '_EnableDataBrowserEditCommand'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * ExecuteDataBrowserEditCommand() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function ExecuteDataBrowserEditCommand( browser: ControlRef; command: DataBrowserEditCommand ): OSStatus; external name '_ExecuteDataBrowserEditCommand'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserSelectionAnchor() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserSelectionAnchor( browser: ControlRef; var first: DataBrowserItemID; var last: DataBrowserItemID ): OSStatus; external name '_GetDataBrowserSelectionAnchor'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * MoveDataBrowserSelectionAnchor() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function MoveDataBrowserSelectionAnchor( browser: ControlRef; direction: DataBrowserSelectionAnchorDirection; extendSelection: Boolean ): OSStatus; external name '_MoveDataBrowserSelectionAnchor'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Container Manipulation } { * OpenDataBrowserContainer() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function OpenDataBrowserContainer( browser: ControlRef; container: DataBrowserItemID ): OSStatus; external name '_OpenDataBrowserContainer'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * CloseDataBrowserContainer() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function CloseDataBrowserContainer( browser: ControlRef; container: DataBrowserItemID ): OSStatus; external name '_CloseDataBrowserContainer'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SortDataBrowserContainer() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SortDataBrowserContainer( browser: ControlRef; container: DataBrowserItemID; sortChildren: Boolean ): OSStatus; external name '_SortDataBrowserContainer'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Aggregate Item Access and Iteration } { * GetDataBrowserItems() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItems( browser: ControlRef; container: DataBrowserItemID; recurse: Boolean; state: DataBrowserItemState; items: Handle ): OSStatus; external name '_GetDataBrowserItems'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemCount() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemCount( browser: ControlRef; container: DataBrowserItemID; recurse: Boolean; state: DataBrowserItemState; var numItems: UInt32 ): OSStatus; external name '_GetDataBrowserItemCount'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * ForEachDataBrowserItem() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function ForEachDataBrowserItem( browser: ControlRef; container: DataBrowserItemID; recurse: Boolean; state: DataBrowserItemState; callback: DataBrowserItemUPP; clientData: UnivPtr ): OSStatus; external name '_ForEachDataBrowserItem'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Individual Item Access and Display } { * IsDataBrowserItemSelected() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function IsDataBrowserItemSelected( browser: ControlRef; item: DataBrowserItemID ): Boolean; external name '_IsDataBrowserItemSelected'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemState() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemState( browser: ControlRef; item: DataBrowserItemID; var state: DataBrowserItemState ): OSStatus; external name '_GetDataBrowserItemState'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * RevealDataBrowserItem() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function RevealDataBrowserItem( browser: ControlRef; item: DataBrowserItemID; propertyID: DataBrowserPropertyID; options: DataBrowserRevealOptions ): OSStatus; external name '_RevealDataBrowserItem'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Selection Set Manipulation } { * SetDataBrowserSelectedItems() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserSelectedItems( browser: ControlRef; numItems: UInt32; items: DataBrowserItemIDPtr; operation: DataBrowserSetOption ): OSStatus; external name '_SetDataBrowserSelectedItems'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { DataBrowser Attribute Manipulation } { The user customizable portion of the current view style settings } { * SetDataBrowserUserState() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserUserState( browser: ControlRef; stateInfo: CFDictionaryRef ): OSStatus; external name '_SetDataBrowserUserState'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserUserState() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserUserState( browser: ControlRef; var stateInfo: CFDictionaryRef ): OSStatus; external name '_GetDataBrowserUserState'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { All items are active/enabled or not } { * SetDataBrowserActiveItems() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserActiveItems( browser: ControlRef; active: Boolean ): OSStatus; external name '_SetDataBrowserActiveItems'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserActiveItems() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserActiveItems( browser: ControlRef; var active: Boolean ): OSStatus; external name '_GetDataBrowserActiveItems'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Inset the scrollbars within the DataBrowser bounds } { * SetDataBrowserScrollBarInset() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserScrollBarInset( browser: ControlRef; var insetRect: Rect ): OSStatus; external name '_SetDataBrowserScrollBarInset'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserScrollBarInset() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserScrollBarInset( browser: ControlRef; var insetRect: Rect ): OSStatus; external name '_GetDataBrowserScrollBarInset'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { The "user focused" item } { For the ListView, this means the root container } { For the ColumnView, this means the rightmost container column } { * SetDataBrowserTarget() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserTarget( browser: ControlRef; target: DataBrowserItemID ): OSStatus; external name '_SetDataBrowserTarget'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserTarget() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserTarget( browser: ControlRef; var target: DataBrowserItemID ): OSStatus; external name '_GetDataBrowserTarget'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Current sort ordering } { ListView tracks this per-column } { * SetDataBrowserSortOrder() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserSortOrder( browser: ControlRef; order: DataBrowserSortOrder ): OSStatus; external name '_SetDataBrowserSortOrder'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserSortOrder() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserSortOrder( browser: ControlRef; var order: DataBrowserSortOrder ): OSStatus; external name '_GetDataBrowserSortOrder'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Scrollbar values } { * SetDataBrowserScrollPosition() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserScrollPosition( browser: ControlRef; top: UInt32; left: UInt32 ): OSStatus; external name '_SetDataBrowserScrollPosition'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserScrollPosition() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserScrollPosition( browser: ControlRef; var top: UInt32; var left: UInt32 ): OSStatus; external name '_GetDataBrowserScrollPosition'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Show/Hide each scrollbar } { * SetDataBrowserHasScrollBars() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserHasScrollBars( browser: ControlRef; horiz: Boolean; vert: Boolean ): OSStatus; external name '_SetDataBrowserHasScrollBars'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserHasScrollBars() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserHasScrollBars( browser: ControlRef; var horiz: Boolean; var vert: Boolean ): OSStatus; external name '_GetDataBrowserHasScrollBars'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Property passed to sort callback (ListView sort column) } { * SetDataBrowserSortProperty() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserSortProperty( browser: ControlRef; property: DataBrowserPropertyID ): OSStatus; external name '_SetDataBrowserSortProperty'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserSortProperty() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserSortProperty( browser: ControlRef; var property: DataBrowserPropertyID ): OSStatus; external name '_GetDataBrowserSortProperty'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Modify selection behavior } { * SetDataBrowserSelectionFlags() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserSelectionFlags( browser: ControlRef; selectionFlags: DataBrowserSelectionFlags ): OSStatus; external name '_SetDataBrowserSelectionFlags'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserSelectionFlags() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserSelectionFlags( browser: ControlRef; var selectionFlags: DataBrowserSelectionFlags ): OSStatus; external name '_GetDataBrowserSelectionFlags'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Dynamically modify property appearance/behavior } { * SetDataBrowserPropertyFlags() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserPropertyFlags( browser: ControlRef; property: DataBrowserPropertyID; flags: DataBrowserPropertyFlags ): OSStatus; external name '_SetDataBrowserPropertyFlags'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserPropertyFlags() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserPropertyFlags( browser: ControlRef; property: DataBrowserPropertyID; var flags: DataBrowserPropertyFlags ): OSStatus; external name '_GetDataBrowserPropertyFlags'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Text of current in-place edit session } { * SetDataBrowserEditText() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserEditText( browser: ControlRef; text: CFStringRef ): OSStatus; external name '_SetDataBrowserEditText'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * CopyDataBrowserEditText() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.5 and later * Non-Carbon CFM: not available } function CopyDataBrowserEditText( browser: ControlRef; var text: CFStringRef ): OSStatus; external name '_CopyDataBrowserEditText'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserEditText() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserEditText( browser: ControlRef; text: CFMutableStringRef ): OSStatus; external name '_GetDataBrowserEditText'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Item/property currently being edited } { * SetDataBrowserEditItem() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserEditItem( browser: ControlRef; item: DataBrowserItemID; property: DataBrowserPropertyID ): OSStatus; external name '_SetDataBrowserEditItem'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserEditItem() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserEditItem( browser: ControlRef; var item: DataBrowserItemID; var property: DataBrowserPropertyID ): OSStatus; external name '_GetDataBrowserEditItem'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Get the current bounds of a visual part of an item's property } { * GetDataBrowserItemPartBounds() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemPartBounds( browser: ControlRef; item: DataBrowserItemID; property: DataBrowserPropertyID; part: DataBrowserPropertyPart; var bounds: Rect ): OSStatus; external name '_GetDataBrowserItemPartBounds'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { DataBrowser ItemData Accessors (used within DataBrowserItemData callback) } type DataBrowserItemDataRef = UnivPtr; { * SetDataBrowserItemDataIcon() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserItemDataIcon( itemData: DataBrowserItemDataRef; theData: IconRef ): OSStatus; external name '_SetDataBrowserItemDataIcon'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemDataIcon() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.5 and later * Non-Carbon CFM: not available } function GetDataBrowserItemDataIcon( itemData: DataBrowserItemDataRef; var theData: IconRef ): OSStatus; external name '_GetDataBrowserItemDataIcon'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserItemDataText() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserItemDataText( itemData: DataBrowserItemDataRef; theData: CFStringRef ): OSStatus; external name '_SetDataBrowserItemDataText'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemDataText() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemDataText( itemData: DataBrowserItemDataRef; var theData: CFStringRef ): OSStatus; external name '_GetDataBrowserItemDataText'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserItemDataValue() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserItemDataValue( itemData: DataBrowserItemDataRef; theData: SInt32 ): OSStatus; external name '_SetDataBrowserItemDataValue'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemDataValue() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemDataValue( itemData: DataBrowserItemDataRef; var theData: SInt32 ): OSStatus; external name '_GetDataBrowserItemDataValue'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserItemDataMinimum() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserItemDataMinimum( itemData: DataBrowserItemDataRef; theData: SInt32 ): OSStatus; external name '_SetDataBrowserItemDataMinimum'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemDataMinimum() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemDataMinimum( itemData: DataBrowserItemDataRef; var theData: SInt32 ): OSStatus; external name '_GetDataBrowserItemDataMinimum'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserItemDataMaximum() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserItemDataMaximum( itemData: DataBrowserItemDataRef; theData: SInt32 ): OSStatus; external name '_SetDataBrowserItemDataMaximum'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemDataMaximum() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemDataMaximum( itemData: DataBrowserItemDataRef; var theData: SInt32 ): OSStatus; external name '_GetDataBrowserItemDataMaximum'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserItemDataBooleanValue() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserItemDataBooleanValue( itemData: DataBrowserItemDataRef; theData: Boolean ): OSStatus; external name '_SetDataBrowserItemDataBooleanValue'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemDataBooleanValue() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemDataBooleanValue( itemData: DataBrowserItemDataRef; var theData: Boolean ): OSStatus; external name '_GetDataBrowserItemDataBooleanValue'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserItemDataMenuRef() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserItemDataMenuRef( itemData: DataBrowserItemDataRef; theData: MenuRef ): OSStatus; external name '_SetDataBrowserItemDataMenuRef'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemDataMenuRef() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemDataMenuRef( itemData: DataBrowserItemDataRef; var theData: MenuRef ): OSStatus; external name '_GetDataBrowserItemDataMenuRef'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserItemDataRGBColor() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserItemDataRGBColor( itemData: DataBrowserItemDataRef; const (*var*) theData: RGBColor ): OSStatus; external name '_SetDataBrowserItemDataRGBColor'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemDataRGBColor() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemDataRGBColor( itemData: DataBrowserItemDataRef; var theData: RGBColor ): OSStatus; external name '_GetDataBrowserItemDataRGBColor'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserItemDataDrawState() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserItemDataDrawState( itemData: DataBrowserItemDataRef; theData: ThemeDrawState ): OSStatus; external name '_SetDataBrowserItemDataDrawState'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemDataDrawState() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemDataDrawState( itemData: DataBrowserItemDataRef; var theData: ThemeDrawState ): OSStatus; external name '_GetDataBrowserItemDataDrawState'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserItemDataButtonValue() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserItemDataButtonValue( itemData: DataBrowserItemDataRef; theData: ThemeButtonValue ): OSStatus; external name '_SetDataBrowserItemDataButtonValue'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemDataButtonValue() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemDataButtonValue( itemData: DataBrowserItemDataRef; var theData: ThemeButtonValue ): OSStatus; external name '_GetDataBrowserItemDataButtonValue'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserItemDataIconTransform() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserItemDataIconTransform( itemData: DataBrowserItemDataRef; theData: IconTransformType ): OSStatus; external name '_SetDataBrowserItemDataIconTransform'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemDataIconTransform() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemDataIconTransform( itemData: DataBrowserItemDataRef; var theData: IconTransformType ): OSStatus; external name '_GetDataBrowserItemDataIconTransform'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserItemDataDateTime() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserItemDataDateTime( itemData: DataBrowserItemDataRef; theData: SInt32 ): OSStatus; external name '_SetDataBrowserItemDataDateTime'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemDataDateTime() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemDataDateTime( itemData: DataBrowserItemDataRef; var theData: SInt32 ): OSStatus; external name '_GetDataBrowserItemDataDateTime'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserItemDataLongDateTime() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserItemDataLongDateTime( itemData: DataBrowserItemDataRef; (*const*) var theData: LongDateTime ): OSStatus; external name '_SetDataBrowserItemDataLongDateTime'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemDataLongDateTime() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemDataLongDateTime( itemData: DataBrowserItemDataRef; var theData: LongDateTime ): OSStatus; external name '_GetDataBrowserItemDataLongDateTime'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserItemDataItemID() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserItemDataItemID( itemData: DataBrowserItemDataRef; theData: DataBrowserItemID ): OSStatus; external name '_SetDataBrowserItemDataItemID'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemDataItemID() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.5 and later * Non-Carbon CFM: not available } function GetDataBrowserItemDataItemID( itemData: DataBrowserItemDataRef; var theData: DataBrowserItemID ): OSStatus; external name '_GetDataBrowserItemDataItemID'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserItemDataProperty() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserItemDataProperty( itemData: DataBrowserItemDataRef; var theData: DataBrowserPropertyID ): OSStatus; external name '_GetDataBrowserItemDataProperty'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Standard DataBrowser Callbacks } { Basic Item Management & Manipulation } type DataBrowserItemDataProcPtr = function( browser: ControlRef; item: DataBrowserItemID; property: DataBrowserPropertyID; itemData: DataBrowserItemDataRef; setValue: Boolean ): OSStatus; type DataBrowserItemDataUPP = DataBrowserItemDataProcPtr; { Item Comparison } type DataBrowserItemCompareProcPtr = function( browser: ControlRef; itemOne: DataBrowserItemID; itemTwo: DataBrowserItemID; sortProperty: DataBrowserPropertyID ): Boolean; type DataBrowserItemCompareUPP = DataBrowserItemCompareProcPtr; { ItemEvent Notification } { A Very Important Note about DataBrowserItemNotificationProcPtr: } { Under all currently shipping versions of CarbonLib (eg. up through 1.3), your callback is called } { just as the prototype appears in this header. It should only be expecting three parameters because } { DataBrowser will only pass three parameters. } { Under Mac OS X, your callback is called with an additional parameter. If you wish to interpret } { the additional parameter, your callback should have the same prototype as the } { DataBrowserItemNotificationWithItemProcPtr (below). You may freely take a callback with this } { prototype and pass it to NewDataBrowserItemNotificationUPP in order to generate a } { DataBrowserItemNotificationUPP that you can use just like any other DataBrowserItemNotificationUPP. } { If you use this technique under CarbonLib, you will *not* receive valid data in the fourth } { parameter, and any attempt to use the invalid data will probably result in a crash. } type DataBrowserItemNotificationWithItemProcPtr = procedure( browser: ControlRef; item: DataBrowserItemID; message: DataBrowserItemNotification; itemData: DataBrowserItemDataRef ); type DataBrowserItemNotificationProcPtr = procedure( browser: ControlRef; item: DataBrowserItemID; message: DataBrowserItemNotification ); type DataBrowserItemNotificationWithItemUPP = DataBrowserItemNotificationWithItemProcPtr; type DataBrowserItemNotificationUPP = DataBrowserItemNotificationProcPtr; { Drag & Drop Processing } type DataBrowserAddDragItemProcPtr = function( browser: ControlRef; theDrag: DragReference; item: DataBrowserItemID; var itemRef: ItemReference ): Boolean; type DataBrowserAcceptDragProcPtr = function( browser: ControlRef; theDrag: DragReference; item: DataBrowserItemID ): Boolean; type DataBrowserReceiveDragProcPtr = function( browser: ControlRef; theDrag: DragReference; item: DataBrowserItemID ): Boolean; type DataBrowserPostProcessDragProcPtr = procedure( browser: ControlRef; theDrag: DragReference; trackDragResult: OSStatus ); type DataBrowserAddDragItemUPP = DataBrowserAddDragItemProcPtr; type DataBrowserAcceptDragUPP = DataBrowserAcceptDragProcPtr; type DataBrowserReceiveDragUPP = DataBrowserReceiveDragProcPtr; type DataBrowserPostProcessDragUPP = DataBrowserPostProcessDragProcPtr; { Contextual Menu Support } type DataBrowserGetContextualMenuProcPtr = procedure( browser: ControlRef; var menu: MenuRef; var helpType: UInt32; var helpItemString: CFStringRef; var selection: AEDesc ); type DataBrowserSelectContextualMenuProcPtr = procedure( browser: ControlRef; menu: MenuRef; selectionType: UInt32; menuID: SInt16; menuItem: MenuItemIndex ); type DataBrowserGetContextualMenuUPP = DataBrowserGetContextualMenuProcPtr; type DataBrowserSelectContextualMenuUPP = DataBrowserSelectContextualMenuProcPtr; { Help Manager Support } type DataBrowserItemHelpContentProcPtr = procedure( browser: ControlRef; item: DataBrowserItemID; property: DataBrowserPropertyID; inRequest: HMContentRequest; var outContentProvided: HMContentProvidedType; ioHelpContent: HMHelpContentPtr ); type DataBrowserItemHelpContentUPP = DataBrowserItemHelpContentProcPtr; { * NewDataBrowserItemDataUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserItemDataUPP( userRoutine: DataBrowserItemDataProcPtr ): DataBrowserItemDataUPP; external name '_NewDataBrowserItemDataUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewDataBrowserItemCompareUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserItemCompareUPP( userRoutine: DataBrowserItemCompareProcPtr ): DataBrowserItemCompareUPP; external name '_NewDataBrowserItemCompareUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewDataBrowserItemNotificationWithItemUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.5 and later * Non-Carbon CFM: not available } function NewDataBrowserItemNotificationWithItemUPP( userRoutine: DataBrowserItemNotificationWithItemProcPtr ): DataBrowserItemNotificationWithItemUPP; external name '_NewDataBrowserItemNotificationWithItemUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * NewDataBrowserItemNotificationUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserItemNotificationUPP( userRoutine: DataBrowserItemNotificationProcPtr ): DataBrowserItemNotificationUPP; external name '_NewDataBrowserItemNotificationUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewDataBrowserAddDragItemUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserAddDragItemUPP( userRoutine: DataBrowserAddDragItemProcPtr ): DataBrowserAddDragItemUPP; external name '_NewDataBrowserAddDragItemUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewDataBrowserAcceptDragUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserAcceptDragUPP( userRoutine: DataBrowserAcceptDragProcPtr ): DataBrowserAcceptDragUPP; external name '_NewDataBrowserAcceptDragUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewDataBrowserReceiveDragUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserReceiveDragUPP( userRoutine: DataBrowserReceiveDragProcPtr ): DataBrowserReceiveDragUPP; external name '_NewDataBrowserReceiveDragUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewDataBrowserPostProcessDragUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserPostProcessDragUPP( userRoutine: DataBrowserPostProcessDragProcPtr ): DataBrowserPostProcessDragUPP; external name '_NewDataBrowserPostProcessDragUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewDataBrowserGetContextualMenuUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserGetContextualMenuUPP( userRoutine: DataBrowserGetContextualMenuProcPtr ): DataBrowserGetContextualMenuUPP; external name '_NewDataBrowserGetContextualMenuUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewDataBrowserSelectContextualMenuUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserSelectContextualMenuUPP( userRoutine: DataBrowserSelectContextualMenuProcPtr ): DataBrowserSelectContextualMenuUPP; external name '_NewDataBrowserSelectContextualMenuUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * NewDataBrowserItemHelpContentUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserItemHelpContentUPP( userRoutine: DataBrowserItemHelpContentProcPtr ): DataBrowserItemHelpContentUPP; external name '_NewDataBrowserItemHelpContentUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeDataBrowserItemDataUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserItemDataUPP( userUPP: DataBrowserItemDataUPP ); external name '_DisposeDataBrowserItemDataUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeDataBrowserItemCompareUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserItemCompareUPP( userUPP: DataBrowserItemCompareUPP ); external name '_DisposeDataBrowserItemCompareUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeDataBrowserItemNotificationWithItemUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.5 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserItemNotificationWithItemUPP( userUPP: DataBrowserItemNotificationWithItemUPP ); external name '_DisposeDataBrowserItemNotificationWithItemUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * DisposeDataBrowserItemNotificationUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserItemNotificationUPP( userUPP: DataBrowserItemNotificationUPP ); external name '_DisposeDataBrowserItemNotificationUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeDataBrowserAddDragItemUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserAddDragItemUPP( userUPP: DataBrowserAddDragItemUPP ); external name '_DisposeDataBrowserAddDragItemUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeDataBrowserAcceptDragUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserAcceptDragUPP( userUPP: DataBrowserAcceptDragUPP ); external name '_DisposeDataBrowserAcceptDragUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeDataBrowserReceiveDragUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserReceiveDragUPP( userUPP: DataBrowserReceiveDragUPP ); external name '_DisposeDataBrowserReceiveDragUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeDataBrowserPostProcessDragUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserPostProcessDragUPP( userUPP: DataBrowserPostProcessDragUPP ); external name '_DisposeDataBrowserPostProcessDragUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeDataBrowserGetContextualMenuUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserGetContextualMenuUPP( userUPP: DataBrowserGetContextualMenuUPP ); external name '_DisposeDataBrowserGetContextualMenuUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeDataBrowserSelectContextualMenuUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserSelectContextualMenuUPP( userUPP: DataBrowserSelectContextualMenuUPP ); external name '_DisposeDataBrowserSelectContextualMenuUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeDataBrowserItemHelpContentUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserItemHelpContentUPP( userUPP: DataBrowserItemHelpContentUPP ); external name '_DisposeDataBrowserItemHelpContentUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeDataBrowserItemDataUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function InvokeDataBrowserItemDataUPP( browser: ControlRef; item: DataBrowserItemID; property: DataBrowserPropertyID; itemData: DataBrowserItemDataRef; setValue: Boolean; userUPP: DataBrowserItemDataUPP ): OSStatus; external name '_InvokeDataBrowserItemDataUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeDataBrowserItemCompareUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function InvokeDataBrowserItemCompareUPP( browser: ControlRef; itemOne: DataBrowserItemID; itemTwo: DataBrowserItemID; sortProperty: DataBrowserPropertyID; userUPP: DataBrowserItemCompareUPP ): Boolean; external name '_InvokeDataBrowserItemCompareUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeDataBrowserItemNotificationWithItemUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.5 and later * Non-Carbon CFM: not available } procedure InvokeDataBrowserItemNotificationWithItemUPP( browser: ControlRef; item: DataBrowserItemID; message: DataBrowserItemNotification; itemData: DataBrowserItemDataRef; userUPP: DataBrowserItemNotificationWithItemUPP ); external name '_InvokeDataBrowserItemNotificationWithItemUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * InvokeDataBrowserItemNotificationUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure InvokeDataBrowserItemNotificationUPP( browser: ControlRef; item: DataBrowserItemID; message: DataBrowserItemNotification; userUPP: DataBrowserItemNotificationUPP ); external name '_InvokeDataBrowserItemNotificationUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeDataBrowserAddDragItemUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function InvokeDataBrowserAddDragItemUPP( browser: ControlRef; theDrag: DragReference; item: DataBrowserItemID; var itemRef: ItemReference; userUPP: DataBrowserAddDragItemUPP ): Boolean; external name '_InvokeDataBrowserAddDragItemUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeDataBrowserAcceptDragUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function InvokeDataBrowserAcceptDragUPP( browser: ControlRef; theDrag: DragReference; item: DataBrowserItemID; userUPP: DataBrowserAcceptDragUPP ): Boolean; external name '_InvokeDataBrowserAcceptDragUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeDataBrowserReceiveDragUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function InvokeDataBrowserReceiveDragUPP( browser: ControlRef; theDrag: DragReference; item: DataBrowserItemID; userUPP: DataBrowserReceiveDragUPP ): Boolean; external name '_InvokeDataBrowserReceiveDragUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeDataBrowserPostProcessDragUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure InvokeDataBrowserPostProcessDragUPP( browser: ControlRef; theDrag: DragReference; trackDragResult: OSStatus; userUPP: DataBrowserPostProcessDragUPP ); external name '_InvokeDataBrowserPostProcessDragUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeDataBrowserGetContextualMenuUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure InvokeDataBrowserGetContextualMenuUPP( browser: ControlRef; var menu: MenuRef; var helpType: UInt32; var helpItemString: CFStringRef; var selection: AEDesc; userUPP: DataBrowserGetContextualMenuUPP ); external name '_InvokeDataBrowserGetContextualMenuUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeDataBrowserSelectContextualMenuUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure InvokeDataBrowserSelectContextualMenuUPP( browser: ControlRef; menu: MenuRef; selectionType: UInt32; menuID: SInt16; menuItem: MenuItemIndex; userUPP: DataBrowserSelectContextualMenuUPP ); external name '_InvokeDataBrowserSelectContextualMenuUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeDataBrowserItemHelpContentUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure InvokeDataBrowserItemHelpContentUPP( browser: ControlRef; item: DataBrowserItemID; property: DataBrowserPropertyID; inRequest: HMContentRequest; var outContentProvided: HMContentProvidedType; ioHelpContent: HMHelpContentPtr; userUPP: DataBrowserItemHelpContentUPP ); external name '_InvokeDataBrowserItemHelpContentUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Standard Callback (vtable) Structure } const kDataBrowserLatestCallbacks = 0; type DataBrowserCallbacksPtr = ^DataBrowserCallbacks; DataBrowserCallbacks = record version: UInt32; { Use kDataBrowserLatestCallbacks } case SInt16 of 0: ( itemDataCallback: DataBrowserItemDataUPP; itemCompareCallback: DataBrowserItemCompareUPP; itemNotificationCallback: DataBrowserItemNotificationUPP; addDragItemCallback: DataBrowserAddDragItemUPP; acceptDragCallback: DataBrowserAcceptDragUPP; receiveDragCallback: DataBrowserReceiveDragUPP; postProcessDragCallback: DataBrowserPostProcessDragUPP; itemHelpContentCallback: DataBrowserItemHelpContentUPP; getContextualMenuCallback: DataBrowserGetContextualMenuUPP; selectContextualMenuCallback: DataBrowserSelectContextualMenuUPP; ); end; { * InitDataBrowserCallbacks() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function InitDataBrowserCallbacks( var callbacks: DataBrowserCallbacks ): OSStatus; external name '_InitDataBrowserCallbacks'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Macro for initializing callback structure } // #define InitializeDataBrowserCallbacks(callbacks, vers) \ { (callbacks)->version = (vers); InitDataBrowserCallbacks(callbacks); } { * GetDataBrowserCallbacks() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserCallbacks( browser: ControlRef; var callbacks: DataBrowserCallbacks ): OSStatus; external name '_GetDataBrowserCallbacks'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserCallbacks() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserCallbacks( browser: ControlRef; const (*var*) callbacks: DataBrowserCallbacks ): OSStatus; external name '_SetDataBrowserCallbacks'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Custom Format Callbacks (kDataBrowserCustomType display properties) } type DataBrowserDragFlags = UInt32; type DataBrowserTrackingResult = SInt16; const kDataBrowserContentHit = 1; kDataBrowserNothingHit = 0; kDataBrowserStopTracking = -1; type DataBrowserDrawItemProcPtr = procedure( browser: ControlRef; item: DataBrowserItemID; property: DataBrowserPropertyID; itemState: DataBrowserItemState; const (*var*) theRect: Rect; gdDepth: SInt16; colorDevice: Boolean ); type DataBrowserEditItemProcPtr = function( browser: ControlRef; item: DataBrowserItemID; property: DataBrowserPropertyID; theString: CFStringRef; var maxEditTextRect: Rect; var shrinkToFit: Boolean ): Boolean; type DataBrowserHitTestProcPtr = function( browser: ControlRef; itemID: DataBrowserItemID; property: DataBrowserPropertyID; const (*var*) theRect: Rect; const (*var*) mouseRect: Rect ): Boolean; type DataBrowserTrackingProcPtr = function( browser: ControlRef; itemID: DataBrowserItemID; property: DataBrowserPropertyID; const (*var*) theRect: Rect; startPt: Point; modifiers: EventModifiers ): DataBrowserTrackingResult; type DataBrowserItemDragRgnProcPtr = procedure( browser: ControlRef; itemID: DataBrowserItemID; property: DataBrowserPropertyID; const (*var*) theRect: Rect; dragRgn: RgnHandle ); type DataBrowserItemAcceptDragProcPtr = function( browser: ControlRef; itemID: DataBrowserItemID; property: DataBrowserPropertyID; const (*var*) theRect: Rect; theDrag: DragReference ): DataBrowserDragFlags; type DataBrowserItemReceiveDragProcPtr = function( browser: ControlRef; itemID: DataBrowserItemID; property: DataBrowserPropertyID; dragFlags: DataBrowserDragFlags; theDrag: DragReference ): Boolean; type DataBrowserDrawItemUPP = DataBrowserDrawItemProcPtr; type DataBrowserEditItemUPP = DataBrowserEditItemProcPtr; type DataBrowserHitTestUPP = DataBrowserHitTestProcPtr; type DataBrowserTrackingUPP = DataBrowserTrackingProcPtr; type DataBrowserItemDragRgnUPP = DataBrowserItemDragRgnProcPtr; type DataBrowserItemAcceptDragUPP = DataBrowserItemAcceptDragProcPtr; type DataBrowserItemReceiveDragUPP = DataBrowserItemReceiveDragProcPtr; { * NewDataBrowserDrawItemUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserDrawItemUPP( userRoutine: DataBrowserDrawItemProcPtr ): DataBrowserDrawItemUPP; external name '_NewDataBrowserDrawItemUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * NewDataBrowserEditItemUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserEditItemUPP( userRoutine: DataBrowserEditItemProcPtr ): DataBrowserEditItemUPP; external name '_NewDataBrowserEditItemUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * NewDataBrowserHitTestUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserHitTestUPP( userRoutine: DataBrowserHitTestProcPtr ): DataBrowserHitTestUPP; external name '_NewDataBrowserHitTestUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * NewDataBrowserTrackingUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserTrackingUPP( userRoutine: DataBrowserTrackingProcPtr ): DataBrowserTrackingUPP; external name '_NewDataBrowserTrackingUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * NewDataBrowserItemDragRgnUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserItemDragRgnUPP( userRoutine: DataBrowserItemDragRgnProcPtr ): DataBrowserItemDragRgnUPP; external name '_NewDataBrowserItemDragRgnUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * NewDataBrowserItemAcceptDragUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserItemAcceptDragUPP( userRoutine: DataBrowserItemAcceptDragProcPtr ): DataBrowserItemAcceptDragUPP; external name '_NewDataBrowserItemAcceptDragUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * NewDataBrowserItemReceiveDragUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function NewDataBrowserItemReceiveDragUPP( userRoutine: DataBrowserItemReceiveDragProcPtr ): DataBrowserItemReceiveDragUPP; external name '_NewDataBrowserItemReceiveDragUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * DisposeDataBrowserDrawItemUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserDrawItemUPP( userUPP: DataBrowserDrawItemUPP ); external name '_DisposeDataBrowserDrawItemUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * DisposeDataBrowserEditItemUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserEditItemUPP( userUPP: DataBrowserEditItemUPP ); external name '_DisposeDataBrowserEditItemUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * DisposeDataBrowserHitTestUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserHitTestUPP( userUPP: DataBrowserHitTestUPP ); external name '_DisposeDataBrowserHitTestUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * DisposeDataBrowserTrackingUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserTrackingUPP( userUPP: DataBrowserTrackingUPP ); external name '_DisposeDataBrowserTrackingUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * DisposeDataBrowserItemDragRgnUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserItemDragRgnUPP( userUPP: DataBrowserItemDragRgnUPP ); external name '_DisposeDataBrowserItemDragRgnUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * DisposeDataBrowserItemAcceptDragUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserItemAcceptDragUPP( userUPP: DataBrowserItemAcceptDragUPP ); external name '_DisposeDataBrowserItemAcceptDragUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * DisposeDataBrowserItemReceiveDragUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure DisposeDataBrowserItemReceiveDragUPP( userUPP: DataBrowserItemReceiveDragUPP ); external name '_DisposeDataBrowserItemReceiveDragUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * InvokeDataBrowserDrawItemUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure InvokeDataBrowserDrawItemUPP( browser: ControlRef; item: DataBrowserItemID; property: DataBrowserPropertyID; itemState: DataBrowserItemState; const (*var*) theRect: Rect; gdDepth: SInt16; colorDevice: Boolean; userUPP: DataBrowserDrawItemUPP ); external name '_InvokeDataBrowserDrawItemUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * InvokeDataBrowserEditItemUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function InvokeDataBrowserEditItemUPP( browser: ControlRef; item: DataBrowserItemID; property: DataBrowserPropertyID; theString: CFStringRef; var maxEditTextRect: Rect; var shrinkToFit: Boolean; userUPP: DataBrowserEditItemUPP ): Boolean; external name '_InvokeDataBrowserEditItemUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * InvokeDataBrowserHitTestUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function InvokeDataBrowserHitTestUPP( browser: ControlRef; itemID: DataBrowserItemID; property: DataBrowserPropertyID; const (*var*) theRect: Rect; const (*var*) mouseRect: Rect; userUPP: DataBrowserHitTestUPP ): Boolean; external name '_InvokeDataBrowserHitTestUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * InvokeDataBrowserTrackingUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function InvokeDataBrowserTrackingUPP( browser: ControlRef; itemID: DataBrowserItemID; property: DataBrowserPropertyID; const (*var*) theRect: Rect; startPt: Point; modifiers: EventModifiers; userUPP: DataBrowserTrackingUPP ): DataBrowserTrackingResult; external name '_InvokeDataBrowserTrackingUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * InvokeDataBrowserItemDragRgnUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } procedure InvokeDataBrowserItemDragRgnUPP( browser: ControlRef; itemID: DataBrowserItemID; property: DataBrowserPropertyID; const (*var*) theRect: Rect; dragRgn: RgnHandle; userUPP: DataBrowserItemDragRgnUPP ); external name '_InvokeDataBrowserItemDragRgnUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * InvokeDataBrowserItemAcceptDragUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function InvokeDataBrowserItemAcceptDragUPP( browser: ControlRef; itemID: DataBrowserItemID; property: DataBrowserPropertyID; const (*var*) theRect: Rect; theDrag: DragReference; userUPP: DataBrowserItemAcceptDragUPP ): DataBrowserDragFlags; external name '_InvokeDataBrowserItemAcceptDragUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { * InvokeDataBrowserItemReceiveDragUPP() * * Availability: * Mac OS X: in version 10.1 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function InvokeDataBrowserItemReceiveDragUPP( browser: ControlRef; itemID: DataBrowserItemID; property: DataBrowserPropertyID; dragFlags: DataBrowserDragFlags; theDrag: DragReference; userUPP: DataBrowserItemReceiveDragUPP ): Boolean; external name '_InvokeDataBrowserItemReceiveDragUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) { Custom Callback (vtable) Structure } const kDataBrowserLatestCustomCallbacks = 0; type DataBrowserCustomCallbacksPtr = ^DataBrowserCustomCallbacks; DataBrowserCustomCallbacks = record version: UInt32; { Use kDataBrowserLatestCustomCallbacks } case SInt16 of 0: ( drawItemCallback: DataBrowserDrawItemUPP; editTextCallback: DataBrowserEditItemUPP; hitTestCallback: DataBrowserHitTestUPP; trackingCallback: DataBrowserTrackingUPP; dragRegionCallback: DataBrowserItemDragRgnUPP; acceptDragCallback: DataBrowserItemAcceptDragUPP; receiveDragCallback: DataBrowserItemReceiveDragUPP; ); end; { * InitDataBrowserCustomCallbacks() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function InitDataBrowserCustomCallbacks( var callbacks: DataBrowserCustomCallbacks ): OSStatus; external name '_InitDataBrowserCustomCallbacks'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { Macro for initializing custom callback structure } // #define InitializeDataBrowserCustomCallbacks(callbacks, vers) \ { (callbacks)->version = (vers); InitDataBrowserCustomCallbacks(callbacks); } { * GetDataBrowserCustomCallbacks() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserCustomCallbacks( browser: ControlRef; var callbacks: DataBrowserCustomCallbacks ): OSStatus; external name '_GetDataBrowserCustomCallbacks'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserCustomCallbacks() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserCustomCallbacks( browser: ControlRef; const (*var*) callbacks: DataBrowserCustomCallbacks ): OSStatus; external name '_SetDataBrowserCustomCallbacks'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { TableView Formatting } type DataBrowserTableViewHiliteStyle = UInt32; const kDataBrowserTableViewMinimalHilite = 0; kDataBrowserTableViewFillHilite = 1; type DataBrowserTableViewPropertyFlags = UInt32; const { kDataBrowserTableView DataBrowserPropertyFlags } kDataBrowserTableViewSelectionColumn = 1 shl kDataBrowserViewSpecificFlagsOffset; { The row and column indicies are zero-based } type DataBrowserTableViewRowIndex = UInt32; type DataBrowserTableViewColumnIndex = UInt32; type DataBrowserTableViewColumnID = DataBrowserPropertyID; type DataBrowserTableViewColumnDesc = DataBrowserPropertyDesc; DataBrowserTableViewColumnDescPtr = ^DataBrowserTableViewColumnDesc; { TableView API } { Use when setting column position } const kDataBrowserTableViewLastColumn = $FFFFFFFF; { * RemoveDataBrowserTableViewColumn() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function RemoveDataBrowserTableViewColumn( browser: ControlRef; column: DataBrowserTableViewColumnID ): OSStatus; external name '_RemoveDataBrowserTableViewColumn'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserTableViewColumnCount() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserTableViewColumnCount( browser: ControlRef; var numColumns: UInt32 ): OSStatus; external name '_GetDataBrowserTableViewColumnCount'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserTableViewHiliteStyle() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserTableViewHiliteStyle( browser: ControlRef; hiliteStyle: DataBrowserTableViewHiliteStyle ): OSStatus; external name '_SetDataBrowserTableViewHiliteStyle'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserTableViewHiliteStyle() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserTableViewHiliteStyle( browser: ControlRef; var hiliteStyle: DataBrowserTableViewHiliteStyle ): OSStatus; external name '_GetDataBrowserTableViewHiliteStyle'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserTableViewRowHeight() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserTableViewRowHeight( browser: ControlRef; height: UInt16 ): OSStatus; external name '_SetDataBrowserTableViewRowHeight'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserTableViewRowHeight() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserTableViewRowHeight( browser: ControlRef; var height: UInt16 ): OSStatus; external name '_GetDataBrowserTableViewRowHeight'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserTableViewColumnWidth() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserTableViewColumnWidth( browser: ControlRef; width: UInt16 ): OSStatus; external name '_SetDataBrowserTableViewColumnWidth'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserTableViewColumnWidth() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserTableViewColumnWidth( browser: ControlRef; var width: UInt16 ): OSStatus; external name '_GetDataBrowserTableViewColumnWidth'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserTableViewItemRowHeight() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserTableViewItemRowHeight( browser: ControlRef; item: DataBrowserItemID; height: UInt16 ): OSStatus; external name '_SetDataBrowserTableViewItemRowHeight'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserTableViewItemRowHeight() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserTableViewItemRowHeight( browser: ControlRef; item: DataBrowserItemID; var height: UInt16 ): OSStatus; external name '_GetDataBrowserTableViewItemRowHeight'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserTableViewNamedColumnWidth() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserTableViewNamedColumnWidth( browser: ControlRef; column: DataBrowserTableViewColumnID; width: UInt16 ): OSStatus; external name '_SetDataBrowserTableViewNamedColumnWidth'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserTableViewNamedColumnWidth() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserTableViewNamedColumnWidth( browser: ControlRef; column: DataBrowserTableViewColumnID; var width: UInt16 ): OSStatus; external name '_GetDataBrowserTableViewNamedColumnWidth'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserTableViewGeometry() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserTableViewGeometry( browser: ControlRef; variableWidthColumns: Boolean; variableHeightRows: Boolean ): OSStatus; external name '_SetDataBrowserTableViewGeometry'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserTableViewGeometry() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserTableViewGeometry( browser: ControlRef; var variableWidthColumns: Boolean; var variableHeightRows: Boolean ): OSStatus; external name '_GetDataBrowserTableViewGeometry'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserTableViewItemID() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserTableViewItemID( browser: ControlRef; row: DataBrowserTableViewRowIndex; var item: DataBrowserItemID ): OSStatus; external name '_GetDataBrowserTableViewItemID'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserTableViewItemRow() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserTableViewItemRow( browser: ControlRef; item: DataBrowserItemID; row: DataBrowserTableViewRowIndex ): OSStatus; external name '_SetDataBrowserTableViewItemRow'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserTableViewItemRow() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserTableViewItemRow( browser: ControlRef; item: DataBrowserItemID; var row: DataBrowserTableViewRowIndex ): OSStatus; external name '_GetDataBrowserTableViewItemRow'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserTableViewColumnPosition() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserTableViewColumnPosition( browser: ControlRef; column: DataBrowserTableViewColumnID; position: DataBrowserTableViewColumnIndex ): OSStatus; external name '_SetDataBrowserTableViewColumnPosition'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserTableViewColumnPosition() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserTableViewColumnPosition( browser: ControlRef; column: DataBrowserTableViewColumnID; var position: DataBrowserTableViewColumnIndex ): OSStatus; external name '_GetDataBrowserTableViewColumnPosition'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserTableViewColumnProperty() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserTableViewColumnProperty( browser: ControlRef; column: DataBrowserTableViewColumnIndex; var property: DataBrowserTableViewColumnID ): OSStatus; external name '_GetDataBrowserTableViewColumnProperty'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { kDataBrowserListView Formatting } { * Discussion: * DataBrowserPropertyFlags that are specific to kDataBrowserListView } const kDataBrowserListViewSelectionColumn = kDataBrowserTableViewSelectionColumn; kDataBrowserListViewMovableColumn = 1 shl (kDataBrowserViewSpecificFlagsOffset + 1); kDataBrowserListViewSortableColumn = 1 shl (kDataBrowserViewSpecificFlagsOffset + 2); { * kDataBrowserListViewTypeSelectColumn marks a column as * type-selectable. If one or more of your list view columns are * marked as type-selectable, Data Browser will do type-selection for * you automatically. Data Browser applies the typing to the first * column (in the system direction) with this property flag. This * flag only intended for use with columns of type * kDataBrowserTextType, kDataBrowserIconAndTextType, and * kDataBrowserDateTimeType; if you set it for a column of another * type, the type-selection behavior is undefined. Turning on this * flag also causes Data Browser to gather all keyboard input via a * carbon event handler instead of relying on calls to * HandleControlKey; therefore, you will never see these keyboard * events come out of WaitNextEvent. Only available on 10.3 and later. } kDataBrowserListViewTypeSelectColumn = 1 shl (kDataBrowserViewSpecificFlagsOffset + 3); { * Normally the text in a header button for a column of type * kDataBrowserIconAndTextType is aligned as though it has an icon * next to it even if no icon is specified for the header button; in * other words, space is reserved for an icon in the header button * even if no icon is displayed. However, this flag indicates that * space should not be reserved for an icon if no icon is provided * for the header button. This flag allows a client to justify the * left edge of the text in a header button to the left edge of the * icon in the cells beneath it. Available on 10.4 and later. } kDataBrowserListViewNoGapForIconInHeaderButton = 1 shl (kDataBrowserViewSpecificFlagsOffset + 4); kDataBrowserListViewDefaultColumnFlags = kDataBrowserListViewMovableColumn + kDataBrowserListViewSortableColumn; type DataBrowserListViewPropertyFlags = DataBrowserPropertyFlags; const kDataBrowserListViewLatestHeaderDesc = 0; type DataBrowserListViewHeaderDescPtr = ^DataBrowserListViewHeaderDesc; DataBrowserListViewHeaderDesc = record version: UInt32; { Use kDataBrowserListViewLatestHeaderDesc } minimumWidth: UInt16; maximumWidth: UInt16; titleOffset: SInt16; titleString: CFStringRef; initialOrder: DataBrowserSortOrder; btnFontStyle: ControlFontStyleRec; btnContentInfo: ControlButtonContentInfo; end; type DataBrowserListViewColumnDescPtr = ^DataBrowserListViewColumnDesc; DataBrowserListViewColumnDesc = record propertyDesc: DataBrowserTableViewColumnDesc; headerBtnDesc: DataBrowserListViewHeaderDesc; end; { kDataBrowserListView API } const kDataBrowserListViewAppendColumn = kDataBrowserTableViewLastColumn; { * AutoSizeDataBrowserListViewColumns() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function AutoSizeDataBrowserListViewColumns( browser: ControlRef ): OSStatus; external name '_AutoSizeDataBrowserListViewColumns'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * AddDataBrowserListViewColumn() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function AddDataBrowserListViewColumn( browser: ControlRef; var columnDesc: DataBrowserListViewColumnDesc; position: DataBrowserTableViewColumnIndex ): OSStatus; external name '_AddDataBrowserListViewColumn'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserListViewHeaderDesc() * * Summary: * Returns information about a specified column header in a list * view. * * Discussion: * Note that this API does not correctly use CoreFoundation naming * conventions. Although the API name begins with "Get", implying * that you do not need to release the CFStringRef and IconRef * returned by this API, in fact you do actually need to release * these objects. * * Mac OS X threading: * Not thread safe * * Parameters: * * browser: * The data browser for which you need header information. * * column: * The column ID for which you need header information. * * desc: * On exit, contains header information for the specified column. * You must release the CFStringRef and IconRef contained in this * structure. * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: in CarbonLib 1.5 and later * Non-Carbon CFM: not available } function GetDataBrowserListViewHeaderDesc( browser: ControlRef; column: DataBrowserTableViewColumnID; var desc: DataBrowserListViewHeaderDesc ): OSStatus; external name '_GetDataBrowserListViewHeaderDesc'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * SetDataBrowserListViewHeaderDesc() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.2 and later in Carbon.framework * CarbonLib: in CarbonLib 1.5 and later * Non-Carbon CFM: not available } function SetDataBrowserListViewHeaderDesc( browser: ControlRef; column: DataBrowserTableViewColumnID; var desc: DataBrowserListViewHeaderDesc ): OSStatus; external name '_SetDataBrowserListViewHeaderDesc'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { * SetDataBrowserListViewHeaderBtnHeight() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserListViewHeaderBtnHeight( browser: ControlRef; height: UInt16 ): OSStatus; external name '_SetDataBrowserListViewHeaderBtnHeight'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserListViewHeaderBtnHeight() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserListViewHeaderBtnHeight( browser: ControlRef; var height: UInt16 ): OSStatus; external name '_GetDataBrowserListViewHeaderBtnHeight'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserListViewUsePlainBackground() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserListViewUsePlainBackground( browser: ControlRef; usePlainBackground: Boolean ): OSStatus; external name '_SetDataBrowserListViewUsePlainBackground'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserListViewUsePlainBackground() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserListViewUsePlainBackground( browser: ControlRef; var usePlainBackground: Boolean ): OSStatus; external name '_GetDataBrowserListViewUsePlainBackground'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserListViewDisclosureColumn() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserListViewDisclosureColumn( browser: ControlRef; column: DataBrowserTableViewColumnID; expandableRows: Boolean ): OSStatus; external name '_SetDataBrowserListViewDisclosureColumn'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserListViewDisclosureColumn() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserListViewDisclosureColumn( browser: ControlRef; var column: DataBrowserTableViewColumnID; var expandableRows: Boolean ): OSStatus; external name '_GetDataBrowserListViewDisclosureColumn'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { kDataBrowserColumnView API } { * GetDataBrowserColumnViewPath() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserColumnViewPath( browser: ControlRef; path: Handle ): OSStatus; external name '_GetDataBrowserColumnViewPath'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserColumnViewPathLength() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserColumnViewPathLength( browser: ControlRef; var pathLength: UInt32 ): OSStatus; external name '_GetDataBrowserColumnViewPathLength'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserColumnViewPath() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserColumnViewPath( browser: ControlRef; length: UInt32; path: DataBrowserItemIDPtr ): OSStatus; external name '_SetDataBrowserColumnViewPath'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * SetDataBrowserColumnViewDisplayType() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function SetDataBrowserColumnViewDisplayType( browser: ControlRef; propertyType: DataBrowserPropertyType ): OSStatus; external name '_SetDataBrowserColumnViewDisplayType'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * GetDataBrowserColumnViewDisplayType() * * Mac OS X threading: * Not thread safe * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: in CarbonLib 1.1 and later * Non-Carbon CFM: not available } function GetDataBrowserColumnViewDisplayType( browser: ControlRef; var propertyType: DataBrowserPropertyType ): OSStatus; external name '_GetDataBrowserColumnViewDisplayType'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { DataBrowser UPP macros } { Customizing Data Browser Accessibility Information Warning: The following assumes you already understand how to handle the Accessibility Carbon Events described in CarbonEvents.h. Data Browser automatically handles the various Accessibility Carbon Events to provide a large amount of Accessibility information. However, your application may need to override or augment the default information that Data Browser provides. Though it is already possible for your application to install various Accessibility Carbon Event handlers on a Data Browser instance, it is impossible to interpret the AXUIElementRefs contained in the events without the help of the Data Browser. A given AXUIElementRef that is passed to Data Browser list view in an Accessibility Carbon Event could represent a row, a cell, or the list view as a whole. If your application needs to add an attribute to only the rows in a list view, your application will need to ask Data Browser what any given AXUIElementRef represents. The AXUIElementGetDataBrowserItemInfo allows your application to ask that question. Additionally, your application may want to generate its own AXUIElementRefs that represent children of or point to various rows or cells of a Data Browser instance. The AXUIElementCreateWithDataBrowserAndItemInfo API allows your application to manufacture AXUIElementRefs that represent certain parts of a Data Browser so you can provide them in your Accessibility Carbon Event handlers. Typical Usage Scenario: You want to add an Accessibility attribute to all rows in a Data Browser list view. Step 1: Install the appropriate Accessibility Carbon Event handlers on your Data Browser instance. Call InstallEventHandler or a similar API to install a handler onto your Data Browser ControlRef for the kEventAccessibleGetAllAttributeNames, kEventAccessibleGetNamedAttribute, and other appropriate events. Step 2: Your handler should find out what part of the Data Browser is being asked for its accessibility information. Extract the kEventParamAccessibleObject parameter out of the Carbon Event and pass it to AXUIElementGetDataBrowserItemInfo. See that API description for more usage information and calling requirements. Examine the DataBrowserAccessibilityItemInfo structure that is filled out to determine whether it represents the part of the Data Browser you are interested in adding an attribute to. In this case, you are looking for a row, so you would make sure the item field is not kDataBrowserNoItem, and that the columnProperty is kDataBrowserItemNoProperty. Step 3: Your event handler should call CallNextEventHandler to allow the Data Browser to do the default handling of the event. This is particularly important if the AXUIElementRef did not represent a row, since you don't want to disrupt the Data Browser's handling of the event for parts other than rows. Step 4: If you determined that the part was a row in step 2, your handler should now do whatever custom work it deems necessary. For the kEventAccessibleGetAllAttributeNames, your handler would extract the kEventParamAccessibleAttributeNames parameter out of the event and add your custom attribute name to the array. For the kEventAccessibleGetNamedAttribute event, your handler would test the kEventParamAccessibleAttributeName parameter to see if it matches your custom attribute name; if so, your handler would put its custom data in the kEventParamAccessibleAttributeValue parameter. Any other events would be handled similarly. Step 5: Your event handler should return an appropriate result code. In cases where the AXUIElementRef does not represent a row or when the attribute name is not your custom attribute, your handler can return the same result code that was returned by CallNextEventHandler in step 3. In cases where your handler decided to augment or override the default handling of the event, your handler will typically want to return noErr. See the Carbon Event documentation for more details on the meanings of result codes returned by event handlers. } { * DataBrowserAccessibilityItemInfoV0 * * Summary: * A specific description of Data Browser accessibility item * information. * * Discussion: * If you fill this structure as part of a * DataBrowserAccessibilityItemInfo, you must set the * DataBrowserAccessibilityItemInfo's version field to zero. } type DataBrowserAccessibilityItemInfoV0 = record { * The DataBrowserItemID of the container the AXUIElementRef * represents or lives within. Even kDataBrowserNoItem might be * meaningful, since it is the root container ID if you haven't * overridden it via SetDataBrowserTarget. In list view, the * container helps narrow down the AXUIElementRef to either a * disclosed child of another row, or the list as a whole. In column * view, the container helps narrow down the AXUIElementRef to a * column; also see the columnProperty description below. } container: DataBrowserItemID; { * The DataBrowserItemID of the item the AXUIElementRef represents or * lives within. If item is kDataBrowserNoItem, the AXUIElementRef * represents just the container. In list view, the item helps narrow * down the AXUIElementRef to either a row, or the root container as * a whole. In column view, the item helps narrow down the * AXUIElementRef to either a cell, or a column as a whole; also see * the columnProperty description below. } item: DataBrowserItemID; { * The DataBrowserPropertyID of the column the AXUIElementRef * represents or lives within. If columnProperty is * kDataBrowserItemNoProperty and item is not kDataBrowserNoItem, the * AXUIElementRef represents a whole row. In list view, this field * helps narrow down the AXUIElementRef to either a cell, or a row as * a whole. In column view, the columnProperty will/must always be * set to kDataBrowserItemNoProperty unless the AXUIElementRef * represents the preview column. When the AXUIElementRef represents * the preview column, the columnProperty will/must always be set to * kDataBrowserColumnViewPreviewProperty, and the other fields of * this structure will/must be set to zero or the equivalent constant. } columnProperty: DataBrowserPropertyID; { * The DataBrowserPropertyPart of the sub-cell part the * AXUIElementRef represents. Examples include the disclosure * triangle in a cell, the text in a cell, and the check box in a * cell. If propertyPart is kDataBrowserPropertyEnclosingPart and * columnProperty is not kDataBrowserItemNoProperty, the * AXUIElementRef represents the cell as a whole. In both list view * and column view, this field helps narrow down the AXUIElementRef * to either a sub-cell part, or a cell as a whole. For column view, * also see the columnProperty description above. } propertyPart: DataBrowserPropertyPart; end; { * DataBrowserAccessibilityItemInfoV1 * * Summary: * A specific description of Data Browser accessibility item * information. * * Discussion: * If you fill this structure as part of a * DataBrowserAccessibilityItemInfo, you must set the * DataBrowserAccessibilityItemInfo's version field to one. * * This structure is identical to the V0 structure except for the * inclusion of row and column indicies. These indicies may be * useful to clients who call AXUIElementGetDataBrowserItemInfo. * * If your Data Browser instance allows a given item and/or * container to be displayed more than once at a given point in * time, you can use the row and column indicies to differentiate * the particular visual occurances of that item when calling * AXUIElementCreateWithDataBrowserAndItemInfo. See the additional * details in the rowIndex and columnIndex discussions below. } type DataBrowserAccessibilityItemInfoV1 = record { * The DataBrowserItemID of the container the AXUIElementRef * represents or lives within. Even kDataBrowserNoItem might be * meaningful, since it is the root container ID if you haven't * overridden it via SetDataBrowserTarget. In list view, the * container helps narrow down the AXUIElementRef to either a * disclosed child of another row, or the list as a whole. In column * view, the container helps narrow down the AXUIElementRef to a * column; also see the columnProperty description below. } container: DataBrowserItemID; { * The DataBrowserItemID of the item the AXUIElementRef represents or * lives within. If item is kDataBrowserNoItem, the AXUIElementRef * represents just the container. In list view, the item helps narrow * down the AXUIElementRef to either a row, or the root container as * a whole. In column view, the item helps narrow down the * AXUIElementRef to either a cell, or a column as a whole; also see * the columnProperty description below. } item: DataBrowserItemID; { * The DataBrowserPropertyID of the column the AXUIElementRef * represents or lives within. If columnProperty is * kDataBrowserItemNoProperty and item is not kDataBrowserNoItem, the * AXUIElementRef represents a whole row. In list view, this field * helps narrow down the AXUIElementRef to either a cell, or a row as * a whole. In column view, the columnProperty will/must always be * set to kDataBrowserItemNoProperty unless the AXUIElementRef * represents the preview column. When the AXUIElementRef represents * the preview column, the columnProperty will/must always be set to * kDataBrowserColumnViewPreviewProperty, and the other fields of * this structure will/must be set to zero or the equivalent constant. } columnProperty: DataBrowserPropertyID; { * The DataBrowserPropertyPart of the sub-cell part the * AXUIElementRef represents. Examples include the disclosure * triangle in a cell, the text in a cell, and the check box in a * cell. If propertyPart is kDataBrowserPropertyEnclosingPart and * columnProperty is not kDataBrowserItemNoProperty, the * AXUIElementRef represents the cell as a whole. In both list view * and column view, this field helps narrow down the AXUIElementRef * to either a sub-cell part, or a cell as a whole. For column view, * also see the columnProperty description above. } propertyPart: DataBrowserPropertyPart; { * The zero-based DataBrowserTableViewRowIndex of the row specified * by the other parts of this structure. If the other parts of this * structure do not specify a row or a part thereof, this field * will/must be set to zero; because this field is zero based, you * must test the other parts this structure to see whether this field * is meaningful. In list view, when the other parts of this * structure specify an item or part thereof, this field will/must be * set to the row index at which the specified item can be found. In * column view, when the other parts of this structure specify a cell * or part thereof, this field will/must be set to the row index at * which the specified cell can be found. } rowIndex: DataBrowserTableViewRowIndex; { * The zero-based DataBrowserTableViewColumnIndex of the column * specified by the other parts of this structure. If the other parts * of this structure do not specify a column or a part thereof, this * field will/must be set to zero; because this field is zero based, * you must test the other parts this structure to see whether this * field is meaningful. In list view, when the other parts of this * structure specify a cell or part thereof, this field will/must be * set to the column index at which the specified cell can be found. * In column view, when the other parts of this structure specify a * column or part thereof, this field will/must be set to the column * index at which the specified cell can be found. } columnIndex: DataBrowserTableViewColumnIndex; end; { * DataBrowserAccessibilityItemInfo * * Summary: * A generalized description of Data Browser accessibility item * information. * * Discussion: * Pass this structure to AXUIElementGetDataBrowserItemInfo or * AXUIElementCreateWithDataBrowserAndItemInfo. } type DataBrowserAccessibilityItemInfo = record { * A UInt32 which identifies how to interpret the following union. * Set this field to zero if you fill out the union's data in the * form of a DataBrowserAccessibilityItemInfoV0 structure. Set this * field to one if you fill out the union's data in the form of a * DataBrowserAccessibilityItemInfoV1 structure. } version: UInt32; case SInt16 of 0: ( v0: DataBrowserAccessibilityItemInfoV0; ); 1: ( v1: DataBrowserAccessibilityItemInfoV1; ); end; { * AXUIElementGetDataBrowserItemInfo() * * Summary: * Gets a description of the part of a Data Browser represented by a * given AXUIElementRef. * * Mac OS X threading: * Not thread safe * * Parameters: * * inElement: * An AXUIElementRef representing part of a Data Browser. * * inDataBrowser: * A Data Browser ControlRef. * * inDesiredInfoVersion: * A UInt32 indicating the the version you want the ioInfo * structure passed back as. Currently, the only supported version * is zero, so you must pass zero in the inDesiredInfoVersion * parameter. * * outInfo: * A DataBrowserAccessibilityItemInfo that will be filled in with * a description of the part of the Data Browser that the * AXUIElementRef represents. * * Result: * An OSStatus result code. The function will return noErr if it was * able to generate a description of the AXUIElementRef. If the * AXUIElementRef does not represent the Data Browser you passed in, * the function will return paramErr. If the AXUIElementRef * represents some non-item part of the Data Browser, the function * will return errDataBrowserItemNotFound. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function AXUIElementGetDataBrowserItemInfo( inElement: AXUIElementRef; inDataBrowser: ControlRef; inDesiredInfoVersion: UInt32; var outInfo: DataBrowserAccessibilityItemInfo ): OSStatus; external name '_AXUIElementGetDataBrowserItemInfo'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { * AXUIElementCreateWithDataBrowserAndItemInfo() * * Summary: * Creates an AXUIElementRef to represent some part of a Data * Browser accessibility hierarchy. * * Mac OS X threading: * Not thread safe * * Parameters: * * inDataBrowser: * A Data Browser ControlRef. * * inInfo: * A DataBrowserAccessibilityItemInfo describing the part of the * Data Browser for which you want to create an AXUIElementRef. * * Result: * An AXUIElementRef representing the part, or NULL if one cannot be * created to represent the part you specified. * * Availability: * Mac OS X: in version 10.4 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.4 and later * Non-Carbon CFM: not available } function AXUIElementCreateWithDataBrowserAndItemInfo( inDataBrowser: ControlRef; const (*var*) inInfo: DataBrowserAccessibilityItemInfo ): AXUIElementRef; external name '_AXUIElementCreateWithDataBrowserAndItemInfo'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {---------------------------------------------------------------------------------------} { EditUnicodeText Control } {---------------------------------------------------------------------------------------} { This control is only available in Mac OS X. It is super similar to Edit Text control } { Use all the same Get/Set tags. But don't ask for the TEHandle. } {---------------------------------------------------------------------------------------} { This callback supplies the functionality of the TSMTEPostUpdateProcPtr that is used } { in the EditText control. A client should supply this call if they want to look at } { inline text that has been fixed before it is included in the actual body text } { if the new text (i.e. the text in the handle) should be included in the body text } { the client should return true. If the client wants to block the inclusion of the } { text they should return false. } type EditUnicodePostUpdateProcPtr = function( uniText: UniCharArrayHandle; uniTextLength: UniCharCount; iStartOffset: UniCharArrayOffset; iEndOffset: UniCharArrayOffset; refcon: UnivPtr ): Boolean; type EditUnicodePostUpdateUPP = EditUnicodePostUpdateProcPtr; { * NewEditUnicodePostUpdateUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.0 and later * Non-Carbon CFM: not available } function NewEditUnicodePostUpdateUPP( userRoutine: EditUnicodePostUpdateProcPtr ): EditUnicodePostUpdateUPP; external name '_NewEditUnicodePostUpdateUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * DisposeEditUnicodePostUpdateUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.0 and later * Non-Carbon CFM: not available } procedure DisposeEditUnicodePostUpdateUPP( userUPP: EditUnicodePostUpdateUPP ); external name '_DisposeEditUnicodePostUpdateUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { * InvokeEditUnicodePostUpdateUPP() * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.0 and later * Non-Carbon CFM: not available } function InvokeEditUnicodePostUpdateUPP( uniText: UniCharArrayHandle; uniTextLength: UniCharCount; iStartOffset: UniCharArrayOffset; iEndOffset: UniCharArrayOffset; refcon: UnivPtr; userUPP: EditUnicodePostUpdateUPP ): Boolean; external name '_InvokeEditUnicodePostUpdateUPP'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) const kControlEditUnicodeTextProc = 912; kControlEditUnicodeTextPasswordProc = 914; { Control Kind Tag } const kControlKindEditUnicodeText = FourCharCode('eutx'); { The HIObject class ID for the HITextField class. } {$ifc USE_CFSTR_CONSTANT_MACROS} {$definec kHITextFieldClassID CFSTRP('com.apple.HITextField')} {$endc} { * CreateEditUnicodeTextControl() * * Summary: * Creates a new edit text control. * * Discussion: * This is the preferred edit text control. Use it instead of the * EditText control. This control handles Unicode and draws its text * using antialiasing, which the other control does not. * * Mac OS X threading: * Not thread safe * * Parameters: * * window: * The window in which the control should be placed. May be NULL * in 10.3 and later. * * boundsRect: * The bounds of the control, in local coordinates of the window. * * text: * The text of the control. May be NULL. * * isPassword: * A Boolean indicating whether the field is to be used as a * password field. Passing false indicates that the field is to * display entered text normally. True means that the field will * be used as a password field and any text typed into the field * will be displayed only as bullets. * * style: * The control's font style, size, color, and so on. May be NULL. * * outControl: * On exit, contains the new control (if noErr is returned as the * result code). * * Result: * An operating system result code. * * Availability: * Mac OS X: in version 10.0 and later in Carbon.framework * CarbonLib: not available in CarbonLib 1.x, is available on Mac OS X version 10.0 and later * Non-Carbon CFM: not available } function CreateEditUnicodeTextControl( window: WindowRef; const (*var*) boundsRect: Rect; text: CFStringRef { can be NULL }; isPassword: Boolean; {const} style: ControlFontStyleRecPtr { can be NULL }; var outControl: ControlRef ): OSStatus; external name '_CreateEditUnicodeTextControl'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) { The EditUnicodeText control supports these tags previously defined for the EditText control: kControlEditTextLockedTag kControlFontStyleTag kControlEditTextFixedTextTag kControlEditTextTextTag kControlEditTextKeyFilterTag kControlEditTextValidationProcTag kControlEditTextSelectionTag kControlEditTextKeyScriptBehaviorTag kControlEditTextCFStringTag kControlEditTextPasswordTag kControlEditTextPasswordCFStringTag } { Tagged data supported by EditUnicodeText control only } const kControlEditTextSingleLineTag = FourCharCode('sglc'); { data is a Boolean; indicates whether the control should always be single-line} kControlEditTextInsertTextBufferTag = FourCharCode('intx'); { data is an array of char; get or set the control's text as WorldScript-encoded text} kControlEditTextInsertCFStringRefTag = FourCharCode('incf'); { data is a CFStringRef; get or set the control's text as a CFStringRef. Caller should release CFString if getting.} kControlEditUnicodeTextPostUpdateProcTag = FourCharCode('upup'); { data is a UnicodePostUpdateUPP; get or set the post-update proc} {$ifc OLDROUTINENAMES} {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} { ₯ OLDROUTINENAMES } {ΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡΡ} const kControlCheckboxUncheckedValue = kControlCheckBoxUncheckedValue; kControlCheckboxCheckedValue = kControlCheckBoxCheckedValue; kControlCheckboxMixedValue = kControlCheckBoxMixedValue; const inLabel = kControlLabelPart; inMenu = kControlMenuPart; inTriangle = kControlTrianglePart; inButton = kControlButtonPart; inCheckBox = kControlCheckBoxPart; inUpButton = kControlUpButtonPart; inDownButton = kControlDownButtonPart; inPageUp = kControlPageUpPart; inPageDown = kControlPageDownPart; const kInLabelControlPart = kControlLabelPart; kInMenuControlPart = kControlMenuPart; kInTriangleControlPart = kControlTrianglePart; kInButtonControlPart = kControlButtonPart; kInCheckBoxControlPart = kControlCheckBoxPart; kInUpButtonControlPart = kControlUpButtonPart; kInDownButtonControlPart = kControlDownButtonPart; kInPageUpControlPart = kControlPageUpPart; kInPageDownControlPart = kControlPageDownPart; {$endc} {OLDROUTINENAMES} {$ALIGN MAC68K} end.
unit AllStars; interface uses Types, UITypes, FMX_Types, contnrs; const STARS_COUNT = 150; type TStarItem = class Loc: TPointF; Speed: double; procedure Draw(const c: TCanvas); end; TStarsApp = class private FWidth, FHeight: double; FStars: TObjectList; public constructor Create(const AWidth, AHeight: double); destructor Destroy; override; procedure Update; procedure Draw(const c: TCanvas); procedure ResizeView(const AWidth, AHeight: double); end; implementation uses Classes; { TStarsApp } constructor TStarsApp.Create(const AWidth, AHeight: double); var i: integer; s: TStarItem; begin FWidth := AWidth; FHeight := AHeight; FStars := TObjectList.Create; for i := 0 to STARS_COUNT-1 do begin s := TStarItem.Create; s.Loc := PointF(random(round(FWidth)), random(round(FHeight))); s.Speed := 1 + random(2); FStars.Add(s); end; end; destructor TStarsApp.Destroy; begin FStars.Free; inherited; end; procedure TStarsApp.Draw(const c: TCanvas); var i: integer; s: TStarItem; begin c.Clear(claBlack); for i := 0 to FStars.Count-1 do begin s := TStarItem(FStars[i]); s.Draw(c); end; end; procedure TStarsApp.ResizeView(const AWidth, AHeight: double); var i: integer; s: TStarItem; temp: double; begin FWidth := AWidth; FHeight := AHeight; for i := 0 to FStars.Count-1 do begin s := TStarItem(FStars[i]); temp := s.Loc.X; s.Loc.X := s.Loc.Y; s.Loc.Y := temp; end; end; procedure TStarsApp.Update; var i: integer; s: TStarItem; begin for i := 0 to FStars.Count-1 do begin s := TStarItem(FStars[i]); s.Loc.Y := s.Loc.Y + s.Speed; if s.Loc.Y > FHeight then s.Loc := PointF(random(round(FWidth)),0); end; end; { TStarItem } procedure TStarItem.Draw(const c: TCanvas); begin if Speed > 2 then c.Stroke.Color := MakeColor(255,255,255) else if Speed > 1 then c.Stroke.Color := MakeColor(190,190,190) else c.Stroke.Color := MakeColor(100,100,100); c.StrokeThickness := 1; c.Stroke.Kind := TBrushKind.bkSolid; c.DrawLine(PointF(Loc.X-1, Loc.Y), PointF(Loc.X+1, Loc.Y), 1); c.DrawLine(PointF(Loc.X, Loc.Y-1), PointF(Loc.X, Loc.Y+1), 1); end; initialization Randomize; end.
unit uModel; interface type TEndereco = class private FLogradouro: string; FBairro: string; FCEP: String; FCidade: string; procedure SetBairro(const Value: string); procedure SetCEP(const Value: String); procedure SetCidade(const Value: string); procedure SetLogradouro(const Value: string); published property Logradouro : string read FLogradouro write SetLogradouro; property Bairro : string read FBairro write SetBairro; property Cidade : string read FCidade write SetCidade; property CEP : String read FCEP write SetCEP; end; TPessoa = class private FNome: string; FEndereco: TEndereco; procedure SetNome(const Value: string); procedure SetEndereco(const Value: TEndereco); { private declarations } protected { protected declarations } public { public declarations } property Nome : string read FNome write SetNome; property Endereco : TEndereco read FEndereco write SetEndereco; end; TPessoaFisica = class(TPessoa) private FCPF: string; procedure SetCPF(const Value: string); { private declarations } protected { protected declarations } public { public declarations } property CPF : string read FCPF write SetCPF; end; TCliete = class(TPessoaFisica) private FSaldo: Double; FLimiteCredito: Integer; procedure SetSaldo(const Value: Double); procedure SetLimiteCredito(val: Integer); { private declarations } protected { protected declarations } public { public declarations } property Saldo: Double read FSaldo write SetSaldo; property LimiteCredito: Double read FLimiteCredito write SetLimiteCredito; end; TPessoaJuridica = class(TPessoa) private FCNPJ: string; procedure SetCNPJ(const Value: string); { private declarations } protected { protected declarations } public { public declarations } property CNPJ:string read FCNPJ write SetCNPJ; end; TFornecedor = class(TPessoaJuridica) private FPrazoentrega: Integer; procedure SetPrazoentrega(const Value: Integer); { private declarations } protected { protected declarations } public { public declarations } property Prazoentrega:Integer read FPrazoentrega write SetPrazoentrega; end; implementation { TPessoa } procedure TPessoa.SetEndereco(const Value: TEndereco); begin FEndereco := Value; end; procedure TPessoa.SetNome(const Value: string); begin FNome := Value; end; { TPessoaFisica } procedure TPessoaFisica.SetCPF(const Value: string); begin FCPF := Value; end; { TCliete } procedure TCliete.SetSaldo(const Value: Double); begin FSaldo := Value; end; { TPessoaJuridica } procedure TPessoaJuridica.SetCNPJ(const Value: string); begin FCNPJ := Value; end; { TFornecedor } procedure TFornecedor.SetPrazoentrega(const Value: Integer); begin FPrazoentrega := Value; end; { TEndereco } procedure TEndereco.SetBairro(const Value: string); begin FBairro := Value; end; procedure TEndereco.SetCEP(const Value: String); begin FCEP := Value; end; procedure TEndereco.SetCidade(const Value: string); begin FCidade := Value; end; procedure TEndereco.SetLogradouro(const Value: string); begin FLogradouro := Value; end; procedure TCliete.SetLimiteCredito(val: Integer); begin end; end.
unit BaseTypesUnit; {* Базовые типы, используемые в адаптере } // Модуль: "w:\garant6x\implementation\Garant\tie\Garant\GblAdapterLib\BaseTypesUnit.pas" // Стереотип: "Interfaces" // Элемент модели: "BaseTypes" MUID: (456EA56002BF) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , IOUnit //#UC START# *456EA56002BFintf_uses* //#UC END# *456EA56002BFintf_uses* ; const {* Общие константы, используемые в GblAdapter } NODE_FLAG_STORABLE_ENTITY: Integer = 1; {* маска, применяемая к Node::flags. Если BaseEntity::storable == true, то (Node::flags AND NODE_FLAG_STORABLE_ENTITY) возвращает true } PROPERTY_PATH_DELIMITER: PAnsiChar = /; {* символ - разделитель частей пути } DEFAULT_PRELOAD_CACHE: Cardinal = 50; {* Размер по умолчанию при подгрузке фильтрованных эелментов дерева атрибутов. } LIBRARY_NAME: PAnsiChar = GblAdapter.dll; {* Название библиотеки } ALL_DOCUMENTS_KIND: unsigned long long = -1; type TClassId = Cardinal; {* Идентификатор класса объекта } TObjectId = Cardinal; {* Идентификатор объекта внутри класса } TPId = record {* Persistent ID, тип для идентификации хранимых объектов. } class_id: TClassId; {* идентификатор класса } object_id: TObjectId; {* идентификатор объекта } end;//TPId TDate = record {* Дата. } day: unsigned short; {* Число } month: unsigned short; {* Месяц } year: unsigned short; {* Год. } //#UC START# *456EA6F00109publ* //#UC END# *456EA6F00109publ* end;//TDate TDateInterval = record {* Интервал дат (включающий). } start: ; {* начальная дата } finish: ; {* завершающая дата } end;//TDateInterval TTime = record {* Время } hour: unsigned short; {* часы } min: unsigned short; {* минуты } sec: unsigned short; {* секунды } end;//TTime TDateTime = record {* Дата и время } date: ; {* Дата } time: ; {* время } end;//TDateTime TLanguages = ( {* Языки } LG_RUSSIAN {* Русский } , LG_ENGLISH {* Английский } , LG_FRENCH {* Французский } , LG_GERMAN {* Немецкий } , LG_SPANISH {* Испанский } , LG_ITALIAN {* Итальянский } );//TLanguages INamedElement = interface {* Именованный элемент. } ['{E6AAFF18-FAD7-4E46-A586-CEEC45905094}'] procedure GetName; stdcall; procedure SetName(const aValue); stdcall; procedure GetComment; stdcall; procedure SetComment(const aValue); stdcall; property Name: read GetName write SetName; {* имя } property Comment: read GetComment write SetComment; {* комментарий } end;//INamedElement ConstantModify = class {* Исключение возникает при попытке изменить константный параметер. } end;//ConstantModify AccessDenied = class {* Возбуждается в случае нарушения прав доступа. } end;//AccessDenied InvalidTimeStamp = class {* Исключение возбуждается в случае если запрошенная операция не может быть выполнена на сервер, по причине неверной метки синхронизации. Возможно необходимо повторить вызов. } end;//InvalidTimeStamp StorageLocked = class {* База блокирована } end;//StorageLocked Unsupported = class {* Возвращается в случае если вызванная опреация не поддеоживается объектом. } end;//Unsupported NotSaved = class {* Возвращается при попытке сохранить/восстановить изменения в несохраненном (т.е не привязанном к месту хранения, например к папкам) объекте } end;//NotSaved FoldersNotAvailable = class {* Папки недоступны. Возвращается в случае, если у пользователя нет доступа к папкам. } end;//FoldersNotAvailable CanNotFindData = class {* Запрошенные данные не найдены. Возвращается в случае, если данные запрошенные по операции get_<something> отсутствуют. } end;//CanNotFindData DuplicateNode = class {* Возникает в случае добавления узла в дерево, где уже есть такой же узел. При этом уникальность определяется самим узлом. } end;//DuplicateNode InvalidType = class {* Плохой тип данных } end;//InvalidType CanNotSave = class {* объект не может быть сохранён } end;//CanNotSave InvalidXMLType = class {* Ошибка при разборе XML } end;//InvalidXMLType AllContentIsFiltered = class {* Всё сожержимое отфильтровано, что противоречит бизнес-логике } end;//AllContentIsFiltered TCodePage = short; {* номер кодовой страницы } IEntityStorage = interface {* Хранилище сущностей } ['{D4613491-81A1-4AD8-B51E-95923E4DA97A}'] procedure GetContentType; stdcall; {* получить тип содержимого } procedure GetCachedContent; stdcall; {* получить содежимое } end;//IEntityStorage IEntityBase = interface {* Базовый абстрактный интерфейс для сущностей. Данный интерфейс должен заменить устаревыший BaseTreeSupport::BaseEntity . } ['{AC2E64E2-18A5-4F4A-B16F-A186B4F6BB37}'] function GetIsSaved: ByteBool; stdcall; function GetIsChanged: ByteBool; stdcall; function GetEid: Cardinal; stdcall; { can raise Unsupported } procedure SaveTo(var storage: IEntityStorage; out aRet {* IEntityStorage }); stdcall; { can raise AccessDenied, Unsupported, NotSaved, DuplicateNode, CanNotSave } {* Перезаписать сущность текущей сущностью. } procedure AppendTo(var storage: IEntityStorage; out aRet {* IEntityStorage }); stdcall; { can raise ConstantModify, AccessDenied, Unsupported, CanNotSave } {* Сохраняет в базе измененное состояние объекта. Объеденяя с с ранее сохраненными данными } property IsSaved: ByteBool read GetIsSaved; {* Признак того что данный объект уже сохранен в базе данных. Для не сохраненный объекта сначало необходимо указать место хранения (чаще всего папки). Для не сохраненных объектов операция save вернет исключение. } property IsChanged: ByteBool read GetIsChanged; {* свойство изменённости } property Eid: Cardinal read GetEid; {* идентификатор } end;//IEntityBase EmptyResult = class {* Возвращается при операции по изменению дерева в случае, если результат получается пустой, и это запрещенно логикой конкретеного дерева. } end;//EmptyResult TItemStatus = ( {* Статус элемента. } IS_ABOLISHED {* Утратил силу } , IS_ACTIVE {* Действующий } , IS_PREACTIVE {* Не вступил в силу } , IS_UNKNOWN {* Неопределен } );//TItemStatus TNavigatorMenuItemType = ( {* Возможные типы элементов основного меню. } NM_FOLDER {* Псевдоэлемент - папка. } , NM_RUBRICATOR {* Навигатор по классификатору. } , NM_ATTRIBUTE_SEARCH {* Поиск по атрибутам. } , NM_SITUATION_SEARCH {* Поиск по ситуации. } , NM_PUBLISH_SOURCE_SEARCH {* Поиск по источнику опубликования. } , NM_SINGLE_CONTEXT_SEARCH {* Атомарный (простой) поиск по контексту. } , NM_SINGLE_ATTRIBUTE_SEARCH {* Атомарный (простой) поиск по древовидному атрибуту. } , NM_SINGLE_DATE_NUMBER_SEARCH {* Атомарный (простой) поиск по дате и номеру. } , NM_FILTER_5X {* Карточка фильтра а-ля Гарант 5.х. } , NM_ATTRIBUTE_SEARCH_5X {* Карточка поиска по атрибутам а-ля Гарант 5.х. } , NM_SITUATION_SEARCH_5X {* Карточка поиска по ситуациям а-ля Гарант 5.х. } , NM_UPDATE {* Обновление. } , NM_CONFIGURATION_LIST {* Список конфигураций. } , NM_LIST {* Список. } , NM_COMPLECT_INFO {* Информация о комплекте. } , NM_DOCUMENT {* Документ } , NM_LAW_NAVIGATOR_FOLDER {* Папка "Правовой навигатор" } , NM_BUSINESS_INFO_FOLDER {* Папка "Справочная информация" } , NM_SEARCH_FOLDER {* Папка "Поиск" } , NM_UPDATE_FOLDER {* Папка "Обновление" } , NM_RECENTLY_DOCUMENTS_FOLDER {* Папка "Последние открытые документы" } , NM_EXPLANATORY_DICTIONARY {* Толковый словарь } , NM_NEW_DOCS {* Новые документы } , NM_PRIME_FOLDER {* пункт меню ПРАЙМ } , NM_REVIEW {* пункт меню ОБЗОРЫ ЗАКОНОДАТЕЛЬСТВА } , NM_NEWS_LINE {* мониторинги } , NM_SEARCH_WITH_LAW_SUPPORT {* Пункт меню: Поиск с правовой поддержкой } , NM_LAW_SUPPORT {* пункт меню: правовая поддержка } , NM_CALENDAR , NM_BUSINESS_REFERENCES , NM_HOT_INFORMATION , NM_CODEX {* Кодексы } , NM_FORMS {* Формы документа } , NM_MONITORINGS {* Мониторинги } , NM_PHARM_SEARCH {* поиск в инфарме } , NM_INPHARM {* Инфарм } , NM_PHARM_LEK {* Лекарственные препараты } , NM_PHARM_FIRMS {* Фирмы производители } , NM_PHARM_DICT {* Словарь медицинских терминов } , NM_PHARM_BASIC_SECTION {* Основные разделы справочника } , NM_TAXES_AND_FINANCE {* Налоги и финансы } , NM_BUSINESS_REFERENCES_FOLDER {* Папка Бизнес-справки } , NM_LEGAL_ISSUES {* Юридические вопросы } , NM_HR {* Зарплата и кадры } , NM_BUDGET_ORGS {* Гос. и муниципальные учреждения } , NM_LAW_FOR_ALL {* Право для всех } , NM_GOS_ZAKUPKI );//TNavigatorMenuItemType TSearchResultType = ( {* Тип результата поиска } SRT_DOCUMENT_LIST {* найден список документов } , SRT_AUTOREFERAT {* найден автореферат } , SRT_CONSULTATION {* найдена консультация } );//TSearchResultType ISearchEntity = interface {* Сущность, передаваемая в метод finish_process на прогресс индикаторе, как результат поиска } ['{8299FB1B-C061-4407-84D9-AF61A0E35754}'] function GetResultType: TSearchResultType; stdcall; function GetDocumentCount: size; stdcall; function GetEntryCount: size; stdcall; function GetEditionCount: size; stdcall; property ResultType: TSearchResultType read GetResultType; {* Тип результата поиска (список, автореферат, консультация) } property DocumentCount: size read GetDocumentCount; {* Количество найденных документов } property EntryCount: size read GetEntryCount; {* Количество вхождений } property EditionCount: size read GetEditionCount; {* количество редакций } end;//ISearchEntity TSortOrder = ( {* Направление сортировки. } SO_ASCENDING {* По возрастанию значений. } , SO_DESCENDING {* По убыванию значений. } );//TSortOrder TSortType = ( {* Тип сортировки. } ST_PRIORITY {* Сортировка по юридической силе } , ST_CREATE_DATE {* Сортировка по дате создания } , ST_LAST_EDIT_DATE {* Сортировка по дате последнего изменения } , ST_NOT_SORTED {* Не отсортирован } , ST_RELEVANCE {* сортировка по релевантности } );//TSortType TSortParams = record {* Параметры сортировки. } sort_order: TSortOrder; {* порядок сортировки } sort_type: TSortType; {* тип сортивровки } end;//TSortParams TTextSearchOptionType = ( {* Типы поиска по контексту } TSO_TEXT {* поиск по тексту } , TSO_NAME {* поиск по заголовку } , TSO_PARA {* поиск по параграфу } , TSO_SENTENCE {* поиск по предложению } );//TTextSearchOptionType IVariant = interface {* тип данных для нотификации } ['{0B872568-888B-4CC1-B7ED-D0E555EDA7B7}'] function GetLong: Integer; stdcall; { can raise InvalidType } {* вернуть целое } function GetBool: ByteBool; stdcall; { can raise InvalidType } {* вернуть булево значение } procedure GetString(out aRet {* IString }); stdcall; { can raise InvalidType } {* вернуть строку } procedure GetObject(out aRet {* IUnknown }); stdcall; { can raise InvalidType } {* вернуть объект } end;//IVariant ILanguagesList = array of TLanguages; {* Список языков } IStringList = array of IString; {* контейнер строк } InternalDatabaseError = class {* Произошла внутреняя ошибка при обращении к базе } end;//InternalDatabaseError NoSession = class {* выбрасывается из методов, которые могут дергаться только в контексте сессии, т.е. после логина } end;//NoSession DuplicateName = class {* Элемент с таким именем уже существует, а два и более созадвать нельзя } end;//DuplicateName TUid = Integer; {* идентификатор пользователя или группы } TListNodeType = ( LNT_SUB {* Саб } , LNT_PARA {* Параграф } , LNT_EXTERNAL_OBJECT {* Объект, открываемый во внешнем приложении } , LNT_EXTERNAL_LINK , LNT_DOCUMENT_ABOLISHED {* Утративший силу документ } , LNT_DOCUMENT_ACTIVE {* Документ } , LNT_DOCUMENT_PREACTIVE {* Не вступивший в силу документ } , LNT_DOCUMENT_UNKNOWN {* Неизвестный тип } , LNT_EDITION_ABOLISHED {* Утратившая силу редакция } , LNT_EDITION_ACTIVE {* Актуальная редакция } , LNT_EDITION_PREACTIVE {* Редакция, которая еще не действует } , LNT_EDITION_UNKNOWN {* Неизвестный тип редакции } , LNT_EDITIONS_GROUP {* Узел Редакции } , LNT_BLOCK {* Блок } , LNT_DRUG_ANNULED {* препарат аннулирован } , LNT_DRUG_NARCOTIC {* наркотический препарат } , LNT_DRUG_NONANNULED_NONNARCOTIC {* разрешённый ненаркотический препарат } , LNT_FORM_ANNULED {* аннулированная форма препарата } , LNT_FORM_RUSSIAN_IMPORTANT {* жизненноважный российский препарат } , LNT_FORM_NONRUSSIAN_IMPORTANT {* жизненноважный иностранный препарат } , LNT_FORM_RUSSIAN_NONIMPORTANT {* российский препарат } , LNT_FORM_NONRUSSIAN_NONIMPORTANT {* иностранный препарат } , LNT_FIRM {* Фирма } , LNT_AAK {* Документ ААК } );//TListNodeType TBaseTypesObjectId = TObjectId; {* Это создал Шура, т.к. были коллизии с модулем ActiveX и его ObjectId в модуле Document } function Make; overload; stdcall; {* создать нулевую дату } function Make(y: unsigned short; m: unsigned short; d: unsigned short); overload; stdcall; {* создать заданную дату } implementation uses l3ImplUses //#UC START# *456EA56002BFimpl_uses* //#UC END# *456EA56002BFimpl_uses* ; function Make; {* создать нулевую дату } //#UC START# *462C9BE5030D_456EA6F00109_var* //#UC END# *462C9BE5030D_456EA6F00109_var* begin System.FillChar(Result, SizeOf(Result), 0); //#UC START# *462C9BE5030D_456EA6F00109_impl* !!! Needs to be implemented !!! //#UC END# *462C9BE5030D_456EA6F00109_impl* end;//Make function Make(y: unsigned short; m: unsigned short; d: unsigned short); {* создать заданную дату } //#UC START# *462C9BF10128_456EA6F00109_var* //#UC END# *462C9BF10128_456EA6F00109_var* begin System.FillChar(Result, SizeOf(Result), 0); //#UC START# *462C9BF10128_456EA6F00109_impl* !!! Needs to be implemented !!! //#UC END# *462C9BF10128_456EA6F00109_impl* end;//Make end.
unit DAO.PlanilhaEntradaEntregas; interface uses Generics.Collections, System.Classes, System.SysUtils, Forms, Windows, Model.PlanilhaEntradaEntregas; type TPlanilhaEntradaEntregasDAO = class public function GetPlanilha(sFile: String): TObjectList<TPlanilhaEntradaEntregas>; end; implementation { TPlanilhaEntradaEntregasDAO } uses Common.Utils; function TPlanilhaEntradaEntregasDAO.GetPlanilha(sFile: String): TObjectList<TPlanilhaEntradaEntregas>; var ArquivoCSV: TextFile; sLinha: String; sDetalhe: TStringList; entradas : TObjectList<TPlanilhaEntradaEntregas>; i : Integer; lstRemessa: TStringList; iIndex: Integer; bFlag: Boolean; begin try entradas := TObjectList<TPlanilhaEntradaEntregas>.Create; if not FileExists(sFile) then begin Application.MessageBox(PChar('Arquivo ' + sFile + ' não foi encontrado!'), 'Atenção', MB_ICONWARNING + MB_OK); Exit; end; AssignFile(ArquivoCSV, sFile); if sFile.IsEmpty then Exit; sDetalhe := TStringList.Create; sDetalhe.StrictDelimiter := True; sDetalhe.Delimiter := ';'; lstRemessa := TStringList.Create; Reset(ArquivoCSV); Readln(ArquivoCSV, sLinha); if Copy(sLinha, 0, 38) <> 'CONSULTA DE ENTREGAS NA WEB POR STATUS' then begin Application.MessageBox('Arquivo informado não foi identificado como a Planilha de Entrada de Entregas!', 'Atenção', MB_ICONWARNING + MB_OK); Exit; end; sDetalhe.DelimitedText := sLinha; if sDetalhe.Count <> 26 then begin Application.MessageBox('Quantidade de Colunas não indica ser da Planilha de Entrada de Entregas!', 'Atenção', MB_ICONWARNING + MB_OK); Exit; end; i := 0; while not Eoln(ArquivoCSV) do begin Readln(ArquivoCSV, sLinha); sDetalhe.DelimitedText := sLinha + ';'; bFlag := False; if TUtils.ENumero(sDetalhe[0]) then begin if StrToIntDef(sDetalhe[25], 1) > 1 then begin if not lstRemessa.Find(sDetalhe[2], iIndex) then begin lstRemessa.Add(sDetalhe[2]); lstRemessa.Sort; bFlag := True; end else begin bFlag := False; end; end else begin bFlag := True; end; if bFlag then begin entradas.Add(TPlanilhaEntradaEntregas.Create); i := entradas.Count - 1; entradas[i].CodigoDestino := sDetalhe[0]; entradas[i].NomeDestino := sDetalhe[1]; entradas[i].NossoNumero := sDetalhe[2]; entradas[i].CodigoCliente := sDetalhe[3]; entradas[i].NumeroNF := sDetalhe[4]; entradas[i].NomeConsumidor := sDetalhe[5]; entradas[i].AosCuidados := sDetalhe[6]; entradas[i].Logradouro := sDetalhe[7]; entradas[i].Complemento := sDetalhe[8]; entradas[i].Bairro := sDetalhe[9]; entradas[i].Cidade := sDetalhe[10]; entradas[i].CEP := sDetalhe[11]; entradas[i].Telefone := sDetalhe[12]; entradas[i].Expedicao := sDetalhe[13]; entradas[i].Previsao := sDetalhe[14]; entradas[i].Status := sDetalhe[15]; entradas[i].DescricaoStatus := sDetalhe[16]; entradas[i].NomeEntregador := sDetalhe[17]; entradas[i].Container := sDetalhe[18]; entradas[i].ValorProuto := sDetalhe[19]; entradas[i].ValorVerba := sDetalhe[20]; entradas[i].Altura := sDetalhe[21]; entradas[i].Largura := sDetalhe[22]; entradas[i].Comprimento := sDetalhe[23]; entradas[i].Peso := sDetalhe[24]; entradas[i].Volume := sDetalhe[25]; end; end; end; Result := entradas; finally CloseFile(ArquivoCSV); end; end; end.
unit uSceneClass; interface uses uScene, Graphics, uGraph, uResFont, uButton; type TSceneClass = class(TSceneCustom) private FLogo: TBitmap; FIsLoad: Boolean; FGraph: TGraph; FTemp: TBitmap; FFont: TResFont; FBack: TBitmap; FBtn: array[1..2] of TButton; procedure Load; procedure DoNext; procedure DoPrev; public //** Конструктор. constructor Create; //** Деструктор. destructor Destroy; override; procedure Draw(); override; function MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; override; function MouseMove(X, Y: Integer): Boolean; override; function Click(Button: TMouseBtn): Boolean; override; function Keys(var Key: Word): Boolean; override; end; implementation uses uUtils, uSCR; { TSceneClass } function TSceneClass.Click(Button: TMouseBtn): Boolean; begin Result := True; end; constructor TSceneClass.Create; begin FIsLoad := False; end; destructor TSceneClass.Destroy; var I: Byte; begin for I := Low(FBtn) to High(FBtn) do FBtn[I].Free; FGraph.Free; FBack.Free; FLogo.Free; FFont.Free; inherited; end; procedure TSceneClass.DoNext; begin end; procedure TSceneClass.DoPrev; begin end; procedure TSceneClass.Draw; var I: Byte; begin if not FIsLoad then Load; FTemp := Graphics.TBitmap.Create; FTemp.Assign(FLogo); with FTemp.Canvas do begin IsGame := False; for I := Low(FBtn) to High(FBtn) do FBtn[I].Draw; end; SCR.BG.Canvas.Draw(0, 0, FTemp); FTemp.Free; end; function TSceneClass.Keys(var Key: Word): Boolean; begin TransKeys(Key); Result := True; case Key of 13: DoNext; 27: DoPrev; end; end; procedure TSceneClass.Load; begin FIsLoad := True; FBtn[1] := TButton.Create(10, 540, FLogo.Canvas, 'Назад'); FBtn[2] := TButton.Create(590, 540, FLogo.Canvas, 'Играть'); end; function TSceneClass.MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; var I: Byte; begin Result := False; for I := Low(FBtn) to High(FBtn) do FBtn[I].MouseDown(X, Y); SceneManager.Draw; end; function TSceneClass.MouseMove(X, Y: Integer): Boolean; var I: Byte; begin Result := False; for I := Low(FBtn) to High(FBtn) do FBtn[I].Draw; SceneManager.Draw; end; end.
unit dec8_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m6502,m6809,main_engine,controls_engine,ym_2203,ym_3812,gfx_engine, rom_engine,pal_engine,sound_engine,misc_functions,mcs51,timer_engine; function iniciar_dec8:boolean; implementation const srd_rom:array[0..1] of tipo_roms=( (n:'dy01-e.b14';l:$10000;p:$0;crc:$176e9299),(n:'dy00.b16';l:$10000;p:$10000;crc:$2bf6b461)); srd_char:tipo_roms=(n:'dy05.b6';l:$4000;p:$0000;crc:$8780e8a3); srd_tiles:array[0..1] of tipo_roms=( (n:'dy03.b4';l:$10000;p:$0000;crc:$44f2a4f9),(n:'dy02.b5';l:$10000;p:$10000;crc:$522d9a9e)); srd_snd:tipo_roms=(n:'dy04.d7';l:$8000;p:$8000;crc:$2ae3591c); srd_sprites:array[0..5] of tipo_roms=( (n:'dy07.h16';l:$8000;p:$0000;crc:$97eaba60),(n:'dy06.h14';l:$8000;p:$8000;crc:$c279541b), (n:'dy09.k13';l:$8000;p:$10000;crc:$d30d1745),(n:'dy08.k11';l:$8000;p:$18000;crc:$71d645fd), (n:'dy11.k16';l:$8000;p:$20000;crc:$fd9ccc5b),(n:'dy10.k14';l:$8000;p:$28000;crc:$88770ab8)); srd_mcu:tipo_roms=(n:'id8751h.mcu';l:$1000;p:0;crc:$11cd6ca4); //Dip srd_dip_a:array [0..5] of def_dip=( (mask:$3;name:'Coin A';number:4;dip:((dip_val:$3;dip_name:'1C 2C'),(dip_val:$2;dip_name:'1C 3C'),(dip_val:$1;dip_name:'1C 4C'),(dip_val:$0;dip_name:'1C 6C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$4;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$c;dip_name:'1C 1C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$20;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Flip Screen';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$80;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); srd_dip_b:array [0..5] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$1;dip_name:'1'),(dip_val:$3;dip_name:'3'),(dip_val:$2;dip_name:'5'),(dip_val:$0;dip_name:'28'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Difficulty';number:4;dip:((dip_val:$8;dip_name:'Easy'),(dip_val:$c;dip_name:'Normal'),(dip_val:$4;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'Bonus Life';number:2;dip:((dip_val:$10;dip_name:'Every 50K'),(dip_val:$0;dip_name:'Every 100K'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'After Stage 10';number:2;dip:((dip_val:$20;dip_name:'Back to Stager 1'),(dip_val:$0;dip_name:'Game Over'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Allow Continue';number:2;dip:((dip_val:$80;dip_name:'No'),(dip_val:$0;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var scroll_x,i8751_return,i8751_value:word; i8751_port0,mcu_irq_timer,rom_bank,sound_latch:byte; rom:array[0..5,0..$3fff] of byte; snd_dec:array[0..$7fff] of byte; procedure update_video_dec8; var f,nchar,color,atrib,x,y:word; procedure draw_sprites(pri:byte); var x,y,f,nchar:word; color,atrib:byte; flipy:boolean; begin for f:=0 to $7f do begin atrib:=buffer_sprites[(f*4)+1]; color:=(atrib and $03)+((atrib and $08) shr 1); if ((pri=0) and (color<>0)) then continue; if ((pri=1) and (color=0)) then continue; nchar:=buffer_sprites[(f*4)+3]+((atrib and $e0) shl 3); if (nchar=0) then continue; x:=buffer_sprites[f*4]; y:=buffer_sprites[(f*4)+2]; flipy:=(atrib and $04)<>0; if (atrib and $10)<>0 then begin put_gfx_sprite_diff(nchar,$40+(color shl 3),false,flipy,2,0,0); put_gfx_sprite_diff(nchar+1,$40+(color shl 3),false,flipy,2,16,0); actualiza_gfx_sprite_size(x,y,4,32,16); end else begin put_gfx_sprite(nchar,$40+(color shl 3),false,flipy,2); actualiza_gfx_sprite(x,y,4,2); end; end; end; begin for f:=0 to $1ff do begin atrib:=memoria[$1400+(f*2)]; color:=(atrib and $f0) shr 4; if (gfx[1].buffer[f] or buffer_color[color]) then begin x:=f div 32; y:=31-(f mod 32); nchar:=memoria[$1401+(f*2)]+((atrib and $3) shl 8); put_gfx(x*16,y*16,nchar,color shl 4,2,1); if color=0 then put_gfx_block_trans(x*16,y*16,3,16,16) else put_gfx_trans(x*16,y*16,nchar,color shl 4,3,1); gfx[1].buffer[f]:=false; end; end; scroll__y(2,4,256-scroll_x); draw_sprites(0); scroll__y(3,4,256-scroll_x); draw_sprites(1); //Foreground for f:=0 to $3ff do begin if gfx[0].buffer[f] then begin x:=f div 32; y:=31-(f mod 32); nchar:=memoria[$800+f]; put_gfx_trans(x*8,y*8,nchar,$80,1,0); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,0,256,256,1,0,0,256,256,4); actualiza_trozo_final(8,0,240,256,4); fillchar(buffer_color[0],MAX_COLOR_BUFFER,0); end; procedure eventos_dec8; begin if event.arcade then begin //P1 if arcade_input.right[0] then marcade.in0:=marcade.in0 and $fe else marcade.in0:=marcade.in0 or 1; if arcade_input.left[0] then marcade.in0:=marcade.in0 and $fd else marcade.in0:=marcade.in0 or 2; if arcade_input.up[0] then marcade.in0:=marcade.in0 and $fb else marcade.in0:=marcade.in0 or 4; if arcade_input.down[0] then marcade.in0:=marcade.in0 and $f7 else marcade.in0:=marcade.in0 or 8; if arcade_input.but0[0] then marcade.in0:=marcade.in0 and $ef else marcade.in0:=marcade.in0 or $10; if arcade_input.but1[0] then marcade.in0:=marcade.in0 and $df else marcade.in0:=marcade.in0 or $20; if arcade_input.start[0] then marcade.in0:=marcade.in0 and $bf else marcade.in0:=marcade.in0 or $40; if arcade_input.start[1] then marcade.in0:=marcade.in0 and $7f else marcade.in0:=marcade.in0 or $80; //P2 if arcade_input.right[1] then marcade.in1:=marcade.in1 and $fe else marcade.in1:=marcade.in1 or 1; if arcade_input.left[1] then marcade.in1:=marcade.in1 and $fd else marcade.in1:=marcade.in1 or 2; if arcade_input.up[1] then marcade.in1:=marcade.in1 and $fb else marcade.in1:=marcade.in1 or 4; if arcade_input.down[1] then marcade.in1:=marcade.in1 and $f7 else marcade.in1:=marcade.in1 or 8; if arcade_input.but0[1] then marcade.in1:=marcade.in1 and $ef else marcade.in1:=marcade.in1 or $10; if arcade_input.but1[1] then marcade.in1:=marcade.in1 and $df else marcade.in1:=marcade.in1 or $20; //i8751 if arcade_input.coin[1] then marcade.in2:=marcade.in2 and $df else marcade.in2:=marcade.in2 or $20; if arcade_input.coin[0] then marcade.in2:=marcade.in2 and $bf else marcade.in2:=marcade.in2 or $40; end; end; procedure principal_dec8; var frame_m,frame_s,frame_mcu:single; f:word; begin init_controls(false,false,false,true); frame_m:=m6809_0.tframes; frame_s:=m6502_0.tframes; frame_mcu:=mcs51_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 263 do begin //Main m6809_0.run(frame_m); frame_m:=frame_m+m6809_0.tframes-m6809_0.contador; //Sound m6502_0.run(frame_s); frame_s:=frame_s+m6502_0.tframes-m6502_0.contador; //MCU mcs51_0.run(frame_mcu); frame_mcu:=frame_mcu+mcs51_0.tframes-mcs51_0.contador; case f of 247:begin m6809_0.change_nmi(PULSE_LINE); update_video_dec8; marcade.in1:=marcade.in1 or $40; end; 263:marcade.in1:=marcade.in1 and $bf; end; end; eventos_dec8; video_sync; end; end; function getbyte_dec8(direccion:word):byte; begin case direccion of $0..$17ff,$8000..$ffff:getbyte_dec8:=memoria[direccion]; $2000:getbyte_dec8:=i8751_return shr 8; $2001:getbyte_dec8:=i8751_return and $ff; $2800..$288f:getbyte_dec8:=buffer_paleta[direccion and $ff]; $3000..$308f:getbyte_dec8:=buffer_paleta[(direccion and $ff)+$100]; $3800:getbyte_dec8:=marcade.dswa; //dsw0 $3801:getbyte_dec8:=marcade.in0; $3802:getbyte_dec8:=marcade.in1; $3803:getbyte_dec8:=marcade.dswb; //dsw1 $4000..$7fff:getbyte_dec8:=rom[rom_bank,direccion and $3fff]; end; end; procedure cambiar_color(dir:word); var tmp_color:byte; color:tcolor; bit0,bit1,bit2,bit3:byte; begin tmp_color:=buffer_paleta[dir]; //Red bit0:=(tmp_color and 1) shr 0; bit1:=(tmp_color and 2) shr 1; bit2:=(tmp_color and 4) shr 2; bit3:=(tmp_color and 8) shr 3; color.r:=$03*bit0+$1f*bit1+$43*bit2+$8f*bit3; //Green bit0:=(tmp_color and $10) shr 4; bit1:=(tmp_color and $20) shr 5; bit2:=(tmp_color and $40) shr 6; bit3:=(tmp_color and $80) shr 7; color.g:=$03*bit0+$1f*bit1+$43*bit2+$8f*bit3; //Blue tmp_color:=buffer_paleta[dir+$100]; bit0:=tmp_color and 1; bit1:=(tmp_color and 2) shr 1; bit2:=(tmp_color and 4) shr 2; bit3:=(tmp_color and 8) shr 3; color.b:=$03*bit0+$1f*bit1+$43*bit2+$8f*bit3; set_pal_color(color,dir); buffer_color[(dir shr 4) and $f]:=true; end; procedure putbyte_dec8(direccion:word;valor:byte); begin case direccion of 0..$7ff,$c00..$13ff:memoria[direccion]:=valor; $800..$bff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $1400..$17ff:if memoria[direccion]<>valor then begin gfx[1].buffer[(direccion and $3ff) shr 1]:=true; memoria[direccion]:=valor; end; $1800:begin i8751_value:=(i8751_value and $ff) or (valor shl 8); mcs51_0.change_irq1(ASSERT_LINE); timers.enabled(mcu_irq_timer,true); end; $1801:i8751_value:=(i8751_value and $ff00) or valor; $1802:;//i8751_return:=0; $1804:copymemory(@buffer_sprites[0],@memoria[$600],$200); //DMA $1805:begin rom_bank:=valor shr 5; scroll_x:=(scroll_x and $ff) or ((valor and $f) shl 8); end; $1806:scroll_x:=(scroll_x and $f00) or valor; $2000:begin sound_latch:=valor; m6502_0.change_nmi(PULSE_LINE); end; $2001:main_screen.flip_main_screen:=valor<>0; $2800..$288f:if buffer_paleta[direccion and $ff]<>valor then begin buffer_paleta[direccion and $ff]:=valor; cambiar_color(direccion and $ff); end; $3000..$308f:if buffer_paleta[(direccion and $ff)+$100]<>valor then begin buffer_paleta[(direccion and $ff)+$100]:=valor; cambiar_color(direccion and $ff); end; $4000..$ffff:; //ROM end; end; function getbyte_snd_dec8(direccion:word):byte; begin case direccion of 0..$5ff:getbyte_snd_dec8:=mem_snd[direccion]; $2000:getbyte_snd_dec8:=ym2203_0.status; $2001:getbyte_snd_dec8:=ym2203_0.Read; $4000:getbyte_snd_dec8:=ym3812_0.status; $6000:getbyte_snd_dec8:=sound_latch; $8000..$ffff:if m6502_0.opcode then getbyte_snd_dec8:=snd_dec[direccion and $7fff] else getbyte_snd_dec8:=mem_snd[direccion]; end; end; procedure putbyte_snd_dec8(direccion:word;valor:byte); begin case direccion of 0..$5ff:mem_snd[direccion]:=valor; $2000:ym2203_0.control(valor); $2001:ym2203_0.write(valor); $4000:ym3812_0.control(valor); $4001:ym3812_0.write(valor); $8000..$ffff:; //ROM end; end; procedure dec8_sound_update; begin ym2203_0.Update; ym3812_0.update; end; //MCU function in_port0:byte; begin in_port0:=i8751_port0; end; function in_port2:byte; begin in_port2:=$ff; end; function in_port3:byte; begin in_port3:=marcade.in2; end; procedure out_port0(valor:byte); begin i8751_port0:=valor; end; procedure out_port2(valor:byte); begin if (valor and $10)=0 then i8751_port0:=i8751_value shr 8; if (valor and $20)=0 then i8751_port0:=i8751_value and $ff; if (valor and $40)=0 then i8751_return:=(i8751_return and $ff) or (i8751_port0 shl 8); if (valor and $80)=0 then i8751_return:=(i8751_return and $ff00) or i8751_port0; if (valor and $4)=0 then m6809_0.change_irq(ASSERT_LINE); if (valor and $2)=0 then m6809_0.change_irq(CLEAR_LINE); end; procedure i8751_irq; begin timers.enabled(mcu_irq_timer,false); mcs51_0.change_irq1(CLEAR_LINE); end; procedure snd_irq(irqstate:byte); begin m6502_0.change_irq(irqstate); end; //Main procedure reset_dec8; begin m6809_0.reset; m6502_0.reset; mcs51_0.reset; ym2203_0.reset; ym3812_0.reset; marcade.in0:=$ff; marcade.in1:=$bf; //VBlank off marcade.in2:=$ff; sound_latch:=0; rom_bank:=0; i8751_return:=0; i8751_value:=0; i8751_port0:=0; scroll_x:=0; end; function iniciar_dec8:boolean; const pc_x:array[0..7] of dword=($2000*8+0, $2000*8+1, $2000*8+2, $2000*8+3, 0, 1, 2, 3); ps_x:array[0..15] of dword=(16*8, 1+(16*8), 2+(16*8), 3+(16*8), 4+(16*8), 5+(16*8), 6+(16*8), 7+(16*8), 0,1,2,3,4,5,6,7); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 , 8*8,9*8,10*8,11*8,12*8,13*8,14*8,15*8); pt_x:array[0..15] of dword=(0, 1, 2, 3, 1024*8*8+0, 1024*8*8+1, 1024*8*8+2, 1024*8*8+3, 16*8+0, 16*8+1, 16*8+2, 16*8+3, 16*8+1024*8*8+0, 16*8+1024*8*8+1, 16*8+1024*8*8+2, 16*8+1024*8*8+3); var f:word; memoria_temp,memoria_temp2:array[0..$3ffff] of byte; begin iniciar_dec8:=false; llamadas_maquina.bucle_general:=principal_dec8; llamadas_maquina.reset:=reset_dec8; llamadas_maquina.fps_max:=57.444583; iniciar_audio(false); screen_init(1,256,256,true); screen_init(2,256,512); screen_mod_scroll(2,256,256,255,512,256,511); screen_init(3,256,512,true); screen_mod_scroll(3,256,256,255,512,256,511); screen_init(4,256,512,false,true); iniciar_video(240,256); //Main CPU m6809_0:=cpu_m6809.Create(2000000,264,TCPU_M6809); m6809_0.change_ram_calls(getbyte_dec8,putbyte_dec8); //Sound CPU m6502_0:=cpu_m6502.create(1500000,264,TCPU_M6502); m6502_0.change_ram_calls(getbyte_snd_dec8,putbyte_snd_dec8); m6502_0.init_sound(dec8_sound_update); //MCU mcs51_0:=cpu_mcs51.create(8000000,264); mcs51_0.change_io_calls(in_port0,nil,in_port2,in_port3,out_port0,nil,out_port2,nil); mcu_irq_timer:=timers.init(mcs51_0.numero_cpu,64,i8751_irq,nil,false); //Sound Chip ym2203_0:=ym2203_chip.create(1500000,0.5,0.5); ym3812_0:=ym3812_chip.create(YM3812_FM,3000000,0.7); ym3812_0.change_irq_calls(snd_irq); //cargar roms y ponerlas en su sitio if not(roms_load(@memoria_temp,srd_rom)) then exit; copymemory(@rom[4,0],@memoria_temp[0],$4000); copymemory(@rom[5,0],@memoria_temp[$4000],$4000); copymemory(@memoria[$8000],@memoria_temp[$8000],$8000); //Cheat! //memoria[$96e4]:=$39; copymemory(@rom[0,0],@memoria_temp[$10000],$4000); copymemory(@rom[1,0],@memoria_temp[$14000],$4000); copymemory(@rom[2,0],@memoria_temp[$18000],$4000); copymemory(@rom[3,0],@memoria_temp[$1c000],$4000); //cargar roms audio y desencriptar if not(roms_load(@mem_snd,srd_snd)) then exit; for f:=$8000 to $ffff do snd_dec[f-$8000]:=bitswap8(mem_snd[f],7,5,6,4,3,2,1,0); //cargar ROM MCU if not(roms_load(mcs51_0.get_rom_addr,srd_mcu)) then exit; //Cargar chars if not(roms_load(@memoria_temp,srd_char)) then exit; init_gfx(0,8,8,$400); gfx[0].trans[0]:=true; gfx_set_desc_data(2,0,8*8,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@ps_y,false,true); //Cargar tiles y ponerlas en su sitio if not(roms_load(@memoria_temp,srd_tiles)) then exit; for f:=0 to 3 do begin copymemory(@memoria_temp2[$10000*f],@memoria_temp[$4000*f],$4000); copymemory(@memoria_temp2[$8000+($10000*f)],@memoria_temp[$10000+($4000*f)],$4000); end; init_gfx(1,16,16,$400); for f:=0 to 7 do gfx[1].trans[f]:=true; gfx_set_desc_data(4,4,32*8,$8000*8,$8000*8+4,0,4); for f:=0 to 3 do convert_gfx(1,$100*f*16*16,@memoria_temp2[$10000*f],@pt_x,@ps_y,false,true); //Cargar sprites if not(roms_load(@memoria_temp,srd_sprites)) then exit; init_gfx(2,16,16,$800); gfx[2].trans[0]:=true; gfx_set_desc_data(3,0,16*16,$10000*8,$20000*8,$0*8); convert_gfx(2,0,@memoria_temp,@ps_x,@ps_y,false,true); //DIP marcade.dswa:=$7f; marcade.dswb:=$ff; marcade.dswa_val:=@srd_dip_a; marcade.dswb_val:=@srd_dip_b; //final reset_dec8; iniciar_dec8:=true; end; end.
namespace Sugar.Test; interface uses Sugar, Sugar.Data.Json, Sugar.Collections, RemObjects.Elements.EUnit; type JsonObjectParserTest = public class (Test) private JObj: JsonObject := nil; public method EmptyObject; method SimpleObjectStringValue; method SimpleObjectIntValue; method SimpleObjectFloatValue; method SimpleObjectLongValue; method SimpleObjectBigIntegerValue; method SimpleObjectNullValue; method SimpleObjectTrueValue; method SimpleObjectFalseValue; method MultiValuesObject; method NestedObject; method NestedArray; method UnprotectedKey; method UnprotectedValue; method NonObjectParseFails; method UnclosedObjectFails; method NilJsonFails; method BrokenFormatJsonFails; end; implementation method JsonObjectParserTest.EmptyObject; begin JObj := JsonObject.Load("{}"); Assert.IsNotNil(JObj); Assert.AreEqual(JObj.Count, 0); end; method JsonObjectParserTest.SimpleObjectStringValue; begin JObj := JsonObject.Load('{ "v":"1"}'); Assert.IsNotNil(JObj); Assert.AreEqual(JObj.Count, 1); Assert.AreEqual(JObj["v"].Kind, JsonValueKind.String); Assert.AreEqual(JObj["v"].ToStr, "1"); end; method JsonObjectParserTest.SimpleObjectIntValue; begin JObj := JsonObject.Load('{"v":1}'); Assert.IsNotNil(JObj); Assert.AreEqual(JObj.Count, 1); Assert.AreEqual(JObj["v"].Kind, JsonValueKind.Integer); Assert.AreEqual(JObj["v"].ToInteger, 1); end; method JsonObjectParserTest.SimpleObjectFloatValue; begin JObj := JsonObject.Load('{ "PI":3.141E-10}'); Assert.IsNotNil(JObj); Assert.AreEqual(JObj.Count, 1); Assert.AreEqual(JObj["PI"].Kind, JsonValueKind.Double); Assert.AreEqual(JObj["PI"].ToDouble, 3.141E-10); end; method JsonObjectParserTest.SimpleObjectLongValue; begin JObj := JsonObject.Load('{"v":12345123456789}'); Assert.IsNotNil(JObj); Assert.AreEqual(JObj.Count, 1); Assert.AreEqual(JObj["v"].Kind, JsonValueKind.Integer); Assert.AreEqual(JObj["v"].ToInteger, 12345123456789); end; method JsonObjectParserTest.SimpleObjectBigIntegerValue; begin JObj := JsonObject.Load('{"v":999999999999999999999999999999999999999999999999999999}'); Assert.IsNotNil(JObj); Assert.AreEqual(JObj.Count, 1); Assert.AreEqual(JObj["v"].Kind, JsonValueKind.Double); Assert.AreEqual(JObj["v"].ToDouble, 1E+54); end; method JsonObjectParserTest.SimpleObjectNullValue; begin JObj := JsonObject.Load('{"v":null}'); Assert.IsNotNil(JObj); Assert.AreEqual(JObj.Count, 1); Assert.AreEqual(JObj["v"].Kind, JsonValueKind.Null); Assert.AreEqual(JObj["v"].IsNull, true); end; method JsonObjectParserTest.SimpleObjectTrueValue; begin JObj := JsonObject.Load('{"v":true}'); Assert.IsNotNil(JObj); Assert.AreEqual(JObj.Count, 1); Assert.AreEqual(JObj["v"].Kind, JsonValueKind.Boolean); Assert.AreEqual(JObj["v"].ToBoolean, true); end; method JsonObjectParserTest.SimpleObjectFalseValue; begin JObj := JsonObject.Load('{"v":false}'); Assert.IsNotNil(JObj); Assert.AreEqual(JObj.Count, 1); Assert.AreEqual(JObj["v"].Kind, JsonValueKind.Boolean); Assert.AreEqual(JObj["v"].ToBoolean, false); end; method JsonObjectParserTest.MultiValuesObject; begin JObj := JsonObject.Load('{ "a":1.7E308, "b": 42, "c": null, "d": "string"}'); Assert.IsNotNil(JObj); Assert.AreEqual(JObj.Count, 4); Assert.AreEqual(JObj["a"].ToDouble, 1.7E308); Assert.AreEqual(JObj["b"].ToInteger, 42); Assert.AreEqual(JObj["c"].IsNull, true); Assert.AreEqual(JObj["d"].ToStr, "string"); end; method JsonObjectParserTest.NestedObject; begin JObj := JsonObject.Load('{ "a": "abc", "b": { "a": "abc"}}'); Assert.IsNotNil(JObj); Assert.AreEqual(JObj.Count, 2); Assert.AreEqual(JObj["a"].ToStr, "abc"); Assert.AreEqual(JObj["b"].Kind, JsonValueKind.Object); var lObj := JObj["b"].ToObject; Assert.IsNotNil(lObj); Assert.AreEqual(lObj.Count, 1); Assert.AreEqual(lObj["a"].ToStr, "abc"); end; method JsonObjectParserTest.NestedArray; begin JObj := JsonObject.Load('{ "a": "abc", "b": [1, 2]}'); Assert.IsNotNil(JObj); Assert.AreEqual(JObj.Count, 2); Assert.AreEqual(JObj["a"].ToStr, "abc"); Assert.AreEqual(JObj["b"].Kind, JsonValueKind.Array); var lObj := JObj["b"].ToArray; Assert.IsNotNil(lObj); Assert.AreEqual(lObj.Count, 2); Assert.AreEqual(lObj[0].ToInteger, 1); Assert.AreEqual(lObj[1].ToInteger, 2); end; method JsonObjectParserTest.UnprotectedKey; begin JObj := JsonObject.Load('{ a: "abc", b: "bca"}'); Assert.IsNotNil(JObj); Assert.AreEqual(JObj.Count, 2); Assert.AreEqual(JObj["a"].ToStr, "abc"); Assert.AreEqual(JObj["b"].ToStr, "bca"); end; method JsonObjectParserTest.UnprotectedValue; begin JObj := JsonObject.Load('{ a: abc, b: bca}'); Assert.IsNotNil(JObj); Assert.AreEqual(JObj.Count, 2); Assert.AreEqual(JObj["a"].ToStr, "abc"); Assert.AreEqual(JObj["b"].ToStr, "bca"); end; method JsonObjectParserTest.NonObjectParseFails; begin Assert.Throws(->JsonObject.Load("[1, 2, 3]")); end; method JsonObjectParserTest.UnclosedObjectFails; begin Assert.Throws(->JsonObject.Load('{"a": 1')); end; method JsonObjectParserTest.NilJsonFails; begin Assert.Throws(->JsonObject.Load(nil)); end; method JsonObjectParserTest.BrokenFormatJsonFails; begin Assert.Throws(->JsonObject.Load('"a": 1')); Assert.Throws(->JsonObject.Load('{true: 1}')); Assert.Throws(->JsonObject.Load('{123: 1}')); Assert.Throws(->JsonObject.Load('{"a" 1}')); Assert.Throws(->JsonObject.Load('{"a": 1 a "b": 2}')); end; end.
{ This file is part of the AF UDF library for Firebird 1.0 or high. Copyright (c) 2007-2009 by Arteev Alexei, OAO Pharmacy Tyumen. See the file COPYING.TXT, included in this distribution, for details about the copyright. 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. email: alarteev@yandex.ru, arteev@pharm-tmn.ru, support@pharm-tmn.ru **********************************************************************} unit uafdbf; {$mode objfpc} {$H+} interface uses dbf,dbf_dbffile, uafudfs, ib_util; {Creates an object to work with DBF} function CreateDBF (FileName: PChar; var AnsiOrOem: Integer; var Mode: integer; var Share: integer; var Overwrite: integer): PtrUDF; cdecl; {Creates a DBF file on disk} function CreateTableDBF (var Handle: PtrUDF): integer; cdecl; {Closes DBF} function CloseDBF (var Handle: PtrUDF): integer; cdecl; {Opens DBF} function OpenDBF (var Handle: PtrUDF): integer; cdecl; {Sets the format for creating file DBF} function SetFormatDBF (var Handle: PtrUDF; var FormatDBF: integer): integer; cdecl; function GetFormatDBF (var Handle: PtrUDF): integer; cdecl; //------------------------------------------------------------------------------ (*** Navigation on the table ***) {Move the cursor in the table ahead 1} function NextInDBF (var Handle: PtrUDF): integer; cdecl; {Move the cursor in the table back to 1} function PrevInDBF (var Handle: PtrUDF): integer; cdecl; {Move the cursor to the top of the table} function FirstInDBF (var Handle: PtrUDF): integer; cdecl; {Move the cursor to the end of the table} function LastInDBF (var Handle: PtrUDF): integer; cdecl; {Returns for the end of the table table} function EofInDBF (var Handle: PtrUDF): integer; cdecl; {Current line number in the open table} function RecNoDBF (var Handle: PtrUDF): integer; cdecl; {Number of rows in the table otrutoy} function RecordCountDBF (var Handle: PtrUDF): integer; cdecl; {Move the cursor to an open position at the table from the beginning NewRecNO table} function SetRecNoDBF (var Handle: PtrUDF; var NewRecNO: integer): integer; cdecl; //------------------------------------------------------------------------------ (*** Editing entries ***) function StateDBF (var Handle: PtrUDF): integer; cdecl; { Saves the record } function PostDBF (var Handle: PtrUDF): integer; cdecl; { Adds an entry } function AppendDBF (var Handle: PtrUDF): integer; cdecl; {Edit current record} function EditDBF (var Handle: PtrUDF): integer; cdecl; {Deletes a record from DBF} function DeleteDBF (var Handle: PtrUDF): integer; cdecl; { Cancels editing entries } function CancelDBF (var Handle: PtrUDF): integer; cdecl; {Compress table permanently removing deleted records} function PackDBF (var Handle: PtrUDF): integer; cdecl; //------------------------------------------------------------------------------ (*** Working with Fields ***) {Creates a field in a closed table} function AddFieldDBF (var Handle: PtrUDF; FieldName: Pchar; TypeField: Pchar; var ALen, ADecLen: integer): integer; cdecl; {Returns kolichetvo fields in the table} function FieldCountDBF (var Handle: PtrUDF): integer; cdecl; {Returns whether there is a box} function FieldExistsDBF (var Handle: PtrUDF; FieldName: Pchar): integer; cdecl; {Returns the name of the field by index} function GetFieldNameDBFByIndex (var Handle: PtrUDF; var Index: Integer): Pchar; cdecl; // ------------------------------------------------ ------------------------------ (*** Work with field values ​​***) {Set value of the field for the current edited line} function SetValueDBFFieldByName (var Handle: PtrUDF; FieldName: Pchar; Value: Pchar): integer; cdecl; {Returns the value of the field for the current edited line} function GetValueDBFFieldByName (var Handle: PtrUDF; FieldName: Pchar): Pchar; cdecl; {Returns 1 if the field current line Null, otherwise 0} function ValueIsNullDBF (var Handle: PtrUDF; FieldName: Pchar): integer; cdecl; //------------------------------------------------------------------------------ implementation uses DB, SysUtils, udbfwrap; {******************************************************************} { Function: SetFormatDBF } { Purpose: Sets the format DBF } { Entrance: } { Handle - The handle of the object } { FormatDBF format compatibility DBF } { 3 - dBASE III+ } { 4 - dBASE IV (default) } { 7 - Visual dBASE VII } { 25 - FoxPro } { } { Result: 0-fail 1-successfully } { } { Description: } { } {******************************************************************} function SetFormatDBF(var Handle:PtrUDF;var FormatDBF:integer):integer;cdecl; var afobj:TAFObj; begin result := 0; try afobj := HandleToAfObj(Handle); TDbfWrap(afobj.Obj).ADbf.TableLevel:= FormatDBF; Result := 1; except on e:Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function GetFormatDBF(var Handle:PtrUDF):integer;cdecl; var afobj:TAFObj; begin result := 0; try afobj := HandleToAfObj(Handle); result := TDbfWrap(afobj.Obj).ADbf.TableLevel; except on e:Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; {******************************************************************} { Function: CreateDBF } { Purpose: Create or Open DBF } { Entrance: } { FileName } { AnsiOrOem 0=OEM 1=ANSI } { Mode 0=ReadOnly 1=Read/Write } { Share 0-Exclusive 1=Share } { Result: 0-fail or handle } { } { Description: } { } {******************************************************************} function CreateDBF(FileName:PChar;var AnsiOrOem:Integer; var Mode:integer; var Share:integer;var Overwrite:integer):PtrUDF;cdecl; var adbfwp:TDbfWrap; begin Result := 0; try adbfwp:=TDbfWrap.Create(AnsiOrOem=0); with adbfwp.adbf do begin FilePathFull:= ExtractFileDir(FileName); TableName:= ExtractFileName(FileName); Exclusive:= Share=0; ReadOnly:= Mode=0; ShowDeleted:= False; StoreDefs:=true; end; if (Overwrite=1) and (FileExists(FileName)) then DeleteFile(FileName); except if Assigned(adbfwp) then adbfwp.Free; exit; end; result := TAFObj.Create(adbfwp).Handle; end; Type TCommonFuncDBFInt = function(var afobj:TAFObj):integer; function ExecCommonFuncDbfInt(var Handle:PtrUdf;func:TCommonFuncDBFInt;DefaultResult:integer=0):integer; var afobj:TAFObj; begin result := DefaultResult; try afobj := HandleToAfObj(Handle); result := func(afobj); except on e:Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; { CreateTableDBF } function DoCreateTableDBF(var afobj:TAFObj):integer; begin TDbfWrap(afobj.Obj).ADbf.CreateTable; result := 1; end; function CreateTableDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoCreateTableDBF); end; { CloseDBF } function DoCloseDBF(var afobj:TAFObj):integer; begin TDbfWrap(afobj.Obj).ADbf.Active := false; result := 1; end; function CloseDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoCloseDBF); end; { OpenDBF } function DoOpenDBF(var afobj:TAFObj):integer; begin TDbfWrap(afobj.Obj).ADbf.Active := true; result := 1; end; function OpenDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoOpenDBF); end; { StateDBF } function DoStateDBF(var afobj:TAFObj):integer; begin result := Integer(TDbfWrap(afobj.Obj).ADbf.State); end; function StateDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoStateDBF,-1); end; { RecNoDBF } function DoRecNoDBF(var afobj:TAFObj):integer; begin result := TDbfWrap(afobj.Obj).ADbf.RecNo; end; function RecNoDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoRecNoDBF,-1); end; { RecordCountDBF } function DoRecordCountDBF(var afobj:TAFObj):integer; begin result := TDbfWrap(afobj.Obj).ADbf.RecordCount; end; function RecordCountDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoRecordCountDBF,-1); end; { PostDBF } function DoPostDBF(var afobj:TAFObj):integer; begin TDbfWrap(afobj.Obj).ADbf.Post; result := 1; end; function PostDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoPostDBF); end; { AppendDBF } function DoAppendDBF(var afobj:TAFObj):integer; begin TDbfWrap(afobj.Obj).ADbf.Append; result := 1; end; function AppendDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoAppendDBF); end; { NextInDBF } function DoNextInDBF(var afobj:TAFObj):integer; begin TDbfWrap(afobj.Obj).ADbf.Next; result := 1; end; function NextInDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoNextInDBF); end; { PrevInDBF } function DoPrevInDBF(var afobj:TAFObj):integer; begin TDbfWrap(afobj.Obj).ADbf.Prior; result := 1; end; function PrevInDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoPrevInDBF); end; { FirstInDBF } function DoFirstInDBF(var afobj:TAFObj):integer; begin TDbfWrap(afobj.Obj).ADbf.First; result := 1; end; function FirstInDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoFirstInDBF); end; { LastInDBF } function DoLastInDBF(var afobj:TAFObj):integer; begin TDbfWrap(afobj.Obj).ADbf.Last; result := 1; end; function LastInDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoLastInDBF); end; { EditDBF } function DoEditDBF(var afobj:TAFObj):integer; begin TDbfWrap(afobj.Obj).ADbf.Edit; result := 1; end; function EditDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoEditDBF); end; { DeleteDBF } function DoDeleteDBF(var afobj:TAFObj):integer; begin TDbfWrap(afobj.Obj).ADbf.Delete; result := 1; end; function DeleteDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoDeleteDBF); end; { CancelDBF } function DoCancelDBF(var afobj:TAFObj):integer; begin TDbfWrap(afobj.Obj).ADbf.Cancel; result := 1; end; function CancelDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoCancelDBF); end; { PackDBF } function DoPackDBF(var afobj:TAFObj):integer; begin TDbfWrap(afobj.Obj).ADbf.PackTable; result := 1; end; function PackDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoPackDBF); end; { FieldCountDBF } function DoFieldCountDBF(var afobj:TAFObj):integer; begin result := TDbfWrap(afobj.Obj).ADbf.FieldCount; end; function FieldCountDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoFieldCountDBF); end; { EofInDBF } function DoEofInDBF(var afobj:TAFObj):integer; begin result := Integer(TDbfWrap(afobj.Obj).ADbf.Eof); end; function EofInDBF(var Handle:PtrUDF):integer;cdecl; begin result := ExecCommonFuncDbfInt(Handle,@DoEofInDBF,1); end; function SetRecNoDBF(var Handle:PtrUDF;var NewRecNO:integer):integer;cdecl; var afobj:TAFObj; begin result := 0; try afobj := HandleToAfObj(Handle); TDbfWrap(afobj.Obj).ADbf.RecNo := NewRecNO; Result := TDbfWrap(afobj.Obj).ADbf.RecNo; except on e:Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function FieldExistsDBF(var Handle:PtrUDF;FieldName:Pchar):integer;cdecl; var afobj:TAFObj; begin result := 0; try afobj := HandleToAfObj(Handle); if TDbfWrap(afobj.Obj).ADbf.FindField(FieldName)<>nil then result := 1; except on e:Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function SetValueDBFFieldByName(var Handle:PtrUDF;FieldName:Pchar;Value:Pchar):integer;cdecl; var afobj:TAFObj; begin result := 0; try afobj := HandleToAfObj(Handle); if Value= nil then TDbfWrap(afobj.Obj).ADbf.FieldByName(FieldName).Clear else case TDbfWrap(afobj.Obj).ADbf.FieldByName(FieldName).DataType of ftDateTime:TDbfWrap(afobj.Obj).ADbf.FieldByName(FieldName).AsDateTime := StrToDateTime(Value); ftFloat, ftCurrency:TDbfWrap(afobj.Obj).ADbf.FieldByName(FieldName).AsFloat := StrToFloat(Value); else TDbfWrap(afobj.Obj).ADbf.FieldByName(FieldName).AsString := TDbfWrap(afobj.Obj).Convert(Value); end; result := 1; except on e:Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function GetFieldNameDBFByIndex(var Handle:PtrUDF;var Index:Integer):Pchar;cdecl; var afobj:TAFObj; F:TField; begin try afobj := HandleToAfObj(Handle); f:=TDbfWrap(afobj.Obj).ADbf.Fields[index]; if f<>nil then begin Result := ib_util_malloc(Length(f.FieldName)+1); StrPCopy(Result, f.FieldName); end else Result := nil; except on e:Exception do begin if Assigned(afobj) then afobj.FixedError(e); Result := nil; end; end; end; function GetValueDBFFieldByName(var Handle:PtrUDF;FieldName:Pchar):Pchar;cdecl; var afobj:TAFObj; s: String; begin try afobj := HandleToAfObj(Handle); with TDbfWrap(afobj.Obj) do begin s := Convert(ADbf.FieldByName(FieldName).AsString,False); Result := ib_util_malloc(Length(s)+1); StrPLCopy(Result,s,32765); end; except on e:Exception do begin if Assigned(afobj) then afobj.FixedError(e); Result := nil; end; end; end; function ValueIsNullDBF(var Handle:PtrUDF;FieldName:Pchar):integer;cdecl; var afobj:TAFObj; begin result := -1; try afobj := HandleToAfObj(Handle); Result := Integer(TDbfWrap(afobj.Obj).ADbf.FieldByName(FieldName).IsNull); except on e:Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function AddFieldDBF(var Handle:PtrUDF;FieldName:Pchar;TypeField:Pchar;var ALen,ADecLen:integer):integer;cdecl; var afobj:TAFObj; begin result := 0; try afobj := HandleToAfObj(Handle); if TDbfWrap(afobj.Obj).ADbf.FieldDefs.IndexOf(FieldName)<>-1 then raise Exception.CreateFmt('Field %s is exists.',[FieldName]); with TDbfWrap(afobj.Obj).ADbf.FieldDefs.AddFieldDef do begin Name:= FieldName; if TypeField='N' then DataType := ftFloat else if TypeField='C' then DataType := ftString else if TypeField='D' then DataType := ftDate else raise exception.CreateFmt('Field %s: Unknow DataType:%s',[FieldName,TypeField]); Size:= Word(ALen); Precision := Word(ADeclen); end; result := 1; except on e:Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; end.
// ============================================================================ // Delphi-interface for Philip Hazel's PCRE Vr. 3.1 // Copyright (c) 1999, Juergen Haible. All Rights Reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ============================================================================ {$ALIGN ON} // suggested {$BOOLEVAL OFF} // mandatory {$LONGSTRINGS ON} // mandatory {$IOCHECKS ON} // mandatory {$EXTENDEDSYNTAX ON} // mandatory {$WRITEABLECONST OFF} // suggested {$DEBUGINFO ON} // suggested {$LOCALSYMBOLS ON} // suggested {$REFERENCEINFO ON} // suggested unit clPCREDef; // Delphi-interface for Philip Hazel's PCRE Vr. 3.1 // ---------------------------------------------------------------------------- // Contains a Delphi-interface for: // Perl-Compatible Regular Expressions (PCRE) Vr. 3.1 // Written by Philip Hazel (<ph10@cam.ac.uk>). // Copyright (c) 1997-2000 University of Cambridge // ftp://ftp.cus.cam.ac.uk/pub/software/programs/pcre/ // When using PCRE for own programs, be aware of its license (see below). // ---------------------------------------------------------------------------- // ============================================================================ { PCRE LICENCE ------------ PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by: Philip Hazel <ph10@cam.ac.uk> University of Cambridge Computing Service, Cambridge, England. Phone: +44 1223 334714. Copyright (c) 1997-2000 University of Cambridge Permission is granted to anyone to use this software for any purpose on any computer system, and to redistribute it freely, subject to the following restrictions: 1. This software 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. 2. The origin of this software must not be misrepresented, either by explicit claim or by omission. 3. Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. If PCRE is embedded in any software that is released under the GNU General Purpose Licence (GPL), then the terms of that licence shall supersede any condition above with which it is incompatible. } // ============================================================================ {------------------------------------------------------------------------------ Steps to create the needed object-files with Borland C++ Builder 3: 1. Load and unzip PCRE-sources from: ftp://ftp.cus.cam.ac.uk/pub/software/programs/pcre/pcre-3.1.tar.gz 2. Create config.h: rename config.in config.h change: #define HAVE_STRERROR 1 change: #define HAVE_MEMMOVE 1 3. Create pcre.h: rename pcre.in pcre.h change: #define PCRE_MAJOR 3 change: #define PCRE_MINOR 1 change: #define PCRE_DATE 09-Feb-2000 (note: values taken from configure.in) 4. Create chartables.c: bcc32 dftables.c dftables >chartables.c 5. Create object-files: bcc32 -c -DSTATIC maketables.c bcc32 -c -DSTATIC get.c bcc32 -c -DSTATIC study.c bcc32 -c -DSTATIC pcre.c bcc32 -c -DSTATIC pcreposix.c 6. Create pcretest and test object-files: bcc32 -DSTATIC pcretest.c pcre.obj get.obj study.obj maketables.obj pcreposix.obj pcretest testdata\testinput1 testtry fc testtry testdata\testoutput1 pcretest -i testdata\testinput2 testtry fc testtry testdata\testoutput2 pcretest testdata\testinput3 testtry fc testtry testdata\testoutput3 The three object-files covered by this interface (pcre.obj, study.obj and [optionally] get.obj) are included with this distribution. They are built from the original sources with the steps and modifications noted above. ------------------------------------------------------------------------------} interface {$I clVer.inc} {$IFNDEF DELPHIXE} uses clWUtils; {.$DEFINE PCRE_INCLUDE_GET} // remove dot to additionally link "get.obj" const // Options PCRE_CASELESS = $0001; PCRE_MULTILINE = $0002; PCRE_DOTALL = $0004; PCRE_EXTENDED = $0008; PCRE_ANCHORED = $0010; PCRE_DOLLAR_ENDONLY = $0020; PCRE_EXTRA = $0040; PCRE_NOTBOL = $0080; PCRE_NOTEOL = $0100; PCRE_UNGREEDY = $0200; PCRE_NOTEMPTY = $0400; // Exec-time and get-time error codes PCRE_ERROR_NOMATCH = (-1); PCRE_ERROR_NULL = (-2); PCRE_ERROR_BADOPTION = (-3); PCRE_ERROR_BADMAGIC = (-4); PCRE_ERROR_UNKNOWN_NODE = (-5); PCRE_ERROR_NOMEMORY = (-6); PCRE_ERROR_NOSUBSTRING = (-7); // Request types for pcre_fullinfo() PCRE_INFO_OPTIONS = 0; PCRE_INFO_SIZE = 1; PCRE_INFO_CAPTURECOUNT = 2; PCRE_INFO_BACKREFMAX = 3; PCRE_INFO_FIRSTCHAR = 4; PCRE_INFO_FIRSTTABLE = 5; PCRE_INFO_LASTLITERAL = 6; type // Types _pcre = Pointer; _pcre_extra = Pointer; Int = LongInt; PInt = ^Int; PPChar = ^PclChar; PPPChar = ^PPChar; // Functions // const char * pcre_version(void) function _pcre_version: PclChar; cdecl; external; // pcre * pcre_compile(const char *pattern, int options, const char **errorptr, // int *erroroffset, const unsigned char *tables) function _pcre_compile( const pattern : PclChar; options : Int; const errorptr: PPChar; erroroffset : PInt; const tables : PclChar ): _pcre; cdecl; external; // int pcre_exec(const pcre *external_re, const pcre_extra *external_extra, // const char *subject, int length, int start_offset, int options, // int *offsets, int offsetcount) function _pcre_exec( const external_re : _pcre; const external_extra: _pcre_extra; const subject : PclChar; length : Int; startoffset : Int; options : Int; offsets : PInt; offsetcount : Int ): Int; cdecl; external; // int pcre_info(const pcre *external_re, int *optptr, int *first_char) function _pcre_info( const external_re: _pcre; optptr : PInt; first_char : PInt ): Int; cdecl; external; // int pcre_fullinfo(const pcre *external_re, const pcre_extra *study_data, // int what, void *where) function _pcre_fullinfo( const external_re: _pcre; const study_data : _pcre_extra; what : Int; where : Pointer ): Int; cdecl; external; // pcre_extra * pcre_study(const pcre *external_re, int options, // const char **errorptr) function _pcre_study( const external_re: _pcre; options : Int; const errorptr : PPChar ): _pcre_extra; cdecl; external; {$IFDEF PCRE_INCLUDE_GET} // int pcre_copy_substring(const char *subject, int *ovector, int stringcount, // int stringnumber, char *buffer, int size) function _pcre_copy_substring( const subject: PclChar; ovector : PInt; stringcount : Int; stringnumber : Int; buffer : PclChar; size : Int ): Int; cdecl; external; // int pcre_get_substring(const char *subject, int *ovector, int stringcount, // int stringnumber, const char **stringptr) function _pcre_get_substring( const subject : PclChar; ovector : PInt; stringcount : Int; stringnumber : Int; const stringptr: PPChar ): Int; cdecl; external; // int pcre_get_substring_list(const char *subject, int *ovector, // int stringcount, const char ***listptr) function _pcre_get_substring_list( const subject: PclChar; ovector : PInt; stringcount : Int; const listptr: PPPChar ): Int; cdecl; external; {$ENDIF} // ---------------------------------------------------------------------------- {$ENDIF} implementation {$IFNDEF DELPHIXE} uses SysUtils; // Link PCRE-objectfiles: {$LINK pcre.obj} {$LINK study.obj} {$IFDEF PCRE_INCLUDE_GET} {$LINK get.obj} {$ENDIF} // Declarations needed just to make compiler happy: function _pcre_malloc( size: Cardinal ): Pointer; cdecl; external; // procedure _pcre_free( block: Pointer ); cdecl; external; // ---------------------------------------------------------------------------- // Replacements for functions of C-runtime-library used in PCRE: type size_t = Cardinal; // void *malloc(size_t size); function _malloc( size: size_t ): Pointer; cdecl; begin Result := AllocMem( size ); end; // void free(void *block); procedure _free( block: Pointer ); cdecl; begin FreeMem( block ); end; // void *memset(void *s, int c, size_t n); function _memset( s: Pointer; c: Integer; n: size_t ): Pointer; cdecl; begin FillChar( s^, n, c ); Result := s; end; // void *memmove(void *dest, const void *src, size_t n); function _memmove( dest: Pointer; src: Pointer; n: size_t ): Pointer; cdecl; begin Move( src^, dest^, n ); Result := dest; end; // void *memcpy(void *dest, const void *src, size_t n); function _memcpy( dest: Pointer; src: Pointer; n: size_t ): Pointer; cdecl; begin Move( src^, dest^, n ); Result := dest; end; // char *strchr(const char *s, int c); function _strchr( const s: PclChar; c: Integer ): PclChar; cdecl; begin Result := StrScan( s, TclChar(c) ); end; // int strncmp(const char *s1, const char *s2, size_t maxlen); function _strncmp( const s1, s2: PclChar; maxlen: size_t ): Integer; cdecl; begin Result := StrLComp( s1, s2, maxlen ); end; // ---------------------------------------------------------------------------- {$ENDIF} end.
unit fpcorm_dbcore_constants; {$mode objfpc}{$H+} interface uses Classes, SysUtils; const c_SQL_NULL = 'NULL'; c_XML_NULL = ''; c_String_NULL = ''; c_SQL_Boolean: array [Boolean] of String = ('0', '1'); c_XML_Boolean: array [Boolean] of String = ('False', 'True'); c_String_Boolean: array [Boolean] of String = ('False', 'True'); c_SQL_DecimalSeparatorChar = '.'; c_XML_DecimalSeparatorChar = '.'; c_String_DecimalSeparatorChar = ','; c_SQL_DateTimeFormat = 'yyyymmdd hh:nn:ss.zzz'; c_XML_DateTimeFormat = 'yyyymmdd hh:nn:ss.zzz'; c_String_DateTimeFormat = 'yyyy-mm-dd hh:nn:ss'; implementation end.
unit m3DBFiler; // Модуль: "w:\common\components\rtl\Garant\m3\m3DBFiler.pas" // Стереотип: "SimpleClass" // Элемент модели: "Tm3DBFiler" MUID: (555C88FF0236) {$Include w:\common\components\rtl\Garant\m3\m3Define.inc} interface uses l3IntfUses , l3Filer , m3DBInterfaces ; type Tm3DBFiler = class(Tl3CustomFiler) private f_DB: Im3DB; f_Level: Integer; f_Part: Im3DBDocumentPart; f_PartSelector: Tm3DocPartSelector; f_ObjectIndex: Integer; protected procedure Cleanup; override; {* Функция очистки полей объекта. } function DoOpen: Boolean; override; procedure DoClose; override; procedure ClearFields; override; public constructor Create(const aDB: Im3DB; aDocID: Integer = 0; aDocPart: Tm3DocPartSelector = m3_defDocPart; aLevel: Integer = 0); reintroduce; public property Part: Im3DBDocumentPart read f_Part; property PartSelector: Tm3DocPartSelector read f_PartSelector write f_PartSelector; property ObjectIndex: Integer read f_ObjectIndex write f_ObjectIndex; end;//Tm3DBFiler implementation uses l3ImplUses , l3Types , l3Base , m3StorageInterfaces {$If NOT Defined(NoScripts)} , TtfwClassRef_Proxy {$IfEnd} // NOT Defined(NoScripts) //#UC START# *555C88FF0236impl_uses* //#UC END# *555C88FF0236impl_uses* ; constructor Tm3DBFiler.Create(const aDB: Im3DB; aDocID: Integer = 0; aDocPart: Tm3DocPartSelector = m3_defDocPart; aLevel: Integer = 0); //#UC START# *555C8A63011E_555C88FF0236_var* //#UC END# *555C8A63011E_555C88FF0236_var* begin //#UC START# *555C8A63011E_555C88FF0236_impl* inherited Create; f_DB := aDB; Handle := aDocID; f_PartSelector := aDocPart; f_Level := aLevel; //f_Index := anObjectIndex; //#UC END# *555C8A63011E_555C88FF0236_impl* end;//Tm3DBFiler.Create procedure Tm3DBFiler.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_555C88FF0236_var* //#UC END# *479731C50290_555C88FF0236_var* begin //#UC START# *479731C50290_555C88FF0236_impl* f_Part := nil; f_DB := nil; inherited; f_ObjectIndex := 0; f_Level := 0; l3FillChar(f_PartSelector, SizeOf(f_PartSelector)); //#UC END# *479731C50290_555C88FF0236_impl* end;//Tm3DBFiler.Cleanup function Tm3DBFiler.DoOpen: Boolean; //#UC START# *555C888301B0_555C88FF0236_var* function OpenDocumentStream(const aDoc : Im3DBDocument; out aPart : Im3DBDocumentPart; aPartSelector : Tm3DocPartSelector; aIndex : Integer; aMode : Tm3StoreAccess; aLevel : Integer): IStream; begin//OpenDocumentStream Assert(aDoc <> nil); aPart := aDoc.GetVersion(aLevel); if (aMode = m3_saRead) then begin Result := aPart.Open(aMode, aPartSelector, aIndex); if (Result = nil) then begin aPart := nil; f_DB.FreeVersions; // - сообщаем, что переменную часть уже можно отпустить, // типа - самые умные и можем рулить хранилищем. aPart := aDoc.GetConst; // - берём постоянную часть end//Result = nil else Exit; // - всё уже открыто end;//Mode = l3_fmRead Result := aPart.Open(aMode, aPartSelector, aIndex); end;//OpenDocumentStream function FMtoSA(aFileMode : Tl3FileMode) : Tm3StoreAccess; begin if (aFileMode = l3_fmRead) then Result := m3_saRead else Result := m3_saReadWrite; end; //#UC END# *555C888301B0_555C88FF0236_var* begin //#UC START# *555C888301B0_555C88FF0236_impl* Result := true; if (f_DB <> nil) and (Handle <> 0) then begin Assert(Handle > 0); COMStream := OpenDocumentStream(f_DB.GetDocument(Handle), f_Part, f_PartSelector, f_ObjectIndex, FMtoSA(Mode), f_Level); end // (f_DB <> nil) and (Handle <> 0) else Result := false; //#UC END# *555C888301B0_555C88FF0236_impl* end;//Tm3DBFiler.DoOpen procedure Tm3DBFiler.DoClose; //#UC START# *555C88B703E7_555C88FF0236_var* //#UC END# *555C88B703E7_555C88FF0236_var* begin //#UC START# *555C88B703E7_555C88FF0236_impl* f_Part := nil; Stream := nil; // - это ОБЯЗАТЕЛЬНО нужно для сбалансированности скобок индикатора inherited; //#UC END# *555C88B703E7_555C88FF0236_impl* end;//Tm3DBFiler.DoClose procedure Tm3DBFiler.ClearFields; begin f_DB := nil; f_Part := nil; inherited; end;//Tm3DBFiler.ClearFields initialization {$If NOT Defined(NoScripts)} TtfwClassRef.Register(Tm3DBFiler); {* Регистрация Tm3DBFiler } {$IfEnd} // NOT Defined(NoScripts) end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} unit ElSndMap; interface uses {$ifdef MSWINDOWS} Windows, Messages, ElRegUtils, mmSystem, {$ifdef VCL_6_USED} Types, {$endif} {$endif} SysUtils, Classes, ElIni, ElTools, TypInfo; type {$ifndef VCL_6_USED} TElSoundName = string[255]; {$else} TElSoundName = string; {$endif} TElSoundMap = class(TComponent) private FSchemes : TStringList; FStorage : TElIniFile; FStoragePath : string; FScheme : string; FApplicationKey : string; FApplicationName : string; FRegIni, ARegIni : TElIniFile; FEventKeys : TStringList; FMute : Boolean; function GetEventLabels(EventKey : string) : string; procedure SetEventLabels(EventKey : string; newValue : string); function GetEnabled(EventKey : string) : boolean; procedure SetEnabled(EventKey : string; newValue : boolean); function GetSchemes : TStringList; function GetEventKeys : TStringList; function GetEventValues(EventKey : string) : string; procedure SetEventValues(EventKey : string; newValue : string); procedure SetApplicationName(newValue : string); procedure SetApplicationKey(newValue : string); procedure SetScheme(newValue : string); procedure SetStorage(newValue : TElIniFile); procedure SetStoragePath(newValue : string); protected { Protected declarations } procedure Notification(AComponent : TComponent; operation : TOperation); override; public { Public declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure Play(EventKey : string); procedure Add(EventKey, EventLabel, EventValue : string; Enabled : boolean); procedure Delete(EventKey : string); procedure Loaded; override; property EventKeys : TStringList read GetEventKeys; { Published } property EventLabel[EventKey : string] : string read GetEventLabels write SetEventLabels; { Published } property EventValue[EventKey : string] : string read GetEventValues write SetEventValues; { Published } property EventEnabled[EventKey : string] : boolean read GetEnabled write SetEnabled; { Published } property Schemes : TStringList read GetSchemes; published property Mute : Boolean read FMute write FMute; { Published } property ApplicationName : string read FApplicationName write SetApplicationName; { Published } property ApplicationKey : string read FApplicationKey write SetApplicationKey; { Published } property Scheme : string read FScheme write SetScheme; property StoragePath : string read FStoragePath write SetStoragePath; { Published } property Storage : TElIniFile read FStorage write SetStorage; end; { TElSoundMap } implementation procedure TElSoundMap.Loaded; begin inherited; if FStorage = nil then FStoragePath := ''; end; function TElSoundMap.GetSchemes : TStringList; begin FSchemes.Clear; if FStorage = nil then FRegIni := ARegIni else FRegIni := FStorage; FRegIni.EnumSubKeys(FStoragePath + FRegIni.Delimiter + 'Schemes\Schemes', FSchemes); result := FSchemes; end; function TElSoundMap.GetEventKeys; begin FEventKeys.Clear; if FStorage = nil then FRegIni := ARegIni else FRegIni := FStorage; FRegIni.EnumSubKeys(FStoragePath + FRegIni.Delimiter + 'Schemes\Apps\' + ApplicationKey, FEventKeys); result := FEventKeys; end; { GetEventNames } function TElSoundMap.GetEventLabels; var SaveKey : string; begin if FStorage = nil then FRegIni := ARegIni else FRegIni := FStorage; SaveKey := FRegIni.CurrentKey; if FRegIni.OpenKey(FStoragePath + FRegIni.Delimiter + 'EventLabels\' + EventKey, false) then begin FRegIni.ReadString('', '', '', result); FRegIni.OpenKey(SaveKey, false); end else result := ''; end; { GetEventValues } procedure TElSoundMap.SetEventLabels(EventKey : string; newValue : string); var SaveKey : string; begin if FStorage = nil then FRegIni := ARegIni else FRegIni := FStorage; SaveKey := FRegIni.CurrentKey; if FRegIni.OpenKey(FStoragePath + FRegIni.Delimiter + '\EventLabels\' + EventKey, true) then begin FRegIni.WriteString('', '', newValue); FRegIni.OpenKey(SaveKey, false); end; end; { SetEventValues } function TElSoundMap.GetEventValues(EventKey : string) : string; var SaveKey : string; begin if FStorage = nil then FRegIni := ARegIni else FRegIni := FStorage; SaveKey := FRegIni.CurrentKey; if FRegIni.OpenKey(FStoragePath + FRegIni.Delimiter + 'Schemes\Apps\' + ApplicationKey + '\' + EventKey + '\' + Scheme, false) then begin FRegIni.ReadString('', '', '', result); FRegIni.OpenKey(SaveKey, false); end else result := ''; end; { GetEventValues } procedure TElSoundMap.SetEventValues(EventKey : string; newValue : string); var SaveKey : string; begin if FStorage = nil then FRegIni := ARegIni else FRegIni := FStorage; SaveKey := FRegIni.CurrentKey; if FRegIni.OpenKey(FStoragePath + FRegIni.Delimiter + 'Schemes\Apps\' + ApplicationKey + '\' + EventKey + '\' + Scheme, true) then begin FRegIni.WriteString('', '', newValue); FRegIni.OpenKey(SaveKey, false); end; end; { SetEventValues } function TElSoundMap.GetEnabled(EventKey : string) : boolean; var SaveKey : string; begin if FStorage = nil then FRegIni := ARegIni else FRegIni := FStorage; SaveKey := FRegIni.CurrentKey; if FRegIni.OpenKey(FStoragePath + FRegIni.Delimiter + 'Schemes\Apps\' + ApplicationKey + '\' + EventKey, false) then begin FRegIni.ReadBool('', 'Disabled', false, result); result := not result; FRegIni.OpenKey(SaveKey, false); end else result := true; end; procedure TElSoundMap.SetEnabled(EventKey : string; newValue : boolean); var SaveKey : string; begin if FStorage = nil then FRegIni := ARegIni else FRegIni := FStorage; SaveKey := FRegIni.CurrentKey; if FRegIni.OpenKey(FStoragePath + FRegIni.Delimiter + 'Schemes\Apps\' + ApplicationKey + '\' + EventKey, true) then begin FRegIni.WriteBool('', 'Disabled', (not newValue)); FRegIni.OpenKey(SaveKey, false); end; end; procedure TElSoundMap.Play(EventKey : string); { public } var S : string; begin if not Mute then begin S := Trim(EventValue[EventKey]); if (Length(S) > 0) and EventEnabled[EventKey] then ElTools.PlaySound(PChar(s), 0, {$ifdef MSWINDOWS}SND_ASYNC{$else}0{$endif}); end; end; { Play } procedure TElSoundMap.Add(EventKey, EventLabel, EventValue : string; Enabled : boolean); var SaveKey : string; begin if FStorage = nil then FRegIni := ARegIni else FRegIni := FStorage; SaveKey := FRegIni.CurrentKey; if FRegIni.OpenKey(FStoragePath + FRegIni.Delimiter + 'Schemes\Apps\' + ApplicationKey + '\' + EventKey, true) then begin Self.EventLabel[EventKey] := EventLabel; Self.EventValue[EventKey] := EventValue; EventEnabled[EventKey] := Enabled; FRegIni.OpenKey(SaveKey, false); end; end; procedure TElSoundMap.Delete(EventKey : string); { public } var SaveKey : string; begin if FStorage = nil then FRegIni := ARegIni else FRegIni := FStorage; SaveKey := FRegIni.CurrentKey; if FRegIni.OpenKey(FStoragePath + FRegIni.Delimiter + 'Schemes\Apps\' + ApplicationKey, true) then begin FRegIni.Delete(EventKey, ''); FRegIni.OpenKey(SaveKey, false); end; if FRegIni.OpenKey(FStoragePath + FRegIni.Delimiter + 'EventLabels', false) then begin FRegIni.Delete(EventKey, ''); FRegIni.OpenKey(SaveKey, false); end; end; { SetEventValues } procedure TElSoundMap.SetApplicationKey(newValue : string); begin if (FApplicationKey <> newValue) then begin {$ifdef MSWINDOWS} if not IsValidKeyName(newValue) then raise Exception.Create('Key name contains invalid characters') else {$endif} FApplicationKey := newValue; end; { if } end; { SetApplicationKey } procedure TElSoundMap.SetScheme(newValue : string); begin if (FScheme <> newValue) then begin {$ifdef MSWINDOWS} if not IsValidKeyName(newValue) then raise Exception.Create('Scheme name contains invalid characters') else {$endif} FScheme := newValue; end; { if } end; { SetApplicationKey } procedure TElSoundMap.SetApplicationName(newValue : string); begin if (FApplicationName <> newValue) then begin FApplicationName := newValue; if FStorage = nil then FRegIni := ARegIni else FRegIni := FStorage; FRegIni.WriteString(FStoragePath + FRegIni.Delimiter + 'Schemes\Apps\' + ApplicationKey, '', newValue); end; { if } end; { SetApplicationKey } procedure TElSoundMap.SetStorage(newValue : TElIniFile); begin if (FStorage <> newValue) then begin FStorage := newValue; if FStorage = nil then StoragePath := ''; end; { if } end; { SetStorage } procedure TElSoundMap.SetStoragePath(newValue : string); begin if FStoragePath <> newValue then begin FStoragePath := newValue; if (FStorage = nil) and (not (csLoading in ComponentState)) then FStoragePath := ''; end; end; procedure TElSoundMap.Notification(AComponent : TComponent; operation : TOperation); begin inherited Notification(AComponent, operation); if (operation = opRemove) then begin if (AComponent = FStorage) then Storage := nil; end; { if } end; { Notification } destructor TElSoundMap.Destroy; begin FSchemes.Free; FEventKeys.Free; ARegIni.Free; inherited Destroy; end; { Destroy } constructor TElSoundMap.Create(AOwner : TComponent); { Creates an object of type TElSoundMap, and initializes properties. } begin inherited Create(AOwner); ARegIni := TElIniFile.Create(Self); FEventKeys := TStringList.Create; ARegIni.UseRegistry := true; ARegIni.Path := '\AppEvents'; FScheme := '.current'; FSchemes := TStringList.Create; end; { Create } end.
unit VariantCompForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TForm1 = class(TForm) btnEqual: TButton; btnCompare: TButton; radRules: TRadioGroup; btnCompare2: TButton; procedure btnEqualClick(Sender: TObject); procedure radRulesClick(Sender: TObject); procedure btnCompareClick(Sender: TObject); procedure btnCompare2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btnEqualClick(Sender: TObject); var a, b: variant; begin a := 0; b := NULL; if a = b then ShowMessage ('0 and 5 are equal') else ShowMessage ('0 and 5 are different') end; procedure TForm1.radRulesClick(Sender: TObject); begin case radRules.ItemIndex of 0: begin NullEqualityRule := ncrLoose; NullMagnitudeRule := ncrLoose; end; 1: begin NullEqualityRule := ncrStrict; NullMagnitudeRule := ncrStrict; end; 2: begin NullEqualityRule := ncrError; NullMagnitudeRule := ncrError; end; end; end; procedure TForm1.btnCompareClick(Sender: TObject); var a, b: variant; begin a := 5; b := NULL; if a > b then ShowMessage ('5 is larger than Null') else ShowMessage ('5 is smaller than Null') end; procedure TForm1.btnCompare2Click(Sender: TObject); var a, b: variant; begin a := -5; b := NULL; if a > b then ShowMessage ('-5 is larger than Null') else ShowMessage ('-5 is smaller than Null') end; end.
unit FMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, U_Usb, RXShell, Menus, ShlObj, uDir, PNGImage; type TTFMain = class(TForm) lstConsole: TListBox; rxtMain: TRxTrayIcon; pmuMain: TPopupMenu; pmuAbout: TMenuItem; N1: TMenuItem; pmuExit: TMenuItem; Button1: TButton; FileList: TListBox; EditStartDir: TEdit; EditFileMask: TEdit; ListBox1: TListBox; LabelCount: TLabel; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure pmuExitClick(Sender: TObject); procedure pmuAboutClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure Button1Click(Sender: TObject); private { Private declarations } FUsb : TUsbClass; function GetFileVersion(const FileName: TFileName; var Major, Minor, Release, Build: word): boolean; procedure WriteLog(strMessage: String); procedure UsbIN(ASender : TObject; const ADevType,ADriverName, AFriendlyName, ATargetPath : string); procedure UsbOUT(ASender : TObject; const ADevType,ADriverName, AFriendlyName, ATargetPath : string); public { Public declarations } TargetDirectory: String; TargetDirectoryBase: String; flagExit: Boolean; end; procedure WriteLogFile(strMessage:String; strPathBase:String); const FORCE_TARGET_DIR = 'C:\'; var TFMain: TTFMain; implementation {$R *.dfm} procedure TTFMain.WriteLog(strMessage: String); begin // lstConsole.Items.Add('[' + FormatDateTime('YYYY-MM-DD HH:NN:SS', Now) + '] ' + strMessage); WriteLogFile(strMessage, TargetDirectoryBase); end; procedure TTFMain.FormCreate(Sender: TObject); var RealPath: Array[0..MAX_PATH] of Char; Success:Bool; PIDl: PItemIDList; hRes: HRESULT; begin try FUsb:= TUsbClass.Create; FUsb.OnUsbInsertion := UsbIN; FUsb.OnUsbRemoval := UsbOUT; flagExit := False; hRes := SHGetSpecialFolderLocation(Self.Handle, CSIDL_PERSONAL, PIDL); if hRes = NO_ERROR then begin Success := SHGetPathFromIDList(PIDl, RealPath); if Success then TargetDirectoryBase := String(RealPath) else TargetDirectoryBase := FORCE_TARGET_DIR; end else begin TargetDirectoryBase := FORCE_TARGET_DIR; end; if Copy(TargetDirectoryBase, Length(TargetDirectoryBase), 1) <> '\' then TargetDirectoryBase := TargetDirectoryBase + '\'; TargetDirectoryBase := TargetDirectoryBase + 'OhMyUSBCloner\'; WriteLog('기본 저장 경로 : ' + TargetDirectoryBase); except On E: Exception do WriteLog('Exception : TTFMain.FormCreate<'+E.Message+'>'); end; end; procedure TTFMain.UsbIN(ASender : TObject; const ADevType, ADriverName, AFriendlyName, ATargetPath : string); var ODir: TDir; iResult : Boolean; begin { showmessage('USB Inserted - Device Type = ' + ADevType + #13#10 + 'Driver Name = ' + ADriverName + #13+#10 + 'Friendly Name = ' + AFriendlyName + #13 + #10 + 'Target Path = ' + ATargetPath); } // if Copy(TargetDirectoryBase, Length(TargetDirectoryBase), 1) <> '\' then // TargetDirectoryBase := TargetDirectoryBase + '\'; try try ODir := TDir.Create; TargetDirectory := TargetDirectoryBase + FormatDateTime('yyyymmddhhnnss', Now) + '\'; //디렉토리 없으면 디렉토리 생성해 준다. if Not DirectoryExists(TargetDirectory) Then begin ForceDirectories(TargetDirectory); end; WriteLog('USB Inserted - Device Type = ' + ADevType + ' / ' + 'Driver Name = ' + ADriverName + ' / ' + 'Friendly Name = ' + AFriendlyName + ' / ' + 'Target Path = ' + ATargetPath); WriteLog('Copy file(s) from ''' + ATargetPath + ':\'' to ''' + TargetDirectory + ''''); iResult := ODir.Copy(String(ATargetPath + ':\*.*' + #00), TargetDirectory + #00); WriteLog('Result = ' + BoolToStr(iResult, True)); finally FreeAndNil(ODir); end; except On E: Exception do WriteLog('Exception : TTFMain.UsbIN<'+E.Message+'>'); end; end; procedure TTFMain.UsbOUT(ASender : TObject; const ADevType,ADriverName, AFriendlyName, ATargetPath : string); begin { showmessage('USB Removed - Device Type = ' + ADevType + #13#10 + 'Driver Name = ' + ADriverName + #13+#10 + 'Friendly Name = ' + AFriendlyName + #13 + #10 + 'Target Path = ' + ATargetPath); } try WriteLog('USB Removedz - Device Type = ' + ADevType + ' / ' + 'Driver Name = ' + ADriverName + ' / ' + 'Friendly Name = ' + AFriendlyName + ' / ' + 'Target Path = ' + ATargetPath); except On E: Exception do WriteLog('Exception : TTFMain.UsbOUT<'+E.Message+'>'); end; end; procedure TTFMain.FormClose(Sender: TObject; var Action: TCloseAction); begin try FreeAndNil(FUsb); except On E: Exception do WriteLog('Exception : TTFMain.FormClose<'+E.Message+'>'); end; end; procedure TTFMain.pmuExitClick(Sender: TObject); begin try WriteLog('pmuExitClick Event'); flagExit := True; Close; except On E: Exception do WriteLog('Exception : TTFMain.pmuExitClick<'+E.Message+'>'); end; end; procedure TTFMain.pmuAboutClick(Sender: TObject); var Major, Minor, Release, Build: word; strMessage:String; begin try if GetFileVersion(Application.ExeName,Major, Minor, Release, Build) then begin strMessage := 'OhMyUSBCloner ' + IntTostr(Major) + '.' + IntToStr(Minor) + '.' + IntToStr(Release) + '.' + IntToStr(Build); end else begin strMessage := 'OhMyUSBCloner'; end; strMessage := strMessage + #10 + #13 + 'e-mail : bandoche@hanmail.net'; strMessage := strMessage + #10 + #13 + 'website : blog.bandoche.com'; MessageBox(Handle, PChar(strMessage), 'OhMyUSBCloner',MB_ICONINFORMATION + MB_OK); except On E: Exception do WriteLog('Exception : TTFMain.pmuExitClick<'+E.Message+'>'); end; end; procedure TTFMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := flagExit; if not flagExit then begin Hide; end; end; procedure WriteLogFile(strMessage:String; strPathBase:String); var OFileStream : TFileStream; DirPath : String; StrMon: String; StrDay: String; StrTime: String; StrPath: String; StrVal: String; begin try try //해당 월 구하기 StrMon := FormatDateTime('yyyymm', Now); StrDay := FormatDateTime('yyyymmdd', Now); StrTime := FormatDateTime('yyyy-mm-dd hh:nn:ss', Now); StrPath := strPathBase + '\' + FormatDateTime('YYYYMMDD', Now) +'.log'; if Copy(strPathBase, Length(strPathBase), 1) <> '\' then strPathBase := strPathBase + '\'; //넘어온 문자열 형식에 맞춰서 넘겨주기 StrVal := '['+StrTime+'] ' + strMessage; //디렉토리 없으면 디렉토리 생성해 준다. if Not DirectoryExists(strPathBase) Then begin ForceDirectories(strPathBase); end; if FileExists(StrPath) Then OFileStream := TFileStream.Create(StrPath, fmOpenWrite) else OFileStream := TFileStream.Create(StrPath, fmCreate); OFileStream.Seek(OFileStream.Size, soBeginning); OFileStream.WriteBuffer(PChar(StrVal)^, Length(StrVal)); OFileStream.WriteBuffer(PChar(#13#10)^, Length(#13#10)); finally OFileStream.Free; end; except On E: Exception do ; end; end; { 설명 : 파일 버전 가져오는 함수 작성자 : 정상준(bandoche@tapi.co.kr) 작성일 : 2010-04-29 } function TTFMain.GetFileVersion(const FileName: TFileName; var Major, Minor, Release, Build: word): boolean; // Returns True on success and False on failure. var size, len: longword; handle: THandle; buffer: pchar; pinfo: ^VS_FIXEDFILEINFO; begin Result := False; try size := GetFileVersionInfoSize(Pointer(FileName), handle); if size > 0 then begin GetMem(buffer, size); if GetFileVersionInfo(Pointer(FileName), 0, size, buffer) then if VerQueryValue(buffer, '\', pointer(pinfo), len) then begin Major := HiWord(pinfo.dwFileVersionMS); Minor := LoWord(pinfo.dwFileVersionMS); Release := HiWord(pinfo.dwFileVersionLS); Build := LoWord(pinfo.dwFileVersionLS); Result := True; end; FreeMem(buffer); end; except On E:Exception do WriteLog('Exception : TTFMain.GetFileVersion<'+E.Message+'>'); end; end; // Recursive procedure to build a list of files procedure FindFiles(FilesList: TStringList; StartDir, FileMask: string); var SR: TSearchRec; DirList: TStringList; IsFound: Boolean; i: integer; begin if StartDir[length(StartDir)] <> '\' then StartDir := StartDir + '\'; { Build a list of the files in directory StartDir (not the directories!) } IsFound := FindFirst(StartDir+FileMask, faAnyFile-faDirectory, SR) = 0; while IsFound do begin FilesList.Add(StartDir + SR.Name); IsFound := FindNext(SR) = 0; end; FindClose(SR); // Build a list of subdirectories DirList := TStringList.Create; IsFound := FindFirst(StartDir+'*.*', faAnyFile, SR) = 0; while IsFound do begin if ((SR.Attr and faDirectory) <> 0) and (SR.Name[1] <> '.') then DirList.Add(StartDir + SR.Name); IsFound := FindNext(SR) = 0; end; FindClose(SR); // Scan the list of subdirectories for i := 0 to DirList.Count - 1 do FindFiles(FilesList, DirList[i], FileMask); DirList.Free; end; // Example: how to use FindFiles //procedure TForm1.ButtonFindClick(Sender: TObject); //var // FilesList: TStringList; //begin // FilesList := TStringList.Create; // try // FindFiles(FilesList, EditStartDir.Text, EditFileMask.Text); // ListBox1.Items.Assign(FilesList); // LabelCount.Caption := 'Files found: ' + IntToStr(FilesList.Count); // finally // FilesList.Free; // end; //end; procedure TTFMain.Button1Click(Sender: TObject); var FilesList: TStringList; begin FilesList := TStringList.Create; try FindFiles(FilesList, EditStartDir.Text, EditFileMask.Text); ListBox1.Items.Assign(FilesList); LabelCount.Caption := 'Files found: ' + IntToStr(FilesList.Count); finally FilesList.Free; end; end; end.
unit ConsCheRech2013; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cons_2013, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxRibbonSkins, dxSkinsCore, dxSkinsDefaultPainters, cxStyles, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, Data.DB, cxDBData, dxSkinsdxBarPainter, cxLocalization, Datasnap.Provider, Datasnap.DBClient, System.Actions, Vcl.ActnList, JvAppStorage, JvAppIniStorage, JvComponentBase, JvFormPlacement, Vcl.ImgList, dxBar, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, dxStatusBar, dxRibbonStatusBar, dxRibbon, cxNavigator, Vcl.Menus, Vcl.DBActns, dmres; type TFConsCheRech2013 = class(TFCons_2013) cdsFECHA: TDateTimeField; cdsCODCTE: TStringField; cdsNUMERO: TStringField; cdsCLIENTE: TStringField; cdsDENOCLI: TStringField; cdsIMPORTE: TFloatField; cdsBANCO: TStringField; cdsDENOBCO: TStringField; cdsNUMCHE: TStringField; cdsMOTIVO: TStringField; cdsFIRMANTE: TStringField; cdsCANCELADO: TStringField; acTodos: TAction; acCancel: TAction; acPen: TAction; mgrBar6: TdxBar; dxBarLargeButton10: TdxBarLargeButton; dxBarLargeButton11: TdxBarLargeButton; dxBarLargeButton12: TdxBarLargeButton; vistaFECHA: TcxGridDBColumn; vistaCODCTE: TcxGridDBColumn; vistaNUMERO: TcxGridDBColumn; vistaCLIENTE: TcxGridDBColumn; vistaDENOCLI: TcxGridDBColumn; vistaIMPORTE: TcxGridDBColumn; vistaBANCO: TcxGridDBColumn; vistaDENOBCO: TcxGridDBColumn; vistaNUMCHE: TcxGridDBColumn; vistaMOTIVO: TcxGridDBColumn; vistaFIRMANTE: TcxGridDBColumn; vistaCANCELADO: TcxGridDBColumn; dxBarLargeButton13: TdxBarLargeButton; acImpNota: TAction; procedure acTodosExecute(Sender: TObject); procedure acCancelExecute(Sender: TObject); procedure acPenExecute(Sender: TObject); procedure acImpNotaExecute(Sender: TObject); private { Private declarations } FCancelado: string; public { Public declarations } procedure requeryconsulta; override; constructor create( AOwner: TComponent; const filtro: string ); overload; procedure imprima( vista: boolean ); override; end; var FConsCheRech2013: TFConsCheRech2013; implementation uses dmcons, Informes; {$R *.dfm} { TFConsCheRech2013 } procedure TFConsCheRech2013.acCancelExecute(Sender: TObject); begin inherited; FCancelado := 'N'; // diferentes de Requeryconsulta; end; procedure TFConsCheRech2013.acImpNotaExecute(Sender: TObject); begin inherited; with DCons do begin QSelChRech.Parameters.ParamByName( 'CODCTE' ).value := cdsCODCTE.value; QSelChRech.Parameters.ParamByName( 'NUMERO' ).value := cdsNUMERO.value; VerInforme( 'ChequeRechazado.rtm', QSelChRech, nil, nil, nil, true ); end; end; procedure TFConsCheRech2013.acPenExecute(Sender: TObject); begin inherited; FCancelado := 'S'; // diferentes de Requeryconsulta; end; procedure TFConsCheRech2013.acTodosExecute(Sender: TObject); begin inherited; FCancelado := 'z'; Requeryconsulta; end; constructor TFConsCheRech2013.create(AOwner: TComponent; const filtro: string); begin FCancelado := filtro; inherited create( AOwner ); end; procedure TFConsCheRech2013.imprima(vista: boolean); begin inherited; cds.DisableControls; try VerInforme( 'InfCheRech.rtm', cds, nil, nil, nil, Vista ); finally cds.EnableControls; end; end; procedure TFConsCheRech2013.requeryconsulta; begin inherited; with DCons do try cds.DisableControls; cds.Close; cds.Params.paramByName( 'CANCEL' ).Value := FCancelado; cds.Open; finally cds.EnableControls; end; end; end.
(*---------------------------------------------------------*) (* some algorithms for handling double linked cyclic *) (* Neuhold Michael *) (*---------------------------------------------------------*) PROGRAM ListDLCA; TYPE NodePtr = ^Node; Node = RECORD value: INTEGER; prev,next: NodePtr; END; ListPtr = NodePtr; (* newNode - creates new node *) FUNCTION NewNode(value: INTEGER): NodePtr; VAR n: NodePtr; BEGIN New(n); n^.value := value; n^.prev := n; n^.next := n; NewNode := n; END; (* Init List - initializes list with nil *) PROCEDURE InitList(VAR l: ListPtr); BEGIN l := NewNode(0); END; (* Prepend - add node at the beginnig of the list *) PROCEDURE Prepend(VAR l: ListPtr; n: NodePtr); BEGIN n^.next := l^.next; n^.prev := l; l^.next^.prev := n; l^.next := n; END; (* NrOfNodes: Count the number of nodes in list l *) FUNCTION NrOfNodes(l: ListPtr): INTEGER; VAR n: NodePtr; cnt: INTEGER; (* count number of nodes *) BEGIN n := l; cnt := 0; WHILE n <> NIL DO BEGIN cnt := cnt + 1; n := n^.next; END; NrOfNodes := cnt; END; (* Append: add node at last position in list *) PROCEDURE Append(VAR l: ListPtr; n: NodePtr); BEGIN n^.next := l; n^.prev := l^.prev; l^.prev^.next := n; l^.prev := n; END; { (* DisposeList - Dispose all Nods of List *) PROCEDURE DisposeList(VAR l: ListPtr); VAR nToDespose: NodePtr; BEGIN WHILE l <> NIL DO BEGIN nToDespose := l; l := l^.next; Dispose(nToDespose); END; END; } (* WriteList - write all nodes of list. *) PROCEDURE WriteList(l: ListPtr); VAR n: NodePtr; BEGIN n := l; n := n^.next; Write('< '); WHILE n <> l DO BEGIN Write(n^.value); IF n^.next <> l THEN Write(', '); n := n^.next; END; WriteLn(' >'); END; { (* Insert: insert node sorted into list *) (* asserrtion: l is sorted *) PROCEDURE Insert(VAR l: ListPtr; n: NodePtr); VAR succ, pred: NodePtr; BEGIN (* Assert l is sorted *) pred := NIL; succ := l; WHILE (succ <> NIL) AND (n^.value > succ^.value) DO BEGIN pred := succ; succ := succ^.next; END; IF pred = NIL THEN BEGIN l := n; END ELSE BEGIN pred^.next := n; END; n^.next := succ; (* Assert l is sorted *) END; (* NodeWith: Find Node with Value xValue *) FUNCTION NodeWith(l: ListPtr; xValue: INTEGER): NodePtr; VAR n: NodePtr; BEGIN n := l; WHILE (n <> NIL) AND (n^.value <> xValue) DO BEGIN n := n^.next; END; NodeWith := n; END; (* Delete First Node With value xValue *) (* remove it from list l and dispose ist. *) PROCEDURE DeleteFirstNodeWith(VAR l: ListPtr; xValue: INTEGER); VAR pred, n: NodePtr; BEGIN IF l <> NIL THEN BEGIN pred := NIL; n := l; WHILE (n <> NIL) AND (n^.value <> xValue) DO BEGIN pred := n; n := n^.next; END; IF (n <> NIL) THEN BEGIN IF pred = NIL THEN l := l^.next ELSE BEGIN pred^.next := n^.next; Dispose(n); n := NIL; END; END; END; END; } VAR l: ListPtr; BEGIN InitList(l); Prepend(l, NewNode(15)); Prepend(l, NewNode(14)); Prepend(l, NewNode(13)); Prepend(l, NewNode(12)); Append(l, NewNode(20)); WriteList(l); {Insert(l, NewNode(18)); WriteList(l); WriteLn; WriteLn('Anzahl der Elemente: ', NrOfNodes(l)); WriteLn; IF NodeWith(l, 12) <> NIL THEN WriteLn('l contains node with!'); DeleteFirstNodeWith(l,12); WriteList(l); DisposeList(l); InitList(l); Insert(l, NewNode(18)); WriteList(l); WriteLn; DisposeList(l);} END.
unit Dib2SurfaceFrames; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses Windows, Dibs, SurfaceSpriteImages, ColorTrans, ColorTableMgr; // Dibs conversion function SurfaceFrameFromDib(DibHeader : PDib; DibPixels : pointer) : TSurfaceFrameImage; //procedure AddDibToSurfaceFrame(FrameImage : TSurfaceFrameImage; DibHeader : PDib; DibPixels : pointer); implementation uses Classes, DDrawD3DManager, GDI, BitBlt{$IFDEF MEMREPORTS}, MemoryReports{$ENDIF}; // Dibs conversion function PackRGBQuad(const RGBQuad : TRGBQuad) : word; const rRight = 11; gRight = 5; rLeft = 3; gLeft = 3; bLeft = 3; begin with RGBQuad do Result := ( (rgbRed shr rLeft) shl rRight ) or ( (rgbGreen shr gLeft) shl gRight ) or ( rgbBlue shr bLeft ); end; function SurfaceFrameFromDib(DibHeader : PDib; DibPixels : pointer) : TSurfaceFrameImage; var i : cardinal; ImgFrame : TFrame; rgbpalette : PRGBPalette; frame : pchar; palinfo : TPaletteInfo; Transcolor : word; begin with DibHeader^ do begin if not Assigned(DibPixels) then DibPixels := DibPtr(DibHeader); Result := TSurfaceFrameImage.Create(biWidth, abs(biHeight)); ImgFrame.surface := DDrawD3DMgr.CreateCompatibleOffscreenSurface(Result.Width, Result.Height); {$IFDEF MEMREPORTS} //ReportMemoryAllocation(cSpriteAllocCause, Size); {$ENDIF} getmem(frame, biWidth*abs(biHeight)); Result.AddFrame(ImgFrame); getmem(rgbpalette, DibPaletteSize(DibHeader)); Move(DibColors(DibHeader)^, rgbpalette^, DibPaletteSize(DibHeader)); palinfo := TPaletteInfo.Create; palinfo.AttachPalette(rgbpalette, DibPaletteSize(DibHeader) div sizeof(rgbpalette[0])); palinfo.Owned := true; palinfo.RequiredState([tsHiColor565TableValid]); Result.OwnsPalette := true; Result.LockFrame(0, true); try if DibIsTopDown(DibHeader) then for i := 0 to Result.Height - 1 do begin Move(DibPixels^, (frame + i*biWidth)^, biWidth); inc(pchar(DibPixels), DwordAlign(biWidth)); end else for i := Result.Height - 1 downto 0 do begin Move(DibPixels^, (frame + i*biWidth)^, biWidth); inc(pchar(DibPixels), DwordAlign(biWidth)); end; TransColor := PackRGBQuad(rgbpalette[byte(frame[0])]); fillchar(Result.PixelAddr[0, 0, 0]^, Result.StorageWidth[0]*Result.Height, TransColor); BltCopySourceCTT16(frame, Result.PixelAddr[0, 0, 0], Result.Width, Result.Height, byte(frame[0]), Result.Width, Result.StorageWidth[0], palinfo.HiColor565Table); //BltCopyOpaqueCTT16(frame, Result.PixelAddr[0, 0, 0], Result.Width, Result.Height, Result.Width, Result.StorageWidth[0], palinfo.HiColor565Table); Result.TranspIndx := Result.Pixel[0, 0, 0]; finally Result.UnlockFrame(0); palinfo.Free; freemem(frame); end; {$IFDEF MEMREPORTS} //ReportMemoryAllocation(cSpriteAllocCause, 3*DibPaletteSize(DibHeader) + sizeof(Result) + sizeof(Result.PaletteInfo)); {$ENDIF} end; end; { procedure AddDibToFrame( FrameImage : TFrameImage; DibHeader : PDib; DibPixels : pointer ); var Buf : TFrame; Size : cardinal; i : cardinal; begin with DibHeader^ do begin if not Assigned( DibPixels ) then DibPixels := DibPtr( DibHeader ); Size := biWidth * Abs( biHeight ); GetMem( Buf.pixels, Size ); if DibIsTopDown( DibHeader ) then for i := 0 to FrameImage.Height - 1 do begin Move( DibPixels^, pchar(Buf.pixels)[FrameImage.PixelOfs(0, i, 0)], biWidth); inc( pchar(DibPixels), DwordAlign(biWidth) ); end else for i := FrameImage.Height - 1 downto 0 do begin Move( DibPixels^, pchar(Buf.pixels)[FrameImage.PixelOfs(0, i, 0)], biWidth); inc( pchar(DibPixels), DwordAlign(biWidth) ); end; FrameImage.AddFrame( Buf ); end; end; } end.
unit vos_win32_hw_keyboard; interface uses Windows; type PVOS_Win32_HW_Keyboard_Rec = ^TVOS_Win32_HW_Keyboard_Rec; TVOS_Win32_HW_Keyboard_Rec = packed record DefaultKbLayout: HKL; end; const KbLayoutRegkeyFmt = 'System\CurrentControlSet\Control\Keyboard Layouts\%.8x'; // do not localize KbLayoutRegSubkey = 'layout text'; // do not localize procedure InitKeyboard(AKeyboard: PVOS_Win32_HW_Keyboard_Rec); implementation (* Imm32.dll _WINNLSEnableIME: function(hwnd: HWnd; bool: LongBool): Boolean stdcall; _ImmGetContext: function(hWnd: HWND): HIMC stdcall; _ImmReleaseContext: function(hWnd: HWND; hImc: HIMC): Boolean stdcall; _ImmGetConversionStatus: function(hImc: HIMC; var Conversion, Sentence: DWORD): Boolean stdcall; _ImmSetConversionStatus: function(hImc: HIMC; Conversion, Sentence: DWORD): Boolean stdcall; _ImmSetOpenStatus: function(hImc: HIMC; fOpen: Boolean): Boolean stdcall; _ImmSetCompositionWindow: function(hImc: HIMC; lpCompForm: PCOMPOSITIONFORM): Boolean stdcall; _ImmSetCompositionFont: function(hImc: HIMC; lpLogfont: PLOGFONTA): Boolean stdcall; _ImmGetCompositionString: function(hImc: HIMC; dWord1: DWORD; lpBuf: pointer; dwBufLen: DWORD): Longint stdcall; _ImmIsIME: function(hKl: HKL): Boolean stdcall; _ImmNotifyIME: function(hImc: HIMC; dwAction, dwIndex, dwValue: DWORD): Boolean stdcall; *) procedure InitKeyboard(AKeyboard: PVOS_Win32_HW_Keyboard_Rec); var KbList: array[0..63] of HKL; TotalKbLayout: Integer; begin AKeyboard.DefaultKbLayout := Windows.GetKeyboardLayout(0); TotalKbLayout := Windows.GetKeyboardLayoutList(64, KbList); if 0 = TotalKbLayout then begin end; end; end.
unit SelFolderForm; { Inno Setup Copyright (C) 1997-2004 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. "Select Folder" form $jrsoftware: issrc/Projects/SelFolderForm.pas,v 1.15 2010/10/22 10:33:26 mlaan Exp $ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, SetupForm, StdCtrls, FolderTreeView, NewStaticText, BidiCtrls; type TSelectFolderForm = class(TSetupForm) BrowseLabel: TNewStaticText; PathEdit: TEdit; NewFolderButton: TNewButton; OKButton: TNewButton; CancelButton: TNewButton; procedure PathEditChange(Sender: TObject); procedure NewFolderButtonClick(Sender: TObject); private { Private declarations } FFolderTreeView: TCustomFolderTreeView; FNewFolderName: String; FStartMenu, FAppendDir: Boolean; procedure FolderTreeViewChange(Sender: TObject); public { Public declarations } constructor Create(AOwner: TComponent); override; constructor Create2(AOwner: TComponent; AStartMenu: Boolean); end; function ShowSelectFolderDialog(const StartMenu, AppendDir: Boolean; var Path: String; const NewFolderName: String): Boolean; implementation uses PathFunc, Msgs, MsgIDs, Main, SetupTypes, Wizard, CmnFunc2; {$R *.DFM} function ShowSelectFolderDialog(const StartMenu, AppendDir: Boolean; var Path: String; const NewFolderName: String): Boolean; var Form: TSelectFolderForm; begin Form := TSelectFolderForm.Create2(nil, StartMenu); try Form.FAppendDir := AppendDir; Form.FNewFolderName := NewFolderName; Form.NewFolderButton.Visible := not AppendDir and (NewFolderName <> ''); if StartMenu then begin with Form.FFolderTreeView as TStartMenuFolderTreeView do if IsNT then SetPaths(GetRealShellFolder(False, sfPrograms, False), GetRealShellFolder(True, sfPrograms, False), GetRealShellFolder(False, sfStartup, False), GetRealShellFolder(True, sfStartup, False)) else SetPaths(GetRealShellFolder(False, sfPrograms, False), '', GetRealShellFolder(False, sfStartup, False), ''); TidyUpGroupName(Path); end else TidyUpDirName(Path); if AppendDir then begin if PathExtractDir(Path) <> Path then Form.FFolderTreeView.ChangeDirectory(PathExtractDir(Path), True); end else Form.FFolderTreeView.ChangeDirectory(Path, True); if StartMenu or (Form.FFolderTreeView.Directory <> '') then Form.ActiveControl := Form.FFolderTreeView; Form.PathEdit.Text := Path; Result := (Form.ShowModal = mrOK); if Result then Path := Trim(Form.PathEdit.Text); finally Form.Free; end; end; { TSelectFolderForm } constructor TSelectFolderForm.Create(AOwner: TComponent); var YDiff, W: Integer; begin inherited; if not FStartMenu then begin FFolderTreeView := TFolderTreeView.Create(Self); TFolderTreeView(FFolderTreeView).OnChange := FolderTreeViewChange; TFolderTreeView(FFolderTreeView).OnRename := WizardForm.DirTreeRename; end else begin FFolderTreeView := TStartMenuFolderTreeView.Create(Self); TStartMenuFolderTreeView(FFolderTreeView).OnChange := FolderTreeViewChange; TStartMenuFolderTreeView(FFolderTreeView).OnRename := WizardForm.GroupTreeRename; end; FFolderTreeView.SetBounds(16, 64, 317, 229); FFolderTreeView.Visible := False; FFolderTreeView.Parent := Self; PathEdit.BringToFront; { for MSAA } BrowseLabel.BringToFront; { for MSAA } FFolderTreeView.TabOrder := 2; FFolderTreeView.Visible := True; InitializeFont; Caption := SetupMessages[msgBrowseDialogTitle]; BrowseLabel.Caption := SetupMessages[msgBrowseDialogLabel]; YDiff := WizardForm.AdjustLabelHeight(BrowseLabel); PathEdit.Top := PathEdit.Top + YDiff; TryEnableAutoCompleteFileSystem(PathEdit.Handle); FFolderTreeView.Top := FFolderTreeView.Top + YDiff; NewFolderButton.Caption := SetupMessages[msgButtonNewFolder]; NewFolderButton.Top := NewFolderButton.Top + YDiff; NewFolderButton.Width := CalculateButtonWidth([msgButtonNewFolder]); W := CalculateButtonWidth([msgButtonOK, msgButtonCancel]); CancelButton.Caption := SetupMessages[msgButtonCancel]; CancelButton.SetBounds(CancelButton.Left + CancelButton.Width - W, CancelButton.Top + YDiff, W, CancelButton.Height); OKButton.Caption := SetupMessages[msgButtonOK]; OKButton.SetBounds(CancelButton.Left - ScalePixelsX(6) - W, OKButton.Top + YDiff, W, OKButton.Height); ClientHeight := ClientHeight + YDiff; CenterInsideControl(WizardForm, False); end; constructor TSelectFolderForm.Create2(AOwner: TComponent; AStartMenu: Boolean); begin FStartMenu := AStartMenu; Create(AOwner); end; procedure TSelectFolderForm.PathEditChange(Sender: TObject); begin OKButton.Enabled := (Trim(PathEdit.Text) <> ''); end; procedure TSelectFolderForm.FolderTreeViewChange(Sender: TObject); begin if FAppendDir then PathEdit.Text := AddBackslash(FFolderTreeView.Directory) + FNewFolderName else PathEdit.Text := FFolderTreeView.Directory; NewFolderButton.Enabled := FStartMenu or (FFolderTreeView.Directory <> ''); end; procedure TSelectFolderForm.NewFolderButtonClick(Sender: TObject); begin FFolderTreeView.CreateNewDirectory(FNewFolderName); end; end.
unit MdiChilds.ImportStroyInformResource; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MDIChilds.CustomDialog, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxCustomData, cxStyles, cxTL, cxTextEdit, cxCheckBox, cxTLdxBarBuiltInMenu, dxSkinsCore, dxSkinBlueprint, dxSkinMcSkin, dxSkinOffice2013LightGray, dxSkinSeven, dxSkinSharpPlus, dxSkinSpringTime, dxSkinVisualStudio2013Blue, dxSkinVS2010, JvBaseDlg, JvSelectDirectory, cxInplaceContainer, Vcl.StdCtrls, Vcl.ExtCtrls, JvComponentBase, JvSearchFiles, MdiChilds.ProgressForm, Parsers.Excel.StroyInformResource, ActionHandler; type TFmImportStroyInformResource = class(TFmProcess) edtFolder: TLabeledEdit; btnOpen: TButton; tvFolders: TcxTreeList; clRegion: TcxTreeListColumn; JvSelectDirectory: TJvSelectDirectory; JvSearchFiles: TJvSearchFiles; edtShapeT: TLabeledEdit; edtShapeF: TLabeledEdit; btnOpenT: TButton; btnOpenF: TButton; OpenDialog: TOpenDialog; procedure btnOpenClick(Sender: TObject); procedure edtFolderChange(Sender: TObject); procedure JvSearchFilesFindFile(Sender: TObject; const AName: string); procedure btnOpenTClick(Sender: TObject); procedure btnOpenFClick(Sender: TObject); private FFiles: TStringList; function CreateOrGetParentNode(FileName: string): TcxTreeListNode; protected procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure UpdateTree; end; TStroyInformResourceActionHandler = class (TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; var FmImportStroyInformResource: TFmImportStroyInformResource; implementation {$R *.dfm} procedure TFmImportStroyInformResource.btnOpenClick(Sender: TObject); begin if JvSelectDirectory.Execute then edtFolder.Text := JvSelectDirectory.Directory; end; procedure TFmImportStroyInformResource.btnOpenFClick(Sender: TObject); begin if OpenDialog.Execute then edtShapeF.Text := OpenDialog.FileName; end; procedure TFmImportStroyInformResource.btnOpenTClick(Sender: TObject); begin if OpenDialog.Execute then edtShapeT.Text := OpenDialog.FileName; end; constructor TFmImportStroyInformResource.Create(AOwner: TComponent); begin inherited; FFiles := TStringList.Create; end; function TFmImportStroyInformResource.CreateOrGetParentNode(FileName: string): TcxTreeListNode; var I: Integer; begin FileName := ExtractFileDir(FileName); // Result := nil; for I := 0 to tvFolders.Count - 1 do if tvFolders.Items[I].Values[0] = FileName then begin Result := tvFolders.Items[I]; Exit; end; Result := tvFolders.Add; // Result.CheckGroupType := ncgCheckGroup; // Result.CheckState := cbsChecked; Result.Values[0] := FileName; // Result.Values[0] := True; end; destructor TFmImportStroyInformResource.Destroy; begin FFiles.Free; inherited; end; //procedure TFmImportStroyInformResource.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); //var // FilesParser: TStroyInformResourceFilesParser; // I: Integer; //begin // Assert(edtShapeT.Text <> EmptyStr, 'Не задан шаблон индексов перевозок ТСНБ!'); // Assert(edtShapeF.Text <> EmptyStr, 'Не задан шаблон индексов перевозок ФСНБ!'); // // ShowMessage := True; // ProgressForm.InitPB(FFiles.Count); // ProgressForm.Show; // FilesParser := TStroyInformResourceFilesParser.Create; // FilesParser.ShapeFSNB := edtShapeF.Text; // FilesParser.ShapeTSNB := edtShapeT.Text; // try // for I := 0 to FFiles.Count - 1 do // begin // ProgressForm.StepIt(ExtractFileName(FFiles[I])); // if ProgressForm.InProcess then // begin // try // FilesParser.ParseFile(FFiles[I]); // except // on E: Exception do // GsLogger.WriteLogEx(ExtractFilePath(FFiles[I]) + 'Необработанные файлы.txt', ExtractFileName(FFiles[I]) + #9 + E.Message); // end; // end // else // Break; // end; // finally // FilesParser.Free; // end; //end; procedure TFmImportStroyInformResource.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var Importer: TStroyInformResourceFolderImporter; I: Integer; begin Assert(edtShapeT.Text <> EmptyStr, 'Не задан шаблон индексов перевозок ТСНБ!'); Assert(edtShapeF.Text <> EmptyStr, 'Не задан шаблон индексов перевозок ФСНБ!'); ShowMessage := True; Shape1 := edtShapeT.Text; Shape2 := edtShapeF.Text; Importer := TStroyInformResourceFolderImporter.Create; try Importer.Files.Clear; for I := 0 to tvFolders.Count - 1 do Importer.Files.Add(IncludeTrailingPathDelimiter(tvFolders.Items[I].Values[0])); Importer.Import; finally Importer.Free; end; end; procedure TFmImportStroyInformResource.edtFolderChange(Sender: TObject); begin UpdateTree; end; procedure TFmImportStroyInformResource.JvSearchFilesFindFile(Sender: TObject; const AName: string); var Node: TcxTreeListNode; begin FFiles.Add(AName); Node := tvFolders.AddChild(CreateOrGetParentNode(AName)); Node.Values[0] := ExtractFileName(AName); // Node.CheckGroupType := ncgRadioGroup; //Node.CheckState := cbsChecked; // Node.Values[0] := True; end; procedure TFmImportStroyInformResource.UpdateTree; begin tvFolders.Clear; FFiles.Clear; tvFolders.BeginUpdate; if DirectoryExists(edtFolder.Text) then begin JvSearchFiles.RootDirectory := edtFolder.Text; JvSearchFiles.Search; end; tvFolders.EndUpdate; end; { TStroyInformResourceActionHandler } procedure TStroyInformResourceActionHandler.ExecuteAction; begin TFmImportStroyInformResource.Create(Application).Show; end; begin ActionHandlerManager.RegisterActionHandler('СтройИнформРесурс', hkDefault, TStroyInformResourceActionHandler); end.
unit DAO.DestinosTransporte; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Control.Sistema, Model.DestinosTransportes; type TDestinosTransporteDAO = class private FConexao: TConexao; public constructor Create; function Insert(aDestinos: TDestinosTransporte): Boolean; function Update(aDestinos: TDestinosTransporte): Boolean; function Delete(aDestinos: TDestinosTransporte): Boolean; function Find(aParam: array of Variant): TFDQuery; end; const TABLENAME = 'trs_destinos'; implementation { tDestinosTransporteDAO } constructor TDestinosTransporteDAO.Create; begin FConexao := TConexao.Create; end; function tDestinosTransporteDAO.Delete(aDestinos: TDestinosTransporte): Boolean; var sSQL: String; sWhere: String; FDQuery : TFDQuery; begin try FDQuery := FConexao.ReturnQuery; Result := False; FDQuery.ExecSQL('DELETE FROM ' + TABLENAME + 'WHERE COD_DESTINO = :PCOD_DESTINO', [aDestinos.Destino]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function tDestinosTransporteDAO.Find(aParam: array of Variant): TFDQuery; var FdQuery : TFDQuery; begin if Length(aParam) <= 1 then Exit; FDQuery := FConexao.ReturnQuery; FdQuery.SQL.Add('SELECT * FROM ' + TABLENAME); if aParam[0] = 'CODIGO' then begin FDQuery.SQL.Add('WHERE COD_DESTINO = :CODIGO'); FDQuery.ParamByName('CODIGO').AsInteger := aParam[1]; end; if aParam[0] = 'DESCRICAO' then begin FDQuery.SQL.Add('WHERE DES_DESTINO = :DESTINO'); FDQuery.ParamByName('DESTINO').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; FDQuery.Open(); Result := FDQuery; end; function tDestinosTransporteDAO.Insert(aDestinos: TDestinosTransporte): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + '(COD_DESTINO, DES_DESTINO, DES_LOG) VALUES (:PCOD_DESTINO, :PDES_DESTINO, ' + ':PDES_LOG)', [aDestinos.Destino, aDestinos.Descricao, aDestinos.Log]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function tDestinosTransporteDAO.Update(aDestinos: TDestinosTransporte): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL('UPDATE ' + TABLENAME + 'SET DES_DESTINO = :PDES_DESTINO, DES_LOG = :PDES_LOG WHERE COD_DESTINO = :PCOD_DESTINO', [aDestinos.Descricao, aDestinos.Log, aDestinos.Destino]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; end.
{ $Project$ $Workfile$ $Revision: 1.3 $ $DateUTC$ $Id: IdTlsClientOptions.pas,v 1.3 2015/06/16 12:31:51 lukyanets Exp $ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log: IdTlsClientOptions.pas,v $ Revision 1.3 2015/06/16 12:31:51 lukyanets Новый Indy 10 } { Rev 1.0 27-03-05 10:04:26 MterWoord Second import, first time the filenames weren't prefixed with Id Rev 1.0 27-03-05 09:09:00 MterWoord Created } unit IdTlsClientOptions; interface uses Mono.Security.Protocol.Tls, System.Security.Cryptography.X509Certificates; type TIdTlsClientOptions = class private FProtocol: SecurityProtocolType; FCertificateCollection: X509CertificateCollection; procedure SetProtocol(const Value: SecurityProtocolType); public constructor Create; procedure set_CertificateCollection(const Value: X509CertificateCollection); published property Protocol: SecurityProtocolType read FProtocol write SetProtocol; property CertificateCollection: X509CertificateCollection read FCertificateCollection write set_CertificateCollection; end; implementation { TIdTlsServerOptions } procedure TIdTlsClientOptions.SetProtocol(const Value: SecurityProtocolType); begin FProtocol := Value; end; constructor TIdTlsClientOptions.Create; begin inherited; FProtocol := SecurityProtocolType.Tls; end; procedure TIdTlsClientOptions.set_CertificateCollection( const Value: X509CertificateCollection); begin FCertificateCollection := Value; end; end.
{**************************************************************************************************} { } { Project JEDI } { } { 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 MediaWikiApi.pas } { } { The Initial Developer of the Original Code is Florent Ouchet. } { Portions created by Florent Ouchet are Copyright Florent Ouchet. All rights reserved. } { } { Contributor(s): } { } {**************************************************************************************************} unit MediaWikiApi; interface // main documentation is located at http://www.mediawiki.org/wiki/API uses SysUtils, Classes, JclBase, JclSimpleXml, OverbyteIcsHttpProt, OverbyteIcsWSocket, MediaWikiUtils; type TMediaWikiRequest = (mwrLogin, mwrLogout, mwrQuerySiteInfoGeneral, mwrQuerySiteInfoNamespaces, mwrQuerySiteInfoNamespaceAliases, mwrQuerySiteInfoSpecialPageAliases, mwrQuerySiteInfoMagicWords, mwrQuerySiteInfoStatistics, mwrQuerySiteInfoInterWikiMap, mwrQuerySiteInfoDBReplLag, mwrQuerySiteInfoUserGroups, mwrQuerySiteInfoExtensions, mwrQueryTokens, mwrQueryUserInfoBlockInfo, mwrQueryUserInfoHasMsg, mwrQueryUserInfoGroups, mwrQueryUserInfoRights, mwrQueryUserInfoChangeableGroups, mwrQueryUserInfoOptions, mwrQueryUserInfoEditCount, mwrQueryUserInfoRateLimits, mwrQueryMessages, mwrQueryPageInfo, mwrQueryPageRevisionInfo, mwrQueryPageCategoryInfo, mwrQueryPageLinkInfo, mwrQueryPageTemplateInfo, mwrQueryPageExtLinkInfo, mwrQueryAllPageInfo, mwrQueryAllLinkInfo, mwrQueryAllCategoryInfo, mwrQueryAllUserInfo, mwrQueryBackLinkInfo, mwrQueryBlockInfo, mwrQueryCategoryMemberInfo, mwrEdit, mwrMove, mwrDelete, mwrDeleteRevision, mwrUpload, mwrUserMerge); TMediaWikiRequests = set of TMediaWikiRequest; const MediaWikiExclusiveRequests: TMediaWikiRequests = [mwrLogin, mwrLogout, mwrEdit, mwrMove, mwrDelete, mwrDeleteRevision, mwrUpload]; {$TYPEINFO ON} type TMediaWikiApi = class; TMediaWikiCallback = procedure (Sender: TMediaWikiApi) of object; TMediaWikiWarningCallback = procedure (Sender: TMediaWikiApi; const AInfo, AQuery: string; var Ignore: Boolean); TMediaWikiErrorCallback = procedure (Sender: TMediaWikiApi; const AInfo, ACode: string; var Ignore: Boolean); TMediaWikiXMLCallback = procedure (Sender: TMediaWikiApi; XML: TJclSimpleXML) of object; TMediaWikiStringsCallback = procedure (Sender: TMediaWikiApi; AStrings: TStrings) of object; TMediaWikiExtensionsCallback = procedure (Sender: TMediaWikiApi; const Extensions: TMediaWikiExtensions) of object; TMediaWikiBooleanCallback = procedure (Sender: TMediaWikiApi; Value: Boolean) of object; TMediaWikiIntegerCallback = procedure (Sender: TMediaWikiApi; Value: Integer) of object; TMediaWikiRateLimitsCallback = procedure (Sender: TMediaWikiApi; const RateLimits: TMediaWikiRateLimits) of object; TMediaWikiPageInfosCallback = procedure (Sender: TMediaWikiApi; const PageInfos: TMediaWikiPageInfos) of object; TMediaWikiPageRevisionInfosCallback = procedure (Sender: TMediaWikiApi; const PageRevisionInfos: TMediaWikiPageRevisionInfos; const ContinueInfo: TMediaWikiContinueInfo) of object; TMediaWikiRevisionRangeCallback = procedure (Sender: TMediaWikiApi; StartRevID, EndRevID: TMediaWikiID) of object; TMediaWikiPageCategoryCallback = procedure (Sender: TMediaWikiApi; const PageCategoryInfos: TMediaWikiPageCategoryInfos; const ContinueInfo: TMediaWikiContinueInfo) of object; TMediaWikiPageLinkCallback = procedure (Sender: TMediaWikiApi; const PageLinkInfos: TMediaWikiPageLinkInfos; const ContinueInfo: TMediaWikiContinueInfo) of object; TMediaWikiPageTemplateCallback = procedure (Sender: TMediaWikiApi; const PageTemplateInfos: TMediaWikiPageTemplateInfos; const ContinueInfo: TMediaWikiContinueInfo) of object; TMediaWikiPageExtLinkCallback = procedure (Sender: TMediaWikiApi; const PageExtLinkInfos: TMediaWikiPageExtLinkInfos; const ContinueInfo: TMediaWikiContinueInfo) of object; TMediaWikiAllPageCallback = procedure (Sender: TMediaWikiApi; const AllPages: TMediaWikiAllPageInfos; const ContinueInfo: TMediaWikiContinueInfo) of object; TMediaWikiAllLinkCallback = procedure (Sender: TMediaWikiApi; const AllLinks: TMediaWikiAllLinkInfos; const ContinueInfo: TMediaWikiContinueInfo) of object; TMediaWikiAllCategoriesCallback = procedure (Sender: TMediaWikiApi; ACategories: TStrings; const ContinueInfo: TMediaWikiContinueInfo) of object; TMediaWikiAllUserCallback = procedure (Sender: TMediaWikiApi; const AllUsers: TMediaWikiAllUserInfos; const ContinueInfo: TMediaWikiContinueInfo) of object; TMediaWikiBackLinkCallback = procedure (Sender: TMediaWikiApi; const BackLinks: TMediaWikiBackLinkInfos; const ContinueInfo: TMediaWikiContinueInfo) of object; TMediaWikiBlockCallback = procedure (Sender: TMediaWikiApi; const Blocks: TMediaWikiBlockInfos; const ContinueInfo: TMediaWikiContinueInfo) of object; TMediaWikiCategoryMemberCallback = procedure (Sender: TMediaWikiApi; const CategoryMembers: TMediaWikiCategoryMemberInfos; const ContinueInfo: TMediaWikiContinueInfo) of object; TMediaWikiEditCallback = procedure (Sender: TMediaWikiApi; const EditInfo: TMediaWikiEditInfo) of object; TMediaWikiMoveCallback = procedure (Sender: TMediaWikiApi; const MoveInfo: TMediaWikiMoveInfo) of object; TMediaWikiDeleteCallback = procedure (Sender: TMediaWikiApi; const DeleteInfo: TMediaWikiDeleteInfo) of object; TMediaWikiDeleteRevisionCallback = procedure (Sender: TMediaWikiApi; const DeleteRevisionInfo: TMediaWikiDeleteRevisionInfo) of object; TMediaWikiUploadCallback = procedure (Sender: TMediaWikiApi; const UploadInfo: TMediaWikiUploadInfo) of object; TMediaWikiUserMergeCallback = procedure (Sender: TMediaWikiApi; const UserMergeInfo: TMediaWikiUserMergeInfo) of object; TMediaWikiTokenValuesCallback = procedure (Sender: TMediaWikiApi; const Tokens: TMediaWikiTokenValues) of object; TMediaWikiXMLRequestCallbacks = array [TMediaWikiRequest] of TMediaWikiXMLCallback; TMediaWikiApi = class // general stuff private FHttpsCli: TSslHttpCli; FSslContext: TSslContext; procedure OnCookieRcvd(Sender: TObject; const Data: String; var Accept: Boolean); private FSendStream: TMemoryStream; FReceiveStream: TMemoryStream; FRequestCallbacks: TMediaWikiXMLRequestCallbacks; FQueryStrings: TStrings; FPendingRequests: TMediaWikiRequests; function GetReady: Boolean; procedure RequestDone(Sender: TObject; RqType: THttpRequest; ErrCode: Word); public constructor Create; destructor Destroy; override; procedure CheckRequest(Request: TMediaWikiRequest); procedure QueryInit; property SendStream: TMemoryStream read FSendStream; property ReceiveStream: TMemoryStream read FReceiveStream; // synchronous post function QueryExecute: AnsiString; procedure QueryExecuteXML(XML: TJclSimpleXML); // asynchronous post procedure QueryExecuteAsync; property PendingRequests: TMediaWikiRequests read FPendingRequests; property Ready: Boolean read GetReady; published property HttpsCli: TSslHttpCli read FHttpsCli; property SslContext: TSslContext read FSslContext; // error handling private FIgnoreWarnings: Boolean; FIgnoreErrors: Boolean; FOnWarning: TMediaWikiWarningCallback; FOnError: TMediaWikiErrorCallback; procedure ProcessXMLWarning(const AInfo, AQuery: string); procedure ProcessXMLError(const AInfo, ACode: string); public property IgnoreWarnings: Boolean read FIgnoreWarnings write FIgnoreWarnings; property IgnoreErrors: Boolean read FIgnoreErrors write FIgnoreErrors; property OnWarning: TMediaWikiWarningCallback read FOnWarning write FOnWarning; property OnError: TMediaWikiErrorCallback read FOnError write FOnError; //property OutputFormat: TMediaWikiOutputFormat; // login stuff private FOnLoginDone: TMediaWikiCallback; FLoginPassword: string; FLoginResult: TMediaWikiLoginResult; FLoginToken: string; FLoginUserID: TMediaWikiID; FLoginUserName: string; procedure LoginParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); procedure LoginGetToken(Sender: TMediaWikiApi; const TokenValues: TMediaWikiTokenValues); public // synchronous login function Login: TMediaWikiLoginResult; overload; function Login(const lgName, lgPassword: string): TMediaWikiLoginResult; overload; function Login(const lgName, lgPassword, lgToken: string): TMediaWikiLoginResult; overload; function Login(const lgName, lgPassword, lgToken: string; OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; // asynchronous login procedure LoginAsync; overload; procedure LoginAsync(const lgName, lgPassword: string); overload; procedure LoginAsync(const lgName, lgPassword, lgToken: string); overload; property OnLoginDone: TMediaWikiCallback read FOnLoginDone write FOnLoginDone; // login states property LoginToken: string read FLoginToken write FLoginToken; property LoginResult: TMediaWikiLoginResult read FLoginResult write FLoginResult; property LoginUserID: TMediaWikiID read FLoginUserID write FLoginUserID; published property LoginUserName: string read FLoginUserName write FLoginUserName; property LoginPassword: string read FLoginPassword write FLoginPassword; // logout stuff private FOnLogoutDone: TMediaWikiCallback; procedure LogoutParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public // synchronous login procedure Logout; overload; procedure Logout(const csrf: string); overload; // asynchronous login procedure LogoutAsync(const csrf: string); property OnLogoutDone: TMediaWikiCallback read FOnLogoutDone write FOnLogoutDone; // Meta information queries, site information, general private FOnQuerySiteInfoGeneralDone: TMediaWikiStringsCallback; FQuerySiteInfoGeneralStrings: TStrings; procedure QuerySiteInfoGeneralParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QuerySiteInfoGeneral(Infos: TStrings); overload; function QuerySiteInfoGeneral(OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QuerySiteInfoGeneralAsync; property OnQuerySiteInfoGeneralDone: TMediaWikiStringsCallback read FOnQuerySiteInfoGeneralDone write FOnQuerySiteInfoGeneralDone; // Meta information queries, site information, namespaces: A list of all namespaces private FOnQuerySiteInfoNamespacesDone: TMediaWikiStringsCallback; FQuerySiteInfoNamespacesStrings: TStrings; procedure QuerySiteInfoNamespacesParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QuerySiteInfoNamespaces(Infos: TStrings); overload; function QuerySiteInfoNamespaces(OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QuerySiteInfoNamespacesAsync; property OnQuerySiteInfoNamespacesDone: TMediaWikiStringsCallback read FOnQuerySiteInfoNamespacesDone write FOnQuerySiteInfoNamespacesDone; // Meta information queries, site information, namespacealiases: A list of all namespace aliases (MW 1.13+) private FOnQuerySiteInfoNamespaceAliasesDone: TMediaWikiStringsCallback; FQuerySiteInfoNamespaceAliasesStrings: TStrings; procedure QuerySiteInfoNamespaceAliasesParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QuerySiteInfoNamespaceAliases(Infos: TStrings); overload; function QuerySiteInfoNamespaceAliases(OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QuerySiteInfoNamespaceAliasesAsync; property OnQuerySiteInfoNamespaceAliasesDone: TMediaWikiStringsCallback read FOnQuerySiteInfoNamespaceAliasesDone write FOnQuerySiteInfoNamespaceAliasesDone; // Meta information queries, site information, specialpagealiases: A list of all special page aliases (MW 1.13+) private FOnQuerySiteInfoSpecialPageAliasesDone: TMediaWikiStringsCallback; FQuerySiteInfoSpecialPageAliasesStrings: TStrings; procedure QuerySiteInfoSpecialPageAliasesParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QuerySiteInfoSpecialPageAliases(Infos: TStrings); overload; function QuerySiteInfoSpecialPageAliases(OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QuerySiteInfoSpecialPageAliasesAsync; property OnQuerySiteInfoSpecialPageAliasesDone: TMediaWikiStringsCallback read FOnQuerySiteInfoSpecialPageAliasesDone write FOnQuerySiteInfoSpecialPageAliasesDone; // Meta information queries, site information, magicwords: A list of magic words and their aliases (MW 1.14+) private FOnQuerySiteInfoMagicWordsDone: TMediaWikiStringsCallback; FQuerySiteInfoMagicWordsStrings: TStrings; procedure QuerySiteInfoMagicWordsParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QuerySiteInfoMagicWords(Infos: TStrings); overload; function QuerySiteInfoMagicWords(OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QuerySiteInfoMagicWordsAsync; property OnQuerySiteInfoMagicWordsDone: TMediaWikiStringsCallback read FOnQuerySiteInfoMagicWordsDone write FOnQuerySiteInfoMagicWordsDone; // Meta information queries, site information, statistics: Site statistics à la Special:Statistics (MW 1.11+) private FOnQuerySiteInfoStatisticsDone: TMediaWikiStringsCallback; FQuerySiteInfoStatisticsStrings: TStrings; procedure QuerySiteInfoStatisticsParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QuerySiteInfoStatistics(Infos: TStrings); overload; function QuerySiteInfoStatistics(OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QuerySiteInfoStatisticsAsync; property OnQuerySiteInfoStatisticsDone: TMediaWikiStringsCallback read FOnQuerySiteInfoStatisticsDone write FOnQuerySiteInfoStatisticsDone; // Meta information queries, site information, interwikimap: A list of all interwiki prefixes and where they go (MW 1.11+) private FOnQuerySiteInfoInterWikiMapDone: TMediaWikiStringsCallback; FQuerySiteInfoInterWikiMapStrings: TStrings; procedure QuerySiteInfoInterWikiMapParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QuerySiteInfoInterWikiMap(Local: Boolean; Infos: TStrings); overload; function QuerySiteInfoInterWikiMap(Local: Boolean; OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QuerySiteInfoInterWikiMapAsync(Local: Boolean); property OnQuerySiteInfoInterWikiMapDone: TMediaWikiStringsCallback read FOnQuerySiteInfoInterWikiMapDone write FOnQuerySiteInfoInterWikiMapDone; // Meta information queries, site information, dbrepllag: Get information about the database server with the highest replication lag (MW 1.11) private FOnQuerySiteInfoDBReplLagDone: TMediaWikiStringsCallback; FQuerySiteInfoDBReplLagStrings: TStrings; procedure QuerySiteInfoDBReplLagParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QuerySiteInfoDBReplLag(ShowAllDB: Boolean; Infos: TStrings); overload; function QuerySiteInfoDBReplLag(ShowAllDB: Boolean; OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QuerySiteInfoDBReplLagAsync(ShowAllDB: Boolean); property OnQuerySiteInfoDBReplLagDone: TMediaWikiStringsCallback read FOnQuerySiteInfoDBReplLagDone write FOnQuerySiteInfoDBReplLagDone; // Meta information queries, site information, usergroups: A list of all user groups and their permissions (MW 1.13+) private FOnQuerySiteInfoUserGroupsDone: TMediaWikiStringsCallback; FQuerySiteInfoUserGroupsStrings: TStrings; procedure QuerySiteInfoUserGroupsParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QuerySiteInfoUserGroups(IncludeUserCount: Boolean; Infos: TStrings); overload; function QuerySiteInfoUserGroups(IncludeUserCount: Boolean; OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QuerySiteInfoUserGroupsAsync(IncludeUserCount: Boolean); property OnQuerySiteInfoUserGroupsDone: TMediaWikiStringsCallback read FOnQuerySiteInfoUserGroupsDone write FOnQuerySiteInfoUserGroupsDone; // Meta information queries, site information, extensions: A list of extensions installed on the wiki (MW 1.14+) private FOnQuerySiteInfoExtensionsDone: TMediaWikiExtensionsCallback; FQuerySiteInfoExtensions: TMediaWikiExtensions; procedure QuerySiteInfoExtensionsParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QuerySiteInfoExtensions(out Infos: TMediaWikiExtensions); overload; function QuerySiteInfoExtensions(OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QuerySiteInfoExtensionsAsync; property OnQuerySiteInfoExtensionsDone: TMediaWikiExtensionsCallback read FOnQuerySiteInfoExtensionsDone write FOnQuerySiteInfoExtensionsDone; (* TODO: fileextensions: A list of file extensions allowed to be uploaded (MW 1.15+) *) (* TODO: rightsinfo: Get information about the license governing the wiki's content (MW 1.15+) *) (* TODO: languages: Get available languages as seen in preferences (MW 1.16+) *) // Meta information queries, tokens private FOnQueryTokensDone: TMediaWikiTokenValuesCallback; FQueryTokenValues: TMediaWikiTokenValues; procedure QueryTokensParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryTokens(Tokens: TMediaWikiTokens; out TokenValues: TMediaWikiTokenValues); overload; function QueryTokens(Tokens: TMediaWikiTokens; OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QueryTokensAsync(Tokens: TMediaWikiTokens); property OnQueryTokenDone: TMediaWikiTokenValuesCallback read FOnQueryTokensDone write FOnQueryTokensDone; property QueryTokenValues: TMediaWikiTokenValues read FQueryTokenValues write FQueryTokenValues; // Meta information queries, user information, blockinfo: Whether the current user is blocked, by whom, and why private FOnQueryUserInfoBlockInfoDone: TMediaWikiStringsCallback; FQueryUserInfoBlockInfoStrings: TStrings; procedure QueryUserInfoBlockInfoParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryUserInfoBlockInfo(Infos: TStrings); overload; function QueryUserInfoBlockInfo(OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QueryUserInfoBlockInfoAsync; property OnQueryUserInfoBlockInfoDone: TMediaWikiStringsCallback read FOnQueryUserInfoBlockInfoDone write FOnQueryUserInfoBlockInfoDone; // Meta information queries, user information, hasmsg: Whether the current user has new messages on their user talk page private FOnQueryUserInfoHasMsgDone: TMediaWikiBooleanCallback; FQueryUserInfoHasMsg: Boolean; procedure QueryUserInfoHasMsgParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public function QueryUserInfoHasMsg: Boolean; overload; function QueryUserInfoHasMsg(OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QueryUserInfoHasMsgAsync; property OnQueryUserInfoHasMsgDone: TMediaWikiBooleanCallback read FOnQueryUserInfoHasMsgDone write FOnQueryUserInfoHasMsgDone; // Meta information queries, user information, groups: Which groups the current user belongs to private FOnQueryUserInfoGroupsDone: TMediaWikiStringsCallback; FQueryUserInfoGroupsStrings: TStrings; procedure QueryUserInfoGroupsParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryUserInfoGroups(Infos: TStrings); overload; function QueryUserInfoGroups(OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QueryUserInfoGroupsAsync; property OnQueryUserInfoGroupsDone: TMediaWikiStringsCallback read FOnQueryUserInfoGroupsDone write FOnQueryUserInfoGroupsDone; // Meta information queries, user information, rights: Which rights the current user has private FOnQueryUserInfoRightsDone: TMediaWikiStringsCallback; FQueryUserInfoRightsStrings: TStrings; procedure QueryUserInfoRightsParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryUserInfoRights(Infos: TStrings); overload; function QueryUserInfoRights(OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QueryUserInfoRightsAsync; property OnQueryUserInfoRightsDone: TMediaWikiStringsCallback read FOnQueryUserInfoRightsDone write FOnQueryUserInfoRightsDone; // Meta information queries, user information, changeablegroups: Which groups the current user can add/remove private FOnQueryUserInfoChangeableGroupsDone: TMediaWikiStringsCallback; FQueryUserInfoChangeableGroupsStrings: TStrings; procedure QueryUserInfoChangeableGroupsParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryUserInfoChangeableGroups(Infos: TStrings); overload; function QueryUserInfoChangeableGroups(OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QueryUserInfoChangeableGroupsAsync; property OnQueryUserInfoChangeableGroupsDone: TMediaWikiStringsCallback read FOnQueryUserInfoChangeableGroupsDone write FOnQueryUserInfoChangeableGroupsDone; // Meta information queries, user information, options: Which preferences the current user has private FOnQueryUserInfoOptionsDone: TMediaWikiStringsCallback; FQueryUserInfoOptionsStrings: TStrings; procedure QueryUserInfoOptionsParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryUserInfoOptions(Infos: TStrings); overload; function QueryUserInfoOptions(OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QueryUserInfoOptionsAsync; property OnQueryUserInfoOptionsDone: TMediaWikiStringsCallback read FOnQueryUserInfoOptionsDone write FOnQueryUserInfoOptionsDone; // Meta information queries, user information, editcount: The number of edits the current user has made private FOnQueryUserInfoEditCountDone: TMediaWikiIntegerCallback; FQueryUserInfoEditCount: Integer; procedure QueryUserInfoEditCountParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public function QueryUserInfoEditCount: Integer; overload; function QueryUserInfoEditCount(OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QueryUserInfoEditCountAsync; property OnQueryUserInfoEditCountDone: TMediaWikiIntegerCallback read FOnQueryUserInfoEditCountDone write FOnQueryUserInfoEditCountDone; // Meta information queries, user information, ratelimits: Rate limits applying to the current user private FOnQueryUserInfoRateLimitsDone: TMediaWikiRateLimitsCallback; FQueryUserInfoRateLimits: TMediaWikiRateLimits; procedure QueryUserInfoRateLimitsParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryUserInfoRateLimits(out Infos: TMediaWikiRateLimits); overload; function QueryUserInfoRateLimits(OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QueryUserInfoRateLimitsAsync; property OnQueryUserInfoRateLimitsDone: TMediaWikiRateLimitsCallback read FOnQueryUserInfoRateLimitsDone write FOnQueryUserInfoRateLimitsDone; (* TODO: email: Email address and authentication timestamp in ISO 8601 format [1.15+] *) // Meta information queries, allmessages: Lists the contents of all (or a few) interface messages. private FOnQueryMessagesDone: TMediaWikiStringsCallback; FQueryMessagesStrings: TStrings; procedure QueryMessagesParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryMessages(const NameFilter, ContentFilter, Lang: string; Infos: TStrings); overload; function QueryMessages(const NameFilter, ContentFilter, Lang: string; OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QueryMessagesAsync(const NameFilter, ContentFilter, Lang: string); property OnQueryMessagesDone: TMediaWikiStringsCallback read FOnQueryMessagesDone write FOnQueryMessagesDone; // Queries, info / in: Gets basic page information private FOnQueryPageInfoDone: TMediaWikiPageInfosCallback; FQueryPageInfos: TMediaWikiPageInfos; procedure QueryPageInfoParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryPageInfo(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageInfoFlags; out Infos: TMediaWikiPageInfos); overload; function QueryPageInfo(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageInfoFlags; OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure QueryPageInfoAsync(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageInfoFlags); property OnQueryPageInfoDone: TMediaWikiPageInfosCallback read FOnQueryPageInfoDone write FOnQueryPageInfoDone; // Queries, revisions / rv: Returns revisions for a given page private FOnQueryPageRevisionInfoDone: TMediaWikiPageRevisionInfosCallback; FQueryPageRevisionInfos: TMediaWikiPageRevisionInfos; FQueryPageRevisionContinueInfo: TMediaWikiContinueInfo; procedure QueryPageRevisionInfoParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryPageRevisionInfo(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageRevisionInfoFlags; out Infos: TMediaWikiPageRevisionInfos; var ContinueInfo: TMediaWikiContinueInfo; MaxRevisions: Integer = 0; Section: Integer = -1; StartRevisionID: TMediaWikiID = -1; EndRevisionID: TMediaWikiID = -1; const StartDateTime: TDateTime = 0.0; const EndDateTime: TDateTime = 0.0; const IncludeUser: string = ''; const ExcludeUser: string = ''); overload; function QueryPageRevisionInfo(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageRevisionInfoFlags; OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; MaxRevisions: Integer = 0; Section: Integer = -1; StartRevisionID: TMediaWikiID = -1; EndRevisionID: TMediaWikiID = -1; const StartDateTime: TDateTime = 0.0; const EndDateTime: TDateTime = 0.0; const IncludeUser: string = ''; const ExcludeUser: string = ''): AnsiString; overload; procedure QueryPageRevisionInfoAsync(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageRevisionInfoFlags; const ContinueInfo: TMediaWikiContinueInfo; MaxRevisions: Integer = 0; Section: Integer = -1; StartRevisionID: TMediaWikiID = -1; EndRevisionID: TMediaWikiID = -1; const StartDateTime: TDateTime = 0.0; const EndDateTime: TDateTime = 0.0; const IncludeUser: string = ''; const ExcludeUser: string = ''); property OnQueryPageRevisionInfoDone: TMediaWikiPageRevisionInfosCallback read FOnQueryPageRevisionInfoDone write FOnQueryPageRevisionInfoDone; // Queries, categories / cl: Gets a list of all categories private FOnQueryPageCategoryInfoDone: TMediaWikiPageCategoryCallback; FQueryPageCategoryInfos: TMediaWikiPageCategoryInfos; FQueryPageCategoryContinueInfo: TMediaWikiContinueInfo; procedure QueryPageCategoryInfoParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryPageCategoryInfo(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageCategoryInfoFlags; out Infos: TMediaWikiPageCategoryInfos; var ContinueInfo: TMediaWikiContinueInfo; MaxCategories: Integer = 0; const CategoryTitles: string = ''); overload; function QueryPageCategoryInfo(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageCategoryInfoFlags; OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; MaxCategories: Integer = 0; const CategoryTitles: string = ''): AnsiString; overload; procedure QueryPageCategoryInfoAsync(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageCategoryInfoFlags; const ContinueInfo: TMediaWikiContinueInfo; MaxCategories: Integer = 0; const CategoryTitles: string = ''); property OnQueryPageCategoryInfoDone: TMediaWikiPageCategoryCallback read FOnQueryPageCategoryInfoDone write FOnQueryPageCategoryInfoDone; // Queries, imageinfo / ii: Gets image information TODO // Queries, langlinks / ll: Gets a list of all language links TODO // Queries, links / pl: Gets a list of all links private FOnQueryPageLinkInfoDone: TMediaWikiPageLinkCallback; FQueryPageLinkInfos: TMediaWikiPageLinkInfos; FQueryPageLinkContinueInfo: TMediaWikiContinueInfo; procedure QueryPageLinkInfoParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryPageLinkInfo(const Titles: string; PageID: Boolean; out Infos: TMediaWikiPageLinkInfos; var ContinueInfo: TMediaWikiContinueInfo; MaxLinks: Integer = 0; Namespace: Integer = -1); overload; function QueryPageLinkInfo(const Titles: string; PageID: Boolean; OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; MaxLinks: Integer = 0; Namespace: Integer = -1): AnsiString; overload; procedure QueryPageLinkInfoAsync(const Titles: string; PageID: Boolean; const ContinueInfo: TMediaWikiContinueInfo; MaxLinks: Integer = 0; Namespace: Integer = -1); property OnQueryPageLinkInfoDone: TMediaWikiPageLinkCallback read FOnQueryPageLinkInfoDone write FOnQueryPageLinkInfoDone; // Queries, templates / tl: Gets a list of all pages included in the provided pages private FOnQueryPageTemplateInfoDone: TMediaWikiPageTemplateCallback; FQueryPageTemplateInfos: TMediaWikiPageTemplateInfos; FQueryPageTemplateContinueInfo: TMediaWikiContinueInfo; procedure QueryPageTemplateInfoParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryPageTemplateInfo(const Titles: string; PageID: Boolean; out Infos: TMediaWikiPageTemplateInfos; var ContinueInfo: TMediaWikiContinueInfo; MaxTemplates: Integer = 0; Namespace: Integer = -1); overload; function QueryPageTemplateInfo(const Titles: string; PageID: Boolean; OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; MaxTemplates: Integer = 0; Namespace: Integer = -1): AnsiString; overload; procedure QueryPageTemplateInfoAsync(const Titles: string; PageID: Boolean; const ContinueInfo: TMediaWikiContinueInfo; MaxTemplates: Integer = 0; Namespace: Integer = -1); property OnQueryPageTemplateInfoDone: TMediaWikiPageTemplateCallback read FOnQueryPageTemplateInfoDone write FOnQueryPageTemplateInfoDone; // Queries, images / im: Gets a list of all images used on the provided pages TODO // Queries, extlinks / el: Gets a list of all external links on the provided pages private FOnQueryPageExtLinkInfoDone: TMediaWikiPageExtLinkCallback; FQueryPageExtLinkInfos: TMediaWikiPageExtLinkInfos; FQueryPageExtLinkContinueInfo: TMediaWikiContinueInfo; procedure QueryPageExtLinkInfoParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryPageExtLinkInfo(const Titles: string; PageID: Boolean; out Infos: TMediaWikiPageExtLinkInfos; var ContinueInfo: TMediaWikiContinueInfo; MaxLinks: Integer = 0); overload; function QueryPageExtLinkInfo(const Titles: string; PageID: Boolean; OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; MaxLinks: Integer = 0): AnsiString; overload; procedure QueryPageExtLinkInfoAsync(const Titles: string; PageID: Boolean; const ContinueInfo: TMediaWikiContinueInfo; MaxLinks: Integer = 0); property OnQueryPageExtLinkInfoDone: TMediaWikiPageExtLinkCallback read FOnQueryPageExtLinkInfoDone write FOnQueryPageExtLinkInfoDone; // Queries, categoryinfo / ci: Gets information about categories TODO // Queries, duplicatefiles / df: List duplicates of the given files. TODO // Queries, list, all pages: Returns a list of pages in a given namespace, ordered by page title. private FOnQueryAllPageInfoDone: TMediaWikiAllPageCallback; FQueryAllPageInfos: TMediaWikiAllPageInfos; FQueryAllPageContinueInfo: TMediaWikiContinueInfo; procedure QueryAllPageInfoParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryAllPageInfo(out Infos: TMediaWikiAllPageInfos; var ContinueInfo: TMediaWikiContinueInfo; const Prefix: string = ''; MaxPage: Integer = 0; Namespace: Integer = -1; RedirFilter: TMediaWikiAllPageFilterRedir = mwfAllPageFilterAll; LangFilter: TMediaWikiAllPageFilterLang = mwfAllPageLangAll; MinSize: Integer = -1; MaxSize: Integer = -1; ProtectionFilter: TMediaWikiAllPageFilterProtection = mwfAllPageProtectionNone; LevelFilter: TMediaWikiAllPageFilterLevel = mwfAllPageLevelNone; Direction: TMediaWikiAllPageDirection = mwfAllPageAscending); overload; function QueryAllPageInfo(OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string = ''; MaxPage: Integer = 0; Namespace: Integer = -1; RedirFilter: TMediaWikiAllPageFilterRedir = mwfAllPageFilterAll; LangFilter: TMediaWikiAllPageFilterLang = mwfAllPageLangAll; MinSize: Integer = -1; MaxSize: Integer = -1; ProtectionFilter: TMediaWikiAllPageFilterProtection = mwfAllPageProtectionNone; LevelFilter: TMediaWikiAllPageFilterLevel = mwfAllPageLevelNone; Direction: TMediaWikiAllPageDirection = mwfAllPageAscending): AnsiString; overload; procedure QueryAllPageInfoAsync(const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string = ''; MaxPage: Integer = 0; Namespace: Integer = -1; RedirFilter: TMediaWikiAllPageFilterRedir = mwfAllPageFilterAll; LangFilter: TMediaWikiAllPageFilterLang = mwfAllPageLangAll; MinSize: Integer = -1; MaxSize: Integer = -1; ProtectionFilter: TMediaWikiAllPageFilterProtection = mwfAllPageProtectionNone; LevelFilter: TMediaWikiAllPageFilterLevel = mwfAllPageLevelNone; Direction: TMediaWikiAllPageDirection = mwfAllPageAscending); property OnQueryAllPageInfoDone: TMediaWikiAllPageCallback read FOnQueryAllPageInfoDone write FOnQueryAllPageInfoDone; // Queries, list, all links: Returns a list of (unique) links to pages in a given namespace starting ordered by link title. private FOnQueryAllLinkInfoDone: TMediaWikiAllLinkCallback; FQueryAllLinkInfos: TMediaWikiAllLinkInfos; FQueryAllLinkContinueInfo: TMediaWikiContinueInfo; procedure QueryAllLinkInfoParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryAllLinkInfo(out Infos: TMediaWikiAllLinkInfos; var ContinueInfo: TMediaWikiContinueInfo; const Prefix: string = ''; MaxLink: Integer = 0; Namespace: Integer = -1; Flags: TMediaWikiAllLinkInfoFlags = []); overload; function QueryAllLinkInfo(OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string = ''; MaxLink: Integer = 0; Namespace: Integer = -1; Flags: TMediaWikiAllLinkInfoFlags = []): AnsiString; overload; procedure QueryAllLinkInfoAsync(const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string = ''; MaxLink: Integer = 0; Namespace: Integer = -1; Flags: TMediaWikiAllLinkInfoFlags = []); property OnQueryAllLinkInfoDone: TMediaWikiAllLinkCallback read FOnQueryAllLinkInfoDone write FOnQueryAllLinkInfoDone; // Queries, list, all categories: Get a list of all categories. private FOnQueryAllCategoryInfoDone: TMediaWikiAllCategoriesCallback; FQueryAllCategoryInfos: TStrings; FQueryAllCategoryContinueInfo: TMediaWikiContinueInfo; procedure QueryAllCategoryInfoParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryAllCategoryInfo(Infos: TStrings; var ContinueInfo: TMediaWikiContinueInfo; const Prefix: string = ''; MaxCategory: Integer = 0; Flags: TMediaWikiAllCategoryInfoFlags = []); overload; function QueryAllCategoryInfo(OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string = ''; MaxCategory: Integer = 0; Flags: TMediaWikiAllCategoryInfoFlags = []): AnsiString; overload; procedure QueryAllCategoryInfoAsync(const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string = ''; MaxCategory: Integer = 0; Flags: TMediaWikiAllCategoryInfoFlags = []); property OnQueryAllCategoryInfoDone: TMediaWikiAllCategoriesCallback read FOnQueryAllCategoryInfoDone write FOnQueryAllCategoryInfoDone; // Queries, list, all users: Get a list of registered users, ordered by username. private FOnQueryAllUserInfoDone: TMediaWikiAllUserCallback; FQueryAllUserInfos: TMediaWikiAllUserInfos; FQueryAllUserContinueInfo: TMediaWikiContinueInfo; procedure QueryAllUserInfoParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryAllUserInfo(out Infos: TMediaWikiAllUserInfos; var ContinueInfo: TMediaWikiContinueInfo; const Prefix: string = ''; const Group: string = ''; MaxUser: Integer = 0; Flags: TMediaWikiAllUserInfoFlags = []); overload; function QueryAllUserInfo(OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string = ''; const Group: string = ''; MaxUser: Integer = 0; Flags: TMediaWikiAllUserInfoFlags = []): AnsiString; overload; procedure QueryAllUserInfoAsync(const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string = ''; const Group: string = ''; MaxUser: Integer = 0; Flags: TMediaWikiAllUserInfoFlags = []); property OnQueryAllUserInfoDone: TMediaWikiAllUserCallback read FOnQueryAllUserInfoDone write FOnQueryAllUserInfoDone; // Queries, list, allimages / ai: Returns a list of all images, ordered by image title. TODO // Queries, list, all backlinks / bl: Lists pages that link to a given page, similar to Special:Whatlinkshere. Ordered by linking page title. private FOnQueryBackLinkInfoDone: TMediaWikiBackLinkCallback; FQueryBackLinkInfos: TMediaWikiBackLinkInfos; FQueryBackLinkContinueInfo: TMediaWikiContinueInfo; procedure QueryBackLinkInfoParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryBackLinkInfo(const BackLinkTitle: string; out Infos: TMediaWikiBackLinkInfos; var ContinueInfo: TMediaWikiContinueInfo; Namespace: Integer = -1; MaxLink: Integer = 0; Flags: TMediaWikiBackLinkInfoFlags = []); overload; function QueryBackLinkInfo(const BackLinkTitle: string; OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; Namespace: Integer = -1; MaxLink: Integer = 0; Flags: TMediaWikiBackLinkInfoFlags = []): AnsiString; overload; procedure QueryBackLinkInfoAsync(const BackLinkTitle: string; const ContinueInfo: TMediaWikiContinueInfo; Namespace: Integer = -1; MaxLink: Integer = 0; Flags: TMediaWikiBackLinkInfoFlags = []); property OnQueryBackLinkInfoDone: TMediaWikiBackLinkCallback read FOnQueryBackLinkInfoDone write FOnQueryBackLinkInfoDone; // Queries, list, all blocks / bk: List all blocks, à la Special:Ipblocklist. This module cannot be used as a generator. private FOnQueryBlockInfoDone: TMediaWikiBlockCallback; FQueryBlockInfos: TMediaWikiBlockInfos; FQueryBlockContinueInfo: TMediaWikiContinueInfo; procedure QueryBlockInfoParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryBlockInfo(out Infos: TMediaWikiBlockInfos; var ContinueInfo: TMediaWikiContinueInfo; const StartDateTime: TDateTime = 0.0; const StopDateTime: TDateTime = 0.0; const BlockIDs: string = ''; const Users: string = ''; const IP: string = ''; MaxBlock: Integer = 0; Flags: TMediaWikiBlockInfoFlags = []); overload; function QueryBlockInfo(OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; const StartDateTime: TDateTime = 0.0; const StopDateTime: TDateTime = 0.0; const BlockIDs: string = ''; const Users: string = ''; const IP: string = ''; MaxBlock: Integer = 0; Flags: TMediaWikiBlockInfoFlags = []): AnsiString; overload; procedure QueryBlockInfoAsync(const ContinueInfo: TMediaWikiContinueInfo; const StartDateTime: TDateTime = 0.0; const StopDateTime: TDateTime = 0.0; const BlockIDs: string = ''; const Users: string = ''; const IP: string = ''; MaxBlock: Integer = 0; Flags: TMediaWikiBlockInfoFlags = []); property OnQueryBlockInfoDone: TMediaWikiBlockCallback read FOnQueryBlockInfoDone write FOnQueryBlockInfoDone; // Queries, list, categorymembers / cm: List of pages that belong to a given category, ordered by page sort title. private FOnQueryCategoryMemberInfoDone: TMediaWikiCategoryMemberCallback; FQueryCategoryMemberInfos: TMediaWikiCategoryMemberInfos; FQueryCategoryMemberContinueInfo: TMediaWikiContinueInfo; procedure QueryCategoryMemberInfoParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure QueryCategoryMemberInfo(const CategoryTitle: string; out Infos: TMediaWikiCategoryMemberInfos; var ContinueInfo: TMediaWikiContinueInfo; PageNamespace: Integer = -1; const StartDateTime: TDateTime = 0.0; const StopDateTime: TDateTime = 0.0; const StartSortKey: string = ''; const StopSortKey: string = ''; MaxCategoryMember: Integer = 0; Flags: TMediaWikiCategoryMemberInfoFlags = []); overload; function QueryCategoryMemberInfo(const CategoryTitle: string; OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; PageNamespace: Integer = -1; const StartDateTime: TDateTime = 0.0; const StopDateTime: TDateTime = 0.0; const StartSortKey: string = ''; const StopSortKey: string = ''; MaxCategoryMember: Integer = 0; Flags: TMediaWikiCategoryMemberInfoFlags = []): AnsiString; overload; procedure QueryCategoryMemberInfoAsync(const CategoryTitle: string; const ContinueInfo: TMediaWikiContinueInfo; PageNamespace: Integer = -1; const StartDateTime: TDateTime = 0.0; const StopDateTime: TDateTime = 0.0; const StartSortKey: string = ''; const StopSortKey: string = ''; MaxCategoryMember: Integer = 0; Flags: TMediaWikiCategoryMemberInfoFlags = []); property OnQueryCategoryMemberInfoDone: TMediaWikiCategoryMemberCallback read FOnQueryCategoryMemberInfoDone write FOnQueryCategoryMemberInfoDone; // Queries, list, embeddedin / ei: List pages that include a certain page TODO // Queries, list, exturlusage / eu: Get a list of pages that link to a certain URL, à la Special:Linksearch TODO // Queries, list, imageusage / iu: List of pages that include a given image. Ordered by page title. TODO // Queries, list, logevents / le: Get a list of all logged events, à la Special:Log. This module cannot be used as a generator. TODO // Queries, list, recentchanges / rc: Get all recent changes to the wiki, à la Special:Recentchanges. This module cannot be used as a generator. TODO // Queries, list, search / sr: Search for a string in all articles à la Special:Search TODO // Queries, list, usercontribs / uc: Gets a list of contributions made by a given user, ordered by modification time. This module cannot be used as a generator. TODO // Queries, list, watchlist / wl: Get a list of pages on the current user's watchlist that were changed within the given time period. Ordered by time of the last change of the watched page. TODO // Queries, list, deletedrevs / dr: List deleted revisions. TODO // Queries, list, users / us: Get information about a list of users. TODO // Queries, list, random / rn: Get a list of random pages. TODO // Queries, list, protectedtitles / pt: Get a list of titles protected from creation. TODO // Edit private FOnEditDone: TMediaWikiEditCallback; FEditInfo: TMediaWikiEditInfo; procedure EditParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure Edit(const PageTitle, Section, Text, PrependText, AppendText, EditToken, Summary: string; out EditInfo: TMediaWikiEditInfo; const MD5: string = ''; const CaptchaID: string = ''; const CaptchaWord: string = ''; const BaseDateTime: TDateTime = 0.0; const StartDateTime: TDateTime = 0.0; UndoRevisionID: TMediaWikiID = -1; Flags: TMediaWikiEditFlags = []); overload; function Edit(const PageTitle, Section, Text, PrependText, AppendText, EditToken, Summary: string; OutputFormat: TMediaWikiOutputFormat; const MD5: string = ''; const CaptchaID: string = ''; const CaptchaWord: string = ''; const BaseDateTime: TDateTime = 0.0; const StartDateTime: TDateTime = 0.0; UndoRevisionID: TMediaWikiID = -1; Flags: TMediaWikiEditFlags = []): AnsiString; overload; procedure EditAsync(const PageTitle, Section, Text, PrependText, AppendText, EditToken, Summary: string; const MD5: string = ''; const CaptchaID: string = ''; const CaptchaWord: string = ''; const BaseDateTime: TDateTime = 0.0; const StartDateTime: TDateTime = 0.0; UndoRevisionID: TMediaWikiID = -1; Flags: TMediaWikiEditFlags = []); property OnEditDone: TMediaWikiEditCallback read FOnEditDone write FOnEditDone; // Move private FOnMoveDone: TMediaWikiMoveCallback; FMoveInfo: TMediaWikiMoveInfo; procedure MoveParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure Move(const FromPageTitle, ToPageTitle, MoveToken, Reason: string; FromPageID: TMediaWikiID; Flags: TMediaWikiMoveFlags; out MoveInfo: TMediaWikiMoveInfo); overload; function Move(const FromPageTitle, ToPageTitle, MoveToken, Reason: string; FromPageID: TMediaWikiID; Flags: TMediaWikiMoveFlags; OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure MoveAsync(const FromPageTitle, ToPageTitle, MoveToken, Reason: string; FromPageID: TMediaWikiID; Flags: TMediaWikiMoveFlags); property OnMoveDone: TMediaWikiMoveCallback read FOnMoveDone write FOnMoveDone; // Rollback TODO // Delete private FOnDeleteDone: TMediaWikiDeleteCallback; FDeleteInfo: TMediaWikiDeleteInfo; procedure DeleteParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure Delete(const PageTitle, DeleteToken, Reason: string; FromPageID: TMediaWikiID; out DeleteInfo: TMediaWikiDeleteInfo; Suppress: Boolean = False); overload; function Delete(const PageTitle, DeleteToken, Reason: string; FromPageID: TMediaWikiID; OutputFormat: TMediaWikiOutputFormat; Suppress: Boolean = False): AnsiString; overload; procedure DeleteAsync(const PageTitle, DeleteToken, Reason: string; FromPageID: TMediaWikiID; Suppress: Boolean = False); property OnDeleteDone: TMediaWikiDeleteCallback read FOnDeleteDone write FOnDeleteDone; // Delete Revision private FOnDeleteRevisionDone: TMediaWikiDeleteRevisionCallback; FDeleteRevisionInfo: TMediaWikiDeleteRevisionInfo; procedure DeleteRevisionParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure DeleteRevision(const PageTitle, DeleteToken, Reason: string; FromPageID, RevisionID: TMediaWikiID; out DeleteRevisionInfo: TMediaWikiDeleteRevisionInfo); overload; function DeleteRevision(const PageTitle, DeleteToken, Reason: string; FromPageID, RevisionID: TMediaWikiID; OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure DeleteRevisionAsync(const PageTitle, DeleteToken, Reason: string; FromPageID, RevisionID: TMediaWikiID); property OnDeleteRevisionDone: TMediaWikiDeleteRevisionCallback read FOnDeleteRevisionDone write FOnDeleteRevisionDone; // restore deleted revisions TODO // (un)protect pages TODO // (Un)block users TODO // (Un)watch pages TODO // Send e-mail TODO // Patrol changes TODO // Import pages TODO // Change user group membership TODO // Upload files TODO private FOnUploadDone: TMediaWikiUploadCallback; FUploadInfo: TMediaWikiUploadInfo; procedure UploadParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure Upload(const FileName, Comment, Text, EditToken: string; Flags: TMediaWikiUploadFlags; Content: TStream; const URL: string; out UploadInfo: TMediaWikiUploadInfo); overload; function Upload(const FileName, Comment, Text, EditToken: string; Flags: TMediaWikiUploadFlags; Content: TStream; const URL: string; OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure UploadAsync(const FileName, Comment, Text, EditToken: string; Flags: TMediaWikiUploadFlags; Content: TStream; const URL: string); property OnUploadDone: TMediaWikiUploadCallback read FOnUploadDone write FOnUploadDone; // User Merge private FOnUserMergeDone: TMediaWikiUserMergeCallback; FUserMergeInfo: TMediaWikiUserMergeInfo; procedure UserMergeParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); public procedure UserMerge(const OldUser, NewUser, Token: string; DeleteUser: Boolean; out UserMergeInfo: TMediaWikiUserMergeInfo); overload; function UserMerge(const OldUser, NewUser, Token: string; DeleteUser: Boolean; OutputFormat: TMediaWikiOutputFormat): AnsiString; overload; procedure UserMergeAsync(const OldUser, NewUser, Token: string; DeleteUser: Boolean); property OnUserMergeDone: TMediaWikiUserMergeCallback read FOnUserMergeDone write FOnUserMergeDone; end; {$TYPEINFO OFF} implementation uses JclStrings, JclStreams; //=== { TMediaWikiApi } ====================================================== constructor TMediaWikiApi.Create; begin inherited Create; FIgnoreWarnings := True; FIgnoreErrors := False; FHttpsCli := TSslHttpCli.Create(nil); FHttpsCli.OnRequestDone := RequestDone; FHttpsCli.OnCookie := OnCookieRcvd; FSslContext := TSslContext.Create(nil); FHttpsCli.SslContext := FSslContext; FSendStream := TMemoryStream.Create; FReceiveStream := TMemoryStream.Create; FHttpsCli.SendStream := FSendStream; FHttpsCli.RcvdStream := FReceiveStream; FQueryStrings := TStringList.Create; end; destructor TMediaWikiApi.Destroy; begin if LoginUserID <> 0 then Logout; FQueryStrings.Free; FSendStream.Free; FReceiveStream.Free; FHttpsCli.Free; inherited Destroy; end; procedure TMediaWikiApi.OnCookieRcvd(Sender: TObject; const Data: String; var Accept: Boolean); var Cookies: TStrings; Cookie, Name, Value: string; begin Cookies := TStringList.Create; try StrToStrings(FHttpsCli.Cookie, '; ', Cookies); Cookie := StrBefore(';',Data); Name := StrBefore('=', Cookie); Value := StrAfter('=', Cookie); Cookies.Values[Name] := Value; FHttpsCli.Cookie := StringsToStr(Cookies,'; ', False); finally Cookies.Free; end; Accept := True; end; procedure TMediaWikiApi.CheckRequest(Request: TMediaWikiRequest); begin // check socket ready state, done by httpcli if FPendingRequests * MediaWikiExclusiveRequests <> [] then raise EMediaWikiError.Create('execute exclusive request first', ''); Include(FPendingRequests, Request); end; function TMediaWikiApi.GetReady: Boolean; begin Result := HttpsCli.State = httpReady; end; procedure TMediaWikiApi.ProcessXMLError(const AInfo, ACode: string); var Ignore: Boolean; begin Ignore := IgnoreErrors; if Assigned(FOnError) then FOnError(Self, AInfo, ACode, Ignore); if not Ignore then raise EMediaWikiError.Create(AInfo, ACode); end; procedure TMediaWikiApi.ProcessXMLWarning(const AInfo, AQuery: string); var Ignore: Boolean; begin Ignore := IgnoreWarnings; if Assigned(FOnWarning) then FOnWarning(Self, AInfo, AQuery, Ignore); if not Ignore then raise EMediaWikiWarning.Create(AInfo, AQuery); end; function TMediaWikiApi.QueryExecute: AnsiString; var ContentType: string; begin FSendStream.Size := 0; MediaWikiQueryPost(FQueryStrings, FSendStream, ContentType); FHttpsCli.ContentTypePost := ContentType; FSendStream.Position := 0; FReceiveStream.Size := 0; FHttpsCli.Post; FPendingRequests := []; SetLength(Result, FReceiveStream.Size); FReceiveStream.Position := 0; FReceiveStream.ReadBuffer(Result[1], Length(Result)); end; procedure TMediaWikiApi.QueryExecuteAsync; var ContentType: AnsiString; begin FSendStream.Size := 0; MediaWikiQueryPost(FQueryStrings, FSendStream, ContentType); FHttpsCli.ContentTypePost := ContentType; FSendStream.Position := 0; FReceiveStream.Size := 0; FHttpsCli.PostASync; end; procedure TMediaWikiApi.QueryExecuteXML(XML: TJclSimpleXML); var ContentType: string; begin FSendStream.Size := 0; MediaWikiQueryPost(FQueryStrings, FSendStream, ContentType); FHttpsCli.ContentTypePost := ContentType; FSendStream.Position := 0; FReceiveStream.Size := 0; FHttpsCli.Post; FPendingRequests := []; FReceiveStream.Position := 0; try XML.LoadFromStream(FReceiveStream, seUTF8); except FReceiveStream.Position := 0; // FReceiveStream.SaveToFile('c:\dev\receive.xml'); raise; end; MediaWikiCheckXML(XML, ProcessXMLWarning, ProcessXMLError); end; function TMediaWikiApi.Login(const lgName, lgPassword, lgToken: string; OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrLogin); MediaWikiQueryLoginAdd(FQueryStrings, lgName, lgPassword, lgToken, OutputFormat); Result := QueryExecute; end; function TMediaWikiApi.Login: TMediaWikiLoginResult; begin Result := Login(LoginUserName, LoginPassword); end; function TMediaWikiApi.Login(const lgName, lgPassword: string): TMediaWikiLoginResult; var Tokens: TMediaWikiTokenValues; begin QueryTokens([mwtLogin],Tokens); FLoginToken := Tokens[mwtLogin]; Result := Login(lgName, lgPassword, FLoginToken); end; function TMediaWikiApi.Login(const lgName, lgPassword, lgToken: string): TMediaWikiLoginResult; var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; try QueryInit; CheckRequest(mwrLogin); MediaWikiQueryLoginAdd(FQueryStrings, lgName, lgPassword, lgToken, mwoXML); QueryExecuteXml(XML); LoginParseXmlResult(Self, XML); Result := LoginResult; finally XML.Free; end; end; procedure TMediaWikiApi.LoginAsync; begin OnQueryTokenDone := LoginGetToken; FRequestCallbacks[mwrLogin] := LoginParseXmlResult; CheckRequest(mwrLogin); QueryTokensAsync([mwtLogin]); end; procedure TMediaWikiApi.LoginAsync(const lgName, lgPassword: string); begin FLoginUserName := lgName; FLoginPassword := lgPassword; LoginAsync; end; procedure TMediaWikiApi.LoginAsync(const lgName, lgPassword, lgToken: string); begin FRequestCallbacks[mwrLogin] := LoginParseXmlResult; CheckRequest(mwrLogin); MediaWikiQueryLoginAdd(FQueryStrings, lgName, lgPassword, lgToken, mwoXML); end; procedure TMediaWikiApi.LoginGetToken(Sender: TMediaWikiApi; const TokenValues: TMediaWikiTokenValues); begin FLoginToken := TokenValues[mwtLogin]; LoginAsync(FLoginUserName, FLoginPassword, FLoginToken); end; procedure TMediaWikiApi.LoginParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryLoginParseXmlResult(XML, FLoginResult, FLoginUserID, FLoginUserName); if Assigned(FOnLoginDone) then FOnLoginDone(Self); end; procedure TMediaWikiApi.Logout; var TokenValues: TMediaWikiTokenValues; begin QueryTokens([mwtCsrf],TokenValues); Logout(TokenValues[mwtCsrf]); end; procedure TMediaWikiApi.Logout(const csrf: string); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; try QueryInit; CheckRequest(mwrLogout); MediaWikiQueryLogoutAdd(FQueryStrings, csrf, mwoXML); QueryExecuteXML(XML); LogoutParseXmlResult(Self, XML); finally XML.Free; end; end; procedure TMediaWikiApi.LogoutAsync(const csrf: string); begin FRequestCallbacks[mwrLogout] := LogoutParseXmlResult; CheckRequest(mwrLogout); MediaWikiQueryLogoutAdd(FQueryStrings, csrf, mwoXML); end; procedure TMediaWikiApi.LogoutParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryLogoutParseXmlResult(XML); LoginUserID := 0; if Assigned(FOnLogoutDone) then FOnLogoutDone(Self); end; procedure TMediaWikiApi.QueryInit; var Request: TMediaWikiRequest; begin FQueryStrings.Clear; for Request := mwrQuerySiteInfoGeneral to High(TMediaWikiRequest) do FRequestCallbacks[Request] := nil; FPendingRequests := []; end; procedure TMediaWikiApi.QuerySiteInfoGeneral(Infos: TStrings); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQuerySiteInfoGeneralStrings := Infos; try QueryInit; CheckRequest(mwrQuerySiteInfoGeneral); MediaWikiQuerySiteInfoGeneralAdd(FQueryStrings, mwoXML); QueryExecuteXML(XML); QuerySiteInfoGeneralParseXmlResult(Self, XML); finally XML.Free; end; end; function TMediaWikiApi.QuerySiteInfoGeneral( OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQuerySiteInfoGeneral); MediaWikiQuerySiteInfoGeneralAdd(FQueryStrings, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QuerySiteInfoGeneralAsync; begin CheckRequest(mwrQuerySiteInfoGeneral); MediaWikiQuerySiteInfoGeneralAdd(FQueryStrings, mwoXML); FRequestCallbacks[mwrQuerySiteInfoGeneral] := QuerySiteInfoGeneralParseXmlResult; end; procedure TMediaWikiApi.QuerySiteInfoGeneralParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQuerySiteInfoGeneralStrings); if OwnsStrings then FQuerySiteInfoGeneralStrings := TStringList.Create; try MediaWikiQuerySiteInfoGeneralParseXmlResult(XML, FQuerySiteInfoGeneralStrings); if Assigned(FOnQuerySiteInfoGeneralDone) then FOnQuerySiteInfoGeneralDone(Self, FQuerySiteInfoGeneralStrings); finally if OwnsStrings then FreeAndNil(FQuerySiteInfoGeneralStrings) else FQuerySiteInfoGeneralStrings := nil; end; end; procedure TMediaWikiApi.QuerySiteInfoNamespaces(Infos: TStrings); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQuerySiteInfoNamespacesStrings := Infos; try QueryInit; CheckRequest(mwrQuerySiteInfoNamespaces); MediaWikiQuerySiteInfoNamespacesAdd(FQueryStrings, mwoXML); QueryExecuteXML(XML); QuerySiteInfoNamespacesParseXmlResult(Self, XML); finally XML.Free; end; end; function TMediaWikiApi.QuerySiteInfoNamespaces( OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQuerySiteInfoNamespaces); MediaWikiQuerySiteInfoNamespacesAdd(FQueryStrings, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QuerySiteInfoNamespacesAsync; begin CheckRequest(mwrQuerySiteInfoNamespaces); MediaWikiQuerySiteInfoNamespacesAdd(FQueryStrings, mwoXML); FRequestCallbacks[mwrQuerySiteInfoNamespaces] := QuerySiteInfoNamespacesParseXmlResult; end; procedure TMediaWikiApi.QuerySiteInfoNamespacesParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQuerySiteInfoNamespacesStrings); if OwnsStrings then FQuerySiteInfoNamespacesStrings := TStringList.Create; try MediaWikiQuerySiteInfoNamespacesParseXmlResult(XML, FQuerySiteInfoNamespacesStrings); if Assigned(FOnQuerySiteInfoNamespacesDone) then FOnQuerySiteInfoNamespacesDone(Self, FQuerySiteInfoNamespacesStrings); finally if OwnsStrings then FreeAndNil(FQuerySiteInfoNamespacesStrings) else FQuerySiteInfoNamespacesStrings := nil; end; end; procedure TMediaWikiApi.QuerySiteInfoNamespaceAliases(Infos: TStrings); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQuerySiteInfoNamespaceAliasesStrings := Infos; try QueryInit; CheckRequest(mwrQuerySiteInfoNamespaceAliases); MediaWikiQuerySiteInfoNamespaceAliasesAdd(FQueryStrings, mwoXML); QueryExecuteXML(XML); QuerySiteInfoNamespaceAliasesParseXmlResult(Self, XML); finally XML.Free; end; end; function TMediaWikiApi.QuerySiteInfoNamespaceAliases( OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQuerySiteInfoNamespaceAliases); MediaWikiQuerySiteInfoNamespaceAliasesAdd(FQueryStrings, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QuerySiteInfoNamespaceAliasesAsync; begin CheckRequest(mwrQuerySiteInfoNamespaceAliases); MediaWikiQuerySiteInfoNamespaceAliasesAdd(FQueryStrings, mwoXML); FRequestCallbacks[mwrQuerySiteInfoNamespaceAliases] := QuerySiteInfoNamespaceAliasesParseXmlResult; end; procedure TMediaWikiApi.QuerySiteInfoNamespaceAliasesParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQuerySiteInfoNamespaceAliasesStrings); if OwnsStrings then FQuerySiteInfoNamespaceAliasesStrings := TStringList.Create; try MediaWikiQuerySiteInfoNamespaceAliasesParseXmlResult(XML, FQuerySiteInfoNamespaceAliasesStrings); if Assigned(FOnQuerySiteInfoNamespaceAliasesDone) then FOnQuerySiteInfoNamespaceAliasesDone(Self, FQuerySiteInfoNamespaceAliasesStrings); finally if OwnsStrings then FreeAndNil(FQuerySiteInfoNamespaceAliasesStrings) else FQuerySiteInfoNamespaceAliasesStrings := nil; end; end; procedure TMediaWikiApi.QuerySiteInfoSpecialPageAliases(Infos: TStrings); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQuerySiteInfoSpecialPageAliasesStrings := Infos; try QueryInit; CheckRequest(mwrQuerySiteInfoSpecialPageAliases); MediaWikiQuerySiteInfoSpecialPageAliasesAdd(FQueryStrings, mwoXML); QueryExecuteXML(XML); QuerySiteInfoSpecialPageAliasesParseXmlResult(Self, XML); finally XML.Free; end; end; function TMediaWikiApi.QuerySiteInfoSpecialPageAliases( OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQuerySiteInfoSpecialPageAliases); MediaWikiQuerySiteInfoSpecialPageAliasesAdd(FQueryStrings, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QuerySiteInfoSpecialPageAliasesAsync; begin CheckRequest(mwrQuerySiteInfoSpecialPageAliases); MediaWikiQuerySiteInfoSpecialPageAliasesAdd(FQueryStrings, mwoXML); FRequestCallbacks[mwrQuerySiteInfoSpecialPageAliases] := QuerySiteInfoSpecialPageAliasesParseXmlResult; end; procedure TMediaWikiApi.QuerySiteInfoSpecialPageAliasesParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQuerySiteInfoSpecialPageAliasesStrings); if OwnsStrings then FQuerySiteInfoSpecialPageAliasesStrings := TStringList.Create; try MediaWikiQuerySiteInfoSpecialPageAliasesParseXmlResult(XML, FQuerySiteInfoSpecialPageAliasesStrings); if Assigned(FOnQuerySiteInfoSpecialPageAliasesDone) then FOnQuerySiteInfoSpecialPageAliasesDone(Self, FQuerySiteInfoSpecialPageAliasesStrings); finally if OwnsStrings then FreeAndNil(FQuerySiteInfoSpecialPageAliasesStrings) else FQuerySiteInfoSpecialPageAliasesStrings := nil; end; end; procedure TMediaWikiApi.QuerySiteInfoMagicWords(Infos: TStrings); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQuerySiteInfoMagicWordsStrings := Infos; try QueryInit; CheckRequest(mwrQuerySiteInfoMagicWords); MediaWikiQuerySiteInfoMagicWordsAdd(FQueryStrings, mwoXML); QueryExecuteXML(XML); QuerySiteInfoMagicWordsParseXmlResult(Self, XML); finally XML.Free; end; end; function TMediaWikiApi.QuerySiteInfoMagicWords( OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQuerySiteInfoMagicWords); MediaWikiQuerySiteInfoMagicWordsAdd(FQueryStrings, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QuerySiteInfoMagicWordsAsync; begin CheckRequest(mwrQuerySiteInfoMagicWords); MediaWikiQuerySiteInfoMagicWordsAdd(FQueryStrings, mwoXML); FRequestCallbacks[mwrQuerySiteInfoMagicWords] := QuerySiteInfoMagicWordsParseXmlResult; end; procedure TMediaWikiApi.QuerySiteInfoMagicWordsParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQuerySiteInfoMagicWordsStrings); if OwnsStrings then FQuerySiteInfoMagicWordsStrings := TStringList.Create; try MediaWikiQuerySiteInfoMagicWordsParseXmlResult(XML, FQuerySiteInfoMagicWordsStrings); if Assigned(FOnQuerySiteInfoMagicWordsDone) then FOnQuerySiteInfoMagicWordsDone(Self, FQuerySiteInfoMagicWordsStrings); finally if OwnsStrings then FreeAndNil(FQuerySiteInfoMagicWordsStrings) else FQuerySiteInfoMagicWordsStrings := nil; end; end; procedure TMediaWikiApi.QuerySiteInfoStatistics(Infos: TStrings); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQuerySiteInfoStatisticsStrings := Infos; try QueryInit; CheckRequest(mwrQuerySiteInfoStatistics); MediaWikiQuerySiteInfoStatisticsAdd(FQueryStrings, mwoXML); QueryExecuteXML(XML); QuerySiteInfoStatisticsParseXmlResult(Self, XML); finally XML.Free; end; end; function TMediaWikiApi.QuerySiteInfoStatistics( OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQuerySiteInfoStatistics); MediaWikiQuerySiteInfoStatisticsAdd(FQueryStrings, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QuerySiteInfoStatisticsAsync; begin CheckRequest(mwrQuerySiteInfoStatistics); MediaWikiQuerySiteInfoStatisticsAdd(FQueryStrings, mwoXML); FRequestCallbacks[mwrQuerySiteInfoStatistics] := QuerySiteInfoStatisticsParseXmlResult; end; procedure TMediaWikiApi.QuerySiteInfoStatisticsParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQuerySiteInfoStatisticsStrings); if OwnsStrings then FQuerySiteInfoStatisticsStrings := TStringList.Create; try MediaWikiQuerySiteInfoStatisticsParseXmlResult(XML, FQuerySiteInfoStatisticsStrings); if Assigned(FOnQuerySiteInfoStatisticsDone) then FOnQuerySiteInfoStatisticsDone(Self, FQuerySiteInfoStatisticsStrings); finally if OwnsStrings then FreeAndNil(FQuerySiteInfoStatisticsStrings) else FQuerySiteInfoStatisticsStrings := nil; end; end; procedure TMediaWikiApi.QuerySiteInfoInterWikiMap(Local: Boolean; Infos: TStrings); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQuerySiteInfoInterWikiMapStrings := Infos; try QueryInit; CheckRequest(mwrQuerySiteInfoInterWikiMap); MediaWikiQuerySiteInfoInterWikiMapAdd(FQueryStrings, Local, mwoXML); QueryExecuteXML(XML); QuerySiteInfoInterWikiMapParseXmlResult(Self, XML); finally XML.Free; end; end; function TMediaWikiApi.QuerySiteInfoInterWikiMap(Local: Boolean; OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQuerySiteInfoInterWikiMap); MediaWikiQuerySiteInfoInterWikiMapAdd(FQueryStrings, Local, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QuerySiteInfoInterWikiMapAsync(Local: Boolean); begin CheckRequest(mwrQuerySiteInfoInterWikiMap); MediaWikiQuerySiteInfoInterWikiMapAdd(FQueryStrings, Local, mwoXML); FRequestCallbacks[mwrQuerySiteInfoInterWikiMap] := QuerySiteInfoInterWikiMapParseXmlResult; end; procedure TMediaWikiApi.QuerySiteInfoInterWikiMapParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQuerySiteInfoInterWikiMapStrings); if OwnsStrings then FQuerySiteInfoInterWikiMapStrings := TStringList.Create; try MediaWikiQuerySiteInfoInterWikiMapParseXmlResult(XML, FQuerySiteInfoInterWikiMapStrings); if Assigned(FOnQuerySiteInfoInterWikiMapDone) then FOnQuerySiteInfoInterWikiMapDone(Self, FQuerySiteInfoInterWikiMapStrings); finally if OwnsStrings then FreeAndNil(FQuerySiteInfoInterWikiMapStrings) else FQuerySiteInfoInterWikiMapStrings := nil; end; end; procedure TMediaWikiApi.QuerySiteInfoDBReplLag(ShowAllDB: Boolean; Infos: TStrings); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQuerySiteInfoDBReplLagStrings := Infos; try QueryInit; CheckRequest(mwrQuerySiteInfoDBReplLag); MediaWikiQuerySiteInfoDBReplLagAdd(FQueryStrings, ShowAllDB, mwoXML); QueryExecuteXML(XML); QuerySiteInfoDBReplLagParseXmlResult(Self, XML); finally XML.Free; end; end; function TMediaWikiApi.QuerySiteInfoDBReplLag(ShowAllDB: Boolean; OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQuerySiteInfoDBReplLag); MediaWikiQuerySiteInfoDBReplLagAdd(FQueryStrings, ShowAllDB, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QuerySiteInfoDBReplLagAsync(ShowAllDB: Boolean); begin CheckRequest(mwrQuerySiteInfoDBReplLag); MediaWikiQuerySiteInfoDBReplLagAdd(FQueryStrings, ShowAllDB, mwoXML); FRequestCallbacks[mwrQuerySiteInfoDBReplLag] := QuerySiteInfoDBReplLagParseXmlResult; end; procedure TMediaWikiApi.QuerySiteInfoDBReplLagParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQuerySiteInfoDBReplLagStrings); if OwnsStrings then FQuerySiteInfoDBReplLagStrings := TStringList.Create; try MediaWikiQuerySiteInfoDBReplLagParseXmlResult(XML, FQuerySiteInfoDBReplLagStrings); if Assigned(FOnQuerySiteInfoDBReplLagDone) then FOnQuerySiteInfoDBReplLagDone(Self, FQuerySiteInfoDBReplLagStrings); finally if OwnsStrings then FreeAndNil(FQuerySiteInfoDBReplLagStrings) else FQuerySiteInfoDBReplLagStrings := nil; end; end; procedure TMediaWikiApi.QuerySiteInfoUserGroups(IncludeUserCount: Boolean; Infos: TStrings); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQuerySiteInfoUserGroupsStrings := Infos; try QueryInit; CheckRequest(mwrQuerySiteInfoUserGroups); MediaWikiQuerySiteInfoUserGroupsAdd(FQueryStrings, IncludeUserCount, mwoXML); QueryExecuteXML(XML); QuerySiteInfoUserGroupsParseXmlResult(Self, XML); finally XML.Free; end; end; function TMediaWikiApi.QuerySiteInfoUserGroups(IncludeUserCount: Boolean; OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQuerySiteInfoUserGroups); MediaWikiQuerySiteInfoUserGroupsAdd(FQueryStrings, IncludeUserCount, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QuerySiteInfoUserGroupsAsync(IncludeUserCount: Boolean); begin CheckRequest(mwrQuerySiteInfoUserGroups); MediaWikiQuerySiteInfoUserGroupsAdd(FQueryStrings, IncludeUserCount, mwoXML); FRequestCallbacks[mwrQuerySiteInfoUserGroups] := QuerySiteInfoUserGroupsParseXmlResult; end; procedure TMediaWikiApi.QuerySiteInfoUserGroupsParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQuerySiteInfoUserGroupsStrings); if OwnsStrings then FQuerySiteInfoUserGroupsStrings := TStringList.Create; try MediaWikiQuerySiteInfoUserGroupsParseXmlResult(XML, FQuerySiteInfoUserGroupsStrings); if Assigned(FOnQuerySiteInfoUserGroupsDone) then FOnQuerySiteInfoUserGroupsDone(Self, FQuerySiteInfoUserGroupsStrings); finally if OwnsStrings then FreeAndNil(FQuerySiteInfoUserGroupsStrings) else FQuerySiteInfoUserGroupsStrings := nil; end; end; procedure TMediaWikiApi.QuerySiteInfoExtensions(out Infos: TMediaWikiExtensions); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; SetLength(FQuerySiteInfoExtensions, 0); try QueryInit; CheckRequest(mwrQuerySiteInfoExtensions); MediaWikiQuerySiteInfoExtensionsAdd(FQueryStrings, mwoXML); QueryExecuteXML(XML); QuerySiteInfoExtensionsParseXmlResult(Self, XML); finally Infos := FQuerySiteInfoExtensions; FQuerySiteInfoExtensions := nil; XML.Free; end; end; function TMediaWikiApi.QuerySiteInfoExtensions( OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQuerySiteInfoExtensions); MediaWikiQuerySiteInfoExtensionsAdd(FQueryStrings, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QuerySiteInfoExtensionsAsync; begin CheckRequest(mwrQuerySiteInfoExtensions); MediaWikiQuerySiteInfoExtensionsAdd(FQueryStrings, mwoXML); FRequestCallbacks[mwrQuerySiteInfoExtensions] := QuerySiteInfoExtensionsParseXmlResult; end; procedure TMediaWikiApi.QuerySiteInfoExtensionsParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQuerySiteInfoExtensionsParseXmlResult(XML, FQuerySiteInfoExtensions); if Assigned(FOnQuerySiteInfoExtensionsDone) then FOnQuerySiteInfoExtensionsDone(Self, FQuerySiteInfoExtensions); end; procedure TMediaWikiApi.QueryTokensParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryTokensParseXmlResult(XML, FQueryTokenValues); if Assigned(FOnQueryTokensDone) then FOnQueryTokensDone(Self, FQueryTokenValues); end; procedure TMediaWikiApi.QueryTokens(Tokens: TMediaWikiTokens; out TokenValues: TMediaWikiTokenValues); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; try QueryInit; CheckRequest(mwrQueryTokens); MediaWikiQueryTokensAdd(FQueryStrings, Tokens, mwoXML); QueryExecuteXML(XML); QueryTokensParseXmlResult(Self, XML); TokenValues := FQueryTokenValues; finally XML.Free; end; end; function TMediaWikiApi.QueryTokens(Tokens: TMediaWikiTokens; OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQueryTokens); MediaWikiQueryTokensAdd(FQueryStrings, Tokens, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryTokensAsync(Tokens: TMediaWikiTokens); begin CheckRequest(mwrQueryTokens); MediaWikiQueryTokensAdd(FQueryStrings, Tokens, mwoXML); FRequestCallbacks[mwrQueryTokens] := QueryTokensParseXmlResult; end; procedure TMediaWikiApi.QueryUserInfoBlockInfo(Infos: TStrings); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQueryUserInfoBlockInfoStrings := Infos; try QueryInit; CheckRequest(mwrQueryUserInfoBlockInfo); MediaWikiQueryUserInfoBlockInfoAdd(FQueryStrings, mwoXML); QueryExecuteXML(XML); QueryUserInfoBlockInfoParseXmlResult(Self, XML); finally XML.Free; end; end; function TMediaWikiApi.QueryUserInfoBlockInfo( OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQueryUserInfoBlockInfo); MediaWikiQueryUserInfoBlockInfoAdd(FQueryStrings, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryUserInfoBlockInfoAsync; begin CheckRequest(mwrQueryUserInfoBlockInfo); MediaWikiQueryUserInfoBlockInfoAdd(FQueryStrings, mwoXML); FRequestCallbacks[mwrQueryUserInfoBlockInfo] := QueryUserInfoBlockInfoParseXmlResult; end; procedure TMediaWikiApi.QueryUserInfoBlockInfoParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQueryUserInfoBlockInfoStrings); if OwnsStrings then FQueryUserInfoBlockInfoStrings := TStringList.Create; try MediaWikiQueryUserInfoBlockInfoParseXmlResult(XML, FQueryUserInfoBlockInfoStrings); if Assigned(FOnQueryUserInfoBlockInfoDone) then FOnQueryUserInfoBlockInfoDone(Self, FQueryUserInfoBlockInfoStrings); finally if OwnsStrings then FreeAndNil(FQueryUserInfoBlockInfoStrings) else FQueryUserInfoBlockInfoStrings := nil; end; end; function TMediaWikiApi.QueryUserInfoHasMsg: Boolean; var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; try QueryInit; CheckRequest(mwrQueryUserInfoHasMsg); MediaWikiQueryUserInfoHasMsgAdd(FQueryStrings, mwoXML); QueryExecuteXML(XML); QueryUserInfoHasMsgParseXmlResult(Self, XML); finally Result := FQueryUserInfoHasMsg; FQueryUserInfoHasMsg := False; XML.Free; end; end; function TMediaWikiApi.QueryUserInfoHasMsg( OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQueryUserInfoHasMsg); MediaWikiQueryUserInfoHasMsgAdd(FQueryStrings, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryUserInfoHasMsgAsync; begin CheckRequest(mwrQueryUserInfoHasMsg); MediaWikiQueryUserInfoHasMsgAdd(FQueryStrings, mwoXML); FRequestCallbacks[mwrQueryUserInfoHasMsg] := QueryUserInfoHasMsgParseXmlResult; end; procedure TMediaWikiApi.QueryUserInfoHasMsgParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryUserInfoHasMsgParseXmlResult(XML, FQueryUserInfoHasMsg); if Assigned(FOnQueryUserInfoHasMsgDone) then FOnQueryUserInfoHasMsgDone(Self, FQueryUserInfoHasMsg); end; procedure TMediaWikiApi.QueryUserInfoGroups(Infos: TStrings); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQueryUserInfoGroupsStrings := Infos; try QueryInit; CheckRequest(mwrQueryUserInfoGroups); MediaWikiQueryUserInfoGroupsAdd(FQueryStrings, mwoXML); QueryExecuteXML(XML); QueryUserInfoGroupsParseXmlResult(Self, XML); finally XML.Free; end; end; function TMediaWikiApi.QueryUserInfoGroups( OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQueryUserInfoGroups); MediaWikiQueryUserInfoGroupsAdd(FQueryStrings, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryUserInfoGroupsAsync; begin CheckRequest(mwrQueryUserInfoGroups); MediaWikiQueryUserInfoGroupsAdd(FQueryStrings, mwoXML); FRequestCallbacks[mwrQueryUserInfoGroups] := QueryUserInfoGroupsParseXmlResult; end; procedure TMediaWikiApi.QueryUserInfoGroupsParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQueryUserInfoGroupsStrings); if OwnsStrings then FQueryUserInfoGroupsStrings := TStringList.Create; try MediaWikiQueryUserInfoGroupsParseXmlResult(XML, FQueryUserInfoGroupsStrings); if Assigned(FOnQueryUserInfoGroupsDone) then FOnQueryUserInfoGroupsDone(Self, FQueryUserInfoGroupsStrings); finally if OwnsStrings then FreeAndNil(FQueryUserInfoGroupsStrings) else FQueryUserInfoGroupsStrings := nil; end; end; procedure TMediaWikiApi.QueryUserInfoRights(Infos: TStrings); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQueryUserInfoRightsStrings := Infos; try QueryInit; CheckRequest(mwrQueryUserInfoRights); MediaWikiQueryUserInfoRightsAdd(FQueryStrings, mwoXML); QueryExecuteXML(XML); QueryUserInfoRightsParseXmlResult(Self, XML); finally XML.Free; end; end; function TMediaWikiApi.QueryUserInfoRights( OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQueryUserInfoRights); MediaWikiQueryUserInfoRightsAdd(FQueryStrings, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryUserInfoRightsAsync; begin CheckRequest(mwrQueryUserInfoRights); MediaWikiQueryUserInfoRightsAdd(FQueryStrings, mwoXML); FRequestCallbacks[mwrQueryUserInfoRights] := QueryUserInfoRightsParseXmlResult; end; procedure TMediaWikiApi.QueryUserInfoRightsParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQueryUserInfoRightsStrings); if OwnsStrings then FQueryUserInfoRightsStrings := TStringList.Create; try MediaWikiQueryUserInfoRightsParseXmlResult(XML, FQueryUserInfoRightsStrings); if Assigned(FOnQueryUserInfoRightsDone) then FOnQueryUserInfoRightsDone(Self, FQueryUserInfoRightsStrings); finally if OwnsStrings then FreeAndNil(FQueryUserInfoRightsStrings) else FQueryUserInfoRightsStrings := nil; end; end; procedure TMediaWikiApi.QueryUserInfoChangeableGroups(Infos: TStrings); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQueryUserInfoChangeableGroupsStrings := Infos; try QueryInit; CheckRequest(mwrQueryUserInfoChangeableGroups); MediaWikiQueryUserInfoChangeableGroupsAdd(FQueryStrings, mwoXML); QueryExecuteXML(XML); QueryUserInfoChangeableGroupsParseXmlResult(Self, XML); finally XML.Free; end; end; function TMediaWikiApi.QueryUserInfoChangeableGroups( OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQueryUserInfoChangeableGroups); MediaWikiQueryUserInfoChangeableGroupsAdd(FQueryStrings, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryUserInfoChangeableGroupsAsync; begin CheckRequest(mwrQueryUserInfoChangeableGroups); MediaWikiQueryUserInfoChangeableGroupsAdd(FQueryStrings, mwoXML); FRequestCallbacks[mwrQueryUserInfoChangeableGroups] := QueryUserInfoChangeableGroupsParseXmlResult; end; procedure TMediaWikiApi.QueryUserInfoChangeableGroupsParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQueryUserInfoChangeableGroupsStrings); if OwnsStrings then FQueryUserInfoChangeableGroupsStrings := TStringList.Create; try MediaWikiQueryUserInfoChangeableGroupsParseXmlResult(XML, FQueryUserInfoChangeableGroupsStrings); if Assigned(FOnQueryUserInfoChangeableGroupsDone) then FOnQueryUserInfoChangeableGroupsDone(Self, FQueryUserInfoChangeableGroupsStrings); finally if OwnsStrings then FreeAndNil(FQueryUserInfoChangeableGroupsStrings) else FQueryUserInfoChangeableGroupsStrings := nil; end; end; procedure TMediaWikiApi.QueryUserInfoOptions(Infos: TStrings); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQueryUserInfoOptionsStrings := Infos; try QueryInit; CheckRequest(mwrQueryUserInfoOptions); MediaWikiQueryUserInfoOptionsAdd(FQueryStrings, mwoXML); QueryExecuteXML(XML); QueryUserInfoOptionsParseXmlResult(Self, XML); finally XML.Free; end; end; function TMediaWikiApi.QueryUserInfoOptions( OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQueryUserInfoOptions); MediaWikiQueryUserInfoOptionsAdd(FQueryStrings, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryUserInfoOptionsAsync; begin CheckRequest(mwrQueryUserInfoOptions); MediaWikiQueryUserInfoOptionsAdd(FQueryStrings, mwoXML); FRequestCallbacks[mwrQueryUserInfoOptions] := QueryUserInfoOptionsParseXmlResult; end; procedure TMediaWikiApi.QueryUserInfoOptionsParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQueryUserInfoOptionsStrings); if OwnsStrings then FQueryUserInfoOptionsStrings := TStringList.Create; try MediaWikiQueryUserInfoOptionsParseXmlResult(XML, FQueryUserInfoOptionsStrings); if Assigned(FOnQueryUserInfoOptionsDone) then FOnQueryUserInfoOptionsDone(Self, FQueryUserInfoOptionsStrings); finally if OwnsStrings then FreeAndNil(FQueryUserInfoOptionsStrings) else FQueryUserInfoOptionsStrings := nil; end; end; function TMediaWikiApi.QueryUserInfoEditCount: Integer; var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; try QueryInit; CheckRequest(mwrQueryUserInfoEditCount); MediaWikiQueryUserInfoEditCountAdd(FQueryStrings, mwoXML); QueryExecuteXML(XML); QueryUserInfoEditCountParseXmlResult(Self, XML); finally Result := FQueryUserInfoEditCount; FQueryUserInfoEditCount := 0; XML.Free; end; end; function TMediaWikiApi.QueryUserInfoEditCount( OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQueryUserInfoEditCount); MediaWikiQueryUserInfoEditCountAdd(FQueryStrings, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryUserInfoEditCountAsync; begin CheckRequest(mwrQueryUserInfoEditCount); MediaWikiQueryUserInfoEditCountAdd(FQueryStrings, mwoXML); FRequestCallbacks[mwrQueryUserInfoEditCount] := QueryUserInfoEditCountParseXmlResult; end; procedure TMediaWikiApi.QueryUserInfoEditCountParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryUserInfoEditCountParseXmlResult(XML, FQueryUserInfoEditCount); if Assigned(FOnQueryUserInfoEditCountDone) then FOnQueryUserInfoEditCountDone(Self, FQueryUserInfoEditCount); end; procedure TMediaWikiApi.QueryUserInfoRateLimits(out Infos: TMediaWikiRateLimits); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; SetLength(FQueryUserInfoRateLimits, 0); try QueryInit; CheckRequest(mwrQueryUserInfoRateLimits); MediaWikiQueryUserInfoRateLimitsAdd(FQueryStrings, mwoXML); QueryExecuteXML(XML); QueryUserInfoRateLimitsParseXmlResult(Self, XML); finally Infos := FQueryUserInfoRateLimits; FQueryUserInfoRateLimits := nil; XML.Free; end; end; function TMediaWikiApi.QueryUserInfoRateLimits( OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQueryUserInfoRateLimits); MediaWikiQueryUserInfoRateLimitsAdd(FQueryStrings, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryUserInfoRateLimitsAsync; begin CheckRequest(mwrQueryUserInfoRateLimits); MediaWikiQueryUserInfoRateLimitsAdd(FQueryStrings, mwoXML); FRequestCallbacks[mwrQueryUserInfoRateLimits] := QueryUserInfoRateLimitsParseXmlResult; end; procedure TMediaWikiApi.QueryUserInfoRateLimitsParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryUserInfoRateLimitsParseXmlResult(XML, FQueryUserInfoRateLimits); if Assigned(FOnQueryUserInfoRateLimitsDone) then FOnQueryUserInfoRateLimitsDone(Self, FQueryUserInfoRateLimits); end; procedure TMediaWikiApi.QueryMessages(const NameFilter, ContentFilter, Lang: string; Infos: TStrings); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQueryMessagesStrings := Infos; try QueryInit; CheckRequest(mwrQueryMessages); MediaWikiQueryMessagesAdd(FQueryStrings, NameFilter, ContentFilter, Lang, mwoXML); QueryExecuteXML(XML); QueryMessagesParseXmlResult(Self, XML); finally XML.Free; end; end; function TMediaWikiApi.QueryMessages(const NameFilter, ContentFilter, Lang: string; OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQueryMessages); MediaWikiQueryMessagesAdd(FQueryStrings, NameFilter, ContentFilter, Lang, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryMessagesAsync(const NameFilter, ContentFilter, Lang: string); begin CheckRequest(mwrQueryMessages); MediaWikiQueryMessagesAdd(FQueryStrings, NameFilter, ContentFilter, Lang, mwoXML); FRequestCallbacks[mwrQueryMessages] := QueryMessagesParseXmlResult; end; procedure TMediaWikiApi.QueryMessagesParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQueryMessagesStrings); if OwnsStrings then FQueryMessagesStrings := TStringList.Create; try MediaWikiQueryMessagesParseXmlResult(XML, FQueryMessagesStrings); if Assigned(FOnQueryMessagesDone) then FOnQueryMessagesDone(Self, FQueryMessagesStrings); finally if OwnsStrings then FreeAndNil(FQueryMessagesStrings) else FQueryMessagesStrings := nil; end; end; procedure TMediaWikiApi.QueryPageInfo(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageInfoFlags; out Infos: TMediaWikiPageInfos); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; SetLength(FQueryPageInfos, 0); try QueryInit; CheckRequest(mwrQueryPageInfo); MediaWikiQueryPageInfoAdd(FQueryStrings, Titles, PageID, Flags, mwoXML); QueryExecuteXML(XML); QueryPageInfoParseXmlResult(Self, XML); finally Infos := FQueryPageInfos; FQueryPageInfos := nil; XML.Free; end; end; function TMediaWikiApi.QueryPageInfo(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageInfoFlags; OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrQueryPageInfo); MediaWikiQueryPageInfoAdd(FQueryStrings, Titles, PageID, Flags, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryPageInfoAsync(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageInfoFlags); begin CheckRequest(mwrQueryPageInfo); MediaWikiQueryPageInfoAdd(FQueryStrings, Titles, PageID, Flags, mwoXML); FRequestCallbacks[mwrQueryPageInfo] := QueryPageInfoParseXmlResult; end; procedure TMediaWikiApi.QueryPageInfoParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryPageInfoParseXmlResult(XML, FQueryPageInfos); if Assigned(FOnQueryPageInfoDone) then FOnQueryPageInfoDone(Self, FQueryPageInfos); end; procedure TMediaWikiApi.QueryPageRevisionInfo(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageRevisionInfoFlags; out Infos: TMediaWikiPageRevisionInfos; var ContinueInfo: TMediaWikiContinueInfo; MaxRevisions, Section: Integer; StartRevisionID, EndRevisionID: TMediaWikiID; const StartDateTime, EndDateTime: TDateTime; const IncludeUser, ExcludeUser: string); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; SetLength(FQueryPageRevisionInfos, 0); try QueryInit; CheckRequest(mwrQueryPageRevisionInfo); MediaWikiQueryPageRevisionInfoAdd(FQueryStrings, Titles, PageID, Flags, ContinueInfo, MaxRevisions, Section, StartRevisionID, EndRevisionID, StartDateTime, EndDateTime, IncludeUser, ExcludeUser, mwoXML); QueryExecuteXML(XML); QueryPageRevisionInfoParseXmlResult(Self, XML); finally Infos := FQueryPageRevisionInfos; ContinueInfo := FQueryPageRevisionContinueInfo; FQueryPageRevisionInfos := nil; XML.Free; end; end; function TMediaWikiApi.QueryPageRevisionInfo(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageRevisionInfoFlags; OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; MaxRevisions, Section: Integer; StartRevisionID, EndRevisionID: TMediaWikiID; const StartDateTime, EndDateTime: TDateTime; const IncludeUser, ExcludeUser: string): AnsiString; begin QueryInit; CheckRequest(mwrQueryPageRevisionInfo); MediaWikiQueryPageRevisionInfoAdd(FQueryStrings, Titles, PageID, Flags, ContinueInfo, MaxRevisions, Section, StartRevisionID, EndRevisionID, StartDateTime, EndDateTime, IncludeUser, ExcludeUser, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryPageRevisionInfoAsync(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageRevisionInfoFlags; const ContinueInfo: TMediaWikiContinueInfo; MaxRevisions, Section: Integer; StartRevisionID, EndRevisionID: TMediaWikiID; const StartDateTime, EndDateTime: TDateTime; const IncludeUser, ExcludeUser: string); begin CheckRequest(mwrQueryPageRevisionInfo); MediaWikiQueryPageRevisionInfoAdd(FQueryStrings, Titles, PageID, Flags, ContinueInfo, MaxRevisions, Section, StartRevisionID, EndRevisionID, StartDateTime, EndDateTime, IncludeUser, ExcludeUser, mwoXML); FRequestCallbacks[mwrQueryPageRevisionInfo] := QueryPageRevisionInfoParseXmlResult; end; procedure TMediaWikiApi.QueryPageRevisionInfoParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryPageRevisionInfoParseXmlResult(XML, FQueryPageRevisionInfos, FQueryPageRevisionContinueInfo); if Assigned(FOnQueryPageRevisionInfoDone) then FOnQueryPageRevisionInfoDone(Self, FQueryPageRevisionInfos, FQueryPageRevisionContinueInfo); end; procedure TMediaWikiApi.QueryPageCategoryInfo(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageCategoryInfoFlags; out Infos: TMediaWikiPageCategoryInfos; var ContinueInfo: TMediaWikiContinueInfo; MaxCategories: Integer; const CategoryTitles: string); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; SetLength(FQueryPageCategoryInfos, 0); try QueryInit; CheckRequest(mwrQueryPageCategoryInfo); MediaWikiQueryPageCategoryInfoAdd(FQueryStrings, Titles, PageID, Flags, ContinueInfo, MaxCategories, CategoryTitles, mwoXML); QueryExecuteXML(XML); QueryPageCategoryInfoParseXmlResult(Self, XML); finally Infos := FQueryPageCategoryInfos; ContinueInfo := FQueryPageCategoryContinueInfo; FQueryPageCategoryInfos := nil; XML.Free; end; end; function TMediaWikiApi.QueryPageCategoryInfo(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageCategoryInfoFlags; OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; MaxCategories: Integer; const CategoryTitles: string): AnsiString; begin QueryInit; CheckRequest(mwrQueryPageCategoryInfo); MediaWikiQueryPageCategoryInfoAdd(FQueryStrings, Titles, PageID, Flags, ContinueInfo, MaxCategories, CategoryTitles, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryPageCategoryInfoAsync(const Titles: string; PageID: Boolean; Flags: TMediaWikiPageCategoryInfoFlags; const ContinueInfo: TMediaWikiContinueInfo; MaxCategories: Integer; const CategoryTitles: string); begin CheckRequest(mwrQueryPageCategoryInfo); MediaWikiQueryPageCategoryInfoAdd(FQueryStrings, Titles, PageID, Flags, ContinueInfo, MaxCategories, CategoryTitles, mwoXML); FRequestCallbacks[mwrQueryPageCategoryInfo] := QueryPageCategoryInfoParseXmlResult; end; procedure TMediaWikiApi.QueryPageCategoryInfoParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryPageCategoryInfoParseXmlResult(XML, FQueryPageCategoryInfos, FQueryPageCategoryContinueInfo); if Assigned(FOnQueryPageCategoryInfoDone) then FOnQueryPageCategoryInfoDone(Self, FQueryPageCategoryInfos, FQueryPageCategoryContinueInfo); end; procedure TMediaWikiApi.QueryPageLinkInfo(const Titles: string; PageID: Boolean; out Infos: TMediaWikiPageLinkInfos; var ContinueInfo: TMediaWikiContinueInfo; MaxLinks, Namespace: Integer); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; SetLength(FQueryPageLinkInfos, 0); try QueryInit; CheckRequest(mwrQueryPageLinkInfo); MediaWikiQueryPageLinkInfoAdd(FQueryStrings, Titles, PageID, ContinueInfo, MaxLinks, Namespace, mwoXML); QueryExecuteXML(XML); QueryPageLinkInfoParseXmlResult(Self, XML); finally Infos := FQueryPageLinkInfos; ContinueInfo := FQueryPageLinkContinueInfo; FQueryPageLinkInfos := nil; XML.Free; end; end; function TMediaWikiApi.QueryPageLinkInfo(const Titles: string; PageID: Boolean; OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; MaxLinks, Namespace: Integer): AnsiString; begin QueryInit; CheckRequest(mwrQueryPageLinkInfo); MediaWikiQueryPageLinkInfoAdd(FQueryStrings, Titles, PageID, ContinueInfo, MaxLinks, NameSpace, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryPageLinkInfoAsync(const Titles: string; PageID: Boolean; const ContinueInfo: TMediaWikiContinueInfo; MaxLinks, Namespace: Integer); begin CheckRequest(mwrQueryPageLinkInfo); MediaWikiQueryPageLinkInfoAdd(FQueryStrings, Titles, PageID, ContinueInfo, MaxLinks, Namespace, mwoXML); FRequestCallbacks[mwrQueryPageLinkInfo] := QueryPageLinkInfoParseXmlResult; end; procedure TMediaWikiApi.QueryPageLinkInfoParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryPageLinkInfoParseXmlResult(XML, FQueryPageLinkInfos, FQueryPageLinkContinueInfo); if Assigned(FOnQueryPageLinkInfoDone) then FOnQueryPageLinkInfoDone(Self, FQueryPageLinkInfos, FQueryPageLinkContinueInfo); end; procedure TMediaWikiApi.QueryPageTemplateInfo(const Titles: string; PageID: Boolean; out Infos: TMediaWikiPageTemplateInfos; var ContinueInfo: TMediaWikiContinueInfo; MaxTemplates, Namespace: Integer); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; SetLength(FQueryPageTemplateInfos, 0); try QueryInit; CheckRequest(mwrQueryPageTemplateInfo); MediaWikiQueryPageTemplateInfoAdd(FQueryStrings, Titles, PageID, ContinueInfo, MaxTemplates, Namespace, mwoXML); QueryExecuteXML(XML); QueryPageTemplateInfoParseXmlResult(Self, XML); finally Infos := FQueryPageTemplateInfos; ContinueInfo := FQueryPageTemplateContinueInfo; FQueryPageTemplateInfos := nil; XML.Free; end; end; function TMediaWikiApi.QueryPageTemplateInfo(const Titles: string; PageID: Boolean; OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; MaxTemplates, Namespace: Integer): AnsiString; begin QueryInit; CheckRequest(mwrQueryPageTemplateInfo); MediaWikiQueryPageTemplateInfoAdd(FQueryStrings, Titles, PageID, ContinueInfo, MaxTemplates, Namespace, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryPageTemplateInfoAsync(const Titles: string; PageID: Boolean; const ContinueInfo: TMediaWikiContinueInfo; MaxTemplates, Namespace: Integer); begin CheckRequest(mwrQueryPageTemplateInfo); MediaWikiQueryPageTemplateInfoAdd(FQueryStrings, Titles, PageID, ContinueInfo, MaxTemplates, Namespace, mwoXML); FRequestCallbacks[mwrQueryPageTemplateInfo] := QueryPageTemplateInfoParseXmlResult; end; procedure TMediaWikiApi.QueryPageTemplateInfoParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryPageTemplateInfoParseXmlResult(XML, FQueryPageTemplateInfos, FQueryPageTemplateContinueInfo); if Assigned(FOnQueryPageTemplateInfoDone) then FOnQueryPageTemplateInfoDone(Self, FQueryPageTemplateInfos, FQueryPageTemplateContinueInfo); end; procedure TMediaWikiApi.QueryPageExtLinkInfo(const Titles: string; PageID: Boolean; out Infos: TMediaWikiPageExtLinkInfos; var ContinueInfo: TMediaWikiContinueInfo; MaxLinks: Integer); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; SetLength(FQueryPageExtLinkInfos, 0); try QueryInit; CheckRequest(mwrQueryPageExtLinkInfo); MediaWikiQueryPageExtLinkInfoAdd(FQueryStrings, Titles, PageID, ContinueInfo, MaxLinks, mwoXML); QueryExecuteXML(XML); QueryPageExtLinkInfoParseXmlResult(Self, XML); finally Infos := FQueryPageExtLinkInfos; ContinueInfo := FQueryPageExtLinkContinueInfo; FQueryPageExtLinkInfos := nil; XML.Free; end; end; function TMediaWikiApi.QueryPageExtLinkInfo(const Titles: string; PageID: Boolean; OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; MaxLinks: Integer): AnsiString; begin QueryInit; CheckRequest(mwrQueryPageExtLinkInfo); MediaWikiQueryPageExtLinkInfoAdd(FQueryStrings, Titles, PageID, ContinueInfo, MaxLinks, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryPageExtLinkInfoAsync(const Titles: string; PageID: Boolean; const ContinueInfo: TMediaWikiContinueInfo; MaxLinks: Integer); begin CheckRequest(mwrQueryPageExtLinkInfo); MediaWikiQueryPageExtLinkInfoAdd(FQueryStrings, Titles, PageID, ContinueInfo, MaxLinks, mwoXML); FRequestCallbacks[mwrQueryPageExtLinkInfo] := QueryPageExtLinkInfoParseXmlResult; end; procedure TMediaWikiApi.QueryPageExtLinkInfoParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryPageExtLinkInfoParseXmlResult(XML, FQueryPageExtLinkInfos, FQueryPageExtLinkContinueInfo); if Assigned(FOnQueryPageExtLinkInfoDone) then FOnQueryPageExtLinkInfoDone(Self, FQueryPageExtLinkInfos, FQueryPageExtLinkContinueInfo); end; procedure TMediaWikiApi.QueryAllPageInfo(out Infos: TMediaWikiAllPageInfos; var ContinueInfo: TMediaWikiContinueInfo; const Prefix: string; MaxPage, Namespace: Integer; RedirFilter: TMediaWikiAllPageFilterRedir; LangFilter: TMediaWikiAllPageFilterLang; MinSize, MaxSize: Integer; ProtectionFilter: TMediaWikiAllPageFilterProtection; LevelFilter: TMediaWikiAllPageFilterLevel; Direction: TMediaWikiAllPageDirection); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; SetLength(FQueryAllPageInfos, 0); try QueryInit; CheckRequest(mwrQueryAllPageInfo); MediaWikiQueryAllPageAdd(FQueryStrings, ContinueInfo, Prefix, MaxPage, Namespace, RedirFilter, LangFilter, MinSize, MaxSize, ProtectionFilter, LevelFilter, Direction, mwoXML); QueryExecuteXML(XML); QueryAllPageInfoParseXmlResult(Self, XML); finally Infos := FQueryAllPageInfos; ContinueInfo := FQueryAllPageContinueInfo; FQueryAllPageInfos := nil; XML.Free; end; end; function TMediaWikiApi.QueryAllPageInfo(OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string; MaxPage, Namespace: Integer; RedirFilter: TMediaWikiAllPageFilterRedir; LangFilter: TMediaWikiAllPageFilterLang; MinSize, MaxSize: Integer; ProtectionFilter: TMediaWikiAllPageFilterProtection; LevelFilter: TMediaWikiAllPageFilterLevel; Direction: TMediaWikiAllPageDirection): AnsiString; begin QueryInit; CheckRequest(mwrQueryAllPageInfo); MediaWikiQueryAllPageAdd(FQueryStrings, ContinueInfo, Prefix, MaxPage, Namespace, RedirFilter, LangFilter, MinSize, MaxSize, ProtectionFilter, LevelFilter, Direction, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryAllPageInfoAsync(const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string; MaxPage, Namespace: Integer; RedirFilter: TMediaWikiAllPageFilterRedir; LangFilter: TMediaWikiAllPageFilterLang; MinSize, MaxSize: Integer; ProtectionFilter: TMediaWikiAllPageFilterProtection; LevelFilter: TMediaWikiAllPageFilterLevel; Direction: TMediaWikiAllPageDirection); begin CheckRequest(mwrQueryAllPageInfo); MediaWikiQueryAllPageAdd(FQueryStrings, ContinueInfo, Prefix, MaxPage, Namespace, RedirFilter, LangFilter, MinSize, MaxSize, ProtectionFilter, LevelFilter, Direction, mwoXML); FRequestCallbacks[mwrQueryAllPageInfo] := QueryAllPageInfoParseXmlResult; end; procedure TMediaWikiApi.QueryAllPageInfoParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryAllPageParseXmlResult(XML, FQueryAllPageInfos, FQueryAllPageContinueInfo); if Assigned(FOnQueryAllPageInfoDone) then FOnQueryAllPageInfoDone(Self, FQueryAllPageInfos, FQueryAllPageContinueInfo); end; procedure TMediaWikiApi.QueryAllLinkInfo(out Infos: TMediaWikiAllLinkInfos; var ContinueInfo: TMediaWikiContinueInfo; const Prefix: string; MaxLink: Integer; Namespace: Integer; Flags: TMediaWikiAllLinkInfoFlags); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; SetLength(FQueryAllLinkInfos, 0); try QueryInit; CheckRequest(mwrQueryAllLinkInfo); MediaWikiQueryAllLinkAdd(FQueryStrings, ContinueInfo, Prefix, MaxLink, Namespace, Flags, mwoXML); QueryExecuteXML(XML); QueryAllLinkInfoParseXmlResult(Self, XML); finally Infos := FQueryAllLinkInfos; ContinueInfo := FQueryAllLinkContinueInfo; FQueryAllLinkInfos := nil; XML.Free; end; end; function TMediaWikiApi.QueryAllLinkInfo(OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string; MaxLink: Integer; Namespace: Integer; Flags: TMediaWikiAllLinkInfoFlags): AnsiString; begin QueryInit; CheckRequest(mwrQueryAllLinkInfo); MediaWikiQueryAllLinkAdd(FQueryStrings, ContinueInfo, Prefix, MaxLink, Namespace, Flags, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryAllLinkInfoAsync(const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string; MaxLink: Integer; Namespace: Integer; Flags: TMediaWikiAllLinkInfoFlags); begin CheckRequest(mwrQueryAllLinkInfo); MediaWikiQueryAllLinkAdd(FQueryStrings, ContinueInfo, Prefix, MaxLink, Namespace, Flags, mwoXML); FRequestCallbacks[mwrQueryAllLinkInfo] := QueryAllLinkInfoParseXmlResult; end; procedure TMediaWikiApi.QueryAllLinkInfoParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryAllLinkParseXmlResult(XML, FQueryAllLinkInfos, FQueryAllLinkContinueInfo); if Assigned(FOnQueryAllLinkInfoDone) then FOnQueryAllLinkInfoDone(Self, FQueryAllLinkInfos, FQueryAllLinkContinueInfo); end; procedure TMediaWikiApi.QueryAllCategoryInfo(Infos: TStrings; var ContinueInfo: TMediaWikiContinueInfo; const Prefix: string; MaxCategory: Integer; Flags: TMediaWikiAllCategoryInfoFlags); var XML: TJclSimpleXML; begin Infos.Clear; XML := TJclSimpleXML.Create; FQueryAllCategoryInfos := Infos; try QueryInit; CheckRequest(mwrQueryAllCategoryInfo); MediaWikiQueryAllCategoryAdd(FQueryStrings, ContinueInfo, Prefix, MaxCategory, Flags, mwoXML); QueryExecuteXML(XML); QueryAllCategoryInfoParseXmlResult(Self, XML); finally ContinueInfo := FQueryAllCategoryContinueInfo; XML.Free; end; end; function TMediaWikiApi.QueryAllCategoryInfo(OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string; MaxCategory: Integer; Flags: TMediaWikiAllCategoryInfoFlags): AnsiString; begin QueryInit; CheckRequest(mwrQueryAllCategoryInfo); MediaWikiQueryAllCategoryAdd(FQueryStrings, ContinueInfo, Prefix, MaxCategory, Flags, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryAllCategoryInfoAsync(const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string; MaxCategory: Integer; Flags: TMediaWikiAllCategoryInfoFlags); begin CheckRequest(mwrQueryAllCategoryInfo); MediaWikiQueryAllCategoryAdd(FQueryStrings, ContinueInfo, Prefix, MaxCategory, Flags, mwoXML); FRequestCallbacks[mwrQueryAllCategoryInfo] := QueryAllCategoryInfoParseXmlResult; end; procedure TMediaWikiApi.QueryAllCategoryInfoParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); var OwnsStrings: Boolean; begin OwnsStrings := not Assigned(FQueryAllCategoryInfos); if OwnsStrings then FQueryAllCategoryInfos := TStringList.Create; try MediaWikiQueryAllCategoryParseXmlResult(XML, FQueryAllCategoryInfos, FQueryAllCategoryContinueInfo); if Assigned(FOnQueryAllCategoryInfoDone) then FOnQueryAllCategoryInfoDone(Self, FQueryAllCategoryInfos, FQueryAllCategoryContinueInfo); finally if OwnsStrings then FreeAndNil(FQueryAllCategoryInfos) else FQueryAllCategoryInfos := nil; end; end; procedure TMediaWikiApi.QueryAllUserInfo(out Infos: TMediaWikiAllUserInfos; var ContinueInfo: TMediaWikiContinueInfo; const Prefix, Group: string; MaxUser: Integer; Flags: TMediaWikiAllUserInfoFlags); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; SetLength(FQueryAllUserInfos, 0); try QueryInit; CheckRequest(mwrQueryAllUserInfo); MediaWikiQueryAllUserAdd(FQueryStrings, ContinueInfo, Prefix, Group, MaxUser, Flags, mwoXML); QueryExecuteXML(XML); QueryAllUserInfoParseXmlResult(Self, XML); finally Infos := FQueryAllUserInfos; ContinueInfo := FQueryAllUserContinueInfo; FQueryAllUserInfos := nil; XML.Free; end; end; function TMediaWikiApi.QueryAllUserInfo(OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; const Prefix, Group: string; MaxUser: Integer; Flags: TMediaWikiAllUserInfoFlags): AnsiString; begin QueryInit; CheckRequest(mwrQueryAllUserInfo); MediaWikiQueryAllUserAdd(FQueryStrings, ContinueInfo, Prefix, Group, MaxUser, Flags, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryAllUserInfoAsync(const ContinueInfo: TMediaWikiContinueInfo; const Prefix, Group: string; MaxUser: Integer; Flags: TMediaWikiAllUserInfoFlags); begin CheckRequest(mwrQueryAllUserInfo); MediaWikiQueryAllUserAdd(FQueryStrings, ContinueInfo, Prefix, Group, MaxUser, Flags, mwoXML); FRequestCallbacks[mwrQueryAllUserInfo] := QueryAllUserInfoParseXmlResult; end; procedure TMediaWikiApi.QueryAllUserInfoParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryAllUserParseXmlResult(XML, FQueryAllUserInfos, FQueryAllUserContinueInfo); if Assigned(FOnQueryAllUserInfoDone) then FOnQueryAllUserInfoDone(Self, FQueryAllUserInfos, FQueryAllUserContinueInfo); end; procedure TMediaWikiApi.QueryBackLinkInfo(const BackLinkTitle: string; out Infos: TMediaWikiBackLinkInfos; var ContinueInfo: TMediaWikiContinueInfo; Namespace, MaxLink: Integer; Flags: TMediaWikiBackLinkInfoFlags); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; SetLength(FQueryBackLinkInfos, 0); try QueryInit; CheckRequest(mwrQueryBackLinkInfo); MediaWikiQueryBackLinkAdd(FQueryStrings, BackLinkTitle, ContinueInfo, Namespace, MaxLink, Flags, mwoXML); QueryExecuteXML(XML); QueryBackLinkInfoParseXmlResult(Self, XML); finally Infos := FQueryBackLinkInfos; ContinueInfo := FQueryBackLinkContinueInfo; FQueryBackLinkInfos := nil; XML.Free; end; end; function TMediaWikiApi.QueryBackLinkInfo(const BackLinkTitle: string; OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; Namespace, MaxLink: Integer; Flags: TMediaWikiBackLinkInfoFlags): AnsiString; begin QueryInit; CheckRequest(mwrQueryBackLinkInfo); MediaWikiQueryBackLinkAdd(FQueryStrings, BackLinkTitle, ContinueInfo, Namespace, MaxLink, Flags, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryBackLinkInfoAsync(const BackLinkTitle: string; const ContinueInfo: TMediaWikiContinueInfo; Namespace, MaxLink: Integer; Flags: TMediaWikiBackLinkInfoFlags); begin CheckRequest(mwrQueryBackLinkInfo); MediaWikiQueryBackLinkAdd(FQueryStrings, BackLinkTitle, ContinueInfo, Namespace, MaxLink, Flags, mwoXML); FRequestCallbacks[mwrQueryBackLinkInfo] := QueryBackLinkInfoParseXmlResult; end; procedure TMediaWikiApi.QueryBackLinkInfoParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryBackLinkParseXmlResult(XML, FQueryBackLinkInfos, FQueryBackLinkContinueInfo); if Assigned(FOnQueryBackLinkInfoDone) then FOnQueryBackLinkInfoDone(Self, FQueryBackLinkInfos, FQueryBackLinkContinueInfo); end; procedure TMediaWikiApi.QueryBlockInfo(out Infos: TMediaWikiBlockInfos; var ContinueInfo: TMediaWikiContinueInfo; const StartDateTime, StopDateTime: TDateTime; const BlockIDs, Users, IP: string; MaxBlock: Integer; Flags: TMediaWikiBlockInfoFlags); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; SetLength(FQueryBlockInfos, 0); try QueryInit; CheckRequest(mwrQueryBlockInfo); MediaWikiQueryBlockAdd(FQueryStrings, ContinueInfo, StartDateTime, StopDateTime, BlockIDs, Users, IP, MaxBlock, Flags, mwoXML); QueryExecuteXML(XML); QueryBlockInfoParseXmlResult(Self, XML); finally Infos := FQueryBlockInfos; ContinueInfo := FQueryBlockContinueInfo; FQueryBlockInfos := nil; XML.Free; end; end; function TMediaWikiApi.QueryBlockInfo(OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; const StartDateTime, StopDateTime: TDateTime; const BlockIDs, Users, IP: string; MaxBlock: Integer; Flags: TMediaWikiBlockInfoFlags): AnsiString; begin QueryInit; CheckRequest(mwrQueryBlockInfo); MediaWikiQueryBlockAdd(FQueryStrings, ContinueInfo, StartDateTime, StopDateTime, BlockIDs, Users, IP, MaxBlock, Flags, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryBlockInfoAsync(const ContinueInfo: TMediaWikiContinueInfo; const StartDateTime, StopDateTime: TDateTime; const BlockIDs, Users, IP: string; MaxBlock: Integer; Flags: TMediaWikiBlockInfoFlags); begin CheckRequest(mwrQueryBlockInfo); MediaWikiQueryBlockAdd(FQueryStrings, ContinueInfo, StartDateTime, StopDateTime, BlockIDs, Users, IP, MaxBlock, Flags, mwoXML); FRequestCallbacks[mwrQueryBlockInfo] := QueryBlockInfoParseXmlResult; end; procedure TMediaWikiApi.QueryBlockInfoParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryBlockParseXmlResult(XML, FQueryBlockInfos, FQueryBlockContinueInfo); if Assigned(FOnQueryBlockInfoDone) then FOnQueryBlockInfoDone(Self, FQueryBlockInfos, FQueryBlockContinueInfo); end; procedure TMediaWikiApi.QueryCategoryMemberInfo(const CategoryTitle: string; out Infos: TMediaWikiCategoryMemberInfos; var ContinueInfo: TMediaWikiContinueInfo; PageNamespace: Integer; const StartDateTime, StopDateTime: TDateTime; const StartSortKey, StopSortKey: string; MaxCategoryMember: Integer; Flags: TMediaWikiCategoryMemberInfoFlags); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; SetLength(FQueryCategoryMemberInfos, 0); try QueryInit; CheckRequest(mwrQueryCategoryMemberInfo); MediaWikiQueryCategoryMemberAdd(FQueryStrings, CategoryTitle, ContinueInfo, PageNamespace, StartDateTime, StopDateTime, StartSortKey, StopSortKey, MaxCategoryMember, Flags, mwoXML); QueryExecuteXML(XML); QueryCategoryMemberInfoParseXmlResult(Self, XML); finally Infos := FQueryCategoryMemberInfos; ContinueInfo := FQueryCategoryMemberContinueInfo; FQueryCategoryMemberInfos := nil; XML.Free; end; end; function TMediaWikiApi.QueryCategoryMemberInfo(const CategoryTitle: string; OutputFormat: TMediaWikiOutputFormat; const ContinueInfo: TMediaWikiContinueInfo; PageNamespace: Integer; const StartDateTime, StopDateTime: TDateTime; const StartSortKey, StopSortKey: string; MaxCategoryMember: Integer; Flags: TMediaWikiCategoryMemberInfoFlags): AnsiString; begin QueryInit; CheckRequest(mwrQueryCategoryMemberInfo); MediaWikiQueryCategoryMemberAdd(FQueryStrings, CategoryTitle, ContinueInfo, PageNamespace, StartDateTime, StopDateTime, StartSortKey, StopSortKey, MaxCategoryMember, Flags, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.QueryCategoryMemberInfoAsync(const CategoryTitle: string; const ContinueInfo: TMediaWikiContinueInfo; PageNamespace: Integer; const StartDateTime, StopDateTime: TDateTime; const StartSortKey, StopSortKey: string; MaxCategoryMember: Integer; Flags: TMediaWikiCategoryMemberInfoFlags); begin CheckRequest(mwrQueryCategoryMemberInfo); MediaWikiQueryCategoryMemberAdd(FQueryStrings, CategoryTitle, ContinueInfo, PageNamespace, StartDateTime, StopDateTime, StartSortKey, StopSortKey, MaxCategoryMember, Flags, mwoXML); FRequestCallbacks[mwrQueryCategoryMemberInfo] := QueryCategoryMemberInfoParseXmlResult; end; procedure TMediaWikiApi.QueryCategoryMemberInfoParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiQueryCategoryMemberParseXmlResult(XML, FQueryCategoryMemberInfos, FQueryCategoryMemberContinueInfo); if Assigned(FOnQueryCategoryMemberInfoDone) then FOnQueryCategoryMemberInfoDone(Self, FQueryCategoryMemberInfos, FQueryCategoryMemberContinueInfo); end; procedure TMediaWikiApi.Edit(const PageTitle, Section, Text, PrependText, AppendText, EditToken, Summary: string; out EditInfo: TMediaWikiEditInfo; const MD5, CaptchaID, CaptchaWord: string; const BaseDateTime, StartDateTime: TDateTime; UndoRevisionID: TMediaWikiID; Flags: TMediaWikiEditFlags); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; try QueryInit; CheckRequest(mwrEdit); MediaWikiEditAdd(FQueryStrings, PageTitle, Section, Text, PrependText, AppendText, EditToken, Summary, MD5, CaptchaID, CaptchaWord, BaseDateTime, StartDateTime, UndoRevisionID, Flags, mwoXML); QueryExecuteXML(XML); EditParseXmlResult(Self, XML); finally EditInfo := FEditInfo; XML.Free; end; end; function TMediaWikiApi.Edit(const PageTitle, Section, Text, PrependText, AppendText, EditToken, Summary: string; OutputFormat: TMediaWikiOutputFormat; const MD5, CaptchaID, CaptchaWord: string; const BaseDateTime, StartDateTime: TDateTime; UndoRevisionID: TMediaWikiID; Flags: TMediaWikiEditFlags): AnsiString; begin QueryInit; CheckRequest(mwrEdit); MediaWikiEditAdd(FQueryStrings, PageTitle, Section, Text, PrependText, AppendText, EditToken, Summary, MD5, CaptchaID, CaptchaWord, BaseDateTime, StartDateTime, UndoRevisionID, Flags, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.EditAsync(const PageTitle, Section, Text, PrependText, AppendText, EditToken, Summary, MD5, CaptchaID, CaptchaWord: string; const BaseDateTime, StartDateTime: TDateTime; UndoRevisionID: TMediaWikiID; Flags: TMediaWikiEditFlags); begin CheckRequest(mwrEdit); MediaWikiEditAdd(FQueryStrings, PageTitle, Section, Text, PrependText, AppendText, EditToken, Summary, MD5, CaptchaID, CaptchaWord, BaseDateTime, StartDateTime, UndoRevisionID, Flags, mwoXML); FRequestCallbacks[mwrEdit] := EditParseXmlResult; end; procedure TMediaWikiApi.EditParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiEditParseXmlResult(XML, FEditInfo); if Assigned(FOnEditDone) then FOnEditDone(Self, FEditInfo); end; procedure TMediaWikiApi.Move(const FromPageTitle, ToPageTitle, MoveToken, Reason: string; FromPageID: TMediaWikiID; Flags: TMediaWikiMoveFlags; out MoveInfo: TMediaWikiMoveInfo); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; try QueryInit; CheckRequest(mwrMove); MediaWikiMoveAdd(FQueryStrings, FromPageTitle, ToPageTitle, MoveToken, Reason, FromPageID, Flags, mwoXML); QueryExecuteXML(XML); MoveParseXmlResult(Self, XML); finally MoveInfo := FMoveInfo; XML.Free; end; end; function TMediaWikiApi.Move(const FromPageTitle, ToPageTitle, MoveToken, Reason: string; FromPageID: TMediaWikiID; Flags: TMediaWikiMoveFlags; OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrMove); MediaWikiMoveAdd(FQueryStrings, FromPageTitle, ToPageTitle, MoveToken, Reason, FromPageID, Flags, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.MoveAsync(const FromPageTitle, ToPageTitle, MoveToken, Reason: string; FromPageID: TMediaWikiID; Flags: TMediaWikiMoveFlags); begin CheckRequest(mwrMove); MediaWikiMoveAdd(FQueryStrings, FromPageTitle, ToPageTitle, MoveToken, Reason, FromPageID, Flags, mwoXML); FRequestCallbacks[mwrMove] := MoveParseXmlResult; end; procedure TMediaWikiApi.MoveParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiMoveParseXmlResult(XML, FMoveInfo); if Assigned(FOnMoveDone) then FOnMoveDone(Self, FMoveInfo); end; procedure TMediaWikiApi.Delete(const PageTitle, DeleteToken, Reason: string; FromPageID: TMediaWikiID; out DeleteInfo: TMediaWikiDeleteInfo; Suppress: Boolean); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; try QueryInit; CheckRequest(mwrDelete); MediaWikiDeleteAdd(FQueryStrings, PageTitle, DeleteToken, Reason, FromPageID, Suppress, mwoXML); QueryExecuteXML(XML); DeleteParseXmlResult(Self, XML); finally DeleteInfo := FDeleteInfo; XML.Free; end; end; function TMediaWikiApi.Delete(const PageTitle, DeleteToken, Reason: string; FromPageID: TMediaWikiID; OutputFormat: TMediaWikiOutputFormat; Suppress: Boolean): AnsiString; begin QueryInit; CheckRequest(mwrDelete); MediaWikiDeleteAdd(FQueryStrings, PageTitle, DeleteToken, Reason, FromPageID, Suppress, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.DeleteAsync(const PageTitle, DeleteToken, Reason: string; FromPageID: TMediaWikiID; Suppress: Boolean); begin CheckRequest(mwrDelete); MediaWikiDeleteAdd(FQueryStrings, PageTitle, DeleteToken, Reason, FromPageID, Suppress, mwoXML); FRequestCallbacks[mwrDelete] := DeleteParseXmlResult; end; procedure TMediaWikiApi.DeleteParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiDeleteParseXmlResult(XML, FDeleteInfo); if Assigned(FOnDeleteDone) then FOnDeleteDone(Self, FDeleteInfo); end; procedure TMediaWikiApi.DeleteRevision(const PageTitle, DeleteToken, Reason: string; FromPageID, RevisionID: TMediaWikiID; out DeleteRevisionInfo: TMediaWikiDeleteRevisionInfo); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; try QueryInit; CheckRequest(mwrDeleteRevision); MediaWikiDeleteRevisionAdd(FQueryStrings, PageTitle, DeleteToken, Reason, FromPageID, RevisionID, mwoXML); QueryExecuteXML(XML); DeleteRevisionParseXmlResult(Self, XML); finally DeleteRevisionInfo := FDeleteRevisionInfo; XML.Free; end; end; function TMediaWikiApi.DeleteRevision(const PageTitle, DeleteToken, Reason: string; FromPageID, RevisionID: TMediaWikiID; OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrDeleteRevision); MediaWikiDeleteRevisionAdd(FQueryStrings, PageTitle, DeleteToken, Reason, FromPageID, RevisionID, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.DeleteRevisionAsync(const PageTitle, DeleteToken, Reason: string; FromPageID, RevisionID: TMediaWikiID); begin CheckRequest(mwrDeleteRevision); MediaWikiDeleteRevisionAdd(FQueryStrings, PageTitle, DeleteToken, Reason, FromPageID, RevisionID, mwoXML); FRequestCallbacks[mwrDeleteRevision] := DeleteRevisionParseXmlResult; end; procedure TMediaWikiApi.DeleteRevisionParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiDeleteRevisionParseXmlResult(XML, FDeleteRevisionInfo); if Assigned(FOnDeleteRevisionDone) then FOnDeleteRevisionDone(Self, FDeleteRevisionInfo); end; procedure TMediaWikiApi.Upload(const FileName, Comment, Text, EditToken: string; Flags: TMediaWikiUploadFlags; Content: TStream; const URL: string; out UploadInfo: TMediaWikiUploadInfo); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; try QueryInit; CheckRequest(mwrUpload); MediaWikiUploadAdd(FQueryStrings, FileName, Comment, Text, EditToken, Flags, Content, URL, mwoXML); QueryExecuteXML(XML); UploadParseXmlResult(Self, XML); finally UploadInfo := FUploadInfo; XML.Free; end; end; function TMediaWikiApi.Upload(const FileName, Comment, Text, EditToken: string; Flags: TMediaWikiUploadFlags; Content: TStream; const URL: string; OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrUpload); MediaWikiUploadAdd(FQueryStrings, FileName, Comment, Text, EditToken, Flags, Content, URL, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.UploadAsync(const FileName, Comment, Text, EditToken: string; Flags: TMediaWikiUploadFlags; Content: TStream; const URL: string); begin CheckRequest(mwrUpload); MediaWikiUploadAdd(FQueryStrings, FileName, Comment, Text, EditToken, Flags, Content, URL, mwoXML); FRequestCallbacks[mwrUpload] := UploadParseXmlResult; end; procedure TMediaWikiApi.UploadParseXmlResult( Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiUploadParseXmlResult(XML, FUploadInfo); if Assigned(FOnUploadDone) then FOnUploadDone(Self, FUploadInfo); end; procedure TMediaWikiApi.UserMerge(const OldUser, NewUser, Token: string; DeleteUser: Boolean; out UserMergeInfo: TMediaWikiUserMergeInfo); var XML: TJclSimpleXML; begin XML := TJclSimpleXML.Create; try QueryInit; CheckRequest(mwrUserMerge); MediaWikiUserMergeAdd(FQueryStrings, OldUser, NewUser, Token, DeleteUser, mwoXML); QueryExecuteXML(XML); UserMergeParseXmlResult(Self, XML); finally UserMergeInfo := FUserMergeInfo; XML.Free; end; end; function TMediaWikiApi.UserMerge(const OldUser, NewUser, Token: string; DeleteUser: Boolean; OutputFormat: TMediaWikiOutputFormat): AnsiString; begin QueryInit; CheckRequest(mwrUserMerge); MediaWikiUserMergeAdd(FQueryStrings, OldUser, NewUser, Token, DeleteUser, OutputFormat); Result := QueryExecute; end; procedure TMediaWikiApi.UserMergeAsync(const OldUser, NewUser, Token: string; DeleteUser: Boolean); begin CheckRequest(mwrUserMerge); MediaWikiUserMergeAdd(FQueryStrings, OldUser, NewUser, Token, DeleteUser, mwoXML); FRequestCallbacks[mwrUserMerge] := UserMergeParseXmlResult; end; procedure TMediaWikiApi.UserMergeParseXmlResult(Sender: TMediaWikiApi; XML: TJclSimpleXML); begin MediaWikiUserMergeParseXmlResult(XML, FUserMergeInfo); if Assigned(FOnUserMergeDone) then FOnUserMergeDone(Self, FUserMergeInfo); end; procedure TMediaWikiApi.RequestDone(Sender: TObject; RqType: THttpRequest; ErrCode: Word); var XML: TJclSimpleXML; function NeedXML: TJclSimpleXML; begin Result := XML; if not Assigned(Result) then begin XML := TJclSimpleXML.Create; FReceiveStream.Position := 0; XML.LoadFromStream(FReceiveStream, seUTF8); MediaWikiCheckXML(XML, ProcessXMLWarning, ProcessXMLError); Result := XML; end; end; var Request: TMediaWikiRequest; Callback: TMediaWikiXMLCallback; begin FPendingRequests := []; if ErrCode <> 0 then raise EMediaWikiException.Create('request error') else if FHttpsCli.StatusCode <> 200 then raise EMediaWikiException.Create('http request error'); XML := nil; try for Request := Low(TMediaWikiRequest) to High(TMediaWikiRequest) do begin Callback := FRequestCallbacks[Request]; FRequestCallbacks[Request] := nil; if Assigned(Callback) then Callback(Self, NeedXML); end; finally XML.Free; end; end; end.
program checkCase; var grade: char; begin grade := 'A'; case (grade) of 'A' : ; 'B', 'C': ; 'D' :; 'F' : ; end; end.
unit sdsChangesBetweenEditions; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ChangesBetweenEditions$Domain" // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/ChangesBetweenEditions/sdsChangesBetweenEditions.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UseCaseControllerImp::Class>> F1 Пользовательские сервисы::ChangesBetweenEditions::ChangesBetweenEditions$Domain::ChangesBetweenEditionsImplementation::TsdsChangesBetweenEditions // // Прецедент ОИД // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses Classes {$If not defined(NoVCM)} , vcmControllers {$IfEnd} //not NoVCM , ChangesBetweenEditionsInterfaces {$If not defined(NoVCM)} , vcmInterfaces {$IfEnd} //not NoVCM , l3ProtoObjectWithCOMQI, l3Interfaces, l3NotifyPtrList {$If not defined(NoVCM)} , vcmExternalInterfaces {$IfEnd} //not NoVCM , DocumentAndListInterfaces {a}, DocumentUnit, nevTools, DocumentInterfaces, l3TreeInterfaces ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type _InitDataType_ = InsChangesBetweenEditionsInfo; _SetDataType_ = IsdsChangesBetweenEditionsData; _SetType_ = IsdsChangesBetweenEditions; {$Include w:\common\components\gui\Garant\VCM\implementation\vcmFormSetDataSource.imp.pas} TsdsChangesBetweenEditions = {final ucc} class(_vcmFormSetDataSource_, IsdsChangesBetweenEditions, IsdsPrimDocument {from IsdsChangesBetweenEditions}, IsdsEditionsHolder {from IsdsChangesBetweenEditions}) {* Прецедент ОИД } private // private fields f_Changes : IvcmViewAreaControllerRef; {* Поле для области вывода Changes} f_EditionsList : IvcmViewAreaControllerRef; {* Поле для области вывода EditionsList} protected // realized methods {$If not defined(NoVCM)} function MakeData: _SetDataType_; override; {* Данные сборки. } {$IfEnd} //not NoVCM function pm_GetChanges: IdsChangesBetweenEditions; function DoGet_Changes: IdsChangesBetweenEditions; function pm_GetDocInfo: IdeDocInfo; function pm_GetEditionsList: IdsEditions; function DoGet_EditionsList: IdsEditions; protected // overridden protected methods {$If not defined(NoVCM)} procedure ClearAreas; override; {* Очищает ссылки на области ввода } {$IfEnd} //not NoVCM protected // Методы преобразования к реализуемым интерфейсам function As_IsdsPrimDocument: IsdsPrimDocument; function As_IsdsEditionsHolder: IsdsEditionsHolder; end;//TsdsChangesBetweenEditions {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses dsChangesBetweenEditions, sdsChangesBetweenEditionsData, deDocInfo, dsEditions {$If not defined(NoVCM)} , vcmLocalInterfaces {$IfEnd} //not NoVCM , l3Base, SysUtils, vcmFormDataSourceRef {a} ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type _Instance_R_ = TsdsChangesBetweenEditions; {$Include w:\common\components\gui\Garant\VCM\implementation\vcmFormSetDataSource.imp.pas} // start class TsdsChangesBetweenEditions {$If not defined(NoVCM)} function TsdsChangesBetweenEditions.MakeData: _SetDataType_; //#UC START# *47F3778403D9_4DDCD7D0002E_var* //#UC END# *47F3778403D9_4DDCD7D0002E_var* begin //#UC START# *47F3778403D9_4DDCD7D0002E_impl* Result := TsdsChangesBetweenEditionsData.Make(InitialUseCaseData); //#UC END# *47F3778403D9_4DDCD7D0002E_impl* end;//TsdsChangesBetweenEditions.MakeData {$IfEnd} //not NoVCM function TsdsChangesBetweenEditions.pm_GetChanges: IdsChangesBetweenEditions; //#UC START# *4DDCD7520351_4DDCD7D0002Eget_var* //#UC END# *4DDCD7520351_4DDCD7D0002Eget_var* begin if (f_Changes = nil) then begin f_Changes := TvcmViewAreaControllerRef.Make; //#UC START# *4DDCD7520351_4DDCD7D0002Eget_init* // - код инициализации ссылки на ViewArea //#UC END# *4DDCD7520351_4DDCD7D0002Eget_init* end;//f_Changes = nil if f_Changes.IsEmpty //#UC START# *4DDCD7520351_4DDCD7D0002Eget_need* // - условие создания ViewArea //#UC END# *4DDCD7520351_4DDCD7D0002Eget_need* then f_Changes.Referred := DoGet_Changes; Result := IdsChangesBetweenEditions(f_Changes.Referred); end; function TsdsChangesBetweenEditions.DoGet_Changes: IdsChangesBetweenEditions; //#UC START# *4DDCD7520351_4DDCD7D0002Earea_var* //#UC END# *4DDCD7520351_4DDCD7D0002Earea_var* begin //#UC START# *4DDCD7520351_4DDCD7D0002Earea_impl* Result := TdsChangesBetweenEditions.Make(Self, InitialUseCaseData); //#UC END# *4DDCD7520351_4DDCD7D0002Earea_impl* end;//TsdsChangesBetweenEditions.DoGet_Changes function TsdsChangesBetweenEditions.pm_GetDocInfo: IdeDocInfo; //#UC START# *4DF9D63B0360_4DDCD7D0002Eget_var* //#UC END# *4DF9D63B0360_4DDCD7D0002Eget_var* begin //#UC START# *4DF9D63B0360_4DDCD7D0002Eget_impl* Result := TdeDocInfo.Make(InitialUseCaseData.RightEdition); //#UC END# *4DF9D63B0360_4DDCD7D0002Eget_impl* end;//TsdsChangesBetweenEditions.pm_GetDocInfo function TsdsChangesBetweenEditions.pm_GetEditionsList: IdsEditions; //#UC START# *4ED906420134_4DDCD7D0002Eget_var* //#UC END# *4ED906420134_4DDCD7D0002Eget_var* begin if (f_EditionsList = nil) then begin f_EditionsList := TvcmViewAreaControllerRef.Make; //#UC START# *4ED906420134_4DDCD7D0002Eget_init* // - код инициализации ссылки на ViewArea //#UC END# *4ED906420134_4DDCD7D0002Eget_init* end;//f_EditionsList = nil if f_EditionsList.IsEmpty //#UC START# *4ED906420134_4DDCD7D0002Eget_need* // - условие создания ViewArea //#UC END# *4ED906420134_4DDCD7D0002Eget_need* then f_EditionsList.Referred := DoGet_EditionsList; Result := IdsEditions(f_EditionsList.Referred); end; function TsdsChangesBetweenEditions.DoGet_EditionsList: IdsEditions; //#UC START# *4ED906420134_4DDCD7D0002Earea_var* //#UC END# *4ED906420134_4DDCD7D0002Earea_var* begin //#UC START# *4ED906420134_4DDCD7D0002Earea_impl* Result := TdsEditions.Make(Self); //#UC END# *4ED906420134_4DDCD7D0002Earea_impl* end;//TsdsChangesBetweenEditions.DoGet_EditionsList {$If not defined(NoVCM)} procedure TsdsChangesBetweenEditions.ClearAreas; {-} begin if (f_Changes <> nil) then f_Changes.Referred := nil; if (f_EditionsList <> nil) then f_EditionsList.Referred := nil; inherited; end;//TsdsChangesBetweenEditions.ClearAreas {$IfEnd} //not NoVCM // Методы преобразования к реализуемым интерфейсам function TsdsChangesBetweenEditions.As_IsdsPrimDocument: IsdsPrimDocument; begin Result := Self; end; function TsdsChangesBetweenEditions.As_IsdsEditionsHolder: IsdsEditionsHolder; begin Result := Self; end; {$IfEnd} //not Admin AND not Monitorings end.
unit DAO.CidadesCEP; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.CidadesCEP; type TCidadesCEPDAO= class private FConexao : TConexao; public constructor Create; function GetID(): Integer; function Inserir(ACidades: TCidadesCEP): Boolean; function Alterar(ACidades: TCidadesCEP): Boolean; function Excluir(ACidades: TCidadesCEP): Boolean; function Pesquisar(aParam: array of variant): TFDQuery; end; const TABLENAME = 'cadastro_cidades'; implementation { TCidadesCEPDAO } uses Control.Sistema; function TCidadesCEPDAO.Alterar(ACidades: TCidadesCEP): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('update ' + TABLENAME + ' set des_descricao = :des_descricao, uf_estado = :uf_estado, cod_ibge = :cod_ibge, ' + 'num_ddd = :num_ddd' + 'where id_cidade = :id_cidade;', [ACidades.Descricao, ACidades.UF, Acidades.UF, Acidades.CodigoIBGE, ACidades.DDD]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end;end; constructor TCidadesCEPDAO.Create; begin FConexao := TSistemaControl.GetInstance.Conexao; end; function TCidadesCEPDAO.Excluir(ACidades: TCidadesCEP): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where id_cidade = :id_cidade', [ACidades.ID]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end;end; function TCidadesCEPDAO.GetID: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(id_cidade),0) + 1 from ' + TABLENAME); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end;end; function TCidadesCEPDAO.Inserir(ACidades: TCidadesCEP): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); ACidades.ID := GetID; FDQuery.ExecSQL('insert into ' + TABLENAME + ' (' + 'id_cidade, des_descricao, uf_estado, cod_ibge, num_ddd) ' + 'VALUES ' + '(:id_cidade, :des_descricao, :uf_estado, :cod_ibge, :num_ddd);', [ACidades.ID, ACidades.Descricao, ACidades.UF, ACidades.CodigoIBGE, ACidades.DDD]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCidadesCEPDAO.Pesquisar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'ID' then begin FDQuery.SQL.Add('where id_cidade = :id_cidade'); FDQuery.ParamByName('id_cidade').AsInteger := aParam[1]; end; if aParam[0] = 'UF' then begin FDQuery.SQL.Add('where uf_estado = :uf_estado'); FDQuery.ParamByName('uf_estado').AsString := aParam[1]; end; if aParam[0] = 'CIDADE' then begin FDQuery.SQL.Add('where des_descricao like :des_descricao'); FDQuery.ParamByName('des_descricao').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('where ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open; Result := FDQuery; end; end.
unit MainUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ActnList, Vcl.StdActns, Vcl.Menus, Vcl.ExtCtrls, VCLTee.TeEngine, VCLTee.TeeProcs, VCLTee.Chart, VCLTee.Series, Fftw3_Common, Fftw3_64, Vcl.ComCtrls, Vcl.StdCtrls; type TFormFilterKernelExplorer = class(TForm) ActionDomainFilterKernel: TAction; ActionDomainMagnitude: TAction; ActionDomainPhase: TAction; ActionDomainComplex: TAction; ActionFileExit: TFileExit; ActionList: TActionList; Chart: TChart; MainMenu: TMainMenu; MenuItemDomain: TMenuItem; MenuItemDomainFilterKernel: TMenuItem; MenuItemDomainFrequencyDomain: TMenuItem; MenuItemDomainPhase: TMenuItem; MenuItemDomainReal: TMenuItem; MenuItemExit: TMenuItem; MenuItemFile: TMenuItem; N1: TMenuItem; PanelControl: TPanel; LabelLow: TLabel; LabelHigh: TLabel; TrackBarLow: TTrackBar; TrackBarHigh: TTrackBar; procedure ActionDomainFilterKernelExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ActionDomainMagnitudeExecute(Sender: TObject); procedure ActionDomainPhaseExecute(Sender: TObject); procedure ActionDomainComplexExecute(Sender: TObject); procedure TrackBarChange(Sender: TObject); private FFftwPlan: TFftw64Plan; FKernelSize: Integer; FFilterKernel: PFftw64Real; FFrequencyDomain: PFftw64Complex; FSeriesFilterKernel: TFastLineSeries; FSeriesReal: TFastLineSeries; FSeriesImaginary: TFastLineSeries; FSeriesMagnitude: TFastLineSeries; FSeriesPhase: TFastLineSeries; FWisdomFileName: TFileName; procedure BuildFilterKernel; end; var FormFilterKernelExplorer: TFormFilterKernelExplorer; implementation uses Math; {$R *.dfm} procedure TFormFilterKernelExplorer.FormCreate(Sender: TObject); begin FKernelSize := 512; // allocate memory FFilterKernel := Fftw64AllocReal(FKernelSize); FFrequencyDomain := Fftw64AllocComplex(FKernelSize); // create FFTW plan FFftwPlan := Fftw64PlanDftReal2Complex1D(FKernelSize, FFilterKernel, FFrequencyDomain, []); // create series and add to chart FSeriesFilterKernel := TFastLineSeries.Create(Chart); FSeriesReal := TFastLineSeries.Create(Chart); FSeriesImaginary := TFastLineSeries.Create(Chart); FSeriesMagnitude := TFastLineSeries.Create(Chart); FSeriesPhase := TFastLineSeries.Create(Chart); Chart.AddSeries(FSeriesFilterKernel); Chart.AddSeries(FSeriesReal); Chart.AddSeries(FSeriesImaginary); Chart.AddSeries(FSeriesMagnitude); Chart.AddSeries(FSeriesPhase); FSeriesReal.Active := False; FSeriesImaginary.Active := False; FSeriesMagnitude.Active := False; FSeriesPhase.Active := False; FWisdomFileName := ChangeFileExt(ParamStr(0), '.wsd'); end; procedure TFormFilterKernelExplorer.FormDestroy(Sender: TObject); begin // free memory Fftw64Free(FFilterKernel); Fftw64Free(FFrequencyDomain); end; procedure TFormFilterKernelExplorer.FormShow(Sender: TObject); begin BuildFilterKernel; Fftw64ImportWisdomFromFilename(PAnsiChar(AnsiString(FWisdomFileName))); end; procedure TFormFilterKernelExplorer.TrackBarChange(Sender: TObject); begin BuildFilterKernel; end; procedure TFormFilterKernelExplorer.FormClose(Sender: TObject; var Action: TCloseAction); begin Fftw64ExportWisdomToFilename(PAnsiChar(AnsiString(FWisdomFileName))); end; procedure TFormFilterKernelExplorer.ActionDomainComplexExecute(Sender: TObject); begin FSeriesFilterKernel.Active := False; FSeriesReal.Active := True; FSeriesImaginary.Active := True; FSeriesMagnitude.Active := False; FSeriesPhase.Active := False; end; procedure TFormFilterKernelExplorer.ActionDomainFilterKernelExecute( Sender: TObject); begin FSeriesFilterKernel.Active := True; FSeriesReal.Active := False; FSeriesImaginary.Active := False; FSeriesMagnitude.Active := False; FSeriesPhase.Active := False; end; procedure TFormFilterKernelExplorer.ActionDomainMagnitudeExecute( Sender: TObject); begin FSeriesFilterKernel.Active := False; FSeriesReal.Active := False; FSeriesImaginary.Active := False; FSeriesMagnitude.Active := True; FSeriesPhase.Active := False; end; procedure TFormFilterKernelExplorer.ActionDomainPhaseExecute(Sender: TObject); begin FSeriesFilterKernel.Active := False; FSeriesReal.Active := False; FSeriesImaginary.Active := False; FSeriesMagnitude.Active := False; FSeriesPhase.Active := True; end; procedure TFormFilterKernelExplorer.BuildFilterKernel; var Index: Integer; Data: PFftw64Real; Complex: PFftw64Complex; Temp, Scale: Double; CutOff: array [0 .. 1] of Double; begin // build sinc filter kernel Data := FFilterKernel; CutOff[0] := 0.01 * TrackBarLow.Position; CutOff[1] := 0.01 * TrackBarHigh.Position; Scale := 2 * Pi / (FKernelSize - 1); for Index := 0 to FKernelSize - 1 do begin // calculate sinc function if (Index = FKernelSize div 2) then Data^ := 2.0 * (CutOff[0] - CutOff[1]) else begin Temp := PI * (Index - FKernelSize div 2); Data^ := (Sin(2 * CutOff[0] * Temp) - Sin(2 * CutOff[1] * Temp)) / Temp; end; // apply Blackman-Harris window Data^ := Data^ * (0.35875 - 0.48829 * Cos(Index * Scale) + 0.14128 * Cos(2 * Index * Scale) - 0.01168 * Cos(3 * Index * Scale)); Inc(Data); end; Fftw64ExecuteDftReal2Complex(FFftwPlan, FFilterKernel, FFrequencyDomain); FSeriesFilterKernel.Clear; Data := FFilterKernel; for Index := 0 to FKernelSize - 1 do begin FSeriesFilterKernel.Add(Data^); Inc(Data); end; FSeriesReal.Clear; FSeriesImaginary.Clear; FSeriesMagnitude.Clear; FSeriesPhase.Clear; Complex := FFrequencyDomain; for Index := 0 to FKernelSize div 2 - 1 do begin FSeriesReal.Add(Complex^.Re); FSeriesImaginary.Add(Complex^.Im); FSeriesMagnitude.Add(Hypot(Complex^.Re, Complex^.Im)); FSeriesPhase.Add(ArcTan2(Complex^.Re, Complex^.Im)); Inc(Complex); end; end; end.
program Example9; var x, a, b: integer; begin readln(x); a := 0; b := 10; while x > 0 do begin if x mod 10 > a then a := x mod 10; if x mod 10 < b then b := x mod 10; x := x div 10; end; writeln('Max=', a); write('Min=', b); end.
unit UserCR2_WarningBaloonKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы UserCR2_WarningBaloon } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Document\Forms\UserCR2_WarningBaloonKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "UserCR2_WarningBaloonKeywordsPack" MUID: (4EF47F5A02F7_Pack) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , UserCR2_WarningBaloon_Form , tfwPropertyLike {$If Defined(Nemesis)} , nscEditor {$IfEnd} // Defined(Nemesis) , tfwScriptingInterfaces , TypInfo , tfwTypeInfo , tfwControlString , kwBynameControlPush , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4EF47F5A02F7_Packimpl_uses* //#UC END# *4EF47F5A02F7_Packimpl_uses* ; type TkwUserCR2WarningBaloonFormViewer = {final} class(TtfwPropertyLike) {* Слово скрипта .TUserCR2_WarningBaloonForm.Viewer } private function Viewer(const aCtx: TtfwContext; aUserCR2_WarningBaloonForm: TUserCR2_WarningBaloonForm): TnscEditor; {* Реализация слова скрипта .TUserCR2_WarningBaloonForm.Viewer } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwUserCR2WarningBaloonFormViewer Tkw_Form_UserCR2_WarningBaloon = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы UserCR2_WarningBaloon ---- *Пример использования*: [code]форма::UserCR2_WarningBaloon TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_UserCR2_WarningBaloon Tkw_UserCR2_WarningBaloon_Control_Viewer = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола Viewer ---- *Пример использования*: [code]контрол::Viewer TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_UserCR2_WarningBaloon_Control_Viewer Tkw_UserCR2_WarningBaloon_Control_Viewer_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола Viewer ---- *Пример использования*: [code]контрол::Viewer:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_UserCR2_WarningBaloon_Control_Viewer_Push function TkwUserCR2WarningBaloonFormViewer.Viewer(const aCtx: TtfwContext; aUserCR2_WarningBaloonForm: TUserCR2_WarningBaloonForm): TnscEditor; {* Реализация слова скрипта .TUserCR2_WarningBaloonForm.Viewer } begin Result := aUserCR2_WarningBaloonForm.Viewer; end;//TkwUserCR2WarningBaloonFormViewer.Viewer class function TkwUserCR2WarningBaloonFormViewer.GetWordNameForRegister: AnsiString; begin Result := '.TUserCR2_WarningBaloonForm.Viewer'; end;//TkwUserCR2WarningBaloonFormViewer.GetWordNameForRegister function TkwUserCR2WarningBaloonFormViewer.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscEditor); end;//TkwUserCR2WarningBaloonFormViewer.GetResultTypeInfo function TkwUserCR2WarningBaloonFormViewer.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwUserCR2WarningBaloonFormViewer.GetAllParamsCount function TkwUserCR2WarningBaloonFormViewer.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TUserCR2_WarningBaloonForm)]); end;//TkwUserCR2WarningBaloonFormViewer.ParamsTypes procedure TkwUserCR2WarningBaloonFormViewer.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Viewer', aCtx); end;//TkwUserCR2WarningBaloonFormViewer.SetValuePrim procedure TkwUserCR2WarningBaloonFormViewer.DoDoIt(const aCtx: TtfwContext); var l_aUserCR2_WarningBaloonForm: TUserCR2_WarningBaloonForm; begin try l_aUserCR2_WarningBaloonForm := TUserCR2_WarningBaloonForm(aCtx.rEngine.PopObjAs(TUserCR2_WarningBaloonForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aUserCR2_WarningBaloonForm: TUserCR2_WarningBaloonForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(Viewer(aCtx, l_aUserCR2_WarningBaloonForm)); end;//TkwUserCR2WarningBaloonFormViewer.DoDoIt function Tkw_Form_UserCR2_WarningBaloon.GetString: AnsiString; begin Result := 'UserCR2_WarningBaloonForm'; end;//Tkw_Form_UserCR2_WarningBaloon.GetString class procedure Tkw_Form_UserCR2_WarningBaloon.RegisterInEngine; begin inherited; TtfwClassRef.Register(TUserCR2_WarningBaloonForm); end;//Tkw_Form_UserCR2_WarningBaloon.RegisterInEngine class function Tkw_Form_UserCR2_WarningBaloon.GetWordNameForRegister: AnsiString; begin Result := 'форма::UserCR2_WarningBaloon'; end;//Tkw_Form_UserCR2_WarningBaloon.GetWordNameForRegister function Tkw_UserCR2_WarningBaloon_Control_Viewer.GetString: AnsiString; begin Result := 'Viewer'; end;//Tkw_UserCR2_WarningBaloon_Control_Viewer.GetString class procedure Tkw_UserCR2_WarningBaloon_Control_Viewer.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscEditor); end;//Tkw_UserCR2_WarningBaloon_Control_Viewer.RegisterInEngine class function Tkw_UserCR2_WarningBaloon_Control_Viewer.GetWordNameForRegister: AnsiString; begin Result := 'контрол::Viewer'; end;//Tkw_UserCR2_WarningBaloon_Control_Viewer.GetWordNameForRegister procedure Tkw_UserCR2_WarningBaloon_Control_Viewer_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('Viewer'); inherited; end;//Tkw_UserCR2_WarningBaloon_Control_Viewer_Push.DoDoIt class function Tkw_UserCR2_WarningBaloon_Control_Viewer_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::Viewer:push'; end;//Tkw_UserCR2_WarningBaloon_Control_Viewer_Push.GetWordNameForRegister initialization TkwUserCR2WarningBaloonFormViewer.RegisterInEngine; {* Регистрация UserCR2_WarningBaloonForm_Viewer } Tkw_Form_UserCR2_WarningBaloon.RegisterInEngine; {* Регистрация Tkw_Form_UserCR2_WarningBaloon } Tkw_UserCR2_WarningBaloon_Control_Viewer.RegisterInEngine; {* Регистрация Tkw_UserCR2_WarningBaloon_Control_Viewer } Tkw_UserCR2_WarningBaloon_Control_Viewer_Push.RegisterInEngine; {* Регистрация Tkw_UserCR2_WarningBaloon_Control_Viewer_Push } TtfwTypeRegistrator.RegisterType(TypeInfo(TUserCR2_WarningBaloonForm)); {* Регистрация типа TUserCR2_WarningBaloonForm } {$If Defined(Nemesis)} TtfwTypeRegistrator.RegisterType(TypeInfo(TnscEditor)); {* Регистрация типа TnscEditor } {$IfEnd} // Defined(Nemesis) {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.