text
stringlengths
14
6.51M
namespace HorseRace; interface uses System.Windows.Forms, System.Drawing; type HorseUIUpdateDelegate = delegate(aPictureBox : PictureBox; anIncrement : Integer); MainForm = class(System.Windows.Forms.Form) {$REGION Windows Form Designer generated fields} private panel2: System.Windows.Forms.Panel; panel3: System.Windows.Forms.Panel; panel1: System.Windows.Forms.Panel; Horse1: System.Windows.Forms.PictureBox; Horse2: System.Windows.Forms.PictureBox; Horse3: System.Windows.Forms.PictureBox; bStartRace: System.Windows.Forms.Button; components: System.ComponentModel.Container := nil; pictureBox1: System.Windows.Forms.PictureBox; method bStartRace_Click(sender: System.Object; e: System.EventArgs); method MainForm_Load(sender: System.Object; e: System.EventArgs); method InitializeComponent; {$ENDREGION} private const TotalHorses: Integer = 3; protected fFirstHorse: Integer; method Dispose(aDisposing: Boolean); override; method DoHorseUIUpdate(aPictureBox : PictureBox; anIncrement : Integer); method SetFirstHorse(Value : Integer); locked; // Thread safe public constructor; class method Main; method FindControl(aParent: Control; aName: String): Control; method Race(LaneNumber: Integer); async; // Asynchronous method that will execute in its own thread property FirstHorse: Integer read fFirstHorse write SetFirstHorse; class RandomGen: Random := new Random(); end; implementation {$REGION Construction and Disposition} constructor MainForm; begin // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // end; method MainForm.Dispose(aDisposing: boolean); begin if aDisposing then begin if assigned(components) then components.Dispose(); // // TODO: Add custom disposition code here // end; inherited Dispose(aDisposing); end; {$ENDREGION} {$REGION Windows Form Designer generated code} method MainForm.InitializeComponent; begin var resources: System.ComponentModel.ComponentResourceManager := new System.ComponentModel.ComponentResourceManager(typeOf(MainForm)); self.Horse1 := new System.Windows.Forms.PictureBox(); self.Horse2 := new System.Windows.Forms.PictureBox(); self.Horse3 := new System.Windows.Forms.PictureBox(); self.bStartRace := new System.Windows.Forms.Button(); self.panel1 := new System.Windows.Forms.Panel(); self.panel2 := new System.Windows.Forms.Panel(); self.panel3 := new System.Windows.Forms.Panel(); self.pictureBox1 := new System.Windows.Forms.PictureBox(); (self.Horse1 as System.ComponentModel.ISupportInitialize).BeginInit(); (self.Horse2 as System.ComponentModel.ISupportInitialize).BeginInit(); (self.Horse3 as System.ComponentModel.ISupportInitialize).BeginInit(); (self.pictureBox1 as System.ComponentModel.ISupportInitialize).BeginInit(); self.SuspendLayout(); // // Horse1 // self.Horse1.Image := (resources.GetObject('Horse1.Image') as System.Drawing.Image); self.Horse1.Location := new System.Drawing.Point(16, 77); self.Horse1.Name := 'Horse1'; self.Horse1.Size := new System.Drawing.Size(95, 72); self.Horse1.TabIndex := 0; self.Horse1.TabStop := false; // // Horse2 // self.Horse2.Image := (resources.GetObject('Horse2.Image') as System.Drawing.Image); self.Horse2.Location := new System.Drawing.Point(16, 181); self.Horse2.Name := 'Horse2'; self.Horse2.Size := new System.Drawing.Size(95, 72); self.Horse2.TabIndex := 1; self.Horse2.TabStop := false; // // Horse3 // self.Horse3.Image := (resources.GetObject('Horse3.Image') as System.Drawing.Image); self.Horse3.Location := new System.Drawing.Point(16, 285); self.Horse3.Name := 'Horse3'; self.Horse3.Size := new System.Drawing.Size(95, 72); self.Horse3.TabIndex := 3; self.Horse3.TabStop := false; // // bStartRace // self.bStartRace.ImageAlign := System.Drawing.ContentAlignment.MiddleRight; self.bStartRace.Location := new System.Drawing.Point(16, 12); self.bStartRace.Name := 'bStartRace'; self.bStartRace.Size := new System.Drawing.Size(120, 23); self.bStartRace.TabIndex := 7; self.bStartRace.Text := 'Start Race'; self.bStartRace.Click += new System.EventHandler(@self.bStartRace_Click); // // panel1 // self.panel1.Anchor := (((System.Windows.Forms.AnchorStyles.Top or System.Windows.Forms.AnchorStyles.Left) or System.Windows.Forms.AnchorStyles.Right) as System.Windows.Forms.AnchorStyles); self.panel1.BackColor := System.Drawing.Color.FromArgb(((0 as System.Byte) as System.Int32), ((192 as System.Byte) as System.Int32), ((0 as System.Byte) as System.Int32)); self.panel1.BorderStyle := System.Windows.Forms.BorderStyle.FixedSingle; self.panel1.Location := new System.Drawing.Point(16, 149); self.panel1.Name := 'panel1'; self.panel1.Size := new System.Drawing.Size(488, 16); self.panel1.TabIndex := 8; // // panel2 // self.panel2.Anchor := (((System.Windows.Forms.AnchorStyles.Top or System.Windows.Forms.AnchorStyles.Left) or System.Windows.Forms.AnchorStyles.Right) as System.Windows.Forms.AnchorStyles); self.panel2.BackColor := System.Drawing.Color.FromArgb(((0 as System.Byte) as System.Int32), ((192 as System.Byte) as System.Int32), ((0 as System.Byte) as System.Int32)); self.panel2.BorderStyle := System.Windows.Forms.BorderStyle.FixedSingle; self.panel2.Location := new System.Drawing.Point(16, 253); self.panel2.Name := 'panel2'; self.panel2.Size := new System.Drawing.Size(488, 16); self.panel2.TabIndex := 9; // // panel3 // self.panel3.Anchor := (((System.Windows.Forms.AnchorStyles.Top or System.Windows.Forms.AnchorStyles.Left) or System.Windows.Forms.AnchorStyles.Right) as System.Windows.Forms.AnchorStyles); self.panel3.BackColor := System.Drawing.Color.FromArgb(((0 as System.Byte) as System.Int32), ((192 as System.Byte) as System.Int32), ((0 as System.Byte) as System.Int32)); self.panel3.BorderStyle := System.Windows.Forms.BorderStyle.FixedSingle; self.panel3.Location := new System.Drawing.Point(16, 357); self.panel3.Name := 'panel3'; self.panel3.Size := new System.Drawing.Size(488, 16); self.panel3.TabIndex := 10; // // pictureBox1 // self.pictureBox1.Image := (resources.GetObject('pictureBox1.Image') as System.Drawing.Image); self.pictureBox1.InitialImage := (resources.GetObject('pictureBox1.InitialImage') as System.Drawing.Image); self.pictureBox1.Location := new System.Drawing.Point(446, 12); self.pictureBox1.Name := 'pictureBox1'; self.pictureBox1.Size := new System.Drawing.Size(62, 62); self.pictureBox1.SizeMode := System.Windows.Forms.PictureBoxSizeMode.StretchImage; self.pictureBox1.TabIndex := 11; self.pictureBox1.TabStop := false; // // MainForm // self.ClientSize := new System.Drawing.Size(520, 406); self.Controls.Add(self.pictureBox1); self.Controls.Add(self.panel3); self.Controls.Add(self.panel2); self.Controls.Add(self.panel1); self.Controls.Add(self.bStartRace); self.Controls.Add(self.Horse1); self.Controls.Add(self.Horse2); self.Controls.Add(self.Horse3); self.ForeColor := System.Drawing.SystemColors.ControlText; self.Icon := (resources.GetObject('$this.Icon') as System.Drawing.Icon); self.Name := 'MainForm'; self.Text := 'Horse Race Sample'; self.Load += new System.EventHandler(@self.MainForm_Load); (self.Horse1 as System.ComponentModel.ISupportInitialize).EndInit(); (self.Horse2 as System.ComponentModel.ISupportInitialize).EndInit(); (self.Horse3 as System.ComponentModel.ISupportInitialize).EndInit(); (self.pictureBox1 as System.ComponentModel.ISupportInitialize).EndInit(); self.ResumeLayout(false); end; {$ENDREGION} {$REGION Application Entry Point} [STAThread] class method MainForm.Main; begin try with lForm := new MainForm() do Application.Run(lForm); except on E: Exception do begin MessageBox.Show(E.Message); end; end; end; {$ENDREGION} method MainForm.MainForm_Load(sender: System.Object; e: System.EventArgs); begin { Notice the use of the "matching" keyword in this for-each block. We loop through all the Controls in the form that are of PictureBox type. } for each matching picture: PictureBox in Controls do (picture.Image as Bitmap).MakeTransparent(Color.Red); end; method MainForm.bStartRace_Click(sender: System.Object; e: System.EventArgs); begin fFirstHorse := 0; { Since the Race method was marked "async", the following loop will terminate before the horses finish racing } for i: Integer := 1 to TotalHorses do Race(i); { We need to wait until there's a winner before showing the dialog } while (FirstHorse=0) do Application.DoEvents; { Displays the winner } MessageBox.Show('Horse '+FirstHorse.ToString+' won the race!'); end; method MainForm.DoHorseUIUpdate(aPictureBox : PictureBox; anIncrement : integer); begin if (anIncrement<=0) then aPictureBox.Left := 8 else aPictureBox.Left := aPictureBox.Left+anIncrement; end; method MainForm.Race(LaneNumber: integer); var horse: PictureBox; begin { We find the right PictureBox } horse := FindControl(Self, 'Horse'+LaneNumber.ToString) as PictureBox; if (horse=NIL) then raise new Exception('No such lane!'); { The race code } horse.Invoke(new HorseUIUpdateDelegate(@DoHorseUIUpdate), [horse, 0]); while (horse.Left<horse.Parent.Width-horse.Width-20) do begin { Control access needs to be synchronized } horse.BeginInvoke(new HorseUIUpdateDelegate(@DoHorseUIUpdate), [horse, 10]); System.Threading.Thread.Sleep(RandomGen.Next(10, 300)); end; { The following assignment is thread safe, because of the "locked" directive used in the declaration of SetFirstHorse above } if (FirstHorse = 0) then FirstHorse := LaneNumber; end; method MainForm.FindControl(aParent: Control; aName: string): Control; begin for each matching tmpcontrol: Control in aParent.Controls do begin if (String.Compare(tmpcontrol.Name, aName, TRUE)=0) then begin { Exits returning tmpcontrol as value. This is equivalent to [..] begin result := tmpcontrol; exit; end; } exit(tmpcontrol); end else begin { Scans the control recursively } result := FindControl(tmpcontrol, aName); if (result <> NIL) then exit; end; end; end; method MainForm.SetFirstHorse(Value: integer); { Safety checks to ensure this method is always called with a proper value. } { Note how we make use of the new "between" operator to compare both upper and lower bounds at the same time. } require 0 < Value <= TotalHorses; begin fFirstHorse := Value; end; end.
unit KanjiDicReader; { Reads KANJIDIC format. # comment 亜 3021 U4e9c [fields] [readings] [T1 readings] [T2 ...] [meanings] See http://www.csse.monash.edu.au/~jwb/kanjidic_doc.html This is a parser, not a database. It's optimized for a single pass decoding. If you need something like: KanjiDic.GetKanji('..').Readings Then parse KANJIDIC with this parser and store the data in easily accessible format. Reading entries: var entry: TKanjidicEntry; while input.ReadLn(s) do begin ParseKanjidicLine(s, @entry); DoStuffWithEntry(@entry); end; For speed, it's important that you allocate a single TKanjidicEntry and do not realloc it with every line. Accessing fields: entry.readings[0].JoinKuns(', '); //a list of all common kuns entry.readings[2].JoinOns(', '); //a list of rare ons entry.JoinMeanings(', '); entry.TryGetIntValue('J', x); x := entry.GetIntValueDef('G', 5); } interface uses SysUtils, FastArray; { Do not pass here lines starting with this character. Alternatively, use IsKanjidicComment() } const KANJIDIC_COMMENT: WideChar = '#'; { Some reasonable values. Increase if it's not enough one day } const MaxReadingClasses = 3; type EKanjidicParsingException = class(Exception); { NOTE: This can be made much faster if we assume all field keys are AnsiStrings with at most 4 symbols (VERY reasonable assumption). We can just declare key as integer, and even have some sort of table to map integer(key_string) to one of sequential pre-allocated cells, i.e. integer('U') -> 0 integer('K') -> 1 This will all work in constant time. We can also have some constant time uppercase functions } TFieldEntry = record key: string; //always lowercase values: TArray<string>; //all values so far are ansi procedure Reset; procedure Copy(const ASource: TFieldEntry); procedure AddValue(const value: string); inline; function Join(const sep: string): string; inline; end; PFieldEntry = ^TFieldEntry; TReadingClassEntry = record key: string; ons: TArray<UnicodeString>; kuns: TArray<UnicodeString>; procedure Reset; procedure Copy(const ASource: TReadingClassEntry); procedure AddOn(const value: UnicodeString); inline; procedure AddKun(const value: UnicodeString); inline; function JoinOns(const sep: UnicodeString): UnicodeString; inline; function JoinKuns(const sep: UnicodeString): UnicodeString; inline; end; PReadingClassEntry = ^TReadingClassEntry; TKanjidicEntry = record kanji: UnicodeString; //it may be wider than a char jis: string; //JIS key fields: TArray<TFieldEntry>; { Kanjidic supports several reading classes: T0 the default, T1 and T2. There's no _used because there's a fixed number of them. } readings: array[0..MaxReadingClasses-1] of TReadingClassEntry; meanings: TArray<UnicodeString>; //we support multilingual kanjidics procedure Reset; procedure Copy(const ASource: TKanjidicEntry); procedure AddField(const key: string; const value: string); procedure AddMeaning(const value: UnicodeString); inline; function GetField(const key: string): PFieldEntry; function TryGetStrValue(const key: string; out value: UnicodeString): boolean; function GetStrValueDef(const key: string; const def: string = ''): UnicodeString; function TryGetIntValue(const key: string; out value: integer): boolean; function GetIntValueDef(const key: string; const def: integer = 0): integer; function JoinMeanings(const sep: UnicodeString): UnicodeString; inline; //Shortcuts for ease of access function GetPinyin: PFieldEntry; function GetKoreanReadings: PFieldEntry; end; PKanjidicEntry = ^TKanjidicEntry; { Returns true if the line in question is a Kanjidic comment line. You could have done this by yourself, but here goes. } function IsKanjidicComment(const s: UnicodeString): boolean; { Parses a valid non-empty non-comment Kanjidic line and populates the record } procedure ParseKanjidicLine(const s: UnicodeString; ed: PKanjidicEntry); { Composes Kanjidic line from parsed data } function ComposeKanjidicLine(ed: PKanjidicEntry): UnicodeString; implementation resourcestring eNoKanjiFieldInRecord = 'No kanji field in record'; eNoJisFieldInRecord = 'No jis field in record'; eBrokenMeaningBrakets = 'Broken meaning brakets'; eUnsupportedReadingClass = 'Unsupported reading class: %s'; { Entries } procedure TFieldEntry.Reset; begin key := ''; values.Clear; end; procedure TFieldEntry.Copy(const ASource: TFieldEntry); var i: integer; begin Self.Reset; Self.key := ASource.key; Self.values.Reset; for i := 0 to ASource.values.Count-1 do Self.values.Add(ASource.values[i]); end; procedure TFieldEntry.AddValue(const value: string); begin values.Add(value); end; function TFieldEntry.Join(const sep: string): string; begin Result := FastArray.Join(values, sep); end; procedure TReadingClassEntry.Reset; begin ons.Clear; kuns.Clear; end; procedure TReadingClassEntry.Copy(const ASource: TReadingClassEntry); var i: integer; begin Self.Reset; Self.key := ASource.key; Self.ons.Reset; for i := 0 to ASource.ons.Count-1 do Self.ons.Add(ASource.ons[i]); for i := 0 to ASource.kuns.Count-1 do Self.kuns.Add(ASource.kuns[i]); end; procedure TReadingClassEntry.AddOn(const value: UnicodeString); begin ons.Add(value); end; procedure TReadingClassEntry.AddKun(const value: UnicodeString); begin kuns.Add(value); end; function TReadingClassEntry.JoinOns(const sep: UnicodeString): UnicodeString; begin Result := FastArray.Join(ons, sep); end; function TReadingClassEntry.JoinKuns(const sep: UnicodeString): UnicodeString; begin Result := FastArray.Join(kuns, sep); end; procedure TKanjidicEntry.Reset; var i: integer; begin kanji := ''; jis := ''; fields.Clear; meanings.Clear; for i := 0 to Length(readings) - 1 do readings[i].Reset; end; procedure TKanjidicEntry.Copy(const ASource: TKanjidicEntry); var i: integer; begin Self.Reset; Self.kanji := ASource.kanji; Self.jis := ASource.jis; Self.fields.Reset; for i := 0 to ASource.fields.Count-1 do Self.fields.AddNew^.Copy(ASource.fields[i]); for i := 0 to Length(ASource.readings)-1 do Self.readings[i].Copy(ASource.readings[i]); for i := 0 to ASource.meanings.Count-1 do Self.meanings.Add(ASource.meanings[i]); end; procedure TKanjidicEntry.AddField(const key: string; const value: string); var field: PFieldEntry; begin field := GetField(key); if field=nil then begin field := PFieldEntry(fields.AddNew()); field^.Reset; field^.key := AnsiLowerCase(key); end; field^.AddValue(value); end; procedure TKanjidicEntry.AddMeaning(const value: UnicodeString); begin meanings.Add(value); end; function TKanjidicEntry.GetField(const key: string): PFieldEntry; var i: integer; tmp: string; begin Result := nil; tmp := AnsiLowerCase(key); for i := 0 to fields.Length - 1 do if fields[i].key=tmp then begin Result := PFieldEntry(fields.GetPointer(i)); break; end; end; function TKanjidicEntry.TryGetStrValue(const key: string; out value: UnicodeString): boolean; var field: PFieldEntry; begin field := GetField(key); if (field=nil) or (field.values.Length<=0) then Result := false else begin Result := true; value := field.values[0]; end; end; { Returns first value for the field, or empty string } function TKanjidicEntry.GetStrValueDef(const key: string; const def: UnicodeString = ''): UnicodeString; begin if not TryGetStrValue(key, Result) then Result := def; end; function TKanjidicEntry.TryGetIntValue(const key: string; out value: integer): boolean; var str: UnicodeString; begin Result := TryGetStrValue(key, str) and TryStrToInt(str, value); end; function TKanjidicEntry.GetIntValueDef(const key: string; const def: integer = 0): integer; begin if not TryGetIntValue(key, Result) then Result := def; end; function TKanjidicEntry.JoinMeanings(const sep: UnicodeString): UnicodeString; begin Result := Join(meanings, sep); end; function TKanjidicEntry.GetPinyin: PFieldEntry; begin Result := GetField('Y'); end; function TKanjidicEntry.GetKoreanReadings: PFieldEntry; begin Result := GetField('W'); end; function IsKanjidicComment(const s: UnicodeString): boolean; var pc: PWideChar; begin pc := PWideChar(integer(s)); //do not uniquestr on cast if pc=nil then begin Result := false; exit; end; while pc^=' ' do Inc(pc); Result := pc^=KANJIDIC_COMMENT; end; function ReadNextWord(var pc: PWideChar; out word: UnicodeString): boolean; var stop_char: WideChar; begin while pc^=' ' do Inc(pc); if pc^=#00 then begin //Nothing to read Result := false; exit; end; //Otherwise there is something Result := true; if pc^='{' then stop_char := '}' else stop_char := ' '; while (pc^<>#00) and (pc^<>stop_char) do begin word := word + pc^; Inc(pc); end; if pc^<>#00 then begin //We eat the stop_char. We must do this with curly bracket, and even if it's space it's okay. if stop_char<>' ' then word := word + stop_char; Inc(pc); end; end; function IsKatakana(const ch: WideChar): boolean; inline; begin Result := (Word(ch)>=$30A0) and (Word(ch)<=$30FF); end; function IsHiragana(const ch: WideChar): boolean; inline; begin Result := (Word(ch)>=$3040) and (Word(ch)<=$309F); end; procedure ParseKanjidicLine(const s: UnicodeString; ed: PKanjidicEntry); var rclass: integer; pc: PWideChar; word: UnicodeString; pref: string; begin ed.Reset; rclass := 0; pc := PWideChar(integer(s)); //do not uniquestr on cast if pc=nil then exit; if not ReadNextWord(pc, ed.kanji) then raise EKanjidicParsingException.Create(eNoKanjiFieldInRecord); if not ReadNextWord(pc, word) then raise EKanjidicParsingException.Create(eNoJisFieldInRecord); ed.jis := string(word); //Rest is dynamic while ReadNextWord(pc, word) do begin if Length(word)<=0 then continue; pref := ''; //Meaning if word[1]='{' then begin if word[Length(word)]<>'}' then raise EKanjidicParsingException.Create(eBrokenMeaningBrakets); ed.AddMeaning(copy(word, 2, Length(word)-2)); end else //Readings if IsKatakana(word[1]) then ed.readings[rclass].AddOn(word) else if IsHiragana(word[1]) then ed.readings[rclass].AddKun(word) else //Reading class, e.g. T0, T1 if (Length(word)=2) and (word[1]='T') and (word[2]>='0') and (word[2]<='9') then begin rclass := Ord(word[2])-Ord('0'); if rclass>Length(ed.readings) then raise EKanjidicParsingException.CreateFmt(eUnsupportedReadingClass, [word]); end else //Normal field begin if word[1]='X' then begin { Cross-references are normal fields with added X at the start: N123 -> XN123 We remove X to parse keys uniformly, and then append it back. Note that some keys (i.e. J) have different meanings with crossrefs } delete(word,1,1); pref := 'X'; end; //Most field keys are 1-char, but some arent: //D* keys are two chars (there's a lot of second char versions and more plannet) if (word[1]='D') and (Length(word)>=2) then ed.AddField(pref+word[1]+word[2], copy(word, 3, Length(word)-2)) else //In addition to I keys there are IN if (word[1]='I') and (Length(word)>=2) and (word[2]='N') then ed.AddField(pref+word[1]+word[2], copy(word, 3, Length(word)-2)) else //MN and MP if (word[1]='M') and (Length(word)>=2) and ((word[2]='N') or (word[2]='P')) then ed.AddField(pref+word[1]+word[2], copy(word, 3, Length(word)-2)) else //ZPP, ZSP, ZBP, ZRP if (word[1]='Z') and (Length(word)>=3) and (word[3]='P') and ((word[2]='P') or (word[2]='S') or (word[2]='B') or (word[2]='R')) then ed.AddField(pref+word[1]+word[2]+word[3], copy(word, 4, Length(word)-3)) else ed.AddField(pref+word[1], copy(word, 2, Length(word)-1)); end; end; end; function ComposeKanjidicLine(ed: PKanjidicEntry): UnicodeString; var i, j: integer; begin Result := ed.kanji + ' ' + ed.jis; //Fields for i := 0 to ed.fields.Count-1 do for j := 0 to ed.fields[i].values.Count-1 do Result := Result + ' ' + ed.fields[i].key+ed.fields[i].values[j]; //Readings for i := 0 to Length(ed.readings)-1 do begin if (ed.readings[i].ons.Count<=0) and (ed.readings[i].kuns.Count<=0) then continue; if (i>0) then Result := Result + ' T'+IntToStr(i); for j := 0 to ed.readings[i].ons.Count-1 do Result := Result + ' ' + ed.readings[i].ons[j]; for j := 0 to ed.readings[i].kuns.Count-1 do Result := Result + ' ' + ed.readings[i].kuns[j]; end; //Meanings for i := 0 to ed.meanings.Count-1 do Result := Result + ' {' + ed.meanings[i] + '}'; end; end.
{*******************************************************} { } { Devgear PointMobile(BI-07) barcorder } { Copyright(c) 2017 Devgear, Inc. } { All rights reserved } { } {*******************************************************} // Author : Humphrey Kim(hjfactory@gmail.com) // Date : 2017.03 // Description // - 포인트 모바일 바코더 연동 라이브러리 // - Bluetooth, Blutooth admin 권한 줄 것(프로젝트 옵션) // History // - 2017.03 : Initial creation // ToDo // - 예외처리 보강 // - 컴포넌트화 // - Export Event 추가 unit PointMobileBluetoothChatService; interface uses System.SysUtils, System.Classes, Androidapi.JNI.PM3SDK_BI07, System.Bluetooth, System.Android.Bluetooth, Androidapi.JNI.Bluetooth, Androidapi.JNI.JavaTypes, Androidapi.Helpers, Androidapi.JNI.Widget, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Os, androidapi.JNIBridge; const MESSAGE_STATE_CHANGE = 1; MESSAGE_BARCODE = 2; MESSAGE_WRITE = 3; MESSAGE_DEVICE_NAME = 4; MESSAGE_SEND = 5; MESSAGE_TOAST = 6; MESSAGE_FAIL = 7; MESSAGE_SUCCESS = 8; MESSAGE_NOTRESP = 9; MESSAGE_FRAMEERROR = 10; MESSAGE_BTCANTABALIABLE = 11; MESSAGE_RECEIVEDEBUG = 12; MESSAGE_DISPLAY = 13; MESSAGE_WRITEDEBUG = 14; MESSAGE_BATCH = 15; MESSAGE_NFC = 16; MESSAGE_GPS_NMEA = 17; MESSAGE_KEY_EVENT = 18; MESSAGE_TIMER_END = 19; MESSAGE_NFC_SEND = 20; MESSAGE_KEY_STANDARD_EVENT = 21; STATE_NONE = 0; STATE_LISTEN = 1; STATE_CONNECTING = 2; STATE_CONNECTED = 3; type TReadBarcordEvent = procedure(AValue: string) of object; THandleMessageEvent = procedure(msg: JMessage) of object; TCharServiceHandlerCallback = class(TJavaLocal, JHandler_Callback) private FOnHandleMessage: THandleMessageEvent; public // 인터페이스 상속받은 메소드는 public에 둘 것 // private에 두면 Segmentation fault (11) 오류 발생 function handleMessage(msg: JMessage): Boolean; cdecl; property OnHandleMessage: THandleMessageEvent read FOnHandleMessage write FOnHandleMessage; end; TPointMobileBluetoothChatService = class private FBluetoothManager: TBluetoothManager; FBluetoothAdapter: TBluetoothAdapter; FBluetoothDevice: TBluetoothDevice; FOnReadBarcord: TReadBarcordEvent; procedure ProcessHandlerStateChage; procedure ProcessHandlerBarcord(AJObject: JObject; ALen: Integer); procedure DoReadBarcord(AValue: string); // strict private private FHandler: JHandler; FCallback: TCharServiceHandlerCallback; FChatService: JBluetoothChatService; public procedure InitBluetooth; procedure SetUpChatService; procedure ChatServiceHandleMessage(msg: JMessage); procedure ConnectChatService; procedure StartChatService; procedure RunScan; procedure ClearBluetooth; property OnReadBarcord: TReadBarcordEvent read FOnReadBarcord write FOnReadBarcord; end; function JObjectToStr(const AJObject: JObject): string; procedure ToastMessage(const AValue: string); implementation uses FMX.Helpers.Android, FMX.Types; function JObjectToStr(const AJObject: JObject): string; var LObj: ILocalObject; ObjID: Pointer; JBytes: TJavaArray<Byte>; JData: JString; begin Result := ''; if JStringToString(AJObject.getClass.getCanonicalName) <> 'byte[]' then Exit; if AJObject.QueryInterface(ILocalObject, LObj) = 0 then ObjID := LObj.GetObjectID else Exit; JBytes := TJavaArray<Byte>(WrapJNIArray(ObjID, TypeInfo(TJavaArray<Byte>))); JData := TJString.JavaClass.init(JBytes, 0, JBytes.Length); Result := JStringToString(JData); end; procedure ToastMessage(const AValue: string); var Toast: JToast; begin CallInUiThread(procedure begin Toast := TJToast.JavaClass.makeText(SharedActivityContext, StrToJCharSequence(AValue), TJToast.JavaClass.LENGTH_SHORT); Toast.show; end); end; { TCharServiceHandler } function TCharServiceHandlerCallback.handleMessage(msg: JMessage): Boolean; begin Result := True; if Assigned(FOnHandleMessage) then FOnHandleMessage(msg); end; { TPointMobileBluetoothChatService } procedure TPointMobileBluetoothChatService.ChatServiceHandleMessage( msg: JMessage); var DeviceName, JData: JString; begin Log.d(msg.what.ToString); case msg.what of MESSAGE_STATE_CHANGE: ProcessHandlerStateChage; MESSAGE_BARCODE: ProcessHandlerBarcord(msg.obj, msg.arg1); MESSAGE_DEVICE_NAME: begin DeviceName := msg.getData.getString(StringToJString('device_name')); Log.d('Device name: ' + JStringToString(DeviceName)); end; // 필요한 이벤트 추가 할 것 end; end; procedure TPointMobileBluetoothChatService.InitBluetooth; begin FBluetoothManager := TBluetoothManager.Current; if not (FBluetoothManager.ConnectionState = TBluetoothConnectionState.Connected) then Exit; Log.d('Connected Bluetooth: ' + FBluetoothManager.CurrentAdapter.AdapterName); FBluetoothAdapter := FBluetoothManager.CurrentAdapter; if not Assigned(FBluetoothAdapter) then begin Log.d('BlueTooth is not available'); Exit; end; end; procedure TPointMobileBluetoothChatService.ProcessHandlerBarcord( AJObject: JObject; ALen: Integer); var Data: string; begin Data := JObjectToStr(AJObject); DoReadBarcord(Data); end; procedure TPointMobileBluetoothChatService.ProcessHandlerStateChage; begin case FChatService.getState of STATE_NONE: ToastMessage('STATE_NONE'); STATE_LISTEN: ToastMessage('STATE_LISTEN'); STATE_CONNECTING: ToastMessage('STATE_CONNECTING'); STATE_CONNECTED: ToastMessage('STATE_CONNECTED'); end; end; procedure TPointMobileBluetoothChatService.SetupChatService; var Context: JContext; Looper: JLooper; begin if FBluetoothAdapter.State = TBluetoothAdapterState.Off then begin Log.d('Turn on bluetooth'); Exit; end; FCallback := TCharServiceHandlerCallback.Create; FCallback.OnHandleMessage := ChatServiceHandleMessage; Context := TAndroidHelper.Context; Looper := TJLooper.JavaClass.getMainLooper; FHandler := TJHandler.JavaClass.init(Looper, FCallback); FChatService := TJBluetoothChatService.JavaClass.init(Context, FHandler); TJSendCommand.JavaClass.SendCommandInit(FChatService, FHandler); end; procedure TPointMobileBluetoothChatService.ConnectChatService; var I: Integer; DeviceName: string; ChatServiceState: Integer; begin if FBluetoothAdapter.PairedDevices.Count = 0 then Exit; FBluetoothDevice := FBluetoothAdapter.PairedDevices[0] as TBluetoothDevice; FChatService.connectByAddress(StringToJString(FBluetoothDevice.Address)); end; procedure TPointMobileBluetoothChatService.StartChatService; begin if Assigned(FChatService) then begin if FChatService.getState = TJBluetoothChatService.JavaClass.STATE_NONE then FChatService.start; end; end; procedure TPointMobileBluetoothChatService.RunScan; var ResultCode: JPMSyncService_Result; begin if FChatService.getState <> TJBluetoothChatService.JavaClass.STATE_CONNECTED then begin ToastMessage('Not Conneted Bluetooth.'); Exit; end; ResultCode := TJSendCommand.JavaClass.ScanSetTrigger; if ResultCode = TJPMSyncService_Result.JavaClass.Fail then begin ToastMessage('Retry scan trigger'); ResultCode := TJSendCommand.JavaClass.ScanSetTrigger; if ResultCode = TJPMSyncService_Result.JavaClass.Fail then ToastMessage('Failed scan trigger'); end; end; procedure TPointMobileBluetoothChatService.ClearBluetooth; begin FBluetoothManager.DisposeOf; end; procedure TPointMobileBluetoothChatService.DoReadBarcord(AValue: string); begin TThread.Queue(nil, procedure begin if Assigned(FOnReadBarcord) then FOnReadBarcord(AValue); end); end; end.
unit AST.Pascal.ConstCalculator; interface uses System.SysUtils, System.Math, AST.Classes, AST.Delphi.Classes, AST.Parser.Errors, AST.Delphi.Operators, AST.Delphi.Errors, AST.Delphi.Intf; type TExpressionCalculator = record private fErrors: TASTDelphiErrors; fSysDecls: PDelphiSystemDeclarations; function CalcSets(const Left, Right: TIDConstant; Operation: TOperatorID): TIDConstant; function CalcPointer(LeftConst, RightConst: TIDConstant; Operation: TOperatorID): TIDConstant; function CalcInteger(LValue, RValue: Int64; Operation: TOperatorID): TIDConstant; function CalcFloat(LValue, RValue: Extended; Right: TIDExpression; Operation: TOperatorID): TIDConstant; function CalcBoolean(LValue, RValue: Boolean; Operation: TOperatorID): TIDConstant; function CalcString(const LValue, RValue: string; Operation: TOperatorID): TIDConstant; function CalcChar(const LValue, RValue: Char; Operation: TOperatorID): TIDConstant; function CalcIn(const Left, Right: TIDConstant): TIDConstant; function CalcDynArrays(const Left, Right: TIDConstant; Operation: TOperatorID): TIDConstant; property Sys: PDelphiSystemDeclarations read fSysDecls; public constructor Create(const Module: IASTDelphiUnit); function ProcessConstOperation(Left, Right: TIDExpression; Operation: TOperatorID): TIDExpression; overload; function ProcessConstOperation(const Left, Right: TIDConstant; Operation: TOperatorID): TIDConstant; overload; end; implementation uses AST.Delphi.System, AST.Pascal.Parser, AST.Delphi.DataTypes, AST.Parser.Utils, AST.Delphi.Parser; function AddSets(Left, Right: TIDSetConstant): TIDConstant; var LList, RList: TIDExpressions; begin LList := Left.Value; RList := Right.Value; // todo: remove duplicates Result := TIDSetConstant.CreateAsAnonymous(Left.Scope, Left.DataType, LList + RList); Result.TextPosition := Left.TextPosition; end; function SubtractSets(Left, Right: TIDSetConstant): TIDConstant; var LList, RList: TIDExpressions; begin LList := Left.Value; RList := Right.Value; // todo: implement substaction Result := TIDSetConstant.CreateAsAnonymous(Left.Scope, Left.DataType, LList); Result.TextPosition := Left.TextPosition; end; function TExpressionCalculator.CalcSets(const Left, Right: TIDConstant; Operation: TOperatorID): TIDConstant; function DynArrayToSetIfNeeded(const AConst: TIDConstant): TIDSetConstant; begin if AConst is TIDSetConstant then Result := TIDSetConstant(AConst) else begin var LExpressions := TIDDynArrayConstant(AConst).Value; var LSetDataType := TIDSet.CreateAsAnonymous(AConst.Scope, TIDOrdinal(Sys._UInt8)); Result := TIDSetConstant.CreateAsAnonymous(AConst.Scope, LSetDataType, LExpressions); Result.TextPosition := AConst.TextPosition; end; end; begin var ALeftSet := DynArrayToSetIfNeeded(Left); var ARightSet := DynArrayToSetIfNeeded(Right); case Operation of opEqual: Result := Sys._False; // todo: opNotEqual: Result := Sys._False; // todo: opAdd: Result := AddSets(ALeftSet, ARightSet); opSubtract: Result := SubtractSets(ALeftSet, ARightSet); opMultiply: Result := Left; // todo: else Result := nil; end; end; function TExpressionCalculator.ProcessConstOperation(const Left, Right: TIDConstant; Operation: TOperatorID): TIDConstant; ////////////////////////////////////////////////////////////// function CalcInteger(LValue, RValue: Int64; Operation: TOperatorID): TIDConstant; var iValue: Int64; fValue: Double; bValue: Boolean; DT: TIDType; begin case Operation of opAdd: iValue := LValue + RValue; opSubtract: iValue := LValue - RValue; opMultiply: iValue := LValue * RValue; opNegative: iValue := -RValue; opIntDiv, opDivide: begin if RValue = 0 then fErrors.DIVISION_BY_ZERO(Sys._EmptyStrExpression); if Operation = opIntDiv then iValue := LValue div RValue else begin fValue := LValue / RValue; Exit(TIDFloatConstant.CreateAsAnonymous(Left.Scope, Sys._Float64, fValue)); end; end; opEqual, opNotEqual, opGreater, opGreaterOrEqual, opLess, opLessOrEqual: begin case Operation of opEqual: bValue := (LValue = RValue); opNotEqual: bValue := (LValue <> RValue); opGreater: bValue := (LValue > RValue); opGreaterOrEqual: bValue := (LValue >= RValue); opLess: bValue := (LValue < RValue); opLessOrEqual: bValue := (LValue <= RValue); else bValue := False; end; Exit(TIDBooleanConstant.CreateAsAnonymous(Left.Scope, Sys._Boolean, bValue)); end; opAnd: iValue := LValue and RValue; opOr: iValue := LValue or RValue; opXor: iValue := LValue xor RValue; opNot: iValue := not RValue; opShiftLeft: iValue := LValue shl RValue; opShiftRight: iValue := LValue shr RValue; else Exit(nil); end; DT := Sys.DataTypes[GetValueDataType(iValue)]; Result := TIDIntConstant.CreateAsAnonymous(Left.Scope, DT, iValue); end; ////////////////////////////////////////////////////////////// function CalcFloat(LValue, RValue: Double; Operation: TOperatorID): TIDConstant; var fValue: Double; bValue: Boolean; ValueDT: TIDType; begin ValueDT := Sys._Float64; case Operation of opAdd: fValue := LValue + RValue; opSubtract: fValue := LValue - RValue; opMultiply: fValue := LValue * RValue; opDivide: begin if RValue = 0 then fErrors.DIVISION_BY_ZERO(Sys._EmptyStrExpression); fValue := LValue / RValue; end; opNegative: begin fValue := -RValue; ValueDT := Right.DataType; end; opEqual, opNotEqual, opGreater, opGreaterOrEqual, opLess, opLessOrEqual: begin case Operation of opEqual: bValue := LValue = RValue; opNotEqual: bValue := LValue <> RValue; opGreater: bValue := LValue > RValue; opGreaterOrEqual: bValue := LValue >= RValue; opLess: bValue := LValue < RValue; opLessOrEqual: bValue := LValue <= RValue; else bValue := False; end; Exit(TIDBooleanConstant.CreateAsAnonymous(Left.Scope, Sys._Boolean, bValue)); end; else Exit(nil); end; Result := TIDFloatConstant.CreateAsAnonymous(Left.Scope, ValueDT, fValue); Result.ExplicitDataType := ValueDT; end; ////////////////////////////////////////////////////////////// function CalcBoolean(LValue, RValue: Boolean; Operation: TOperatorID): TIDConstant; var Value: Boolean; begin case Operation of opAnd: Value := LValue and RValue; opOr: Value := LValue or RValue; opXor: Value := LValue xor RValue; opNot: Value := not RValue; else Exit(nil); end; Result := TIDBooleanConstant.Create(Left.Scope, Identifier(BoolToStr(Value, True)), Sys._Boolean, Value); end; ////////////////////////////////////////////////////////////// function CalcString(const LValue, RValue: string): TIDConstant; var sValue: string; bValue: Boolean; begin case Operation of opAdd: begin sValue := LValue + RValue; Result := TIDStringConstant.CreateAsAnonymous(Left.Scope, Sys._UnicodeString, sValue); end; opEqual, opNotEqual: begin case Operation of opEqual: bValue := LValue = RValue; opNotEqual: bValue := LValue <> RValue; else bValue := False; end; Exit(TIDBooleanConstant.CreateAsAnonymous(Left.Scope, Sys._Boolean, bValue)); end; else Exit(nil); end; end; /////////////////////////////////////////////////////////////// function CalcIn(const Left: TIDConstant; const Right: TIDRangeConstant): TIDConstant; var LB, HB: TIDConstant; bValue: Boolean; begin LB := TIDConstant(Right.Value.LBExpression.Declaration); HB := TIDConstant(Right.Value.HBExpression.Declaration); bValue := (Left.CompareTo(LB) >= 0) and (Left.CompareTo(HB) <= 0); Result := TIDBooleanConstant.CreateAsAnonymous(Left.Scope, Sys._Boolean, bValue); end; var LeftType, RightType: TClass; Constant: TIDConstant; begin LeftType := Left.ClassType; RightType := Right.ClassType; Constant := nil; if RightType = TIDRangeConstant then begin Constant := CalcIn(Left, TIDRangeConstant(Right)); end else if LeftType = TIDIntConstant then begin if RightType = TIDIntConstant then Constant := CalcInteger(TIDIntConstant(Left).Value, TIDIntConstant(Right).Value, Operation) else Constant := CalcFloat(TIDIntConstant(Left).Value, TIDFloatConstant(Right).Value, Operation) end else if LeftType = TIDFloatConstant then begin if RightType = TIDIntConstant then Constant := CalcFloat(TIDFloatConstant(Left).Value, TIDIntConstant(Right).Value, Operation) else Constant := CalcFloat(TIDFloatConstant(Left).Value, TIDFloatConstant(Right).Value, Operation) end else if LeftType = TIDStringConstant then begin if RightType = TIDStringConstant then Constant := CalcString(TIDStringConstant(Left).Value, TIDStringConstant(Right).Value) else Constant := CalcString(TIDStringConstant(Left).Value, TIDCharConstant(Right).Value) end else if LeftType = TIDCharConstant then begin if RightType = TIDCharConstant then Constant := CalcString(TIDCharConstant(Left).Value, TIDCharConstant(Right).Value) else Constant := CalcString(TIDCharConstant(Left).Value, TIDStringConstant(Right).Value) end else if LeftType = TIDBooleanConstant then Constant := CalcBoolean(TIDBooleanConstant(Left).Value, TIDBooleanConstant(Right).Value, Operation) else AbortWorkInternal('Invalid parameters', Left.SourcePosition); if not Assigned(Constant) then AbortWork('Operation %s not supported for constants', [OperatorFullName(Operation)], Left.SourcePosition); Result := Constant; end; function TExpressionCalculator.CalcPointer(LeftConst, RightConst: TIDConstant; Operation: TOperatorID): TIDConstant; begin // todo: if LeftConst is TIDPointerConstant then Exit(LeftConst) else Exit(RightConst); end; function TExpressionCalculator.CalcInteger(LValue, RValue: Int64; Operation: TOperatorID): TIDConstant; var iValue: Int64; fValue: Double; bValue: Boolean; DT: TIDType; begin case Operation of opAdd: iValue := LValue + RValue; opSubtract: iValue := LValue - RValue; opMultiply: iValue := LValue * RValue; opNegative: iValue := -RValue; opIntDiv, opDivide: begin {if RValue = 0 then TASTDelphiUnit.ERROR_DIVISION_BY_ZERO(Right);} if Operation = opIntDiv then iValue := LValue div RValue else begin fValue := LValue / RValue; Exit(TIDFloatConstant.CreateWithoutScope(Sys._Float64, fValue)); end; end; opEqual, opNotEqual, opGreater, opGreaterOrEqual, opLess, opLessOrEqual: begin case Operation of opEqual: bValue := (LValue = RValue); opNotEqual: bValue := (LValue <> RValue); opGreater: bValue := (LValue > RValue); opGreaterOrEqual: bValue := (LValue >= RValue); opLess: bValue := (LValue < RValue); opLessOrEqual: bValue := (LValue <= RValue); else bValue := False; end; Exit(TIDBooleanConstant.CreateWithoutScope(Sys._Boolean, bValue)); end; opAnd: iValue := LValue and RValue; opOr: iValue := LValue or RValue; opXor: iValue := LValue xor RValue; opNot: iValue := not RValue; opShiftLeft: iValue := LValue shl RValue; opShiftRight: iValue := LValue shr RValue; else Exit(nil); end; DT := Sys.DataTypes[GetValueDataType(iValue)]; Result := TIDIntConstant.CreateWithoutScope(DT, iValue); end; function TExpressionCalculator.CalcFloat(LValue, RValue: Extended; Right: TIDExpression; Operation: TOperatorID): TIDConstant; var fValue: Extended; bValue: Boolean; ValueDT: TIDType; begin ValueDT := Sys._Float64; case Operation of opAdd: fValue := LValue + RValue; opSubtract: fValue := LValue - RValue; opMultiply: fValue := LValue * RValue; opDivide: begin if RValue = 0 then begin if LValue = 0 then fValue := System.Math.NaN else if LValue < 0 then fValue := System.Math.NegInfinity else fValue := System.Math.Infinity; end else fValue := LValue / RValue; end; opNegative: begin fValue := -RValue; ValueDT := Right.DataType; end; opEqual, opNotEqual, opGreater, opGreaterOrEqual, opLess, opLessOrEqual: begin case Operation of opEqual: bValue := LValue = RValue; opNotEqual: bValue := LValue <> RValue; opGreater: bValue := LValue > RValue; opGreaterOrEqual: bValue := LValue >= RValue; opLess: bValue := LValue < RValue; opLessOrEqual: bValue := LValue <= RValue; else bValue := False; end; Exit(TIDBooleanConstant.CreateWithoutScope(Sys._Boolean, bValue)); end; else Exit(nil); end; Result := TIDFloatConstant.CreateWithoutScope(ValueDT, fValue); end; function TExpressionCalculator.CalcBoolean(LValue, RValue: Boolean; Operation: TOperatorID): TIDConstant; var Value: Boolean; begin case Operation of opAnd: Value := LValue and RValue; opOr: Value := LValue or RValue; opXor: Value := LValue xor RValue; opNot: Value := not RValue; else Exit(nil); end; Result := TIDBooleanConstant.CreateWithoutScope(Sys._Boolean, Value); end; function TExpressionCalculator.CalcString(const LValue, RValue: string; Operation: TOperatorID): TIDConstant; var sValue: string; bValue: Boolean; begin case Operation of opAdd: begin sValue := LValue + RValue; Result := TIDStringConstant.CreateWithoutScope(Sys._UnicodeString, sValue); end; opEqual, opNotEqual: begin case Operation of opEqual: bValue := LValue = RValue; opNotEqual: bValue := LValue <> RValue; else bValue := False; end; Exit(TIDBooleanConstant.CreateWithoutScope(Sys._Boolean, bValue)); end; else Exit(nil); end; end; function TExpressionCalculator.CalcChar(const LValue, RValue: Char; Operation: TOperatorID): TIDConstant; var sValue: string; bValue: Boolean; begin case Operation of opAdd: begin sValue := LValue + RValue; Result := TIDStringConstant.CreateWithoutScope(Sys._UnicodeString, sValue); end; opEqual, opNotEqual, opGreater, opGreaterOrEqual, opLess, opLessOrEqual: begin case Operation of opEqual: bValue := (LValue = RValue); opNotEqual: bValue := (LValue <> RValue); opGreater: bValue := (LValue > RValue); opGreaterOrEqual: bValue := (LValue >= RValue); opLess: bValue := (LValue < RValue); opLessOrEqual: bValue := (LValue <= RValue); else bValue := False; end; Exit(TIDBooleanConstant.CreateWithoutScope(Sys._Boolean, bValue)); end; else Exit(nil); end; end; function TExpressionCalculator.CalcIn(const Left, Right: TIDConstant): TIDConstant; begin if Right is TIDRangeConstant then begin var LRangeConstant := TIDRangeConstant(Right).Value; var LLoBnd := LRangeConstant.LBExpression.Declaration as TIDConstant; var LHiBnd := LRangeConstant.HBExpression.Declaration as TIDConstant; if (Left.CompareTo(LLoBnd) >= 0) and (Left.CompareTo(LHiBnd) <= 0) then Result := Sys._True else Result := Sys._False end else if Right is TIDDynArrayConstant then begin var LExpressions := TIDDynArrayConstant(Right).Value; for var LExpr in LExpressions do begin if Left.CompareTo(LExpr.AsConst) = 0 then begin Exit(Sys._True); end; end; Result := Sys._False; end else Result := nil; end; function TExpressionCalculator.CalcDynArrays(const Left, Right: TIDConstant; Operation: TOperatorID): TIDConstant; begin // todo: case Operation of opEqual: Result := TIDBooleanConstant.CreateAsAnonymous(Left.Scope, Sys._Boolean, False); opMultiply: Result := Left; // todo: else Result := nil; end; end; function TExpressionCalculator.ProcessConstOperation(Left, Right: TIDExpression; Operation: TOperatorID): TIDExpression; var L, R: TIDConstant; LeftType, RightType: TClass; Constant: TIDConstant; begin L := Left.Declaration as TIDConstant; R := Right.Declaration as TIDConstant; LeftType := L.ClassType; RightType := R.ClassType; Constant := nil; // todo: full refactor if Operation = opIn then Constant := CalcIn(L, R) else if LeftType = TIDIntConstant then begin if RightType = TIDIntConstant then Constant := CalcInteger(TIDIntConstant(L).Value, TIDIntConstant(R).Value, Operation) else Constant := CalcFloat(TIDIntConstant(L).Value, TIDFloatConstant(R).Value, Right, Operation) end else if LeftType = TIDFloatConstant then begin if RightType = TIDIntConstant then Constant := CalcFloat(TIDFloatConstant(L).Value, TIDIntConstant(R).Value, Right, Operation) else Constant := CalcFloat(TIDFloatConstant(L).Value, TIDFloatConstant(R).Value, Right, Operation) end else if LeftType = TIDStringConstant then begin if RightType = TIDStringConstant then Constant := CalcString(TIDStringConstant(L).Value, TIDStringConstant(R).Value, Operation) else Constant := CalcString(TIDStringConstant(L).Value, TIDCharConstant(R).Value, Operation) end else if LeftType = TIDCharConstant then begin if RightType = TIDCharConstant then Constant := CalcChar(TIDCharConstant(L).Value, TIDCharConstant(R).Value, Operation) else Constant := CalcString(TIDCharConstant(L).Value, TIDStringConstant(R).Value, Operation) end else if LeftType = TIDBooleanConstant then Constant := CalcBoolean(TIDBooleanConstant(L).Value, TIDBooleanConstant(R).Value, Operation) else if ((LeftType = TIDSetConstant) and (RightType = TIDSetConstant)) or ((LeftType = TIDSetConstant) and (RightType = TIDDynArrayConstant)) or ((LeftType = TIDDynArrayConstant) and (RightType = TIDSetConstant)) then begin Constant := CalcSets(L, R, Operation); end else if (LeftType = TIDDynArrayConstant) and (RightType = TIDDynArrayConstant) then begin Constant := CalcDynArrays(L, R, Operation); end else if (LeftType = TIDPointerConstant) or (RightType = TIDPointerConstant) then begin Constant := CalcPointer(L, R, Operation) end else AbortWorkInternal('Const Calc: invalid arguments', L.SourcePosition); if not Assigned(Constant) then AbortWork('Operation %s not supported for constants', [OperatorFullName(Operation)], L.SourcePosition); Result := TIDExpression.Create(Constant, Right.TextPosition); end; { TExpressionCalculator } constructor TExpressionCalculator.Create(const Module: IASTDelphiUnit); begin fSysDecls := Module.SystemDeclarations; fErrors := Module.Errors; end; end.
{ Clever Internet Suite Version 6.2 Copyright (C) 1999 - 2006 Clever Components www.CleverComponents.com } unit clSmtpServer; interface {$I clVer.inc} {$IFDEF DELPHI6} {$WARN SYMBOL_PLATFORM OFF} {$ENDIF} {$IFDEF DELPHI7} {$WARN UNSAFE_CODE OFF} {$WARN UNSAFE_TYPE OFF} {$WARN UNSAFE_CAST OFF} {$ENDIF} uses Classes, SysUtils, WinSock, clTcpServer, clSocket, clUserMgr, clMCUtils, clEncoder, clSspi, clSspiAuth; type TclSmtpUserAccountItem = class(TclUserAccountItem) private FEmail: string; public procedure Assign(Source: TPersistent); override; published property Email: string read FEmail write FEmail; end; TclSmtpUserAccountList = class(TclUserAccountList) private function GetItem(Index: Integer): TclSmtpUserAccountItem; procedure SetItem(Index: Integer; const Value: TclSmtpUserAccountItem); public function Add: TclSmtpUserAccountItem; function AccountByEmail(const AEmail: string): TclSmtpUserAccountItem; property Items[Index: Integer]: TclSmtpUserAccountItem read GetItem write SetItem; default; end; TclSmtpConnectionState = (csSmtpConnect, csSmtpHelo, csSmtpMail, csSmtpRcpt, csSmtpData); TclSmtpReceivingData = (rdSmtpCommand, rdSmtpUser, rdSmtpPassword, rdSmtpCramMD5, rdSmtpNTLM, rdSmtpData); TclSmtpMailFromAction = (mfAccept, mfReject); TclSmtpRcptToAction = (rtAddressOk, rtRelayDenied, rtBadAddress, rtForward, rtNotForward, rtTooManyAddresses, rtDisabled); TclSmtpMailDataAction = (mdNone, mdOk, mdMailBoxFull, mdSystemFull, mdProcessingError, mdTransactionFailed); TclSmtpCommandConnection = class(TclCommandConnection) private FConnectionState: TclSmtpConnectionState; FReceivingData: TclSmtpReceivingData; FUserName: string; FIsEHLO: Boolean; FIsAuthorized: Boolean; FCramMD5Key: string; FNTLMAuth: TclNtAuthServerSspi; FMailFrom: string; FRcptToList: TStrings; FRawData: TMemoryStream; procedure Reset; protected procedure DoDestroy; override; public constructor Create; procedure InitParams; property ConnectionState: TclSmtpConnectionState read FConnectionState; property ReceivingData: TclSmtpReceivingData read FReceivingData; property IsEHLO: Boolean read FIsEHLO; property IsAuthorized: Boolean read FIsAuthorized; property UserName: string read FUserName; property CramMD5Key: string read FCramMD5Key; property MailFrom: string read FMailFrom; property RcptToList: TStrings read FRcptToList; property RawData: TMemoryStream read FRawData; end; TclSmtpCommandHandler = procedure (AConnection: TclSmtpCommandConnection; const ACommand, AParams: string) of object; TclSmtpCommandInfo = class(TclTcpCommandInfo) private FHandler: TclSmtpCommandHandler; protected procedure Execute(AConnection: TclCommandConnection; AParams: TclTcpCommandParams); override; end; TclSmtpLoginAuthenticateEvent = procedure (Sender: TObject; AConnection: TclSmtpCommandConnection; Account: TclSmtpUserAccountItem; const APassword: string; var IsAuthorized, Handled: Boolean) of object; TclSmtpAuthAuthenticateEvent = procedure (Sender: TObject; AConnection: TclSmtpCommandConnection; Account: TclSmtpUserAccountItem; const AKey, AHash: string; var IsAuthorized, Handled: Boolean) of object; TclSmtpMailFromEvent = procedure (Sender: TObject; AConnection: TclSmtpCommandConnection; const AMailFrom: string; var Action: TclSmtpMailFromAction) of object; TclSmtpRecipientToEvent = procedure (Sender: TObject; AConnection: TclSmtpCommandConnection; const ARcptTo: string; var AForwardTo: string; var Action: TclSmtpRcptToAction) of object; TclSmtpMessageReceivedEvent = procedure (Sender: TObject; AConnection: TclSmtpCommandConnection; const ARecipient: string; IsFinalDelivery: Boolean; AMessage: TStrings; var Action: TclSmtpMailDataAction) of object; TclSmtpConnectionEvent = procedure (Sender: TObject; AConnection: TclSmtpCommandConnection) of object; TclSmtpDispatchMessageEvent = procedure (Sender: TObject; AConnection: TclSmtpCommandConnection; ARelayHeader: TStrings; AMessage: TStream; var Action: TclSmtpMailDataAction) of object; TclSmtpServer = class(TclTcpCommandServer) private FUserAccounts: TclSmtpUserAccountList; FUseAuth: Boolean; FSASLFlags: TclServerSaslFlags; FMaxRecipients: Integer; FHelpText: TStrings; FOnAuthAuthenticate: TclSmtpAuthAuthenticateEvent; FOnLoginAuthenticate: TclSmtpLoginAuthenticateEvent; FOnMailFrom: TclSmtpMailFromEvent; FOnRecipientTo: TclSmtpRecipientToEvent; FOnMessageReceived: TclSmtpMessageReceivedEvent; FOnStateChanged: TclSmtpConnectionEvent; FOnDispatchReceivedMessage: TclSmtpDispatchMessageEvent; procedure HandleNullCommand(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandleAUTH(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandleDATA(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandleEHLO(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandleHELO(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandleMAIL(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandleNOOP(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandleQUIT(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandleRCPT(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandleRSET(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandleSTARTTLS(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandleHELP(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandleEndCommand(AConnection: TclSmtpCommandConnection; const ACommand: string; AHandler: TclSmtpCommandHandler); procedure HandleUser(AConnection: TclSmtpCommandConnection; AData: TStream); procedure HandleUserEnd(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandlePassword(AConnection: TclSmtpCommandConnection; AData: TStream); procedure HandlePasswordEnd(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandleCramMD5(AConnection: TclSmtpCommandConnection; AData: TStream); procedure HandleCramMD5End(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandleNTLM(AConnection: TclSmtpCommandConnection; AData: TStream); procedure HandleNTLMEnd(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure HandleDataLine(AConnection: TclSmtpCommandConnection; AData: TStream); procedure HandleDataLineEnd(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); procedure RaiseBadSequenceError(const ACommand: string); procedure RaiseSyntaxError(const ACommand: string); procedure SetUserAccounts(const Value: TclSmtpUserAccountList); function GetCaseInsensitive: Boolean; procedure SetCaseInsensitive(const Value: Boolean); function LoginAuthenticate(AConnection: TclSmtpCommandConnection; Account: TclUserAccountItem; const APassword: string): Boolean; function CramMD5Authenticate(AConnection: TclSmtpCommandConnection; Account: TclUserAccountItem; const AKey, AHash: string): Boolean; function NtlmAuthenticate(AConnection: TclSmtpCommandConnection; Account: TclUserAccountItem): Boolean; procedure CheckAuthAbort(AConnection: TclSmtpCommandConnection; const AParams: string); overload; procedure CheckAuthAbort(AConnection: TclSmtpCommandConnection; AParams: TStream); overload; function IsRoutedMail(const AEmail: string): Boolean; function GetMessageID(AMessage: TStrings): string; procedure ChangeState(AConnection: TclSmtpCommandConnection; ANewState: TclSmtpConnectionState); procedure CheckTlsMode(AConnection: TclSmtpCommandConnection; const ACommand: string); procedure SetHelpText(const Value: TStrings); procedure FillDefaultHelpText; function GetAuthData(AConnection: TclSmtpCommandConnection; AEncoder: TclEncoder): string; function ProcessReceivedMessage(AConnection: TclSmtpCommandConnection; IsFinalDelivery: Boolean; ARecipientPos: Integer; AMessage: TStrings): TclSmtpMailDataAction; function DispatchReceivedMessage(AConnection: TclSmtpCommandConnection): TclSmtpMailDataAction; procedure FillRelayHeader(AConnection: TclSmtpCommandConnection; AHeader: TStrings); protected procedure AddSmtpCommand(const ACommand: string; AHandler: TclSmtpCommandHandler); procedure RegisterCommands; override; function GetNullCommand(const ACommand: string): TclTcpCommandInfo; override; procedure DoReadConnection(AConnection: TclCommandConnection; AData: TStream); override; procedure ProcessUnhandledError(AConnection: TclCommandConnection; AParams: TclTcpCommandParams; E: Exception); override; procedure DoProcessCommand(AConnection: TclCommandConnection; AInfo: TclTcpCommandInfo; AParams: TclTcpCommandParams); override; procedure DoAcceptConnection(AConnection: TclCommandConnection); override; function CreateDefaultConnection: TclCommandConnection; override; procedure DoDestroy; override; function GenCramMD5Key: string; virtual; function GenMessageID: string; virtual; procedure DoAuthAuthenticate(AConnection: TclSmtpCommandConnection; Account: TclSmtpUserAccountItem; const AKey, AHash: string; var IsAuthorized, Handled: Boolean); virtual; procedure DoLoginAuthenticate(AConnection: TclSmtpCommandConnection; Account: TclSmtpUserAccountItem; const APassword: string; var IsAuthorized, Handled: Boolean); virtual; procedure DoMailFrom(AConnection: TclSmtpCommandConnection; const AMailFrom: string; var Action: TclSmtpMailFromAction); virtual; procedure DoRecipientTo(AConnection: TclSmtpCommandConnection; const ARcptTo: string; var AForwardTo: string; var Action: TclSmtpRcptToAction); virtual; procedure DoMessageReceived(AConnection: TclSmtpCommandConnection; const ARecipient: string; IsFinalDelivery: Boolean; AMessage: TStrings; var Action: TclSmtpMailDataAction); virtual; procedure DoStateChanged(AConnection: TclSmtpCommandConnection); virtual; procedure DoDispatchReceivedMessage(AConnection: TclSmtpCommandConnection; ARelayHeader: TStrings; AMessage: TStream; var Action: TclSmtpMailDataAction); virtual; public constructor Create(AOwner: TComponent); override; published property Port default cDefaultSmtpPort; property UserAccounts: TclSmtpUserAccountList read FUserAccounts write SetUserAccounts; property CaseInsensitive: Boolean read GetCaseInsensitive write SetCaseInsensitive default True; property UseAuth: Boolean read FUseAuth write FUseAuth default True; property SASLFlags: TclServerSaslFlags read FSASLFlags write FSASLFlags default [ssUseLogin, ssUseCramMD5, ssUseNTLM]; property MaxRecipients: Integer read FMaxRecipients write FMaxRecipients default 100; property HelpText: TStrings read FHelpText write SetHelpText; property OnLoginAuthenticate: TclSmtpLoginAuthenticateEvent read FOnLoginAuthenticate write FOnLoginAuthenticate; property OnAuthAuthenticate: TclSmtpAuthAuthenticateEvent read FOnAuthAuthenticate write FOnAuthAuthenticate; property OnMailFrom: TclSmtpMailFromEvent read FOnMailFrom write FOnMailFrom; property OnRecipientTo: TclSmtpRecipientToEvent read FOnRecipientTo write FOnRecipientTo; property OnMessageReceived: TclSmtpMessageReceivedEvent read FOnMessageReceived write FOnMessageReceived; property OnStateChanged: TclSmtpConnectionEvent read FOnStateChanged write FOnStateChanged; property OnDispatchReceivedMessage: TclSmtpDispatchMessageEvent read FOnDispatchReceivedMessage write FOnDispatchReceivedMessage; end; procedure RaiseSmtpError(const ACommand, AMessage: string; ACode: Integer); implementation uses Windows, clMailMessage, clCryptUtils, clUtils, clTlsSocket{$IFDEF LOGGER}, clLogger{$ENDIF}; procedure RaiseSmtpError(const ACommand, AMessage: string; ACode: Integer); begin raise EclTcpCommandError.Create(ACommand, Format('%d %s', [ACode, AMessage]), ACode); end; { TclSmtpServer } procedure TclSmtpServer.AddSmtpCommand(const ACommand: string; AHandler: TclSmtpCommandHandler); var info: TclSmtpCommandInfo; begin info := TclSmtpCommandInfo.Create(); AddCommand(info); info.Name := ACommand; info.FHandler := AHandler; end; constructor TclSmtpServer.Create(AOwner: TComponent); begin inherited Create(AOwner); FUserAccounts := TclSmtpUserAccountList.Create(Self, TclSmtpUserAccountItem); FHelpText := TStringList.Create(); FillDefaultHelpText(); Port := cDefaultSmtpPort; ServerName := 'Clever Internet Suite SMTP service'; CaseInsensitive := True; UseAuth := True; SASLFlags := [ssUseLogin, ssUseCramMD5, ssUseNTLM]; MaxRecipients := 100; end; function TclSmtpServer.CreateDefaultConnection: TclCommandConnection; begin Result := TclSmtpCommandConnection.Create(); end; procedure TclSmtpServer.DoAcceptConnection(AConnection: TclCommandConnection); begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end; {$ENDIF} {$ENDIF} inherited DoAcceptConnection(AConnection); SendResponse(AConnection, '', '220 ' + GetLocalHost() + ' ' + ServerName + '; ' + DateTimeToMailTime(Now())); end; procedure TclSmtpServer.RegisterCommands; begin AddSmtpCommand('EHLO', HandleEHLO); AddSmtpCommand('HELO', HandleHELO); AddSmtpCommand('AUTH', HandleAUTH); AddSmtpCommand('NOOP', HandleNOOP); AddSmtpCommand('QUIT', HandleQUIT); AddSmtpCommand('RSET', HandleRSET); AddSmtpCommand('MAIL', HandleMAIL); AddSmtpCommand('RCPT', HandleRCPT); AddSmtpCommand('DATA', HandleDATA); AddSmtpCommand('HELP', HandleHELP); AddSmtpCommand('STARTTLS', HandleSTARTTLS); end; procedure TclSmtpServer.RaiseBadSequenceError(const ACommand: string); begin RaiseSmtpError(ACommand, 'Bad sequence of commands', 503); end; procedure TclSmtpServer.HandleEHLO(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); var s: string; begin if (AConnection.ConnectionState <> csSmtpConnect) then begin RaiseBadSequenceError(ACommand); end; s := Trim(AParams); if (s = '') then begin RaiseSmtpError(ACommand, 'EHLO requires domain address', 501); end; ChangeState(AConnection, csSmtpHelo); AConnection.FIsEHLO := True; if (not UseAuth) then begin AConnection.FIsAuthorized := True; end; SendResponse(AConnection, ACommand, '250-%s Hello %s, pleased to meet you', [GetLocalHost(), s]); if UseAuth then begin s := ''; if (ssUseLogin in SASLFlags) then begin s := s + 'LOGIN '; end; if (ssUseCramMD5 in SASLFlags) then begin s := s + 'CRAM-MD5 '; end; if (ssUseNTLM in SASLFlags) then begin s := s + 'NTLM '; end; if (s <> '') then begin s := system.Copy(s, 1, Length(s) - 1); end; if (s <> '') then begin SendResponse(AConnection, ACommand, '250-AUTH %s', [s]); SendResponse(AConnection, ACommand, '250-AUTH=%s', [s]); end; end; if (UseTLS <> stNone) and (not AConnection.IsTls) then begin SendResponse(AConnection, ACommand, '250-STARTTLS'); end; SendResponse(AConnection, ACommand, '250 HELP'); end; procedure TclSmtpServer.HandleHELO(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); var s: string; begin if (AConnection.ConnectionState <> csSmtpConnect) then begin RaiseBadSequenceError(ACommand); end; s := Trim(AParams); if (s = '') then begin RaiseSmtpError(ACommand, 'HELO requires domain address', 501); end; ChangeState(AConnection, csSmtpHelo); if (not UseAuth) then begin AConnection.FIsAuthorized := True; end; SendResponse(AConnection, ACommand, '250 %s Hello %s, pleased to meet you', [GetLocalHost(), s]); end; procedure TclSmtpServer.CheckAuthAbort(AConnection: TclSmtpCommandConnection; const AParams: string); begin if (Trim(AParams) = '*') then begin AConnection.InitParams(); AConnection.FConnectionState := csSmtpHelo; RaiseSmtpError('AUTH', 'Authentication aborted', 501); end; end; procedure TclSmtpServer.CheckAuthAbort(AConnection: TclSmtpCommandConnection; AParams: TStream); var s: string; begin AParams.Position := 0; SetLength(s, AParams.Size); AParams.Read(PChar(s)^, AParams.Size); CheckAuthAbort(AConnection, s); end; procedure TclSmtpServer.HandleUser(AConnection: TclSmtpCommandConnection; AData: TStream); begin AConnection.BeginWork(); try AConnection.RawData.LoadFromStream(AData); finally AConnection.EndWork(); end; AConnection.FReceivingData := rdSmtpPassword; HandleEndCommand(AConnection, 'AUTH', HandleUserEnd); end; procedure TclSmtpServer.HandlePassword(AConnection: TclSmtpCommandConnection; AData: TStream); begin AConnection.BeginWork(); try AConnection.RawData.LoadFromStream(AData); finally AConnection.EndWork(); end; AConnection.FReceivingData := rdSmtpCommand; HandleEndCommand(AConnection, 'AUTH', HandlePasswordEnd); end; procedure TclSmtpServer.HandleCramMD5(AConnection: TclSmtpCommandConnection; AData: TStream); begin AConnection.BeginWork(); try AConnection.RawData.LoadFromStream(AData); finally AConnection.EndWork(); end; AConnection.FReceivingData := rdSmtpCommand; HandleEndCommand(AConnection, 'AUTH', HandleCramMD5End); end; procedure TclSmtpServer.HandleDataLine(AConnection: TclSmtpCommandConnection; AData: TStream); var s: string; len: Integer; begin AConnection.BeginWork(); try AConnection.RawData.CopyFrom(AData, 0); finally AConnection.EndWork(); end; try len := AConnection.RawData.Size; if (len > 4) then begin len := 5; end; AConnection.RawData.Position := AConnection.RawData.Size - len; SetLength(s, len); AConnection.RawData.Read(PChar(s)^, len); if CheckForEndOfData(s) then begin AConnection.RawData.Size := AConnection.RawData.Size - 3; AConnection.FReceivingData := rdSmtpCommand; HandleEndCommand(AConnection, 'DATA', HandleDataLineEnd); end; finally AConnection.RawData.Position := AConnection.RawData.Size; end; end; procedure TclSmtpServer.DoMessageReceived(AConnection: TclSmtpCommandConnection; const ARecipient: string; IsFinalDelivery: Boolean; AMessage: TStrings; var Action: TclSmtpMailDataAction); begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'DoMessageReceived');{$ENDIF} if Assigned(OnMessageReceived) then begin OnMessageReceived(Self, AConnection, ARecipient, IsFinalDelivery, AMessage, Action); end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'DoMessageReceived'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'DoMessageReceived', E); raise; end; end;{$ENDIF} end; procedure TclSmtpServer.DoLoginAuthenticate(AConnection: TclSmtpCommandConnection; Account: TclSmtpUserAccountItem; const APassword: string; var IsAuthorized, Handled: Boolean); begin if Assigned(OnLoginAuthenticate) then begin OnLoginAuthenticate(Self, AConnection, Account, APassword, IsAuthorized, handled); end; end; procedure TclSmtpServer.DoAuthAuthenticate(AConnection: TclSmtpCommandConnection; Account: TclSmtpUserAccountItem; const AKey, AHash: string; var IsAuthorized, Handled: Boolean); begin if Assigned(OnAuthAuthenticate) then begin OnAuthAuthenticate(Self, AConnection, Account, AKey, AHash, IsAuthorized, handled); end; end; function TclSmtpServer.LoginAuthenticate(AConnection: TclSmtpCommandConnection; Account: TclUserAccountItem; const APassword: string): Boolean; var handled: Boolean; begin handled := False; Result := False; DoLoginAuthenticate(AConnection, TclSmtpUserAccountItem(Account), APassword, Result, handled); if (not handled) and (Account <> nil) then begin Result := Account.Authenticate(APassword); end; end; function TclSmtpServer.CramMD5Authenticate(AConnection: TclSmtpCommandConnection; Account: TclUserAccountItem; const AKey, AHash: string): Boolean; var handled: Boolean; calculated: string; begin handled := False; Result := False; DoAuthAuthenticate(AConnection, TclSmtpUserAccountItem(Account), AKey, AHash, Result, handled); if (not handled) and (Account <> nil) then begin calculated := HMAC_MD5(AKey, Account.Password); Result := (calculated = AHash); end; end; function TclSmtpServer.GenCramMD5Key: string; begin Result := GenerateCramMD5Key(); end; function TclSmtpServer.GenMessageID: string; begin Result := GenerateMessageID(); end; procedure TclSmtpServer.HandleAUTH(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); var encoder: TclEncoder; method: string; s: string; begin CheckTlsMode(AConnection, ACommand); if AConnection.IsAuthorized or (not AConnection.IsEHLO) then begin RaiseBadSequenceError(ACommand); end; if not UseAuth then begin RaiseBadSequenceError(ACommand); end; encoder := TclEncoder.Create(nil); try encoder.SuppressCrlf := True; method := UpperCase(Trim(AParams)); if (method = 'LOGIN') and (ssUseLogin in SASLFlags) then begin encoder.EncodeString('Username:', s, cmMIMEBase64); AConnection.FReceivingData := rdSmtpUser; SendResponse(AConnection, ACommand, '334 ' + s); end else if (method = 'CRAM-MD5') and (ssUseCramMD5 in SASLFlags) then begin AConnection.FCramMD5Key := GenCramMD5Key(); encoder.EncodeString(AConnection.CramMD5Key, s, cmMIMEBase64); AConnection.FReceivingData := rdSmtpCramMD5; SendResponse(AConnection, ACommand, '334 ' + s); end else if (system.Pos('NTLM', method) = 1) and (ssUseNTLM in SASLFlags) then begin AConnection.FNTLMAuth.Free(); AConnection.FNTLMAuth := TclNtAuthServerSspi.Create(); AConnection.FReceivingData := rdSmtpNTLM; s := system.Copy(method, Length('NTLM ') + 1, Length(method)); s := Trim(s); if (s <> '') then begin AConnection.BeginWork(); try AConnection.RawData.Size := 0; AConnection.RawData.Position := 0; AConnection.RawData.Read(PChar(s)^, Length(s)); finally AConnection.EndWork(); end; HandleNTLMEnd(AConnection, ACommand, AParams); end else begin SendResponse(AConnection, ACommand, '334'); end; end else begin RaiseSmtpError(ACommand, 'Unrecognized authentication type', 504); end; finally encoder.Free(); end; end; procedure TclSmtpServer.HandleNOOP(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); begin SendResponse(AConnection, ACommand, '250 OK'); end; procedure TclSmtpServer.HandleQUIT(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); begin try SendResponse(AConnection, ACommand, '221 %s closing connection', [GetLocalHost()]); AConnection.Close(False); except on EclSocketError do ; end; end; procedure TclSmtpServer.HandleRCPT(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); var ind: Integer; name, email, forwardTo: string; action: TclSmtpRcptToAction; isRouted: Boolean; begin CheckTlsMode(AConnection, ACommand); if not (AConnection.ConnectionState in [csSmtpMail, csSmtpRcpt]) then begin RaiseBadSequenceError(ACommand); end; ind := system.Pos('TO:', UpperCase(AParams)); if (ind = 0) then begin RaiseSyntaxError(ACommand); end; GetEmailAddressParts(system.Copy(AParams, ind + Length('TO:'), 1000), name, email); if (email <> '') then begin action := rtAddressOk; isRouted := IsRoutedMail(email); if (AConnection.RcptToList.Count >= MaxRecipients) then begin action := rtTooManyAddresses; end else if isRouted then begin action := rtRelayDenied; end else if (UserAccounts.AccountByEmail(email) = nil) and (not AConnection.IsAuthorized) then begin action := rtRelayDenied; end; end else begin action := rtBadAddress; end; DoRecipientTo(AConnection, email, forwardTo, action); case action of rtAddressOk: begin ChangeState(AConnection, csSmtpRcpt); AConnection.FRcptToList.Add(email); SendResponse(AConnection, ACommand, '250 <%s> Recipient ok', [email]); end; rtForward: begin ChangeState(AConnection, csSmtpRcpt); AConnection.FRcptToList.Add(forwardTo); SendResponse(AConnection, ACommand, '250 <%s> Recipient ok', [email]); end; rtRelayDenied: RaiseSmtpError(ACommand, Format('<%s> Relay denied', [email]), 550); rtNotForward: RaiseSmtpError(ACommand, Format('<%s> User not local; please try <%s>', [email, forwardTo]), 551); rtTooManyAddresses: RaiseSmtpError(ACommand, 'Too many recipients', 452); rtDisabled: RaiseSmtpError(ACommand, Format('<%s> Account disabled', [email]), 550); else RaiseSmtpError(ACommand, Format('<%s> Invalid address', [email]), 500); end; end; function TclSmtpServer.IsRoutedMail(const AEmail: string): Boolean; function GetSymbolCount(const AStr, ASymbol: string): Integer; var i: Integer; begin Result := 0; for i := 1 to Length(AStr) do begin if (AStr[i] = ASymbol) then begin Inc(Result); end; end; end; begin Result := (GetSymbolCount(AEmail, '@') > 1); end; procedure TclSmtpServer.HandleMAIL(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); var ind: Integer; name, email: string; action: TclSmtpMailFromAction; isRouted: Boolean; begin //UseAuth CheckTlsMode(AConnection, ACommand); if (AConnection.ConnectionState <> csSmtpHelo) then begin RaiseBadSequenceError(ACommand); end; ind := system.Pos('FROM:', UpperCase(AParams)); if (ind = 0) then begin RaiseSyntaxError(ACommand); end; GetEmailAddressParts(system.Copy(AParams, ind + Length('FROM:'), 1000), name, email); action := mfAccept; isRouted := IsRoutedMail(email); if isRouted then begin action := mfReject; end; DoMailFrom(AConnection, email, action); if (action = mfAccept) then begin ChangeState(AConnection, csSmtpMail); AConnection.FMailFrom := email; SendResponse(AConnection, ACommand, '250 <%s> Sender ok', [email]); end else if isRouted then begin RaiseSmtpError(ACommand, 'This server does not accept routed mail', 553); end else begin RaiseSmtpError(ACommand, Format('<%s> Sender not permitted', [email]), 553); end; end; procedure TclSmtpServer.HandleDATA(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); begin CheckTlsMode(AConnection, ACommand); if (AConnection.ConnectionState <> csSmtpRcpt) then begin RaiseBadSequenceError(ACommand); end; ChangeState(AConnection, csSmtpData); AConnection.FReceivingData := rdSmtpData; AConnection.RawData.Clear(); SendResponse(AConnection, ACommand, '354 Start mail input, end with <CRLF>.<CRLF>'); end; procedure TclSmtpServer.HandleRSET(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); begin CheckTlsMode(AConnection, ACommand); AConnection.Reset(); if (AConnection.ConnectionState <> csSmtpConnect) then begin ChangeState(AConnection, csSmtpHelo); end; SendResponse(AConnection, ACommand, '250 Reset state'); end; procedure TclSmtpServer.DoReadConnection(AConnection: TclCommandConnection; AData: TStream); var connection: TclSmtpCommandConnection; begin connection := (AConnection as TclSmtpCommandConnection); case connection.ReceivingData of rdSmtpUser: HandleUser(connection, AData); rdSmtpPassword: HandlePassword(connection, AData); rdSmtpCramMD5: HandleCramMD5(connection, AData); rdSmtpNTLM: HandleNTLM(connection, AData); rdSmtpData: HandleDataLine(connection, AData); else inherited DoReadConnection(connection, AData); end; end; procedure TclSmtpServer.SetUserAccounts(const Value: TclSmtpUserAccountList); begin FUserAccounts.Assign(Value); end; function TclSmtpServer.GetCaseInsensitive: Boolean; begin Result := FUserAccounts.CaseInsensitive; end; procedure TclSmtpServer.SetCaseInsensitive(const Value: Boolean); begin FUserAccounts.CaseInsensitive := Value; end; procedure TclSmtpServer.RaiseSyntaxError(const ACommand: string); begin RaiseSmtpError(ACommand, 'Syntax error in parameters or arguments', 501); end; procedure TclSmtpServer.DoMailFrom(AConnection: TclSmtpCommandConnection; const AMailFrom: string; var Action: TclSmtpMailFromAction); begin if Assigned(OnMailFrom) then begin OnMailFrom(Self, AConnection, AMailFrom, Action); end; end; procedure TclSmtpServer.DoRecipientTo(AConnection: TclSmtpCommandConnection; const ARcptTo: string; var AForwardTo: string; var Action: TclSmtpRcptToAction); begin if Assigned(OnRecipientTo) then begin OnRecipientTo(Self, AConnection, ARcptTo, AForwardTo, Action); end; end; procedure TclSmtpServer.DoDestroy; begin FHelpText.Free(); FUserAccounts.Free(); inherited DoDestroy(); end; function TclSmtpServer.GetMessageID(AMessage: TStrings): string; var fieldList: TStrings; begin fieldList := TStringList.Create(); try GetHeaderFieldList(0, AMessage, fieldList); Result := GetHeaderFieldValue(AMessage, fieldList, 'Message-ID'); finally fieldList.Free(); end; end; procedure TclSmtpServer.ChangeState(AConnection: TclSmtpCommandConnection; ANewState: TclSmtpConnectionState); begin if (AConnection.ConnectionState <> ANewState) then begin AConnection.FConnectionState := ANewState; DoStateChanged(AConnection); end; end; procedure TclSmtpServer.DoStateChanged(AConnection: TclSmtpCommandConnection); begin if Assigned(OnStateChanged) then begin OnStateChanged(Self, AConnection); end; end; function TclSmtpServer.GetNullCommand(const ACommand: string): TclTcpCommandInfo; var info: TclSmtpCommandInfo; begin info := TclSmtpCommandInfo.Create(); info.Name := ACommand; info.FHandler := HandleNullCommand; Result := info; end; procedure TclSmtpServer.HandleNullCommand(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); begin RaiseSmtpError(ACommand, 'Syntax error, command unrecognized: ' + ACommand, 500); end; procedure TclSmtpServer.HandleEndCommand(AConnection: TclSmtpCommandConnection; const ACommand: string; AHandler: TclSmtpCommandHandler); var info: TclSmtpCommandInfo; params: TclTcpCommandParams; begin {$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'HandleEndCommand, command: %s ', nil, [ACommand]);{$ENDIF} info := nil; params := nil; try info := TclSmtpCommandInfo.Create(); params := TclTcpCommandParams.Create(); info.Name := ACommand; info.FHandler := AHandler; ProcessCommand(AConnection, info, params); finally params.Free(); info.Free(); end; end; function TclSmtpServer.GetAuthData(AConnection: TclSmtpCommandConnection; AEncoder: TclEncoder): string; var s: string; begin AConnection.RawData.Position := 0; SetLength(s, AConnection.RawData.Size); AConnection.RawData.Read(PChar(s)^, AConnection.RawData.Size); try Result := ''; AEncoder.DecodeString(Trim(s), Result, cmMIMEBase64); except on EclEncoderError do begin CheckAuthAbort(AConnection, '*'); end; end; end; procedure TclSmtpServer.HandleUserEnd(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); var encoder: TclEncoder; s: string; begin CheckAuthAbort(AConnection, AConnection.RawData); encoder := TclEncoder.Create(nil); try AConnection.FUserName := GetAuthData(AConnection, encoder); encoder.EncodeString('Password:', s, cmMIMEBase64); SendResponse(AConnection, ACommand, '334 ' + s); finally encoder.Free(); end; end; procedure TclSmtpServer.HandlePasswordEnd(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); var encoder: TclEncoder; psw: string; begin CheckAuthAbort(AConnection, AConnection.RawData); encoder := TclEncoder.Create(nil); try psw := GetAuthData(AConnection, encoder); if not LoginAuthenticate(AConnection, UserAccounts.AccountByUserName(AConnection.UserName), psw) then begin RaiseSmtpError(ACommand, 'Authentication failed', 535); end; AConnection.FIsAuthorized := True; SendResponse(AConnection, ACommand, '235 Authentication successful'); finally encoder.Free(); end; end; procedure TclSmtpServer.HandleCramMD5End(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); var encoder: TclEncoder; hash: string; begin CheckAuthAbort(AConnection, AConnection.RawData); encoder := TclEncoder.Create(nil); try encoder.SuppressCrlf := True; hash := GetAuthData(AConnection, encoder); if (WordCount(hash, [' ']) <> 2) then begin CheckAuthAbort(AConnection, '*'); end; AConnection.FUserName := ExtractWord(1, hash, [' ']); hash := ExtractWord(2, hash, [' ']); if not CramMD5Authenticate(AConnection, UserAccounts.AccountByUserName(AConnection.UserName), AConnection.CramMD5Key, hash) then begin RaiseSmtpError(ACommand, 'Authentication failed', 535); end; AConnection.FIsAuthorized := True; SendResponse(AConnection, ACommand, '235 Authentication successful'); finally encoder.Free(); end; end; procedure TclSmtpServer.HandleNTLM(AConnection: TclSmtpCommandConnection; AData: TStream); begin AConnection.BeginWork(); try AConnection.RawData.LoadFromStream(AData); finally AConnection.EndWork(); end; HandleEndCommand(AConnection, 'AUTH', HandleNTLMEnd); end; procedure TclSmtpServer.HandleNTLMEnd( AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); var buf: TStream; encoder: TclEncoder; challenge: string; begin CheckAuthAbort(AConnection, AConnection.RawData); try encoder := nil; buf := nil; try encoder := TclEncoder.Create(nil); encoder.SuppressCrlf := True; buf := TMemoryStream.Create(); AConnection.RawData.Position := 0; encoder.DecodeStream(AConnection.RawData, buf, cmMIMEBase64); buf.Position := 0; if AConnection.FNTLMAuth.GenChallenge('NTLM', buf, nil) then begin AConnection.FNTLMAuth.ImpersonateUser(); try AConnection.FUserName := GetCurrentThreadUser(); if not NtlmAuthenticate(AConnection, UserAccounts.AccountByUserName(AConnection.UserName)) then begin AConnection.FUserName := ''; RaiseSmtpError(ACommand, 'Authentication failed', 535); end; finally AConnection.FNTLMAuth.RevertUser(); end; AConnection.FReceivingData := rdSmtpCommand; AConnection.FIsAuthorized := True; SendResponse(AConnection, ACommand, '235 Authentication successful'); end else begin buf.Position := 0; challenge := ''; encoder.EncodeToString(buf, challenge, cmMIMEBase64); SendResponse(AConnection, ACommand, '334 ' + challenge); end; finally buf.Free(); encoder.Free(); end; except on EclEncoderError do CheckAuthAbort(AConnection, '*'); on EclSSPIError do CheckAuthAbort(AConnection, '*'); end; end; procedure TclSmtpServer.FillRelayHeader(AConnection: TclSmtpCommandConnection; AHeader: TStrings); begin AHeader.Add(Format('Received: from %s [%s]', [AConnection.PeerName, AConnection.PeerIP])); AHeader.Add(Format(#9'by %s [%s]', [GetLocalHost(), GetHostIP(GetLocalHost())])); AHeader.Add(Format(#9'with SMTP (%s)', [ServerName])); AHeader.Add(#9'for'); end; function TclSmtpServer.ProcessReceivedMessage(AConnection: TclSmtpCommandConnection; IsFinalDelivery: Boolean; ARecipientPos: Integer; AMessage: TStrings): TclSmtpMailDataAction; var i: Integer; s: string; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'ProcessReceivedMessage');{$ENDIF} Result := mdOk; i := 0; while (i < AConnection.RcptToList.Count) and (Result = mdOk) do begin s := AConnection.RcptToList[i]; if IsFinalDelivery = (UserAccounts.AccountByEmail(s) <> nil) then begin AMessage[ARecipientPos] := Format(#9'for <%s>; %s', [s, DateTimeToMailTime(Now())]); DoMessageReceived(AConnection, s, IsFinalDelivery, AMessage, Result); end; Inc(i); end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'ProcessReceivedMessage'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'ProcessReceivedMessage', E); raise; end; end;{$ENDIF} end; procedure TclSmtpServer.DoDispatchReceivedMessage(AConnection: TclSmtpCommandConnection; ARelayHeader: TStrings; AMessage: TStream; var Action: TclSmtpMailDataAction); begin if Assigned(OnDispatchReceivedMessage) then begin OnDispatchReceivedMessage(Self, AConnection, ARelayHeader, AMessage, Action); end; end; function TclSmtpServer.DispatchReceivedMessage(AConnection: TclSmtpCommandConnection): TclSmtpMailDataAction; var msg: TStrings; messageID: string; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'DispatchReceivedMessage');{$ENDIF} msg := TStringList.Create(); try FillRelayHeader(AConnection, msg); Result := mdNone; DoDispatchReceivedMessage(AConnection, msg, AConnection.RawData, Result); if (Result = mdNone) then begin AConnection.RawData.Position := 0; AddTextStream(msg, AConnection.RawData, False, BatchSize); messageID := GetMessageID(msg); if (messageID = '') then begin messageID := GenMessageID(); msg.Insert(4, 'Message-ID: ' + messageID); end; Result := ProcessReceivedMessage(AConnection, False, 3, msg); if (Result = mdOk) then begin msg.Insert(0, 'Return-path: <' + AConnection.MailFrom + '>'); Result := ProcessReceivedMessage(AConnection, True, 4, msg); end; end; finally msg.Free(); end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'DispatchReceivedMessage'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'DispatchReceivedMessage', E); raise; end; end;{$ENDIF} end; procedure TclSmtpServer.HandleDataLineEnd(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'HandleDataLineEnd');{$ENDIF} ChangeState(AConnection, csSmtpHelo); try case DispatchReceivedMessage(AConnection) of mdOk: SendResponse(AConnection, ACommand, '250 Ok'); mdMailBoxFull: RaiseSmtpError(ACommand, 'Requested mail action aborted: exceeded storage allocation', 552); mdSystemFull: RaiseSmtpError(ACommand, 'Requested action not taken: insufficient system storage', 452); mdProcessingError: RaiseSmtpError(ACommand, 'Requested action aborted: error in processing', 451); else RaiseSmtpError(ACommand, 'Transaction failed', 554); end; finally AConnection.Reset(); end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'HandleDataLineEnd'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'HandleDataLineEnd', E); raise; end; end;{$ENDIF} end; procedure TclSmtpServer.ProcessUnhandledError(AConnection: TclCommandConnection; AParams: TclTcpCommandParams; E: Exception); begin SendResponse(AConnection, AParams.Command, '451 Requested action aborted: ' + Trim(E.Message)); end; procedure TclSmtpServer.DoProcessCommand(AConnection: TclCommandConnection; AInfo: TclTcpCommandInfo; AParams: TclTcpCommandParams); begin AConnection.BeginWork(); try inherited DoProcessCommand(AConnection, AInfo, AParams); finally AConnection.EndWork(); end; end; procedure TclSmtpServer.HandleSTARTTLS(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); begin if (UseTLS = stNone) then begin RaiseSmtpError(ACommand, 'TLS not available', 454); end; if (UseTLS = stImplicit) or AConnection.IsTls then begin RaiseSmtpError(ACommand, 'connection is already secured', 454); end; SendResponse(AConnection, ACommand, '220 please start a TLS connection'); AConnection.InitParams(); StartTls(AConnection); end; procedure TclSmtpServer.CheckTlsMode(AConnection: TclSmtpCommandConnection; const ACommand: string); begin if (UseTLS = stExplicitRequire) and (not AConnection.IsTls) then begin RaiseSmtpError(ACommand, 'Must issue a STARTTLS command first', 530); end; end; procedure TclSmtpServer.HandleHELP(AConnection: TclSmtpCommandConnection; const ACommand, AParams: string); var i: Integer; list: TStrings; begin list := TStringList.Create(); AddMultipleLines(AConnection, list); list.Assign(HelpText); for i := 0 to list.Count - 1 do begin list[i] := '214-' + list[i]; end; SendMultipleLines(AConnection, '214 End Of Help', True); end; procedure TclSmtpServer.SetHelpText(const Value: TStrings); begin FHelpText.Assign(Value); end; procedure TclSmtpServer.FillDefaultHelpText; begin HelpText.Add('Commands Supported:'); HelpText.Add('HELO EHLO AUTH HELP QUIT MAIL NOOP RSET RCPT DATA STARTTLS'); end; function TclSmtpServer.NtlmAuthenticate( AConnection: TclSmtpCommandConnection; Account: TclUserAccountItem): Boolean; var handled: Boolean; begin handled := False; Result := True; DoAuthAuthenticate(AConnection, TclSmtpUserAccountItem(Account), '', '', Result, handled); end; { TclSmtpCommandConnection } constructor TclSmtpCommandConnection.Create; begin inherited Create(); FRcptToList := TStringList.Create(); FRawData := TMemoryStream.Create(); InitParams(); end; procedure TclSmtpCommandConnection.Reset; begin FMailFrom := ''; FRcptToList.Clear(); FRawData.Clear(); end; procedure TclSmtpCommandConnection.DoDestroy; begin FNTLMAuth.Free(); FRawData.Free(); FRcptToList.Free(); inherited DoDestroy(); end; procedure TclSmtpCommandConnection.InitParams; begin FIsAuthorized := False; FUserName := ''; FReceivingData := rdSmtpCommand; FCramMD5Key := ''; FConnectionState := csSmtpConnect; FNTLMAuth.Free(); FNTLMAuth := nil; end; { TclSmtpUserAccountItem } procedure TclSmtpUserAccountItem.Assign(Source: TPersistent); begin if (Source is TclSmtpUserAccountItem) then begin FEmail := (Source as TclSmtpUserAccountItem).Email; end; inherited Assign(Source); end; { TclSmtpUserAccountList } function TclSmtpUserAccountList.AccountByEmail(const AEmail: string): TclSmtpUserAccountItem; var i: Integer; begin for i := 0 to Count - 1 do begin Result := Items[i]; if CaseInsensitive then begin if SameText(Result.Email, AEmail) then Exit; end else begin if (Result.Email = AEmail) then Exit; end; end; Result := nil; end; function TclSmtpUserAccountList.Add: TclSmtpUserAccountItem; begin Result := TclSmtpUserAccountItem(inherited Add()); end; function TclSmtpUserAccountList.GetItem(Index: Integer): TclSmtpUserAccountItem; begin Result := TclSmtpUserAccountItem(inherited GetItem(Index)); end; procedure TclSmtpUserAccountList.SetItem(Index: Integer; const Value: TclSmtpUserAccountItem); begin inherited SetItem(Index, Value); end; { TclSmtpCommandInfo } procedure TclSmtpCommandInfo.Execute(AConnection: TclCommandConnection; AParams: TclTcpCommandParams); begin FHandler(AConnection as TclSmtpCommandConnection, Name, AParams.Params); end; end.
unit ufrmDataCostumer; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterBrowse, StdCtrls, ExtCtrls, System.Actions, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, ufraFooter4Button, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC, ufraFooter5Button, Vcl.ActnList; type TfrmDataCostumer = class(TfrmMasterBrowse) procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure actAddExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure actRefreshExecute(Sender: TObject); procedure FormShow(Sender: TObject); private procedure ParseHeaderGrid(); procedure ParseDataGrid(); public { Public declarations } end; var frmDataCostumer: TfrmDataCostumer; implementation uses ufrmDialogDataCostumer, uTSCommonDlg, DateUtils; {$R *.dfm} procedure TfrmDataCostumer.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; ////frmMain.DestroyMenu((Sender as TForm)); Action := caFree; end; procedure TfrmDataCostumer.FormCreate(Sender: TObject); begin inherited; Self.Caption := 'DATA CUSTOMER'; lblHeader.Caption := Self.Caption; actRefreshExecute(Self); end; procedure TfrmDataCostumer.FormDestroy(Sender: TObject); begin inherited; frmDataCostumer := nil; end; procedure TfrmDataCostumer.actAddExecute(Sender: TObject); begin inherited; if not Assigned(frmDialogDataCostumer) then Application.CreateForm(TfrmDialogDataCostumer, frmDialogDataCostumer); frmDialogDataCostumer.Caption := 'Add Data Customer'; frmDialogDataCostumer.FormMode:=fmAdd; SetFormPropertyAndShowDialog(frmDialogDataCostumer); if (frmDialogDataCostumer.IsProcessSuccessfull) then begin actRefreshExecute(Self); CommonDlg.ShowConfirmSuccessfull(atAdd); end; frmDialogDataCostumer.Free; cxGrid.SetFocus; end; procedure TfrmDataCostumer.actEditExecute(Sender: TObject); begin inherited; {if strgGrid.Cells[5,strgGrid.Row]='' then Exit; if not Assigned(frmDialogDataCostumer) then Application.CreateForm(TfrmDialogDataCostumer, frmDialogDataCostumer); frmDialogDataCostumer.Caption := 'Edit Data Customer'; frmDialogDataCostumer.FormMode:=fmEdit; frmDialogDataCostumer.DataCustomerId:=StrToInt(strgGrid.Cells[5,strgGrid.row]); SetFormPropertyAndShowDialog(frmDialogDataCostumer); if (frmDialogDataCostumer.IsProcessSuccessfull) then begin actRefreshDataCostumerExecute(Self); CommonDlg.ShowConfirmSuccessfull(atEdit); end; frmDialogDataCostumer.Free; strgGrid.SetFocus; } end; procedure TfrmDataCostumer.actRefreshExecute(Sender: TObject); begin inherited; ParseDataGrid(); end; procedure TfrmDataCostumer.ParseHeaderGrid(); begin { with strgGrid do begin Clear; RowCount:= 2; ColCount:= 5; Cells[0,0]:= 'CODE'; Cells[1,0]:= 'NAME'; Cells[2,0]:= 'ADDRESS'; Cells[3,0]:= 'TELEPHONE'; Cells[4,0]:= 'CONTACT PERSON'; AutoSize:= True; end; } end; procedure TfrmDataCostumer.ParseDataGrid; var data: TDataSet; i: Integer; begin { ParseHeaderGrid; SetLength(arr,0); if not assigned(DataCustomer) then DataCustomer := TDataCustomer.Create; data:= DataCustomer.GetListCustomer(arr); with strgGrid, data do begin if not IsEmpty then begin RowCount:= RecordCount+1; i:=0; while not Eof do begin Inc(i); Cells[0,i]:= fieldbyname('CUSTV_CODE').AsString; Cells[1,i]:= fieldbyname('CUSTV_NAME').AsString; Cells[2,i]:= fieldbyname('CUSTV_ADDRESS').AsString; Cells[3,i]:= fieldbyname('CUSTV_TELP').AsString; Cells[4,i]:= fieldbyname('CUSTV_CONTACT_PERSON').AsString; Cells[5,i]:= IntToStr(fieldbyname('CUSTV_ID').AsInteger); Next; end; AutoSize:= True; end; end; } end; procedure TfrmDataCostumer.FormShow(Sender: TObject); begin inherited; cxGrid.SetFocus; end; end.
unit ServiceVersion.Interfaces; interface type iVersion = interface ['{CB5ED8E8-C53D-4232-970F-70ABCAD14797}'] { private } function getValue: string; function getBuild: integer; function getMaintenance: integer; function getMajor: integer; function getMinor: integer; procedure setValue(const Value: string); procedure setBuild(const Value: integer); procedure setMaintenance(const Value: integer); procedure setMajor(const Value: integer); procedure setMinor(const Value: integer); function getFilename: string; procedure setFilename(const aValue: string); { public } property Filename: string read getFilename write setFilename; // Formato da Versão ex: 2.4.3.7 separado em array [0]=2, [1]=4, [2]=3, [3]=7 property Major: integer read getMajor write setMajor; // [0]=2 Versão principal = Mudança do programa ( Reengenharia ) property Minor: integer read getMinor write setMinor; // [1]=4 Versão menor = Mudança de Formulário ( Adição/Remoção ) property Maintenance: integer read getMaintenance write setMaintenance; // [2]=3 Lançamento/Atualização = Mudança de Componente ( Adição/Remoção ) property Build: integer read getBuild write setBuild; // [3]=7 Construção = Correção ( Adequações das funcionalidades ) property Value: string read getValue; end; implementation end.
unit CTEditFormUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, cxTextEdit, cxButtons, ConstSumsDM,ZTypes,ZMessages, Unit_ZGlobal_Consts, FIBDatabase, pFIBDatabase, FIBQuery, pFIBQuery, pFIBStoredProc, Ibase, ZProc, cxLookAndFeelPainters, cxControls, cxContainer, cxEdit; type TCTEditForm = class(TForm) ConstTypeEdit: TcxTextEdit; cxButton1: TcxButton; cxButton2: TcxButton; DefaultTransaction: TpFIBTransaction; StProc: TpFIBStoredProc; DB: TpFIBDatabase; procedure cxButton1Click(Sender: TObject); procedure cxButton2Click(Sender: TObject); private DM:TMainDM; FEditMode:TZControlFormStyle; PLanguageIndex:byte; PDb_handle:TISC_DB_HANDLE; PId:integer; public constructor Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE; EditMode:TZControlFormStyle;Id:integer);reintroduce; property Id:integer read PId; end; var CTEditForm: TCTEditForm; implementation {$R *.dfm} constructor TCTEditForm.Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE; EditMode:TZControlFormStyle;Id:integer); begin inherited Create(AOwner); FEditMode:=EditMode; PLanguageIndex:= LanguageIndex; PId:=Id; PDB_Handle:= DB_Handle; case FEditMode of zcfsInsert: begin Caption:=Caption_Insert[PLanguageIndex]; end; zcfsUpdate: begin with StProc do begin Caption:=Caption_Update[PLanguageIndex]; DB.Handle := PDb_handle; StoredProcName:='Z_SP_CONSTS_S_BY_ID'; Transaction.StartTransaction; Prepare; ParamByName('IN_ID').AsInteger:= PId; ExecProc; ConstTypeEdit.Text:=ParamByName('CONST_NAME').AsString; Transaction.Commit; end; end; end; end; procedure TCTEditForm.cxButton1Click(Sender: TObject); begin Close; end; procedure TCTEditForm.cxButton2Click(Sender: TObject); begin if (ConstTypeEdit.Text='') then begin ZShowMessage('Помилка!','Не вказана назва типу констант!',mtWarning,[mbOk]); ConstTypeEdit.SetFocus; Exit; end; with StProc do try case FEditMode of zcfsInsert: begin DB.Handle := PDb_handle; StoredProcName:='Z_SP_CONSTS_I'; Transaction.StartTransaction; Prepare; ParamByName('CONST_NAME').AsString:=ConstTypeEdit.Text; ExecProc; Transaction.Commit; end; zcfsUpdate: begin DB.Handle := PDb_handle; StoredProcName:='Z_SP_CONSTS_U'; Transaction.StartTransaction; Prepare; ParamByName('ID').AsInteger:= PId; ParamByName('CONST_NAME').AsString:=ConstTypeEdit.Text; ExecProc; Transaction.Commit; end; end; except on e:exception do begin ZShowMessage('Помилка!',e.Message,mtError,[mbOk]); Transaction.Rollback; end; end; Close; end; end.
unit ClipboardMonitor; interface uses Windows, Messages, SysUtils, Classes, Clipbrd; type TClipboardNotifyProc = procedure(Sender: TComponent; Clipboard: TClipboard; FormatsAvailable: TList; var NotifyOtherApplications: Boolean) of object; TClipboardMonitor = class(TComponent) private FNextInChain: THandle; FOnChange: TClipboardNotifyProc; FHandle: HWND; FNotifyOnChange: boolean; procedure WndProc(var Msg: TMessage); protected procedure WMDrawClipboard(var Msg: TWMDrawClipboard); {message WM_DrawClipboard;} procedure WMChangeCBChain(var Msg: TWMChangeCBChain); {message WM_ChangeCBChain;} procedure SetNotifyOnChange(Value: Boolean); function GetClipBoard: TCLipboard; function GetFormatsAsList: TList; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CopyDataToClipboard(Format: word; Data: Pointer; Size: Longint); function DataSize(Format: word): longint; function CopyDataFromClipboard(Format: word; Data: Pointer; Size: longint): Pointer; published property NotifyOnChange: Boolean read FNotifyOnChange write SetNotifyOnChange; property OnChange: TClipboardNotifyProc read FOnChange write FOnChange; property Clipboard: TClipboard read GetClipBoard; end; implementation uses Forms, Math; function GetErrorStr: PChar; var lpMsgBuf: Pointer; begin FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER or FORMAT_MESSAGE_FROM_SYSTEM, nil, GetLastError(), 0, @lpMsgBuf, 0, nil); Result := PChar(lpMsgBuf); end; constructor TClipboardMonitor.Create(AOwner: TComponent); var Msg: TWMDRAWCLIPBOARD; begin inherited Create(AOwner); FHandle := Classes.AllocateHWnd(WndProc); with ClipBrd.Clipboard do try Open; if ClipBrd.Clipboard.FormatCount > 0 then WMDrawClipboard(Msg); finally Close; end; end; destructor TClipboardMonitor.Destroy; begin Classes.DeAllocateHWnd(FHandle); inherited Destroy; end; procedure TClipboardMonitor.WMDrawClipboard(var Msg: TWMDrawClipboard); var Formats: TList; NotifyOtherApps: Boolean; begin Formats := nil; if Assigned(OnChange) then begin try Formats := GetFormatsAsList; NotifyOtherApps := true; OnChange(Self, Clipboard, Formats, NotifyOtherApps); if (NotifyOtherApps) and (FNextInChain <> 0) then PostMessage(FNextInChain, WM_DrawClipboard, 0, 0); finally Formats.Free; end; end; inherited; end; procedure TClipboardMonitor.WMChangeCBChain(var Msg: TWMChangeCBChain); begin with Msg do begin if FNextInChain = Remove then FNextInChain := Next else if FNextInChain <> 0 then PostMessage(FNextInChain, WM_ChangeCBChain, Remove, Next); end; inherited; end; procedure TClipboardMonitor.SetNotifyOnChange(Value: boolean); begin Assert(FHandle > 0, 'Handle must never be 0. Please Assign a handle or left the application handle default in'); FNotifyOnChange := Value; if (FNotifyOnChange) then begin if not (csDesigning in ComponentState) then FNextInChain := SetClipboardViewer(FHandle) end else ChangeClipboardChain(FHandle, FNextInChain); end; function TClipboardMonitor.GetFormatsAsList: TList; var i: longint; begin Result := TList.Create; with Result do begin Capacity := ClipBrd.Clipboard.FormatCount; for i := 0 to Capacity do Result.Add(Pointer(ClipBrd.Clipboard.Formats[i])); end; end; function TClipboardMonitor.GetClipBoard: TClipboard; begin Result := clipbrd.Clipboard; end; procedure TClipboardMonitor.CopyDataToClipboard(Format: word; Data: pointer; Size: longint); var ClipData: THandle; begin ClipData := 0; Assert(Data <> nil, 'You must provide a preallocated pointer'); Assert(Size > 0, 'You must specify the size of the memory block pointer to by Data'); Assert(Format > 0, 'You must provide a valid format'); with ClipBrd.Clipboard do try Open; try try ClipData := GlobalAlloc(GMEM_MOVEABLE+GMEM_DDESHARE, Size); Move(Data^, GlobalLock(ClipData)^, Size); SetAsHandle(Format, ClipData); finally if ClipData <> 0 then GlobalUnlock(ClipData); end; except if ClipData <> 0 then GlobalFree(ClipData); raise; end; finally Close; end; end; function TClipboardMonitor.DataSize(Format: Word): Longint; var ClipData: THandle; Flags: longint; begin Result := 0; Assert(Format > 0, 'You must provide a valid format'); with ClipBrd.Clipboard do begin try Open; if HasFormat(Format) then begin ClipData := GetAsHandle(Format); Flags := GlobalFlags(ClipData); if not (Flags and GMEM_DISCARDED = GMEM_DISCARDED) then Result := GlobalSize(ClipData); end; finally Close; end; end; end; function TClipboardMonitor.CopyDataFromClipboard(Format: Word; Data: Pointer; Size: Longint): Pointer; var ClipData: THandle; ClipDataSize, BufferSize, Flags: Longint; begin Result := nil; Assert(Data <> nil, 'You must provide a preallocated pointer'); Assert(Size > 0, 'You must specify the size of the memory block pointer to by Data'); Assert(Format > 0, 'You must provide a valid format'); with ClipBrd.Clipboard do begin try Open; if HasFormat(Format) then begin ClipData := GetAsHandle(Format); Flags := GlobalFlags(ClipData); if not (Flags AND GMEM_DISCARDED = GMEM_DISCARDED) then ClipDataSize := GlobalSize(ClipData) else raise Exception.Create('Clipboard Data Invalid'); BufferSize := Min(Size, ClipDataSize); try Move(GlobalLock(ClipData)^, Data^, BufferSize); finally GlobalUnlock(ClipData); end; end else raise Exception.Create('Format not availble on clipboard'); finally Close; end; end; end; procedure TClipboardMonitor.WndProc(var Msg: TMessage); var WMDrawClipboardMsg: TWMDrawClipboard absolute Msg; WMChangeCBChainMsg: TWMChangeCBChain absolute Msg; begin case Msg.Msg of WM_DRAWCLIPBOARD: WMDrawClipboard(WMDrawClipboardMsg); WM_CHANGECBCHAIN: WMChangeCBChain(WMChangeCBChainMsg); else DefWindowProc(FHandle, Msg.Msg, Msg.WParam, Msg.LParam); end; end; end.
{ File: GuessingGame.pas Copyright (C) Nelson Ka Hei Chan 2008 <me@nelsonchan.info> Distributed under the GPLv3 License, See http://www.gnu.org/licenses/gpl-3.0.txt The program is designed and written by Nelson Chan - Program Manual - Design: Flow and algorithms: Greeting -> Enter Menu -> Mode A, B or C -> Game running -> AFR -> end |__________inside a while loop_____________| |_____________inside a repeat until loop____________| Explaination: The beginning is simple so i'm going to skip it. Let's talk about the while loop first, it is used to repeat the game part but not the whole mode(with the name entering ans instruction), I use "request = 'play' " as the parameter to do the loop so in AFR when player input 'again' then will assign 'play' to request, and anything else will exit the loop e.g. : 'end' , 'menu'(note that 'menu' is not an absolute parameter it is just used to repeat the Repeat until loop as i use "until request = 'end'" as the parameter to exit the loop, and it would go back to the menu part so i just call it 'menu'. Talking about the Repeat-Until loop, yes, it is used when user want to go to menu in the AFR and quit when request='end'. Validation: An validation design is used wherever it asks the user to input something. It is used to make sure user input the required elements. Also to avoid error that will occur when user inputs a non-integer (string) in the MATH part. I use the function and variables "val(input,inputvalue,inputcode)". Mode A: It is a story-based-liked design and a classic one, a random number wil be generated and the player need to guess the number, wrong guess -> -HP, correct -> +HP and go to next level. With status display. I add a feature "magic power" it can heal the player for 50HP when used. The maximum level is 11, that means the player will play 10 levels(begin with lvl 1). The game will end when hp <= 0 , level = 11 ,user's termination. Flow : User input name -> Read instruction? -> Choose difficulty -> Start up -> update status display -> user input -> checking -> Game over with messages-> AFR |_______________A repeat until loop______________| |_____________________________________________the while loop______________________________________________________| Mode B: PVP mode, players choose the ceiling of the range and compete with each other who find out the random number first who wins. P1 will go first and then P2. The algorithm to determine whose turn is in this way: When var : whoseturn = 1 then P1's turn, whoseturn = 2 then P2's turn. While checking, if P1 get it wrong(too small or too large) then set whoseturn to 2, and when P2 get it wrong, set whoseturn to 1. Flow: User input names -> Read instruction? -> User set the range -> P1,P2-> AFR |_____| <----A Repeat-Until loop// |__________the while loop_________| Mode C: Quite similar to PVP mode but this time VS with computer. As usual, player set the range and begin the game. Basically just like Mode B, but this time need to do another random function to generate computer's guess. I do it by 'computerguess := random(maximum-minimum-1)+(minimum+1)' since the maximum and minimum is always changing, so as to keep the random number inside the range. Flow: SKIP , similar to Mode B Remarks: All random number generated will exclude the minimum and maximum. The reason is that let's say minimum = 5 and maximum = 10, If the magicnum = 5 or 10, it will state the range is 5-6 or 9-10. And if user got the number, the program will return the both messages(wrong guess and correct) This is a problem, so I just say the Range is Between min and max , where min and max not included. and generate the magicnum by 'random(maximum-2)+(minimum+1)', therefore the range will be 2 to 9 when max=10 and min=1. and 'computerguess := random(maximum-minimum-1)+(minimum+1)' I also use the DELAY function to simulate delay to slow down the printing a bit to make the user more comfortable when receiving long messages. !! The magicnum will be shown when using "PROGRAM TEST" as the name } program GuessingGame_byNelson; uses crt ; const numberofmodes =3 ; type playedTF= array[1..numberofmodes] of boolean ; var {engine} name, name2, request , input ,instruction : string ; errordetect,inputvalue , inputcode ,count : integer ; FirstTimeToPlay : playedTF ; Key : LongINT ; {MODE A} magicnum, hp, level, NoOfTry, TotalTry ,magicpower,MPlevel : integer ; minimum, maximum , difficulty : integer ; {MODE B & C} {minimum, maximum and magicnum also used} whoseturn : integer ; computerguess : integer ; {Procedure: Print instruction word by word with delay} procedure write_instruction(count:integer;time:integer); begin count:=0; Repeat If KeyPressed then Key := Ord(ReadKey); If (Key = Ord('s')) or (Key = Ord('S')) Then repeat count := count + 1 ; if NOT((instruction[count] = '/')or(instruction[count]='\')) Then write(instruction[count]) else writeln; until instruction[count] = '\' Else begin count:=count+1; if NOT((instruction[count] = '/')or(instruction[count]='\')) Then write(instruction[count]) else writeln; delay(time) end Until instruction[count] = '\' end; {End} {Procedure : Ask for request , what to do?} procedure AFR_WTD ; begin If input='end' Then begin writeln; writeln; Repeat if errordetect = 1 Then writeln('Unknown request!'); write('Do you want to go back to menu? (yes/no)');readln(request); If (request = 'yes') or (request = 'no') Then errordetect := 0 Else errordetect := 1 Until errordetect = 0 ; If request = 'yes' Then begin request := 'menu' ; clrscr end Else request := 'end' end Else begin delay(200); writeln; writeln; writeln; writeln; writeln; writeln('------------------------------------------------------------'); writeln('What would you like to do now?'); writeln('Enter: ''again'' to play again'); writeln(' ''menu'' to go to menu'); writeln(' ''end'' to Exit'); Repeat If errordetect = 1 Then writeln('ERROR! Unknown request. Try again'); If errordetect = 2 Then writeln('You didn''t enter anything.'); write('Request: ');readln(request); If request = 'again' Then begin request := 'play'; errordetect:=0 end; If request = 'end' Then begin request := 'end' ; errordetect := 0 end ; If request= 'menu' Then begin request := 'menu' ; errordetect := 0 end ; If NOT(request='play') and NOT(request='end') and NOT(request='menu') Then errordetect := 1 ; If length(request) = 0 Then errordetect := 2 ; writeln Until (errordetect = 0) end end; {End Ask for request, what to do?} {Procedure : Ask for request, read instruction?} {- ORIGINAL DESIGN - If FirstTimeToPlay[mode] = true Then begin Repeat If errordetect = 1 Then writeln('ERROR! Unknown request. Please enter ''yes'' or ''no'' only. Try again'); If errordetect = 2 Then writeln('You didn''t enter anything, please try again'); write('Would you like to read INSTRUCTION before playing? (yes/no)');readln(request); If (request <> 'yes') and (request <> 'no') Then errordetect := 1 ; If length(request) = 0 Then errordetect := 2 ; If (request = 'yes') or (request = 'no') Then errordetect := 0 ; writeln Until errordetect = 0; FirstTimeToPlay[mode]:=False ; If request = 'yes' Then request := 'instruction' Else request := 'play' end Else request := 'play' ; clrscr } procedure AFR_RI(mode : integer); begin If FirstTimeToPlay[mode] = true Then begin request := 'instruction' ; FirstTimeToPlay[mode] := false end Else request := 'play'; clrscr end; {End procedure AFR_RI} {MAIN PROGRAM BODY} begin {initialization} count:=0; clrscr; For count := 1 to 3 do FirstTimeToPlay[count] := true; errordetect := 0 ; randomize; {End initialization} textcolor(white); writeln('+++Guessing Game+++'); writeln('-by Nelson , Last updated: 13:22 @29.03.2008 ') ; instruction:='//Welcome to play this game!/It''s all about Guessing!!/\ '; write_instruction(count,10); Key := 0 ; writeln ; delay(200); write('Press ENTER when ready');readln; Repeat clrscr; {Ask for request, main menu} writeln('- Menu -'); writeln('Choose a mode to play : '); writeln('A: Single Player'); writeln('B: Player V.S. Player'); writeln('C: Player V.S. Computer'); writeln; writeln('Q: Quit'); writeln ; Repeat If errordetect = 1 Then writeln('ERROR! Input the alphabet only.'); If errordetect = 2 Then writeln('You didn''t input anything. '); write('Input the corresponding alphabet: ');readln(request); If (request = 'A')or(request='a') or(request = 'B')or(request='b') or(request = 'C')or(request='c') or(request = 'Q')or(request='q') Then begin If (request = 'Q')or(request='q') Then request:= 'end'; errordetect := 0 end Else errordetect := 1; If length(request) = 0 Then errordetect := 2; writeln Until errordetect = 0 ; {End AFR main menu} If (request = 'A') or (request = 'a') Then {MODE A} begin clrscr; {Input name, name contain <=38 characters} Repeat If errordetect = 1 Then writeln('ERROR! Name too long. Enter a name which contains <= 38 characters.'); If errordetect = 2 Then writeln('ERROR! you didn''t input anything, try again.'); write('Enter your name: ');readln(name); If (length(name) <= 38) and (length(name)<>0) Then errordetect := 0; If length(name) > 38 Then errordetect := 1; If length(name) = 0 Then errordetect := 2; writeln Until errordetect = 0 ; {End input name} AFR_RI(1); {Call procedure ask for request, read instruction?} {Instruction} If request = 'instruction' Then begin writeln('INSTRUCTIONS (Press [s] to skip)') ; writeln; instruction:='Listen up,/At the beginning you will have 100hp./A Magic number will be generated in each level\'; write_instruction(count,50); instruction:='You need to guess what the magic number is.\'; write_instruction(count,50); instruction:='The range of the number will be shown in the status display.\'; write_instruction(count,50); instruction:='5HP damage will be taken for each incorrect guess,\'; write_instruction(count,50); instruction:='and heal for 20HP for every correct guess and proceed to the next level.\'; write_instruction(count,50); instruction:='There are 10 levels totally./Besides, there is something called "Magic Power"\'; write_instruction(count,50); instruction:='it can recover your HP for 50HP/To use it, type "magic" when it ask you to guess.\'; write_instruction(count,50); instruction:='You will receive 1 Magic Power for completing every 5 levels\'; write_instruction(count,50); writeln('------------------------------'); write('Ready? Press ENTER to continue ...'); readln; request := 'play' ; end; Key := 0; {End instruction} {outter loop PLAY} While request = 'play' Do begin clrscr; {Ask for request , difficulty?} writeln('Choose a difficulty '); writeln('1 : Normal'); writeln('2 : Hard'); Repeat If errordetect = 1 Then writeln('ERROR! Unknown request. Enter 1 or 2 only, try again'); If errordetect = 2 Then writeln('You didn''t enter anything.'); write('Input the corresponding number : ');readln(request); If (request <> '1') and (request <> '2') Then errordetect := 1 ; If length(request) = 0 Then errordetect := 2 ; If (request = '1') or (request = '2') Then errordetect := 0 Until errordetect = 0; If request = '1' Then {processing} difficulty := 50; If request = '2' Then difficulty := 100; clrscr; {End ask for request} {Initialization & reset} magicnum := random(1) ; inputvalue := 0 ; inputcode := 0 ; hp := 100 ; level := 1 ; magicpower := 0 ; minimum := 1 ; maximum := Level*difficulty; NoOfTry := 0 ; TotalTry := 0 ; MPlevel := 0 ; {End initialization & reset} {Core Running} Repeat {startup and changes after passing a level} magicnum := random(level*difficulty-2)+2; NoOfTry := 0; maximum := level * difficulty ; minimum := 1; If MPlevel = 5 Then begin magicpower:=magicpower+1; MPlevel := 0 end; {end startup and changes} Repeat {Status display} writeln('++++++++++++++++++STATUS DISPLAY++++++++++++++++++') ; writeln('+ Player: ', name:38,' +') ; writeln('+ HP : ', hp:38,' +') ; writeln('+ Magic Power left:', magicpower:29,' +') ; writeln('+ Level : ', level:38,' +') ; writeln('+ Range : ', ' ':15, 'Between ',minimum:5,' and ', maximum:5,' +') ; writeln('+ No.of try: ', NoOfTry:35,' +') ; If TotalTry = 0 Then writeln('+ Accuracy : stand by +') Else writeln('+ Accuracy : ', (level-1)/TotalTry*100:34:2,'% +'); writeln('++++++++++++++++++++++++++++++++++++++++++++++++++') ; writeln('*You may quit the game by inputting ''end''*'); writeln('*Input ''magic'' to use Magic power*'); {End status display} writeln; If name = 'PROGRAM TEST' Then writeln('#The magic number is ',magicnum,' #'); {Input} Repeat writeln; If errordetect = 1 Then writeln('ERROR! Input an integer only, try again'); If errordetect = 2 Then writeln('You didn''t input anything, try that again.'); write('Make a guess : ');readln(input); val(input,inputvalue,inputcode) ; If inputcode <> 0 Then errordetect := 1 ; If length(input) = 0 Then errordetect := 2 ; If ((inputcode = 0) and (length(input) <> 0)) or (input = 'end') or (input = 'magic') Then errordetect := 0 Until (errordetect = 0) ; {End input} {Ignore checking while input 'end' or 'magic'} If NOT(input = 'end') AND NOT(input = 'magic') Then begin delay(200); {Checking} If (inputvalue <= minimum) or (inputvalue >= maximum) Then begin writeln('The number is out of range!'); write('Press ENTER to continue... ');readln end ; If (inputvalue > magicnum) and (inputvalue < maximum) Then begin NoOfTry := NoOfTry+1 ; TotalTry := TotalTry+1 ; maximum := inputvalue ; hp := hp - 5; If hp = 0 Then writeln('Muahaha..You''ve died! The magic number is ',magicnum,'. Try harder next time!') Else begin writeln('The number is too large!'); writeln('5HP Damage received! Your HP becomes ',hp); If hp = 5 Then writeln('You are dying, here comes your last chance') end; write('Press ENTER to continue... ');readln end ; If (inputvalue < magicnum) and (inputvalue > minimum) Then begin NoOfTry := NoOfTry+1 ; TotalTry := TotalTry+1 ; minimum := inputvalue ; hp := hp - 5; If hp = 0 Then writeln('Muahaha..You''ve died! The magic number is ',magicnum,'. Try harder next time!') Else begin writeln('The number is too small!'); writeln('5HP Damage received! Your HP becomes ',hp); If hp = 5 Then writeln('You are dying, here comes your last chance') end; write('Press ENTER to continue... ');readln end ; If inputvalue = magicnum Then begin level := level + 1 ; hp := hp+20; MPlevel := MPlevel+1; TotalTry := TotalTry +1 ; writeln('Congradulations! You are correct!'); If level = 11 Then begin writeln('You have completed the game!!!'); write('Press ENTER to continue..');readln end Else begin if NoOfTry = 0 Then writeln('Lucky huh? Just see if you have the luck with you all the time.') else writeln('You have tried for ',NoOfTry,' times before you''ve got the number.'); write('Press ENTER to proceed to level ', level);readln end end end Else begin If input = 'magic' Then{MAGIC} begin If magicpower <= 0 Then begin writeln('You don''t have any Magic Power.'); write('Press ENTER to continue... ');readln end Else begin writeln('~~~~~~~MAGIC~~~~~~~'); hp:=hp+50 ; magicpower := magicpower - 1; writeln('You are heal for 50HP, your HP becomes ', hp); write('Press ENTER to continue...');readln end {End MAGIC} end end ; {End Checking} clrscr Until (hp<=0) or (inputvalue = magicnum) or (input = 'end') or (level = 11) {loop within the same level} Until (hp<=0) or (input='end') or (level = 11); {GAME OVER} writeln('GAME OVER!!'); if input= 'end' Then writeln('Reason: User sends end'); If level = 11 Then writeln('Reason: You have completed the game!!'); if hp <= 0 then writeln('Reason: You died at Level ', level); if input <> 'end' Then begin write('Your accuracy is : '); writeln((level-1)/TotalTry*100:0:2,'%'); write('Rank: '); delay(500); If level = 1 Then writeln('You didn''t play it seriously.') Else begin Case round((level-1)/TotalTry*100) Of 0.. 5: writeln('Poor!'); 6.. 10: writeln('Good Try'); 11.. 15: writeln('Not bad!'); 16.. 20: writeln('Nice job!'); 21.. 25: writeln('Expert!'); 26.. 30: writeln('Excellent!!') Else writeln('GOD LIKE!!!') End end end; write('Press ENTER to continue... '); readln; {End game over messages} AFR_WTD{Call Ask for request_what to do} end {loop PLAY} end; {End MODE A} {MODE B} If (request = 'B')or(request='b') Then begin clrscr; {Input Player 1 name} Repeat If errordetect = 2 Then writeln('ERROR! you didn''t input anything, try again.'); write('Enter the name of Player 1 : ');readln(name); If length(name) > 0 Then errordetect := 0 Else errordetect := 2; Until errordetect = 0 ; {End input name} {Input Player 2 name} Repeat If errordetect = 2 Then writeln('ERROR! you didn''t input anything, try again.'); write('Enter the name of Player 2 : ');readln(name2); If length(name2) > 0 Then errordetect := 0 Else errordetect := 2; writeln Until errordetect = 0 ; {End input name} AFR_RI(2); {Call procedure ask for request, read instruction?} {Instruction} If request = 'instruction' Then begin writeln('INSTRUCTION (Press [s] to skip)'); writeln; instruction:='Listen up,/First you two have to choose the top range of the random number.\'; write_instruction(count,50); instruction:='Then, a random number will be generated base on the range given by you.\'; write_instruction(count,50); instruction:='In the game, you two will have to compete with each other.\'; write_instruction(count,50); instruction:='The one who get the number first will win.\'; write_instruction(count,50); writeln('---------------------------------------------------'); write('Ready? Press ENTER to continue..');readln end; Key := 0; {End Instruction} clrscr; request := 'play' ; While request = 'play' Do begin clrscr; minimum:=1; {Input max range} Repeat If errordetect = 1 Then writeln('ERROR! Input an integer >=3 and <=32767 only!'); If errordetect = 2 Then writeln('You didn''t enter anything, try again.'); write('Enter the maximum value of the range: ');readln(input); val(input, maximum ,inputcode); If (inputcode = 0) and (maximum >= 3) and(maximum<=32767) Then errordetect:=0 Else errordetect := 1 ; If length(input)=0 Then errordetect := 2 ; writeln Until errordetect = 0; {End input max range} magicnum := random(maximum-2)+(minimum+1); whoseturn := 1 ; {Game running} Repeat {P1} If whoseturn = 1 Then begin clrscr; writeln('*You may end the game by inputting ''end''*'); writeln; writeln; If name = 'PROGRAM TEST' Then writeln('#The magic number is : ',magicnum,' #') ; writeln('The magic number is between ',minimum,' and ',maximum ); {P1 Input} Repeat writeln; If errordetect = 1 Then writeln('ERROR! Input an integer only. Try again'); If errordetect = 2 Then writeln('ERROR! You didn''t input anything, try that again.'); write('(P1) ',name,'''s turn: ');readln(input); val(input,inputvalue,inputcode) ; If inputcode <> 0 Then errordetect := 1 ; If length(input) = 0 Then errordetect := 2 ; If ((inputcode = 0) and (length(input) <> 0)) or (input = 'end')Then errordetect := 0 Until (errordetect = 0) ; {End P1 input} writeln; {P1 Check} If NOT(input = 'end') Then {ignore checking when input ='end'} begin delay(200); If (inputvalue <= minimum) or (inputvalue >= maximum) Then begin writeln('The number is out of range, try again.'); write('Press ENTER to continue... ');readln end ; If (inputvalue > magicnum) and (inputvalue < maximum) Then begin maximum := inputvalue ; whoseturn:=2 ; writeln('The number is too large!'); writeln('Now is (P2) ',name2,'''s turn!'); write('Press ENTER to continue... ');readln end ; If (inputvalue < magicnum) and (inputvalue > minimum) Then begin minimum := inputvalue ; whoseturn:=2 ; writeln('The number is too small!'); writeln('Now is (P2) ',name2,'''s turn!'); write('Press ENTER to continue... ');readln end ; If inputvalue = magicnum Then begin writeln('(P1)',name,' has got the magic number!'); writeln('(P1)',name,' WINS the game!!'); write('Press ENTER to continue..');readln ; request := 'finish' end end {End P1 Check} end ; {work with the If whoseturn = 1} {End P1} {P2} If whoseturn = 2 Then begin clrscr; writeln('*You may end the game by inputting ''end''*'); writeln; writeln; If name2 = 'PROGRAM TEST' Then writeln('#The magic number is : ',magicnum,' #') ; writeln('The magic number is between ',minimum,' and ',maximum ); {P2 input} Repeat writeln; If errordetect = 1 Then writeln('ERROR! Input an integer only. Try again'); If errordetect = 2 Then writeln('ERROR! You didn''t input anything, try that again.'); write('(P2) ',name2,'''s turn: ');readln(input); val(input,inputvalue,inputcode) ; If inputcode <> 0 Then errordetect := 1 ; If length(input) = 0 Then errordetect := 2 ; If ((inputcode = 0) and (length(input) <> 0)) or (input = 'end')Then errordetect := 0 Until (errordetect = 0) ; {End P2 input} writeln; {P2 Check} If NOT(input = 'end') Then {ignore checking when input ='end'} begin delay(200); If (inputvalue <= minimum) or (inputvalue >= maximum) Then begin writeln('The number is out of range, try again.'); write('Press ENTER to continue... ');readln end ; If (inputvalue > magicnum) and (inputvalue < maximum) Then begin maximum := inputvalue ; whoseturn:=1 ; writeln('The number is too large!'); writeln('Now is (P1) ',name,'''s turn!'); write('Press ENTER to continue... ');readln end ; If (inputvalue < magicnum) and (inputvalue > minimum) Then begin minimum := inputvalue ; whoseturn:=1 ; writeln('The number is too small!'); writeln('Now is (P1) ',name,'''s turn!'); write('Press ENTER to continue... ');readln end ; If inputvalue = magicnum Then begin writeln('(P2)',name2,' has got the magic number!'); writeln('(P2)',name2,' WINS the game!!'); write('Press ENTER to continue..');readln ; request := 'finish' end end {End P2 Check} end ; {work with If whoseturn = 2} {End P2} Until (request = 'finish') or (input = 'end') ; {Game stop} AFR_WTD{Call Ask for request_what to do} end {the while 'play' loop} end; {End MODE B} {MODE C} If (request = 'C') or (request = 'c') Then begin clrscr; {Input name} Repeat If errordetect = 2 Then writeln('ERROR! you didn''t input anything, try again.'); write('Enter the name of Player : ');readln(name); If length(name) > 0 Then errordetect := 0 Else errordetect := 2; writeln Until errordetect = 0 ; {End input name} AFR_RI(3); {Call procedure ask for request, read instruction?} {Instruction} If request = 'instruction' Then begin writeln('INSTRUCTION (Press [s] to skip)'); writeln; instruction:='Listen!/You are going to compete with the Computer.\'; write_instruction(count,50); instruction:='You will be asked to input the maximum range of the magic number.\'; write_instruction(count,50); instruction:='After that, a magic number will be generated randomly base on the range given.\'; write_instruction(count,50); instruction:='The one who find out the magic number will win the game!\'; write_instruction(count,50); writeln('---------------------------------------------------'); write('Ready? Press ENTER to continue..');readln end; Key := 0; {End Instruction} request := 'play'; While request = 'play' Do begin clrscr; {initialisation} computerguess:= random(1); minimum := 1 ; {end initialisation} {Input max range} Repeat If errordetect = 1 Then writeln('ERROR! Input an integer >=3 and <=32767 only!'); If errordetect = 2 Then writeln('You didn''t enter anything, try again.'); write('Enter the maximum value of the range: ');readln(input); val(input, maximum ,inputcode); If (inputcode = 0) and (maximum >=3)and(maximum<=32767) Then errordetect:=0 Else errordetect := 1 ; If length(input)=0 Then errordetect := 2 ; writeln Until errordetect = 0; {End input max range} magicnum := random(maximum-2)+(minimum+1) ; {Generate magicnum} whoseturn := 1 ; {Game running} Repeat clrscr; {Player} If whoseturn = 1 Then begin clrscr; writeln('*You may end the game by inputting ''end''*'); writeln; If name = 'PROGRAM TEST' Then writeln('#The magic number is : ',magicnum,' #') Else writeln; writeln('The magic number is between ',minimum,' and ',maximum ); {Player Input} Repeat writeln; If errordetect = 1 Then writeln('ERROR! Input an integer only. Try again'); If errordetect = 2 Then writeln('ERROR! You didn''t input anything, try that again.'); write('(Player) ',name,'''s turn: ');readln(input); val(input,inputvalue,inputcode) ; If inputcode <> 0 Then errordetect := 1 ; If length(input) = 0 Then errordetect := 2 ; If ((inputcode = 0) and (length(input) <> 0)) or (input = 'end')Then errordetect := 0 Until (errordetect = 0) ; {End Player input} writeln; {Player Check} If NOT(input = 'end') Then {ignore checking when input ='end'} begin delay(200); If (inputvalue <= minimum) or (inputvalue >= maximum) Then begin writeln('The number is out of range, try again.'); write('Press ENTER to continue... ');readln end ; If (inputvalue > magicnum) and (inputvalue < maximum) Then begin maximum := inputvalue ; whoseturn:=2 ; writeln('The number is too large!'); writeln('Now is Computer''s turn!'); write('Press ENTER to continue... ');readln end ; If (inputvalue < magicnum) and (inputvalue > minimum) Then begin minimum := inputvalue ; whoseturn:=2 ; writeln('The number is too small!'); writeln('Now is Computer''s turn!'); write('Press ENTER to continue... ');readln end ; If inputvalue = magicnum Then begin writeln('YOU WIN! ',name,' has got the magic number!'); writeln('(Player)',name,' WINS the game!!'); write('Press ENTER to continue..');readln ; request := 'finish' end end {End Player Check} end ; {work with the If whoseturn = 1} {End Player} {CPU} If whoseturn = 2 Then begin clrscr; writeln('*You may end the game by inputting ''end''*'); writeln; writeln; writeln('The magic number is between ',minimum,' and ',maximum ); writeln; {CPU input} {AI} If maximum-minimum >=50 then computerguess := minimum + (maximum-minimum)DIV 2 Else begin If maximum-minimum = 4 Then repeat computerguess := random(maximum-minimum-1)+(minimum+1) until (computerguess <> maximum-2) and (computerguess <> minimum+2) Else If maximum-minimum = 3 Then computerguess := random(maximum-minimum-1)+(minimum+1) Else repeat computerguess := random(maximum-minimum-1)+(minimum+1) until (computerguess <> maximum -2) and (computerguess <> minimum +2) end ; {End AI} write('Computer''s turn: '); delay(500); writeln(computerguess); {End CPU input} writeln; delay(200); {CPU Check} If (computerguess <= minimum) or (computerguess >= maximum) Then begin writeln('The number is out of range, try again.'); write('Press ENTER to continue... ');readln end ; If (computerguess > magicnum) and (computerguess < maximum) Then begin maximum := computerguess ; whoseturn:=1 ; writeln('The number is too large!'); writeln('Now is (Player) ',name,'''s turn!'); write('Press ENTER to continue... ');readln end ; If (computerguess < magicnum) and (computerguess > minimum) Then begin minimum := computerguess ; whoseturn:=1 ; writeln('The number is too small!'); writeln('Now is (Player) ',name,'''s turn!'); write('Press ENTER to continue... ');readln end ; If computerguess = magicnum Then begin writeln('YOU LOST! Computer has got the magic number!'); writeln('Computer WINS the game!!'); write('Press ENTER to continue..');readln ; request := 'finish' end {CPU Check} end {work with If whoseturn = 2} {End CPU} Until (request = 'finish') or (input = 'end') ; {Game stop} AFR_WTD{Call procedure: Ask for request,what to do} end; {the while play loop} end {End MODE C} Until request = 'end' ; {so when request = 'menu' will repeat the loop} writeln; write('Press ENTER to quit..');readln end.
unit GLDBoxParamsFrame; interface uses Classes, Controls, Forms, StdCtrls, ComCtrls, GL, GLDTypes, GLDSystem, GLDBox, GLDNameAndColorFrame, GLDUpDown; type TGLDBoxParamsFrame = class(TFrame) NameAndColor: TGLDNameAndColorFrame; GB_Params: TGroupBox; L_Length: TLabel; L_Width: TLabel; L_Height: TLabel; L_LengthSegs: TLabel; L_WidthSegs: TLabel; L_HeightSegs: TLabel; E_Length: TEdit; E_Width: TEdit; E_Height: TEdit; E_LengthSegs: TEdit; E_WidthSegs: TEdit; E_HeightSegs: TEdit; UD_Length: TGLDUpDown; UD_Width: TGLDUpDown; UD_Height: TGLDUpDown; UD_LengthSegs: TUpDown; UD_WidthSegs: TUpDown; UD_HeightSegs: TUpDown; procedure SizeChangeUD(Sender: TObject); procedure SegmentsChangeUD(Sender: TObject; Button: TUDBtnType); procedure EditEnter(Sender: TObject); private FDrawer: TGLDDrawer; procedure SetDrawer(Value: TGLDDrawer); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function HaveBox: GLboolean; function GetParams: TGLDBoxParams; procedure SetParams(const Name: string; const Color: TGLDColor3ub; const Length, Width, Height: GLfloat; const LengthSegs, WidthSegs, HeightSegs: GLushort); procedure SetParamsFrom(Box: TGLDBox); procedure ApplyParams; property Drawer: TGLDDrawer read FDrawer write SetDrawer; end; procedure Register; implementation {$R *.dfm} uses SysUtils, GLDConst, GLDX; constructor TGLDBoxParamsFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); FDrawer := nil; end; destructor TGLDBoxParamsFrame.Destroy; begin if Assigned(FDrawer) then if FDrawer.IOFrame = Self then FDrawer.IOFrame := nil; inherited Destroy; end; function TGLDBoxParamsFrame.HaveBox: GLboolean; begin Result := False; if Assigned(FDrawer) and Assigned(FDrawer.EditedObject) and (FDrawer.EditedObject is TGLDBox) then Result := True; end; function TGLDBoxParamsFrame.GetParams: TGLDBoxParams; begin if HaveBox then with TGLDBox(FDrawer.EditedObject) do begin Result.Position := Position.Vector3f; Result.Rotation := Rotation.Params; end else begin Result.Position := GLD_VECTOR3F_ZERO; Result.Rotation := GLD_ROTATION3D_ZERO; end; Result.Color := NameAndColor.ColorParam; Result.Length := UD_Length.Position; Result.Width := UD_Width.Position; Result.Height := UD_Height.Position; Result.LengthSegs := UD_LengthSegs.Position; Result.WidthSegs := UD_WidthSegs.Position; Result.HeightSegs := UD_HeightSegs.Position; end; procedure TGLDBoxParamsFrame.SetParams(const Name: string; const Color: TGLDColor3ub; const Length, Width, Height: GLfloat; const LengthSegs, WidthSegs, HeightSegs: GLushort); begin NameAndColor.NameParam := Name; NameAndColor.ColorParam := Color; UD_Length.Position := Length; UD_Width.Position := Width; UD_Height.Position := Height; UD_LengthSegs.Position := LengthSegs; UD_WidthSegs.Position := WidthSegs; UD_HeightSegs.Position := HeightSegs; end; procedure TGLDBoxParamsFrame.SetParamsFrom(Box: TGLDBox); begin if not Assigned(Box) then Exit; with Box do SetParams(Name, Color.Color3ub, Length, Width, Height, LengthSegs, WidthSegs, HeightSegs); end; procedure TGLDBoxParamsFrame.ApplyParams; begin if HaveBox then TGLDBox(FDrawer.EditedObject).Params := GetParams; end; procedure TGLDBoxParamsFrame.SizeChangeUD(Sender: TObject); begin if HaveBox then with TGLDBox(FDrawer.EditedObject) do if Sender = UD_Length then Length := UD_Length.Position else if Sender = UD_Width then Width := UD_Width.Position else if Sender = UD_Height then Height := UD_Height.Position; end; procedure TGLDBoxParamsFrame.SegmentsChangeUD(Sender: TObject; Button: TUDBtnType); begin if HaveBox then with TGLDBox(FDrawer.EditedObject) do if Sender = UD_LengthSegs then LengthSegs := UD_LengthSegs.Position else if Sender = UD_WidthSegs then WidthSegs := UD_WidthSegs.Position else if Sender = UD_HeightSegs then HeightSegs := UD_HeightSegs.Position; end; procedure TGLDBoxParamsFrame.EditEnter(Sender: TObject); begin ApplyParams; end; procedure TGLDBoxParamsFrame.Notification(AComponent: TComponent; Operation: TOperation); begin if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and (Operation = opRemove) then FDrawer := nil; inherited Notification(AComponent, Operation); end; procedure TGLDBoxParamsFrame.SetDrawer(Value: TGLDDrawer); begin FDrawer := Value; NameAndColor.Drawer := FDrawer; end; procedure Register; begin //RegisterComponents('GLDraw', [TGLDBoxParamsFrame]); end; end.
unit untMenuPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.ImageList, System.Actions, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.WinXCtrls, Vcl.StdCtrls, Vcl.CategoryButtons, Vcl.Buttons, Vcl.ImgList, Vcl.Imaging.PngImage, Vcl.ComCtrls, Vcl.ActnList, Vcl.Menus; type TfrmMenuPrincipal = class(TForm) pnlToolbar: TPanel; pnlShowFrame: TPanel; SV: TSplitView; imlIcons: TImageList; imgMenu: TImage; ActionListMenu: TActionList; actCadastro: TAction; actRelatorio: TAction; lblTitle: TLabel; ColorDlgMenu: TColorDialog; catRelatorio: TCategoryButtons; catMenuItems: TCategoryButtons; catcadastro: TCategoryButtons; ActRClientes: TAction; ActRProjeto: TAction; ActCProjeto: TAction; ActCClientes: TAction; PanelTexto: TPanel; Panel1: TPanel; Image1: TImage; Image2: TImage; Timer: TTimer; PanelHora: TPanel; procedure SVClosed(Sender: TObject); procedure SVOpened(Sender: TObject); procedure SVOpening(Sender: TObject); procedure catMenuItemsCategoryCollapase(Sender: TObject; const Category: TButtonCategory); procedure imgMenuClick(Sender: TObject); procedure actConfiguracaoExecute(Sender: TObject); procedure actRelatorioExecute(Sender: TObject); procedure actCadastroExecute(Sender: TObject); procedure SVMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure ChamaSubMenu(Menu,SubMenuBt: TCategoryButtons ; Rect: TRect ) ; procedure ActCProjetoExecute(Sender: TObject); procedure ActCClientesExecute(Sender: TObject); procedure TimerTimer(Sender: TObject); procedure Image1Click(Sender: TObject); private { Private declarations } rec : TRect ; FFormActive: TForm; procedure LoadForm(AClass: TFormClass); public var nomeMenu : string; end; var frmMenuPrincipal: TfrmMenuPrincipal; implementation {$R *.dfm} uses untCadastroProjetos; // procedure que irei utilizar para da show nos forms. procedure TfrmMenuPrincipal.LoadForm(AClass: TFormClass); begin if Assigned(Self.FFormActive) then begin Self.FFormActive.Close; Self.FFormActive.Free; Self.FFormActive := nil; end; // Self.FFormActive := AClass.Create(nil); Self.FFormActive.Parent := Self.pnlShowFrame; Self.FFormActive.BorderStyle := TFormBorderStyle.bsNone; // Self.FFormActive.Top := 0; Self.FFormActive.Left := 0; Self.FFormActive.Align := TAlign.alClient; // Self.FFormActive.Show; // end; procedure TfrmMenuPrincipal.imgMenuClick(Sender: TObject); begin if SV.Opened then SV.Close else SV.Open; end; procedure TfrmMenuPrincipal.SVClosed(Sender: TObject); begin // When TSplitView is closed, adjust ButtonOptions and Width catMenuItems.ButtonOptions := catMenuItems.ButtonOptions - [boShowCaptions]; if SV.CloseStyle = svcCompact then catMenuItems.Width := SV.CompactWidth; end; procedure TfrmMenuPrincipal.SVOpened(Sender: TObject); begin // muda o tramanho dos submenus na animação quando abrir o TSplitView catMenuItems.ButtonOptions := catMenuItems.ButtonOptions + [boShowCaptions]; catMenuItems.Width := SV.OpenedWidth; end; procedure TfrmMenuPrincipal.SVOpening(Sender: TObject); begin // muda o tramanho dos submenus na animação catMenuItems.ButtonOptions := catMenuItems.ButtonOptions + [boShowCaptions]; catMenuItems.Width := SV.OpenedWidth; end; procedure TfrmMenuPrincipal.TimerTimer(Sender: TObject); begin PanelHora.Caption := DateToStr(now) + ' ' + TimeToStr(now); end; procedure TfrmMenuPrincipal.ActCClientesExecute(Sender: TObject); begin MessageDlg('Opção em Desenvolvimento!', mtError, [mbOk], 0); end; procedure TfrmMenuPrincipal.actConfiguracaoExecute(Sender: TObject); begin if ColorDlgMenu.Execute then Begin SV.Color := ColorDlgMenu.Color ; pnlToolbar.Color := ColorDlgMenu.Color ; End; end; procedure TfrmMenuPrincipal.ActCProjetoExecute(Sender: TObject); begin // nomeMenu := lblTitle.caption; // lblTitle.caption := lblTitle.caption + ' > ' + actCadastro.caption + ' > ' + ActCProjeto.caption; // Self.LoadForm(TfrmCadastroProjetos); // end; Procedure TfrmMenuPrincipal.actRelatorioExecute(Sender: TObject); begin MessageDlg('Opção em Desenvolvimento!', mtError, [mbOk], 0); end; procedure TfrmMenuPrincipal.actCadastroExecute(Sender: TObject); begin ChamaSubMenu( catMenuItems,catcadastro,rec ) ; end; procedure TfrmMenuPrincipal.catMenuItemsCategoryCollapase(Sender: TObject; const Category: TButtonCategory); begin catMenuItems.Categories[0].Collapsed := true; end; procedure TfrmMenuPrincipal.ChamaSubMenu(Menu, SubMenuBt: TCategoryButtons; Rect: TRect); var i:integer ; begin // usar a Tag do SubMenu para Fechar quando abrir um Outro SubMenu for I:= 0 to ComponentCount -1 do begin if ( Components[I] is TCategoryButtons ) then begin If ( TCategoryButtons(Components[i]).Tag = 1 ) then TCategoryButtons(Components[i]).Visible := false ; end; end; Rect := Menu.Categories.CategoryButtons.GetButtonRect(Menu.Categories.CategoryButtons.SelectedItem) ; SubMenuBt.Left := Menu.Categories[0].Items[0].CategoryButtons.width - Menu.Categories[0].Items[0].CategoryButtons.width ; SubMenuBt.Top := (rect.Top - 20); SubMenuBt.Visible := true ; SubMenuBt.Show ; end; procedure TfrmMenuPrincipal.Image1Click(Sender: TObject); begin close; end; procedure TfrmMenuPrincipal.SVMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin catRelatorio.Visible := false; catcadastro.Visible := false; end; end.
unit fileutil; interface procedure myCopyfile(_from, _to: String); procedure Deletefile(_from: String); procedure Renamefile(_from, _to: String); procedure Movefile(_from, _to: String); implementation uses Windows, shellapi, shlobj, forms, sysUtils, Messages, Dialogs; procedure myCopyfile(_from, _to: String); var f: TSHFileOPStruct; f_from, f_to: array[0..255] of char; k:integer; begin for k:=0 to 255 do begin f_from[k]:=#0; f_to[k]:=#0; end; F.Wnd := application.handle; F.wFunc := FO_COPY; StrPcopy(f_from,_from); StrPcopy(f_to,_to); F.pFrom := f_from; F.pTo := f_to; F.fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR; if ShFileOperation(F) <> 0 then ShowMessage('Erro na Cópia. Tente novamente.'); end; procedure Deletefile(_from: String); var f: TSHFileOPStruct; f_from, f_to: array[0..255] of char; k:integer; begin for k:=0 to 255 do begin f_from[k]:=#0; f_to[k]:=#0; end; F.Wnd := application.handle; F.wFunc := FO_DELETE; strpcopy(f_from,_from); F.pFrom := f_from; F.pTo := f_from; F.fFlags := FOF_NOCONFIRMATION; if ShFileOperation(F) <> 0 then ShowMessage('Erro na exclusão.'); end; procedure Renamefile(_from, _to: String); var f: TSHFileOPStruct; f_from, f_to: array[0..255] of char; k:integer; begin for k:=0 to 255 do begin f_from[k]:=#0; f_to[k]:=#0; end; F.Wnd := application.handle; F.wFunc := FO_RENAME; StrPcopy(f_from,_from); StrPcopy(f_to,_to); F.pFrom := f_from; F.pTo := f_to; F.fFlags := FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR; if ShFileOperation(F) <> 0 then ShowMessage('Erro ao renomear.'); end; procedure Movefile(_from, _to: String); var f: TSHFileOPStruct; f_from, f_to: array[0..255] of char; k:integer; begin for k:=0 to 255 do begin f_from[k]:=#0; f_to[k]:=#0; end; F.Wnd := application.handle; F.wFunc := FO_move; StrPcopy(f_from,_from); StrPcopy(f_to,_to); F.pFrom := f_from; F.pTo := f_from; F.fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR; if ShFileOperation(F) <> 0 then ShowMessage('Erro ao mover.'); end; end.
unit UnitConstantes; {$I Compilar.inc} interface const NomeDoPrograma = 'Xtreme RAT'; {$IFDEF XTREMETRIAL} VersaoDoPrograma = '3.6'; {$ENDIF} {$IFDEF XTREMEPRIVATE} VersaoDoPrograma = '3.6 Private'; {$ENDIF} {$IFDEF XTREMEPRIVATEFUD} VersaoDoPrograma = '3.6 Private (FUD)'; {$ENDIF} DelimitadorComandos = 'ªªª###╚╚╚'; DelimitadorComandosPassword = '###@@@!!!'; RegeditDelimitador = '$%%$**'; ResourceName = 'XTREME'; EditSvrID = '&&&@&&&'; XORPass = 123; MaxBufferSize = 32768; NEWVERSION = 'newversion'; MYVERSION = 'myversion'; WRONGPASS = 'wrongpass'; NEWCONNECTION = 'newconnection'; MAININFO = 'maininfo'; WEBCAMLIST = 'webcamlist'; DESINSTALAR = 'desinstalar'; DESCONECTAR = 'desconectar'; RECONECTAR = 'reconectar'; CHANGEGROUP = 'changegroup'; DESATIVAR = 'desativar'; RESTARTSERVER = 'restartserver'; RENOMEAR = 'renomear'; UPDATESERVERLOCAL = 'updateserverlocal'; RECEBERARQUIVO = 'receberarquivo'; EXECCOMANDO = 'execcomando'; DOWNEXEC = 'downexec'; UPDATESERVERLINK = 'updateserverlink'; OPENWEB = 'openweb'; PING = 'ping'; PONG = 'pong'; GETACCOUNTTYPE = 'getaccounttype'; GETPASSWORDS = 'getpasswords'; KEYSEARCH = 'keysearch'; FILESEARCH = 'filesearch'; ENVIARLOGSKEY = 'enviarlogskey'; GETPROCESSLIST = 'getprocesslist'; KILLPROCESSID = 'killprocessid'; SUSPENDPROCESSID = 'suspendprocess'; RESUMEPROCESSID = 'resumeprocessid'; CPUUSAGE = 'cpuusage'; PROCESS = 'processos'; JANELAS = 'janelas'; LISTADEJANELAS = 'listadejanelas'; FECHARJANELA = 'fecharjanela'; HABILITARJANELA = 'habilitarjanela'; DESABILITARJANELA = 'desabilitarjanela'; OCULTARJANELA = 'ocultarjanela'; MOSTRARJANELA = 'mostrarjanela'; MINIMIZARJANELA = 'minimizarjanela'; MAXIMIZARJANELA = 'maximizarjanela'; RESTAURARJANELA = 'restaurarjanela'; FINALIZARJANELA = 'finalizarjanela'; MUDARCAPTION = 'mudarcaption'; CRAZYWINDOW = 'crazywindow'; SENDKEYSWINDOW = 'sendkeyswindow'; WINDOWPREV = 'windowprev'; SERVICOS = 'servicos'; LISTADESERVICOS = 'listadeservicos'; INSTALARSERVICO = 'instalarservico'; PARARSERVICO = 'pararservico'; INICIARSERVICO = 'iniciarservico'; REMOVERSERVICO = 'removerservico'; EDITARSERVICO = 'editarservico'; REGISTRO = 'registro'; LISTADECHAVES = 'listadechaves'; LISTADEDADOS = 'listadedados'; NOVOREGISTRO = 'novoregistro'; RENOMEARREGISTRO = 'renomearregistro'; NOVACHAVE = 'novachave'; APAGARREGISTRO = 'apagarregistro'; APAGARCHAVE = 'apagarchave'; RENOMEARCHAVE = 'renomearchave'; STARTUPMANAGER = 'startupmanager'; SHELL = 'shell'; SHELLSTART = 'shellstart'; SHELLCOMMAND = 'shellcommand'; SHELLDESATIVAR = 'shelldesativar'; CLIPBOARD = 'clipboard'; GETCLIPBOARD = 'getclipboard'; CLEARCLIPBOARD = 'clearclipboard'; SETCLIPBOARD = 'setclipboard'; LISTADEDISPOSITIVOSPRONTA = 'listadedispositivospronta'; LISTADEDISPOSITIVOSEXTRASPRONTA = 'listadedispositivosextraspronta'; LISTDEVICES = 'listdevices'; LISTEXTRADEVICES = 'listextradevices'; LISTADEPORTASPRONTA = 'listadeportasativas'; FINALIZARCONEXAO = 'finalizarconexao'; FINALIZARPROCESSOPORTAS = 'finalizarprocessoportas'; LISTARPORTAS = 'listarportas'; LISTARPORTASDNS = 'listarportasdns'; PROGRAMAS = 'programas'; LISTADEPROGRAMAS = 'listadeprogramas'; DESINSTALARPROGRAMA = 'desinstalarprograma'; DESINSTALARPROGRAMASILENT = 'desinstalarprogramassilent'; DESKTOP = 'desktop'; DESKTOPNEW = 'desktopnew'; DESKTOPCONFIG = 'desktopconfig'; STARTDESKTOP = 'startdesktop'; DESKTOPSTREAM = 'desktopstream'; DESKTOPMOUSEPOS = 'desktopmousepos'; DESKTOPMOVEMOUSE = 'desktopmovemouse'; DESKTOPPREVIEW = 'desktoppreview'; TECLADOEXECUTAR = 'tecaladoexecutar'; MOUSECLICK = 'mouseclick'; WEBCAM = 'webcam'; WEBCAMSTART = 'webcamstart'; WEBCAMSTREAM = 'webcamstream'; WEBCAMCONFIG = 'webcamconfig'; WEBCAMSTOP = 'webcamstop'; FDIVERSOS = 'fdiversos'; NEWFDIVERSOS = 'newfdiversos'; FMESSAGE = 'fmessage'; FSHUTDOWN = 'fshutdown'; FHIBERNAR = 'fhibernar'; FLOGOFF = 'flogoff'; POWEROFF = 'fpoweroff'; FRESTART = 'frestart'; FDESLMONITOR = 'fdeslmonitor'; BTN_START_HIDE = 'btnstarthide'; BTN_START_SHOW = 'btnstartshow'; BTN_START_BLOCK = 'btnstartblock'; BTN_START_UNBLOCK = 'btnstartunblock'; DESK_ICO_HIDE = 'deskicohide'; DESK_ICO_SHOW = 'deskicoshow'; DESK_ICO_BLOCK = 'deskicoblock'; DESK_ICO_UNBLOCK = 'deskicounblock'; TASK_BAR_HIDE = 'taskbarhide'; TASK_BAR_SHOW = 'taskbarshow'; TASK_BAR_BLOCK = 'taskbarblock'; TASK_BAR_UNBLOCK = 'taskbarunblock'; MOUSE_BLOCK = 'mouseblock'; MOUSE_UNBLOCK = 'mouseunblock'; MOUSE_SWAP = 'mouseswap'; SYSTRAY_ICO_HIDE = 'systrayicohide'; SYSTRAY_ICO_SHOW = 'systrayicoshow'; OPENCD = 'opencd'; CLOSECD = 'closecd'; KEYLOGGER = 'keylogger'; KEYLOGGERNEW = 'keyloggernew'; KEYLOGGERATIVAR = 'keyloggerativar'; KEYLOGGERDESATIVAR = 'keyloggerdesativar'; KEYLOGGERBAIXAR = 'keyloggerbaixar'; KEYLOGGEREXCLUIR = 'keyloggerexcluir'; KEYLOGGERONLINESTART = 'keyloggeronlinestart'; KEYLOGGERONLINESTOP = 'keyloggeronlinestop'; KEYLOGGERONLINEKEY = 'keyloggeronlinekey'; FILEMANAGER = 'filemanager'; FILEMANAGERNEW = 'filemanagernew'; FMDRIVELIST = 'fmdrivelist'; FMSPECIALFOLDERS = 'fmspecialfolders'; FMSPECIALFOLDERS2 = 'fmspecialfolders2'; FMSHAREDDRIVELIST = 'fmshareddrivelist'; FMFOLDERLIST = 'fmfolderlist'; FMFOLDERLIST2 = 'fmfolderlist2'; FMFILELIST = 'fmfilelist'; FMFILELIST2 = 'fmfilelist2'; FMFILESEARCHLIST = 'fmfilesearchlist'; FMFILESEARCHLISTSTOP = 'fmfilesearchliststop'; FMCRIARPASTA = 'fmcriarpasta'; FMRENOMEARPASTA = 'fmrenomearcriarpasta'; FMDELETARPASTA = 'fmdeletarpasta'; FMDELETARPASTALIXO = 'fmdeletarpastalixo'; FMEXECNORMAL = 'fmexecnormal'; FMEXECHIDE = 'fmexechide'; FMEXECPARAM = 'fmexecparam'; FMDELETARARQUIVO = 'fmdeletararquivo'; FMDELETARARQUIVOLIXO = 'fmdeletararquivolixo'; FMEDITARARQUIVO = 'fmeditararquivo'; FMWALLPAPER = 'fmwallpaper'; FMTHUMBS = 'fmthumbs'; FMTHUMBS2 = 'fmthumbs2'; FMTHUMBS_SEARCH = 'fmthumbs_search'; FMDOWNLOAD = 'fmdownload'; FMDOWNLOADFOLDERADD = 'fmdownloadfolderadd'; FMDOWNLOADFOLDER = 'fmdownloadfolder'; FMDOWNLOADERROR = 'fmdownloaderror'; FMRESUMEDOWNLOAD = 'fmresumedownload'; FMUPLOAD = 'fmupload'; FMUPLOADERROR = 'fmuploaderror'; FMCOPYFILE = 'fmcopyfile'; FMCOPYFOLDER = 'fmcopyfolder'; FMDOWNLOADALL = 'fmdownloadall'; FMRARFILE = 'fmrarfile'; FMGETRARFILE = 'fmgetrarfile'; FMUNRARFILE = 'fmunrarfile'; FMCHECKRAR = 'fmcheckrar'; FMUNZIPFILE = 'fmunzipfile'; AUDIO = 'audio'; AUDIOSETTINGS = 'audiosettings'; AUDIOSTREAM = 'audiostream'; STARTAUDIO = 'startaudio'; SERVERSETTINGS = 'serversettings'; GETSERVERSETTINGS = 'getserversettings'; GETDESKTOPPREVIEW = 'getdesktoppreview'; GETDESKTOPPREVIEWINFO = 'getdesktoppreviewinfo'; CHANGESERVERSETTINGS = 'changeserversettings'; CHROMEPASS = 'chromepass'; CHAT = 'chat'; CHATSTART = 'chatstart'; CHATSTOP = 'chatstop'; CHATTEXT = 'chattext'; MSN = 'msn'; GETMSNSTATUS = 'getmsnstatus'; SETMSNSTATUS = 'setmsnstatus'; MSNCONTACTLIST = 'msncontactlist'; EXITMSN = 'exitmsn'; MSNINFO = 'msninfo'; MSNADDCONTACT = 'msnaddcontact'; MSNDELCONTACT = 'msndelcontact'; MSNBLOCKCONTACT = 'msnblockcontact'; MSNUNBLOCKCONTACT = 'msnunblockcontact'; PROXYSTART = 'proxystart'; PROXYSTOP = 'proxystop'; MOUSESTART = 'mousestart'; MOUSESTOP = 'mousestop'; UPLOADANDEXECUTE = 'uploadandexecute'; UPLOADANDEXECUTEYES = 'uploadandexecuteyes'; UPLOADANDEXECUTENO = 'uploadandexecuteno'; FMSENDFTP = 'fmsendftp'; FMSENDFTPYES = 'fmsendftpyes'; FMSENDFTPNO = 'fmsendftpno'; MOUSELOGGERSTOP = 'mouseloggerstop'; MOUSELOGGERSTART = 'mouseloggerstart'; MOUSELOGGERBUFFER = 'mouseloggerbuffer'; MOUSELOGGERSTARTSEND = 'mouseloggerstartsend'; MOUSELOGGERSTOPSEND = 'mouseloggerstopsend'; MOUSELOGGERDELETE = 'mouseloggerdelete'; implementation end.
library keyboard; { Библиотека отслеживает нажатие всех возможных клавиш, конвертирует их в строки, отправляет в место, куда назначено при запуске клавиатуры } interface const // Virtual Key Codes VK_Back = 8; VK_Tab = 9; VK_LineFeed = 10; VK_Enter = 13; VK_Return = 13; VK_ShiftKey = 16; VK_ControlKey = 17; VK_Menu = 18; VK_Pause = 19; VK_CapsLock = 20; VK_Capital = 20; VK_Escape = 27; VK_Space = 32; VK_Prior = 33; VK_PageUp = 33; VK_PageDown = 34; VK_Next = 34; VK_End = 35; VK_Home = 36; VK_Left = 37; VK_Up = 38; VK_Right = 39; VK_Down = 40; VK_Select = 41; VK_Print = 42; VK_Snapshot = 44; VK_PrintScreen = 44; VK_Insert = 45; VK_Delete = 46; VK_Help = 47; VK_A = 65; VK_B = 66; VK_C = 67; VK_D = 68; VK_E = 69; VK_F = 70; VK_G = 71; VK_H = 72; VK_I = 73; VK_J = 74; VK_K = 75; VK_L = 76; VK_M = 77; VK_N = 78; VK_O = 79; VK_P = 80; VK_Q = 81; VK_R = 82; VK_S = 83; VK_T = 84; VK_U = 85; VK_V = 86; VK_W = 87; VK_X = 88; VK_Y = 89; VK_Z = 90; VK_LWin = 91; VK_RWin = 92; VK_Apps = 93; VK_Sleep = 95; VK_NumPad0 = 96; VK_NumPad1 = 97; VK_NumPad2 = 98; VK_NumPad3 = 99; VK_NumPad4 = 100; VK_NumPad5 = 101; VK_NumPad6 = 102; VK_NumPad7 = 103; VK_NumPad8 = 104; VK_NumPad9 = 105; VK_Multiply = 106; VK_Add = 107; VK_Separator = 108; VK_Subtract = 109; VK_Decimal = 110; VK_Divide = 111; VK_F1 = 112; VK_F2 = 113; VK_F3 = 114; VK_F4 = 115; VK_F5 = 116; VK_F6 = 117; VK_F7 = 118; VK_F8 = 119; VK_F9 = 120; VK_F10 = 121; VK_F11 = 122; VK_F12 = 123; VK_NumLock = 144; VK_Scroll = 145; VK_LShiftKey = 160; VK_RShiftKey = 161; VK_LControlKey = 162; VK_RControlKey = 163; VK_LMenu = 164; VK_RMenu = 165; VK_KeyCode = 65535; VK_Shift = 65536; VK_Control = 131072; VK_Alt = 262144; VK_Modifiers = -65536; type тНажатие = procedure(лит: string);// ссылка н приём нажатия в terminal.dll тКлава = class public передать: тНажатие;// хранит процедуру из terminal.dll /// клон OnKeyPress procedure Кнп_Нажата(лит: char); begin var стр := лит; self.передать(стр); end; /// Обратный вызов из terminal.dll procedure Кнопка_Вниз(кнп: integer); begin case кнп of VK_Enter: self.передать('enter'); VK_Delete: self.передать('delete'); end; end; constructor Create; begin end; end; implementation begin end.
{********************************************************} { JBS JSON Library } { Copyright (c) 2013 JBS Soluções. } {********************************************************} unit jsonlib; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DB, fpjson, jsonparser, typinfo, zstream, base64; {Converte de dataset para formato JSON} function DataSetToJSON(DataSet: TDataSet; ReturnFields: boolean = True; ReturnData: boolean = True): string; {converte de formato JSON para dataset} function JSONToDataset(var dataset: TDataSet; JsonObject: TJSONObject): boolean; //EncodeString : Encode a String function EncodeString(const Input: string): string; //DecodeString : Decode a String function DecodeString(const Input: string): string; //BoolStr : boolean to string with numbers options function BoolStr(Value: boolean; ToNumberString: boolean = False): string; procedure JSONDataToDataset(AJSON: TJSONData; var ADataSet: TDataSet; const ADateAsString: boolean = True); overload; function CreateFieldsByJson(var dataset: TDataset; ColsJson: TJSONdata): boolean; procedure GetFieldTypeInfo(Field: TField; var FieldType, JsonTyp: string); function CreateJsonValueByField(JsonObject: TJSONObject; Field: TField): boolean; function ImportDataFromJSon(DataSet: TDataSet; DataJson: TJSONData): integer; function GetValue2Field(Field: TField; JsonValue: TJSONOBject): variant; function FieldsToJSON(AFields: TFields; const ADateAsString: boolean = True): string; procedure JSONToFields(AJSON: TJSONObject; var ADataset: TDataset; const ADateAsString: boolean = True); function GetJSONType(const AFieldType: TFieldType): ShortString; const JSON_NULL = 'null'; JSON_STRING = 'string'; JSON_BOOLEAN = 'boolean'; JSON_DATE = 'date'; JSON_FLOAT = 'float'; JSON_INT = 'int'; cstFieldType = 'FieldType'; //< label of json tag FieldType. cstFieldName = 'FieldName'; //< label of json tag FieldName. cstDisplayLabel = 'DisplayLabel'; //< label of json tag Displaylabel. cstFieldSize = 'FieldSize'; //< label of json tag FieldSize. cstJsonType = 'JsonType'; //< label of json tag JsonType. cstRequired = 'Required'; //< label of json tag Required. cstFieldIndex = 'FieldIndex'; //< label of json tag FieldIndex. cstCols = 'Fields'; //< label of json tag Fields. cstData = 'Data'; //< label of json tag Data. implementation const {Constant array of encode chars.} EncodeTable: array[0..63] of char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789+/'; {Constant array of encode Bytes.} DecodeTable: array[#0..#127] of integer = ( byte('='), 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64); type TPacket = packed record case integer of 0: (b0, b1, b2, b3: byte); 1: (i: integer); 2: (a: array[0..3] of byte); 3: (c: array[0..3] of char); end; procedure EncodePacket(const Packet: TPacket; NumChars: integer; OutBuf: PChar); begin OutBuf[0] := EnCodeTable[Packet.a[0] shr 2]; OutBuf[1] := EnCodeTable[((Packet.a[0] shl 4) or (Packet.a[1] shr 4)) and $0000003f]; if NumChars < 2 then OutBuf[2] := '=' else OutBuf[2] := EnCodeTable[((Packet.a[1] shl 2) or (Packet.a[2] shr 6)) and $0000003f]; if NumChars < 3 then OutBuf[3] := '=' else OutBuf[3] := EnCodeTable[Packet.a[2] and $0000003f]; end; function DecodePacket(InBuf: PChar; var nChars: integer): TPacket; begin Result.a[0] := (DecodeTable[InBuf[0]] shl 2) or (DecodeTable[InBuf[1]] shr 4); NChars := 1; if InBuf[2] <> '=' then begin Inc(NChars); Result.a[1] := byte((DecodeTable[InBuf[1]] shl 4) or (DecodeTable[InBuf[2]] shr 2)); end; if InBuf[3] <> '=' then begin Inc(NChars); Result.a[2] := byte((DecodeTable[InBuf[2]] shl 6) or DecodeTable[InBuf[3]]); end; end; procedure EncodeStream(Input, Output: TStream); var InBuf: array[0..509] of byte; OutBuf: array[0..1023] of char; BufPtr: PChar; I, J, K, BytesRead: integer; Packet: TPacket; begin InBuf[0] := 0; OutBuf[0] := #0; K := 0; repeat BytesRead := Input.Read(InBuf, SizeOf(InBuf)); I := 0; BufPtr := OutBuf; while I < BytesRead do begin if BytesRead - I < 3 then J := BytesRead - I else J := 3; Packet.i := 0; Packet.b0 := InBuf[I]; if J > 1 then Packet.b1 := InBuf[I + 1]; if J > 2 then Packet.b2 := InBuf[I + 2]; EncodePacket(Packet, J, BufPtr); Inc(I, 3); Inc(BufPtr, 4); Inc(K, 4); if K > 75 then begin BufPtr[0] := #$0D; BufPtr[1] := #$0A; Inc(BufPtr, 2); K := 0; end; end; Output.Write(Outbuf, BufPtr - PChar(@OutBuf)); until BytesRead = 0; end; procedure DecodeStream(Input, Output: TStream); var InBuf: array[0..75] of char; OutBuf: array[0..60] of byte; InBufPtr, OutBufPtr: PChar; I, J, K, BytesRead: integer; Packet: TPacket; procedure SkipWhite; var C: char; NumRead: integer; begin C := #0; while True do begin NumRead := Input.Read(C, 1); if NumRead = 1 then begin if C in ['0'..'9', 'A'..'Z', 'a'..'z', '+', '/', '='] then begin Input.Position := Input.Position - 1; Break; end; end else Break; end; end; function ReadInput: integer; var WhiteFound, EndReached: boolean; CntRead, Idx, IdxEnd: integer; begin IdxEnd := 0; repeat WhiteFound := False; CntRead := Input.Read(InBuf[IdxEnd], (SizeOf(InBuf) - IdxEnd)); EndReached := CntRead < (SizeOf(InBuf) - IdxEnd); Idx := IdxEnd; IdxEnd := CntRead + IdxEnd; while (Idx < IdxEnd) do begin if not (InBuf[Idx] in ['0'..'9', 'A'..'Z', 'a'..'z', '+', '/', '=']) then begin Dec(IdxEnd); if Idx < IdxEnd then Move(InBuf[Idx + 1], InBuf[Idx], IdxEnd - Idx); WhiteFound := True; end else Inc(Idx); end; until (not WhiteFound) or (EndReached); Result := IdxEnd; end; begin J := 0; repeat SkipWhite; { BytesRead := Input.Read(InBuf, SizeOf(InBuf)); } BytesRead := ReadInput; InBufPtr := InBuf; OutBufPtr := @OutBuf; I := 0; while I < BytesRead do begin Packet := DecodePacket(InBufPtr, J); K := 0; while J > 0 do begin OutBufPtr^ := char(Packet.a[K]); Inc(OutBufPtr); Dec(J); Inc(K); end; Inc(InBufPtr, 4); Inc(I, 4); end; Output.Write(OutBuf, OutBufPtr - PChar(@OutBuf)); until BytesRead = 0; end; function iif(condicao: boolean; verdadeiro,falso: string): string; begin if condicao then result := verdadeiro else result := falso; end; function CreateFieldsByJson(var dataset: TDataset; ColsJson: TJSONData): boolean; var ft: TFieldType; i: integer; fieldName, fieldLabel: string; fieldSize: integer; fieldRequired: boolean; begin try DataSet.Close; dataset.FieldDefs.Clear; for i := 0 to ColsJson.Count - 1 do begin ft := TFieldType(GetEnumValue(typeinfo(TFieldType), 'ft' + (ColsJson.Items[i] as TJSONObject).Strings[cstFieldType])); if ft = ftAutoInc then ft := ftInteger; fieldName := (ColsJson.Items[i] as TJSONObject).Strings[cstFieldName]; fieldSize := (ColsJson.Items[i] as TJSONObject).Integers[cstFieldSize]; fieldRequired := (ColsJson.Items[i] as TJSONObject).Booleans[cstRequired]; fieldLabel := (ColsJson.Items[i] as TJSONObject).Strings[cstDisplayLabel]; dataset.FieldDefs.Add(fieldName, ft, fieldSize, fieldRequired); dataset.FieldDefs.Find(fieldName).CreateField(dataset).DisplayLabel := fieldLabel; end; Result := True; except Result := False; end; end; procedure GetFieldTypeInfo(Field: TField; var FieldType, JsonTyp: string); begin FieldType := GetEnumName(typeinfo(tfieldtype), Ord(Field.DataType)); Delete(FieldType, 1, 2); JsonTyp := GetJSONType(Field.DataType); end; function CreateJsonValueByField(JsonObject: TJSONObject; Field: TField): boolean; begin if Field is TDateTimeField then JsonObject.Objects[Field.FieldName].Value := Field.AsDateTime else if Field is TBlobField then JsonObject.Objects[Field.FieldName].Value := EncodeString(Field.AsString) else JsonObject.Objects[Field.FieldName].Value := Field.Value; Result := True; end; function ImportDataFromJSon(DataSet: TDataSet; DataJson: TJSONData): integer; var i: integer; FieldName: string; FieldValue: variant; begin if not DataSet.Active then DataSet.Open; DataSet.DisableControls; try for i := 0 to DataJson.Count - 1 do begin DataSet.Append; FieldName := (DataJson.Items[i] as TJSONObject).AsString; FieldValue := DataJson.Items[i].Value; if DataSet.FindField(FieldName) <> nil then begin DataSet.FindField(FieldName).Value := FieldValue; end; DataSet.Post; end; finally DataSet.First; DataSet.EnableControls; end; Result := 1; end; function GetValue2Field(Field: TField; JsonValue: TJSONObject): variant; begin if JsonValue.Types[Field.Name] = jtNull then Result := Null else if Field is TDateTimeField then Result := TDateTime(JsonValue.AsInteger) else if (Field is TIntegerField) or (Field is TLargeintField) then Result := JsonValue.AsInteger else if Field is TNumericField then Result := JsonValue.AsFloat else if Field is TBooleanField then Result := JsonValue.AsBoolean else if Field is TStringField then Result := JsonValue.AsString else if Field is TBlobField then Result := DecodeString(JsonValue.AsString); end; {Converte de dataset para formato JSON} function DataSetToJSON(DataSet: TDataSet; ReturnFields: boolean = True; ReturnData: boolean = True): string; var i: integer; sFields, sData, FieldType, JsonTyp: string; List: TStringList; begin List := TStringList.Create; JsonTyp := ''; FieldType := ''; sData := ''; sFields := ''; try List.Sorted := True; if ReturnFields then begin sFields := '"' + cstCols + '":['; for i := 0 to DataSet.FieldCount - 1 do begin GetFieldTypeInfo(DataSet.Fields[i], FieldType, JsonTyp); sFields := sFields + format( '{"%s":"%s","%s":%s,"%s":"%s","%s":%s,"%s":"%s","%s":%s,"%s":"%s"}', [cstJsonType, JsonTyp, cstFieldIndex, IntToStr(DataSet.Fields[i].Index), cstFieldType, FieldType, cstFieldSize, iif(FieldType = 'Integer', '0', IntToStr(DataSet.Fields[i].Size)), cstFieldName, Dataset.Fields[i].FieldName, cstRequired, BoolStr(DataSet.Fields[i].Required), cstDisplayLabel, Dataset.Fields[i].DisplayLabel]); if i < (dataset.FieldCount - 1) then sFields := sFields + ','; List.Add(DataSet.Fields[i].FieldName + '=' + JsonTyp); end; sFields := sFields + ']'; end; if ReturnData then begin DataSet.DisableControls; DataSet.First; sData := '"' + cstData + '":['; while not dataset.EOF do begin sData := sData + FieldsToJSON(Dataset.Fields); dataset.Next; if not dataset.EOF then sData := sData + ','; end; sData := sData + ']'; end; if returnFields then Result := sFields; if returndata then begin if ReturnFields then Result := sFields + ', ' + sData else Result := sData; end; Result := format('{%s}', [Result]); finally List.Free; DataSet.First; DataSet.EnableControls; end; end; {converte de formato JSON para dataset} function JSONToDataset(var dataset: TDataSet; JsonObject: TJSONObject): boolean; begin if JsonObject = nil then begin Result := False; Exit; end; CreateFieldsByJson(dataset, JsonObject[cstCols]); if dataset.FieldDefs.Count > 0 then dataset.Open else begin Result := False; exit; end; JSONDataToDataset(JsonObject[cstData], dataset); Result := True; end; procedure JSONDataToDataset(AJSON: TJSONData; var ADataSet: TDataSet; const ADateAsString: boolean = True); overload; var I, iCount: integer; P: TJSONParser; O: TJsonArray; json: string; begin try json := AJSON.AsJSON; P := TJSONParser.Create(json); O := (P.Parse as TJSONArray); iCount := Pred(O.Count); for I := 0 to iCount do begin ADataSet.Append; JSONToFields(O.Objects[I], ADataSet, ADateAsString); ADataSet.Post; end; finally P.Free; O.Free; end; end; function FieldsToJSON(AFields: TFields; const ADateAsString: boolean = True): string; var I: integer; VField: TField; VFieldType, VFieldName: ShortString; VJSON: TJSONObject; begin try VJSON := TJSONOBject.Create; for I := 0 to Pred(AFields.Count) do begin VField := AFields[I]; VFieldType := GetJSONType(VField.DataType); VFieldName := VField.FieldName; if (VFieldType = JSON_NULL) or VField.IsNull then begin VJSON.Add(VFieldName); Continue; end; if VFieldType = JSON_STRING then VJSON.Add(VFieldName, VField.AsString) else if VFieldType = JSON_BOOLEAN then VJSON.Add(VFieldName, VField.AsBoolean) else if VFieldType = JSON_DATE then begin if ADateAsString then VJSON.Add(VFieldName, VField.AsString) else VJSON.Add(VFieldName, VField.AsFloat); end else if (VFieldType = JSON_FLOAT) and (VField.Size > 0) then VJSON.Add(VFieldName, VField.AsFloat) else if (VFieldType = JSON_FLOAT) and (VField.Size = 0) then VJSON.Add(VFieldName, VField.AsInteger) else if VFieldType = JSON_INT then VJSON.Add(VFieldName, VField.AsInteger) else VJSON.Add(VFieldName, VField.AsString); end; Result := VJSON.AsJSON; finally VJSON.Free; end; end; procedure JSONToFields(AJSON: TJSONObject; var ADataset: TDataset; const ADateAsString: boolean = True); var I: integer; VName: string; VField: TField; VData: TJSONData; begin for I := 0 to Pred(AJSON.Count) do begin VName := (AJSON as tjsonobject).Names[I]; VField := ADataset.Fields.FindField(VName); if not Assigned(VField) then Continue; VData := AJSON.Items[I]; ADataset.FieldByName(VName).Clear; if VData.IsNull then Exit; if (VField is TStringField) or (VField is TBinaryField) or (VField is TBlobField) or (VField is TVariantField) then ADataset.FieldByName(VName).AsString := VData.AsString else if (VField is TLongintField) or (VField is TLargeintField) or (VField is TAutoIncField) then ADataset.FieldByName(VName).Value := VData.AsInteger else if (VField is TFloatField) or (VField is TBCDField) or (VField is TFMTBCDField) then ADataset.FieldByName(VName).AsFloat := VData.AsFloat else if VField is TBooleanField then ADataset.FieldByName(VName).AsBoolean := VData.AsBoolean else if VField is TDateTimeField then begin if ADateAsString then ADataset.FieldByName(VName).AsDateTime := StrToDateTime(VData.AsString) else ADataset.FieldByName(VName).AsDateTime := VData.AsFloat; end else ADataset.FieldByName(VName).AsString := VData.AsString; end; end; function GetJSONType(const AFieldType: TFieldType): ShortString; begin Result := JSON_NULL; case AFieldType of ftUnknown: Result := JSON_STRING; ftString: Result := JSON_STRING; ftSmallint: Result := JSON_INT; ftInteger: Result := JSON_INT; ftWord: Result := JSON_INT; ftBoolean: Result := JSON_BOOLEAN; ftFloat: Result := JSON_FLOAT; ftCurrency: Result := JSON_FLOAT; ftBCD: Result := JSON_FLOAT; ftDate: Result := JSON_DATE; ftTime: Result := JSON_STRING; ftDateTime: Result := JSON_DATE; ftAutoInc: Result := JSON_INT; ftBlob: Result := JSON_STRING; ftMemo: Result := JSON_STRING; ftFmtMemo: Result := JSON_STRING; ftFixedChar: Result := JSON_STRING; ftWideString: Result := JSON_STRING; ftLargeint: Result := JSON_INT; ftVariant: Result := JSON_STRING; ftTimeStamp: Result := JSON_DATE; ftFMTBcd: Result := JSON_FLOAT; ftFixedWideChar: Result := JSON_STRING; ftWideMemo: Result := JSON_STRING; else Result := JSON_STRING; end; end; function EncodeString(const Input: string): string; var InStr, OutStr: TStringStream; begin InStr := TStringStream.Create(Input); try OutStr := TStringStream.Create(''); try EncodeStream(InStr, OutStr); Result := OutStr.DataString; finally OutStr.Free; end; finally InStr.Free; end; end; function DecodeString(const Input: string): string; var InStr, OutStr: TStringStream; begin InStr := TStringStream.Create(Input); try OutStr := TStringStream.Create(''); try DecodeStream(InStr, OutStr); Result := OutStr.DataString; finally OutStr.Free; end; finally InStr.Free; end; end; function BoolStr(Value: boolean; ToNumberString: boolean = False): string; begin if Value then Result := BoolToStr(ToNumberString, '1', 'true') else Result := BoolToStr(ToNumberString, '0', 'false'); end; end.
unit cs_OrdersType_MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cs_OrdersType_DM, cxGridDBTableView, cxGrid, dxBar, dxBarExtItems, iBase, cxCheckBox, uCS_Constants, cxTextEdit, ImgList, AArray, ib_externals, AppStruClasses, RxMemDs, FIBDataset, pFIBDataset, uCS_Resources; type TcsFormOrdersType = class(TForm) dxBarManager1: TdxBarManager; btnSelect: TdxBarLargeButton; cxGrid1: TcxGrid; TypesView: TcxGridDBTableView; col_IdType: TcxGridDBColumn; col_Name: TcxGridDBColumn; col_Shablon: TcxGridDBColumn; col_IdShablon: TcxGridDBColumn; col_IsActive: TcxGridDBColumn; col_IsLogical: TcxGridDBColumn; col_CanCancel: TcxGridDBColumn; col_IdTypeEdbo: TcxGridDBColumn; cxGridLevel1: TcxGridLevel; DisabledLargeImages: TImageList; PopupImageList: TImageList; LargeImages: TImageList; Styles: TcxStyleRepository; BackGround: TcxStyle; FocusedRecord: TcxStyle; Header: TcxStyle; DesabledRecord: TcxStyle; cxStyle15: TcxStyle; cxStyle16: TcxStyle; cxStyle17: TcxStyle; cxStyle18: TcxStyle; cxStyle19: TcxStyle; cxStyle20: TcxStyle; cxStyle21: TcxStyle; cxStyle22: TcxStyle; cxStyle23: TcxStyle; cxStyle24: TcxStyle; cxStyle25: TcxStyle; cxStyle26: TcxStyle; cxStyle27: TcxStyle; cxStyle28: TcxStyle; cxStyle29: TcxStyle; cxStyle30: TcxStyle; Default_StyleSheet: TcxGridTableViewStyleSheet; DevExpress_Style: TcxGridTableViewStyleSheet; btnImport: TdxBarLargeButton; btnExit: TdxBarLargeButton; procedure btnSelectClick(Sender: TObject); procedure btnImportClick(Sender: TObject); procedure btnExitClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } EDBOGuidesIntf: TFMASAppModule; EDBOPersonIntf: TFMASAppModule; ResultArray: TAArray; CanConnectToEdbo: Boolean; IdMode: Integer; // режимы подключения формы: 0 - обычный, 1 - выборка только наших типов, 2 - только типов едбо procedure InitCaptions; procedure InitStyles; procedure InitMode(IdMode: Integer); //настройка формы в соответствии с режимом function MyCsConnectToEdbo: Boolean; public { Public declarations } IndLangVWF: Integer; TextViewColorVWF: TColor; ID_User_Global: Int64; User_Name_Global: string; function GetOrdersTypeFromEdbo: Boolean; //отобрать из едбо всю информацию о приказах constructor Create(AOwner: TComponent; aParam: TAArray); reintroduce; end; procedure ShowAllPrkBpl(aOwner: TComponent; aParam: TAArray); stdcall; exports ShowAllPrkBpl; var csFormOrdersType: TcsFormOrdersType; DM: TDM; implementation {$R *.dfm} procedure ShowAllPrkBpl(aOwner: TComponent; aParam: TAArray); var T: TcsFormOrdersType; begin T := TcsFormOrdersType.Create(aOwner, aParam); T.FormStyle := aParam['Input']['aFrmStyle'].AsVariant; case T.FormStyle of fsNormal: begin T.ShowModal; end; fsMDIChild: begin end; else T.Free; end; end; constructor TcsFormOrdersType.Create(AOwner: TComponent; aParam: TAArray); var DBHandle: TISC_DB_HANDLE; begin if Assigned(PVoid(aParam['Input']['aDBHANDLE'])) then begin DBHandle := PVoid(aParam['Input']['aDBHANDLE'].asInteger); ResultArray := aParam; ID_User_Global := aParam['Input']['ID_USER_GLOBAL'].AsInt64; IndLangVWF := 0; if Assigned(aParam['Input']['ID_MODE']) then IdMode := aParam['Input']['ID_MODE'].AsInteger else IdMode := 0; inherited Create(aOwner); InitCaptions; WindowState := wsMaximized; DM := TDM.Create(self, DBHandle); //инициализация режима должна происходить после создания DM формы, //т.к. при инициализации режима мы меняем селект датасета на ДМ форме InitMode(IdMode); TypesView.DataController.DataSource := DM.DSOrdersType; end else ShowMessage('Ошибка HANDLE`a Базы'); end; procedure TcsFormOrdersType.InitCaptions; begin csFormOrdersType.Caption := nOrdersType_MainForm_Caption[IndLangVWF]; btnImport.Caption := nAction_GetOrderTypeFromEDBO[IndLangVWF]; btnSelect.Caption := nAction_Vibrat[IndLangVWF]; btnExit.Caption := nAction_Exit[IndLangVWF]; end; procedure TcsFormOrdersType.InitStyles; begin end; procedure TcsFormOrdersType.btnSelectClick(Sender: TObject); begin ResultArray['OutPut']['ID_TYPE_EDBO'].AsInteger := DM.DSetOrdersType.fbn('NUMBER_FROM_EDBO').AsInteger; ResultArray['OutPut']['TYPE_NAME'].AsString := DM.DSetOrdersType.fbn('TYPE_NAME').AsString; Close; end; function TcsFormOrdersType.MyCsConnectToEdbo: Boolean; var path_str: string; begin try Result := True; with TFMASAppModuleCreator.Create do begin path_str := ExtractFilePath(Application.ExeName) + 'Contingent_Student\'; //Экземпляр для работы с веб-сервисом EDBOGuides EDBOGuidesIntf := CreateFMASModule(path_str, 'EDBOIntf'); if (EDBOGuidesIntf = nil) then begin csMessageDlg(nMsgBoxTitle[IndLangVWF], nMsgErrorWithEDBO[IndLangVWF], mtInformation, [mbOk], 0); Result := False; end; //Экземпляр для работы с веб-сервисом EDBOPerson EDBOPersonIntf := CreateFMASModule(path_str, 'EDBOIntf'); if (EDBOPersonIntf = nil) then begin csMessageDlg(nMsgBoxTitle[IndLangVWF], nMsgErrorWithEDBO[IndLangVWF], mtInformation, [mbOk], 0); Result := False; end; end; except on E: Exception do begin ShowMessage(E.Message); Result := False; end; end; end; function TcsFormOrdersType.GetOrdersTypeFromEdbo: Boolean; var ActualDate: TDateTime; Id_AcademicYear: Integer; Filter: AnsiString; MemoryData_EDBO: TRxMemoryData; i: Integer; PubSysDataDSet: TpFIBDataset; begin Result := True; PubSysDataDSet := TpFIBDataset.Create(Self); PubSysDataDSet.Database := DM.DB; PubSysDataDSet.Transaction := DM.DefaultTransaction; if PubSysDataDSet.Active then PubSysDataDSet.Close; PubSysDataDSet.SQLs.SelectSQL.Text := 'Select Can_Connect_To_Edbo From Pub_Sys_Data'; PubSysDataDSet.Open; if PubSysDataDSet['Can_Connect_To_Edbo'] = null then CanConnectToEdbo := False else CanConnectToEdbo := Boolean(PubSysDataDSet['Can_Connect_To_Edbo']); if CanConnectToEdbo then begin MemoryData_Edbo := TRxMemoryData.Create(Self); (EDBOPersonIntf as IEDBOTools).GetXMLDataFromService('PersonEducationHistoryTypesGet', MemoryData_EDBO); try MemoryData_EDBO.Open; MemoryData_EDBO.First; except on E: Exception do Showmessage(E.Message); end; DM.RxMem_EdboOrdersType.Close; DM.RxMem_EdboOrdersType.EmptyTable; DM.RxMem_EdboOrdersType.Open; for i := 0 to MemoryData_EDBO.RecordCount - 1 do begin try DM.RxMem_EdboOrdersType.Insert; DM.RxMem_EdboOrdersType.FieldByName('fId_PersonEducationHistoryType ').AsInteger := MemoryData_EDBO['FId_PersonEducationHistoryType']; DM.RxMem_EdboOrdersType.FieldByName('fPersonEducationHistoryTypeName').AsString := MemoryData_EDBO['FPersonEducationHistoryTypeName']; DM.RxMem_EdboOrdersType.Post; except on E: Exception do begin csMessageDlg(nMsgBoxTitle[IndLangVWF], E.Message, mtInformation, [mbOk], 0); exit; end; end; MemoryData_EDBO.Next; end; result := False; DM.StorProc.Transaction.StartTransaction; DM.StorProc.StoredProcName := 'CS_GET_ORDER_TYPES_FROM_EDBO'; DM.StorProc.Prepare; for i := 0 to DM.RxMem_EdboOrdersType.RecordCount - 1 do begin try DM.StorProc.ParamByName('NUMBER_FROM_EDBO').AsInteger := DM.RxMem_EdboOrdersType.FieldByName('fId_PersonEducationHistoryType ').AsInteger; DM.StorProc.ParamByName('TYPE_NAME').AsString := DM.RxMem_EdboOrdersType.FieldByName('fPersonEducationHistoryTypeName').AsString; DM.StorProc.ExecProc; { DM.RxMem_EdboOrdersType.Insert; DM.RxMem_EdboOrdersType.FieldByName('fId_PersonEducationHistoryType ').AsInteger := MemoryData_EDBO['FId_PersonEducationHistoryType']; DM.RxMem_EdboOrdersType.FieldByName('fPersonEducationHistoryTypeName').AsString := MemoryData_EDBO['FPersonEducationHistoryTypeName']; DM.RxMem_EdboOrdersType.Post; } except on E: Exception do begin csMessageDlg(nMsgBoxTitle[IndLangVWF], E.Message, mtInformation, [mbOk], 0); DM.StorProc.Transaction.Rollback; exit; end; end; DM.RxMem_EdboOrdersType.Next; end; try // DM.StorProc.ExecProc; DM.StorProc.Transaction.Commit; result := True; except on E: Exception do begin csMessageDlg(nMsgBoxTitle[IndLangVWF], nMsgErrorWithEDBO[IndLangVWF] + #10#13 + E.Message, mtInformation, [mbOk], 0); Result := False; DM.StorProc.Transaction.Rollback; exit; end; end; MemoryData_EDBO.Close; MemoryData_EDBO.Free; PubSysDataDSet.Free; end; end; procedure TcsFormOrdersType.btnImportClick(Sender: TObject); begin if (csMessageDlg(nMsgBoxTitle[IndLangVWF], nMsgImportOrderTypes[IndLangVWF], mtInformation, [mbOK, mbCancel], 0) = mrOk) then begin if MyCsConnectToEdbo then begin // ApplyFilter if DM.RxMem_EdboOrdersType.Active then begin DM.RxMem_EdboOrdersType.Close; DM.RxMem_EdboOrdersType.EmptyTable; DM.RxMem_EdboOrdersType.Open; end else DM.RxMem_EdboOrdersType.EmptyTable; if (EDBOPersonIntf as IEDBOTools).InitEDBOConnection('EDBOPerson', DM.DB.Handle) then begin GetOrdersTypeFromEdbo; if DM.StorProc.Transaction.Active then DM.StorProc.Transaction.Commit; DM.DSetOrdersType.Close; DM.DSetOrdersType.Open; end else csMessageDlg(nMsgBoxTitle[IndLangVWF], nMsgErrorConnectEDBO[IndLangVWF], mtWarning, [mbOk], 0); end else begin csMessageDlg(nMsgBoxTitle[IndLangVWF], nMsgErrorConnectEDBO[IndLangVWF], mtError, [mbOK], 0); exit; end; end; end; procedure TcsFormOrdersType.btnExitClick(Sender: TObject); begin Close; end; procedure TcsFormOrdersType.FormClose(Sender: TObject; var Action: TCloseAction); begin if FormStyle = fsMDIChild then Action := caFree; end; procedure TcsFormOrdersType.InitMode(IdMode: Integer); var SelectSql: string; begin //настройка формы в соответствии с режимом // 0 - обычный, 1 - выбор только наших типов приказов, 2 - выбор только типов пркиазов едбо SelectSql := 'SELECT * FROM CS_DT_ORDER_TYPE'; case IdMode of 1: begin btnSelect.Visible := ivAlways; //IdMode = 1 в случае выбора типа приказов для добавления нового пункта //В этом случае используется проверка на права SelectSql := 'Select * from CS_DT_ORDER_TYPE_SEL(' + IntToStr(ID_User_Global) + ')'; col_IdTypeEdbo.Visible := False; col_Shablon.Visible := False; col_IdShablon.Visible := False; col_IsActive.Visible := False; col_IsLogical.Visible := False; col_CanCancel.Visible := False; //чтоб не было сообщений типа "поле не найдено" при хождении по гриду col_IdTypeEdbo.DataBinding.FieldName := ''; col_Shablon.DataBinding.FieldName := ''; col_IdShablon.DataBinding.FieldName := ''; col_IsActive.DataBinding.FieldName := ''; col_IsLogical.DataBinding.FieldName := ''; col_CanCancel.DataBinding.FieldName := ''; end; 2: begin btnSelect.Visible := ivAlways; SelectSql := 'Select * from Cs_Dt_Order_Type_Edbo_Sel'; col_Shablon.Visible := False; col_IdShablon.Visible := False; col_IsActive.Visible := False; col_IsLogical.Visible := False; col_CanCancel.Visible := False; end; // в случае неопознанного режима, работа будет такая же как и в режиме 0, // поэтому объединяем эти случаи в вариант else else begin btnSelect.Visible := ivNever; end; end; DM.DSetOrdersType.Close; DM.DSetOrdersType.SQLs.SelectSQL.Text := SelectSql; DM.DSetOrdersType.Open; // DM.DSetOrdersType.FetchAll; end; end.
{******************************************************************************* * uInvisControl * * * * Библиотека компонентов для работы с формой редактирования (qFControls) * * Поле ввода, заполняемое в коде без участия пользователя (TInvisControl) * * Copyright © 2005, Олег Г. Волков, Донецкий Национальный Университет * *******************************************************************************} unit uInvisControl; interface uses SysUtils, Classes, Controls, uFControl, StdCtrls, Graphics, uLabeledFControl, Registry; type TqFInvisControl = class(TqFControl) private FVal: Variant; FLabel: TLabel; protected procedure SetFieldName(FieldName: String); override; public constructor Create(AOwner: TComponent); override; function ToString: String; override; procedure SetValue(Val: Variant);override; function GetValue: Variant; override; procedure LoadFromRegistry(reg: TRegistry); override; // vallkor procedure SaveIntoRegistry(reg: TRegistry); override; // vallkor end; procedure Register; {$R *.res} implementation uses qFTools, Dialogs; procedure TqFInvisControl.SetValue(Val: Variant); begin FVal := Val; end; function TqFInvisControl.GetValue: Variant; begin Result := FVal; end; function TqFInvisControl.ToString: String; begin Result := qFVariantToString(FVal); end; constructor TqFInvisControl.Create(AOwner: TComponent); begin inherited Create(AOwner); if csDesigning in ComponentState then begin FLabel := TLabel.Create(Self); FLabel.AutoSize := True; FLabel.Parent := Self; FLabel.Visible := True; FLabel.Caption := FieldName; FLabel.Font.Color := clBlue; FLabel.Color := clYellow; end else Visible := False; end; procedure Register; begin RegisterComponents('qFControls', [TqFInvisControl]); end; procedure TqFInvisControl.LoadFromRegistry(reg: TRegistry); // vallkor begin inherited LoadFromRegistry(reg); // Для инвизибла непонятно как end; procedure TqFInvisControl.SaveIntoRegistry(reg: TRegistry); // vallkor begin inherited SaveIntoRegistry(reg); // Для инвизибла непонятно как end; procedure TqFInvisControl.SetFieldName(FieldName: String); begin inherited; FLabel.Caption := FieldName; end; end.
unit dStringGridHelper; interface uses FireDAC.Comp.Client, Data.Bind.Components, Data.Bind.Grid, System.Classes, Data.DB, Data.Bind.DBScope, VCL.Grids; type TStringGridHelper = class helper for TStringGrid private function FindBindComp(const ABindingsList: TBindingsList; const AGridName: String): TLinkGridToDataSource; function FindMember(const ALinkGridToDataSource: TLinkGridToDataSource; const AHeaderName: String): String; public procedure SortRecords(const BindingsList: TBindingsList; const HeaderName: String); end; implementation { TStringGridHelper } { Given a binding list and a String Grid component name, this routine returns the TLinkGridToDataSource object that contains information about the binding to the grid } function TStringGridHelper.FindBindComp(const ABindingsList: TBindingsList; const AGridName: String): TLinkGridToDataSource; var I: Integer; // Index begin Result := nil; // Default "not found" for I := 0 to pred(ABindingsList.BindCompCount) do // loop through all binding components in the list begin if ABindingsList.BindComps[I] is TLinkGridToDataSource then // must be a link grid to datasource begin if ABindingsList.BindComps[I].ControlComponent.Name = AGridName then // check for the specified grid name Exit(TLinkGridToDataSource(ABindingsList.BindComps[I])); // if found, return the binding list entry end; end; end; { Given a binding list component and header name (the text in the header of the column), return the Member Name that populates the column. This will be the field name in the underlying dataset. Notes: Often, Headername and MemberName are the same. This occurs if no HeaderName has been specified for the link. This routine accepts null values for the Link. Thus if the request to find the link failed (and returned nil) this routine will simply return the provided HeaderName. Note: It is possible to specify duplicate HeaderNames, e.g., two columns with the same header text. The first HeaderName that matches will be the one selected. Order is determined by the order they appear in the Columns collection. Duplicate names can only occur when HeaderNames are manually specified. They ordinarily default to the MemberName, which is the column name, and will hence be unique. } function TStringGridHelper.FindMember(const ALinkGridToDataSource: TLinkGridToDataSource; const AHeaderName: String): String; var I: Integer; // Index begin Result := AHeaderName; // default return value if no membername found if Assigned(ALinkGridToDataSource) then // bypass if no valid link begin for I := 0 to pred(ALinkGridToDataSource.Columns.Count) do // search through the link columns begin if ALinkGridToDataSource.Columns.Items[I].Header = AHeaderName then // test for HeaderName match begin Exit(ALinkGridToDataSource.Columns.Items[I].MemberName); // if matched return the related MemberName (dataset field) end; end; end; end; { This is the single entry point for this helper. It most easily invoked from the OnFixedCellClick event of the TStringGrid that requires a column sort. Example: procedure TfSObjDisplay.GridSort(Sender: TObject; ACol, ARow: Integer); begin TStringGrid(Sender).SortRecords(BindingsList1, TStringGrid(Sender).Cells[ACol, ARow]); end; Also note that the properties of the TString grid should specify goColMoving = False (I know of no way to have both column moving and Fixed Column click recognition) goFixedColClick = True Not sure why both of these need to be chosen as True goFixedRowClick = True but was unable to get the OnFixedCellClick event to fire unless they were both set to True } procedure TStringGridHelper.SortRecords(const BindingsList: TBindingsList; const HeaderName: String); var LLinkGridToDataSource: TLinkGridToDataSource; // Bindingslist link component for the TStringGrid LBindSourceDB: TBindSourceDB; // BindSourceDB component that actually points to related table LQuery: TFDQuery; // The underlying FDQuery that supplies data to the TStringGrid LMemberName: String; // The FDQuery column name that supplies data to the column begin LLinkGridToDataSource := FindBindComp(BindingsList, Self.Name); // discover the grid <==> datasource object Assert(LLinkGridToDataSource.DataSource is TBindSourceDB, 'Datasource must be TBindSourceDB.'); // verify object type LBindSourceDB := TBindSourceDB(LLinkGridToDataSource.DataSource); // discover the binding database object Assert(LBindSourceDB.DataSet is TFDQuery, 'DataSet must be TFDQuery.'); // verify the object type LQuery := TFDQuery(LBindSourceDB.DataSet); // discover the underlying FDQuery LMemberName := FindMember(LLinkGridToDataSource, HeaderName); // extract the column name for the desired sort LLinkGridToDataSource.Active := False; // disable the binding LQuery.IndexFieldNames := LMemberName; // apply the column name to the IndexFieldNames property LQuery.IndexesActive := True; // make sure the indexes are active LLinkGridToDataSource.Active := True; // enable the binding end; end.
unit UTotalGastoMesVO; //mapeamento interface uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO,UCnaeVO, UCidadeVO, UEstadoVO, UPaisVO; type [TEntity] [TTable('TotalGastoMes')] TTotalGastoMesVO = class(TGenericVO) private FidTotalGastoMes: Integer; FdtMesAno : TdateTime; FvlTotal : currency; FidCondominio: Integer; public [TId('idtotalgastomes')] [TGeneratedValue(sAuto)] property idTotalGastoMes: Integer read FidTotalGastoMes write FidTotalGastoMes; [TColumn('dtMesAno','Data Inicio',0,[ldGrid,ldLookup,ldComboBox], False)] property dtMesAno: TDateTime read FdtMesAno write FdtMesAno; [TColumn('vltotal','Valor Total',50,[ldGrid,ldLookup,ldComboBox], False)] property vlTotal: currency read FvlTotal write FvlTotal; [TColumn('idcondominio','Condominio',0,[ldLookup,ldComboBox], False)] property idCondominio: integer read FidCondominio write FidCondominio; procedure ValidarCampos; end; implementation { TProprietarioUnidadeVO } procedure TTotalGastoMesVO.ValidarCampos; begin if (Self.FvlTotal = 0) then begin raise Exception.Create('O campo Total Gasto Męs é obrigatório!'); end else if (self.FdtMesAno = 0) then begin raise Exception.Create('O campo data é obrigatório!'); end; end; end.
{----------------------------------------------------------------------------- Unit Name: cPyBaseDebugger Author: Kiriakos Vlahos Date: 23-Apr-2006 Purpose: History: Base debugger classes -----------------------------------------------------------------------------} unit cPyBaseDebugger; interface uses Windows, SysUtils, Classes, uEditAppIntfs, PythonEngine, Forms, Contnrs; type TDebuggerState = (dsInactive, dsRunning, dsPaused, dsRunningNoDebug); TDebuggerCommand = (dcNone, dcRun, dcStepInto, dcStepOver, dcStepOut, dcRunToCursor, dcAbort); TDebuggerLineInfo = (dlCurrentLine, dlBreakpointLine, dlDisabledBreakpointLine, dlExecutableLine, dlErrorLine); TDebuggerLineInfos = set of TDebuggerLineInfo; TNamespaceItemAttribute = (nsaNew, nsaChanged); TNamespaceItemAttributes = set of TNamespaceItemAttribute; TBreakpointChangeEvent = procedure(Sender: TObject; Editor : IEditor; ALine: integer) of object; TDebuggerStateChangeEvent = procedure(Sender: TObject; OldState, NewState: TDebuggerState) of object; TDebuggerYieldEvent = procedure(Sender: TObject; DoIdle : Boolean) of object; TEditorPos = class(TPersistent) public Editor : IEditor; Line : integer; Char : integer; IsSyntax : Boolean; ErrorMsg : string; procedure Clear; procedure Assign(Source: TPersistent); override; end; TBaseFrameInfo = class(TObject) // Base (abstract) class for Call Stack frame information protected function GetFunctionName : string; virtual; abstract; function GetFileName : string; virtual; abstract; function GetLine : integer; virtual; abstract; public property FunctionName : string read GetFunctionName; property FileName : string read GetFileName; property Line : integer read GetLine; end; TBaseNameSpaceItem = class(TObject) // Base (abstract) class for Namespace item information protected GotChildNodes : Boolean; GotBufferedValue : Boolean; BufferedValue : string; function GetOrCalculateValue : String; function GetName : string; virtual; abstract; function GetObjectType : string; virtual; abstract; function GetValue : string; virtual; abstract; function GetDocString : string; virtual; abstract; function GetChildCount : integer; virtual; abstract; function GetChildNode(Index: integer): TBaseNameSpaceItem; virtual; abstract; public Attributes : TNamespaceItemAttributes; function IsDict : Boolean; virtual; abstract; function IsModule : Boolean; virtual; abstract; function IsFunction : Boolean; virtual; abstract; function IsMethod : Boolean; virtual; abstract; function Has__dict__ : Boolean; virtual; abstract; function IndexOfChild(AName : string): integer; virtual; abstract; procedure GetChildNodes; virtual; abstract; procedure CompareToOldItem(OldItem : TBaseNameSpaceItem); property Name : string read GetName; property ObjectType : string read GetObjectType; property Value : string read GetOrCalculateValue; property DocString : string read GetDocString; property ChildCount : integer read GetChildCount; property ChildNode[Index : integer] : TBaseNameSpaceItem read GetChildNode; end; TPyBaseDebugger = class(TObject) // Base class for implementing Python Debuggers private fOnBreakpointChange: TBreakpointChangeEvent; fOnCurrentPosChange: TNotifyEvent; fOnErrorPosChange: TNotifyEvent; fOnStateChange: TDebuggerStateChangeEvent; fOnYield: TDebuggerYieldEvent; protected fBreakPointsChanged : Boolean; fCurrentPos : TEditorPos; fErrorPos : TEditorPos; fDebuggerState: TDebuggerState; fWantedState: TDebuggerState; fOldargv : Variant; procedure DoOnBreakpointChanged(Editor : IEditor; ALine: integer); procedure DoCurrentPosChanged; procedure DoErrorPosChanged; procedure DoStateChange; procedure DoYield(DoIdle : Boolean); procedure SetCommandLine(const ScriptName : string); virtual; procedure RestoreCommandLine; public constructor Create; destructor Destroy; override; procedure ToggleBreakpoint(Editor : IEditor; ALine: integer); procedure SetBreakPoint(FileName : string; ALine : integer; Disabled : Boolean; Condition : string); procedure ClearAllBreakpoints; function GetLineInfos(Editor : IEditor; ALine: integer): TDebuggerLineInfos; function IsBreakpointLine(Editor: IEditor; ALine: integer; var Disabled : boolean): boolean; function IsExecutableLine(Editor: IEditor; ALine: integer): boolean; function SyntaxCheck(Editor : IEditor; Quiet : Boolean = False) : Boolean; function IsRunning: boolean; function Compile(Editor : IEditor) : Variant; function ImportModule(Editor : IEditor) : Variant; procedure RunNoDebug(Editor : IEditor); procedure Run(Editor : IEditor; InitStepIn : Boolean = False); virtual; abstract; procedure RunToCursor(Editor : IEditor; ALine: integer); virtual; abstract; procedure StepInto(Editor : IEditor); virtual; abstract; procedure StepOver; virtual; abstract; procedure StepOut; virtual; abstract; procedure Pause; virtual; abstract; procedure Abort; virtual; abstract; // Evaluate expression in the current frame procedure Evaluate(const Expr : string; out ObjType, Value : string); virtual; abstract; // Fills in CallStackList with TBaseFrameInfo objects procedure GetCallStack(CallStackList : TObjectList); virtual; abstract; // functions to get TBaseNamespaceItems corresponding to a frame's gloabals and locals function GetFrameGlobals(Frame : TBaseFrameInfo) : TBaseNameSpaceItem; virtual; abstract; function GetFrameLocals(Frame : TBaseFrameInfo) : TBaseNameSpaceItem; virtual; abstract; property CurrentPos: TEditorPos read fCurrentPos; property ErrorPos: TEditorPos read fErrorPos; property DebuggerState : TDebuggerState read fDebuggerState; property BreakPointsChanged : Boolean read fBreakPointsChanged write fBreakPointsChanged; property OnBreakpointChange: TBreakpointChangeEvent read fOnBreakpointChange write fOnBreakpointChange; property OnCurrentPosChange: TNotifyEvent read fOnCurrentPosChange write fOnCurrentPosChange; property OnErrorPosChange: TNotifyEvent read fOnErrorPosChange write fOnErrorPosChange; property OnStateChange: TDebuggerStateChangeEvent read fOnStateChange write fOnStateChange; property OnYield: TDebuggerYieldEvent read fOnYield write fOnYield; end; implementation uses dmCommands, frmPythonII, VarPyth, frmMessages, frmPyIDEMain, MMSystem, Math, JvDockControlForm, JclFileUtils, Dialogs, uCommonFunctions, cParameters, JclSysUtils, StringResources, SynUnicode; { TEditorPos } procedure TEditorPos.Assign(Source: TPersistent); begin if Source is TEditorPos then begin Self.Editor := TEditorPos(Source).Editor; Self.Line := TEditorPos(Source).Line; Self.Char := TEditorPos(Source).Char; Self.IsSyntax := TEditorPos(Source).IsSyntax; Self.ErrorMsg := TEditorPos(Source).ErrorMsg; end else inherited; end; procedure TEditorPos.Clear; begin Editor := nil; Line := -1; Char := -1; IsSyntax := False; ErrorMsg := ''; end; { TPyBaseDebugger } procedure TPyBaseDebugger.DoOnBreakpointChanged(Editor : IEditor; ALine: integer); begin fBreakPointsChanged := True; if Assigned(fOnBreakpointChange) then fOnBreakpointChange(Self, Editor, ALine); end; procedure TPyBaseDebugger.DoCurrentPosChanged; begin if Assigned(fOnCurrentPosChange) then fOnCurrentPosChange(Self); end; procedure TPyBaseDebugger.DoErrorPosChanged; begin if Assigned(fOnErrorPosChange) then fOnErrorPosChange(Self); end; procedure TPyBaseDebugger.DoYield(DoIdle : Boolean); begin if Assigned(fOnYield) then fOnYield(Self, DoIdle); end; constructor TPyBaseDebugger.Create; begin inherited Create; fDebuggerState := dsInactive; fBreakPointsChanged := False; fCurrentPos := TEditorPos.Create; fCurrentPos.Clear; fErrorPos := TEditorPos.Create; fErrorPos.Clear; end; procedure TPyBaseDebugger.DoStateChange; Var OldDebuggerState: TDebuggerState; begin if fDebuggerState <> fWantedState then begin OldDebuggerState := fDebuggerState; if fWantedState in [dsInactive, dsRunning, dsRunningNoDebug] then fCurrentPos.Clear else begin fErrorPos.Clear; DoErrorPosChanged; end; fDebuggerState := fWantedState; if Assigned(fOnStateChange) then fOnStateChange(Self, OldDebuggerState, fWantedState); DoCurrentPosChanged; end; end; destructor TPyBaseDebugger.Destroy; begin fCurrentPos.Free; fErrorPos.Free; inherited; end; procedure TPyBaseDebugger.ToggleBreakpoint(Editor : IEditor; ALine: integer); var SetBP: boolean; i: integer; BreakPoint : TBreakPoint; begin if ALine > 0 then begin SetBP := TRUE; for i := 0 to Editor.Breakpoints.Count - 1 do begin if TBreakPoint(Editor.Breakpoints[i]).LineNo = ALine then begin Editor.Breakpoints.Delete(i); SetBP := FALSE; break; end else if TBreakPoint(Editor.Breakpoints[i]).LineNo > ALine then begin BreakPoint := TBreakPoint.Create; BreakPoint.LineNo := ALine; Editor.Breakpoints.Insert(i, BreakPoint); SetBP := FALSE; break; end; end; if SetBP then begin BreakPoint := TBreakPoint.Create; BreakPoint.LineNo := ALine; Editor.Breakpoints.Add(BreakPoint); end; DoOnBreakpointChanged(Editor, ALine); end; end; procedure TPyBaseDebugger.SetBreakPoint(FileName: string; ALine: integer; Disabled : Boolean; Condition: string); var Editor : IEditor; i: integer; BreakPoint : TBreakPoint; begin Editor := GI_EditorFactory.GetEditorByNameOrTitle(FileName); BreakPoint := nil; if Assigned(Editor) and (ALine > 0) then begin for i := 0 to Editor.Breakpoints.Count - 1 do begin if TBreakPoint(Editor.Breakpoints[i]).LineNo = ALine then begin BreakPoint := TBreakPoint(Editor.Breakpoints[i]); break; end else if TBreakPoint(Editor.Breakpoints[i]).LineNo > ALine then begin BreakPoint := TBreakPoint.Create; Editor.Breakpoints.Insert(i, BreakPoint); break; end; end; if not Assigned(BreakPoint) then begin BreakPoint := TBreakPoint.Create; Editor.Breakpoints.Add(BreakPoint); end; BreakPoint.LineNo := ALine; BreakPoint.Disabled := Disabled; BreakPoint.Condition := Condition; DoOnBreakpointChanged(Editor, ALine); end; end; procedure TPyBaseDebugger.ClearAllBreakpoints; Var i : integer; begin for i := 0 to GI_EditorFactory.Count -1 do if GI_EditorFactory.Editor[i].Breakpoints.Count > 0 then begin GI_EditorFactory.Editor[i].Breakpoints.Clear; DoOnBreakpointChanged(GI_EditorFactory.Editor[i], -1); end; end; function TPyBaseDebugger.GetLineInfos(Editor : IEditor; ALine: integer): TDebuggerLineInfos; Var Disabled : boolean; begin Result := []; if ALine > 0 then begin if (Editor = fCurrentPos.Editor) and (ALine = fCurrentPos.Line) then Include(Result, dlCurrentLine); if (Editor = fErrorPos.Editor) and (ALine = fErrorPos.Line) then Include(Result, dlErrorLine); if IsExecutableLine(Editor, ALine) then Include(Result, dlExecutableLine); Disabled := False; if IsBreakpointLine(Editor, ALine, Disabled) then if Disabled then Include(Result, dlDisabledBreakpointLine) else Include(Result, dlBreakpointLine); end; end; function TPyBaseDebugger.IsBreakpointLine(Editor: IEditor; ALine: integer; var Disabled : boolean): boolean; Var i: integer; begin Result := FALSE; if ALine > 0 then begin i := Editor.Breakpoints.Count - 1; while i >= 0 do begin if TBreakPoint(Editor.Breakpoints[i]).LineNo = ALine then begin Disabled := TBreakPoint(Editor.Breakpoints[i]).Disabled; Result := TRUE; break; end; Dec(i); end; end; end; function TPyBaseDebugger.IsExecutableLine(Editor: IEditor; ALine: integer): boolean; begin Assert(Assigned(Editor)); with Editor.SynEdit do begin Result := CommandsDataModule.IsExecutableLine(Lines[ALine-1]); end; end; function TPyBaseDebugger.SyntaxCheck(Editor: IEditor; Quiet : Boolean = False): Boolean; Var FName, Source : string; tmp: PPyObject; PyErrType, PyErrValue, PyErrTraceback, PyErrValueTuple : PPyObject; SupressOutput : IInterface; begin ErrorPos.Clear; DoErrorPosChanged; MessagesWindow.ClearMessages; FName := Editor.FileName; if FName = '' then FName := '<'+Editor.FileTitle+'>'; Source := CommandsDataModule.CleanEOLs(Editor.EncodedText)+#10; with GetPythonEngine do begin if Quiet then SupressOutput := PythonIIForm.OutputSupressor; // Do not show errors Result := CheckExecSyntax(Source); if not Result then begin if Quiet then begin if Assigned(PyErr_Occurred()) and (PyErr_ExceptionMatches(PyExc_SyntaxError^) = 1) then begin PyErr_Fetch(@PyErrType, @PyErrValue, @PyErrTraceback); // Clears the Error if Assigned(PyErrValue) then begin // Sometimes there's a tuple instead of instance... if PyTuple_Check( PyErrValue ) and (PyTuple_Size( PyErrValue) >= 2) then begin fErrorPos.ErrorMsg := PyString_AsString(PyTuple_GetItem( PyErrValue, 0)); PyErrValueTuple := PyTuple_GetItem( PyErrValue, 1); if PyTuple_Check( PyErrValueTuple ) and (PyTuple_Size( PyErrValueTuple) >= 4) then begin fErrorPos.Line := PyInt_AsLong(PyTuple_GetItem( PyErrValueTuple, 1)); fErrorPos.Char := PyInt_AsLong(PyTuple_GetItem( PyErrValueTuple, 2)); end; end else // Is it an instance of the SyntaxError class ? if PyInstance_Check( PyErrValue ) or (PyType_IsSubtype(PyErrValue^.ob_type, PPyTypeObject(GetPythonEngine.PyExc_SyntaxError^)) = 1) then begin // Get the text containing the error, cut of carriage return tmp := PyObject_GetAttrString(PyErrValue, 'text'); if Assigned(tmp) and PyString_Check(tmp) then fErrorPos.ErrorMsg := Trim(PyString_AsString(tmp)); Py_XDECREF(tmp); // Get the offset where the error should appear tmp := PyObject_GetAttrString(PyErrValue, 'offset' ); if Assigned(tmp) and PyInt_Check(tmp) then fErrorPos.Char := PyInt_AsLong(tmp); Py_XDECREF(tmp); // Get the line number of the error tmp := PyObject_GetAttrString(PyErrValue, 'lineno' ); if Assigned(tmp) and PyInt_Check(tmp) then fErrorPos.Line := PyInt_AsLong(tmp); Py_XDECREF(tmp); end; FErrorPos.Editor := Editor; fErrorPos.IsSyntax := True; DoErrorPosChanged; end; Py_XDECREF(PyErrType); Py_XDECREF(PyErrValue); Py_XDECREF(PyErrTraceback); end; end else begin // Display error // New Line for output PythonIIForm.AppendText(sLineBreak); PyErr_Print; // Throw exception for the error try RaiseError; except on E: EPySyntaxError do begin E.EFileName := FName; // add the filename MessagesWindow.ShowPythonSyntaxError(E); if PyIDEMainForm.ShowFilePosition(E.EFileName, E.ELineNumber, E.EOffset) and Assigned(GI_ActiveEditor) then begin FErrorPos.Editor := GI_ActiveEditor; end; fErrorPos.Line := E.ELineNumber; fErrorPos.Char := E.EOffset; fErrorPos.IsSyntax := True; DoErrorPosChanged; if Not Quiet then MessageDlg(E.Message, mtError, [mbOK], 0); end; end; end; end; end; end; function TPyBaseDebugger.IsRunning: boolean; begin Result := fDebuggerState in [dsRunning, dsRunningNoDebug]; end; function TPyBaseDebugger.Compile(Editor: IEditor): Variant; Var co : PPyObject; FName, Source : string; begin VarClear(Result); ErrorPos.Clear; DoErrorPosChanged; MessagesWindow.ClearMessages; FName := Editor.FileName; if FName = '' then FName := '<'+Editor.FileTitle+'>'; Source := CommandsDataModule.CleanEOLs(Editor.EncodedText)+#10; with GetPythonEngine do begin co := Py_CompileString(PChar(Source), PChar(FName), file_input ); if not Assigned( co ) then begin // New Line for output PythonIIForm.AppendText(sLineBreak); // Display error PyErr_Print; // Throw exception for the error try RaiseError; except on E: EPySyntaxError do begin MessagesWindow.ShowPythonSyntaxError(E); if PyIDEMainForm.ShowFilePosition(E.EFileName, E.ELineNumber, E.EOffset) and Assigned(GI_ActiveEditor) then begin FErrorPos.Editor := GI_ActiveEditor; fErrorPos.Line := E.ELineNumber; fErrorPos.Char := E.EOffset; fErrorPos.IsSyntax := True; DoErrorPosChanged; end; MessageDlg(E.Message, mtError, [mbOK], 0); SysUtils.Abort; end; end; end else begin Result := VarPythonCreate(co); // Cleanup ByteCode GetPythonEngine.Py_XDECREF(co); end; end; end; function TPyBaseDebugger.ImportModule(Editor: IEditor) : Variant; { Imports Editor text without saving the file. Does not add the module name to the locals() of the interpreter. } Var Code : Variant; Path, NameOfModule : string; PyObject, Module : PPyObject; PythonPathAdder : IInterface; begin VarClear(Result); //Compile Code := Compile(Editor); Path := ExtractFileDir(Editor.FileName); if Length(Path) > 1 then begin // Add the path of the executed file to the Python path PythonPathAdder := AddPathToPythonPath(Path, False); end; if Editor.FileName <> '' then NameOfModule := FileNameToModuleName(Editor.FileName) else NameOfModule := PathRemoveExtension(Editor.FileTitle); PyObject := ExtractPythonObjectFrom(Code); fWantedState := dsRunningNoDebug; DoStateChange; try with GetPythonEngine do begin Py_XINCREF(PyObject); try Module := PyImport_ExecCodeModule(NameOfModule, PyObject); Result := VarPythonCreate(Module); Py_XDECREF(Module); finally Py_XDECREF(PyObject); end; CheckError; end; if VarIsNone(Result) then begin MessageDlg('Error in importing module', mtError, [mbOK], 0); SysUtils.Abort; end; finally fWantedState := dsInactive; DoStateChange; end; end; procedure TimeCallBack(TimerID, Msg: Uint; dwUser, dw1, dw2: DWORD); stdcall; begin if PLongWord(dwUser)^ = 0 then Exit; if (MessageBox(0, 'The Python Script has timed out. Do you want to interrupt it?', 'ScriptTimeOut', MB_ICONWARNING or MB_YESNO) = idYes) then begin GetPythonEngine.PyErr_SetInterrupt; //Generate Keyboard interrupt signal TimeKillEvent(PLongWord(dwUser)^); PLongWord(dwUser)^ := 0; end; end; procedure TPyBaseDebugger.RunNoDebug(Editor: IEditor); Var Code : Variant; TI : TTracebackItem; mmResult,Resolution : LongWord; tc : TTimeCaps; Path, OldPath : string; PythonPathAdder : IInterface; begin // Repeat here to make sure it is set right MaskFPUExceptions(CommandsDataModule.PyIDEOptions.MaskFPUExceptions); //Compile Code := Compile(Editor); fWantedState := dsRunningNoDebug; DoStateChange; // New Line for output PythonIIForm.AppendText(sLineBreak); mmResult := 0; Resolution := 100; Path := ExtractFileDir(Editor.FileName); OldPath := GetCurrentDir; if Length(Path) > 1 then begin // Add the path of the executed file to the Python path - Will be automatically removed PythonPathAdder := AddPathToPythonPath(Path); // Change the current path try ChDir(Path) except MessageDlg('Could not set the current directory to the script path', mtWarning, [mbOK], 0); end; end; // Set the command line parameters SetCommandLine(Editor.GetFileNameOrTitle); ShowDockForm(PythonIIForm); try // Set Multimedia Timer if (CommandsDataModule.PyIDEOptions.TimeOut > 0) and (timeGetDevCaps(@tc, SizeOf(tc))=TIMERR_NOERROR) then begin Resolution := Min(Resolution,tc.wPeriodMax); TimeBeginPeriod(Resolution); mmResult := TimeSetEvent(CommandsDataModule.PyIDEOptions.TimeOut, resolution, @TimeCallBack, DWORD(@mmResult), TIME_PERIODIC or 256); end; try PythonIIForm.Debugger.run_nodebug(Code); except // CheckError already called by VarPyth on E: Exception do begin MessagesWindow.ShowPythonTraceback; MessagesWindow.AddMessage(E.Message); with GetPythonEngine.Traceback do begin if ItemCount > 0 then begin TI := Items[ItemCount -1]; if PyIDEMainForm.ShowFilePosition(TI.FileName, TI.LineNo, 1) and Assigned(GI_ActiveEditor) then begin FErrorPos.Editor := GI_ActiveEditor; fErrorPos.Line := TI.LineNo; DoErrorPosChanged; end; end; end; MessageDlg(E.Message, mtError, [mbOK], 0); SysUtils.Abort; end; end; finally if CommandsDataModule.PyIDEOptions.TimeOut > 0 then begin if (mmResult <> 0) then TimeKillEvent(mmResult); TimeEndPeriod(Resolution); end; PythonIIForm.AppendText(sLineBreak+PythonIIForm.PS1); // Restore the command line parameters RestoreCommandLine; // Change the back current path ChDir(OldPath); fWantedState := dsInactive; DoStateChange; end; end; procedure TPyBaseDebugger.RestoreCommandLine; begin SysModule.argv := fOldargv; end; procedure TPyBaseDebugger.SetCommandLine(const ScriptName : string); var SysMod : Variant; S, Param : string; P : PChar; // List : TStringList; // I: integer; begin SysMod := SysModule; fOldargv := SysMod.argv; SysMod.argv := NewPythonList; SysMod.argv.append(ScriptName); S := iff(CommandsDataModule.PyIDEOptions.UseCommandLine, CommandsDataModule.PyIDEOptions.CommandLine, ''); if S <> '' then begin S := Parameters.ReplaceInText(S); P := GetParamStr(PChar(S), Param); while Param <> '' do begin SysMod.argv.append(Param); P := GetParamStr(P, Param); end; PythonIIForm.AppendText(Format(SCommandLineMsg, [S])); end; // List := TStringList.Create; // try // ExtractStrings([' '], [' '], PChar(S), List); // for I := 0 to List.Count - 1 do // SysMod.argv.append(AnsiDequotedStr(List[i], '"')); // finally // List.Free; // end; end; { TBaseNameSpaceItem } procedure TBaseNameSpaceItem.CompareToOldItem(OldItem: TBaseNameSpaceItem); var i, Index : integer; Child : TBaseNameSpaceItem; begin if OldItem.GotBufferedValue then begin if OldItem.BufferedValue <> Value then Attributes := [nsaChanged]; end; if OldItem.GotChildNodes then begin GetChildNodes; for i := 0 to ChildCount - 1 do begin Child := ChildNode[i]; Index := OldItem.IndexOfChild(Child.Name); if Index >= 0 then Child.CompareToOldItem(OldItem.ChildNode[Index]) else Child.Attributes := [nsaNew]; end; end; end; function TBaseNameSpaceItem.GetOrCalculateValue: String; begin if GotBufferedValue then Result := BufferedValue else begin BufferedValue := GetValue; GotBufferedValue := True; Result := BufferedValue; end; end; end.
{ Unit for light weight threads. This file is part of the Free Pascal run time library. Copyright (C) 2008 Mattias Gaertner mattias@freepascal.org See the file COPYING.FPC, 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. **********************************************************************} { Abstract: Light weight threads. This unit provides methods to easily run a procedure/method with several threads at once. } unit MTProcs; {$mode objfpc}{$H+} {$inline on} interface uses Classes, SysUtils, MTPCPU; type TProcThreadGroup = class; TProcThreadPool = class; TProcThread = class; { TMultiThreadProcItem } TMTPThreadState = ( mtptsNone, mtptsActive, mtptsWaitingForIndex, mtptsWaitingFailed, mtptsInactive, mtptsTerminated ); TMultiThreadProcItem = class private FGroup: TProcThreadGroup; FIndex: PtrInt; FThread: TProcThread; FWaitingForIndexEnd: PtrInt; FWaitingForIndexStart: PtrInt; fWaitForPool: PRTLEvent; FState: TMTPThreadState; public destructor Destroy; override; function WaitForIndexRange(StartIndex, EndIndex: PtrInt): boolean; function WaitForIndex(Index: PtrInt): boolean; inline; procedure CalcBlock(Index, BlockSize, LoopLength: PtrInt; out BlockStart, BlockEnd: PtrInt); inline; property Index: PtrInt read FIndex; property Group: TProcThreadGroup read FGroup; property WaitingForIndexStart: PtrInt read FWaitingForIndexStart; property WaitingForIndexEnd: PtrInt read FWaitingForIndexEnd; property Thread: TProcThread read FThread; end; { TProcThread } TMTPThreadList = ( mtptlPool, mtptlGroup ); TProcThread = class(TThread) private FItem: TMultiThreadProcItem; FNext, FPrev: array[TMTPThreadList] of TProcThread; procedure AddToList(var First: TProcThread; ListType: TMTPThreadList); inline; procedure RemoveFromList(var First: TProcThread; ListType: TMTPThreadList); inline; procedure Terminating(aPool: TProcThreadPool; E: Exception); public constructor Create; destructor Destroy; override; procedure Execute; override; property Item: TMultiThreadProcItem read FItem; end; TMTMethod = procedure(Index: PtrInt; Data: Pointer; Item: TMultiThreadProcItem) of object; TMTProcedure = procedure(Index: PtrInt; Data: Pointer; Item: TMultiThreadProcItem); { TProcThreadGroup Each task creates a new group of threads. A group can either need more threads or it has finished and waits for its threads to end. The thread that created the group is not in the list FFirstThread. } TMTPGroupState = ( mtpgsNone, mtpgsNeedThreads, // the groups waiting for more threads to help mtpgsFinishing, // the groups waiting for its threads to finish mtpgsException // there was an exception => close asap ); TProcThreadGroup = class private FEndIndex: PtrInt; FException: Exception; FFirstRunningIndex: PtrInt; FFirstThread: TProcThread; FLastRunningIndex: PtrInt; FMaxThreads: PtrInt; FNext, FPrev: TProcThreadGroup; FPool: TProcThreadPool; FStarterItem: TMultiThreadProcItem; FStartIndex: PtrInt; FState: TMTPGroupState; FTaskData: Pointer; FTaskFrame: Pointer; FTaskMethod: TMTMethod; FTaskProcedure: TMTProcedure; FThreadCount: PtrInt; procedure AddToList(var First: TProcThreadGroup; ListType: TMTPGroupState); inline; procedure RemoveFromList(var First: TProcThreadGroup); inline; function NeedMoreThreads: boolean; inline; procedure IncreaseLastRunningIndex(Item: TMultiThreadProcItem); procedure AddThread(AThread: TProcThread); procedure RemoveThread(AThread: TProcThread); inline; procedure Run(Index: PtrInt; Data: Pointer; Item: TMultiThreadProcItem); inline; procedure IndexComplete(Index: PtrInt); procedure WakeThreadsWaitingForIndex; function HasFinishedIndex(aStartIndex, aEndIndex: PtrInt): boolean; procedure EnterExceptionState(E: Exception); public constructor Create; destructor Destroy; override; property Pool: TProcThreadPool read FPool; property StartIndex: PtrInt read FStartIndex; property EndIndex: PtrInt read FEndIndex; property FirstRunningIndex: PtrInt read FFirstRunningIndex; // first started property LastRunningIndex: PtrInt read FLastRunningIndex; // last started property TaskData: Pointer read FTaskData; property TaskMethod: TMTMethod read FTaskMethod; property TaskProcedure: TMTProcedure read FTaskProcedure; property TaskFrame: Pointer read FTaskFrame; property MaxThreads: PtrInt read FMaxThreads; property StarterItem: TMultiThreadProcItem read FStarterItem; end; { TLightWeightThreadPool Group 0 are the inactive threads } { TProcThreadPool } TProcThreadPool = class private FMaxThreadCount: PtrInt; FThreadCount: PtrInt; FFirstInactiveThread: TProcThread; FFirstActiveThread: TProcThread; FFirstTerminatedThread: TProcThread; FFirstGroupNeedThreads: TProcThreadGroup; FFirstGroupFinishing: TProcThreadGroup; FCritSection: TRTLCriticalSection; FDestroying: boolean; procedure SetMaxThreadCount(const AValue: PtrInt); procedure CleanTerminatedThreads; procedure DoParallelIntern(const AMethod: TMTMethod; const AProc: TMTProcedure; const AFrame: Pointer; StartIndex, EndIndex: PtrInt; Data: Pointer = nil; MaxThreads: PtrInt = 0); public // for debugging only: the critical section is public: procedure EnterPoolCriticalSection; inline; procedure LeavePoolCriticalSection; inline; public constructor Create; destructor Destroy; override; procedure DoParallel(const AMethod: TMTMethod; StartIndex, EndIndex: PtrInt; Data: Pointer = nil; MaxThreads: PtrInt = 0); inline; procedure DoParallel(const AProc: TMTProcedure; StartIndex, EndIndex: PtrInt; Data: Pointer = nil; MaxThreads: PtrInt = 0); inline; // experimental procedure DoParallelLocalProc(const LocalProc: Pointer; StartIndex, EndIndex: PtrInt; Data: Pointer = nil; MaxThreads: PtrInt = 0); // do not make this inline! // utility functions for loops: procedure CalcBlockSize(LoopLength: PtrInt; out BlockCount, BlockSize: PtrInt; MinBlockSize: PtrInt = 0); inline; public property MaxThreadCount: PtrInt read FMaxThreadCount write SetMaxThreadCount; property ThreadCount: PtrInt read FThreadCount; end; var ProcThreadPool: TProcThreadPool = nil; threadvar CurrentThread: TThread; // TProcThread sets this, you can set this for your own TThreads descendants implementation { TMultiThreadProcItem } destructor TMultiThreadProcItem.Destroy; begin if fWaitForPool<>nil then begin RTLeventdestroy(fWaitForPool); fWaitForPool:=nil; end; inherited Destroy; end; function TMultiThreadProcItem.WaitForIndexRange( StartIndex, EndIndex: PtrInt): boolean; var aPool: TProcThreadPool; begin //WriteLn('TLightWeightThreadItem.WaitForIndexRange START Index='+IntToStr(Index)+' StartIndex='+IntToStr(StartIndex)+' EndIndex='+IntToStr(EndIndex)); if (EndIndex>=Index) then exit(false); if EndIndex<StartIndex then exit(true); if Group=nil then exit(true); // a single threaded group has no group object // multi threaded group aPool:=Group.Pool; if aPool.FDestroying then exit(false); // no more wait allowed aPool.EnterPoolCriticalSection; try if Group.FState=mtpgsException then begin //WriteLn('TLightWeightThreadItem.WaitForIndexRange Index='+IntToStr(Index)+', Group closing because of error'); exit(false); end; if Group.HasFinishedIndex(StartIndex,EndIndex) then begin //WriteLn('TLightWeightThreadItem.WaitForIndexRange Index='+IntToStr(Index)+', range already finished'); exit(true); end; FState:=mtptsWaitingForIndex; FWaitingForIndexStart:=StartIndex; FWaitingForIndexEnd:=EndIndex; if fWaitForPool=nil then fWaitForPool:=RTLEventCreate; RTLeventResetEvent(fWaitForPool); finally aPool.LeavePoolCriticalSection; end; //WriteLn('TLightWeightThreadItem.WaitForIndexRange '+IntToStr(Index)+' waiting ... '); RTLeventWaitFor(fWaitForPool); Result:=FState=mtptsActive; FState:=mtptsActive; //WriteLn('TLightWeightThreadItem.WaitForIndexRange END '+IntToStr(Index)); end; function TMultiThreadProcItem.WaitForIndex(Index: PtrInt): boolean; inline; begin Result:=WaitForIndexRange(Index,Index); end; procedure TMultiThreadProcItem.CalcBlock(Index, BlockSize, LoopLength: PtrInt; out BlockStart, BlockEnd: PtrInt); begin BlockStart:=BlockSize*Index; BlockEnd:=BlockStart+BlockSize; if LoopLength<BlockEnd then BlockEnd:=LoopLength; dec(BlockEnd); end; { TProcThread } procedure TProcThread.AddToList(var First: TProcThread; ListType: TMTPThreadList); begin FNext[ListType]:=First; if FNext[ListType]<>nil then FNext[ListType].FPrev[ListType]:=Self; First:=Self; end; procedure TProcThread.RemoveFromList(var First: TProcThread; ListType: TMTPThreadList); begin if First=Self then First:=FNext[ListType]; if FNext[ListType]<>nil then FNext[ListType].FPrev[ListType]:=FPrev[ListType]; if FPrev[ListType]<>nil then FPrev[ListType].FNext[ListType]:=FNext[ListType]; FNext[ListType]:=nil; FPrev[ListType]:=nil; end; procedure TProcThread.Terminating(aPool: TProcThreadPool; E: Exception); begin aPool.EnterPoolCriticalSection; try // remove from group if Item.FGroup<>nil then begin // an exception occured Item.FGroup.EnterExceptionState(E); Item.FGroup.RemoveThread(Self); Item.FGroup:=nil; end; // move to pool's terminated threads case Item.FState of mtptsActive: RemoveFromList(aPool.FFirstActiveThread,mtptlPool); mtptsInactive: RemoveFromList(aPool.FFirstInactiveThread,mtptlPool); end; AddToList(aPool.FFirstTerminatedThread,mtptlPool); Item.FState:=mtptsTerminated; finally aPool.LeavePoolCriticalSection; end; end; constructor TProcThread.Create; begin inherited Create(true); fItem:=TMultiThreadProcItem.Create; fItem.fWaitForPool:=RTLEventCreate; fItem.FThread:=Self; end; destructor TProcThread.Destroy; begin FreeAndNil(FItem); inherited Destroy; end; procedure TProcThread.Execute; var aPool: TProcThreadPool; Group: TProcThreadGroup; ok: Boolean; E: Exception; begin MTProcs.CurrentThread:=Self; aPool:=Item.Group.Pool; ok:=false; try repeat // work Group:=Item.Group; Group.Run(Item.Index,Group.TaskData,Item); aPool.EnterPoolCriticalSection; try Group.IndexComplete(Item.Index); // find next work if Group.LastRunningIndex<Group.EndIndex then begin // next index of group Group.IncreaseLastRunningIndex(Item); end else begin // remove from group RemoveFromList(Group.FFirstThread,mtptlGroup); dec(Group.FThreadCount); Item.FGroup:=nil; Group:=nil; if aPool.FFirstGroupNeedThreads<>nil then begin // add to new group aPool.FFirstGroupNeedThreads.AddThread(Self); Group:=Item.Group; end else begin // mark inactive RemoveFromList(aPool.FFirstActiveThread,mtptlPool); AddToList(aPool.FFirstInactiveThread,mtptlPool); Item.FState:=mtptsInactive; RTLeventResetEvent(Item.fWaitForPool); end; end; finally aPool.LeavePoolCriticalSection; end; // wait for new work if Item.FState=mtptsInactive then RTLeventWaitFor(Item.fWaitForPool); until Item.Group=nil; ok:=true; except // stop the exception and store it E:=Exception(AcquireExceptionObject); Terminating(aPool,E); end; if ok then Terminating(aPool,nil); end; { TProcThreadGroup } procedure TProcThreadGroup.AddToList(var First: TProcThreadGroup; ListType: TMTPGroupState); begin FNext:=First; if FNext<>nil then FNext.FPrev:=Self; First:=Self; FState:=ListType; end; procedure TProcThreadGroup.RemoveFromList( var First: TProcThreadGroup); begin if First=Self then First:=FNext; if FNext<>nil then FNext.FPrev:=FPrev; if FPrev<>nil then FPrev.FNext:=FNext; FNext:=nil; FPrev:=nil; FState:=mtpgsNone; end; function TProcThreadGroup.NeedMoreThreads: boolean; begin Result:=(FLastRunningIndex<FEndIndex) and (FThreadCount<FMaxThreads) and (FState<>mtpgsException); end; procedure TProcThreadGroup.IncreaseLastRunningIndex(Item: TMultiThreadProcItem); begin inc(FLastRunningIndex); Item.FIndex:=FLastRunningIndex; if NeedMoreThreads then exit; if FState=mtpgsNeedThreads then begin RemoveFromList(Pool.FFirstGroupNeedThreads); AddToList(Pool.FFirstGroupFinishing,mtpgsFinishing); end; end; procedure TProcThreadGroup.AddThread(AThread: TProcThread); begin AThread.Item.FGroup:=Self; AThread.AddToList(FFirstThread,mtptlGroup); inc(FThreadCount); IncreaseLastRunningIndex(AThread.Item); end; procedure TProcThreadGroup.RemoveThread(AThread: TProcThread); begin AThread.RemoveFromList(FFirstThread,mtptlGroup); dec(FThreadCount); end; procedure TProcThreadGroup.Run(Index: PtrInt; Data: Pointer; Item: TMultiThreadProcItem); inline; begin if Assigned(FTaskFrame) then begin CallLocalProc(FTaskProcedure,FTaskFrame,Index,Data,Item) end else begin if Assigned(FTaskProcedure) then FTaskProcedure(Index,Data,Item) else FTaskMethod(Index,Data,Item) end; end; procedure TProcThreadGroup.IndexComplete(Index: PtrInt); var AThread: TProcThread; NewFirstRunningThread: PtrInt; begin // update FirstRunningIndex NewFirstRunningThread:=FStarterItem.Index; AThread:=FFirstThread; while AThread<>nil do begin if (NewFirstRunningThread>aThread.Item.Index) and (aThread.Item.Index<>Index) then NewFirstRunningThread:=aThread.Item.Index; aThread:=aThread.FNext[mtptlGroup]; end; FFirstRunningIndex:=NewFirstRunningThread; // wake up threads (Note: do this even if FFirstRunningIndex has not changed) WakeThreadsWaitingForIndex; end; procedure TProcThreadGroup.WakeThreadsWaitingForIndex; var aThread: TProcThread; begin if FState<>mtpgsException then begin // wake up waiting threads aThread:=FFirstThread; while aThread<>nil do begin if (aThread.Item.FState=mtptsWaitingForIndex) and HasFinishedIndex(aThread.Item.WaitingForIndexStart, aThread.Item.WaitingForIndexEnd) then begin // wake up the thread aThread.Item.FState:=mtptsActive; RTLeventSetEvent(aThread.Item.fWaitForPool); end; aThread:=aThread.FNext[mtptlGroup]; end; if (FStarterItem.FState=mtptsWaitingForIndex) and HasFinishedIndex(FStarterItem.WaitingForIndexStart,FStarterItem.WaitingForIndexEnd) then begin // wake up the starter thread of this group FStarterItem.FState:=mtptsActive; RTLeventSetEvent(FStarterItem.fWaitForPool); end; end else begin // end group: wake up waiting threads aThread:=FFirstThread; while aThread<>nil do begin if (aThread.Item.FState=mtptsWaitingForIndex) then begin // end group: wake up the thread aThread.Item.FState:=mtptsWaitingFailed; RTLeventSetEvent(aThread.Item.fWaitForPool); end; aThread:=aThread.FNext[mtptlGroup]; end; if (FStarterItem.FState=mtptsWaitingForIndex) then begin // end group: wake up the starter thread of this group FStarterItem.FState:=mtptsWaitingFailed; RTLeventSetEvent(FStarterItem.fWaitForPool); end; end; end; function TProcThreadGroup.HasFinishedIndex( aStartIndex, aEndIndex: PtrInt): boolean; var AThread: TProcThread; begin // test the finished range if FFirstRunningIndex>aEndIndex then exit(true); // test the unfinished range if FLastRunningIndex<aEndIndex then exit(false); // test the active range AThread:=FFirstThread; while AThread<>nil do begin if (AThread.Item.Index>=aStartIndex) and (AThread.Item.Index<=aEndIndex) then exit(false); AThread:=AThread.FNext[mtptlGroup]; end; if (FStarterItem.Index>=aStartIndex) and (FStarterItem.Index<=aEndIndex) then exit(false); Result:=true; end; procedure TProcThreadGroup.EnterExceptionState(E: Exception); begin if FState=mtpgsException then exit; case FState of mtpgsFinishing: RemoveFromList(Pool.FFirstGroupFinishing); mtpgsNeedThreads: RemoveFromList(Pool.FFirstGroupNeedThreads); end; FState:=mtpgsException; FException:=E; WakeThreadsWaitingForIndex; end; constructor TProcThreadGroup.Create; begin FStarterItem:=TMultiThreadProcItem.Create; FStarterItem.FGroup:=Self; end; destructor TProcThreadGroup.Destroy; begin FreeAndNil(FStarterItem); inherited Destroy; end; { TProcThreadPool } procedure TProcThreadPool.SetMaxThreadCount(const AValue: PtrInt); begin if FMaxThreadCount=AValue then exit; if AValue<1 then raise Exception.Create('TLightWeightThreadPool.SetMaxThreadCount'); FMaxThreadCount:=AValue; end; procedure TProcThreadPool.CleanTerminatedThreads; var AThread: TProcThread; begin while FFirstTerminatedThread<>nil do begin AThread:=FFirstTerminatedThread; AThread.RemoveFromList(FFirstTerminatedThread,mtptlPool); AThread.Free; end; end; constructor TProcThreadPool.Create; begin FMaxThreadCount:=GetSystemThreadCount; if FMaxThreadCount<1 then FMaxThreadCount:=1; InitCriticalSection(FCritSection); end; destructor TProcThreadPool.Destroy; procedure WakeWaitingStarterItems(Group: TProcThreadGroup); begin while Group<>nil do begin if Group.StarterItem.FState=mtptsWaitingForIndex then begin Group.StarterItem.FState:=mtptsWaitingFailed; RTLeventSetEvent(Group.StarterItem.fWaitForPool); end; Group:=Group.FNext; end; end; var AThread: TProcThread; begin FDestroying:=true; // wake up all waiting threads EnterPoolCriticalSection; try AThread:=FFirstActiveThread; while AThread<>nil do begin if aThread.Item.FState=mtptsWaitingForIndex then begin aThread.Item.FState:=mtptsWaitingFailed; RTLeventSetEvent(AThread.Item.fWaitForPool); end; AThread:=AThread.FNext[mtptlPool]; end; WakeWaitingStarterItems(FFirstGroupNeedThreads); WakeWaitingStarterItems(FFirstGroupFinishing); finally LeavePoolCriticalSection; end; // wait for all active threads to become inactive while FFirstActiveThread<>nil do Sleep(10); // wake up all inactive threads (without new work they will terminate) EnterPoolCriticalSection; try AThread:=FFirstInactiveThread; while AThread<>nil do begin RTLeventSetEvent(AThread.Item.fWaitForPool); AThread:=AThread.FNext[mtptlPool]; end; finally LeavePoolCriticalSection; end; // wait for all threads to terminate while FFirstInactiveThread<>nil do Sleep(10); // free threads CleanTerminatedThreads; DoneCriticalsection(FCritSection); inherited Destroy; end; procedure TProcThreadPool.EnterPoolCriticalSection; begin EnterCriticalsection(FCritSection); end; procedure TProcThreadPool.LeavePoolCriticalSection; begin LeaveCriticalsection(FCritSection); end; procedure TProcThreadPool.DoParallel(const AMethod: TMTMethod; StartIndex, EndIndex: PtrInt; Data: Pointer; MaxThreads: PtrInt); begin if not Assigned(AMethod) then exit; DoParallelIntern(AMethod,nil,nil,StartIndex,EndIndex,Data,MaxThreads); end; procedure TProcThreadPool.DoParallel(const AProc: TMTProcedure; StartIndex, EndIndex: PtrInt; Data: Pointer; MaxThreads: PtrInt); begin if not Assigned(AProc) then exit; DoParallelIntern(nil,AProc,nil,StartIndex,EndIndex,Data,MaxThreads); end; procedure TProcThreadPool.DoParallelLocalProc(const LocalProc: Pointer; StartIndex, EndIndex: PtrInt; Data: Pointer; MaxThreads: PtrInt); var Frame: Pointer; begin if not Assigned(LocalProc) then exit; Frame:=get_caller_frame(get_frame); DoParallelIntern(nil,TMTProcedure(LocalProc),Frame,StartIndex,EndIndex, Data,MaxThreads); end; procedure TProcThreadPool.CalcBlockSize(LoopLength: PtrInt; out BlockCount, BlockSize: PtrInt; MinBlockSize: PtrInt); begin if LoopLength<=0 then begin BlockCount:=0; BlockSize:=1; exit; end; // split work into equally sized blocks BlockCount:=ProcThreadPool.MaxThreadCount; BlockSize:=(LoopLength div BlockCount); if (BlockSize<MinBlockSize) then BlockSize:=MinBlockSize; BlockCount:=((LoopLength-1) div BlockSize)+1; end; procedure TProcThreadPool.DoParallelIntern(const AMethod: TMTMethod; const AProc: TMTProcedure; const AFrame: Pointer; StartIndex, EndIndex: PtrInt; Data: Pointer; MaxThreads: PtrInt); var Group: TProcThreadGroup; Index: PtrInt; AThread: TProcThread; NewThread: Boolean; Item: TMultiThreadProcItem; HelperThreadException: Exception; begin if (StartIndex>EndIndex) then exit; // nothing to do if FDestroying then raise Exception.Create('Pool destroyed'); if (MaxThreads>MaxThreadCount) or (MaxThreads<=0) then MaxThreads:=MaxThreadCount; if (StartIndex=EndIndex) or (MaxThreads<=1) then begin // single threaded Item:=TMultiThreadProcItem.Create; try for Index:=StartIndex to EndIndex do begin Item.FIndex:=Index; if Assigned(AFrame) then begin CallLocalProc(AProc,AFrame,Index,Data,Item) end else begin if Assigned(AProc) then AProc(Index,Data,Item) else AMethod(Index,Data,Item) end; end; finally Item.Free; end; exit; end; // create a new group Group:=TProcThreadGroup.Create; Group.FPool:=Self; Group.FTaskData:=Data; Group.FTaskMethod:=AMethod; Group.FTaskProcedure:=AProc; Group.FTaskFrame:=AFrame; Group.FStartIndex:=StartIndex; Group.FEndIndex:=EndIndex; Group.FFirstRunningIndex:=StartIndex; Group.FLastRunningIndex:=StartIndex; Group.FMaxThreads:=MaxThreads; Group.FThreadCount:=1; Group.FStarterItem.FState:=mtptsActive; Group.FStarterItem.FIndex:=StartIndex; HelperThreadException:=nil; try // start threads EnterPoolCriticalSection; try Group.AddToList(FFirstGroupNeedThreads,mtpgsNeedThreads); while Group.NeedMoreThreads do begin AThread:=FFirstInactiveThread; NewThread:=false; if AThread<>nil then begin AThread.RemoveFromList(FFirstInactiveThread,mtptlPool); end else if FThreadCount<FMaxThreadCount then begin AThread:=TProcThread.Create; if Assigned(AThread.FatalException) then raise AThread.FatalException; NewThread:=true; inc(FThreadCount); end else begin break; end; // add to Group Group.AddThread(AThread); // start thread AThread.AddToList(FFirstActiveThread,mtptlPool); AThread.Item.FState:=mtptsActive; if NewThread then {$IF defined(VER2_4_2) or defined(VER2_4_3)} AThread.Resume {$ELSE} AThread.Start {$ENDIF} else RTLeventSetEvent(AThread.Item.fWaitForPool); end; finally LeavePoolCriticalSection; end; // run until no more Index left Index:=StartIndex; repeat Group.FStarterItem.FIndex:=Index; Group.Run(Index,Data,Group.FStarterItem); EnterPoolCriticalSection; try Group.IndexComplete(Index); if (Group.FLastRunningIndex<Group.EndIndex) and (Group.FState<>mtpgsException) then begin inc(Group.FLastRunningIndex); Index:=Group.FLastRunningIndex; end else begin Index:=StartIndex; end; finally LeavePoolCriticalSection; end; until Index=StartIndex; finally // wait for Group to finish if Group.FFirstThread<>nil then begin EnterPoolCriticalSection; try Group.FStarterItem.FState:=mtptsInactive; Group.FStarterItem.fIndex:=EndIndex;// needed for Group.HasFinishedIndex // wake threads waiting for starter thread to finish if Group.FStarterItem.FState<>mtptsInactive then Group.EnterExceptionState(nil) else Group.WakeThreadsWaitingForIndex; finally LeavePoolCriticalSection; end; // waiting with exponential spin lock Index:=0; while Group.FFirstThread<>nil do begin sleep(Index); Index:=Index*2+1; if Index>30 then Index:=30; end; end; // remove group from pool EnterPoolCriticalSection; try case Group.FState of mtpgsNeedThreads: Group.RemoveFromList(FFirstGroupNeedThreads); mtpgsFinishing: Group.RemoveFromList(FFirstGroupFinishing); end; finally LeavePoolCriticalSection; end; HelperThreadException:=Group.FException; Group.Free; // free terminated threads (terminated, because of exceptions) CleanTerminatedThreads; end; // if the exception occured in a helper thread raise it now if HelperThreadException<>nil then raise HelperThreadException; end; initialization ProcThreadPool:=TProcThreadPool.Create; CurrentThread:=nil; finalization ProcThreadPool.Free; ProcThreadPool:=nil; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * 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. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFMenuModelDelegate; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefMenuModelDelegateOwn = class(TCefBaseRefCountedOwn, ICefMenuModelDelegate) protected procedure ExecuteCommand(const menuModel: ICefMenuModel; commandId: Integer; eventFlags: TCefEventFlags); virtual; procedure MouseOutsideMenu(const menuModel: ICefMenuModel; const screenPoint: PCefPoint); virtual; procedure UnhandledOpenSubmenu(const menuModel: ICefMenuModel; isRTL: boolean); virtual; procedure UnhandledCloseSubmenu(const menuModel: ICefMenuModel; isRTL: boolean); virtual; procedure MenuWillShow(const menuModel: ICefMenuModel); virtual; procedure MenuClosed(const menuModel: ICefMenuModel); virtual; function FormatLabel(const menuModel: ICefMenuModel; const label_ : uString) : boolean; virtual; public constructor Create; virtual; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions, uCEFMenuModel; procedure cef_menu_model_delegate_execute_command(self: PCefMenuModelDelegate; menu_model: PCefMenuModel; command_id: Integer; event_flags: TCefEventFlags); stdcall; begin with TCefMenuModelDelegateOwn(CefGetObject(self)) do ExecuteCommand(TCefMenuModelRef.UnWrap(menu_model), command_id, event_flags); end; procedure cef_menu_model_delegate_mouse_outside_menu(self: PCefMenuModelDelegate; menu_model: PCefMenuModel; const screen_point: PCefPoint); stdcall; begin with TCefMenuModelDelegateOwn(CefGetObject(self)) do MouseOutsideMenu(TCefMenuModelRef.UnWrap(menu_model), screen_point); end; procedure cef_menu_model_delegate_unhandled_open_submenu(self: PCefMenuModelDelegate; menu_model: PCefMenuModel; is_rtl: integer); stdcall; begin with TCefMenuModelDelegateOwn(CefGetObject(self)) do UnhandledOpenSubmenu(TCefMenuModelRef.UnWrap(menu_model), is_rtl <> 0); end; procedure cef_menu_model_delegate_unhandled_close_submenu(self: PCefMenuModelDelegate; menu_model: PCefMenuModel; is_rtl: integer); stdcall; begin with TCefMenuModelDelegateOwn(CefGetObject(self)) do UnhandledCloseSubmenu(TCefMenuModelRef.UnWrap(menu_model), is_rtl <> 0); end; procedure cef_menu_model_delegate_menu_will_show(self: PCefMenuModelDelegate; menu_model: PCefMenuModel); stdcall; begin with TCefMenuModelDelegateOwn(CefGetObject(self)) do MenuWillShow(TCefMenuModelRef.UnWrap(menu_model)); end; procedure cef_menu_model_delegate_menu_closed(self: PCefMenuModelDelegate; menu_model: PCefMenuModel); stdcall; begin with TCefMenuModelDelegateOwn(CefGetObject(self)) do MenuClosed(TCefMenuModelRef.UnWrap(menu_model)); end; function cef_menu_model_delegate_format_label(self: PCefMenuModelDelegate; menu_model: PCefMenuModel; label_ : PCefString) : integer; stdcall; begin with TCefMenuModelDelegateOwn(CefGetObject(self)) do Result := Ord(FormatLabel(TCefMenuModelRef.UnWrap(menu_model), CefString(label_))); end; constructor TCefMenuModelDelegateOwn.Create; begin CreateData(SizeOf(TCefMenuModelDelegate)); with PCefMenuModelDelegate(FData)^ do begin execute_command := cef_menu_model_delegate_execute_command; mouse_outside_menu := cef_menu_model_delegate_mouse_outside_menu; unhandled_open_submenu := cef_menu_model_delegate_unhandled_open_submenu; unhandled_close_submenu := cef_menu_model_delegate_unhandled_close_submenu; menu_will_show := cef_menu_model_delegate_menu_will_show; menu_closed := cef_menu_model_delegate_menu_closed; format_label := cef_menu_model_delegate_format_label; end; end; procedure TCefMenuModelDelegateOwn.ExecuteCommand( const menuModel: ICefMenuModel; commandId: Integer; eventFlags: TCefEventFlags); begin end; procedure TCefMenuModelDelegateOwn.MouseOutsideMenu(const menuModel: ICefMenuModel; const screenPoint: PCefPoint); begin end; procedure TCefMenuModelDelegateOwn.UnhandledOpenSubmenu(const menuModel: ICefMenuModel; isRTL: boolean); begin end; procedure TCefMenuModelDelegateOwn.UnhandledCloseSubmenu(const menuModel: ICefMenuModel; isRTL: boolean); begin end; procedure TCefMenuModelDelegateOwn.MenuWillShow(const menuModel: ICefMenuModel); begin end; procedure TCefMenuModelDelegateOwn.MenuClosed(const menuModel: ICefMenuModel); begin end; function TCefMenuModelDelegateOwn.FormatLabel(const menuModel: ICefMenuModel; const label_ : uString) : boolean; begin Result := False; end; end.
Unit ListarProgramas; interface uses windows; const UNINST_PATH = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'; Separador = '##@@'; function ListarApp(Clave: String): String; implementation uses UnitDiversos; function GetValueName(chave, valor: string): string; begin try result := lerreg(HKEY_LOCAL_MACHINE, pchar(chave), pchar(valor), ''); except result := ''; end; end; function ToKey(Clave: String): HKEY; begin if Clave = 'HKEY_CLASSES_ROOT' then Result := HKEY_CLASSES_ROOT else if Clave = 'HKEY_CURRENT_CONFIG' then Result := HKEY_CURRENT_CONFIG else if Clave = 'HKEY_CURRENT_USER' then Result := HKEY_CURRENT_USER else if Clave = 'HKEY_LOCAL_MACHINE' then Result := HKEY_LOCAL_MACHINE else if Clave = 'HKEY_USERS' then Result := HKEY_USERS else Result:=0; end; function ListarApp(Clave: String): String; var phkResult: hkey; lpName: PChar; lpcbName, dwIndex: Cardinal; lpftLastWriteTime: FileTime; DispName, UninstStr, QuietUninstallString: string; begin result := ''; if clave = '' then exit; RegOpenKeyEx(ToKey(Copy(Clave, 1, Pos('\', Clave) - 1)), PChar(Copy(Clave, Pos('\', Clave) + 1, Length(Clave))), 0, KEY_ENUMERATE_SUB_KEYS, phkResult); lpcbName := 255; GetMem(lpName, lpcbName); dwIndex := 0; while RegEnumKeyEx(phkResult, dwIndex, @lpName[0] , lpcbName, nil, nil, nil, @lpftLastWriteTime) = ERROR_SUCCESS do begin DispName := getvaluename(UNINST_PATH + '\' + lpname, 'DisplayName'); UninstStr := getvaluename(UNINST_PATH + '\' + lpname, 'UninstallString'); QuietUninstallString := getvaluename(UNINST_PATH + '\' + lpname, 'QuietUninstallString'); if DispName <> '' then begin Result := Result + DispName + Separador; if QuietUninstallString <> '' then Result := Result + QuietUninstallString + Separador + 'YYY' + separador + #13#10 else if UninstStr <> '' then Result := Result + UninstStr + Separador + 'NNN' + separador + #13#10 else Result := Result + ' ' + separador + 'NNN' + separador + #13#10; end; Inc(dwIndex); lpcbName := 255; end; RegCloseKey(phkResult); end; end.
unit Ecopalm2; interface uses Math, SysUtils, DateUtils; implementation uses ModelsManage, Main, GestionDesErreurs, Palmier; // ################################################################## // ###### Ecopalm 2 ######## // ################################################################## procedure EvalCroissanceJour(const CroisVegAn, Cstr: double; var CroissanceJour: Double); // calcul journalier de la Croissance begin try CroissanceJour := Cstr * CroisVegAn / 365; if modeDebugPrecis then MainForm.memDeroulement.Lines.Add('Proc. , Croissance du jour: ' + FloatToStr(CroissanceJour)); except AfficheMessageErreur('EvalCroissanceJour', UEcopalm2); end; end; //////////////////////////////////////////////////////////////////// procedure EvolCroissanceMois(const CroissanceJour: Double; const thisDate: TDateTime; {Proc 206}var CroissanceMois: Double); // Calcul mensuel de la Croissance var Year, Month, Day: Word; begin try DecodeDate(thisdate, Year, Month, Day); if Day = 1 then CroissanceMois := 0; CroissanceMois := CroissanceMois + CroissanceJour; if modeDebugPrecis then MainForm.memDeroulement.Lines.Add('Proc. (' + DateToStr(thisDate) + '), Croissance du mois: ' + FloatToStr(CroissanceMois)); except AfficheMessageErreur('CroissanceMois ', UEcopalm2); end; end; procedure EvalRespMaintJour(const KrespMaint, TmoyCalc: double; {Proc 205}var RespMaintJour: Double); // calcul journalier de la Respiration de Maintenance begin try RespMaintJour := KrespMaint * power(2, (TmoyCalc - 25) / 10); if modeDebugPrecis then MainForm.memDeroulement.Lines.Add('Proc. , Respiration de Maintenance du jour: ' + FloatToStr(RespMaintJour)); except AfficheMessageErreur('EvalRespMaintJour ', UEcopalm2); end; end; //////////////////////////////////////////////////////////////////// procedure EvolRespMaintMois(const RespMaintJour: Double; const thisDate: TDateTime; {Proc 206}var RespMaintMois: Double); // Calcul mensuel de la Respiration de Maintenance var Year, Month, Day: Word; begin try DecodeDate(thisdate, Year, Month, Day); if Day = 1 then RespMaintMois := 0; RespMaintMois := RespMaintMois + RespMaintJour; if modeDebugPrecis then MainForm.memDeroulement.Lines.Add('Proc. (' + DateToStr(thisDate) + '), Respiration de Maintenance du mois: ' + FloatToStr(RespMaintMois)); except AfficheMessageErreur('RespMaintMois ', UEcopalm2); end; end; ////////////////////////////////////////////////////////////////// procedure CalculeCstrMois(const DateDuJour: TDateTime; const Cstr: Double; var CstrMois: Double); {Proc 245} // sert à calculer le CSTR et FTSW moyen mensuel var Annee, Mois, Jour: Word; begin DecodeDate(DateDuJour, Annee, Mois, Jour); if Jour = 1 then CstrMois := 0; CstrMois := CstrMois + (Cstr / DaysInAMonth(Annee, Mois)); end; /////////////////////////////////////////////////////////////////////////////////////////// procedure EvalOffreNetteMois2(const OffreBruteMois, RespMaintMois, CroissanceMois: Double; {Proc 207}var OffreNetteMois: Double); // Calcul mensuel de l'offre nette dédiée à la reproduction begin try OffreNetteMois := OffreBruteMois - RespMaintMois - CroissanceMois; //L'offre nette est ce qui reste éventuellement pour le rendement après déduction de la respiration et de la croissance prioritaires; // L'offre nette peut être < 0 ; on prélève dans les réserves ; on ne prend que la partie >0 dans DeltaOffreDemande except AfficheMessageErreur('EvalOffreNetteMois2', UEcopalm2); end; end; ///////////////////////////////////////////////////////// procedure EvalDemandeReproPot(const thisDate: TDateTime; const ProdAnRegPotPF, KTeneurEau, KChimique: Double; var DemandeReproPot: Double); var PotentielFloraison: Double; begin try PotentielFloraison := TabDemReproMois[MonthOf(thisDate)]; //DemandeReproPot:=PotentielFloraison*(ProdAnRegPotPF *(1- KTeneurEau) * KChimique*1.5) /365; DemandeReproPot := PotentielFloraison * (ProdAnRegPotPF * (1 - KTeneurEau) * KChimique) / 365; //JCC 09/06/05 pour être conforme au calcul du rendement if modeDebugPrecis then MainForm.memDeroulement.Lines.Add('Proc. (' + DateToStr(thisDate) + '), DemandeReproPot: ' + FloatToStr(DemandeReproPot)); except AfficheMessageErreur('EvalDemandeReproPot', UEcopalm2); end; end; //////////////////////////////////////////////////////////////////////////////////////////////////// procedure EvalDemandeMois2(const thisDate: TDateTime; const KPondIc4, KPondIc3, KPondIc2, KPondIc1, {Proc 209}DemandeReproPot, MoisIc1, MoisIc2, MoisIc3, MoisIc4: Double; var DemandeReproMois: Double); // Calcul de la demande reproductive mensuelle pondérée par les Ic var LesFreins, F4, F3, F2, F1: Double; begin try if RechercheIcDecale(thisDate, Trunc(MoisIc4)) = -999 then F4 := 1 else F4 := RechercheIcDecale(thisDate, Trunc(MoisIc4)); if RechercheIcDecale(thisDate, Trunc(MoisIc3)) = -999 then F3 := 1 else F3 := RechercheIcDecale(thisDate, Trunc(MoisIc3)); if RechercheIcDecale(thisDate, Trunc(MoisIc2)) = -999 then F2 := 1 else F2 := RechercheIcDecale(thisDate, Trunc(MoisIc2)); if RechercheIcDecale(thisDate, Trunc(MoisIc1)) = -999 then F1 := 1 else F1 := RechercheIcDecale(thisDate, Trunc(MoisIc1)); LesFreins := min(1, F4 / max(0.001, KPondIc4)) * min(1, F3 / max(0.001, KPondIc3)) * min(1, F2 / max(0.001, KPondIc2)) * min(1, F1 / max(0.001, KPondIc1)); {LesFreins := min(1,KPondIc3 * F3 + (1-KPondIc3)) * min(1,KPondIc2 * F2 + (1-KPondIc2)) * min(1,KPondIc1 * F1 + (1-KPondIc1)); } DemandeReproMois := max(0.001, DemandeReproPot * LesFreins); if modeDebugPrecis then MainForm.memDeroulement.Lines.Add('Proc. (' + DateToStr(thisDate) + '), DemandeReproMois: ' + FloatToStr(DemandeReproMois)); except AfficheMessageErreur('EvalDemandeMois2', UEcopalm2); end; end; ///////////////////////////////////////////////////////////////////// procedure EvolReserveMois2(const OffreNetteMois, DemandeReproMois, KReallocReserve, CoutRealloc, CstrMois: double; {Proc 215}var ReserveMois, Reallocation: double); // Calcule le stock de réserve mensuel // remplace une partie de RepartiAssimilats Proc 65 var DeltaOffreDemande, Ratio: double; begin try // Quand l'offre nette est négative on consomme des réserves prioritairement; ReserveMois := max(0, ReserveMois + min(0, OffreNetteMois)); // On consomme d'abord les réserves quand OffreNetteMois < 0 DeltaOffreDemande := max(0, OffreNetteMois) - DemandeReproMois; Ratio := ReserveMois / 20000; //réserve sur réserve max pour freiner la réallocation if DeltaOffreDemande < 0 then begin if Ratio < 0.4 then Reallocation := Min(ReserveMois / CoutRealloc, -DeltaOffreDemande * KReallocReserve * Ratio / 0.4) else Reallocation := Min(ReserveMois / CoutRealloc, -DeltaOffreDemande * KReallocReserve); // On ne peut pas réallouer plus que les réserves //Reallocation := Min(ReserveMois/CoutRealloc, -DeltaOffreDemande*min(1,ReserveMois/12000)); //JCC 9/06/05 ReserveMois := Max(0, ReserveMois - Reallocation * CoutRealloc); end else begin Reallocation := 0; ReserveMois := ReserveMois + DeltaOffreDemande; end; except AfficheMessageErreur('EvolReserveMois2', UEcopalm2); end; end; ///////////////////////////////////////////////////////////////////// procedure EvalIcMois2(const thisDate: TDateTime; const OffreBruteMois, RendementRegimePS, RespiMois, CroissanceMois: double; {Proc 218}var IcMois: double); // calcul de l'indice de compétition mensuel // JCC calcule Ic = offre brute : (demande repro + croissance + respiration ) begin try IcMois := OffreBruteMois / max(0.001, RendementRegimePS + RespiMois + CroissanceMois); SetLength(tabIcMensuel, length(tabIcMensuel) + 1); tabIcMensuel[High(tabIcMensuel)].Mois := MonthOf(thisDate); tabIcMensuel[High(tabIcMensuel)].Annee := YearOf(thisDate); tabIcMensuel[High(tabIcMensuel)].ValeurIc := IcMois; except AfficheMessageErreur('EvalIcMois2', UEcopalm2); end; end; ///////////////////////////////////////////////////////////////////// procedure EvolReserveMois21(const CroisVegAn, CroissanceMois, OffreNetteMois, DemandeReproMois, KReallocReserve, CoutRealloc, CstrMois: double; {Proc 215}var ReserveMois, Reallocation: double); // Calcule le stock de réserve mensuel // remplace une partie de RepartiAssimilats Proc 65 var DeltaOffreDemande: double; begin try // Quand l'offre nette est négative on consomme des réserves prioritairement; // La croissance végétative étant constante, ce qui manque est prélevé dans les réserves //ReserveMois := max(0,ReserveMois+min(0,OffreNetteMois)+min(0,(CroissanceMois-CroisVegAn/12)*CoutRealloc)); // On consomme d'abord les réserves quand OffreNetteMois < 0 ReserveMois := max(0, ReserveMois + min(0, OffreNetteMois)); DeltaOffreDemande := max(0, OffreNetteMois) - DemandeReproMois; if DeltaOffreDemande < 0 then begin Reallocation := Min(ReserveMois / CoutRealloc, -DeltaOffreDemande * KReallocReserve); // On ne peut pas réallouer plus que les réserves ReserveMois := Max(0, ReserveMois - Reallocation * CoutRealloc); end else begin Reallocation := 0; ReserveMois := ReserveMois + DeltaOffreDemande; end; except AfficheMessageErreur('EvolReserveMois2', UEcopalm2); end; end; ///////////////////////////////////////////////////////////////////// procedure EvalIcMois21(const thisDate: TDateTime; const OffreBruteMois, DemandeReproMois, RespiMois, CroissanceMois: double; {Proc 218}var IcMois: double); // calcul de l'indice de compétition mensuel // JCC calcule Ic = offre brute : (demande repro + croissance + respiration ) begin try IcMois := OffreBruteMois / max(0.001, DemandeReproMois + RespiMois + CroissanceMois); SetLength(tabIcMensuel, length(tabIcMensuel) + 1); tabIcMensuel[High(tabIcMensuel)].Mois := MonthOf(thisDate); tabIcMensuel[High(tabIcMensuel)].Annee := YearOf(thisDate); tabIcMensuel[High(tabIcMensuel)].ValeurIc := IcMois; except AfficheMessageErreur('EvalIcMois2', UEcopalm2); end; end; // ################################################################## procedure EvalOffreBruteJour2(const ReserveMois, KEpsiB, Par, Ltr, Cstr: double; {Proc 205}var OffreBruteJour: Double); // calcul journalier de la photosynthèse // remplace Biomasse.Assimilat Proc76 var ReserveMax, Conversion: Double; begin try begin ReserveMax := 20000; if ReserveMois / ReserveMax <= 0.6 then Conversion := max(1, 1.5 - ReserveMois / ReserveMax) else Conversion := (1 - min(1, ReserveMois / ReserveMax)) / (1 - 0.6); end; OffreBruteJour := Par * KEpsiB * Conversion * Cstr * 10 * (1 - LTR); if modeDebugPrecis then MainForm.memDeroulement.Lines.Add('Proc. n°205, Offre brute du jour: ' + FloatToStr(OffreBruteJour)); except AfficheMessageErreur('EvalOffreBruteJour n°205 ', UPalmier); end; end; //////////////////////////////////////////////////////////////////// //""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" // LISTE DES PROCEDURES DYNAMIQUES // //""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" procedure EvalCroissanceJourDyn(var T: TPointeurProcParam); begin EvalCroissanceJour(T[0], T[1], T[2]); end; procedure EvalDemandeMois2Dyn(var T: TPointeurProcParam); begin EvalDemandeMois2(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9], T[10]); end; procedure EvalDemandeReproPotDyn(var T: TPointeurProcParam); begin EvalDemandeReproPot(T[0], T[1], T[2], T[3], T[4]); end; procedure EvalIcMois2Dyn(var T: TPointeurProcParam); begin EvalIcMois2(T[0], T[1], T[2], T[3], T[4], T[5]); end; procedure EvalOffreNetteMois2Dyn(var T: TPointeurProcParam); begin EvalOffreNetteMois2(T[0], T[1], T[2], T[3]); end; procedure EvalRespMaintJourDyn(var T: TPointeurProcParam); begin EvalRespMaintJour(T[0], T[1], T[2]); end; procedure EvolCroissanceMoisDyn(var T: TPointeurProcParam); begin EvolCroissanceMois(T[0], T[1], T[2]); end; procedure EvolReserveMois2Dyn(var T: TPointeurProcParam); begin EvolReserveMois2(T[0], T[1], T[2], T[3], T[4], T[5], T[6]); end; procedure EvolRespMaintMoisDyn(var T: TPointeurProcParam); begin EvolRespMaintMois(T[0], T[1], T[2]); end; procedure CalculeCstrMoisDyn(var T: TPointeurProcParam); begin CalculeCstrMois(T[0], T[1], T[2]); end; procedure EvolReserveMois21Dyn(var T: TPointeurProcParam); begin EvolReserveMois21(T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]); end; procedure EvalOffreBruteJour2Dyn(var T: TPointeurProcParam); begin EvalOffreBruteJour2(T[0], T[1], T[2], T[3], T[4], T[5]); end; initialization TabProc.AjoutProc('EvalCroissanceJour', EvalCroissanceJourDyn); TabProc.AjoutProc('EvalDemandeMois2', EvalDemandeMois2Dyn); TabProc.AjoutProc('EvalDemandeReproPot', EvalDemandeReproPotDyn); TabProc.AjoutProc('EvalIcMois2', EvalIcMois2Dyn); TabProc.AjoutProc('EvalOffreNetteMois2', EvalOffreNetteMois2Dyn); TabProc.AjoutProc('EvalRespMaintJour', EvalRespMaintJourDyn); TabProc.AjoutProc('EvolCroissanceMois', EvolCroissanceMoisDyn); TabProc.AjoutProc('EvolReserveMois2', EvolReserveMois2Dyn); TabProc.AjoutProc('EvolRespMaintMois', EvolRespMaintMoisDyn); TabProc.AjoutProc('CalculeCstrMois', CalculeCstrMoisDyn); TabProc.AjoutProc('EvolReserveMois21', EvolReserveMois21Dyn); TabProc.AjoutProc('EvalOffreBruteJour2', EvalOffreBruteJour2Dyn); end.
unit GTIN; interface uses SysUtils; type { Global Trade Item Number (GTIN) is an identifier for trade items, developed by GS1 The family of data structures (not symbologies) comprising GTIN include: * GTIN-12 (UPC-A): this is a 12-digit number used primarily in North America * GTIN-8 (EAN/UCC-8): this is an 8-digit number used predominately outside of North America * GTIN-13 (EAN/UCC-13): this is a 13-digit number used predominately outside of North America * GTIN-14 (EAN/UCC-14 or ITF-14): this is a 14-digit number used to identify trade items at various packaging levels } TGTIN = record private FValue: string; function CalculateCheckDigit: string; public class operator Implicit(const GTIN: string): TGTIN; class operator Implicit(const GTIN: TGTIN): string; function IsValid: Boolean; overload; procedure AssertValid; property Value: string read FValue write FValue; end; GTINException = class(Exception); function GTINIsValid(const GTIN: string): Boolean; procedure GTINAssertValid(const GTIN: string); implementation uses Math; procedure GTINAssertValid(const GTIN: string); var G: TGTIN; begin G := GTIN; G.AssertValid; end; function GTINIsValid(const GTIN: string): Boolean; var G: TGTIN; begin G := GTIN; Result := G.IsValid; end; { TGTIN } class operator TGTIN.Implicit(const GTIN: string): TGTIN; begin Result.Value := GTIN; end; procedure TGTIN.AssertValid; var GTINLength: Integer; begin GTINLength := Length(FValue); if not (GTINLength in [8, 12, 13, 14]) then raise GTINException.Create('The GTIN ' + FValue + ' have a invalid Data Structure'); if FValue[GTINLength] <> CalculateCheckDigit then raise GTINException.Create('Check digit is invalid'); end; function TGTIN.CalculateCheckDigit: string; var I: Integer; Sum, CheckDigit: Integer; Number: string; function Multiplier: Integer; begin Result := IfThen(Odd(I), 3, 1); end; begin for I := Length(FValue)-1 downto 1 do Number := Number + FValue[I]; Sum := 0; for I := 1 to Length(Number) do Sum := Sum + (StrToIntDef(Number[I], 0) * Multiplier); CheckDigit := (Ceil(Sum/10)*10) - Sum; Result := IntToStr(CheckDigit); end; class operator TGTIN.Implicit(const GTIN: TGTIN): string; begin Result := GTIN.Value; end; function TGTIN.IsValid: Boolean; begin try AssertValid; Result := True; except Result := False; end; end; end.
{Part 7 of regression test for SPECFUNX unit (c) 2010 W.Ehrhardt} unit t_sfx7; {$i STD.INC} {$ifdef BIT16} {$N+} {$ifndef Windows} {$O+} {$endif} {$endif} {$ifdef NOBASM} {$undef BASM} {$endif} interface procedure test_agmx; procedure test_bernpolyx; procedure test_lambertwx; procedure test_lambertw1x; procedure test_debyex; procedure test_li_invx; procedure test_RiemannRx; procedure test_cosintx; procedure test_sinintx; procedure test_fibpolyx; procedure test_lucpolyx; procedure test_catalanx; procedure test_keplerx; implementation uses sfmisc, AMath,SpecFunX,t_sfx0; {---------------------------------------------------------------------------} procedure test_agmx; var y,f: extended; cnt, failed: integer; const NE = 4; begin cnt := 0; failed := 0; writeln('Function: ','agmx'); y := agmx(MinExtended, sqrt(MaxExtended)); f := 1.0057908883979824235e2462; testrel( 1, 8, y, f, cnt,failed); y := agmx(1, sqrt(MaxExtended)); f := 3.0166361817511369342e2462; testrel( 2, 8, y, f, cnt,failed); y := agmx(MinExtended, 1); f := 0.00013831665471884746733; testrel( 3, NE, y, f, cnt,failed); y := agmx(0, 1); f := 0; testabs( 4, 0, y, f, cnt,failed); y := agmx(1, 0); f := 0; testabs( 5, 0, y, f, cnt,failed); y := agmx(1, 1e-100); f := 0.0067810557455754508824; testrel( 5, NE, y, f, cnt,failed); y := agmx(1, 1e-10); f := 0.064344870476013322929; testrel( 7, NE, y, f, cnt,failed); y := agmx(1, 1e-5); f := 0.12177452186538904490; testrel( 8, NE, y, f, cnt,failed); y := agmx(1, 0.125); f := 0.45196952219967034359; testrel( 9, NE, y, f, cnt,failed); y := agmx(1, 0.5); f := 0.72839551552345343459; testrel(10, NE, y, f, cnt,failed); y := agmx(1, 1); f := 1; testrel(11, 0, y, f, cnt,failed); y := agmx(1, 1000); f := 189.38830240995087556; testrel(12, NE, y, f, cnt,failed); y := agmx(1, 1e20); f := 3311261967046375735.6; testrel(13, NE, y, f, cnt,failed); y := agmx(1, 1e200); f := 3.4007037462646779626e197; testrel(14, NE, y, f, cnt,failed); y := agmx(1, 1e2000); f := 3.4099143980881323512e1996; testrel(15, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_lambertwx; var x,y,f: extended; cnt, failed: integer; i: integer; const NE = 4; const f1 : THexExtW = ($DFCB,$957A,$A652,$FD4D,$BFFE); f2 : THexExtW = ($DBFD,$D0FC,$576C,$FAA5,$BFFE); begin cnt := 0; failed := 0; writeln('Function: ','LambertWx'); x := -exp(-1); y := LambertWx(x); f := -1; testrel( 1, NE, y, f, cnt,failed); x := -6027/16384.0; y := LambertWx(x); f := extended(f1); {= -0.989466090356909241858} testrel( 2, NE, y, f, cnt,failed); x := -3013/8192.0; y := LambertWx(x); f := extended(f2); {= -0.97908541113519070839} testrel( 3, NE, y, f, cnt,failed); x := -753/2048; y := LambertWx(x); f := -0.9670887700916448631; testrel( 4, NE, y, f, cnt,failed); x := -0.25; y := LambertWx(x); f := -0.3574029561813889031; testrel( 5, NE, y, f, cnt,failed); x := -0.125; y := LambertWx(x); f := -0.1444213531375097292; testrel( 6, NE, y, f, cnt,failed); x := -0.0009765625; y := LambertWx(x); f := -0.977517573730222695e-3; testrel( 7, NE, y, f, cnt,failed); x := -1e-10; y := LambertWx(x); f := -0.1000000000100000000e-9; testrel( 8, NE, y, f, cnt,failed); x := 0.0; y := LambertWx(x); f := 0; testrel( 9, 1, y, f, cnt,failed); x := 1e-10; y := LambertWx(x); f := 0.9999999999000000000e-10; testrel(10, NE, y, f, cnt,failed); x := 0.0009765625; y := LambertWx(x); f := 0.9756102202467530500e-3; testrel(11, NE, y, f, cnt,failed); x := 0.125; y := LambertWx(x); f := 0.1117801089327885068; testrel(12, NE, y, f, cnt,failed); x := 0.25; y := LambertWx(x); f := 0.2038883547022401644; testrel(13, NE, y, f, cnt,failed); x := 1; y := LambertWx(x); f := +0.5671432904097838730; testrel(14, NE, y, f, cnt,failed); x := 3.125; y := LambertWx(x); f := 1.070918030310010008; testrel(15, NE, y, f, cnt,failed); x := 10; y := LambertWx(x); f := 1.745528002740699383; testrel(16, NE, y, f, cnt,failed); x := 100; y := LambertWx(x); f := 3.385630140290050185; testrel(17, NE, y, f, cnt,failed); x := 1e4; y := LambertWx(x); f := 7.231846038093372706; testrel(18, NE, y, f, cnt,failed); x := 1e10; y := LambertWx(x); f := 20.02868541330495078; testrel(19, NE, y, f, cnt,failed); x := MaxDouble; {2^1024} y := LambertWx(x); f := 703.2270331047701870; testrel(20, NE, y, f, cnt,failed); x := MaxExtended; y := LambertWx(x); f := 11347.18668117145943; testrel(21, NE, y, f, cnt,failed); x := 1e-300; y := LambertWx(x); f := x; testrel(22, NE, y, f, cnt,failed); x := -0.359375; y := LambertWx(x); f := -0.7990217286464407601; testrel(23, NE, y, f, cnt,failed); x := -0.36767578125; y := LambertWx(x); f := -0.9670887700916448631; testrel(24, NE, y, f, cnt,failed); x := MaxExtended; i := 1000; while x>1e-200 do begin y := LambertWx(x); f := ln(x/y); if y>=0.5 then testrel(i, 2, y, f, cnt,failed) else testabs(i, 1, y, f, cnt,failed); x := 0.125*x; inc(i); end; x := -exp(-1); i := 10000; while x<-MinExtended do begin y := LambertWx(x); f := ln(x/y); if y>=0.5 then testrel(i, 2, y, f, cnt,failed) else testabs(i, 2, y, f, cnt,failed); if x < -1e-7 then x := 0.95*x else x := 0.01*x; inc(i); end; if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_lambertw1x; var x,y,f,lim: extended; cnt, failed: integer; i: integer; const NE = 8; begin cnt := 0; failed := 0; writeln('Function: ','LambertW1x'); x := -exp(-1); y := LambertW1x(x); f := -1; testrel( 1, NE, y, f, cnt,failed); {$ifdef BASM} lim := -MinExtended; x := -6027/16384.0; y := LambertW1x(x); f := -1.010608408692175856; testrel( 2, NE, y, f, cnt,failed); x := -MinExtended; y := LambertW1x(x); f := -11364.47535950542118; {$ifdef WIN16} testrele(13, 1e-14, y, f, cnt,failed); {!!!???} {$else} testrel(13, NE, y, f, cnt,failed); {$endif} {$else} {System ln/exp functions are too inaccurate for iterations at} {arguments very close to -1/e and -0. Test skipped.} lim := -1e-4900; {$endif} x := -3013/8192.0; y := LambertW1x(x); f := -1.021210331605726089434; testrel( 3, NE, y, f, cnt,failed); x := -753/2048; y := LambertW1x(x); f := -1.033649565301978476; testrel( 4, NE, y, f, cnt,failed); x := -0.25; y := LambertW1x(x); f := -2.153292364110349649; testrel( 5, NE, y, f, cnt,failed); x := -0.125; y := LambertW1x(x); f := -3.261685684576488777; testrel( 6, NE, y, f, cnt,failed); x := -0.0009765625; y := LambertW1x(x); f := -9.144639686625083192; testrel( 7, NE, y, f, cnt,failed); x := -1e-10; y := LambertW1x(x); f := -26.29523881924692569; testrel( 8, NE, y, f, cnt,failed); x := -1e-100; y := LambertW1x(x); f := -235.7211588756853137; testrel( 9, NE, y, f, cnt,failed); x := -1e-299; y := LambertW1x(x); f := -695.0168789367294442; testrel(10, NE, y, f, cnt,failed); x := -1e-400; y := LambertW1x(x); f := -927.8669255208986530; testrel(11, NE, y, f, cnt,failed); x := -1e-4000; y := LambertW1x(x); f := -9219.469444747123985; testrel(12, NE, y, f, cnt,failed); x := -exp(-1); i := 1000; while x<Lim do begin y := LambertW1x(x); f := ln(x/y); testrel(i, 2, y, f, cnt,failed); if x < -1e-7 then x := 0.95*x else x := 0.01*x; inc(i); end; if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_debyex; var x,y,f: extended; cnt, failed: integer; const NE = 8; f1 : THexExtW = ($A3D7,$1C70,$01C7,$FFE0,$3FFE); {+9.9951182471380889183E-1} f72: THexExtW = ($6829,$6D07,$8498,$C5B7,$3FFB); {.9654143896262086549358612680186751027932e-1} begin cnt := 0; failed := 0; writeln('Function: ','debyex'); {Test values debye(n,x), n=1,3,4 from MISCFUN [22]} x := 1/512; y := debyex(1,x); {f := 0.99951182471380889183;} f := extended(f1); testrel( 1, NE, y, f, cnt,failed); x := 1/32; y := debyex(1,x); f := 0.99221462647120597836; testrel( 2, NE, y, f, cnt,failed); x := 1/8; y := debyex(1,x); f := 0.96918395997895308324; testrel( 3, NE, y, f, cnt,failed); x := 1/2; y := debyex(1,x); f := 0.88192715679060552968; testrel( 4, NE, y, f, cnt,failed); x := 1.0; y := debyex(1,x); f := 0.77750463411224827642; testrel( 5, NE, y, f, cnt,failed); x := 2.0; y := debyex(1,x); f := 0.60694728460981007205; testrel( 6, NE, y, f, cnt,failed); x := 3.0; y := debyex(1,x); f := 0.48043521957304283829; testrel( 7, NE, y, f, cnt,failed); x := 4.0; y := debyex(1,x); f := 0.38814802129793784501; testrel( 8, NE, y, f, cnt,failed); x := 17/4; y := debyex(1,x); f := 0.36930802829242526815; testrel( 9, NE, y, f, cnt,failed); x := 5.0; y := debyex(1,x); f := 0.32087619770014612104; testrel(10, NE, y, f, cnt,failed); x := 11/2; y := debyex(1,x); f := 0.29423996623154246701; testrel(11, NE, y, f, cnt,failed); x := 6.0; y := debyex(1,x); f := 0.27126046678502189985; testrel(12, NE, y, f, cnt,failed); x := 8.0; y := debyex(1,x); f := 0.20523930310221503723; testrel(13, NE, y, f, cnt,failed); x := 10.0; y := debyex(1,x); f := 0.16444346567994602563; testrel(14, NE, y, f, cnt,failed); x := 20.0; y := debyex(1,x); f := 0.82246701178200016086e-1; testrel(15, NE, y, f, cnt,failed); x := 50.0; y := debyex(1,x); f := 0.32898681336964528729e-1; testrel(16, NE, y, f, cnt,failed); x := 1/512; y := debyex(3,x); f := 0.99926776885985461940; testrel(17, NE, y, f, cnt,failed); x := 1/32; y := debyex(3,x); f := 0.98833007755734698212; testrel(18, NE, y, f, cnt,failed); x := 1/8; y := debyex(3,x); f := 0.95390610472023510237; testrel(19, NE, y, f, cnt,failed); x := 1/2; y := debyex(3,x); f := 0.82496296897623372315; testrel(20, NE, y, f, cnt,failed); x := 1.0; y := debyex(3,x); f := 0.67441556407781468010; testrel(21, NE, y, f, cnt,failed); x := 2.0; y := debyex(3,x); f := 0.44112847372762418113; testrel(22, NE, y, f, cnt,failed); x := 3.0; y := debyex(3,x); f := 0.28357982814342246206; testrel(23, NE, y, f, cnt,failed); x := 4.0; y := debyex(3,x); f := 0.18173691382177474795; testrel(24, NE, y, f, cnt,failed); x := 17/4; y := debyex(3,x); f := 0.16277924385112436877; testrel(25, NE, y, f, cnt,failed); x := 5.0; y := debyex(3,x); f := 0.11759741179993396450; testrel(26, NE, y, f, cnt,failed); x := 11/2; y := debyex(3,x); f := 0.95240802723158889887e-1; testrel(27, NE, y, f, cnt,failed); x := 6.0; y := debyex(3,x); f := 0.77581324733763020269e-1; testrel(28, NE, y, f, cnt,failed); x := 8.0; y := debyex(3,x); f := 0.36560295673194845002e-1; testrel(29, NE, y, f, cnt,failed); x := 10.0; y := debyex(3,x); f := 0.19295765690345489563e-1; testrel(30, NE, y, f, cnt,failed); x := 20.0; y := debyex(3,x); f := 0.24352200674805479827e-2; testrel(31, NE, y, f, cnt,failed); x := 50.0; y := debyex(3,x); f := 0.15585454565440389896e-3; testrel(32, NE, y, f, cnt,failed); x := 1/512; y := debyex(4,x); f := 0.99921896192761576256; testrel(33, NE, y, f, cnt,failed); x := 1/32; y := debyex(4,x); f := 0.98755425280996071022; testrel(34, NE, y, f, cnt,failed); x := 1/8; y := debyex(4,x); f := 0.95086788606389739976; testrel(35, NE, y, f, cnt,failed); x := 1/2; y := debyex(4,x); f := 0.81384569172034042516; testrel(36, NE, y, f, cnt,failed); x := 1.0; y := debyex(4,x); f := 0.65487406888673697092; testrel(37, NE, y, f, cnt,failed); x := 2.0; y := debyex(4,x); f := 0.41189273671788528876; testrel(38, NE, y, f, cnt,failed); x := 3.0; y := debyex(4,x); f := 0.25187863642883314410; testrel(39, NE, y, f, cnt,failed); x := 4.0; y := debyex(4,x); f := 0.15185461258672022043; testrel(40, NE, y, f, cnt,failed); x := 17/4; y := debyex(4,x); f := 0.13372661145921413299; testrel(41, NE, y, f, cnt,failed); x := 5.0; y := debyex(4,x); f := 0.91471377664481164749e-1; testrel(42, NE, y, f, cnt,failed); x := 11/2; y := debyex(4,x); f := 0.71227828197462523663e-1; testrel(43, NE, y, f, cnt,failed); x := 6.0; y := debyex(4,x); f := 0.55676547822738862783e-1; testrel(44, NE, y, f, cnt,failed); x := 8.0; y := debyex(4,x); f := 0.21967566525574960096e-1; testrel(45, NE, y, f, cnt,failed); x := 10.0; y := debyex(4,x); f := 0.96736755602711590082e-2; testrel(46, NE, y, f, cnt,failed); x := 20.0; y := debyex(4,x); f := 0.62214648623965450200e-3; testrel(47, NE, y, f, cnt,failed); x := 50.0; y := debyex(4,x); f := 0.15927210319002161231e-4; testrel(48, NE, y, f, cnt,failed); {Rest of test values for n=6,8,12 calculated with Maple } {f := x->n*int(t^n/(exp(t)-1),t=0..x)/x^n; and Digits:=50} x := 1/512; y := debyex(6,x); f := 0.9991631848471384035; testrel(49, NE, y, f, cnt,failed); x := 1/32; y := debyex(6,x); f := 0.9866681772186796587; testrel(50, NE, y, f, cnt,failed); x := 1/8; y := debyex(6,x); f := 0.9474049305411031823; testrel(51, NE, y, f, cnt,failed); x := 1/2; y := debyex(6,x); f := 0.8012874593544054948; testrel(52, NE, y, f, cnt,failed); x := 1.0; y := debyex(6,x); f := 0.6331114258349510759; testrel(53, NE, y, f, cnt,failed); x := 2.0; y := debyex(6,x); f := 0.3804986630746610429; testrel(54, NE, y, f, cnt,failed); x := 3.0; y := debyex(6,x); f := 0.2193992525257245836; testrel(55, NE, y, f, cnt,failed); x := 4.0; y := debyex(6,x); f := 0.1229278562814578228; testrel(56, NE, y, f, cnt,failed); x := 17/4; y := debyex(6,x); f := 0.1060375248597196031; testrel(57, NE, y, f, cnt,failed); x := 5.0; y := debyex(6,x); f := 0.6777784974890353731e-1; testrel(58, NE, y, f, cnt,failed); x := 11/2; y := debyex(6,x); f := 0.5020600934448088116e-1; testrel(59, NE, y, f, cnt,failed); x := 6.0; y := debyex(6,x); f := 0.3719333613705515670e-1; testrel(60, NE, y, f, cnt,failed); x := 8.0; y := debyex(6,x); f := 0.1145231921902748610e-1; testrel(61, NE, y, f, cnt,failed); x := 10.0; y := debyex(6,x); f := 0.3793849329461595528e-2; testrel(62, NE, y, f, cnt,failed); x := 20.0; y := debyex(6,x); f := 0.6804635545479456894e-4; testrel(63, NE, y, f, cnt,failed); x := 50.0; y := debyex(6,x); f := 0.2787884082105527120e-6; testrel(64, NE, y, f, cnt,failed); x := 1/512; y := debyex(12,x); f := 0.9990988301706686501; testrel(65, NE, y, f, cnt,failed); x := 1/32; y := debyex(12,x); f := 0.9856466765478185763; testrel(66, NE, y, f, cnt,failed); x := 1/8; y := debyex(12,x); f := 0.9434235095071814036; testrel(67, NE, y, f, cnt,failed); x := 1/2; y := debyex(12,x); f := 0.7870231504611680153; testrel(68, NE, y, f, cnt,failed); x := 1.0; y := debyex(12,x); f := 0.6088700041762235049; testrel(69, NE, y, f, cnt,failed); x := 2.0; y := debyex(12,x); f := 0.3472653175019342084; testrel(70, NE, y, f, cnt,failed); x := 3.0; y := debyex(12,x); f := 0.1872401059320712096; testrel(71, NE, y, f, cnt,failed); x := 4.0; y := debyex(12,x); {f := 0.9654143896262086549e-1;} f := extended(f72); testrel(72, NE, y, f, cnt,failed); x := 17/4; y := debyex(12,x); f := 0.8134774441706960165e-1; testrel(73, NE, y, f, cnt,failed); x := 5.0; y := debyex(12,x); f := 0.4814185645191148541e-1; testrel(74, NE, y, f, cnt,failed); x := 11/2; y := debyex(12,x); f := 0.3367880055948328374e-1; testrel(75, NE, y, f, cnt,failed); x := 6.0; y := debyex(12,x); f := 0.2344811348723500784e-1; testrel(76, NE, y, f, cnt,failed); x := 8.0; y := debyex(12,x); f := 0.5344588786833453221e-2; testrel(77, NE, y, f, cnt,failed); x := 10.0; y := debyex(12,x); f := 0.1198815360618837356e-2; testrel(78, NE, y, f, cnt,failed); x := 20.0; y := debyex(12,x); f := 0.1348750701799345211e-5; testrel(79, NE, y, f, cnt,failed); x := 50.0; y := debyex(12,x); f := 0.2354677578932315411e-10; testrel(80, NE, y, f, cnt,failed); {D(n,20) n=20..200} x := 20; f := 0.2045985597891880435e-6; y := debyex(20,x); testrel(81, NE, y, f, cnt,failed); f := 0.6521968411709099410e-7; y := debyex(50,x); testrel(82, NE, y, f, cnt,failed); f := 0.5964824507515076368e-7; y := debyex(60,x); testrel(83, NE, y, f, cnt,failed); f := 0.5378148028857494088e-7; y := debyex(80,x); testrel(84, NE, y, f, cnt,failed); f := 0.5074077974146328750e-7; y := debyex(100,x); testrel(85, NE, y, f, cnt,failed); f := 0.4714758392337898263e-7; y := debyex(150,x); testrel(86, NE, y, f, cnt,failed); f := 0.4552275137444157216e-7; y := debyex(200,x); testrel(87, NE, y, f, cnt,failed); {D(n,5) n=100..10000} x := 5; f := 0.3532560165653401053e-1; y := debyex(100,x); testrel(88, NE, y, f, cnt,failed); f := 0.34193472837210103295e-1; y := debyex(500,x); testrel(89, 20, y, f, cnt,failed); f := 0.3410139487334168171e-1; y := debyex(750,x); testrel(90, 40, y, f, cnt,failed); f := 0.3405548547450571961e-1; y := debyex(1000,x); testrel(91, 40, y, f, cnt,failed); f := 0.3398678310287432440e-1; y := debyex(2000,x); testrel(92, 100, y, f, cnt,failed); f := 0.3393196075652582305e-1; y := debyex(10000,x); testrel(93, 600, y, f, cnt,failed); {Test after fix for large x} y := debyex(1, 100000.0); f := 0.1644934066848226436e-4; testrel(94, NE, y, f, cnt,failed); x := 20000.0; y := debyex(2, x); f := 0.1202056903159594285e-7; testrel(95, NE, y, f, cnt,failed); y := debyex(7, x); f := 0.2767488213020584085e-25; testrel(96, NE, y, f, cnt,failed); y := debyex(10, x); f := 0.3545501280865848353e-35; testrel(97, NE, y, f, cnt,failed); y := debyex(8, 30000.0); f := 0.4926197640450862355e-30; testrel(98, NE, y, f, cnt,failed); y := debyex(20, 12000); f := 0.12691995186452421609e-61; testrel(99, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_RiemannRx; var y,f: extended; cnt, failed: integer; const NE = 6; begin cnt := 0; failed := 0; writeln('Function: ','RiemannRx'); y := RiemannRx(ldexp(1,16000)); f := 2.722853936980310468e4812; testrel( 1, NE, y, f, cnt,failed); y := RiemannRx(1e100); f := 4.361971987140703159e97; testrel( 2, NE, y, f, cnt,failed); y := RiemannRx(1e30); f := 0.1469239889772043272e29; testrel( 3, NE, y, f, cnt,failed); y := RiemannRx(1e24); f := 0.18435599767347541878e23; testrel( 4, NE, y, f, cnt,failed); y := RiemannRx(1e20); f := 0.2220819602556027015e19; testrel( 5, NE, y, f, cnt,failed); y := RiemannRx(1e19); f := 0.2340576673002289402e18; testrel( 6, NE, y, f, cnt,failed); y := RiemannRx(1e18); f := 0.2473995428423949440e17; testrel( 7, NE, y, f, cnt,failed); y := RiemannRx(1e16); f := 0.2792383413609771872e15; testrel( 8, NE, y, f, cnt,failed); y := RiemannRx(1e6); f := 78527.39942912770486; testrel( 9, NE, y, f, cnt,failed); y := RiemannRx(1000); f := 168.3594462811673481; testrel(10, NE, y, f, cnt,failed); y := RiemannRx(100); f := 25.66163326692418259; testrel(11, NE, y, f, cnt,failed); y := RiemannRx(10); f := 4.564583141005090240; testrel(12, NE, y, f, cnt,failed); y := RiemannRx(8); f := 3.901186044934149947; testrel(13, NE, y, f, cnt,failed); y := RiemannRx(4); f := 2.426657752706807136; testrel(14, NE, y, f, cnt,failed); y := RiemannRx(2); f := 1.541009016187131883; testrel(15, NE, y, f, cnt,failed); y := RiemannRx(1); f := 1; testrel(16, NE, y, f, cnt,failed); y := RiemannRx(0.5); f := 0.6635262381124574212; testrel(17, NE, y, f, cnt,failed); y := RiemannRx(0.1); f := 0.2790883528560020161; testrel(18, NE, y, f, cnt,failed); y := RiemannRx(0.125); f := 0.3124612249259569001; testrel(19, NE, y, f, cnt,failed); y := RiemannRx(0.0625); f := 0.2216077332920197402; testrel(20, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_li_invx; var y,f: extended; cnt, failed: integer; const NE = 2; NE1 = 3; begin cnt := 0; failed := 0; writeln('Function: ','li_invx'); y := li_invx(0); f := 1.0 + 0.4513692348833810503; testrel(1, NE, y, f, cnt,failed); y := li_invx(0.25); f := 1.552800837242485188; testrel(2, NE, y, f, cnt,failed); y := li_invx(0.5); f := 1.671930573009875373; testrel(3, NE, y, f, cnt,failed); y := li_invx(0.75); f := 1.810255009236505581; testrel(4, NE, y, f, cnt,failed); y := li_invx(1); f := 1.969047489224750850; testrel(5, NE, y, f, cnt,failed); y := succd(1); y := li_invx(y); f := 1.969047489224751001; testrel(6, NE, y, f, cnt,failed); y := li_invx(2); f := 2.825187152005826843; testrel(7, NE, y, f, cnt,failed); y := li_invx(3); f := 4.045118486231030200; testrel(8, NE, y, f, cnt,failed); y := li_invx(3.5); f := 4.786319700881971309; testrel(9, NE, y, f, cnt,failed); y := li_invx(4); f := 5.609276693050890355; testrel(10, NE, y, f, cnt,failed); y := li_invx(5); f := 7.480870261577641432; testrel(11, NE, y, f, cnt,failed); y := li_invx(8); f := 14.58290311807629198; testrel(12, NE, y, f, cnt,failed); y := li_invx(10); f := 20.284365456596612497; testrel(13, NE, y, f, cnt,failed); y := li_invx(20); f := 56.07960987414566197; testrel(14, NE, y, f, cnt,failed); y := li_invx(100); f := 488.8719098528075319; testrel(15, NE, y, f, cnt,failed); y := li_invx(1000); f := 7762.986220174737687; testrel(16, NE, y, f, cnt,failed); y := li_invx(-0.25); f := 1.365970426374257461; testrel(17, NE, y, f, cnt,failed); y := li_invx(-0.5); f := 1.294838891062147533; testrel(18, NE, y, f, cnt,failed); y := li_invx(-0.75); f := 1.236183126594032207; testrel(19, NE, y, f, cnt,failed); y := li_invx(-1); f := 1.188256066274325355; testrel(20, NE, y, f, cnt,failed); y := li_invx(-10); f := 1.000025489896249632; testrel(21, NE, y, f, cnt,failed); y := li_invx(-15); f := 1.0 + 0.1717517441415356666e-6; testrel(22, NE, y, f, cnt,failed); y := li_invx(-40); f := 1.0 + 0.238528e-17; testrel(23, NE, y, f, cnt,failed); y := li_invx(-43.5); f := 1 + 0.72e-19; testrel(24, NE, y, f, cnt,failed); y := li_invx(1e10); f := 0.2520971600140342078e12; testrel(25, NE, y, f, cnt,failed); y := li_invx(1e100); f := 0.2347125735865764178e103; testrel(26, NE, y, f, cnt,failed); y := li_invx(1e300); f := 0.6963198968074983689e303; testrel(27, NE, y, f, cnt,failed); y := li_invx(1e4500); f := 0.1036987948270089444e4505; testrel(28, NE1, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_bernpolyx; var x,y,f: extended; n, cnt, failed: integer; const NE = 8; NE1 = 32; NE2 = 360; begin cnt := 0; failed := 0; writeln('Function: ','bernpolyx'); y := bernpolyx(1,-1); f := -3/2; testrel(1, NE, y, f, cnt,failed); y := bernpolyx(7,-1); f := -7; testrel(2, NE, y, f, cnt,failed); y := bernpolyx(8,-1); f := 239/30; testrel(3, NE, y, f, cnt,failed); y := bernpolyx(1,1); f := 0.5; testrel(4, NE, y, f, cnt,failed); y := bernpolyx(7,1); f := 0; testrel(5, NE, y, f, cnt,failed); y := bernpolyx(8,1); f := -0.3333333333333333333e-1; testrel(6, NE, y, f, cnt,failed); {some 'normal' case} y := bernpolyx(10,-0.75); f := 0.7507730252815015388; testrel(7, NE, y, f, cnt,failed); y := bernpolyx(12,1/3); f := 0.1265560621400686431; testrel(8, NE, y, f, cnt,failed); y := bernpolyx(11,-0.125); f := -0.9375500085297971964e-1; testrel(9, NE, y, f, cnt,failed); y := bernpolyx(20, 0.375); f := 374.14698287953266697; {$ifdef FPC271or3} testrel(10, NE+1, y, f, cnt,failed); {$else} testrel(10, NE, y, f, cnt,failed); {$endif} y := bernpolyx(15,-1.25); f := -343.8455539522692561; testrel(11, NE, y, f, cnt,failed); y := bernpolyx(12,2.5); f := 1038.229552462511447; testrel(12, NE, y, f, cnt,failed); x := 10000+1/3; y := bernpolyx(15,x); f := 0.9997499416835207086e60; testrel(13, NE, y, f, cnt,failed); y := bernpolyx(10,x); f := 0.9998333083377781148e40; testrel(14, NE, y, f, cnt,failed); x := sqrt(1e21); y := bernpolyx(15,x); f := 0.3162277659418379332e158; testrel(15, NE, y, f, cnt,failed); x := sqrt(1e21); y := bernpolyx(10,x); f := 0.9999999998418861170e105; testrel(16, NE, y, f, cnt,failed); y := bernpolyx(256,0.5); f := 0.7950212504588525285e303; testrel(17, NE, y, f, cnt,failed); y := bernpolyx(100,0.5); f := 2.838224957069370696e78; testrel(18, NE, y, f, cnt,failed); x := -987654321.0/65536.0; {=15070.4089508056641} y := bernpolyx(70,x); f := 0.2949584500818898822e293; testrel(19, NE, y, f, cnt,failed); x := 1e-5; y := bernpolyx(7,x); f := 0.1666666665500000000e-5; testrel(20, NE, y, f, cnt,failed); x := 1e-5; y := bernpolyx(6,x); f := 0.2380952375952380955e-1; testrel(21, NE, y, f, cnt,failed); x := 0.5e-5; y := bernpolyx(6,x); f := 0.2380952379702380953e-1; testrel(22, NE, y, f, cnt,failed); x := 1e-11; y := bernpolyx(2,x); f := 0.1666666666566666667; testrel(23, NE, y, f, cnt,failed); y := bernpolyx(3,x); f := 0.4999999999850000000e-11; testrel(24, NE, y, f, cnt,failed); y := bernpolyx(4,x); f := -0.3333333333333333333e-1; testrel(25, NE, y, f, cnt,failed); y := bernpolyx(5,x); f := -0.1666666666666666667e-11; testrel(26, NE, y, f, cnt,failed); x := 1e-12; y := bernpolyx(15,x); f := 0.175e-10; testrel(27, NE, y, f, cnt,failed); x := 1e-10; y := bernpolyx(15,x); f := 0.175e-8; testrel(28, NE, y, f, cnt,failed); x := 1e-10; y := bernpolyx(20,x); f := -529.1242424242424241; testrel(29, NE, y, f, cnt,failed); x := 2e-10; y := bernpolyx(51,x); f := 0.7650884080998503652e17; testrel(30, NE, y, f, cnt,failed); x := 1e-5; y := bernpolyx(51,x); f := 0.3825442037982211854e22; testrel(31, NE, y, f, cnt,failed); x := 1e-5; y := bernpolyx(101,x); f := -0.2866607204753912463e76; testrel(32, NE, y, f, cnt,failed); x := 3e5; y := bernpolyx(16,x); f := 0.4304557309700593800e88; testrel(33, NE, y, f, cnt,failed); x := -100; y := bernpolyx(2,x); f := 10100.16666666666667; testrel(34, NE, y, f, cnt,failed); x := -Pi; y := bernpolyx(15,x); f := -0.1374730009236393778e9; testrel(35, NE, y, f, cnt,failed); x := sqrt(10); y := bernpolyx(20,x); f := 46168783.47767854148; testrel(36, NE, y, f, cnt,failed); y := bernpolyx(15,x); f := 732699.8879814299995; testrel(37, NE, y, f, cnt,failed); {larger errors} x := 1/4; y := bernpolyx(68,x); f := 0.8896458292761226510e22; testrel(38, NE1, y, f, cnt,failed); x := 2/3; y := bernpolyx(70,x); f := -0.1606254105135901626e45; testrel(39, NE1, y, f, cnt,failed); x := -1.75; y := bernpolyx(75,x); f := 0.6794407537645821705e50; testrel(40, NE1, y, f, cnt,failed); x := 4.75; y := bernpolyx(120,x); f := 0.2450175593271593322e71; testrel(41, NE, y, f, cnt,failed); {extended only} n := 500; x := -100; y := bernpolyx(n,x); f := 0.5033394824322324121e1001; testrel(42, NE, y, f, cnt,failed); x := -100.25; y := bernpolyx(n,x); f := 0.1749862589719046419e1002; testrel(43, NE, y, f, cnt,failed); x := 987654321.0/65536.0; {=15070.4089508056641} y := bernpolyx(n,x); f := 0.1135780279029176150e2090; testrel(44, NE1, y, f, cnt,failed); y := bernpolyx(1000,0.5); f := 0.5318704469415522036e1770; testrel(45, NE, y, f, cnt,failed); {extreme} y := bernpolyx(1000,10.5); f := 5.318704469415522036e+1769; testrel(46, NE2, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_cosintx; var y,f: extended; cnt, failed: integer; const NE = 2; NE2 = 4; begin cnt := 0; failed := 0; writeln('Function: ','cosintx'); {special case} y := cosintx(10000,0); f := 0; testrel(1, NE, y, f, cnt,failed); f := -1234.5; y := cosintx(0,f); testrel(2, NE, y, f, cnt,failed); y := cosintx(1,-1234.5); f := -0.1453956505229364208; testrel(3, NE, y, f, cnt,failed); {------------------------------} y := cosintx(10,4); f := 1.158627877632916986; testrel(4, NE2, y, f, cnt,failed); y := cosintx(10,5); f := 1.159689565748002596; testrel(5, NE2, y, f, cnt,failed); y := cosintx(10,Pi); f := 0.7731263170943631798; testrel(6, NE, y, f, cnt,failed); y := cosintx(10,Pi_2); f := 0.3865631585471815899; testrel(7, NE, y, f, cnt,failed); y := cosintx(10,19*Pi_2); f := 7.344700012396450208; testrel(8, NE, y, f, cnt,failed); y := cosintx(10,-19*Pi_2); f := -7.344700012396450208; testrel(9, NE, y, f, cnt,failed); y := cosintx(10,100); f := 24.38341351832059336; testrel(10, NE, y, f, cnt,failed); y := cosintx(5,1); f := 0.5286328129112155881; testrel(11, NE, y, f, cnt,failed); y := cosintx(17,Pi_2); f := 32768/109395; testrel(12, NE, y, f, cnt,failed); y := cosintx(20,1.25); f := 0.2767696820752703606; testrel(13, NE2, y, f, cnt,failed); y := cosintx(20,10); f := 1.935371243364068614; testrel(14, NE, y, f, cnt,failed); y := cosintx(99,TwoPi); f := 0; testrel(15, NE, y, f, cnt,failed); y := cosintx(99,4); f := -0.1256451290185490101; testrel(16, NE, y, f, cnt,failed); y := cosintx(9,30); f := -0.4063492055789358166; testrel(17, NE, y, f, cnt,failed); y := cosintx(200,10000); f := 563.5558003428517485; testrel(18, NE, y, f, cnt,failed); y := cosintx(600,100000); f := 3255.962631924894514; testrel(19, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_sinintx; var y,f: extended; cnt, failed: integer; const NE = 4; NE2 = 8; NE_R = 80; {large rel. err for sinint(n,0.5) ~ 0, abs.err <= 1} begin cnt := 0; failed := 0; writeln('Function: ','sinintx'); {special case} y := sinintx(10000,0); f := 0; testrel(1, NE, y, f, cnt,failed); f := -1234.5; y := sinintx(0,f); testrel(2, NE, y, f, cnt,failed); y := sinintx(1,-1234.5); f := 1.989373592132422007; testrel(3, NE, y, f, cnt,failed); {------------------------------} y := sinintx(6,0.5); f := 0.9185547761246106100e-3; testrel(4, NE2, y, f, cnt,failed); y := sinintx(6,1.5); f := 0.4204309461889264874; testrel(5, NE, y, f, cnt,failed); y := sinintx(6,2.5); f := 0.9771099714670822183; testrel(6, NE, y, f, cnt,failed); y := sinintx(6,3.0); f := 0.9817475437693720085; testrel(7, NE, y, f, cnt,failed); y := sinintx(6,5.0); f := 1.737945254534703918; testrel(18, NE, y, f, cnt,failed); y := sinintx(6,8.0); f := 2.597326791887639688; testrel(9, NE, y, f, cnt,failed); y := sinintx(6,11.0); f := 3.440542590614796164; testrel(10, NE, y, f, cnt,failed); y := sinintx(6,-4.0); f := -1.009340246947754459; testrel(11, NE, y, f, cnt,failed); y := sinintx(6,-20.0); f := -6.025751555775555279; testrel(12, NE, y, f, cnt,failed); y := sinintx(5,0.5); f := 0.2226985853239443664e-2; testrel(13, NE, y, f, cnt,failed); y := sinintx(5,1.5); f := 0.4628317450440416392; testrel(14, NE, y, f, cnt,failed); y := sinintx(5,2.5); f := 1.057683460168249835; testrel(15, NE2, y, f, cnt,failed); y := sinintx(5,3.5); f := 1.066340666683688580; testrel(16, NE2, y, f, cnt,failed); y := sinintx(5,4.5); f := 0.7379679184068533471; testrel(17, NE, y, f, cnt,failed); y := sinintx(5,5.5); f := 0.2618445135450898748e-1; testrel(18, NE2, y, f, cnt,failed); y := sinintx(5,6.5); f := 0.16811939182727524784e-4; testrel(19, NE, y, f, cnt,failed); y := sinintx(10,Pi_2); f := 0.3865631585471815899; testrel(20, NE, y, f, cnt,failed); y := sinintx(10,Pi); f := 0.7731263170943631798; testrel(21, NE, y, f, cnt,failed); y := sinintx(10,-13*Pi_2); f := -5.025321061113360669; testrel(22, NE, y, f, cnt,failed); y := sinintx(9,Pi_2); f := 0.4063492063492063492; testrel(23, NE, y, f, cnt,failed); y := sinintx(9,Pi); f := 0.8126984126984126984; testrel(24, NE, y, f, cnt,failed); y := sinintx(9,-TwoPi); f := 0; testrel(25, NE, y, f, cnt,failed); y := sinintx(9,-13*Pi_2); f := 0.4063492063492063492; testrel(26, NE2, y, f, cnt,failed); y := sinintx(99,0.5); f := 0.1341426041012494184e-33; testrel(27, NE_R, y, f, cnt,failed); y := sinintx(99,2); f := 0.2512885482248272477; testrel(28, NE, y, f, cnt,failed); y := sinintx(99,Pi_2); f := 0.1256451290185490101; testrel(29, NE, y, f, cnt,failed); y := sinintx(100,0.5); f := 0.6367642770299571293e-34; testrel(30, NE_R, y, f, cnt,failed); y := sinintx(100,2); f := 0.2500354235665634526; testrel(31, NE, y, f, cnt,failed); y := sinintx(100,Pi_2); f := 0.1250184817401874538; testrel(32, NE, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_fibpolyx; var x,y,f,r: extended; cnt, failed, k,n: integer; const NE = 2; NE0 = 3; {AMD/FPC} NE1 = 75; {$ifdef BIT16} const tol=5; {$else} const tol=2; {$endif} {Values directly from Maple, note that the 16-bit compilers are inaccurate} {for some literals of length > 19, therefore the tolerance is increased !} const fp15: array[-10..10] of extended = ( -450359962737049.599999999999998, 14073748835532.8000000000000113, -439804651110.399999999999636200, 13743895347.2000000000116415321, -429496729.599999999627470970153, 13421772.8000000119209289550781, -419430.3999996185302734375, 13107.20001220703125, -409.599609375, 12.8125, 0, 12.8125, 409.599609375, 13107.20001220703125, 419430.3999996185302734375, 13421772.8000000119209289550781, 429496729.599999999627470970153, 13743895347.2000000000116415321, 439804651110.399999999999636200, 14073748835532.8000000000000113, 450359962737049.599999999999998); fm25: array[-10..10] of extended = ( 17491671035336584642638.2191390, 92899200757966079853.9563808855, 493392625783670135.494300316212, 2620434634437155.42014947329880, 13917268549466.5442822966724634, 73915357907.6294983029365539548, 392568420.6778049468994140625, 2084951.88653564453125, 11073.291015625, 58.8125, 0, 58.8125, -11073.291015625, 2084951.88653564453125, -392568420.6778049468994140625, 73915357907.6294983029365539548, -13917268549466.5442822966724634, 2620434634437155.42014947329880, -493392625783670135.494300316212, 92899200757966079853.9563808855, -17491671035336584642638.2191390); begin {pari: fib(n,x) = ([x,1;1,0]^(n-1))[1,1]} cnt := 0; failed := 0; writeln('Function: ','fibpolyx'); y := fibpolyx(10,1.5); f := 409.599609375; testrel(1, NE, y, f, cnt,failed); y := fibpolyx(15,-Pi); f := 0.2909849191767567043e8; testrel(2, NE, y, f, cnt,failed); y := fibpolyx(123,1.5); f := 0.4253529586511730793e37; testrel(3, NE, y, f, cnt,failed); y := fibpolyx(123,-1.5); f := 0.4253529586511730793e37; testrel(4, NE, y, f, cnt,failed); y := fibpolyx(-123,1.5); f := 0.4253529586511730793e37; testrel(5, NE, y, f, cnt,failed); y := fibpolyx(-123,-1.5); f := 0.4253529586511730793e37; testrel(6, NE, y, f, cnt,failed); y := fibpolyx(234,1.5); f := 0.1104279415486490206e71; testrel(7, NE, y, f, cnt,failed); y := fibpolyx(234,-1.5); f := -0.1104279415486490206e71; testrel(8, NE, y, f, cnt,failed); y := fibpolyx(-234,1.5); f := -0.1104279415486490206e71; testrel(9, NE, y, f, cnt,failed); y := fibpolyx(-234,-1.5); f := 0.1104279415486490206e71; testrel(10, NE, y, f, cnt,failed); {Max n for F(n) = fibpolyx(n,1) is 23601, 1476 for double} y := fibpolyx(1476, 1); f := 0.1306989223763399318e309; testrel(11, NE0, y, f, cnt,failed); y := fibpolyx(32000, 1/32); f := 6.875799035044984665e216; testrel(12, NE1, y, f, cnt,failed); y := fibpolyx(23500, 1); f := 0.7245375068339371795e4911; testrel(13, NE1, y, f, cnt,failed); x := 1.5; for k:=-10 to 10 do begin inc(cnt); n := 5*k; y := fibpolyx(n,x); f := fp15[k]; if f=0.0 then r := y-f else r := 1.0-y/f; if abs(r) > tol*eps_x then begin inc(failed); writeln('Test failed: n,x,err= ',n:4, x:8:2, r:30); end; end; x := -2.5; for k:=-10 to 10 do begin inc(cnt); n := 5*k; y := fibpolyx(n,x); f := fm25[k]; if f=0.0 then r := y-f else r := 1.0-y/f; if abs(r) > tol*eps_x then begin inc(failed); writeln('Test failed: n,x,err= ',n:4, x:8:2, r:30); end; end; if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_lucpolyx; var y,f: extended; cnt, failed: integer; const NE = 2; NE1 = 8; NE2 = 25; begin {Pari: luc(n,x) = trace([x,1;1,0]^n) } {Maple: luc := (n,x) -> fibonacci(n+1,x) + fibonacci(n-1,x); } cnt := 0; failed := 0; writeln('Function: ','lucpolyx'); y := lucpolyx(0,0); f := 2; testrel(1, NE, y, f, cnt,failed); y := lucpolyx(1,0); f := 0; testabs(2, 0, y, f, cnt,failed); y := lucpolyx(2,0); f := 2; testrel(3, NE, y, f, cnt,failed); y := lucpolyx(3,0); f := 0; testabs(4, 0, y, f, cnt,failed); y := lucpolyx(-1,0); f := 0; testabs(5, 0, y, f, cnt,failed); y := lucpolyx(-2,0); f := 2; testrel(6, NE, y, f, cnt,failed); y := lucpolyx(-3,0); f := 0; testabs(7, 0, y, f, cnt,failed); y := lucpolyx(1,1.5); f := 1.5; testrel(8, NE, y, f, cnt,failed); y := lucpolyx(2,1.5); f := 4.25; testrel(9, NE, y, f, cnt,failed); y := lucpolyx(9,1.5); f := 511.998046875; testrel(10, NE, y, f, cnt,failed); y := lucpolyx(9,-1.5); f := -511.998046875; testrel(11, NE, y, f, cnt,failed); y := lucpolyx(-9,1.5); f := -511.998046875; testrel(12, NE, y, f, cnt,failed); y := lucpolyx(-9,-1.5); f := 511.998046875; testrel(13, NE, y, f, cnt,failed); y := lucpolyx(10,1.5); f := 1024.0009765625; testrel(14, NE, y, f, cnt,failed); y := lucpolyx(10,-1.5); f := 1024.0009765625; testrel(15, NE, y, f, cnt,failed); y := lucpolyx(-10,1.5); f := 1024.0009765625; testrel(16, NE, y, f, cnt,failed); y := lucpolyx(-10,-1.5); f := 1024.0009765625; testrel(17, NE, y, f, cnt,failed); y := lucpolyx(125,1.5); f := 0.4253529586511730793e38; testrel(18, NE, y, f, cnt,failed); y := lucpolyx(125,-1.5); f := -0.4253529586511730793e38; testrel(19, NE, y, f, cnt,failed); y := lucpolyx(-125,1.5); f := -0.4253529586511730793e38; testrel(20, NE, y, f, cnt,failed); y := lucpolyx(-125,-1.5); f := 0.4253529586511730793e38; testrel(21, NE, y, f, cnt,failed); y := lucpolyx(234,1.5); f := 0.2760698538716225515e71; testrel(22, NE, y, f, cnt,failed); y := lucpolyx(234,-1.5); f := 0.2760698538716225515e71; testrel(23, NE, y, f, cnt,failed); y := lucpolyx(-234,1.5); f := 0.2760698538716225515e71; testrel(24, NE, y, f, cnt,failed); y := lucpolyx(-234,-1.5); f := 0.2760698538716225515e71; testrel(25, NE, y, f, cnt,failed); y := lucpolyx(-123,4.5); f := -6.407383962038300961e82; {Wolfram Alpha} testrel(26, NE, y, f, cnt,failed); {Max n for L(n) = lucpolyx(n,1) is 23599, 1474 for double} y := lucpolyx(1474,1); f := 1.116302065883468286e308; testrel(27, NE1, y, f, cnt,failed); y := lucpolyx(23599,1); f := 7.930896079529250823e4931; testrel(28, NE2, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_catalanx; var y,f: extended; cnt, failed: integer; const NE = 2; NE1 = 5; begin cnt := 0; failed := 0; writeln('Function: ','catalanx'); y := catalanx(0); f := 1; testrel(1, NE, y, f, cnt,failed); y := catalanx(1e-9); f := 1.999999998000000005*0.5; testrel(2, NE, y, f, cnt,failed); y := catalanx(0.125); f := 0.4542281453407636314 * 2; testrel(3, NE, y, f, cnt,failed); y := catalanx(0.5); f := 0.8488263631567751241; testrel(4, NE, y, f, cnt,failed); y := catalanx(2.5); f := 3.104279270973349025; testrel(5, NE, y, f, cnt,failed); y := catalanx(21); f := 24466267020.0; testrel(6, NE, y, f, cnt,failed); y := catalanx(35); {$ifdef BIT16} f := 0.38953568686341265775e18 * 8; {$else} f := 3116285494907301262.0; {$endif} testrel(7, NE, y, f, cnt,failed); y := catalanx(100); f := 0.8965199470901314967e57; testrel(8, NE, y, f, cnt,failed); y := catalanx(500); f := 0.5394974869170390609e297; testrel(9, NE, y, f, cnt,failed); y := catalanx(-1); f := -0.5; testrel(10, NE, y, f, cnt,failed); y := catalanx(-1.25); f := -0.3934468663386987420; testrel(11, NE, y, f, cnt,failed); y := catalanx(-12.375); f := -0.1218624678667657878e-8; testrel(12, NE1, y, f, cnt,failed); y := catalanx(-45.625); f := 0.1538947487306520572e-29; testrel(13, NE1, y, f, cnt,failed); {FPC} y := catalanx(-123.875); f := 0.4497289298048582343e-78; testrel(14, NE, y, f, cnt,failed); y := catalanx(-456.75); f := 0.5916664229531300294e-279; testrel(15, NE, y, f, cnt,failed); {extended only} y := catalanx(5000); f := 0.3182943938277222452e3005; testrel(16, NE1, y, f, cnt,failed); {FPC} y := catalanx(-5678.9375); f := 0.2278821220272931680e-3425; testrel(17, NE1, y, f, cnt,failed); {FPC} if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; {---------------------------------------------------------------------------} procedure test_keplerx; var y,f: extended; cnt, failed: integer; {$ifdef VER5X} const NE = 3; NE1 = 4; NE2 = 24; {$else} const NE = 2; NE1 = 4; NE2 = 16; {$endif} begin cnt := 0; failed := 0; writeln('Function: ','keplerx'); {elliptic, Maple: kepler := (m,e) -> fsolve(y-e*sin(y) = m, y=Pi);} y := keplerx(1, 0.5); f := 1.498701133517848314; testrel(1, NE, y, f, cnt,failed); y := keplerx(-1000, 0.5); f := -1000.497514775673146; testrel(2, NE, y, f, cnt,failed); y := keplerx(Pi_2, 0.75); f := 2.184106679498448926; testrel(3, NE, y, f, cnt,failed); y := keplerx(0.5, 0.125); f := 0.5671542538034771510; testrel(4, NE, y, f, cnt,failed); y := keplerx(0.125, 0.9375); f := 0.7928034322756140260; testrel(5, NE, y, f, cnt,failed); y := keplerx(1.5, 0.9375); f := 2.237023829054169401; testrel(6, NE, y, f, cnt,failed); y := keplerx(10.125, 0.9375); f := 9.790088287071411171; testrel(7, NE, y, f, cnt,failed); y := keplerx(0.125, 0.99609375); f := 0.9136395753855342618; testrel(8, NE, y, f, cnt,failed); {in difficult region m near 0, e near 1} y := 1-ldexp(1,-20); y := keplerx(1/1024, y); f := 0.1803684433746817368; testrel(9, NE2, y, f, cnt,failed); {arguments from literature, somewhat inexact with binary} y := keplerx(0.2, 0.99); f := 1.066997365281563186; testrel(10, NE, y, f, cnt,failed); y := keplerx(0.06, 0.6); f := 0.1491710835982268287; testrel(11, NE, y, f, cnt,failed); y := keplerx(1, 0.9); f := 1.862086686874532255; testrel(12, NE, y, f, cnt,failed); {hyperbolic, Maple: kepler_hyp := (m,e) -> fsolve(e*sinh(x) - x - m, x = signum(m)*ln(2*abs(m)/e + 1.8));} y := keplerx(-1000, 10); f := -5.303631719539061703; testrel(13, NE, y, f, cnt,failed); y := keplerx(1, 2); f := 0.8140967963021331692; testrel(14, NE, y, f, cnt,failed); y := keplerx(6,2); f := 2.107689797681256377; testrel(15, NE, y, f, cnt,failed); y := keplerx(0.5,1.5); f := 0.7673431749540970103; testrel(16, NE, y, f, cnt,failed); y := keplerx(MaxExtended,1.5); f := 11356.811088366595730; testrel(17, NE, y, f, cnt,failed); y := keplerx(10,6); f := 1+0.3978298998186000144; testrel(18, NE, y, f, cnt,failed); y := keplerx(10000,20); f := 6.9084468837654158448; testrel(19, NE, y, f, cnt,failed); y := keplerx(1,20); f := 0.5260603476886937829e-1; testrel(20, NE, y, f, cnt,failed); y := keplerx(0,2); f := 0; testrel(21, NE, y, f, cnt,failed); y := keplerx(1e-6,1.5); f := 0.1999999999996000000e-5; testrel(22, NE, y, f, cnt,failed); {parabolic, Maple: kepler_para := m -> fsolve(x + x^3/3 = m, x = m^(1/3));} y := keplerx(2, 1); f := 1.287909750704127236; testrel(23, NE, y, f, cnt,failed); y := keplerx(1, 1); f := 0.8177316738868235061; testrel(24, NE, y, f, cnt,failed); y := keplerx(0.5,1.0); f := 0.4662205239107734274; testrel(25, NE, y, f, cnt,failed); y := keplerx(0.125, 1); {$ifdef BIT16} f := 0.2487178477269259601*0.5; {$else} f := 0.124358923863462980055; {$endif} testrel(26, NE, y, f, cnt,failed); y := keplerx(1/1024, 1); {$ifdef BIT16} f := 0.1953124379118875708e-2*0.5; {$else} f := 0.9765621895594378539e-3; {$endif} testrel(27, NE, y, f, cnt,failed); y := keplerx(-1000, 1); {f:= -14.35316011237345298;} f := -(14 + 0.3531601123734529825); testrel(28, NE, y, f, cnt,failed); y := keplerx(sqrt_epsh, 1); f := 0.2328306436538696289e-9; testrel(29, NE, y, f, cnt,failed); y := keplerx(1.25e30, 1); f := 0.1553616252976929433e11; testrel(30, NE1, y, f, cnt,failed); y := keplerx(MaxExtended, 1); f := 0.1528234751400654562e1645; testrel(31, NE, y, f, cnt,failed); y := keplerx(0.25*MaxExtended, 1); {$ifdef BIT16} f := 0.1925455132470543184e1645*0.5; {$else} f := 0.9627275662352715918e1644; {$endif} testrel(32, NE1, y, f, cnt,failed); if failed>0 then writeln('*** failed: ',failed,' of ',cnt) else writeln(cnt:4, ' tests OK'); inc(total_cnt, cnt); inc(total_failed, failed); end; end.
namespace RemObjects.Elements.System; interface type IEquatable<T> = public interface method Equals(rhs: T): Boolean; end; IComparable< {in} T> = public interface mapped to Comparable<T> method CompareTo(rhs: T): Integer; mapped to compareTo(rhs); end; IDisposable = public interface mapped to AutoCloseable method Dispose; mapped to close; end; INotifyPropertyChanged = public interface method addPropertyChangeListener(listener: java.beans.PropertyChangeListener); method removePropertyChangeListener(listener: java.beans.PropertyChangeListener); method firePropertyChange(name: String; oldValue: Object; newValue: Object); end; implementation end.
// // Generated by JavaToPas v1.5 20150830 - 103959 //////////////////////////////////////////////////////////////////////////////// unit javax.security.auth.callback.PasswordCallback; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes; type JPasswordCallback = interface; JPasswordCallbackClass = interface(JObjectClass) ['{B3A12D45-0B4A-4E11-B157-35049715C08D}'] function getPassword : TJavaArray<Char>; cdecl; // ()[C A: $1 function getPrompt : JString; cdecl; // ()Ljava/lang/String; A: $1 function init(prompt : JString; echoOn : boolean) : JPasswordCallback; cdecl;// (Ljava/lang/String;Z)V A: $1 function isEchoOn : boolean; cdecl; // ()Z A: $1 procedure clearPassword ; cdecl; // ()V A: $1 procedure setPassword(password : TJavaArray<Char>) ; cdecl; // ([C)V A: $1 end; [JavaSignature('javax/security/auth/callback/PasswordCallback')] JPasswordCallback = interface(JObject) ['{59880C05-F882-4C33-8513-62DA4E8530C4}'] function getPassword : TJavaArray<Char>; cdecl; // ()[C A: $1 function getPrompt : JString; cdecl; // ()Ljava/lang/String; A: $1 function isEchoOn : boolean; cdecl; // ()Z A: $1 procedure clearPassword ; cdecl; // ()V A: $1 procedure setPassword(password : TJavaArray<Char>) ; cdecl; // ([C)V A: $1 end; TJPasswordCallback = class(TJavaGenericImport<JPasswordCallbackClass, JPasswordCallback>) end; implementation end.
unit UDSectionSize; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UCrpe32; type TCrpeSectionSizeDlg = class(TForm) pnlSectionHeight: TPanel; lblHeight: TLabel; lblSection: TLabel; editHeight: TEdit; rgUnits: TRadioGroup; lbSections: TListBox; memoSectionHeight: TMemo; btnOk: TButton; btnClear: TButton; lblWidth: TLabel; editWidth: TEdit; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure lbSectionsClick(Sender: TObject); procedure editHeightExit(Sender: TObject); procedure rgUnitsClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure UpdateSectionSize; procedure btnOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure InitializeControls(OnOff: boolean); procedure editHeightEnter(Sender: TObject); private { Private declarations } public { Public declarations } Cr : TCrpe; SIndex : Smallint; PrevSize : string; end; var CrpeSectionSizeDlg: TCrpeSectionSizeDlg; bSectionSize : boolean; implementation {$R *.DFM} uses UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate procedure } {------------------------------------------------------------------------------} procedure TCrpeSectionSizeDlg.FormCreate(Sender: TObject); begin bSectionSize := True; LoadFormPos(Self); btnOk.Tag := 1; end; {------------------------------------------------------------------------------} { FormShow procedure } {------------------------------------------------------------------------------} procedure TCrpeSectionSizeDlg.FormShow(Sender: TObject); begin UpdateSectionSize; end; {------------------------------------------------------------------------------} { UpdateSectionSize procedure } {------------------------------------------------------------------------------} procedure TCrpeSectionSizeDlg.UpdateSectionSize; var OnOff : boolean; begin {Enable/Disable controls} if IsStrEmpty(Cr.ReportName) then begin OnOff := False; SIndex := -1; end else begin OnOff := (Cr.SectionSize.Count > 0); {Get SectionSize Index} if OnOff then begin if Cr.SectionSize.ItemIndex > -1 then SIndex := Cr.SectionSize.ItemIndex else SIndex := 0; end; end; InitializeControls(OnOff); if OnOff then begin lbSections.Items.AddStrings(Cr.SectionFormat.Names); lbSections.ItemIndex := SIndex; lbSectionsClick(self); end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeSectionSizeDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TRadioGroup then TRadioGroup(Components[i]).Enabled := OnOff; if Components[i] is TListBox then begin TListBox(Components[i]).Clear; TListBox(Components[i]).Color := ColorState(OnOff); TListBox(Components[i]).Enabled := OnOff; end; if Components[i] is TEdit then begin TEdit(Components[i]).Text := ''; if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { lbSectionsClick procedure } {------------------------------------------------------------------------------} procedure TCrpeSectionSizeDlg.lbSectionsClick(Sender: TObject); begin SIndex := lbSections.ItemIndex; Cr.SectionSize[SIndex]; rgUnitsClick(Self); end; {------------------------------------------------------------------------------} { editHeightEnter procedure } {------------------------------------------------------------------------------} procedure TCrpeSectionSizeDlg.editHeightEnter(Sender: TObject); begin PrevSize := editHeight.Text; end; {------------------------------------------------------------------------------} { editHeightExit procedure } {------------------------------------------------------------------------------} procedure TCrpeSectionSizeDlg.editHeightExit(Sender: TObject); begin if rgUnits.ItemIndex = 0 then {inches} begin if not IsFloating(editHeight.Text) then editHeight.Text := PrevSize else begin Cr.SectionSize.Item.Height := InchesStrToTwips(editHeight.Text); UpdateSectionSize; {this will truncate any decimals beyond 3 places} end; end else {twips} begin if not IsNumeric(editHeight.Text) then editHeight.Text := PrevSize else Cr.SectionSize.Item.Height := StrToInt(editHeight.Text); end; end; {------------------------------------------------------------------------------} { rgUnitsClick procedure } {------------------------------------------------------------------------------} procedure TCrpeSectionSizeDlg.rgUnitsClick(Sender: TObject); begin editHeight.OnExit := nil; case rgUnits.ItemIndex of {Inches} 0 : begin editHeight.Text := TwipsToInchesStr(Cr.SectionSize.Item.Height); editWidth.Text := TwipsToInchesStr(Cr.SectionSize.Item.Width); end; {Twips} 1 : begin editHeight.Text := IntToStr(Cr.SectionSize.Item.Height); editWidth.Text := IntToStr(Cr.SectionSize.Item.Width); end; end; editHeight.OnExit := editHeightExit; end; {------------------------------------------------------------------------------} { btnClearClick procedure } {------------------------------------------------------------------------------} procedure TCrpeSectionSizeDlg.btnClearClick(Sender: TObject); begin Cr.SectionSize.Clear; UpdateSectionSize; end; {------------------------------------------------------------------------------} { btnOkClick procedure } {------------------------------------------------------------------------------} procedure TCrpeSectionSizeDlg.btnOkClick(Sender: TObject); begin rgUnits.ItemIndex := 1; {change to twips to avoid the Update call} if not IsStrEmpty(Cr.ReportName) then editHeightExit(editHeight); SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { FormClose procedure } {------------------------------------------------------------------------------} procedure TCrpeSectionSizeDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bSectionSize := False; Release; end; end.
unit BrowseConfig; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, uSystemTypes; type TOnLoadFicha = procedure (Sender : TObject; var FchFicha : TObject) of object; TBrowseConfig = class(TComponent) private { Private declarations } FRefreshInterval : integer; FCor1, FCor2, FCorHighLight : TColor; FAutoOpen, FMultiPage, FMultiplasCores : Boolean; FViewIndexFieldKey1, FViewIndexFieldKey2 : integer; FnOrderByInicial : integer; FViewDeleteTable, FDefaultButton, FFchClassName : String; FOrderByStateInicial : TOrderByState; FMostraDesativado : TDesativadoState; FMostraHidden : THiddenState; FRealDeletion, FCheckSystemOnDelete : Boolean; FOnLoadFicha : TOnLoadFicha; protected { Protected declarations } constructor Create(AOwner: TComponent); override; public { Public declarations } published { Published declarations } property nOrderByInicial : integer read FnOrderByInicial write FnOrderByInicial default 0; property OrderByStateInicial : TOrderByState read FOrderByStateInicial write FOrderByStateInicial default STD_ORDER_ASC; property MostraDesativado : TDesativadoState read FMostraDesativado write FMostraDesativado default STD_NAODESATIVADO; property MostraHidden : THiddenState read FMostraHidden write FMostraHidden default STD_NAOHIDDEN; property AutoOpen : Boolean read FAutoOpen write FAutoOpen default True; property MultiplasCores : Boolean read FMultiplasCores write FMultiplasCores default True; property Cor1 : TColor read FCor1 write FCor1; property Cor2 : TColor read FCor2 write FCor2; property CorHighLight : TColor read FCorHighLight write FCorHighLight; property ViewIndexFieldKey1 : integer read FViewIndexFieldKey1 write FViewIndexFieldKey1 default 0; property ViewIndexFieldKey2 : integer read FViewIndexFieldKey2 write FViewIndexFieldKey2 default 1; property ViewDeleteTable : String read FViewDeleteTable write FViewDeleteTable; property CheckSystemOnDelete : Boolean read FCheckSystemOnDelete write FCheckSystemOnDelete default True; property RealDeletion : Boolean read FRealDeletion write FRealDeletion default False; property MultiPage : Boolean read FMultiPage write FMultiPage default False; property DefaultButton : String read FDefaultButton write FDefaultButton; property FchClassName : String read FFchClassName write FFchClassName; property RefreshInterval : Integer read FRefreshInterval write FRefreshInterval default 10; property OnLoadFicha : TOnLoadFicha read FOnLoadFicha write FOnLoadFicha; end; procedure Register; implementation procedure Register; begin RegisterComponents('NewPower', [TBrowseConfig]); end; constructor TBrowseConfig.Create(AOwner: TComponent); begin inherited Create(AOwner); FAutoOpen := True; FMultiplasCores := True; FnOrderByInicial := 0; FViewIndexFieldKey1 := 0; FViewIndexFieldKey2 := 1; FOrderByStateInicial := STD_ORDER_ASC; FMostraDesativado := STD_NAODESATIVADO; FMostraHidden := STD_NAOHIDDEN; FCheckSystemOnDelete := True; FRealDeletion := False; FMultiPage := False; FViewDeleteTable := ''; FchClassName := ''; FDefaultButton := 'btDetail'; FRefreshInterval := 10; end; end.
UNIT TETRIS_BOARD; INTERFACE USES TETRIS_PIECE, TETRIS_SACK, SDL, SDL_IMAGE; CONST TETRIS_BOARD_WIDTH = 10; TETRIS_BOARD_HEIGHT = 21; TETRIS_BOARD_TICKTIMER = 96; TETRIS_BOARD_GHOSTTIMER = 4; TETRIS_BOARD_RENDER_OFFSETX = (800 div 2) - ((TETRIS_BOARD_WIDTH * 32) div 2) - 6; { 12 - dodatna granica 6 + 6 } TETRIS_BOARD_PIECE_MARKER_CURRENT = 999; TETRIS_BOARD_PIECE_MARKER_GHOST = 969; TYPE playerstats = RECORD i_lines: integer; i_score: integer; END; arrSurfBlock = ARRAY [1 .. 7] OF PSDL_Surface; arrCount = ARRAY [1 .. 7] OF integer; arrboardwidth = ARRAY [1 .. TETRIS_BOARD_WIDTH] OF integer; arrboard = ARRAY[1 .. TETRIS_BOARD_HEIGHT] OF arrboardwidth; TTetrisBoard = CLASS PRIVATE _board : arrboard; ftimerstep : real; spdup : boolean; piece_lv0 : TTauTetrisPiece; piece_lv1 : TTauTetrisPiece; tetrissack : TTauTetrisSack; arrSrfBlock : arrSurfBlock; arrSrfBlockGhost0 : arrSurfBlock; arrSrfBlockGhost1 : arrSurfBlock; srf_block_ghost : PSDL_Surface; srf_block_ghostReserve: PSDL_Surface; ghostblockState : integer; ghostblockTimer : real; blockcounter : arrCount; playersts : playerstats; f_speed : real; b_gameover : boolean; PROCEDURE CheckBoard(); PROCEDURE Piece_DropDown(piece: TTauTetrisPiece; doscore: BOOLEAN); FUNCTION Piece_CanMove(CONST piece: TTauTetrisPiece; offX, offY: integer): boolean; FUNCTION CurPiece_CanMoveDown(): boolean; FUNCTION CurPiece_CanMoveX(a: integer): boolean; PROCEDURE CurPiece_DoNew(); PROCEDURE CurPiece_DownOne(); PUBLIC CONSTRUCTOR Create(); DESTRUCTOR Destroy(); OVERRIDE; PROCEDURE Reset(); PROCEDURE Nullify(); PROCEDURE Draw(pwin: PSDL_Surface); PROCEDURE DrawReserve(pwin: PSDL_Surface); PROCEDURE Add(piece: TTauTetrisPiece; VAR bboard: arrboard; m: integer); PROCEDURE Tick(); PROCEDURE SpeedUp(b: boolean); PROCEDURE CurPiece_DropDown(); PROCEDURE CurPiece_MoveX(a: integer); PROCEDURE CurPiece_Rot(d: integer); PROCEDURE Piece_Rot(lv, d: integer); FUNCTION GetPiece(lv: integer): TTauTetrisPiece; FUNCTION GetGameOver(): boolean; FUNCTION GetPlayerstats(): playerstats; FUNCTION GetBlockCounter(): arrCount; END; IMPLEMENTATION CONSTRUCTOR TTetrisBoard.Create(); VAR srf_tmp: PSDL_Surface; BEGIN ghostblockState := 0; playersts.i_lines := 0; playersts.i_score := 0; piece_lv0 := NIL; tetrissack := TTauTetrisSack.Create(); b_gameover := FALSE; srf_tmp := IMG_Load('data/tex/block/0/t0.png'); arrSrfBlock[1] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/t1.png'); arrSrfBlock[2] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/t2.png'); arrSrfBlock[3] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/t3.png'); arrSrfBlock[4] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/t4.png'); arrSrfBlock[5] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/t5.png'); arrSrfBlock[6] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/t6.png'); arrSrfBlock[7] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/g_t0.png'); arrSrfBlockGhost0[1] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/g_t1.png'); arrSrfBlockGhost0[2] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/g_t2.png'); arrSrfBlockGhost0[3] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/g_t3.png'); arrSrfBlockGhost0[4] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/g_t4.png'); arrSrfBlockGhost0[5] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/g_t5.png'); arrSrfBlockGhost0[6] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/g_t6.png'); arrSrfBlockGhost0[7] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/g_t10.png'); arrSrfBlockGhost1[1] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/g_t11.png'); arrSrfBlockGhost1[2] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/g_t12.png'); arrSrfBlockGhost1[3] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/g_t13.png'); arrSrfBlockGhost1[4] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/g_t14.png'); arrSrfBlockGhost1[5] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/g_t15.png'); arrSrfBlockGhost1[6] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_tmp := IMG_Load('data/tex/block/0/g_t16.png'); arrSrfBlockGhost1[7] := SDL_DisplayFormatAlpha(srf_tmp); SDL_FreeSurface(srf_tmp); srf_block_ghost := arrSrfBlockGhost0[1]; srf_block_ghostReserve := arrSrfBlockGhost0[1]; Nullify(); CurPiece_DoNew(); END; DESTRUCTOR TTetrisBoard.Destroy(); BEGIN SDL_FreeSurface(arrSrfBlockGhost0[1]); SDL_FreeSurface(arrSrfBlockGhost0[2]); SDL_FreeSurface(arrSrfBlockGhost0[3]); SDL_FreeSurface(arrSrfBlockGhost0[4]); SDL_FreeSurface(arrSrfBlockGhost0[5]); SDL_FreeSurface(arrSrfBlockGhost0[6]); SDL_FreeSurface(arrSrfBlockGhost0[7]); SDL_FreeSurface(arrSrfBlockGhost1[1]); SDL_FreeSurface(arrSrfBlockGhost1[2]); SDL_FreeSurface(arrSrfBlockGhost1[3]); SDL_FreeSurface(arrSrfBlockGhost1[4]); SDL_FreeSurface(arrSrfBlockGhost1[5]); SDL_FreeSurface(arrSrfBlockGhost1[6]); SDL_FreeSurface(arrSrfBlockGhost1[7]); SDL_FreeSurface(arrSrfBlock[1]); SDL_FreeSurface(arrSrfBlock[2]); SDL_FreeSurface(arrSrfBlock[3]); SDL_FreeSurface(arrSrfBlock[4]); SDL_FreeSurface(arrSrfBlock[5]); SDL_FreeSurface(arrSrfBlock[6]); SDL_FreeSurface(arrSrfBlock[7]); tetrissack.Free(); piece_lv0.Free(); piece_lv1.Free(); END; PROCEDURE TTetrisBoard.CheckBoard(); VAR i, j, k: integer; clear: boolean; linesclear: integer; BEGIN clear := FALSE; linesclear := 0; i := TETRIS_BOARD_HEIGHT; WHILE (i > 0) DO BEGIN clear := TRUE; FOR j := 1 TO TETRIS_BOARD_WIDTH DO BEGIN IF (_board[i][j] = TETRIS_PIECE_VOID) THEN BEGIN clear := FALSE; END; END; IF (clear) THEN BEGIN linesclear := linesclear + 1; FOR j := i DOWNTO 2 DO BEGIN FOR k := 1 TO TETRIS_BOARD_WIDTH DO BEGIN _board[j][k] := _board[j - 1][k]; END; END; i := i + 1; END; i := i - 1; END; IF (linesclear > 0) THEN BEGIN f_speed := f_speed + 0.6; END; playersts.i_lines := playersts.i_lines + linesclear; playersts.i_score := playersts.i_score + (linesclear * linesclear * 1000); END; PROCEDURE TTetrisBoard.Piece_DropDown(piece: TTauTetrisPiece; doscore: BOOLEAN); BEGIN WHILE (Piece_CanMove(piece, 0, 1)) DO BEGIN IF (doscore) THEN BEGIN playersts.i_score := playersts.i_score + 5; END; piece.MoveOffY(+1); END; END; PROCEDURE TTetrisBoard.CurPiece_DropDown(); BEGIN Piece_DropDown(piece_lv0, TRUE); ftimerstep := TETRIS_BOARD_TICKTIMER; { захтевај следећи корак } END; PROCEDURE TTetrisBoard.Piece_Rot(lv, d: integer); VAR temp: TTauTetrisPiece; sav: TTauTetrisPiece; BEGIN IF (lv = 1) THEN BEGIN piece_lv1.Rot(d); END ELSE BEGIN sav := piece_lv0; temp := TTauTetrisPiece.Create(piece_lv0.GetTip()); temp.SetOffX(sav.GetOffX()); temp.SetOffY(sav.GetOffY()); temp.SetRot(sav.GetRot()); temp.Rot(d); piece_lv0 := temp; IF (NOT Piece_CanMove(piece_lv0, 0, 0)) THEN BEGIN piece_lv0 := sav; temp.Free(); END ELSE BEGIN sav.Free(); END; END END; PROCEDURE TTetrisBoard.CurPiece_Rot(d: integer); VAR temp: TTauTetrisPiece; sav: TTauTetrisPiece; BEGIN sav := piece_lv0; temp := TTauTetrisPiece.Create(piece_lv0.GetTip()); temp.SetOffX(sav.GetOffX()); temp.SetOffY(sav.GetOffY()); temp.SetRot(sav.GetRot()); temp.Rot(d); piece_lv0 := temp; IF (NOT Piece_CanMove(piece_lv0, 0, 0)) THEN BEGIN piece_lv0 := sav; temp.Free(); end ELSE BEGIN sav.Free(); END; END; PROCEDURE TTetrisBoard.CurPiece_DownOne(); BEGIN playersts.i_score := playersts.i_score + 5; piece_lv0.MoveOffY(+1); END; PROCEDURE TTetrisBoard.SpeedUp(b: boolean); BEGIN spdup:= b; END; FUNCTION TTetrisBoard.Piece_CanMove(CONST piece: TTauTetrisPiece; offX, offY: integer): boolean; VAR b: boolean; i, j: integer; BEGIN { Све ради како треба, плиз не дирај. } b := TRUE; FOR j := 1 TO 4 DO BEGIN FOR i := 1 TO 4 DO BEGIN IF (piece.GetRep()[j][i] <> 0) THEN BEGIN IF ((piece.GetOffY() + j + offY) > (TETRIS_BOARD_HEIGHT-3)) THEN BEGIN b := FALSE; END ELSE IF ((piece.GetOffX() + i + offX) > TETRIS_BOARD_WIDTH) THEN BEGIN b := FALSE; END ELSE IF ((piece.GetOffX() + i + offX) < 1) THEN BEGIN b := FALSE; END ELSE IF (_board[piece.GetOffY() + j + offY][piece.GetOffX() + i + offX] <> TETRIS_PIECE_VOID) THEN BEGIN b := FALSE; END; END; END; END; Piece_CanMove := b; END; PROCEDURE TTetrisBoard.CurPiece_DoNew(); BEGIN IF (piece_lv1 = NIL) THEN BEGIN piece_lv1 := tetrissack.GetNext(); END; IF (piece_lv0 <> NIL) THEN BEGIN piece_lv0.Free(); END; piece_lv0 := piece_lv1; piece_lv1 := tetrissack.GetNext(); IF (piece_lv0 = NIL) THEN BEGIN WriteLn('piece_lv0 := tetrissack.GetNext(); -> NIL'); RAISE ExceptionClass.Create(); END; blockcounter[piece_lv1.GetTip()] := blockcounter[piece_lv1.GetTip()] + 1; piece_lv0.MoveOffX((TETRIS_BOARD_WIDTH DIV 2) - 1); if (Piece_CanMove(piece_lv0, 0, 0) <> TRUE) THEN BEGIN b_gameover := true; END; END; PROCEDURE TTetrisBoard.CurPiece_MoveX(a: integer); BEGIN IF (CurPiece_CanMoveX(a)) THEN BEGIN piece_lv0.MoveOffX(a); END; END; FUNCTION TTetrisBoard.CurPiece_CanMoveDown(): boolean; BEGIN CurPiece_CanMoveDown := Piece_CanMove(piece_lv0, 0, 1); END; FUNCTION TTetrisBoard.CurPiece_CanMoveX(a: integer): boolean; BEGIN CurPiece_CanMoveX := Piece_CanMove(piece_lv0, a, 0); END; PROCEDURE TTetrisBoard.Tick(); VAR ftimer: real; BEGIN ftimerstep := ftimerstep + 1.0; ghostblockTimer := ghostblockTimer + 1.0; ftimer := ftimerstep; IF (spdup) THEN BEGIN ftimer := ftimer * 8; END; IF (ghostblockTimer > TETRIS_BOARD_GHOSTTIMER) THEN BEGIN ghostblockTimer := 0.0; ghostblockState := ghostblockState + 1; IF (ghostblockState > 1) THEN BEGIN ghostblockState := 0; END; IF (ghostblockState = 0) THEN BEGIN srf_block_ghost := arrSrfBlockGhost0[piece_lv0.GetTip()]; srf_block_ghostReserve := arrSrfBlockGhost0[piece_lv1.GetTip()]; END ELSE BEGIN srf_block_ghost := arrSrfBlockGhost1[piece_lv0.GetTip()]; srf_block_ghostReserve := arrSrfBlockGhost1[piece_lv1.GetTip()]; END; END; IF ((ftimer + f_speed) > TETRIS_BOARD_TICKTIMER) THEN BEGIN ftimerstep := 0.0; IF (CurPiece_CanMoveDown()) THEN BEGIN CurPiece_DownOne(); END ELSE BEGIN Add(piece_lv0, _board, piece_lv0.GetTip()); { сачувај тетромин } CheckBoard(); CurPiece_DoNew(); END; END; END; PROCEDURE TTetrisBoard.Add(piece: TTauTetrisPiece; VAR bboard: arrboard; m: integer); VAR x: integer; y: integer; BEGIN FOR x := 1 TO 4 DO BEGIN FOR y := 1 TO 4 DO BEGIN IF (piece.GetRep()[y][x] <> 0) THEN BEGIN IF ((y + piece.GetOffY() <= 0)) THEN BEGIN CONTINUE; END; bboard[y + piece.GetOffY()][x + piece.GetOffX()] := m; END; END; END; END; PROCEDURE TTetrisBoard.Draw(pwin: PSDL_Surface); VAR d: TSDL_Rect; i, j: integer; tempBoard: arrboard; piecetemp: TTauTetrisPiece; BEGIN piecetemp := NIL; tempBoard := _board; d.x := 0; d.y := 0; d.w := 1; d.h := 1; piecetemp := TTauTetrisPiece.Create(piece_lv0.GetTip()); piecetemp.SetOffX(piece_lv0.GetOffX()); piecetemp.SetOffY(piece_lv0.GetOffY()); piecetemp.SetRot(piece_lv0.GetRot()); Piece_DropDown(piecetemp, FALSE); Add(piecetemp, tempBoard, TETRIS_BOARD_PIECE_MARKER_GHOST); Add(piece_lv0, tempBoard, piece_lv0.GetTip()); piecetemp.Free(); FOR j := 1 TO TETRIS_BOARD_WIDTH DO BEGIN FOR i := 1 TO TETRIS_BOARD_HEIGHT DO BEGIN IF (tempBoard[i][j] <> TETRIS_PIECE_VOID) THEN BEGIN d.x := (j - 1) * 32 + TETRIS_BOARD_RENDER_OFFSETX + 6; d.y := (i - 1) * 32; IF (tempBoard[i][j] = TETRIS_BOARD_PIECE_MARKER_GHOST) THEN BEGIN SDL_BlitSurface(srf_block_ghost, NIL, pwin, @d); END ELSE BEGIN SDL_BlitSurface(arrSrfBlock[tempBoard[i][j]], NIL, pwin, @d); END; END; END END; END; PROCEDURE TTetrisBoard.Reset(); BEGIN ghostblockState := 0; playersts.i_lines := 0; playersts.i_score := 0; piece_lv0 := NIL; tetrissack.Free(); tetrissack := TTauTetrisSack.Create(); b_gameover := FALSE; f_speed := 0; Nullify(); CurPiece_DoNew(); END; PROCEDURE TTetrisBoard.DrawReserve(pwin: PSDL_Surface); VAR d: TSDL_Rect; x, y: integer; BEGIN d.w := 1; d.h := 1; FOR x := 1 TO 4 DO BEGIN FOR y := 1 TO 4 DO BEGIN d.x := x*32 + (TETRIS_BOARD_RENDER_OFFSETX*7) DIV 3 + 32 + 16 - 8; d.y := y*32 + 256 - 96; IF (piece_lv1.GetRep()[y][x] <> 0) THEN BEGIN SDL_BlitSurface(arrSrfBlock[piece_lv1.GetTip()], NIL, pwin, @d); END ELSE BEGIN SDL_BlitSurface(srf_block_ghostReserve, NIL, pwin, @d); END; END; END; END; PROCEDURE TTetrisBoard.Nullify(); VAR i, j: integer; BEGIN FOR i := 1 TO 7 DO BEGIN blockcounter[i] := 0; END; FOR i := 1 TO TETRIS_BOARD_HEIGHT DO BEGIN FOR j := 1 TO TETRIS_BOARD_WIDTH DO BEGIN _board[i][j] := TETRIS_PIECE_VOID; END; END; END; FUNCTION TTetrisBoard.GetGameOver(): boolean; BEGIN GetGameOver := b_gameover; END; FUNCTION TTetrisBoard.GetPlayerstats(): playerstats; BEGIN GetPlayerstats := playersts; END; FUNCTION TTetrisBoard.GetPiece(lv: integer): TTauTetrisPiece; VAR t: TTauTetrisPiece; BEGIN t := piece_lv0; IF (lv = 1) THEN BEGIN t := piece_lv1; END; GetPiece := t; END; FUNCTION TTetrisBoard.GetBlockCounter(): arrCount; BEGIN GetBlockCounter := blockcounter; END; END.
unit SimpleMvvm.ViewModels.ShellViewModel; interface uses Forms, DSharp.PresentationModel.ViewModelBase, DSharp.PresentationModel.Composition, DSharp.PresentationModel.ViewLocator, DSharp.PresentationModel.ViewModelBinder, DSharp.ComponentModel.Composition, SysUtils, SimpleMvvm.Interfaces; type [PartCreationPolicy(cpShared)] TShellViewModel = class(TViewModelBase, IShellViewModel) private fTopText: string; fBottomText: string; fInjectedViewModel: IInjectedViewModel; procedure SetBottomText(const Value: string); procedure SetTopText(const Value: string); procedure SetInjectedViewModel(const Value: IInjectedViewModel); public constructor Create(); override; [Import] property InjectedViewModel: IInjectedViewModel read fInjectedViewModel write SetInjectedViewModel; property TopText: string read fTopText write SetTopText; property BottomText: string read fBottomText write SetBottomText; procedure ShowDialog(); end; implementation { TShellViewModel } constructor TShellViewModel.Create; begin inherited; BottomText := 'Initial Identical Text'; end; procedure TShellViewModel.SetBottomText(const Value: string); begin fBottomText := Value; fTopText := Value; DoPropertyChanged('TopText'); DoPropertyChanged('BottomText'); end; procedure TShellViewModel.SetInjectedViewModel(const Value: IInjectedViewModel); begin fInjectedViewModel := Value; DoPropertyChanged('InjectedViewModel'); end; procedure TShellViewModel.SetTopText(const Value: string); begin fBottomText := Value; fTopText := Value; DoPropertyChanged('TopText'); DoPropertyChanged('BottomText'); end; procedure TShellViewModel.ShowDialog; var lCopy: IShellViewModel; lViewModel: ISampleDialogViewModel; lView: TForm; begin // //JUST TRYING TO SHOW A COPY OF THE CURRENT VIEWMODEL. // //NOT WORRIED ABOUT PROBLEMS WITH THIS. THIS SEEMS TO WORK FINE THOUGH. // //PartCreationPolicy is set to cpNonShared lCopy := Composition.Get<IShellViewModel>(); WindowManager.ShowDialog(lCopy); lViewModel := Composition.Get<ISampleDialogViewModel>(); // PROBLEM: // I'VE TRIED BINDING AS FOLLOWS, BUT STILL CAN'T GET THE BINDING PROPERTIES // TO WORK AS IN SHELL VIEW/VIEWMODEL // SOLUTION: // I DIDN'T ADD THE USES STATEMENT: // DSharp.Bindings.VCLControls // This isn't necessary, and creates a superfluous view // I thought of trying this to prepare bindings. // lView := ViewLocator.GetOrCreateViewType(TObject(lViewModel).ClassType) as TForm; // ViewModelBinder.Bind(TObject(lViewModel), lView); // FreeAndNil(lView); WindowManager.ShowDialog(lViewModel); end; initialization TShellViewModel.ClassName; end.
unit uFrmInventoryCount; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, PAIDETODOS, Grids, DBGrids, DBCtrls, StdCtrls, Mask, LblEffct, ExtCtrls, DBTables, DB, Variants, uFrmBarcodeSearch, DateBox, Buttons, ADODB, SuperComboADO, siComp, siLangRT, ComCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, DBClient, Provider, cxLookAndFeelPainters, Menus, cxButtons, dxPSGlbl, dxPSUtl, dxPSEngn, dxPrnPg, dxBkgnd, dxWrap, dxPrnDev, dxPSCompsProvider, dxPSFillPatterns, dxPSEdgePatterns, dxPSCore, dxPScxGridLnk, mrBarCodeEdit, uCharFunctions; const COUNTTYPE_INDEX_SELECTION = 0; COUNTTYPE_INDEX_MANUAL = 1; COUNTTYPE_INDEX_IMPORTFILE = 2; COUNTTYPE_INDEX_HANDHELD = 3; type TInventory = class fIDBarcode : String; fModel : String; fDate : String; fTime : String; fQty : Double; end; TFrmInventoryCount = class(TFrmParent) dsModel: TDataSource; spAdjust: TADOStoredProc; spAdjustName: TStringField; spAdjustStoreID: TIntegerField; btAdjust: TButton; quModel: TADOQuery; quModelDataContagem: TDateTimeField; quModelCategory: TStringField; spHelp: TSpeedButton; pcBarcode: TPageControl; tsManual: TTabSheet; tsImport: TTabSheet; Panel4: TPanel; spOpen: TSpeedButton; edSeparator: TEdit; mFields: TMemo; lbTextField: TLabel; lbSeparetor: TLabel; Abrir: TOpenDialog; quBarcodeList: TADODataSet; cdsBarcodeList: TClientDataSet; quBarcodeListIDBarcode: TStringField; quBarcodeListCountDate: TDateTimeField; dsBarcodeList: TDataSource; dspBarcodeList: TDataSetProvider; cdsBarcodeListIDBarcode: TStringField; cdsBarcodeListCountDate: TDateTimeField; quFindBarcode: TADOQuery; quFindBarcodeIDBarcode: TStringField; quFindBarcodeStoreID: TIntegerField; btAdd: TBitBtn; cbFields: TComboBox; lbFields: TLabel; quBarcodeListIDModel: TIntegerField; cdsBarcodeListIDModel: TIntegerField; quFindBarcodeIDModel: TIntegerField; pgBarcodeOption: TPageControl; tsBarcode: TTabSheet; rgTypeImport: TRadioGroup; gridBarcodes: TcxGrid; gridBarcodesDB: TcxGridDBTableView; gridBarcodesDBIDBarcode: TcxGridDBColumn; gridBarcodesDBCounted: TcxGridDBColumn; gridBarcodesDBQtyOnHand: TcxGridDBColumn; gridBarcodesDBDiffer: TcxGridDBColumn; gridBarcodesDBCountDate: TcxGridDBColumn; gridBarcodesLevel1: TcxGridLevel; tsNotFound: TTabSheet; Memo1: TMemo; cbFilter: TComboBox; quBarcodeListQtyOnHand: TFloatField; cdsBarcodeListQtyOnHand: TFloatField; quFindBarcodeQtyOnHand: TFloatField; quModelQtyOnPreSale: TFloatField; quModelQtyOnHand: TFloatField; quModelQtyOnOrder: TFloatField; quModelQtyOnRepair: TFloatField; quBarcodeListCounted: TBCDField; quBarcodeListDiffer: TBCDField; cdsBarcodeListCounted: TBCDField; cdsBarcodeListDiffer: TBCDField; tsSelection: TTabSheet; tsHandHeld: TTabSheet; rgdCountType: TRadioGroup; btnNext: TButton; pnlPO: TPanel; pnlPODetail: TPanel; lbCountUser: TLabel; lbCountInfo: TLabel; lbCountDate: TLabel; lbCountStore: TLabel; DBEdit7: TDBEdit; DBEdit10: TDBEdit; DBEdit11: TDBEdit; pnlPOToolBar: TPanel; btNewInvCount: TcxButton; btCloseInvCount: TcxButton; btDeleteInvCount: TcxButton; grdInvCount: TcxGrid; grdInvCountDB: TcxGridDBTableView; grdInvCountLevel: TcxGridLevel; pnlEspaco: TPanel; pnlPOItem: TPanel; Panel5: TPanel; btInvCountItemRemove: TSpeedButton; btInvCountItemPreview: TSpeedButton; btCustomizeColumns: TSpeedButton; btGroupItem: TSpeedButton; grdInvCountItem: TcxGrid; grdInvCountItemDB: TcxGridDBTableView; grdInvCountItemLevel: TcxGridLevel; lbCountDetail: TLabel; btnExport: TSpeedButton; popCountOption: TPopupMenu; menCyclecount: TMenuItem; menPhysicalcount: TMenuItem; menLiveCount: TMenuItem; menStartupStore: TMenuItem; dsInvCount: TDataSource; dsInvCountItem: TDataSource; quInvCount: TADODataSet; quInvCountItem: TADODataSet; quInvCountIDCount: TIntegerField; quInvCountSystemUser: TStringField; quInvCountStore: TStringField; quInvCountStartDate: TDateTimeField; quInvCountCountType: TIntegerField; quInvCountCountTypeName: TStringField; grdInvCountDBCountTypeName: TcxGridDBColumn; quInvCountItemIDCountItem: TIntegerField; quInvCountItemBarcode: TStringField; quInvCountItemSalePrice: TBCDField; quInvCountItemCountDate: TDateTimeField; quInvCountItemModel: TStringField; quInvCountItemDescription: TStringField; quInvCountItemQtyFrozen: TFloatField; grdInvCountItemDBBarcode: TcxGridDBColumn; grdInvCountItemDBQty: TcxGridDBColumn; grdInvCountItemDBSalePrice: TcxGridDBColumn; grdInvCountItemDBCountDate: TcxGridDBColumn; grdInvCountItemDBModel: TcxGridDBColumn; grdInvCountItemDBDescription: TcxGridDBColumn; grdInvCountItemDBQtyFrozen: TcxGridDBColumn; quInsInvCount: TADOCommand; quInsFrozeCount: TADOCommand; btnRefreshItem: TSpeedButton; quInvCountItemDifference: TFloatField; grdInvCountItemDBDifference: TcxGridDBColumn; gridPrinter: TdxComponentPrinter; gridPrinterLink: TdxGridReportLink; quInvCountIDStore: TIntegerField; quInvCountIDUser: TIntegerField; Panel6: TPanel; btnPreviewBarcodeFile: TSpeedButton; btExportBarcodeFile: TSpeedButton; gridPrinterLinkBarcodeFile: TdxGridReportLink; quInvCountItemQty: TFloatField; quBarcodeListModel: TStringField; cdsBarcodeListModel: TStringField; gridBarcodesDBModel: TcxGridDBColumn; quModelSellingPrice: TBCDField; tcManualCount: TTabControl; Label1: TLabel; edtBarcode: TmrBarCodeEdit; btnSearchDesc: TBitBtn; Panel14: TPanel; lbLastItem: TLabel; lbSalePrice: TLabel; lbPriceResult: TLabel; lbHand: TLabel; lbCountScan: TLabel; lbOnHand: TLabel; lbScanned: TLabel; lbBarcode: TLabel; btPrint: TSpeedButton; pnlLastScan: TPanel; pnlModel: TPanel; Label10: TLabel; Label11: TLabel; Label14: TLabel; Label3: TLabel; Label9: TLabel; Label6: TLabel; scModel: TSuperComboADO; DBEdit1: TDBEdit; scStore: TSuperComboADO; editDate: TDateBox; GroupBox1: TGroupBox; Label4: TLabel; Label5: TLabel; Label7: TLabel; Label8: TLabel; DBEdit3: TDBEdit; DBEdit4: TDBEdit; DBEdit5: TDBEdit; DBEdit6: TDBEdit; editQty: TEdit; rgType: TRadioGroup; lbNewHand: TLabel; lbNewOnHand: TLabel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure btAdjustClick(Sender: TObject); procedure RefreshCombo(Sender: TObject); procedure Init; procedure spHelpClick(Sender: TObject); procedure btnSearchDescClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormDestroy(Sender: TObject); procedure spOpenClick(Sender: TObject); procedure btAddClick(Sender: TObject); procedure cbFilterChange(Sender: TObject); procedure pcBarcodeChange(Sender: TObject); procedure btnNextClick(Sender: TObject); procedure tsManualShow(Sender: TObject); procedure quInvCountCalcFields(DataSet: TDataSet); procedure tsHandHeldShow(Sender: TObject); procedure quInvCountAfterOpen(DataSet: TDataSet); procedure OnInvCountClick(Sender: TObject); procedure btDeleteInvCountClick(Sender: TObject); procedure btInvCountItemRemoveClick(Sender: TObject); procedure quInvCountItemAfterOpen(DataSet: TDataSet); procedure btnRefreshItemClick(Sender: TObject); procedure quInvCountItemCalcFields(DataSet: TDataSet); procedure btnExportClick(Sender: TObject); procedure btGroupItemClick(Sender: TObject); procedure btCustomizeColumnsClick(Sender: TObject); procedure btInvCountItemPreviewClick(Sender: TObject); procedure btCloseInvCountClick(Sender: TObject); procedure quInvCountAfterScroll(DataSet: TDataSet); procedure btnPreviewBarcodeFileClick(Sender: TObject); procedure btExportBarcodeFileClick(Sender: TObject); procedure edtBarcodeAfterSearchBarcode(Sender: TObject); procedure editQtyKeyPress(Sender: TObject; var Key: Char); procedure btPrintClick(Sender: TObject); procedure tcManualCountChange(Sender: TObject); private sCycleCount, sPhysCount, sLiveCount, sStartCount, sBarcode, sModel, sDate, sTime, sQty : String; fFrmBarcodeSearch : TFrmBarcodeSearch; FItemsBarcode : TStringList; Import : Boolean; AView : TcxCustomGridTableView; FScanned : Double; function ValidateFields:Boolean; procedure Clear; procedure AddItemBarcode(Barcode, CodeDate, CodeTime, Model: String; Qty: Double); function FindBarcode(Barcode, Model: String):Boolean; procedure ViewItemsBarcode; procedure SetInicialTab; procedure SetActiveTab(Tab : TTabSheet); procedure Save; procedure OpenInvCount; procedure CloseInvCount; procedure RefreshInvCount; procedure OpenInvCountItem; procedure CloseInvCountItem; procedure RefreshInvCountItem; function ValidateInvCount(iCountType: Integer): Boolean; procedure NewInvCount(iCountType: Integer); procedure DeleteInvCount; procedure DeleteInvCountItem; procedure AdjustInventory(AIDModel, ACountType: Integer; ACountedQty: Double; AAdjustDate: TDateTime); public IsDetail : Boolean; function Start:Boolean; end; var Import : Boolean; iOnHand : Double; iModel : Integer; implementation uses uDM, uMsgBox, uMsgConstant, uNumericFunctions, uDMGlobal, uSystemConst, uFrmExport, uDMCloseCount, uCDSFunctions, uFrmBarcodePrint; {$R *.DFM} function TFrmInventoryCount.ValidateFields:Boolean; begin Result := True; if scStore.Text = '' then begin MsgBox(MSG_CRT_NO_STORE_SELECTED, vbOkOnly + vbCritical); scStore.SetFocus; Result := False; Exit; end; if EditQty.Text = '' then begin MsgBox(MSG_CRT_NO_REAL_QTY, vbOkOnly + vbCritical); EditQty.SetFocus; Result := False; Exit; end; If (MyStrToFloat(EditQty.Text) = 0) and (rgType.ItemIndex = 0) then begin MsgBox(MSG_CRT_QTY_NO_ZERO, vbOkOnly + vbCritical); EditQty.SetFocus; Result := False; Exit; end; end; procedure TFrmInventoryCount.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; quModel.Close; Action := caFree; Clear; end; procedure TFrmInventoryCount.FormShow(Sender: TObject); begin inherited; rgType.ItemIndex := 0; editDate.Date := now; scStore.LookUpValue := IntToStr(DM.fStore.ID); end; procedure TFrmInventoryCount.RefreshCombo(Sender: TObject); begin lbLastItem.Caption := ''; lbBarcode.Caption := ''; lbPriceResult.Caption := FormatCurr('#,##0.00', 0); lbOnHand.Caption := FormatCurr('0.##', 0); lbScanned.Caption := FormatCurr('0.##', 0); lbNewOnHand.Caption := FormatCurr('0.##', 0); if (scModel.LookUpValue <> '') and (scStore.LookUpValue <> '') then begin if not(DM.ModelRestored(StrToInt(scModel.LookUpValue))) then begin edtBarcode.Text := ''; scModel.LookUpValue:= ''; exit; end; with quModel do begin if Active then Close; Parameters.ParambyName('IDModel').Value := StrToInt(scModel.LookUpValue); Parameters.ParambyName('IDStore').Value := StrToInt(scStore.LookUpValue); Open; lbPriceResult.Caption := FormatCurr('#,##0.00', quModelSellingPrice.AsCurrency); lbOnHand.Caption := FormatCurr('0.##', quModelQtyOnHand.AsFloat); if rgType.ItemIndex = 0 then lbNewOnHand.Caption := FormatCurr('0.##', quModelQtyOnHand.AsFloat + FScanned) else lbNewOnHand.Caption := FormatCurr('0.##', FScanned); end; btAdjust.Enabled := True; editQty.SetFocus; end; end; procedure TFrmInventoryCount.btCloseClick(Sender: TObject); begin inherited; Close; end; procedure TFrmInventoryCount.btAdjustClick(Sender: TObject); begin Save; end; procedure TFrmInventoryCount.Init; begin with quModel do begin if Active then Close; Parameters.ParambyName('IDModel').Value := Null; Open; end; scModel.LookUpValue := ''; scModel.SelectAll; edtBarcode.Clear; if edtBarcode.CanFocus then edtBarcode.SetFocus; editQty.Text := ''; btAdjust.Enabled := False; end; procedure TFrmInventoryCount.spHelpClick(Sender: TObject); begin inherited; Application.HelpContext(1840); end; procedure TFrmInventoryCount.btnSearchDescClick(Sender: TObject); var R: integer; begin inherited; with fFrmBarcodeSearch do begin R := Start; if R <> -1 then begin scModel.LookUpValue := IntToStr(R); RefreshCombo(Self); end; end; end; procedure TFrmInventoryCount.FormCreate(Sender: TObject); begin inherited; pcBarcode.ActivePageIndex := COUNTTYPE_INDEX_SELECTION; DM.imgSmall.GetBitmap(BTN18_SEARCH, btnSearchDesc.Glyph); DM.imgBTN.GetBitmap(BTN_PREVIEW, btPrint.Glyph); fFrmBarcodeSearch := TFrmBarcodeSearch.Create(Self); edtBarcode.CheckBarcodeDigit := DM.fSystem.SrvParam[PARAM_REMOVE_BARCODE_DIGIT]; edtBarcode.MinimalDigits := DM.fSystem.SrvParam[PARAM_MIN_BARCODE_LENGTH]; edtBarcode.RunSecondSQL := DM.fSystem.SrvParam[PARAM_SEARCH_MODEL_AFTER_BARCODE]; Case DMGlobal.IDLanguage of LANG_ENGLISH : begin sCycleCount := 'Cycle Count'; sPhysCount := 'Physical Count'; sLiveCount := 'Live Count'; sStartCount := 'Start up Count'; sBarcode := 'Barcode'; sModel := 'Model'; sDate := 'Date'; sTime := 'Time'; sQty := 'Qty'; end; LANG_PORTUGUESE : begin sCycleCount := 'Contagem Ciclo'; sPhysCount := 'Contagem Física'; sLiveCount := 'Contagem Tempo Real'; sStartCount := 'Contagem Inicial'; sBarcode := 'Cód. de barras'; sModel := 'Modelo'; sDate := 'Data'; sTime := 'Hora'; sQty := 'Qtde'; end; LANG_SPANISH : begin sCycleCount := 'Contagem Ciclo'; sPhysCount := 'Contagem Física'; sLiveCount := 'Contagem Tempo Real'; sStartCount := 'Contagem Inicial'; sBarcode := 'Cod. de barras'; sModel := 'Modelo'; sDate := 'Fecha'; sTime := 'Hora'; sQty := 'Cntd'; end; end; DM.imgSmall.GetBitmap(BTN18_DELETE, btInvCountItemRemove.Glyph); DM.imgSmall.GetBitmap(BTN18_PREVIEW, btInvCountItemPreview.Glyph); DM.imgSmall.GetBitmap(BTN18_PREVIEW, btnPreviewBarcodeFile.Glyph); DM.imgBTN.GetBitmap(BTN_GROUPING, btGroupItem.Glyph); DM.imgBTN.GetBitmap(BTN_COLUMN, btCustomizeColumns.Glyph); DM.imgBTN.GetBitmap(BTN_EXPORT, btnExport.Glyph); DM.imgBTN.GetBitmap(BTN_EXPORT, btExportBarcodeFile.Glyph); DM.imgBTN.GetBitmap(BTN_REFRESH, btnRefreshItem.Glyph); AView := TcxCustomGridTableView(grdInvCountItem.FocusedView); end; procedure TFrmInventoryCount.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; case Key of VK_F2 : begin //Procurar por descricao btnSearchDesc.Click; end; end; end; procedure TFrmInventoryCount.FormDestroy(Sender: TObject); begin inherited; FreeAndNil(fFrmBarcodeSearch); FreeAndNil(FItemsBarcode); end; procedure TFrmInventoryCount.spOpenClick(Sender: TObject); var line, symbol: string; i,x,z,j: integer; Cod : Array[1..5] of String; ResultLine : Array[1..5] of String; FFile : TStringList; bHasModel : Boolean; procedure ClearVar; var i:integer; begin x := 1; z := 1; for i := 0 to 5 do Cod[i] := ''; for i := 0 to 5 do ResultLine[i] := ''; end; begin if not Assigned(FItemsBarcode) then FItemsBarcode := TStringList.Create; Clear; ClearVar; line := ''; bHasModel := False; FFile := TStringList.Create; if mFields.Lines.Count = 0 then begin MsgBox(MSG_INF_SELECT_FIELD, vbOkOnly + vbCritical); exit; end; if edSeparator.Text = '' then symbol := #9 else symbol := edSeparator.Text[1]; if mFields.Lines.Count > 0 then begin if Abrir.Execute then FFile.LoadFromFile(Abrir.FileName); Screen.Cursor := crHourGlass; for i := 0 to FFile.Count -1 do begin line := Trim(FFile.Strings[i]); while x <= length(line) do begin if line[x] = symbol then begin inc(z); inc(x); end else begin Cod[z] := Cod[z] + line[x]; inc(x); end end; for j := 0 to mFields.Lines.Count-1 do begin if mFields.Lines[j] = sBarcode then ResultLine[1] := Cod[j+1] else if mFields.Lines[j] = sDate then ResultLine[2] := Cod[j+1] else if mFields.Lines[j] = sTime then ResultLine[3] := Cod[j+1] else if mFields.Lines[j] = sQty then ResultLine[4] := Cod[j+1] else if mFields.Lines[j] = sModel then begin ResultLine[5] := Cod[j+1]; bHasModel := True; end; end; AddItemBarcode(ResultLine[1], ResultLine[2], ResultLine[3], ResultLine[5], StrToFloatDef(ResultLine[4], 1)); ClearVar; end; Screen.Cursor := crDefault; FreeAndNil(FFile); end; if bHasModel then gridBarcodesDB.DataController.KeyFieldNames := 'Model' else gridBarcodesDB.DataController.KeyFieldNames := 'IDBarcode'; ViewItemsBarcode; btAdjust.Enabled := True; end; procedure TFrmInventoryCount.AddItemBarcode(Barcode, CodeDate, CodeTime, Model: String; Qty: Double); var ItemInvent : TInventory; ResultIndex : Integer; Friend : Boolean; begin if Model = '' then ResultIndex := FItemsBarcode.IndexOf(Barcode) else ResultIndex := FItemsBarcode.IndexOf(Model); friend := ResultIndex = -1; if friend then begin ItemInvent := TInventory.Create; if CodeDate = '' then CodeDate := DatetoStr(Date); if CodeTime = '' then CodeTime := TimetoStr(Time); with ItemInvent do begin fIDBarcode := Barcode; FModel := Model; fDate := CodeDate; fTime := CodeTime; fQty := Qty; end; if Model = '' then FItemsBarcode.AddObject(Barcode, ItemInvent) else FItemsBarcode.AddObject(Model, ItemInvent); end else begin TInventory(FItemsBarcode.Objects[ResultIndex]).fQty := TInventory(FItemsBarcode.Objects[ResultIndex]).fQty + Qty; end; end; procedure TFrmInventoryCount.Clear; var i: integer; ItemInvent : TInventory; begin if not(FItemsBarcode = Nil) then begin for i:=0 to FItemsBarcode.Count-1 do begin ItemInvent := TInventory(FItemsBarcode.Objects[i]); FreeAndNil(ItemInvent); end; FItemsBarcode.Clear; end; Memo1.Lines.Clear; if cdsBarcodeList.Active then cdsBarcodeList.Close; end; procedure TFrmInventoryCount.btAddClick(Sender: TObject); var sTemp : String; begin if cbFields.ItemIndex > -1 then if mFields.Lines.Count < 4 then begin sTemp := cbFields.Text; mFields.Lines.Add(cbFields.Text); cbFields.Items.Delete(cbFields.ItemIndex); if sTemp = sModel then cbFields.Items.Delete(cbFields.Items.IndexOf(sBarcode)) else if sTemp = sBarcode then cbFields.Items.Delete(cbFields.Items.IndexOf(sModel)); end else MsgBox(MSG_CRT_EXCEEDED_ITEMS, vbOkOnly + vbCritical) else if mFields.Lines.Count < 4 then MsgBox(MSG_CRT_NO_VALID_ITEM, vbOkOnly + vbCritical) else MsgBox(MSG_CRT_EXCEEDED_ITEMS, vbOkOnly + vbCritical); end; function TFrmInventoryCount.FindBarcode(Barcode, Model: String): Boolean; var friend : boolean; sIDStore : String; begin with quFindBarcode do try if Active then Close; if (scStore.LookUpValue = '') then sIDStore := '0' else sIDStore := scStore.LookUpValue; if Trim(Model) = '' then begin quFindBarcode.SQL.Clear; quFindBarcode.SQL.Add('SELECT INV.QtyOnHand, Barcode.IDBarcode, StoreID, Barcode.IDModel'); quFindBarcode.SQL.Add('FROM Barcode (NOLOCK) LEFT OUTER JOIN Inventory INV (NOLOCK) ON (INV.ModelID = Barcode.IDModel AND StoreID = ' + sIDStore + ')'); quFindBarcode.SQL.Add('WHERE IDBarcode = '+ QuotedStr(Barcode)); end else begin quFindBarcode.SQL.Clear; quFindBarcode.SQL.Add('SELECT INV.QtyOnHand, CAST('+QuotedStr('')+' as varchar(20)) as IDBarcode, INV.StoreID, M.IDModel'); quFindBarcode.SQL.Add('FROM Model M (NOLOCK) LEFT OUTER JOIN Inventory INV (NOLOCK) ON (INV.ModelID = M.IDModel AND StoreID = ' + sIDStore + ')'); quFindBarcode.SQL.Add('WHERE M.Model = ' + QuotedStr(Model)); end; Open; iOnHand := quFindBarcodeQtyOnHand.AsFloat; iModel := quFindBarcodeIDModel.AsInteger; if quFindBarcode.RecordCount = 0 then friend := False else friend := True; finally Close; end; Result := friend; end; procedure TFrmInventoryCount.ViewItemsBarcode; var i: Integer; QtyBarcode: Double; NumBarcode: String; ModelNum : String; DateBarcode: TDateTime; begin for i:=0 to FItemsBarcode.Count-1 do begin NumBarCode := TInventory(FItemsBarcode.Objects[i]).fIDBarcode; ModelNum := TInventory(FItemsBarcode.Objects[i]).fModel; QtyBarCode := TInventory(FItemsBarcode.Objects[i]).fQty; DateBarcode := StrToDateTime(TInventory(FItemsBarcode.Objects[i]).fDate +' '+ TInventory(FItemsBarcode.Objects[i]).fTime); cdsBarcodeList.Open; if FindBarcode(NumBarCode, ModelNum) then begin with cdsBarcodeList do begin Append; cdsBarcodeListQtyOnHand.AsFloat := iOnHand; cdsBarcodeListIDBarcode.AsString := NumBarCode; cdsBarcodeListCounted.AsFloat := QtyBarCode; cdsBarcodeListDiffer.AsFloat := (Abs(iOnHand) - QtyBarCode); cdsBarcodeListCountDate.AsDateTime := DateBarcode; cdsBarcodeListIDModel.AsInteger := iModel; cdsBarcodeListModel.AsString := ModelNum; Post; end; end else Memo1.Lines.Add(NumBarCode + ' ' + ModelNum); end; end; procedure TFrmInventoryCount.cbFilterChange(Sender: TObject); begin cdsBarcodeList.Filtered := True; case cbFilter.ItemIndex of 0 : begin cdsBarcodeList.Filtered := False; cdsBarcodeList.Filter := ''; end; 1 : cdsBarcodeList.Filter := 'Counted > 0'; 2 : cdsBarcodeList.Filter := 'Counted < 0'; 3 : cdsBarcodeList.Filter := 'Counted = 0'; 4 : cdsBarcodeList.Filter := 'QtyOnHand > 0'; 5 : cdsBarcodeList.Filter := 'QtyOnHand < 0'; 6 : cdsBarcodeList.Filter := 'QtyOnHand = 0'; 7 : cdsBarcodeList.Filter := 'Differ > 0'; 8 : cdsBarcodeList.Filter := 'Differ < 0'; 9 : cdsBarcodeList.Filter := 'Differ <> 0'; end; end; procedure TFrmInventoryCount.pcBarcodeChange(Sender: TObject); begin if pcBarcode.TabIndex = COUNTTYPE_INDEX_IMPORTFILE then cbFields.SetFocus; end; function TFrmInventoryCount.Start: Boolean; var AOptions : TcxGridStorageOptions; ASaveViewName : String; fRegistryPath : String; begin fRegistryPath := MR_BRW_REG_PATH + Self.Caption; AOptions := [gsoUseFilter, gsoUseSummary]; DM.LoadGridFromRegistry(TcxGridDBTableView(AView), fRegistryPath, AOptions); SetInicialTab; ShowModal; DM.SaveGridToRegistry(TcxGridDBTableView(AView), fRegistryPath, True, AOptions); end; procedure TFrmInventoryCount.SetInicialTab; begin tsSelection.TabVisible := True; tsManual.TabVisible := False; tsImport.TabVisible := False; tsHandHeld.TabVisible := False; end; procedure TFrmInventoryCount.SetActiveTab(Tab : TTabSheet); begin tsSelection.TabVisible := False; Tab.TabVisible := True; btnNext.Visible := False; btAdjust.Visible := True; if Tab = tsHandHeld then btAdjust.Enabled := False; end; procedure TFrmInventoryCount.Save; var i, iIDModel: Integer; dQtyCounted, dQtyOnHand: Double; begin if pcBarcode.ActivePageIndex = COUNTTYPE_INDEX_IMPORTFILE then begin SetCDSIndex(cdsBarcodeList, 'IDMODEL_INDEX', ['IDModel'], []); try cdsBarcodeList.First; iIDModel := cdsBarcodeListIDModel.AsInteger; dQtyCounted := 0; while not cdsBarcodeList.Eof do begin if iIDModel <> cdsBarcodeListIDModel.AsInteger then begin AdjustInventory(iIDModel, rgTypeImport.ItemIndex+1, dQtyCounted, cdsBarcodeListCountDate.AsDateTime); dQtyCounted := cdsBarcodeListCounted.AsFloat; end else dQtyCounted := dQtyCounted + cdsBarcodeListCounted.AsFloat; iIDModel := cdsBarcodeListIDModel.AsInteger; dQtyOnHand := cdsBarcodeListQtyOnHand.AsFloat; cdsBarcodeList.Next; end; AdjustInventory(iIDModel, rgTypeImport.ItemIndex+1, dQtyCounted, cdsBarcodeListCountDate.AsDateTime); btAdjust.Enabled := False; Clear; finally cdsBarcodeList.IndexName := ''; end; end else if pcBarcode.ActivePageIndex = COUNTTYPE_INDEX_MANUAL then begin if not ValidateFields then Exit; AdjustInventory(StrToInt(scModel.LookUpValue), rgType.ItemIndex+1, MyStrToFloat(editQty.Text), editDate.Date); Init; end; end; procedure TFrmInventoryCount.btnNextClick(Sender: TObject); var Tab: TTabSheet; begin inherited; case rgdCountType.ItemIndex of 0: begin Tab := tsManual; Init; tcManualCount.TabIndex := 1; tcManualCountChange(Self); end; 1:Tab := tsImport; 2:Tab := tsHandHeld; end; SetActiveTab(Tab); end; procedure TFrmInventoryCount.tsManualShow(Sender: TObject); begin inherited; edtBarcode.SetFocus; end; procedure TFrmInventoryCount.quInvCountCalcFields(DataSet: TDataSet); begin inherited; case quInvCountCountType.AsInteger of INV_COUNT_CYCLE : quInvCountCountTypeName.AsString := sCycleCount; INV_COUNT_PHYSICAL: quInvCountCountTypeName.AsString := sPhysCount; INV_COUNT_LIVE : quInvCountCountTypeName.AsString := sLiveCount; INV_COUNT_STARTUP : quInvCountCountTypeName.AsString := sStartCount; end; end; procedure TFrmInventoryCount.CloseInvCount; begin with quInvCount do if Active then Close; end; procedure TFrmInventoryCount.OpenInvCount; begin with quInvCount do if not Active then Open; end; procedure TFrmInventoryCount.RefreshInvCount; begin CloseInvCount; OpenInvCount; end; procedure TFrmInventoryCount.tsHandHeldShow(Sender: TObject); begin inherited; RefreshInvCount; end; procedure TFrmInventoryCount.CloseInvCountItem; begin with quInvCountItem do if Active then Close; end; procedure TFrmInventoryCount.OpenInvCountItem; begin with quInvCountItem do if not Active then begin Parameters.ParamByName('IDCount').Value := quInvCountIDCount.AsInteger; Open; end; end; procedure TFrmInventoryCount.RefreshInvCountItem; begin CloseInvCountItem; OpenInvCountItem; end; procedure TFrmInventoryCount.quInvCountAfterOpen(DataSet: TDataSet); begin inherited; RefreshInvCountItem; btDeleteInvCount.Enabled := quInvCount.RecordCount > 0; btCloseInvCount.Enabled := btDeleteInvCount.Enabled; end; procedure TFrmInventoryCount.DeleteInvCount; var sSQL: String; bError : Boolean; begin try DM.ADODBConnect.BeginTrans; sSQL := 'delete Inv_CountItem where IDCount = ' + quInvCountIDCount.AsString; bError := not DM.RunSQL(sSQL); sSQL := 'delete Inv_FrozeCount where IDCount = ' + quInvCountIDCount.AsString; if not bError then bError := not DM.RunSQL(sSQL); sSQL := 'delete Inv_Count where IDCount = ' + quInvCountIDCount.AsString; if not bError then bError := not DM.RunSQL(sSQL); finally if bError then begin DM.ADODBConnect.RollbackTrans; MsgBox(MSG_CRT_ERROR_OCURRED, vbCritical + vbOkOnly); end else DM.ADODBConnect.CommitTrans; end; end; procedure TFrmInventoryCount.DeleteInvCountItem; var sSQL: String; begin sSQL := 'delete Inv_CountItem where IDCountItem = ' + quInvCountItemIDCountItem.AsString; if not DM.RunSQL(sSQL) then MsgBox(MSG_CRT_NOT_DEL_PURCHASE, vbCritical + vbOkOnly); end; procedure TFrmInventoryCount.NewInvCount(iCountType: Integer); var iIDInvCount: Integer; sSQLFroze: String; begin iIDInvCount := DM.GetNextID('Inv_Count.IDCount'); try Screen.Cursor := crHourGlass; try DM.ADODBConnect.BeginTrans; with quInsInvCount do begin Parameters.ParamByName('IDCount').Value := iIDInvCount; Parameters.ParamByName('StartDate').Value := Now; Parameters.ParamByName('CountType').Value := iCountType; Parameters.ParamByName('IDUser').Value := DM.fUser.ID; Parameters.ParamByName('IDStore').Value := DM.fStore.ID; Execute; end; if iCountType <> INV_COUNT_LIVE then with quInsFrozeCount do begin Parameters.ParamByName('IDCount').Value := iIDInvCount; Parameters.ParamByName('IDStore').Value := DM.fStore.ID; Execute; end; DM.ADODBConnect.CommitTrans; except on E: Exception do begin DM.ADODBConnect.RollbackTrans; //MsgBox(MSG_INF_ERROR + '_' + E.Message, vbCritical + vbOkOnly); MsgBox(MSG_INF_ERROR, vbCritical + vbOkOnly); end; end; finally Screen.Cursor := crDefault; end; end; procedure TFrmInventoryCount.OnInvCountClick(Sender: TObject); begin inherited; if ValidateInvCount(TMenuItem(Sender).Tag) then begin NewInvCount(TMenuItem(Sender).Tag); RefreshInvCount; end else MsgBox(MSG_INF_ERROR, vbInformation + vbOkOnly); end; function TFrmInventoryCount.ValidateInvCount(iCountType: Integer): Boolean; begin if quInvCount.Active then Result := not quInvCount.Locate('CountType', iCountType, []); end; procedure TFrmInventoryCount.btDeleteInvCountClick(Sender: TObject); begin inherited; if (quInvCount.RecordCount > 0) and (MsgBox(MSG_QST_DELETE, vbQuestion + vbYesNo) = vbYes) then begin DeleteInvCount; RefreshInvCount; end; end; procedure TFrmInventoryCount.btInvCountItemRemoveClick(Sender: TObject); begin inherited; if quInvCountItem.RecordCount > 0 then begin DeleteInvCountItem; RefreshInvCountItem; end; end; procedure TFrmInventoryCount.quInvCountItemAfterOpen(DataSet: TDataSet); begin inherited; btnRefreshItem.Enabled := (quInvCount.RecordCount > 0); btInvCountItemRemove.Enabled := (quInvCountItem.RecordCount > 0) and (quInvCountCountType.AsInteger <> INV_COUNT_LIVE); btInvCountItemPreview.Enabled := (quInvCount.RecordCount > 0); btnExport.Enabled := (quInvCount.RecordCount > 0); end; procedure TFrmInventoryCount.btnRefreshItemClick(Sender: TObject); begin inherited; RefreshInvCountItem; end; procedure TFrmInventoryCount.quInvCountItemCalcFields(DataSet: TDataSet); begin inherited; quInvCountItemDifference.AsFloat := quInvCountItemQty.AsFloat - quInvCountItemQtyFrozen.AsFloat; end; procedure TFrmInventoryCount.btnExportClick(Sender: TObject); begin inherited; if (not quInvCountItem.Active) or (quInvCountItem.RecordCount = 0) then begin MsgBox(MSG_INF_NOT_EXCEL_ITEMS, vbOKOnly + vbInformation); Exit; end; with TFrmExport.Create(Self) do Start(grdInvCountItem, Self.Caption); end; procedure TFrmInventoryCount.btGroupItemClick(Sender: TObject); begin inherited; if not TcxGridDBTableView(AView).OptionsView.GroupByBox then TcxGridDBTableView(AView).OptionsView.GroupByBox := True else with grdInvCountItem do begin // Retiro todos os grupos while TcxGridDBTableView(AView).GroupedItemCount > 0 do TcxGridDBTableView(AView).GroupedColumns[TcxGridDBTableView(AView).GroupedItemCount-1].GroupIndex :=-1; TcxGridDBTableView(AView).OptionsView.GroupByBox := False; end; end; procedure TFrmInventoryCount.btCustomizeColumnsClick(Sender: TObject); begin inherited; // Mostra a coluna de customizing do grid TcxGridDBTableView(AView).Controller.Customization := not TcxGridDBTableView(AView).Controller.Customization; end; procedure TFrmInventoryCount.btInvCountItemPreviewClick(Sender: TObject); begin inherited; gridPrinterLink.Caption := lblSubMenu.Caption; gridPrinter.CurrentLink := gridPrinterLink; gridPrinter.Preview(True, nil); end; procedure TFrmInventoryCount.btCloseInvCountClick(Sender: TObject); begin inherited; if quInvCount.FieldByName('CountType').AsInteger = INV_COUNT_PHYSICAL then begin if MsgBox(MSG_CRT_CLOSE_PHYSICAL_INV, vbSuperCritical + vbYesNo) = vbNo then Exit; end else if MsgBox(MSG_CRT_CLOSE_INVENTORY, vbSuperCritical + vbYesNo) = vbNo then Exit; with TDMCloseCount.Create(self) do try Screen.Cursor := crHourGlass; SQLConnection := DM.ADODBConnect; CloseInvCount(quInvCount.FieldByName('IDStore').AsInteger, quInvCount.FieldByName('IDCount').AsInteger, quInvCount.FieldByName('IDUser').AsInteger, quInvCount.FieldByName('CountType').AsInteger); finally Screen.Cursor := crDefault; if LogError.Text <> '' then MsgBox(LogError.Text, vbInformation + vbOKOnly); Free; end; RefreshInvCount; RefreshInvCountItem; end; procedure TFrmInventoryCount.quInvCountAfterScroll(DataSet: TDataSet); begin inherited; RefreshInvCountItem; end; procedure TFrmInventoryCount.btnPreviewBarcodeFileClick(Sender: TObject); begin inherited; if (not cdsBarcodeList.Active) or (cdsBarcodeList.RecordCount = 0) then Exit; gridPrinterLinkBarcodeFile.Caption := lblSubMenu.Caption; gridPrinter.CurrentLink := gridPrinterLinkBarcodeFile; gridPrinter.Preview(True, nil); end; procedure TFrmInventoryCount.btExportBarcodeFileClick(Sender: TObject); begin inherited; If (not cdsBarcodeList.Active) or (cdsBarcodeList.RecordCount = 0) then begin MsgBox(MSG_INF_NOT_EXCEL_ITEMS, vbOKOnly + vbInformation); Exit; end; with TFrmExport.Create(Self) do Start(gridBarcodes, Self.Caption); end; procedure TFrmInventoryCount.edtBarcodeAfterSearchBarcode(Sender: TObject); var IDModel: Integer; begin inherited; with edtBarcode do begin if SearchResult then begin IDModel := GetFieldValue('IDModel'); scModel.LookUpValue := IntToStr(IDModel); FScanned := StrToFloat(edtBarcode.QtyEdit.Text); RefreshCombo(nil); lbLastItem.Caption := scModel.Text + ' - ' + scModel.CodeValue; lbBarcode.Caption := edtBarcode.Text; editQty.Text := edtBarcode.QtyEdit.Text; lbScanned.Caption := edtBarcode.QtyEdit.Text; FScanned := 0; if tcManualCount.TabIndex = 0 then Save else begin editQty.SetFocus; editQty.SelectAll; end; end else begin MsgBox(MSG_CRT_NO_BARCODE, vbCritical + vbOkOnly); edtBarcode.SelectAll; end; end; end; procedure TFrmInventoryCount.AdjustInventory(AIDModel, ACountType: Integer; ACountedQty: Double; AAdjustDate: TDateTime); begin with spAdjust do begin Parameters.ParambyName('@IDStore').Value := StrToInt(scStore.LookUpValue); Parameters.ParambyName('@IDUser').Value := DM.fUser.ID; Parameters.ParambyName('@IDModel').Value := AIDModel; Parameters.ParambyName('@CountType').Value := ACountType; Parameters.ParambyName('@CountedQty').Value := ACountedQty; Parameters.ParambyName('@CountDate').Value := AAdjustDate; ExecProc; end; end; procedure TFrmInventoryCount.editQtyKeyPress(Sender: TObject; var Key: Char); begin inherited; Key := ValidateCurrency(Key); end; procedure TFrmInventoryCount.btPrintClick(Sender: TObject); var AFrmBarcodePrint : TFrmBarcodePrint; begin inherited; if lbBarcode.Caption <> '' then try AFrmBarcodePrint := TFrmBarcodePrint.Create(Self); AFrmBarcodePrint.PrintBarcode(lbBarcode.Caption, 1); finally FreeAndNil(AFrmBarcodePrint); end; end; procedure TFrmInventoryCount.tcManualCountChange(Sender: TObject); begin inherited; if tcManualCount.TabIndex = 0 then begin edtBarcode.Color := $0080FFFF; lbNewHand.Visible := True; lbNewOnHand.Visible := True; end else begin edtBarcode.Color := $00FFE9D2; lbNewHand.Visible := False; lbNewOnHand.Visible := False; end; end; end.
{* * Outliner Lighto * Copyright (C) 2011 Kostas Michalopoulos * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * * Kostas Michalopoulos <badsector@runtimelegend.com> *} program OutlinerLighto; {$MODE OBJFPC}{$H+} uses SysUtils, Crt, Keyboard, Video, UI, Nodes, Tree, Defines {$IFNDEF WINDOWS}, baseunix{$ENDIF} {$IFDEF OLPTC}, ptckvm{$ENDIF}; {$IFDEF WINDOWS} {$R OLICON.RC} {$ENDIF} const LevelColor: array [0..3] of Byte = (3, 2, 6, 5); var Scroll: Integer; CParent: TNode; // note: contains the real parent CNode: TNode; CNIdx: Integer; CNodeY: Integer; UpParent: array of TNode; // note: contains navigation parents (for pointers) Editing, Moving, Running: Boolean; Cx, Cy: Integer; EdPos: Integer; CutNode: TNode; FileName: string; i: Integer; procedure Save; begin SaveTree(FileName, Root); end; procedure Load; begin LoadTree(FileName, Root); end; procedure DrawTree; var lev, x, y: Integer; procedure WriteText(Str: string; Editing: Boolean); var w: string; Pos, lx, i: Integer; procedure WriteW; var i: Integer; begin if lx > x then begin if (y > 0) and (y < ScreenHeight - 1) then WriteChar(' '); if Editing and (Pos < EdPos) then Inc(Cx); Inc(Pos); end; if lx + Length(w) >= ScreenWidth then begin lx:=x; Inc(y); CAttr:=0; if (y > 0) and (y < ScreenHeight - 1) then ClrTo(0, x, y); if Editing then begin CAttr:=8; GotoXY(x - 2, y); if (y > 0) and (y < ScreenHeight - 1) then WriteChar('|'); end; Color(FColor, BColor); end; GotoXY(lx, y); if Editing and (Pos <= EdPos) and (lx=x) then begin Cx:=x; Cy:=y; end; if (y > 0) and (y < ScreenHeight - 1) then WriteStr(w); if Editing then begin for i:=1 to Length(w) do begin if Pos < EdPos then begin Inc(Cx); Cy:=y; end; Inc(Pos); end; end; Inc(lx, Length(w) + 1); end; begin w:=''; lx:=x; Pos:=1; if Editing then begin Cx:=x; Cy:=y; end; for i:=1 to Length(Str) do if Str[i] in [#9, ' '] then begin WriteW; w:=''; end else w:=w + Str[i]; WriteW; end; procedure DrawNode(ANode: TNode); var i, Per: Integer; CNY1: Integer; Child: TNode; NodeType: TNodeType; begin Inc(x, 4); if x > ScreenWidth then Exit; Inc(lev); for i:=0 to Length(ANode.Children) - 1 do begin Child:=ANode.Children[i]; if (((ANode=Root) and (Length(UpParent)=0)) or ((Length(UpParent) > 0) and (UpParent[Length(UpParent) - 1]=ANode))) and (CNIdx=i) then begin if Editing then Color(7, 0) else if Moving then Color(0, 6) else Color(0, 7); CNY1:=y; end else if Child.HasChildren then begin Color(LevelColor[lev and 3], 0); end else if (Child.Parent.NodeType=ntTickable) and (Child.NodeType=ntNormal) then Color(14, 0) else Color(7, 0); if Child.NodeType=ntPointer then begin GotoXY(x - 7, y); CAttr:=9; WriteStr('<-'); end; GotoXY(x - 4, y); if Editing and (CParent=ANode) and (CNIdx=i) then begin CAttr:=8; WriteStr(' | '); end else if (y > 0) and (y < ScreenHeight - 1) then begin NodeType:=Child.TargetNodeType; if Child.HasChildren then begin if NodeType=ntNormal then begin CAttr:=7; if Child.Open then WriteStr(' - ') else WriteStr(' + '); end else if NodeType=ntTickable then begin if (y > 0) and (y < ScreenHeight - 1) then begin Per:=Child.TickPercent; if Per=100 then begin CAttr:=15; WriteStr('[X] ') end else begin if Per in [0..24] then CAttr:=8 else if Per in [25..49] then CAttr:=7 else if Per in [50..74] then CAttr:=13 else if Per in [75..99] then CAttr:=14; WriteStr(Chr(Ord('0')+(Per div 10)) + Chr(Ord('0')+(Per mod 10)) + '%'); end; end; end; end else begin if NodeType=ntNormal then begin if (Child.Parent.NodeType=ntTickable) and (Child.NodeType=ntNormal) then begin CAttr:=15; WriteStr(' -- '); end else begin CAttr:=1; WriteStr(' o ') end; end else if NodeType=ntTickable then begin CAttr:=2; if Child.Tick then WriteStr('[X] ') else WriteStr('[ ] '); end; end; end; Color(FColor, BColor); GotoXY(x, y); if Child.Text='' then begin if (y > 0) and (y < ScreenHeight - 1) then WriteChar(' '); if Editing and (CParent=ANode) and (CNIdx=i) then begin Cx:=x; Cy:=y; end; end else WriteText(Child.Text, Editing and (CParent=ANode) and (CNIdx=i)); Color(7, 0); if (CParent=ANode) and (CNIdx=i) then begin CNodeY:=(CNY1 + y) div 2; end; Inc(y); if Child.Open and Child.HasChildren then begin DrawNode(Child); end; end; Dec(lev); Dec(x, 4); end; begin if ScreenHeight < 6 then Exit; DoWrites:=False; while True do begin y:=-Scroll; x:=0; lev:=-1; DrawNode(Root); if CNodeY < ScreenHeight div 4 then Dec(Scroll) else if CNodeY > ScreenHeight div 4 * 3 then Inc(Scroll) else begin y:=-Scroll; x:=0; lev:=-1; DoWrites:=True; DrawNode(Root); break; end; end; end; procedure GoToPrev; begin if CNIdx > 0 then begin if CNode.Fresh and (CNode.Text='') and (CNIdx=Length(CParent.Children)-1) then begin CParent.Remove(CNode); CNode.Free; end; Dec(CNIdx); CNode:=CParent.Children[CNIdx]; end; end; procedure GoToNext; begin if CNIdx < Length(CParent.Children) - 1 then begin Inc(CNIdx); CNode:=CParent.Children[CNIdx]; end else if not CNode.Fresh then begin CNode:=CParent.AddStr(''); CNode.Fresh:=True; CNode.NodeType:=CParent.TargetNodeType; CNIdx:=Length(CParent.Children) - 1; end; end; function Dive: TNode; var Node: TNode; begin Result:=nil; if CNode.Fresh then Exit; if not CNode.HasChildren then begin Node:=TNode.Create; Node.NodeType:=CNode.TargetNodeType; Node.Text:=''; Node.Fresh:=True; CNode.Add(Node); Result:=Node; end; SetLength(UpParent, Length(UpParent) + 1); UpParent[Length(UpParent) - 1]:=CNode; CNIdx:=0; CNode.WasOpen:=CNode.Open; CNode.Open:=True; CNode:=CNode.Children[0]; CParent:=CNode.Parent; end; procedure Rise; begin if Length(UpParent) > 0 then begin if CNode.Fresh and (CNode.Text='') then begin CParent.Remove(CNode); CNode.Free; end; CNode:=UpParent[Length(UpParent) - 1]; SetLength(UpParent, Length(UpParent) - 1); CParent:=CNode.Parent; CNIdx:=CParent.IndexOf(CNode); CNode.Open:=CNode.WasOpen; if (Length(CNode.Children)=1) and (CNode.Children[0].Fresh) then begin CNode.Remove(CNode.Children[0]); CNode.Children[0].Free; end; end; end; procedure OpenClose; begin if CParent.Children[CNIdx].HasChildren then begin CParent.Children[CNIdx].Open:=not CParent.Children[CNIdx].Open; CParent.Children[CNIdx].WasOpen:=CParent.Children[CNIdx].Open; end; end; function EditMode: Boolean; var Key: TKeyEvent; SaveText: string; Sx, Sy: Integer; Ch: Char; procedure MoveLeft; begin if EdPos > 1 then Dec(EdPos); end; procedure MoveRight; begin if EdPos <= Length(CNode.Text) then Inc(EdPos); end; function CursorUnderWordSeparator: Boolean; begin if not (CNode.Text[EdPos] in ['a'..'z', 'A'..'Z', '0'..'9']) then Exit(True); Result:=False; end; procedure MoveWordLeft; var Start: Boolean; begin MoveLeft; Start:=CursorUnderWordSeparator; while (EdPos > 1) and (Start=CursorUnderWordSeparator) do MoveLeft; end; procedure MoveWordRight; var Start: Boolean; begin MoveRight; Start:=CursorUnderWordSeparator; while (EdPos <= Length(CNode.Text)) and (Start=CursorUnderWordSeparator) do MoveRight; end; begin Result:=True; Editing:=True; SaveText:=CNode.Text; EdPos:=Length(SaveText) + 1; while Editing do begin ClearBackScreen; Top('Outliner Lighto version ' + VERSION + ' Copyright (C) 2011 Kostas "Bad Sector" Michalopoulos'); Status(' Editing Node: ~Enter~ Done ~Arrows~ Move ~ESC~ Cancel'); DrawTree; UpdateScreen(True); SetCursorPos(Cx, Cy); {$IFDEF OLPTC}InvertCharAt(Cx, Cy);{$ENDIF} Key:=TranslateKeyEvent(GetKeyEvent); {$IFDEF OLPTC}InvertCharAt(Cx, Cy);{$ENDIF} case GetKeyEventFlags(Key) of kbASCII: begin Ch:=GetKeyEventChar(Key); case Ch of #8: if EdPos > 1 then begin CNode.Text:=Copy(CNode.Text, 1, EdPos - 2) + Copy(CNode.Text, EdPos, Length(CNode.Text)); Dec(EdPos); end; #27: begin Editing:=False; CNode.Text:=SaveText; Result:=False; end; #13: begin Editing:=False; if CNode.Text <> '' then CNode.Fresh:=False; end; else if Ch in [#32..#127] then begin CNode.Text:=Copy(CNode.Text, 1, EdPos - 1) + Ch + Copy(CNode.Text, EdPos, Length(CNode.Text)); Inc(EdPos); end; end; end; else case GetKeyEventCode(Key) of kbdDelete: if EdPos <= Length(CNode.Text) then begin CNode.Text:=Copy(CNode.Text, 1, EdPos - 1) + Copy(CNode.Text, EdPos + 1, Length(CNode.Text)); end; kbdHome: EdPos:=1; kbdEnd: EdPos:=Length(CNode.Text) + 1; kbdLeft: MoveLeft; kbdRight: MoveRight; 29440: MoveWordLeft; // is this portable? 29696: MoveWordRight; // is this portable? kbdUp: begin Sx:=Cx; Sy:=Cy - 1; while (EdPos > 1) and (not ((Cx=Sx) and (Cy=Sy))) do begin Dec(EdPos); DrawTree; end; end; kbdDown: begin Sx:=Cx; Sy:=Cy + 1; while (EdPos <= Length(CNode.Text)) and (not ((Cx=Sx) and (Cy=Sy))) do begin Inc(EdPos); DrawTree; end; end; end; end; end; end; procedure DeleteNode; var UParent: TNode; begin FreeAndNil(CutNode); if not CNode.Fresh then CutNode:=CNode; CParent.Remove(CNode); if Length(UpParent)=0 then UParent:=Root else UParent:=UpParent[Length(UpParent) - 1]; if UParent.HasChildren then begin if Length(UParent.Children) <= CNIdx then begin CNIdx:=Length(UParent.Children) - 1; CNode:=UParent.Children[CNIdx]; end else begin CNode:=UParent.Children[CNIdx]; end; end else begin if UParent=Root then begin CNode:=Root.AddStr(''); CNode.Fresh:=True; end else begin //CNode:=UParent; //CNIdx:=CNode.Parent.IndexOf(CNode); //CParent:=CNode.Parent; Rise; end; end; end; procedure MultiEditMode; var Node: TNode; Res, AddedAny: Boolean; begin AddedAny:=False; if CNode.Fresh and (CNode.Text='') then begin while True do begin Res:=EditMode; if (not Res) or (CNode.Fresh and (CNode.Text='')) then begin if (CNIdx=Length(CParent.Children)-1) and (not AddedAny) then break; Node:=CutNode; CutNode:=nil; DeleteNode; if CutNode <> nil then CutNode.Free; CutNode:=Node; if CNIdx < Length(CParent.Children)-1 then GoToPrev; break; end; AddedAny:=True; Node:=TNode.Create; Node.Fresh:=True; Node.NodeType:=CParent.TargetNodeType; CParent.Insert(Node, CNIdx + 1); CNode:=Node; Inc(CNIdx); end; end else EditMode; end; procedure DeleteRequest(KeyName: string); var Key: TKeyEvent; begin if CNode.HasChildren then Status(' Press ~' + KeyName + '~ again to delete the node and it''s children') else Status(' Press ~' + KeyName + '~ again to delete the node'); DrawTree; UpdateScreen(True); Key:=TranslateKeyEvent(GetKeyEvent); if (GetKeyEventFlags(Key)=kbASCII) and (UpCase(GetKeyEventChar(Key))='D') then begin DeleteNode; end else if GetKeyEventCode(Key)=kbdDelete then begin DeleteNode; end; end; procedure PasteNode; begin if CutNode=nil then exit; if CNode.Fresh and (CNode.Text='') then begin CParent.Remove(CNode); CNode.Free; CNode:=CutNode; end; CParent.Insert(CutNode, CNIdx); CNode:=CutNode; CutNode:=nil; end; procedure ChangeType; var i: Integer; begin if CNode.NodeType=ntNormal then begin CNode.NodeType:=ntTickable; CParent.NodeType:=ntTickable; end else begin CNode.NodeType:=ntNormal; CParent.NodeType:=ntNormal; for i:=0 to Length(CParent.Children)-1 do if CParent.Children[i].NodeType=ntTickable then begin Cparent.NodeType:=ntTickable; break; end; end; end; procedure GoToHome; begin if CParent=Root then begin CNIdx:=0; CNode:=Root.Children[0]; end else while CParent <> Root do Rise; end; procedure GrabMode; var Key: TKeyEvent; Ch: Char; OParent, Node, MNode: TNode; OIndex: Integer; procedure Restore; var Nodes: array of TNode; Node: TNode; i: Integer; begin CParent.Remove(MNode); GoToHome; SetLength(Nodes, 0); Node:=OParent; while Node <> Root do begin SetLength(Nodes, Length(Nodes) + 1); Nodes[Length(Nodes) - 1]:=Node; Node:=Node.Parent; end; for i:=Length(Nodes) - 1 downto 0 do begin CNode:=Nodes[i]; CNIdx:=CParent.IndexOf(CNode); Node:=Dive; if Node <> nil then begin CParent.Remove(Node); Node.Free; end; end; OParent.Insert(MNode, OIndex); CNode:=MNode; CParent:=OParent; CNIdx:=OIndex; end; begin Moving:=True; MNode:=CNode; OParent:=CParent; OIndex:=CNIdx; while Moving do begin ClearBackScreen; Top('Outliner Lighto version ' + VERSION + ' Copyright (C) 2011 Kostas "Bad Sector" Michalopoulos'); Status(' Grabbed Node: ~G or Enter~ Drop here ~Arrows~ Move ~Q or ESC~ Cancel'); DrawTree; UpdateScreen(True); Key:=TranslateKeyEvent(GetKeyEvent); case GetKeyEventFlags(Key) of kbASCII: begin Ch:=GetKeyEventChar(Key); case Ch of #27, 'q', 'Q': begin Restore; Moving:=False; end; #13, 'g', 'G': begin Moving:=False; end; end; end; else case GetKeyEventCode(Key) of kbdLeft: if CParent <> Root then begin CParent.Remove(MNode); Node:=CParent; Rise; CParent.Insert(MNode, CParent.IndexOf(Node) + 1); CNode:=MNode; CNIdx:=CParent.IndexOf(CNode); end; kbdRight: if CNIdx > 0 then begin GoToPrev; CParent.Remove(MNode); CNode.Add(MNode); Dive; CNode:=MNode; CNIdx:=CParent.IndexOf(CNode); end; kbdUp: if CNIdx > 0 then begin CParent.Remove(MNode); CParent.Insert(MNode, CNIdx - 1); Dec(CNIdx); end; kbdDown: if CNIdx < Length(CParent.Children) - 1 then begin CParent.Remove(MNode); CParent.Insert(MNode, CNIdx + 1); Inc(CNIdx); end; end; end; end; end; procedure MakePointer; var Node: TNode; begin if CNode.Fresh then Exit; Node:=TNode.Create; Node.NodeType:=ntPointer; Node.Target:=CNode; CParent.Insert(Node, CNIdx + 1); GoToNext; GrabMode; end; procedure OrderNodes; var Key: TKeyEvent; begin Status(' Press ~O~ again to order the nodes alphabetically'); DrawTree; UpdateScreen(True); Key:=TranslateKeyEvent(GetKeyEvent); if (GetKeyEventFlags(Key)=kbASCII) and (UpCase(GetKeyEventChar(Key))='O') then begin CParent.OrderChildren; CNIdx:=CParent.IndexOf(CNode); end; end; procedure MainMode; var Key: TKeyEvent; Node: TNode; begin while Running do begin ClearBackScreen; Top('Outliner Lighto version ' + VERSION + ' Copyright (C) 2011 Kostas "Bad Sector" Michalopoulos'); Status(' ~Space~ Toggle ~Arrows~ Browse ~C or Enter~ Change ~I~ Insert ~A~ Append ~D~ Delete ~Q~ Quit '); DrawTree; UpdateScreen(True); SetCursorPos(ScreenWidth - 1, ScreenHeight - 1); Key:=TranslateKeyEvent(GetKeyEvent); case GetKeyEventFlags(Key) of kbASCII: case GetKeyEventChar(Key) of 'q', 'Q': Running:=False; 'r', 'R': begin DoneVideo; InitVideo; end; 's', 'S': Save; #32: OpenClose; 'l', 'L': Dive; 'h', 'H': Rise; 'k', 'K': GoToPrev; 'j', 'J': GoToNext; #13, 'c', 'C': MultiEditMode; 'i', 'I': begin if not CNode.Fresh then begin Node:=TNode.Create; Node.Fresh:=True; Node.NodeType:=CParent.TargetNodeType; CParent.Insert(Node, CNIdx); CNode:=Node; end; MultiEditMode; end; 'a', 'A': begin if not CNode.Fresh then begin Node:=TNode.Create; Node.Fresh:=True; Node.NodeType:=CParent.TargetNodeType; CParent.Insert(Node, CNIdx + 1); GoToNext; end; MultiEditMode; end; 't', 'T': ChangeType; 'x', 'X': begin if CNode.TargetNodeType=ntTickable then CNode.Tick:=not CNode.Tick; end; 'd', 'D': DeleteRequest('D'); 'p', 'P': PasteNode; 'u', 'U': GoToHome; 'g', 'G': if not CNode.Fresh then GrabMode; 'o', 'O': OrderNodes; '.': if not CNode.Fresh then MakePointer; end; else case GetKeyEventCode(Key) of kbdF5: begin DoneVideo; InitVideo; end; kbdUp: GoToPrev; kbdDown: GoToNext; kbdRight: Dive; kbdLeft: Rise; kbdDelete: DeleteRequest('Del'); kbdHome: GoToHome; end; end; end; end; {$IFNDEF WINDOWS} procedure HandleSignal(Signal: CInt); cdecl; begin Save; DestroyTree; ClearScreen; DoneKeyboard; DoneVideo; Crt.GotoXY(1, ScreenHeight); FreeAndNil(CutNode); Halt; end; procedure InstallSignalHandlers; var oa, na: PSigActionRec; begin New(oa); New(na); na^.sa_Handler:=SigActionHandler(@HandleSignal); FillChar(na^.sa_Mask, SizeOf(na^.sa_Mask), #0); na^.sa_Flags:=0; {$IFDEF LINUX} na^.sa_Restorer:=nil; {$ENDIF} if fpSigAction(SigQuit, na, oa) <> 0 then Exit; if fpSigAction(SigTerm, na, oa) <> 0 then Exit; if fpSigAction(SigHup, na, oa) <> 0 then Exit; Dispose(oa); Dispose(na); end; {$ENDIF} {$IFDEF OLPTC} var PTCRows : Integer = 100; PTCCols : Integer = 40; procedure SetPTCVideoMode; var VideoMode: TVideoMode; begin VideoMode.Col:=PTCRows; VideoMode.Row:=PTCCols; VideoMode.Color:=True; KVMSetWindowTitle('Outliner Lighto (PasPTC/PTCKVM version)'); SetVideoMode(VideoMode); end; {$ENDIF} begin FileName:=GetUserDir + '.ol.olol'; for i:=1 to ParamCount do begin if ParamStr(i)='--help' then begin WriteLn('Usage: ol [options] [path-to-olol-file]'); WriteLn('Options:'); WriteLn(' --help These help instructions'); {$IFDEF OLPTC} WriteLn(' --ptcsize=c,r Set the site for the PasPTC/PTCKVM window to'); WriteLn(' <c> columns and <r> rows'); {$ENDIF} exit; end else {$IFDEF OLPTC} if Copy(ParamStr(i), 1, 10)='--ptcsize=' then begin try Tmp:=Copy(ParamStr(i), 11, Length(ParamStr(i))); PTCRows:=StrToInt(Copy(Tmp, 1, Pos(',', Tmp) - 1)); PTCCols:=StrToInt(Copy(Tmp, Pos(',', Tmp) + 1, Length(Tmp))); except PTCRows:=40; PTCCols:=100; end; end else {$ENDIF} FileName:=ParamStr(i); end; InitVideo; InitKeyboard; {$IFDEF OLPTC} SetPTCVideoMode; {$ENDIF} CreateTree; Load; CParent:=Root; CNode:=Root.Children[0]; CNIdx:=0; Color(7, 0); ClearScreen; Scroll:=0; CNodeY:=0; Running:=True; {$IFNDEF WINDOWS} InstallSignalHandlers; {$ENDIF} MainMode; Save; DestroyTree; ClearScreen; DoneKeyboard; DoneVideo; Crt.GotoXY(1, ScreenHeight); FreeAndNil(CutNode); end.
unit fCommon; interface function NameFromFeedURL(const url:string):string; function ShowLabel(const Lbl,LblColor,ClassPrefix:string):string; function ColorPicker(const ValColor:string):string; function CheckColor(const ValColor:string):string; function UtcNow:TDateTime; procedure ClearChart(const key:string); implementation uses Windows, SysUtils; function NameFromFeedURL(const url:string):string; var i,j,l:integer; begin l:=Length(url); i:=1; while (i<=l) and (url[i]<>':') do inc(i); inc(i); if (i<=l) and (url[i]='/') then inc(i); if (i<=l) and (url[i]='/') then inc(i); j:=i; while (j<=l) and (url[j]<>'/') do inc(j); Result:=Copy(url,i,j-i); if Result='feeds.feedburner.com' then begin inc(j); i:=j; while (j<=l) and (url[j]<>'/') do inc(j); Result:=Copy(url,i,j-i); end else if Result='www.instagram.com' then begin inc(j); i:=j; while (j<=l) and (url[j]<>'/') do inc(j); //Result:='i@'+Copy(url,i,j-i); Result:=#$D83D#$DCF8+Copy(url,i,j-i); end else if Result='reddit.com' then begin inc(j); i:=j; while (j<=l) and (url[j]<>'/') do inc(j); Result:='r/'+Copy(url,i,j-i); end else if Copy(Result,Length(Result)-13,14)='.wordpress.com' then Result:='wp:'+Copy(Result,1,Length(Result)-15); //more? if Result='' then Result:=FormatDateTime('[yyyy-mm-dd hh:nn]',UtcNow); end; function HTMLEncode(const x:string):string; begin Result:= StringReplace( StringReplace( StringReplace( x ,'&','&amp;',[rfReplaceAll]) ,'<','&lt;',[rfReplaceAll]) ,'>','&gt;',[rfReplaceAll]) ; end; function ShowLabel(const Lbl,LblColor,ClassPrefix:string):string; var c:string; i,j,k:integer; begin if (Lbl='') and (LblColor='') then Result:='<div class="'+ClassPrefix+'label" title="feeder: system message" style="background-color:#FFCC00;color:#000000;border:1px solid #000000;border-radius:0;">feeder</div>' else begin c:=CheckColor(LblColor); if LowerCase(c)='ffffff' then c:='-666666'; if (c<>'') and (c[1]='-') then c:='FFFFFF;color:#'+Copy(c,2,6)+';border:1px solid #'+Copy(c,2,6) else if (c<>'') and (c[1]='+') then begin try i:=StrToInt('$0'+Copy(c,2,9)); except i:=$EEEEEE; end; j:=0; k:=(i shr 16) and $FF; inc(j,((k*k) shr 8)*3);//R k:=(i shr 8) and $FF; inc(j,((k*k) shr 8)*5);//G k:= i and $FF; inc(j,((k*k) shr 8)*2);//B if j<1200 then c:='EEEEEE;color:#'+Copy(c,2,6) else c:='666666;color:#'+Copy(c,2,6); end else begin while Length(c)<6 do c:='0'+c; try i:=StrToInt('$0'+c); if i=0 then begin c:='EEEEEE'; i:=$EEEEEE; end; except i:=$EEEEEE; end; j:=0; k:=(i shr 16) and $FF; inc(j,((k*k) shr 8)*3);//R k:=(i shr 8) and $FF; inc(j,((k*k) shr 8)*5);//G k:= i and $FF; inc(j,((k*k) shr 8)*2);//B if j<750 then c:=c+';color:#DDDDDD'; end; Result:='<div class="'+ClassPrefix+'label" style="background-color:#'+c+';">'+HTMLEncode(Lbl)+'</div>'; end; end; function ColorPicker(const ValColor:string):string; var i,j,c:integer; const hex:array[0..15] of char='0123456789ABCDEF'; begin try if ValColor='' then c:=$CCCCCC //default else if (ValColor[1]='-') or (ValColor[1]='+') then c:=StrToInt('$0'+Copy(ValColor,2,9)) else c:=StrToInt('$0'+ValColor); except c:=0; end; Result:='<script>'+ #13#10'function doColorSelect(xx){'+ #13#10' var c=document.getElementById("c1");'+ #13#10' var r=document.getElementById("c1r");'+ #13#10' var g=document.getElementById("c1g");'+ #13#10' var b=document.getElementById("c1b");'+ #13#10' var x=r.options[r.selectedIndex].label+g.options[g.selectedIndex].label+b.options[b.selectedIndex].label;'+ #13#10' if(xx)c.value=x;'+ #13#10' r.style.backgroundColor="#"+x;'+ #13#10' g.style.backgroundColor="#"+x;'+ #13#10' b.style.backgroundColor="#"+x;'+ #13#10' for(var i=0;i<6;i++){'+ #13#10' r.options[i].style.backgroundColor="#"+r.options[i].label+g.options[g.selectedIndex].label+b.options[b.selectedIndex].label;'+ #13#10' g.options[i].style.backgroundColor="#"+r.options[r.selectedIndex].label+g.options[i].label+b.options[b.selectedIndex].label;'+ #13#10' b.options[i].style.backgroundColor="#"+r.options[r.selectedIndex].label+g.options[g.selectedIndex].label+b.options[i].label;'+ #13#10' }'+ #13#10'}'+ #13#10'</script>'+ '<input type="text" name="color" id="c1" value="'+HTMLEncode(ValColor)+'" style="width:6em;" />' +'&nbsp;R:<select id="c1r" onchange="doColorSelect(true);">'; i:=0; j:=((c shr 16) and $FF) shr 4; while i<$10 do begin Result:=Result+'<option'; if (j>i-2) and (j<=i+2) then Result:=Result+' selected="1"'; Result:=Result+'>'+hex[i]+hex[i]+'</option>'; inc(i,3); end; Result:=Result+'</select>&nbsp;G:<select id="c1g" onchange="doColorSelect(true);">'; i:=0; j:=((c shr 8) and $FF) shr 4; while i<$10 do begin Result:=Result+'<option'; if (j>i-2) and (j<=i+2) then Result:=Result+' selected="1"'; Result:=Result+'>'+hex[i]+hex[i]+'</option>'; inc(i,3); end; Result:=Result+'</select>&nbsp;B:<select id="c1b" onchange="doColorSelect(true);">'; i:=0; j:=(c and $FF) shr 4; while i<$10 do begin Result:=Result+'<option'; if (j>i-2) and (j<=i+2) then Result:=Result+' selected="1"'; Result:=Result+'>'+hex[i]+hex[i]+'</option>'; inc(i,3); end; Result:=Result+'</select><script>doColorSelect(false);</script>'; Result:=Result+' //TODO: replace this with a nice color picker'; end; function CheckColor(const ValColor:string):string; var i:integer; c:string; begin c:=ValColor; try if (c<>'') and (c[1]='#') then c:=Copy(c,2,Length(c)-1); if (c<>'') and ((c[1]='-') or (c[1]='+')) then begin i:=StrToInt('$0'+Copy(c,2,999)); if i<$1000000 then if Length(c)=4 then c:=c[1]+c[2]+c[2]+c[3]+c[3]+c[4]+c[4] else while Length(c)<7 do c:=c[1]+'0'+Copy(c,2,999) else c:='0'; end else begin i:=StrToInt('$0'+c); if i=0 then c:='EEEEEE' else if i<$1000000 then if Length(c)=3 then c:=c[1]+c[1]+c[2]+c[2]+c[3]+c[3] else while Length(c)<6 do c:='0'+c else c:='EEEEEE'; end; except c:='EEEEEE'; end; Result:=c; end; function UtcNow:TDateTime; var st:TSystemTime; tz:TTimeZoneInformation; tx:cardinal; bias:TDateTime; begin GetLocalTime(st); tx:=GetTimeZoneInformation(tz); case tx of 0:bias:=tz.Bias/1440.0; 1:bias:=(tz.Bias+tz.StandardBias)/1440.0; 2:bias:=(tz.Bias+tz.DaylightBias)/1440.0; else bias:=0.0; end; Result:= EncodeDate(st.wYear,st.wMonth,st.wDay)+ EncodeTime(st.wHour,st.wMinute,st.wSecond,st.wMilliseconds)+ bias; end; procedure ClearChart(const key:string); var fn:string; begin SetLength(fn,MAX_PATH); SetLength(fn,GetModuleFileName(HInstance,PChar(fn),MAX_PATH)); DeleteFile(PChar(ExtractFilePath(fn)+'charts\'+key+'.png')); end; end.
unit Miscel; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses Sysutils, {$IFDEF FPC} LCLIntf, LCLType, {$ELSE} Windows, {$ENDIF} Classes, Forms, Controls, Graphics ; function ExtractBetween(chaine, chaine1, chaine2: string):string; function CompactDate(MyDate: TdateTime): String; function CompactDateTime(ADate: TDateTime): String; function DecompactDateTime(ADate: String): TDateTime; function DecompactDateTimeString(ADate: String ): String; function DecompactDateTimeFileName(FileName: String): String; function ExtractFileNameBeforeExtension(FileName: String): String; function DateToStrForFile(MyDate: TDateTime): String; function TimeToStrForFile(MyTime: TDateTime): String; function SetFileNameUnixToDos(FileName: String): String; function FindAndReplace(Chaine, FromValue, ToValue: String): String; function FindAndReplaceAll(Chaine, FromValue, ToValue: String): String; function BoiteMessage(Texte, Titre: String; Option: Integer): Integer; function SupprimeAccent(Texte: String): String; function ExtendedTrim(s: string): string; function GetDateFromString(s: String): String; procedure GetKeyWordList(Chaine, KeyWord: String; Liste: TStrings); function SupprimeCaractereNonAffichable(Texte: String): String; function SupprimeRetourChariot(Texte: String): String; function GetFirstWord(Chaine, Sep: String): String; function GetKeyWord(Chaine, KeyWord, Sep: String): String; function CodeString(Chaine, Code: String): String; function DecodeString(Chaine, Code: String): String; procedure PositionneToutControle(MyForm: TForm; Value: Boolean); function GetaWordFromKey(Chaine, KeyWord, Sep: String): String; function GetaWordFromIndex(Chaine: String; Index: Integer; Sep: String): String; function NormalizeRequetePourDB(Requete: String): String; function NormalizeRequetePourIB(Requete: String): String; function PosFrom(Substr, Str: String; Index: Integer): Integer; procedure Temporisation(t: Integer); function NormalizeDecimalSeparator(Value: String): String; function FormatMonnaieChaine(Value: String; Decimal: Byte): String; {Contrôle/Creation de répertoire Gestion de fichiers} type TCreateDir = (cdirNo, cdirYes, cdirConfirm, cdirConfirmEach); procedure CheckDirectory(dir: string; CreateDir: TCreateDir); procedure LireDir(FileName: String; Attr: Integer; ListDir: TStrings); function NormalizeDirectoryName(Name : String): string; function NormalizeFileName(Name : String): string; procedure FDCopyFiles(FileName, DestDir: String; FailIfExist: Boolean); procedure FDDeleteFiles(FileName: String); procedure FDFileSetAttr(FileName: String; Attr: Integer); procedure FDRenameFiles(FileName, FileDest: String); procedure DemanderConfirmationSiFichierExiste(FileName: String); procedure GetFile(DirName, FileMask: String; Attr: Integer; ListDir: TStrings); {Gestion du curseur de la souris} procedure PushC(MCursor : TCursor); procedure PopC; {Gestion de Canvas } procedure DrawCheckBox(Canvas: TCanvas; Rect: TRect); {Math} function Arrondie(Value: Double; Decimal: Byte): Double; implementation uses Dialogs, Buttons, ComCtrls, StdCtrls, Menus, DBGrids, {shdocvw,} DBCtrls, fonctions_file; const rc = #13#10; var PushCursor : array[0..511] of TCursor; MSIndex : Integer; function extractbetween(chaine,chaine1,chaine2: string):string; var s:string; begin s:=''; if (chaine1 = '*') and (chaine2 = '*') then Result := chaine else if (chaine1='*') then begin s := chaine; if pos(chaine2,s) > 0 then Result := copy(s,1,pos(chaine2,s)-1) else Result := s; end else if (chaine2 = '*') then begin if pos(chaine1,chaine)>0 then s := trim(copy(chaine,pos(chaine1,chaine)+length(chaine1),length(chaine))) else s := chaine; Result := s; end else begin s := copy(chaine,pos(chaine1,chaine)+length(chaine1),length(chaine)); Result:=copy(s,1,pos(chaine2,s)-1); end; end; function CompactDate(MyDate: TdateTime): String; var Year, Month, Day: Word; sYear, sMonth, sDay: String; begin DecodeDate(MyDate, Year, Month, Day); sYear := IntToStr(Year); if Length(sYear) = 2 then sYear := '20' + sYear; sMonth := IntToStr(Month); While Length(SMonth) < 2 do sMonth := '0' + sMonth; sDay := IntToStr(Day); While Length(SDay) < 2 do sDay := '0' + SDay; Result := sYear + sMonth + sDay; end; function DecompactDateTime(ADate: String ): TDateTime; var StAA,StMM,StJJ, StHH,StMN,StSS: String; begin Result := Now; if (ADate <> '') and (Copy(ADate,1,1) <> '0') then begin StAA := Copy(ADate,1,4); StMM := Copy(ADate,5,2); StJJ := Copy(ADate,7,2); StHH := Copy(ADate,9,2); StMN := Copy(ADate,11,2); StSS := Copy(ADate,13,2); ADate := StJJ+'/' + StMM + '/' + StAA + ' ' +StHH + ':' + StMN + ':' + StSS; try Result := StrToDateTime(ADate); except // La fonction n'echoue jamais end; end; end; function DecompactDateTimeString(ADate: String ): String; var StAA,StMM,StJJ, StHH,StMN,StSS: String; begin Result := ''; if (ADate <> '') and (Copy(ADate,1,1) <> '0') then begin StAA := Copy(ADate,1,4); StMM := Copy(ADate,5,2); StJJ := Copy(ADate,7,2); StHH := Copy(ADate,9,2); StMN := Copy(ADate,11,2); StSS := Copy(ADate,13,2); ADate := StJJ+'/' + StMM + '/' + StAA + ' ' +StHH + ':' + StMN + ':' + StSS; Result := ADate; end; end; function CompactDateTime( ADate: TDateTime ):String; Var AA,MM,JJ, HH,MN,SS,DS:Word; StAA,StMM,StJJ, StHH,StMN,StSS:String; begin Result := ''; DecodeDate(ADate,AA,MM,JJ); DecodeTime(ADate,HH,MN,SS,DS); StAA := IntToStr(AA); While Length(StAA)<2 do StAA := '0' + StAA; StMM := IntToStr(MM); While Length(StMM)<2 do StMM := '0' + StMM; StJJ := IntToStr(JJ); While Length(StJJ)<2 do StJJ := '0' + StJJ; StHH := IntToStr(HH); While Length(StHH)<2 do StHH := '0' + StHH; StMN := IntToStr(MN); While Length(StMN)<2 do StMN := '0' + StMN; StSS := IntToStr(SS); While Length(StSS)<2 do StSS := '0' + StSS; Result := StAA + StMM + StJJ + StHH + StMN + StSS; end; function ExtractFileNameBeforeExtension(FileName: String): String; begin Result := ExtractFileName(FileName); if Pos('.', Result) <> 0 then Result := Copy(Result, 1, Pos('.', Result) -1) end; function DateToStrForFile(MyDate: TDateTime): String; var Year, Month, Day: Word; SYear, SMonth, SDay: String; begin DecodeDate(MyDate, Year, Month, Day); SDay := IntToStr(Day); While Length(SDay) < 2 do SDay := '0' + SDay; SMonth := IntToStr(Month); While Length(SMonth) < 2 do SMonth := '0' + SMonth; SYear := IntToStr(Year); Result := SDay + '-' + SMonth + '-' + SYear; end; function TimeToStrForFile(MyTime: TDateTime): String; var Hour, Min, Sec, MSec: Word; SHour, SMin, SSec : String; begin DecodeTime(MyTime, Hour, Min, Sec, MSec); SHour := IntToStr(Hour); While Length(SHour) < 2 do SHour := '0' + SHour; SMin := IntToStr(Min); While Length(SMin) < 2 do SMin := '0' + SMin; SSec := IntToStr(Sec); While Length(SSec) < 2 do SSec := '0' + SSec; Result := SHour + 'h' + SMin + 'mn' + SSec + 's'; end; function DecompactDateTimeFileName(FileName: String): String; var s, s1: String; begin s := ExtractFileName(FileName); s1 := ExtractFileName(FileName); s := Copy(s, Pos('.', s) -14, 14); s := DecompactDateTimeString(s); s1 := Copy(s1, 1, Pos('.', s1) -15); Result := s1 + ' ' + s; end; function FindAndReplace(Chaine, FromValue, ToValue: String): String; var P: Integer; begin P := Pos(FromValue, Chaine); if P <> 0 then begin Delete(Chaine, P, Length(FromValue)); Insert(ToValue, Chaine, P); end; Result := Chaine; end; function FindAndReplaceAll(Chaine, FromValue, ToValue: String): String; begin Result := Chaine; While Pos(FromValue, Result) <> 0 do Result := FindAndReplace(Result, FromValue, ToValue); end; function SetFileNameUnixToDos(FileName: String): String; begin Result := FindAndReplaceAll(FileName, '/', '\'); Result := FindAndReplaceAll(Result, '\\', '\'); end; function BoiteMessage(Texte, Titre: String; Option: Integer): Integer; begin Result := Application.MessageBox(PChar(Texte), PChar(Titre), Option); end; // Trim + Supression de ',' '.' ';' '-' function ExtendedTrim(s: string): string; const BadChar = ' .,;:?!-'; begin Result := Trim(s); While (Result <> '') and (Pos(Result[1], BadChar) <> 0) do Delete(Result, 1, 1); While (Result <> '') and (Pos(Result[Length(Result)], BadChar) <> 0) do Delete(Result, Length(Result), 1); end; function SupprimeAccent(Texte: String): String; begin Result := Texte; Result := FindAndreplaceAll(Result, 'à', 'a'); Result := FindAndreplaceAll(Result, 'â', 'a'); Result := FindAndreplaceAll(Result, 'ä', 'a'); Result := FindAndreplaceAll(Result, 'é', 'e'); Result := FindAndreplaceAll(Result, 'è', 'e'); Result := FindAndreplaceAll(Result, 'ê', 'e'); Result := FindAndreplaceAll(Result, 'ë', 'e'); Result := FindAndreplaceAll(Result, 'î', 'i'); Result := FindAndreplaceAll(Result, 'ï', 'i'); Result := FindAndreplaceAll(Result, 'ô', 'o'); Result := FindAndreplaceAll(Result, 'ö', 'o'); Result := FindAndreplaceAll(Result, 'ù', 'u'); Result := FindAndreplaceAll(Result, 'û', 'u'); Result := FindAndreplaceAll(Result, 'ü', 'u'); Result := FindAndreplaceAll(Result, 'ç', 'c'); end; function GetFirstWord(Chaine, Sep: String): String; begin Result := Chaine; if Pos(Sep, Chaine) <> 0 then Result := Copy(Result, 1, Pos(Sep, Chaine) -1); end; // Cherche un mot clef dans une chaine (KEYWORD=) function GetKeyWord(Chaine, KeyWord, Sep: String): String; begin Result := ''; KeyWord := KeyWord + '='; if Pos(KeyWord, Chaine) > 0 then begin Delete(Chaine, 1, Pos(KeyWord, Chaine) + Length(KeyWord) -1); if Pos(Sep, Chaine) > 0 then Result := Copy(Chaine, 1, Pos(Sep, Chaine) -1) else Result := Chaine; end; end; function CodeString(Chaine, Code: String): String; var Cpt: Integer; n: Integer; s: String; begin Result := ''; if (Length(Chaine) = 0) or (Length(Code) = 0) then exit; s := ''; Cpt := 1; for n := 1 to Length(Chaine) do begin s := s + Char(Ord(Chaine[n]) xor Ord(Code[Cpt])); Inc(Cpt); if Cpt > length(Code) then Cpt := 1; end; for n := 1 to length(s) do Result := Result + '#' + IntToStr(Ord(s[n])); end; function DecodeString(Chaine, Code: String): String; var Cpt: Integer; n: Integer; s, s1: String; begin Result := ''; if (Length(Chaine) = 0) or (Length(Code) = 0) then exit; s := ''; While Pos('#', Chaine) > 0 do begin Delete(Chaine, 1, Pos('#', Chaine)); if Pos('#', Chaine) > 0 then s1 := Copy(Chaine, 1, Pos('#', Chaine) -1) else s1 := Chaine; s := s + Char(StrToInt(s1)); end; Cpt := 1; for n := 1 to Length(s) do begin Result := Result + Char(Ord(s[n]) xor Ord(Code[Cpt])); Inc(Cpt); if Cpt > length(Code) then Cpt := 1; end; end; function GetDateFromString(s: String): String; const Mois: Array[1..12] of String =('janvier', 'fevrier', 'mars', 'avril', 'mai', 'juin', 'juillet', 'aout', 'septembre', 'octobre', 'novembre', 'decembre'); var n: Integer; begin s := SupprimeAccent(LowerCase(s)); s := FindAndReplaceAll(s, '1er', '1'); // Pour traiter le 1er for n := 1 to 12 do if pos(Mois[n], s) <> 0 then begin s := FindAndReplaceAll(s, Mois[n], '/' + Copy('0' + IntToStr(n), Length(IntToStr(n)), 2) + '/'); Break; end; if Pos(',', s) <> 0 then s := Copy(s, 1, Pos(',', s) -1); Result := ExtendedTrim(s); try Result := DateToStr(StrToDate(Result)); except // Si la date récupérée n'est pas correcte on ne renvoie rien Result := ''; end end; procedure GetKeyWordList(Chaine, KeyWord: String; Liste: TStrings); var n: Integer; begin Liste.Clear; Chaine := LowerCase(Trim(Chaine)); KeyWord := LowerCase(Trim(KeyWord)); While Pos(KeyWord, Chaine) <> 0 do begin Delete(Chaine, 1, Pos(KeyWord, Chaine) + Length(KeyWord) -1); n := Pos(' ', Chaine); if n = 0 then n := Length(Chaine) +1; Liste.Add(Copy(Chaine, 1, n -1)); end; end; function SupprimeCaractereNonAffichable(Texte: String): String; var n: Integer; begin Result := Texte; for n := 1 to length(Result) do if (Result[n] < #32) and (Result[n] <> #10) and (Result[n] <> #13) then Result := FindAndReplaceAll(Result, Result[n], #13#10); end; function SupprimeRetourChariot(Texte: String): String; var n: Integer; begin Result := ''; for n := 1 to length(Texte) do if Texte[n] = #10 then Result := Result + ' ' else if Texte[n] <> #13 then Result := Result + Texte[n]; end; procedure PositionneToutControle(MyForm: TForm; Value: Boolean); var n: Integer; begin //exit; With MyForm do begin for n := 0 to MyForm.ComponentCount -1 do begin if Value then begin if Components[n] is TButton then (Components[n] as TButton).Enabled := Boolean(Components[n].Tag); if Components[n] is TSpeedButton then (Components[n] as TSpeedButton).Enabled := Boolean(Components[n].Tag); if Components[n] is TToolButton then (Components[n] as TToolButton).Enabled := Boolean(Components[n].Tag); if Components[n] is TMenuItem then (Components[n] as TMenuItem).Enabled := Boolean(Components[n].Tag); if Components[n] is TDBGrid then (Components[n] as TDBGrid).Enabled := Boolean(Components[n].Tag); if Components[n] is TDBCheckBox then (Components[n] as TDBCheckBox).Enabled := Boolean(Components[n].Tag); if Components[n] is TTreeView then (Components[n] as TTreeView).Enabled := Boolean(Components[n].Tag); end else begin if Components[n] is TButton then With (Components[n] as TButton) do begin Tag := Integer(Enabled); Enabled := False; end; if Components[n] is TSpeedButton then With (Components[n] as TSpeedButton) do begin Tag := Integer(Enabled); Enabled := False; end; if Components[n] is TToolButton then With (Components[n] as TToolButton) do begin Tag := Integer(Enabled); Enabled := False; end; if Components[n] is TMenuItem then With (Components[n] as TMenuItem) do begin Tag := Integer(Enabled); Enabled := False; end; if Components[n] is TDBGrid then With (Components[n] as TDBGrid) do begin Tag := Integer(Enabled); Enabled := False; end; if Components[n] is TDBCheckBox then With (Components[n] as TDBCheckBox) do begin Tag := Integer(Enabled); Enabled := False; end; if Components[n] is TTreeView then With (Components[n] as TTreeView) do begin Tag := Integer(Enabled); Enabled := False; end; end; end; end; end; function GetaWordFromKey(Chaine, KeyWord, Sep: String): String; begin Result := ''; if Pos(KeyWord, Chaine) > 0 then begin Delete(Chaine, 1, Pos(KeyWord, Chaine) + Length(KeyWord) -1); if Pos(Sep, Chaine) > 0 then Result := Copy(Chaine, 1, Pos(Sep, Chaine) -1) else Result := Chaine; end; end; function GetaWordFromIndex(Chaine: String; Index: Integer; Sep: String): String; begin Result := ''; if index > 0 then begin Delete(Chaine, 1, Index -1); if Pos(Sep, Chaine) > 0 then Result := Copy(Chaine, 1, Pos(Sep, Chaine) -1) else Result := Chaine; end; end; function PosFrom(Substr, Str: String; Index: Integer): Integer; var n: Integer; begin Delete(Str, 1, Index -1); n := Pos(Substr, str); if n = 0 then Result := 0 else Result := Index + n -1; end; procedure Temporisation(t: Integer); var TempsMax: TDateTime; begin TempsMax := Now + (t / 2246400000); Repeat Application.ProcessMessages; Until Now > TempsMax; end; function NormalizeRequetePourDB(Requete: String): String; begin Result := FindAndReplaceAll(Requete, 'upper(a.tout)', 'a.tout'); Result := FindAndReplaceAll(Result, 'upper(a.objet)', 'a.upperobjet'); Result := FindAndReplaceAll(Result, #10, ' '); Result := FindAndReplaceAll(Result, #13, ' '); Result := FindAndReplaceAll(Result, '( ', '('); Result := FindAndReplaceAll(Result, ' )', ')'); Result := FindAndReplaceAll(Result, ' ', ' '); end; function NormalizeRequetePourIB(Requete: String): String; begin Result := FindAndReplaceAll(Requete, 'upper(a.tout)', 'a.tout'); Result := FindAndReplaceAll(Result, #10, ' '); Result := FindAndReplaceAll(Result, #13, ' '); Result := FindAndReplaceAll(Result, '( ', '('); Result := FindAndReplaceAll(Result, ' )', ')'); Result := FindAndReplaceAll(Result, ' ', ' '); end; function NormalizeDecimalSeparator(Value: String): String; begin Result := Value; Result := StringReplace(Result, ',', #2, [rfReplaceAll]); Result := StringReplace(Result, '.', #2, [rfReplaceAll]); Result := StringReplace(Result, #2, DecimalSeparator, [rfReplaceAll]); end; function FormatMonnaieChaine(Value: String; Decimal: Byte): String; begin Result := NormalizeDecimalSeparator(Value); if Pos(DecimalSeparator, Result) = 0 then Result := Result + DecimalSeparator; While (Length(Result) - Pos(DecimalSeparator, Result)) < Decimal do Result := Result + '0'; end; {***************************************************************} { Fonctions Gestion Disque } {***************************************************************} function VerifyDirectoryName(Var Name : String): Boolean; begin Result := False; if trim(Name) = '' then Exit; Name := FindAndReplaceAll(Name, '\\', '\'); if Name[Length(Name)] = '\' then Name := copy(Name,1,Length(Name)-1); if (Name[Length(Name)] = ':') then Exit; Result := True; end; procedure CheckDirectory(dir: string; CreateDir: TCreateDir); var Attr: Integer; s: string; n: word; begin s := LowerCase(Dir); s := Dir; if not VerifyDirectoryName(S) then Exit; Attr := FileGetAttr(s); if Attr < 0 then begin if CreateDir = cdirNo then raise Exception.create('Répertoire ' + s + ' non trouvé'); if (CreateDir = cdirConfirm) or (CreateDir = cdirConfirmEach) then if BoiteMessage('Répertoire ' + s + ' non trouvé' + RC + 'Voulez vous le créer ?', 'Répertoire non trouvé', Mb_IconQuestion + Mb_YesNo) <> IdYes then raise Exception.create('Répertoire ' + s + ' non trouvé'); for n := Length(s) downto 1 do begin if s[n] = '\' then begin if (CreateDir = cdirConfirmEach) then CheckDirectory(Copy(s,1,n-1), cdirConfirmEach) else CheckDirectory(Copy(s,1,n-1), cdirYes); Break; end; end; MkDir(s); end else if (Attr and faDirectory) = 0 then raise Exception.create('Le fichier ' + s + ' n''est pas un répertoire'); end; { Equivalent de la commande Dir } procedure LireDir(FileName: String; Attr: Integer; ListDir: TStrings); var SearchRec: TSearchRec; begin try ListDir.Clear; //PushC(crHourGlass); if FindFirst(FileName, Attr, SearchRec) = 0 then begin ListDir.Add(ExtractFilePath(FileName) + SearchRec.Name); While FindNext(SearchRec) = 0 do ListDir.Add(ExtractFilePath(FileName) + SearchRec.Name); end; finally Sysutils.FindClose(SearchRec); //PopC; end; end; function NormalizeDirectoryName(Name : String): string; begin Result := Trim(Name); if Result = '' then Exit; Result := FindAndReplaceAll(Result, '\\', '\'); if Result[Length(Result)] <> '\' then Result := Result + '\'; end; function NormalizeFileName(Name : String): string; begin Result := Name; Result := FindAndReplaceAll(Result, '\\', '\'); if Length(Result) > 0 then if Result[Length(Result)] = '\' then Result := Copy(Result, 1, Length(Result) -1); end; procedure FDCopyFiles(FileName, DestDir: String; FailIfExist: Boolean); var FileList: TStringList; n: Integer; begin VerifyDirectoryName(DestDir); DestDir := DestDir + '\'; FileList := TStringList.Create; With FileList do try LireDir(FileName, faAnyFile, FileList); for n := 0 to count -1 do fb_CopyFile(Strings[n], DestDir + ExtractFileName(Strings[n]), False, FailIfExist); finally Free; end; end; procedure FDDeleteFiles(FileName: String); var FileList: TStringList; n: Integer; begin FileList := TStringList.Create; With FileList do try LireDir(FileName, faAnyFile, FileList); for n := 0 to count -1 do DeleteFile(PChar(Strings[n])); finally Free; end; end; procedure FDFileSetAttr(FileName: String; Attr: Integer); var FileList: TStringList; n: Integer; begin FileList := TStringList.Create; With FileList do try LireDir(FileName, faAnyFile, FileList); for n := 0 to count -1 do FileSetAttr(PChar(Strings[n]), Attr); finally Free; end; end; procedure FDRenameFiles(FileName, FileDest: String); var FileList: TStringList; n: Integer; begin FileList := TStringList.Create; FileDest := ExtractFilePath(FileDest) + ExtractFileNameBeforeExtension(FileDest); With FileList do try LireDir(FileName, faAnyFile, FileList); for n := 0 to count -1 do RenameFile(Strings[n], FileDest + ExtractFileExt(Strings[n])); finally Free; end; end; procedure DemanderConfirmationSiFichierExiste(FileName: String); begin if FileExists(FileName) then if BoiteMessage('Le fichier "' + ExtractFileName(FileName) + '" existe déja.' + RC + 'Ecraser ?', 'Fichier existant', Mb_IconQuestion + Mb_YesNo + mb_DefButton2) <> IdYes then Abort; end; procedure GetFile(DirName, FileMask: String; Attr: Integer; ListDir: TStrings); // Lit la liste des dossiers procedure GetDirList(DirName: String; DirList: TStrings); var SearchRec: TSearchRec; begin try if FindFirst(DirName + '*.*', faAnyFile , SearchRec) = 0 then begin if ((SearchRec.Attr and faDirectory) <> 0) and(SearchRec.Name <> '..') and (SearchRec.Name <> '.') then begin DirList.Add(NormalizeDirectoryName(DirName + SearchRec.Name)); GetDirList(NormalizeDirectoryName(DirName + SearchRec.Name), DirList) end; While FindNext(SearchRec) = 0 do begin if ((SearchRec.Attr and faDirectory) <> 0) and (SearchRec.Name <> '..') and (SearchRec.Name <> '.') then begin DirList.Add(NormalizeDirectoryName(DirName + SearchRec.Name)); GetDirList(NormalizeDirectoryName(DirName + SearchRec.Name), DirList) end; end; end; finally Sysutils.FindClose(SearchRec); end; end; // Lit les fichiers d'un dossier procedure GetFileOfDir(DirName: String; Attr: Integer; FileList: TStrings); var SearchRec: TSearchRec; begin try if FindFirst(DirName, Attr, SearchRec) = 0 then begin if ((SearchRec.Attr and faDirectory) = 0) and (SearchRec.Name <> '..') and (SearchRec.Name <> '.') then begin FileList.Add(ExtractFilePath(DirName) + SearchRec.Name); end; While FindNext(SearchRec) = 0 do begin if ((SearchRec.Attr and faDirectory) = 0) and (SearchRec.Name <> '..') and (SearchRec.Name <> '.') then begin FileList.Add(ExtractFilePath(DirName) + SearchRec.Name); end; end; end; finally Sysutils.FindClose(SearchRec); end; end; var DirList: TStringList; n: Integer; begin DirList := TStringList.Create; try PushC(crHourGlass); GetFileOfDir(DirName + FileMask, Attr, ListDir); GetDirList(DirName, DirList); With DirList do for n := 0 to count -1 do GetFileOfDir(Strings[n] + FileMask, Attr, ListDir); finally DirList.Free; PopC; end; end; {***************************************************************} { Fonctions Curseur Souris } {***************************************************************} procedure PushC(MCursor : TCursor); begin PushCursor[MSIndex] := Screen.Cursor; MSIndex := MSIndex + 1; Screen.Cursor := MCursor; end; procedure PopC; begin if MSIndex <> 0 then begin MSIndex := MSIndex - 1; Screen.Cursor := PushCursor[MSIndex]; end; end; procedure DrawCheckBox(Canvas: TCanvas; Rect: TRect); begin With Canvas do begin Brush.Color := clWindow; FillRect(Rect); Pen.Color := ClGrayText; MoveTo(Rect.Left, Rect.Bottom); LineTo(Rect.Left, Rect.Top); LineTo(Rect.Right, Rect.Top); Pen.Color := ClBlack; MoveTo(Rect.Left +1, Rect.Bottom); LineTo(Rect.Left +1, Rect.Top +1); LineTo(Rect.Right -1, Rect.Top +1); Pen.Color := ClWhite; LineTo(Rect.Right -1, Rect.Top +1); LineTo(Rect.Right -1, Rect.Bottom -1); LineTo(Rect.Left, Rect.Bottom -1); Pen.Color := ClBtnFace; MoveTo(Rect.Right -2, Rect.Top +2); LineTo(Rect.Right -2, Rect.Bottom -2); LineTo(Rect.Left, Rect.Bottom -2); // Rectangle(Rect); end; end; function Arrondie(Value: Double; Decimal: Byte): Double; var Mult: Integer; n: Byte; begin Mult := 1; for n := 1 to Decimal do Mult := Mult * 10; Result := Round(Value * Mult) / Mult; end; end.
{ Laz-Model Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde Portions (C) 2016 Peter Dyson. Initial Lazarus port This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit uIntegrator; {$mode objfpc}{$H+} interface uses Classes, Contnrs, SysUtils, Dialogs, uModel, uCodeProvider, uError, uUseful, uCodeParser; type TIntegrator = class(TComponent) private FModel: TObjectModel; public constructor Create(om: TObjectModel); reintroduce; destructor Destroy; override; property Model: TObjectModel read FModel; end; TTwowayIntegrator = class(TIntegrator) public procedure InitFromModel; virtual; procedure BuildModelFrom(FileName : string); virtual; end; TExportIntegrator = class(TIntegrator) public procedure InitFromModel; virtual; abstract; end; TImportIntegrator = class(TIntegrator) protected CodeProvider: TCodeProvider; FilesRead : TStringList; procedure ImportOneFile(const FileName : string); virtual; abstract; public constructor Create(om: TObjectModel; ACodeProvider: TCodeProvider); reintroduce; destructor Destroy; override; procedure BuildModelFrom(FileName : string; ResetModel : boolean = True; Lock : boolean = True); overload; procedure BuildModelFrom(FileNames : TStrings); overload; class function GetFileExtensions : TStringList; virtual; abstract; end; TIntegratorClass = class of TIntegrator; TImportIntegratorClass = class of TImportIntegrator; TIntegrators = class private List : TClassList; public constructor Create; destructor Destroy; override; procedure Register(T: TIntegratorClass); function Get(Kind : TIntegratorClass) : TClassList; end; function Integrators : TIntegrators; implementation var _Integrators : TIntegrators = nil; constructor TIntegrator.Create(om: TObjectModel); begin inherited Create(nil); FModel := om; end; destructor TIntegrator.Destroy; begin inherited; FModel := nil; end; procedure TTwowayIntegrator.BuildModelFrom(FileName : string); begin //Stub end; procedure TTwowayIntegrator.InitFromModel; begin //Stub end; procedure TImportIntegrator.BuildModelFrom(FileName: string; ResetModel: boolean; Lock : boolean); begin CodeProvider.AddSearchPath(ExtractFilePath(FileName)); if Lock then Model.Lock; if ResetModel then begin Model.Clear; Model.ModelRoot.SetConfigFile(FileName); end; FilesRead.Add(FileName); try try ImportOneFile(FileName); except on E : EParseError do ShowMessage(E.Message); end; finally if Lock then Model.Unlock; end; end; procedure TImportIntegrator.BuildModelFrom(FileNames: TStrings); var I : integer; P : IEldeanProgress; begin Model.Lock; try // Add all searchpaths first so the units can find eachother. for I := 0 to FileNames.Count-1 do CodeProvider.AddSearchPath(ExtractFilePath(FileNames[I])); // 'Build' all files.. if FileNames.Count>3 then P := TEldeanProgress.Create('Reading files...',FileNames.Count); for I := 0 to FileNames.Count-1 do begin if FilesRead.IndexOf( FileNames[I] )=-1 then BuildModelFrom(FileNames[I], I=0, False) else ErrorHandler.Trace('Skipping file, already parsed: ' + FileNames[I]); if P<>nil then P.Tick; end; finally Model.UnLock; end; end; constructor TImportIntegrator.Create(om: TObjectModel; ACodeProvider: TCodeProvider); begin inherited Create(Om); Self.CodeProvider := ACodeProvider; FilesRead := TStringList.Create; FilesRead.Sorted := True; FilesRead.Duplicates := dupIgnore; end; destructor TImportIntegrator.Destroy; begin CodeProvider.Free; FilesRead.Free; inherited; end; constructor TIntegrators.Create; begin List := TClassList.Create; end; destructor TIntegrators.Destroy; begin List.Free; end; function TIntegrators.Get(Kind: TIntegratorClass): TClassList; var I : integer; begin Result := TClassList.Create; for I := 0 to List.Count - 1 do if List[I].InheritsFrom(Kind) then Result.Add(List[I]); end; procedure TIntegrators.Register(T: TIntegratorClass); begin List.Add(T); end; function Integrators : TIntegrators; begin if _Integrators=nil then _Integrators := TIntegrators.Create; Result := _Integrators; end; initialization finalization if Assigned(_Integrators) then _Integrators.Free; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLRenderContextInfo<p> Stores contextual info useful during rendering methods.<p> <b>History : </b><font size=-1><ul> <li>22/02/10 - Yar - Added bufferLighting, bufferFog, bufferDepthTest to TRenderContextInfo <li>14/03/09 - DanB - Removed IsVolumeClipped functions, instead replaced with IsVolumeClipped functions in GLVectorGeometry.pas that use TFrustrum <li>09/10/08 - DanB - Added TRenderContextClippingInfo + IsVolumeClipped functions from GLVectorGeometry.pas, added nearClippingDistance <li>05/10/08 - DanB - Created from GLTexture.pas split </ul></font> } unit GLRenderContextInfo; interface uses GLPersistentClasses, GLVectorGeometry, GLState, GLColor; type TDrawState = (dsRendering, dsPicking, dsPrinting); TGLSize = record cx : Longint; cy : Longint; end; // TGLObjectsSorting // {: Determines if objects are sorted, and how.<p> Sorting is done level by level (and not for all entities), values are :<ul> <li>osInherited : use inherited sorting mode, defaults to osRenderFarthestFirst <li>osNone : do not sort objects. <li>osRenderFarthestFirst : render objects whose Position is the farthest from the camera first. <li>osRenderBlendedLast : opaque objects are not sorted and rendered first, blended ones are rendered afterwards and depth sorted. <li>osRenderNearestFirst : render objects whose Position is the nearest to the camera first. </ul> } TGLObjectsSorting = (osInherited, osNone, osRenderFarthestFirst, osRenderBlendedLast, osRenderNearestFirst); // TGLVisibilityCulling // {: Determines the visibility culling mode. Culling is done level by level, allowed values are:<ul> <li>vcInherited : use inherited culling value, if selected for the root level, defaults to vcNone <li>vcNone : no visibility culling is performed <li>vcObjectBased : culling is done on a per-object basis, each object may or may not be culled base on its own AxisAlignedDimensions, culling has no impact on the visibility of its children <li>vcHierarchical : culling is performed hierarchically, using hierarchical bounding boxes, if a parent is culled, all of its children, whatever their culling options are invisible. <li><br>Depending on the structure of your scene the most efficient culling method will be either vcObjectBased or vcHierarchical. Also note that if you use many objects with "static" geometry and have a T&amp;L graphics board, it may be faster not to cull at all (ie. leave this to the hardware). } TGLVisibilityCulling = (vcInherited, vcNone, vcObjectBased, vcHierarchical); // TRenderContextClippingInfo // TRenderContextClippingInfo = record origin : TVector; clippingDirection : TVector; viewPortRadius : Single; // viewport bounding radius per distance unit nearClippingDistance : Single; farClippingDistance : Single; frustum : TFrustum; end; // TRenderContextInfo // {: Stores contextual info useful during rendering methods. } TRenderContextInfo = record scene : TObject; //usually TGLScene buffer : TObject; //usually TGLSceneBuffer cameraPosition : TVector; cameraDirection, cameraUp : TVector; modelViewMatrix : PMatrix; viewPortSize : TGLSize; renderDPI : Integer; materialLibrary : TObject; //usually TGLMaterialLibrary; lightmapLibrary : TObject; //usually TGLMaterialLibrary; fogDisabledCounter : Integer; lightingDisabledCounter : Integer; drawState : TDrawState; objectsSorting : TGLObjectsSorting; visibilityCulling : TGLVisibilityCulling; GLStates : TGLStateCache; rcci : TRenderContextClippingInfo; sceneAmbientColor : TColorVector; bufferFaceCull : Boolean; bufferLighting : Boolean; bufferFog : Boolean; bufferDepthTest : Boolean; proxySubObject : Boolean; ignoreMaterials : Boolean; ignoreBlendingRequests : Boolean; ignoreDepthRequests : Boolean; amalgamating : Boolean; lights: TPersistentObjectList; afterRenderEffects: TPersistentObjectList; end; PRenderContextInfo = ^TRenderContextInfo; implementation end.
unit UTemplateDreVO; interface uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO, UCondominioVO; type [TEntity] [TTable('TemplateDre')] TTemplateDreVO = class(TGenericVO) private FidDre : Integer; FidTemplate : Integer; Fclassificacao : String; FflTipo : String; Fordem : String; Ftotal : string; FidCondominio : Integer; Fdescricao : String; public CondominioVO : TCondominioVO; [TId('idDre')] [TGeneratedValue(sAuto)] property idDre : Integer read FidDre write FidDre; [TColumn('idTemplate','Template',0,[ldLookup,ldComboBox], False)] property idTemplate: Integer read FidTemplate write FidTemplate; [TColumn('classificacao','Classificação',200,[ldGrid,ldLookup,ldComboBox], False)] property Classificacao: string read FClassificacao write FClassificacao; [TColumn('descricao','Descrição',400,[ldGrid,ldLookup,ldComboBox], False)] property descricao: string read Fdescricao write Fdescricao; [TColumn('flTipo','Tipo',10,[ldLookup,ldComboBox], False)] property flTipo: string read FflTipo write FflTipo; [TColumn('idCondominio','Condomínio',0,[ldLookup,ldComboBox], False)] property idcondominio: integer read Fidcondominio write Fidcondominio; [TColumn('ordem','Ordem',10,[ldLookup,ldComboBox], False)] property ordem: string read Fordem write Fordem; [TColumn('total','Total',10,[ldLookup,ldComboBox], False)] property total: string read Ftotal write Ftotal; procedure ValidarCamposObrigatorios; end; implementation procedure TTemplateDreVO.ValidarCamposObrigatorios; begin { if (self.FidTemplate = 0) then begin raise Exception.Create('O campo Código é obrigatório!'); end;} if (Self.Fclassificacao = '') then begin raise Exception.Create('O campo Classificação é obrigatório!'); end; if (Self.Fordem = '' )then begin raise Exception.Create('O campo Ordem é obrigatório!'); end; if (self.Fdescricao = '') then begin raise Exception.Create('O campo Descrição é obrigatório!'); end; if (self.FflTipo = '') then begin raise Exception.Create('O campo Tipo é obrigatório!'); end; end; end.
unit uPOSServerTypes; interface type TServerConnection = class private fClientInfo : String; fClientVersion : String; fConnectionTimeOut : Integer; fConnectType : Integer; fPort : Integer; fPOSDir : String; fUser : String; fPW : String; fGlobalDir : String; fFTP : String; public property ClientInfo : String read fClientInfo write fClientInfo; property ClientVersion : String read fClientVersion write fClientVersion; property ConnectionTimeOut : Integer read fConnectionTimeOut write fConnectionTimeOut; property ConnectType : Integer read fConnectType write fConnectType; property FTP : String read fFTP write fFTP; property Port : Integer read fPort write fPort; property User : String read fUser write fUser; property PW : String read fPW write fPW; property GlobalDir : String read fGlobalDir write fGlobalDir; property POSDir : String read fPOSDir write fPOSDir; end; TLocalSetting = class private fIDStoreList : String; fIDDefaulStore : String; fDeleteLog: TDateTime; public property IDDefaulStore : String read fIDDefaulStore write fIDDefaulStore; property IDStoreList : String read fIDStoreList write fIDStoreList; property DeleteLog : TDateTime read fDeleteLog write fDeleteLog; end; TCashRegInfo = class public IDCashreg: Integer; CashRegName: String; LastImportDate: TDateTime; LastImportedFileName: String; LastImportedFileDate: String; IncludeSince: String; end; TOnNeedWriteIniBool = procedure (ASection, AKey: String; AValue: Boolean) of object; TOnNeedWriteIniDateTime = procedure (ASection, AKey: String; AValue: TDateTime) of object; TOnNeedWriteIniString = procedure (ASection, AKey: String; AValue: String) of object; TOnNeedWriteIniInteger = procedure (ASection, AKey: String; AValue: Integer) of object; TSyncLogEvent = procedure(Sender: TObject; const Text: string) of object; TPOSServerStatusEvent = procedure (Msg: String; Count: Integer ) of Object; TPOSServerStepCompleted = procedure of Object; TPOSServerCompleted = procedure of Object; TOnSaveNextSchedule = procedure (sType:String) of object; implementation end.
unit ThItem; interface uses System.Classes, System.Types, System.UITypes, System.UIConsts, System.SysUtils, FMX.Controls, FMX.Types, ThTypes, System.Generics.Collections; type TThItem = class; TThItems = TList<TThItem>; TItemEvent = procedure(Item: TThItem) of object; TItemSelectedEvent = procedure(Item: TThItem; IsMultiSelect: Boolean) of object; TItemMoveEvent = procedure(Item: TThItem; DistancePos: TPointF) of object; TItemResizeEvent = procedure(Item: TThItem; BeforeRect: TRectF) of object; TItemResizingEvent = procedure(Item: TThItem; SpotCorner: TSpotCorner; X, Y: Single; SwapHorz, SwapVert: Boolean) of object; TItemListEvent = procedure(Items: TThItems) of object; TItemListPointvent = procedure(Items: TThItems; Distance: TPointF) of object; TThItemData = class(TInterfacedObject, IThItemData) end; // Item을 담는 객체는 상속받아야 한다. IThItemContainer = interface ['{76A11805-EA40-40B6-84A1-71B4DF277DCD}'] function GetItem(Index: Integer): TThItem; function GetItemCount: Integer; property Items[Index: Integer]: TThItem read GetItem; property ItemCount: Integer read GetItemCount; function FindParent(AItem: TThItem): TFMXObject; procedure ContainChildren(AContainer: TThItem); procedure DoAddObject(const AObject: TFmxObject); procedure DoRemoveObject(const AObject: TFmxObject); end; TThItem = class(TControl, IThItem, IThItemContainer) private FParentCanvas: IThCanvas; FSpotCount: Integer; FOnSelected: TItemSelectedEvent; FOnUnselected: TItemEvent; FOnTracking: TTrackingEvent; FOnMove: TItemMoveEvent; FOnResize: TItemResizeEvent; // 최종 포함된 자식 목록(Undo시 필요) FLastContainItems: TThItems; FOnResizing: TItemResizingEvent; procedure SetSelected(const Value: Boolean); procedure SetParentCanvas(const Value: IThCanvas); function GetBeforendex: Integer; function GetBeforeParent: TFmxObject; procedure SetBeforeIndex(const Value: Integer); procedure SetBeforeParent(const Value: TFmxObject); function GetAbsolutePoint: TPointF; overload; function GetAbsolutePoint(APoint: TPointF): TPointF; overload; function GetItem(Index: Integer): TThItem; function GetItemCount: Integer; function GetIsParentSelected: Boolean; protected FHighlighter: IItemHighlighter; FSelection: IItemSelection; FBeforeSelect, FSelected: Boolean; FMouseDownPos, FDownItemPos: TPointF; procedure DoAddObject(const AObject: TFmxObject); override; procedure DoRemoveObject(const AObject: TFmxObject); override; procedure DoResizing(SpotCorner: TSpotCorner; X, Y: Single; SwapHorz, SwapVert: Boolean); virtual; function CreateHighlighter: IItemHighlighter; virtual; function CreateSelection: IItemSelection; virtual; procedure SpotTracking(SpotCorner: TSpotCorner; X, Y: Single; SwapHorz, SwapVert: Boolean); virtual; function DoGetUpdateRect: TRectF; override; function GetItemRect: TRectF; virtual; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure DoMouseEnter; override; procedure DoMouseLeave; override; // Virtual method procedure DoSelected(Value: Boolean; IsMultiSelect: Boolean = False); virtual; function PtInItem(Pt: TPointF): Boolean; virtual; abstract; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Items[Index: Integer]: TThItem read GetItem; property ItemCount: Integer read GetItemCount; procedure SetItemData(AItemData: IThItemData); virtual; procedure Painting; override; function PointInObject(X, Y: Single): Boolean; override; procedure ItemResizeBySpot(Sender: TObject; BeforeRect: TRectF); procedure DrawItemAtMouse(AFrom, ATo: TPointF); virtual; procedure RealignSpot; procedure ShowSpots; procedure ShowDisableSpots; function FindParent(AChild: TThItem): TFMXObject; procedure ContainChildren(AContainer: TThItem); procedure ReleaseChildren; function IsContain(AChild: TThItem): Boolean; virtual; property ParentCanvas: IThCanvas read FParentCanvas write SetParentCanvas; property Selected: Boolean read FSelected write SetSelected; property IsParentSelected: Boolean read GetIsParentSelected; property BeforeParent: TFmxObject read GetBeforeParent write SetBeforeParent; property BeforeIndex: Integer read GetBeforendex write SetBeforeIndex; property LastContainItems: TThItems read FLastContainItems; property AbsolutePoint: TPointF read GetAbsolutePoint; property OnSelected: TItemSelectedEvent read FOnSelected write FOnSelected; property OnUnselected: TItemEvent read FOnUnselected write FOnUnselected; property OnTracking: TTrackingEvent read FOnTracking write FOnTracking; property OnMove: TItemMoveEvent read FOnMove write FOnMove; property OnResize: TItemResizeEvent read FOnResize write FOnResize; property OnResizing: TItemResizingEvent read FOnResizing write FOnResizing; end; TThItemClass = class of TThItem; TThFileItemData = class(TThItemData) private FFilename: TFileName; public constructor Create(AFileName: TFileName); property Filename: TFileName read FFilename; end; implementation uses ThConsts, DebugUtils; { TThItem } constructor TThItem.Create(AOwner: TComponent); begin inherited Create(AOwner); Cursor := crSizeAll; AutoCapture := True; // Resize, Move 등의 마지막 액션으로 추가된 자식들 FLastContainItems := TList<TThItem>.Create; {$IFDEF ON_HIGHLIGHT} FHighlighter := CreateHighlighter; {$ENDIF} FSelection := CreateSelection; FSpotCount := 0; if Assigned(FSelection) then FSpotCount := FSelection.Count; end; destructor TThItem.Destroy; begin FHighlighter := nil; FSelection := nil; // Interface Free(destory) FLastContainItems.Free; inherited; end; procedure TThItem.ContainChildren(AContainer: TThItem); var I: Integer; CurrItem: TThItem; begin AContainer.LastContainItems.Clear; for I := 0 to ItemCount - 1 do begin CurrItem := Items[I]; if not Assigned(CurrItem) or (AContainer = CurrItem) then Continue; if AContainer.IsContain(CurrItem) then // CurrItem.Parent := AParent; // 여기서 Parent를 바꾸면 Items / ItemCount가 줄어듬 AContainer.LastContainItems.Add(CurrItem); end; for CurrItem in AContainer.LastContainItems do begin CurrItem.Parent := AContainer; AContainer.ContainChildren(CurrItem); end; end; procedure TThItem.SpotTracking(SpotCorner: TSpotCorner; X, Y: Single; SwapHorz, SwapVert: Boolean); begin DoResizing(SpotCorner, X, Y, SwapHorz, SwapVert); end; procedure TThItem.ReleaseChildren; var I: Integer; CurrItem: TThItem; NewParent: TFmxObject; ItemContainer: IThItemContainer; begin // e.g. // 1> 크기변경 시 자식이 범위에 없을 경우(분리 할 경우) // 부모의 자식(형재) 중에서 찾는다. // 포함하는 형재가 없을 경우 부모를 부모로 설정한다. LastContainItems.Clear; for I := 0 to ItemCount - 1 do begin CurrItem := Items[I]; if not (CurrItem is TThItem) then Continue; if not IsContain(CurrItem) then // 여기서 Parent를 바꾸면 Items / ItemCount가 줄어듬 // CurrItem.Parent := AParent; LastContainItems.Add(CurrItem); end; for CurrItem in LastContainItems do begin NewParent := nil; if Supports(Parent, IThItemContainer, ItemContainer) then NewParent := ItemContainer.FindParent(CurrItem); if Assigned(NewParent) then CurrItem.Parent := NewParent else CurrItem.Parent := Parent; end; end; procedure TThItem.SetBeforeIndex(const Value: Integer); begin Tag := Value; end; procedure TThItem.SetBeforeParent(const Value: TFmxObject); begin TagObject := Value; end; procedure TThItem.SetItemData(AItemData: IThItemData); begin end; procedure TThItem.SetParentCanvas(const Value: IThCanvas); begin FParentCanvas := Value; Parent := TFMXObject(Value); BeforeParent := TFMXObject(Value); end; function TThItem.CreateHighlighter: IItemHighlighter; begin end; function TThItem.CreateSelection: IItemSelection; begin end; procedure TThItem.Painting; begin inherited; {$IFDEF ON_HIGHLIGHT} if (IsMouseOver) and Assigned(FHighlighter) then FHighlighter.DrawHighlight; {$ENDIF} if (IsMouseOver or Selected) and Assigned(FSelection) then FSelection.DrawSelection; end; function TThItem.PointInObject(X, Y: Single): Boolean; var P: TPointF; begin Result := False; if IThCanvas(ParentCanvas).IsDrawingItem then Exit; P := AbsoluteToLocal(PointF(X, Y)); Result := PtInItem(P); end; function TThItem.IsContain(AChild: TThItem): Boolean; begin Result := False; end; procedure TThItem.ItemResizeBySpot(Sender: TObject; BeforeRect: TRectF); begin if Assigned(FOnResize) then FOnResize(Self, BeforeRect); end; procedure TThItem.DoMouseEnter; begin inherited; Repaint; end; procedure TThItem.DoMouseLeave; begin inherited; Repaint; end; procedure TThItem.DoAddObject(const AObject: TFmxObject); // AObject.Parent = nil 임 var Item: TThItem; P: TPointF; begin if AObject is TThItem then begin Item := TThItem(AObject); // if Assigned(Item.BeforeParent) and (Item.BeforeParent is TThItem) then P := TThItem(Item.BeforeParent).AbsolutePoint else P := PointF(0, 0); // Item.Position.Point := P.Subtract(AbsolutePoint).Add(Item.Position.Point); Item.Position.Point := P - AbsolutePoint + Item.Position.Point; end; inherited; end; procedure TThItem.DoRemoveObject(const AObject: TFmxObject); var Item: TThItem; begin if not (csDestroying in ComponentState) and (AObject is TThItem) then begin Item := TThItem(AObject); Item.BeforeParent := Self; Item.BeforeIndex := AObject.Index; end; // 초기화 전에 하장 inherited; end; procedure TThItem.DoResizing(SpotCorner: TSpotCorner; X, Y: Single; SwapHorz, SwapVert: Boolean); begin if Assigned(FOnResizing) then FOnResizing(Self, SpotCorner, X, Y, SwapHorz, SwapVert); end; procedure TThItem.DrawItemAtMouse(AFrom, ATo: TPointF); begin end; function TThItem.FindParent(AChild: TThItem): TFMXObject; var I: Integer; CurrItem: TThItem; begin Result := nil; for I := ItemCount - 1 downto 0 do begin CurrItem := Items[I]; if not Assigned(CurrItem) or (CurrItem = AChild) then Continue; if CurrItem.IsContain(AChild) then begin Result := CurrItem.FindParent(AChild); if not Assigned(Result) then begin Result := CurrItem; Exit; end; end; end; end; function TThItem.GetAbsolutePoint: TPointF; begin Result := GetAbsolutePoint(PointF(0, 0)); end; function TThItem.GetAbsolutePoint(APoint: TPointF): TPointF; begin // Result := APoint.Add(Position.Point); Result := APoint + Position.Point; if Parent is TThItem then Result := TThItem(Parent).GetAbsolutePoint(Result); end; function TThItem.GetBeforendex: Integer; begin Result := Tag; end; function TThItem.GetBeforeParent: TFmxObject; begin Result := TFMXObject(TagObject); end; function TThItem.GetIsParentSelected: Boolean; begin if Parent is TThItem then begin Result := TThItem(Parent).Selected; if not Result then Result := TThItem(Parent).IsParentSelected end else Result := False; end; function TThItem.GetItem(Index: Integer): TThItem; var Obj: TFmxObject; begin Result := nil; Obj := Children[Index + FSpotCount]; if (Children.Count > Index + FSpotCount) and (Obj is TThItem) then Result := TThItem(Children[Index + FSpotCount]); end; function TThItem.GetItemCount: Integer; var Obj: TFmxObject; begin // Result := ChildrenCount - FSpotCount; Result := 0; for Obj in Children do if Obj is TThItem then Inc(Result); end; function TThItem.GetItemRect: TRectF; begin Result := LocalRect; end; function TThItem.DoGetUpdateRect: TRectF; begin Result := inherited DoGetUpdateRect; InflateRect(Result, ItemResizeSpotRadius, ItemResizeSpotRadius); InflateRect(Result, 1, 1); end; procedure TThItem.RealignSpot; begin if Assigned(FSelection) then FSelection.RealignSpot; end; procedure TThItem.ShowDisableSpots; begin if Assigned(FSelection) then FSelection.ShowDisableSpots; end; procedure TThItem.ShowSpots; begin if Assigned(FSelection) then FSelection.ShowSpots; end; procedure TThItem.SetSelected(const Value: Boolean); begin DoSelected(Value); end; procedure TThItem.DoSelected(Value: Boolean; IsMultiSelect: Boolean); begin if FSelected = Value then Exit; FSelected := Value; if Value and Assigned(FOnSelected) then FOnSelected(Self, IsMultiSelect) else if (not Value) and Assigned(FOnUnselected) then FOnUnselected(Self); if Assigned(FSelection) then begin if FSelected and FParentCanvas.IsMultiSelected then FSelection.ShowDisableSpots else if {(not FParentCanvas.IsMultiSelected) and} Value then FSelection.ShowSpots else FSelection.HideSpots; end; // 선택시는 다시 그릴 필요 없음(ResizeSpot만 추가되기 때문) if not FSelected then Repaint; end; procedure TThItem.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; if Button = TMouseButton.mbLeft then begin FBeforeSelect := FSelected; if (ssShift in Shift) or (ssCtrl in Shift) then DoSelected(True, True) else if not FSelected then DoSelected(True); FMouseDownPos := PointF(X, Y); FDownItemPos := Position.Point; end; InvalidateRect(UpdateRect); end; procedure TThItem.MouseMove(Shift: TShiftState; X, Y: Single); var Gap: TPointF; begin inherited; if Pressed then begin if FSelected and Assigned(FOnTracking) then begin Gap := PointF(X, Y) - FMouseDownPos; // Down and Move Gap FOnTracking(Self, Gap.X, Gap.Y); end; end; end; procedure TThItem.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; if Button = TMouseButton.mbLeft then begin if ((ssShift in Shift) or (ssCtrl in Shift)) and (FDownItemPos = Position.Point) and FBeforeSelect then DoSelected(False, True) else if (FDownItemPos <> Position.Point) and Assigned(FOnMove) then FOnMove(Self, Position.Point - FDownItemPos); // FOnMove(Self, Position.Point.Subtract(FDownItemPos)); end; end; { TThFileItem } constructor TThFileItemData.Create(AFileName: TFileName); begin FFilename := AFileName; end; end.
{ *************************************************************************** Copyright (c) 2016-2020 Kike Pérez Unit : Quick.Logger.Provider.Slack Description : Log Slack Bot Channel Provider Author : Kike Pérez Version : 1.22 Created : 24/05/2018 Modified : 24/04/2020 This file is part of QuickLogger: https://github.com/exilon/QuickLogger *************************************************************************** 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.Logger.Provider.Slack; {$i QuickLib.inc} interface uses Classes, SysUtils, {$IFDEF DELPHIXE8_UP} System.JSON, {$ELSE} IdHTTP, {$IFDEF FPC} fpjson, {$ELSE} {$IFDEF DELPHIXE7_UP} System.JSON, {$ENDIF} Data.DBXJSON, {$ENDIF} {$ENDIF} Quick.Commons, Quick.HttpClient, Quick.Logger; const SLACKWEBHOOKURL = 'https://hooks.slack.com/services/%s'; type TSlackChannelType = (tcPublic, tcPrivate); TLogSlackProvider = class (TLogProviderBase) private fHttpClient : TJsonHttpClient; fChannelName : string; fUserName : string; fWebHookURL : string; procedure SetChannelName(const Value: string); public constructor Create; override; destructor Destroy; override; property ChannelName : string read fChannelName write SetChannelName; property UserName : string read fUserName write fUserName; property WebHookURL : string read fWebHookURL write fWebHookURL; procedure Init; override; procedure Restart; override; procedure WriteLog(cLogItem : TLogItem); override; end; var GlobalLogSlackProvider : TLogSlackProvider; implementation constructor TLogSlackProvider.Create; begin inherited; LogLevel := LOG_ALL; fChannelName := ''; fWebHookURL := ''; IncludedInfo := [iiAppName,iiHost]; end; destructor TLogSlackProvider.Destroy; begin if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient); inherited; end; procedure TLogSlackProvider.Init; begin fHTTPClient := TJsonHttpClient.Create; fHTTPClient.ContentType := 'application/json'; fHTTPClient.UserAgent := 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'; fHTTPClient.HandleRedirects := True; inherited; end; procedure TLogSlackProvider.Restart; begin Stop; if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient); Init; end; procedure TLogSlackProvider.SetChannelName(const Value: string); begin if Value.StartsWith('#') then fChannelName := Value else fChannelName := '#' + Value; end; procedure TLogSlackProvider.WriteLog(cLogItem : TLogItem); var json : TJsonObject; resp : IHttpRequestResponse; begin if CustomMsgOutput then resp := fHttpClient.Post(fWebHookURL,LogItemToFormat(cLogItem)) else begin json := TJSONObject.Create; try json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('text',LogItemToText(cLogItem)); json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('username',fUserName); json.{$IFDEF FPC}Add{$ELSE}AddPair{$ENDIF}('channel',fChannelName); resp := fHttpClient.Post(fWebHookURL,json); finally json.Free; end; end; if resp.StatusCode <> 200 then raise ELogger.Create(Format('[TLogSlackProvider] : Response %d : %s (%s) trying to send event',[resp.StatusCode,resp.StatusText, {$IFDEF DELPHIXE8_UP} resp.Response.ToJSON])); {$ELSE} {$IFDEF FPC} resp.Response.AsJson])); {$ELSE} resp.Response.ToString])); {$ENDIF} {$ENDIF} end; initialization GlobalLogSlackProvider := TLogSlackProvider.Create; finalization if Assigned(GlobalLogSlackProvider) and (GlobalLogSlackProvider.RefCount = 0) then GlobalLogSlackProvider.Free; end.
unit rtti_serializer_uFactory; interface uses Classes, SysUtils, rtti_broker_iBroker, fgl, typinfo; type { ECacheException } ECacheException = class(Exception) public class procedure ClassAlreadyRegistered(const AClassName: string); class procedure ClassNotRegistered(const AClassName: string); class procedure ObjectInstanceHasNoIDProperty(const AObject: TObject); class procedure ObjectWithIDAlreadyExists(AObject: TObject; AID: integer); end; { TClassCache } TClassCache = class private type TCache = specialize TFPGMap<string, TClass>; private fCache: TCache; public constructor Create; destructor Destroy; override; procedure Add(AClass: TClass); function Find(const AClass: string): TClass; end; { TObjectCache } TObjectCache = class private type TCache = specialize TFPGMap<integer, TObject>; private fCache: TCache; protected function GetID(AObject: TObject): integer; public constructor Create; destructor Destroy; override; procedure Add(AObject: TObject); function Find(AID: integer): TObject; end; { TSerialFactory } TSerialFactory = class(TInterfacedObject, IRBFactory) private fClassCache: TClassCache; procedure SetAddClass(AValue: TClass); protected function GetClass(const AClass: string): TClass; // IRBFactory procedure RegisterClass(const AClass: TClass); function CreateObject(const AClass: string): TObject; function FindClass(const AClass: String): TClass; public constructor Create; destructor Destroy; override; procedure AfterConstruction; override; procedure BeforeDestruction; override; published property AddClass: TClass write SetAddClass; end; implementation { TObjectCache } function TObjectCache.GetID(AObject: TObject): integer; var mIDProp: PPropInfo; begin mIDProp := GetPropInfo(AObject, 'ID'); if mIDProp <> nil then Result := GetPropValue(AObject, 'ID') else ECacheException.ObjectInstanceHasNoIDProperty(AObject); end; constructor TObjectCache.Create; begin fCache := TCache.Create; end; destructor TObjectCache.Destroy; begin FreeAndNil(fCache); inherited Destroy; end; procedure TObjectCache.Add(AObject: TObject); var mID: integer; begin mID := GetID(AObject); if Find(mID) <> nil then ECacheException.ObjectWithIDAlreadyExists(AObject, mID); fCache.Add(mID, AObject); end; function TObjectCache.Find(AID: integer): TObject; var mIndex: integer; begin mIndex := fCache.IndexOf(AID); if mIndex > -1 then Result := fCache.Data[mIndex] else Result := nil; end; { ECacheException } class procedure ECacheException.ClassAlreadyRegistered( const AClassName: string); begin raise CreateFmt('Class %s is already registered', [AClassName]); end; class procedure ECacheException.ClassNotRegistered(const AClassName: string); begin raise CreateFmt('Cannot create object - class %s is not registered', [AClassName]); end; class procedure ECacheException.ObjectInstanceHasNoIDProperty( const AObject: TObject); begin raise CreateFmt('Cannot set ID - class %s do not have implemented ID property', [AObject.ClassName]); end; class procedure ECacheException.ObjectWithIDAlreadyExists(AObject: TObject; AID: integer); begin raise CreateFmt('Object %s with ID=%d already exists', [AObject.ClassName, AID]); end; { TSerialFactory } procedure TSerialFactory.SetAddClass(AValue: TClass); begin RegisterClass(AValue); end; function TSerialFactory.GetClass(const AClass: string): TClass; begin Result := FindClass(AClass); if Result = nil then ECacheException.ClassNotRegistered(AClass); end; procedure TSerialFactory.RegisterClass(const AClass: TClass); begin fClassCache.Add(AClass); end; function TSerialFactory.CreateObject(const AClass: string): TObject; var m: TClass; begin m := GetClass(AClass); Result := m.Create end; function TSerialFactory.FindClass(const AClass: String): TClass; begin Result := fClassCache.Find(AClass); end; constructor TSerialFactory.Create; begin end; destructor TSerialFactory.Destroy; begin inherited Destroy; end; procedure TSerialFactory.AfterConstruction; begin inherited AfterConstruction; fClassCache := TClassCache.Create; end; procedure TSerialFactory.BeforeDestruction; begin FreeAndNil(fClassCache); inherited BeforeDestruction; end; { TClassCache } constructor TClassCache.Create; begin fCache := TCache.Create; end; destructor TClassCache.Destroy; begin FreeAndNil(fCache); inherited Destroy; end; procedure TClassCache.Add(AClass: TClass); begin if Find(AClass.ClassName) <> nil then ECacheException.ClassAlreadyRegistered(AClass.ClassName); fCache.Add(AClass.ClassName, AClass); end; function TClassCache.Find(const AClass: string): TClass; var mIndex: integer; begin mIndex := fCache.IndexOf(AClass); if mIndex > -1 then Result := fCache.Data[mIndex] else Result := nil; end; end.
unit FilesList; interface uses Classes, SysUtils; type TFilesList = class; TFileListOption = (floRecursive); TFileListOptions = set of TFileListOption; TFileInfo = class private FSize: Integer; FAttr: Integer; FPath: String; FName: String; FOwner: TFilesList; function GetFullPath: String; public property Owner: TFilesList read FOwner; property Name: String read FName; property Path: String read FPath; property Attr: Integer read FAttr; property Size: Integer read FSize; property FullPath: String read GetFullPath; end; TFileListOnFileEvent = procedure (FileInfo: TFileInfo; var AddToList: Boolean) of Object; TFilesList = class private FFiles: TList; FFolders: TList; FRoot: String; FMask: String; FOnFile: TFileListOnFileEvent; function GetFiles(Index: Integer): TFileInfo; function GetFolders(Index: Integer): TFilesList; procedure AddFile(FileName, Path: String; Attr: Integer; Size: Integer); procedure AddFolder(FilesList: TFilesList); public constructor Create; destructor Destroy; override; procedure Scan(RootPath, Mask: String; Recursive: Boolean = False); function FilesCount: Integer; function FoldersCount: Integer; procedure Clear; property Files[Index: Integer]: TFileInfo read GetFiles; default; property Folders[Index: Integer]: TFilesList read GetFolders; property Root: String read FRoot; property Mask: String read FMask; property OnFile: TFileListOnFileEvent read FOnFile; end; implementation { TFileInfo } function TFileInfo.GetFullPath: String; begin Result := FPath + FName; end; { TFilesList } function TFilesList.FilesCount: Integer; begin Result := FFiles.Count; end; constructor TFilesList.Create; begin inherited Create; FFiles := TList.Create; FFolders := TList.Create; end; destructor TFilesList.Destroy; begin Clear; FFiles.Free; FFolders.Free; inherited Destroy; end; function TFilesList.GetFiles(Index: Integer): TFileInfo; begin Result := TFileInfo(FFiles.Items[Index]); end; procedure TFilesList.Clear; var i: Integer; begin for i := 0 to FilesCount - 1 do TFileInfo(FFiles.Items[i]).Free; FFiles.Clear; for i := 0 to FoldersCount - 1 do TFilesList(FFolders.Items[i]).Free; FFolders.Clear; end; {$WARNINGS OFF} procedure TFilesList.Scan(RootPath, Mask: String; Recursive: Boolean = False); const Attr = faAnyFile - faVolumeID - faHidden - faSysFile - faSymLink; var SearchRec: TSearchRec; res: Integer; Item: TFilesList; begin if Copy(RootPath, Length(RootPath), 1) <> '\' then RootPath := RootPath + '\'; FRoot := RootPath; FMask := Mask; res := FindFirst(RootPath + Mask, Attr, SearchRec); while res = 0 do begin if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then begin if (SearchRec.Attr and faDirectory) = 0 then AddFile(SearchRec.Name, RootPath, SearchRec.Attr, SearchRec.Size) else if Recursive then begin Item := TFilesList.Create; Item.Scan(RootPath + SearchRec.Name + '\', Mask, Recursive); if Item.FoldersCount + Item.FilesCount > 0 then AddFolder(Item) else Item.Free; end; end; res := FindNext(SearchRec); end; end; {$WARNINGS ON} function TFilesList.GetFolders(Index: Integer): TFilesList; begin Result := TFilesList(FFolders.Items[Index]); end; function TFilesList.FoldersCount: Integer; begin Result := FFolders.Count; end; procedure TFilesList.AddFile(FileName, Path: String; Attr, Size: Integer); var Item: TFileInfo; var AddToList: Boolean; begin AddToList := True; Item := TFileInfo.Create; try Item.FOwner := Self; Item.FName := FileName; Item.FPath := Path; Item.FAttr := Attr; Item.FSize := Size; if Assigned(FOnFile) then FOnFile(Item, AddToList); finally if AddToList then FFiles.Add(Item) else Item.Free; end; end; procedure TFilesList.AddFolder(FilesList: TFilesList); begin FFolders.Add(FilesList); end; end.
unit tagLibUnit; interface uses pFIBDatabase, pFIBQuery, pFIBStoredProc, pFIBDataSet, Dialogs, FIBDataBase, Controls, Forms, IB_Externals, Classes, Registry, Windows, ExtCtrls, IBase, cxSplitter, cxGrid, cxGridBandedTableView, cxGridDBBandedTableView, cxGridTableView, cxGridDBTableView, StylesMain, cxTL, cxDBTL, cxGridCustomTableView, dxBar, cxLookAndFeelPainters, cxLookAndFeels, dxStatusBar, SysUtils, Variants, s_DM_Styles, DevExTrans; type TColParam = packed record BandIndex : integer; ColIndex : integer; RowIndex : integer; LineCount : integer; Width : integer; GroupIndex : integer; Visible : byte; end; const DEF_ID_STYLE = 0; DEF_ID_BAR_STYLE = 2; DEF_ID_GRID_STYLE = 3; DEF_ID_STATUS_BAR_STYLE = 0; var sys_id_User : integer; DataSet : TpFIBDataSet; StoredProc : TpFIBStoredProc; WTrans : TpFIBTransaction; function InitializeTagLib(DB : TpFIBDatabase; RTrans : TpFIBTransaction; id_User : integer) : boolean; function FinalizeTagLib : boolean; procedure ShowChangeStyle(AOwner : TComponent; DBHandle : TISC_DB_HANDLE; RTrans : TISC_TR_HANDLE; fs : TFormStyle); procedure GetFormParams(InForm : TForm); procedure SetFormParams(InForm : TForm); function SetColParams(_in : TColParam) : string; function GetColParams(_in : string) : TColParam; procedure ExecParamsSP(PARENT_KEY : integer; KEY_NAME, PARAM_NAME, PARAM_VALUE : string); procedure DevExTranslate; implementation function InitializeTagLib(DB : TpFIBDatabase; RTrans : TpFIBTransaction; id_User : integer) : boolean; begin Result := True; sys_id_User := id_User; try WTrans := TpFIBTransaction.Create(nil); WTrans.DefaultDatabase := DB; StoredProc := TpFIBStoredProc.Create(nil); StoredProc.Database := DB; StoredProc.Transaction := WTrans; DataSet := TpFIBDataSet.Create(Nil); DataSet.Database := DB; DataSet.Transaction := WTrans; Application.CreateForm(TDM_Styles, DM_Styles); DataSet.SelectSQL.Text := 'select * from S_USER_STYLES_SEL(' + IntToStr(id_User) + ')'; DataSet.Open; DM_Styles.StyleIndex := DataSet['ID_STYLE']; DM_Styles.BarStyleIndex := DataSet['ID_BAR_STYLE']; DM_Styles.GridStyleIndex := DataSet['ID_GRID_STYLE']; DM_Styles.StatusBarStyle := DataSet['ID_STATUSBAR_STYLE']; DataSet.Close; if VarIsNull(DM_Styles.StyleIndex) then DM_Styles.StyleIndex := DEF_ID_STYLE; if VarIsNull(DM_Styles.BarStyleIndex) then DM_Styles.BarStyleIndex := DEF_ID_BAR_STYLE; if VarIsNull(DM_Styles.GridStyleIndex) then DM_Styles.GridStyleIndex := DEF_ID_GRID_STYLE; if VarIsNull(DM_Styles.StatusBarStyle) then DM_Styles.StatusBarStyle := DEF_ID_STATUS_BAR_STYLE; except Result := False; end; end; function FinalizeTagLib : boolean; begin Result := True; try if WTrans.Active then WTrans.Rollback; StoredProc.Free; WTrans.Free; DataSet.Free; except Result := False; end; end; procedure ShowChangeStyle(AOwner : TComponent; DBHandle : TISC_DB_HANDLE; RTrans : TISC_TR_HANDLE; fs : TFormStyle); begin StylesMain.ShowChangeStyle(AOwner, DBHandle, RTrans, fs, sys_id_User); end; procedure GetFormParams(InForm : TForm); var i : integer; id_Parent : integer; p : TColParam; begin if InForm = nil then Exit; if InForm.Owner = nil then begin InForm.Position := poScreenCenter; Exit; end; if DataSet.Active then DataSet.Close; DataSet.SelectSQL.Text := 'SELECT ID_KEY FROM S_REGESTRY WHERE NAME_KEY = ' + QuotedStr('Forms Settings'); DataSet.Open; if not VarIsNull(DataSet['ID_KEY']) then id_Parent := DataSet['ID_KEY'] else Exit; DataSet.Close; DataSet.SelectSQL.Text := 'select * from S_REGESTRY_SEL_PARAMS(' + IntToStr(id_Parent) + ',' + QuotedStr(InForm.ClassName) + ',' + IntToStr(sys_id_User) + ')'; DataSet.Open; while not DataSet.Eof do begin if DataSet.FieldByName('PARAM_NAME').AsString = 'Left' then if not VarIsNull(DataSet.FieldByName('PARAM_NAME').AsVariant) then InForm.Left := DataSet.FieldByName('PARAM_VALUE').AsInteger; if DataSet.FieldByName('PARAM_NAME').AsString = 'Top' then if not VarIsNull(DataSet.FieldByName('PARAM_NAME').AsVariant) then InForm.Top := DataSet.FieldByName('PARAM_VALUE').AsInteger; if DataSet.FieldByName('PARAM_NAME').AsString = 'Width' then if not VarIsNull(DataSet.FieldByName('PARAM_NAME').AsVariant) then InForm.Width := DataSet.FieldByName('PARAM_VALUE').AsInteger; if DataSet.FieldByName('PARAM_NAME').AsString = 'Height' then if not VarIsNull(DataSet.FieldByName('PARAM_NAME').AsVariant) then InForm.Height := DataSet.FieldByName('PARAM_VALUE').AsInteger; DataSet.Next; end; DataSet.Close; DataSet.SelectSQL.Text := 'SELECT ID_KEY FROM S_REGESTRY_ADD(' + IntToStr(id_Parent) + ',' + QuotedStr(InForm.ClassName) + ')'; DataSet.Open; if not VarIsNull(DataSet['ID_KEY']) then id_Parent := DataSet['ID_KEY'] else Exit; DataSet.Close; for i := 0 to InForm.ComponentCount - 1 do if (InForm.Components[i] is TdxBarManager) then begin if not VarIsNull(DM_Styles.BarStyleIndex) then case DM_Styles.BarStyleIndex of 0 : (InForm.Components[i] as TdxBarManager).Style := bmsEnhanced; 1 : (InForm.Components[i] as TdxBarManager).Style := bmsFlat; 2 : (InForm.Components[i] as TdxBarManager).Style := bmsOffice11; 3 : (InForm.Components[i] as TdxBarManager).Style := bmsStandard; 4 : (InForm.Components[i] as TdxBarManager).Style := bmsUseLookAndFeel; 5 : (InForm.Components[i] as TdxBarManager).Style := bmsXP; end; end else if (InForm.Components[i] is TcxGrid) then begin if not VarIsNull(DM_Styles.GridStyleIndex) then case DM_Styles.GridStyleIndex of 0 : (InForm.Components[i] as TcxGrid).LookAndFeel.Kind := lfFlat; // 1 : (InForm.Components[i] as TcxGrid).LookAndFeel.Kind := lfOffice11; 2 : (InForm.Components[i] as TcxGrid).LookAndFeel.Kind := lfStandard; 3 : (InForm.Components[i] as TcxGrid).LookAndFeel.Kind := lfUltraFlat; end; end else if (InForm.Components[i] is TcxGridBandedTableView) or (InForm.Components[i] is TcxGridDBBandedTableView) then begin with (InForm.Components[i] as TcxGridBandedTableView) do begin BeginUpdate; if not VarIsNull(DM_Styles.StyleIndex) then Styles.StyleSheet := DM_Styles.BGridPredefined.StyleSheets[DM_Styles.StyleIndex] else Styles.StyleSheet := DM_Styles.BGridPredefined.StyleSheets[0]; EndUpdate; end; end else if (InForm.Components[i] is TcxGridTableView) or (InForm.Components[i] is TcxGridDBTableView) then begin with (InForm.Components[i] as TcxCustomGridTableView) do begin BeginUpdate; if not VarIsNull(DM_Styles.StyleIndex) then Styles.StyleSheet := DM_Styles.GridPredefined.StyleSheets[DM_Styles.StyleIndex] else Styles.StyleSheet := DM_Styles.GridPredefined.StyleSheets[0]; EndUpdate; end; end else if (InForm.Components[i] is TcxTreeList) or (InForm.Components[i] is TcxDBTreeList) then begin with (InForm.Components[i] as TcxCustomTreeListControl ) do begin BeginUpdate; if not VarIsNull(DM_Styles.StyleIndex) then Styles.StyleSheet := DM_Styles.TreePredefined.StyleSheets[DM_Styles.StyleIndex] else Styles.StyleSheet := DM_Styles.TreePredefined.StyleSheets[0]; EndUpdate; end; end else if (InForm.Components[i] is TcxGridBandedColumn) or (InForm.Components[i] is TcxGridDBBandedColumn) then begin DataSet.SelectSQL.Text := 'select * from S_REGESTRY_SEL_PARAM(' + IntToStr(id_Parent) + ',' + QuotedStr(InForm.Components[i].Name) + ',' + IntToStr(sys_id_User) + ',' + QuotedStr('ColParams') + ')'; DataSet.Open; if not VarIsNull(DataSet['PARAM_VALUE']) then begin p := GetColParams(DataSet['PARAM_VALUE']); (InForm.Components[i] as TcxGridBandedColumn).Position.BandIndex := p.BandIndex; (InForm.Components[i] as TcxGridBandedColumn).Position.ColIndex := p.ColIndex; (InForm.Components[i] as TcxGridBandedColumn).Position.RowIndex := p.RowIndex; (InForm.Components[i] as TcxGridBandedColumn).Position.LineCount := p.LineCount; (InForm.Components[i] as TcxGridBandedColumn).Width := p.Width; (InForm.Components[i] as TcxGridBandedColumn).GroupIndex := p.GroupIndex; (InForm.Components[i] as TcxGridBandedColumn).Visible := (p.Visible = 1); end; DataSet.Close; end else if (InForm.Components[i] is TcxGridColumn) or (InForm.Components[i] is TcxGridDBColumn) then begin DataSet.SelectSQL.Text := 'select * from S_REGESTRY_SEL_PARAM(' + IntToStr(id_Parent) + ',' + QuotedStr(InForm.Components[i].Name) + ',' + IntToStr(sys_id_User) + ',' + QuotedStr('ColParams') + ')'; DataSet.Open; if not VarIsNull(DataSet['PARAM_VALUE']) then begin p := GetColParams(DataSet['PARAM_VALUE']); (InForm.Components[i] as TcxGridColumn).Width := p.Width; (InForm.Components[i] as TcxGridColumn).GroupIndex := p.GroupIndex; (InForm.Components[i] as TcxGridColumn).Visible := (p.Visible = 1); end; DataSet.Close; end else if (InForm.Components[i] is TcxDBTreeListColumn) or (InForm.Components[i] is TcxTreeListColumn) then begin DataSet.SelectSQL.Text := 'select * from S_REGESTRY_SEL_PARAM(' + IntToStr(id_Parent) + ',' + QuotedStr(InForm.Components[i].Name) + ',' + IntToStr(sys_id_User) + ',' + QuotedStr('ColParams') + ')'; DataSet.Open; if not VarIsNull(DataSet['PARAM_VALUE']) then begin p := GetColParams(DataSet['PARAM_VALUE']); (InForm.Components[i] as TcxTreeListColumn).Position.BandIndex := p.BandIndex; (InForm.Components[i] as TcxTreeListColumn).Position.ColIndex := p.ColIndex; (InForm.Components[i] as TcxTreeListColumn).Position.RowIndex := p.RowIndex; (InForm.Components[i] as TcxTreeListColumn).Position.LineCount := p.LineCount; (InForm.Components[i] as TcxTreeListColumn).Width := p.Width; (InForm.Components[i] as TcxTreeListColumn).Visible := (p.Visible = 1); end; DataSet.Close; end else if (InForm.Components[i] is TcxSplitter) then begin if Assigned((InForm.Components[i] as TcxSplitter).Control) then if (InForm.Components[i] as TcxSplitter).AlignSplitter in [salTop, salBottom] then begin DataSet.SelectSQL.Text := 'select * from S_REGESTRY_SEL_PARAM(' + IntToStr(id_Parent) + ',' + QuotedStr(InForm.Components[i].Name) + ',' + IntToStr(sys_id_User) + ',' + QuotedStr('Height') + ')'; DataSet.Open; if not VarIsNull(DataSet['PARAM_VALUE']) then (InForm.Components[i] as TcxSplitter).Control.Height := DataSet['PARAM_VALUE']; DataSet.Close; end else begin DataSet.SelectSQL.Text := 'select * from S_REGESTRY_SEL_PARAM(' + IntToStr(id_Parent) + ',' + QuotedStr(InForm.Components[i].Name) + ',' + IntToStr(sys_id_User) + ',' + QuotedStr('Width') + ')'; DataSet.Open; if not VarIsNull(DataSet['PARAM_VALUE']) then (InForm.Components[i] as TcxSplitter).Control.Width := DataSet['PARAM_VALUE']; DataSet.Close; end; end else if (InForm.Components[i] is TSplitter) then begin if (InForm.Components[i] as TSplitter).Align in [alTop, alBottom] then begin DataSet.SelectSQL.Text := 'select * from S_REGESTRY_SEL_PARAM(' + IntToStr(id_Parent) + ',' + QuotedStr(InForm.Components[i].Name) + ',' + IntToStr(sys_id_User) + ',' + QuotedStr('Top') + ')'; DataSet.Open; if not VarIsNull(DataSet['PARAM_VALUE']) then (InForm.Components[i] as TSplitter).Top := DataSet['PARAM_VALUE']; DataSet.Close; end else begin DataSet.SelectSQL.Text := 'select * from S_REGESTRY_SEL_PARAM(' + IntToStr(id_Parent) + ',' + QuotedStr(InForm.Components[i].Name) + ',' + IntToStr(sys_id_User) + ',' + QuotedStr('Left') + ')'; DataSet.Open; if not VarIsNull(DataSet['PARAM_VALUE']) then (InForm.Components[i] as TSplitter).Left := DataSet['PARAM_VALUE']; DataSet.Close; end end else if (InForm.Components[i] is TdxStatusBar) then begin if not VarIsNull(DM_Styles.StatusBarStyle) then case DM_Styles.StatusBarStyle of 0 : (InForm.Components[i] as TdxStatusBar).PaintStyle := stpsFlat; 1 : (InForm.Components[i] as TdxStatusBar).PaintStyle := stpsOffice11; 2 : (InForm.Components[i] as TdxStatusBar).PaintStyle := stpsStandard; 3 : (InForm.Components[i] as TdxStatusBar).PaintStyle := stpsUseLookAndFeel; 4 : (InForm.Components[i] as TdxStatusBar).PaintStyle := stpsXP; end; end; end; procedure SetFormParams(InForm : TForm); var i : integer; id_Parent : integer; p : TColParam; begin if InForm = nil then Exit; if InForm.Owner = nil then Exit; if InForm.WindowState = wsMaximized then Exit; StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName := 'S_REGESTRY_ADD_PARAMS'; StoredProc.Prepare; DataSet.SelectSQL.Text := 'SELECT ID_KEY FROM S_REGESTRY WHERE NAME_KEY = ' + QuotedStr('Forms Settings'); DataSet.Open; if not VarIsNull(DataSet['ID_KEY']) then id_Parent := DataSet['ID_KEY'] else Exit; DataSet.Close; ExecParamsSP(id_Parent, InForm.ClassName, 'Left', IntToStr(InForm.Left)); ExecParamsSP(id_Parent, InForm.ClassName, 'Top', IntToStr(InForm.Top)); ExecParamsSP(id_Parent, InForm.ClassName, 'Width', IntToStr(InForm.Width)); ExecParamsSP(id_Parent, InForm.ClassName, 'Height', IntToStr(InForm.Height)); id_Parent := StoredProc.FieldByName('ID_KEY').asInteger; ///--------------------- for i := 0 to InForm.ComponentCount - 1 do begin if (InForm.Components[i] is TcxGridBandedColumn) or (InForm.Components[i] is TcxGridDBBandedColumn) then begin if (InForm.Components[i] as TcxGridBandedColumn).Tag = 0 then begin p.BandIndex := (InForm.Components[i] as TcxGridBandedColumn).Position.BandIndex; p.ColIndex := (InForm.Components[i] as TcxGridBandedColumn).Position.ColIndex; p.RowIndex := (InForm.Components[i] as TcxGridBandedColumn).Position.RowIndex; p.LineCount := (InForm.Components[i] as TcxGridBandedColumn).Position.LineCount; p.Width := (InForm.Components[i] as TcxGridBandedColumn).Width; p.GroupIndex := (InForm.Components[i] as TcxGridBandedColumn).GroupIndex; if (InForm.Components[i] as TcxGridBandedColumn).Visible then p.Visible := 1 else p.Visible := 0; ExecParamsSP(id_Parent, InForm.Components[i].Name, 'ColParams', SetColParams(p)); end; end else if (InForm.Components[i] is TcxGridColumn) or (InForm.Components[i] is TcxGridDBColumn) then begin if (InForm.Components[i] as TcxGridColumn).Tag = 0 then begin p.BandIndex := 0; p.ColIndex := 0; p.RowIndex := 0; p.LineCount := 0; p.Width := (InForm.Components[i] as TcxGridColumn).Width; p.GroupIndex := (InForm.Components[i] as TcxGridColumn).GroupIndex; if (InForm.Components[i] as TcxGridColumn).Visible then p.Visible := 1 else p.Visible := 0; ExecParamsSP(id_Parent, InForm.Components[i].Name, 'ColParams', SetColParams(p)); end; end else if (InForm.Components[i] is TcxDBTreeListColumn) or (InForm.Components[i] is TcxTreeListColumn) then begin if (InForm.Components[i] as TcxTreeListColumn).Tag = 0 then begin p.BandIndex := (InForm.Components[i] as TcxTreeListColumn).Position.BandIndex; p.ColIndex := (InForm.Components[i] as TcxTreeListColumn).Position.ColIndex; p.RowIndex := (InForm.Components[i] as TcxTreeListColumn).Position.RowIndex; p.LineCount := (InForm.Components[i] as TcxTreeListColumn).Position.LineCount; p.Width := (InForm.Components[i] as TcxTreeListColumn).Width; if (InForm.Components[i] as TcxTreeListColumn).Visible then p.Visible := 1 else p.Visible := 0; ExecParamsSP(id_Parent, InForm.Components[i].Name, 'ColParams', SetColParams(p)); end; end else if (InForm.Components[i] is TcxSplitter) then begin if Assigned((InForm.Components[i] as TcxSplitter).Control) then if (InForm.Components[i] as TcxSplitter).AlignSplitter in [salTop, salBottom] then ExecParamsSP(id_Parent, InForm.Components[i].Name, 'Height', IntToStr((InForm.Components[i] as TcxSplitter).Control.Height)) else ExecParamsSP(id_Parent, InForm.Components[i].Name, 'Width', IntToStr((InForm.Components[i] as TcxSplitter).Control.Width)); end else if (InForm.Components[i] is TSplitter) then if (InForm.Components[i] as TSplitter).Align in [alTop, alBottom] then ExecParamsSP(id_Parent, InForm.Components[i].Name, 'Top', IntToStr((InForm.Components[i] as TSplitter).Top)) else ExecParamsSP(id_Parent, InForm.Components[i].Name, 'Left', IntToStr((InForm.Components[i] as TSplitter).Left)); end; StoredProc.Transaction.Commit; end; procedure ExecParamsSP(PARENT_KEY : integer; KEY_NAME, PARAM_NAME, PARAM_VALUE : string); begin StoredProc.ParamByName('PARENT_KEY').AsInteger := PARENT_KEY; StoredProc.ParamByName('KEY_NAME').AsString := KEY_NAME; StoredProc.ParamByName('ID_USER').AsInteger := sys_id_User; StoredProc.ParamByName('PARAM_NAME').AsString := PARAM_NAME; StoredProc.ParamByName('PARAM_VALUE').AsString := PARAM_VALUE; StoredProc.ExecProc; end; function SetColParams(_in : TColParam) : string; begin Result := IntToStr(_in.BandIndex) + ';' + IntToStr(_in.ColIndex) + ';' + IntToStr(_in.RowIndex) + ';' + IntToStr(_in.LineCount) + ';' + IntToStr(_in.Width) + ';' + IntToStr(_in.GroupIndex) + ';' + IntToStr(_in.Visible); end; function GetColParams(_in : string) : TColParam; var s : string; k : integer; begin s := _in; k := Pos(';', s); if Copy(s, 1, k - 1) <> '' then Result.BandIndex := StrToInt(Copy(s, 1, k - 1)); s := Copy(s, k + 1, Length(s) - k); k := Pos(';', s); if Copy(s, 1, k - 1) <> '' then Result.ColIndex := StrToInt(Copy(s, 1, k - 1)); s := Copy(s, k + 1, Length(s) - k); k := Pos(';', s); if Copy(s, 1, k - 1) <> '' then Result.RowIndex := StrToInt(Copy(s, 1, k - 1)); s := Copy(s, k + 1, Length(s) - k); k := Pos(';', s); if Copy(s, 1, k - 1) <> '' then Result.LineCount := StrToInt(Copy(s, 1, k - 1)); s := Copy(s, k + 1, Length(s) - k); k := Pos(';', s); if Copy(s, 1, k - 1) <> '' then Result.Width := StrToInt(Copy(s, 1, k - 1)); s := Copy(s, k + 1, Length(s) - k); k := Pos(';', s); if Copy(s, 1, k - 1) <> '' then Result.GroupIndex := StrToInt(Copy(s, 1, k - 1)); s := Copy(s, k + 1, Length(s) - k); if s <> '' then Result.Visible := StrToInt(s); end; procedure DevExTranslate; begin DevExTrans.DevExTranslate; end; end.
unit MVVM.Utils; interface uses {$IFDEF MSWINDOWS} Winapi.Windows, {$ENDIF} //System.Rtti, System.SysUtils, System.Classes, System.UITypes, Spring, MVVM.Interfaces.Architectural; type TCustomAttributeClass = class of TCustomAttribute; Utils = record public class function CreateEvent<T>: IEvent<T>; static; {$IFDEF MSWINDOWS} class procedure IdeDebugMsg(const AMsg: String); static; {$ENDIF} class function iif<T>(const ACondition: Boolean; AResult_True, AResult_False: T): T; overload; static; class function iif<T>(const ACondition: Boolean; AResult_True, AResult_False: TFunc<T>): T; overload; static; class function StringToCaseSelect(const Selector: string; const CaseList: array of string): integer; static; class function InterfaceToCaseSelect(Selector: IInterface; const CaseList: array of TGUID): integer; static; class function AttributeToCaseSelect(Selector: TCustomAttribute; const CaseList: array of TCustomAttributeClass): integer; static; class function ShowView<I: IViewModel>(AViewModel: I; const AViewName: string; const APlatform: String = ''; const AOwner: TComponent = nil): IView<I>; overload; static; class procedure ShowView(AView: IView); overload; static; class function ShowModalView<I: IViewModel>(AViewModel: I; const AViewName: string; const AResultProc: TProc<TModalResult>; const APlatform: String = ''; const AOwner: TComponent = nil): IView<I>; overload; static; class procedure ShowModalView(AView: IView; const AResultProc: TProc<TModalResult>); overload; static; class function StyledFieldOfComponent(const AField: String): String; static; end; implementation uses MVVM.Core, System.TypInfo; { Utils } class function Utils.AttributeToCaseSelect(Selector: TCustomAttribute; const CaseList: array of TCustomAttributeClass): integer; var LCnt: integer; begin Result := -1; for LCnt := 0 to Length(CaseList) - 1 do begin if (Selector is CaseList[LCnt]) then begin Result := LCnt; break; end; end; end; class function Utils.CreateEvent<T>: IEvent<T>; var E: Event<T>; begin Result := E; end; class procedure Utils.IdeDebugMsg(const AMsg: String); begin {$IFDEF MSWINDOWS} OutputDebugString(PChar(FormatDateTime('hhnnss.zzz', Now) + AMsg)); {$ENDIF} end; class function Utils.iif<T>(const ACondition: Boolean; AResult_True, AResult_False: TFunc<T>): T; begin if ACondition then Result := AResult_True else Result := AResult_False; end; class function Utils.iif<T>(const ACondition: Boolean; AResult_True, AResult_False: T): T; begin if ACondition then Result := AResult_True else Result := AResult_False; end; class function Utils.InterfaceToCaseSelect(Selector: IInterface; const CaseList: array of TGUID): integer; var LCnt: integer; begin Result := -1; for LCnt := 0 to Length(CaseList) - 1 do begin if Supports(Selector, CaseList[LCnt]) then begin Result := LCnt; break; end; end; end; class function Utils.ShowModalView<I>(AViewModel: I; const AViewName: string; const AResultProc: TProc<TModalResult>; const APlatform: String; const AOwner: TComponent): IView<I>; var [weak] LViewForm: IViewForm<I>; begin Result := MVVMCore.ViewsProvider.CreateView<I>(APlatform, AViewName, AOwner, AViewModel); if Supports(Result, IView<I>, LViewForm) then begin LViewForm.ExecuteModal(AResultProc); end; end; class procedure Utils.ShowModalView(AView: IView; const AResultProc: TProc<TModalResult>); begin MVVMCore.PlatformServices.ShowModalFormView(AView.GetAsObject as TComponent, AResultProc); end; class function Utils.ShowView<I>(AViewModel: I; const AViewName, APlatform: String; const AOwner: TComponent): IView<I>; var [weak] LViewForm: IViewForm<I>; begin Result := MVVMCore.ViewsProvider.CreateView<I>(APlatform, AViewName, AOwner, AViewModel); if Supports(Result, IView<I>, LViewForm) then begin LViewForm.Execute; end; end; class procedure Utils.ShowView(AView: IView); begin MVVMCore.PlatformServices.ShowFormView(AView.GetAsObject as TComponent); end; class function Utils.StringToCaseSelect(const Selector: string; const CaseList: array of string): integer; var LCnt: integer; begin Result := -1; for LCnt := 0 to Length(CaseList) - 1 do begin if CompareText(Selector, CaseList[LCnt]) = 0 then begin Result := LCnt; break; end; end; end; class function Utils.StyledFieldOfComponent(const AField: String): String; begin Result := 'StylesData[''' + AField + ''']'; end; end.
unit AccessObject; interface uses Windows, Messages, SysUtils, Classes, IBQuery, IBSQL, IBDatabase, Db, Action, IBStoredProc; type TAccessObject = class(TComponent) private dbConnection: TIBDatabase; transInput: TIBTransaction; transOutput: TIBTransaction; queryData: TIBQuery; FObjectName: string; FObjectFullName: string; FParentObjectID: Integer; FObjectID: Integer; FId_system :Integer; public queryDataActions: TIBQuery; bCloseQuery: Boolean; property ObjectName: string read FObjectName write FObjectName; property ObjectFullName: string read FObjectFullName write FObjectFullName; property ObjectID: Integer read FObjectID write FObjectID; property ParentObjectID: Integer read FParentObjectID write FParentObjectID; property Id_system: Integer read FId_system write FId_system; constructor Create(db: TIBDatabase; Data: TIBQuery = nil); destructor Destroy; override; function FillDataByID(ID: Integer): Boolean; function FillDataByName(Name: string; ParentID: Integer = 0): Boolean; procedure NewObject(Name, FullName: string;Id_system:Integer=-1 ;ParentID: Integer = -1); function InsertObject(var str: string): Boolean; function UpdateObject(var str: string): Boolean; function DeleteObject: Boolean; function DeleteAction(ActionID: Integer): Boolean; end; implementation { TAccessObject } constructor TAccessObject.Create(db: TIBDatabase; Data: TIBQuery = nil); begin dbConnection := db; queryData := Data; FObjectID := -1; FParentObjectID := -1; FObjectName := ''; FObjectFullName := ''; bCloseQuery := false; transInput := TIBTransaction.Create(nil); transInput.DefaultDatabase := dbConnection; transInput.Params.Add('read_committed'); transInput.Params.Add('rec_version'); transInput.Params.Add('nowait'); transOutput := TIBTransaction.Create(nil); transOutput.DefaultDatabase := dbConnection; transOutput.Params.AddStrings(transInput.Params); transOutput.StartTransaction; end; destructor TAccessObject.Destroy; begin if Assigned(queryData) then begin queryData.Close; queryData.Free; end; if transOutput.InTransaction then transOutput.Commit; if transInput.InTransaction then transInput.Commit; transOutput.Free; transInput.Free; end; function TAccessObject.FillDataByID(ID: Integer): Boolean; var sql: string; begin Result := false; if not Assigned(queryData) then begin queryData := TIBQuery.Create(nil); queryData.Transaction := transOutput; sql := 'select first1 *' + ' from objects' + ' where objects.id_object=' + IntToStr(ID); queryData.SQL.Text := sql; try queryData.Open; except on exc: Exception do begin //! Exit; end; end; end; // Получаем данные об объекте FObjectID := ID; FParentObjectID := queryData.FieldByName('id_parent').AsInteger; FObjectName := queryData.FieldByName('name').AsString; FObjectFullName := queryData.FieldByName('full_name').AsString; ; if bCloseQuery then queryData.Close; Result := true; end; // Создание нового объекта procedure TAccessObject.NewObject(Name, FullName: string;Id_system:Integer=-1; ParentID: Integer = -1); begin if Assigned(queryData) then queryData.Close; FObjectID := -1; FParentObjectID := ParentID; FObjectName := Name; FObjectFullName := FullName; FId_system :=Id_system; end; // Вставка нового объекта function TAccessObject.InsertObject(var str: string): Boolean; var stprInsObject: TIBStoredProc; begin Result := false; if FParentObjectID < 0 then Exit; stprInsObject := TIBStoredProc.Create(nil); stprInsObject.Database := dbConnection; stprInsObject.Transaction := transInput; stprInsObject.StoredProcName := 'INSERT_OBJECT_EX'; transInput.StartTransaction; try stprInsObject.Prepare; stprInsObject.ParamByName('pid_parent').AsInteger := FParentObjectID; stprInsObject.ParamByName('pname').AsString := FObjectName; stprInsObject.ParamByName('pfull_name').AsString := FObjectFullName; stprInsObject.ParamByName('pid_sys').AsInteger := FId_system; stprInsObject.ExecProc; transInput.Commit; except on E:Exception do begin str:=E.Message; transInput.Rollback; Exit; end; end; FObjectID := stprInsObject.ParamByName('pid_object').AsInteger; stprInsObject.Free; Result := true; end; // Обновление объекта function TAccessObject.UpdateObject(var str: string): Boolean; var sqlUpdObject: TIBSQL; sql: string; begin Result := false; if FParentObjectID < 0 then Exit; sqlUpdObject := TIBSQL.Create(nil); sqlUpdObject.Database := dbConnection; sqlUpdObject.Transaction := transInput; sql := 'update objects set ' + ' id_parent = ' + IntToStr(FParentObjectID) + ', ' + ' name = ''' + FObjectName + ''', ' + ' full_name = ''' + FObjectFullName + ''''+', ' + ' id_sys = '+IntToStr(FId_system)+ ' where id_object = ' + IntToStr(FObjectID); sqlUpdObject.SQL.Text := sql; transInput.StartTransaction; try sqlUpdObject.ExecQuery; transInput.Commit; except on E:Exception do begin str:=E.Message; transInput.Rollback; Exit; end; end; sqlUpdObject.Free; Result := true; end; function TAccessObject.DeleteObject: Boolean; begin // Result := false; end; function TAccessObject.DeleteAction(ActionID: Integer): Boolean; var sqlDelActionFromObj: TIBSQL; sql: string; theAction: TObjectAction; begin Result := false; theAction := TObjectAction.Create(Self, dbConnection); if theAction.FillDataBy(ActionID) and theAction.DeleteFromObject(FObjectID) then Result := true; theAction.Free; end; function TAccessObject.FillDataByName(Name: string; ParentID: Integer): Boolean; var sql: string; begin Result := false; if not Assigned(queryData) then begin queryData := TIBQuery.Create(nil); queryData.Transaction := transOutput; end else queryData.Close; sql := 'select first 1 *' + ' from objects' + ' where objects.name=''' + Trim(Name) + ''' and id_parent=' + IntToStr(ParentID); queryData.SQL.Text := sql; try queryData.Open; except on exc: Exception do begin //! Exit; end; end; if queryData.RecordCount <= 0 then Exit; // Получаем данные об объекте FObjectID := queryData.FieldByName('id_object').AsInteger; FParentObjectID := ParentID; FObjectName := Trim(Name); FObjectFullName := queryData.FieldByName('full_name').AsString; ; Result := true; end; end.
(* WordReader: HDO, 03-02-27 *) (* ---------- *) (* Reads a text file word (= seq. of characters) by word. *) (*===============================================================*) UNIT WordReader; INTERFACE CONST maxWordLen = 20; TYPE Conversion = (noConversion, toLower, toUpper); Word = STRING[maxWordLen]; (*to save memory, longer words are stripped*) PROCEDURE OpenFile(fileName: STRING; c: Conversion); PROCEDURE ReadWord(VAR w: Word); (*w = '' on end of file*) PROCEDURE CloseFile; IMPLEMENTATION USES WinCrt; CONST characters = ['a' .. 'z', 'ä', 'ö', 'ü', 'ß', 'A' .. 'Z', 'Ä', 'Ö', 'Ü']; EF = CHR(0); (*end of file character*) VAR txt: TEXT; (*text file*) open: BOOLEAN; (*file opened?*) line: STRING; (*current line*) ch: CHAR; (*current character*) cnr: INTEGER; (*column number of current character*) conv: Conversion; (*kind of conversion*) PROCEDURE ConvertToLower(VAR w: Word); VAR i: INTEGER; BEGIN FOR i := 1 TO Length(w) DO BEGIN CASE w[i] OF 'A'..'Z': w[i] := CHR(ORD(w[i]) + 32) ; 'Ä': w[i] := 'ä'; 'Ö': w[i] := 'ö'; 'Ü': w[i] := 'ü'; END; (*CASE*) END; (*FOR*) END; (*ConvertToLower*) PROCEDURE ConvertToUpper(VAR w: Word); VAR i: INTEGER; BEGIN FOR i := 1 TO Length(w) DO BEGIN CASE w[i] OF 'a'..'z': w[i] := UpCase(w[i]); 'ä': w[i] := 'Ä'; 'ö': w[i] := 'Ö'; 'ü': w[i] := 'Ü'; END; (*CASE*) END; (*FOR*) END; (*ConvertToUpper*) PROCEDURE NextChar; BEGIN IF cnr < Length(line) THEN BEGIN cnr := cnr + 1; ch := line[cnr] END (*THEN*) ELSE BEGIN IF NOT Eof(txt) THEN BEGIN ReadLn(txt, line); cnr := 0; ch := ' '; (*separate lines by ' '*) END (*THEN*) ELSE ch := EF; END; (*ELSE*) END; (*NextChar*) (* OpenFile: opens text file named fileName *) (*-------------------------------------------------------------*) PROCEDURE OpenFile(fileName: STRING; c: Conversion); BEGIN IF open THEN CloseFile; Assign(txt, fileName); (*$I-*) Reset(txt); (*$I+*) IF IOResult <> 0 THEN BEGIN WriteLn('ERROR in WordReader.OpenFile: file ', fileName, ' not found'); HALT; END; (*IF*) open := TRUE; conv := c; line := ''; cnr := 1; (*1 >= Length('') => force reading of first line*) NextChar; END; (*OpenFile*) (* NextWord: reads next word from file, returns '' on endfile *) (*-------------------------------------------------------------*) PROCEDURE ReadWord(VAR w: Word); VAR i: INTEGER; BEGIN w := ''; WHILE (ch <> EF) AND NOT (ch IN characters) DO BEGIN NextChar; END; (*WHILE*) IF ch = EF THEN EXIT; i := 0; REPEAT IF i < maxWordLen THEN BEGIN i := i + 1; (*$R-*) w[i] := ch; (*$R+*) END; (*IF*) NextChar; UNTIL (ch = EF) OR NOT (ch IN characters); w[0] := Chr(i); CASE conv OF toUpper: ConvertToUpper(w); toLower: ConvertToLower(w); END; (*CASE*) END; (*ReadWord*) (* CloseFile: closes text file *) (*-------------------------------------------------------------*) PROCEDURE CloseFile; BEGIN IF open THEN BEGIN Close(txt); open := FALSE; END; (*IF*) END; (*CloseFile*) BEGIN (*WordReader*) open := FALSE; END. (*WordReader*)
unit feli_collection; {$mode objfpc} interface uses feli_document, fpjson, classes; type FeliCollection = class(TObject) public data: TJsonArray; constructor create(); function where(key: ansiString; operation: ansiString; value: ansiString): FeliCollection; procedure orderBy(key: ansiString; direction: ansiString); function toTJsonArray(): TJsonArray; function toJson(): ansiString; procedure add(document: FeliDocument); function length(): int64; function shift(): TJsonObject; class function fromTJsonArray(dataArray: TJsonArray): FeliCollection; static; end; implementation uses feli_operators, feli_stack_tracer, feli_directions, feli_validation, sysutils; // https://www.w3resource.com/csharp-exercises/searching-and-sorting-algorithm/searching-and-sorting-algorithm-exercise-9.php constructor FeliCollection.create(); begin FeliStackTrace.trace('begin', 'constructor FeliCollection.create();'); data := TJsonArray.create(); FeliStackTrace.trace('end', 'constructor FeliCollection.create();'); end; function FeliCollection.where(key: ansiString; operation: ansiString; value: ansiString): FeliCollection; var dataTemp: TJsonArray; dataEnum: TJsonEnum; dataSingle: TJsonObject; begin FeliStackTrace.trace('begin', 'function FeliCollection.where(key: ansiString; operation: ansiString; value: ansiString): FeliCollection;'); dataTemp := TJsonArray.create(); for dataEnum in data do begin dataSingle := dataEnum.value as TJsonObject; case operation of FeliOperators.equalsTo: begin if (dataSingle.getPath(key).asString = value) then dataTemp.add(dataSingle); end; FeliOperators.notEqualsTo: begin if (dataSingle.getPath(key).asString <> value) then dataTemp.add(dataSingle); end; FeliOperators.largerThanOrEqualTo: begin if (dataSingle.getPath(key).asString >= value) then dataTemp.add(dataSingle); end; FeliOperators.largerThan: begin if (dataSingle.getPath(key).asString > value) then dataTemp.add(dataSingle); end; FeliOperators.smallerThanOrEqualTo: begin if (dataSingle.getPath(key).asString <= value) then dataTemp.add(dataSingle); end; FeliOperators.smallerThan: begin if (dataSingle.getPath(key).asString < value) then dataTemp.add(dataSingle); end; end; end; result := FeliCollection.fromTJsonArray(dataTemp); FeliStackTrace.trace('end', 'function FeliCollection.where(key: ansiString; operation: ansiString; value: ansiString): FeliCollection;'); end; procedure FeliCollection.orderBy(key: ansiString; direction: ansiString); var left, right: integer; function partition(var arr: TJsonArray; left, right: integer; key: ansiString; direction: ansiString): integer; var pivot: ansiString; i, j, dir: integer; begin FeliStackTrace.trace('begin', 'function partition(var arr: TJsonArray; left, right: integer; pivot: ansiString): integer;'); pivot := arr[right].getPath(key).asString; i := left - 1; for j := left to (right - 1) do begin if (direction = FeliDirections.ascending) then dir := 1 else if (direction = FeliDirections.descending) then dir := -1 else dir := 0; if (CompareStr(arr[j].getPath(key).asString, pivot) * dir ) < 0 then begin i := i + 1; arr.exchange(i, j); end; end; arr.exchange((i + 1), right); result := i + 1; FeliStackTrace.trace('end', 'function partition(var arr: TJsonArray; left, right: integer; pivot: ansiString): integer;'); end; procedure quicksort(var arr: TJsonArray; left, right: integer; key: ansiString; direction: ansiString); var pivot: integer; i: integer; tempObject: TJsonObject; begin FeliStackTrace.trace('begin', 'procedure quicksort(var arr: TJsonArray; left, right: integer);'); if (left < right) then begin pivot := partition(arr, left, right, key, direction); quicksort(arr, left, pivot - 1, key, direction); quicksort(arr, pivot + 1, right, key, direction); end; FeliStackTrace.trace('end', 'procedure quicksort(var arr: TJsonArray; left, right: integer);'); end; begin FeliStackTrace.trace('begin', 'procedure FeliCollection.orderBy(key: ansiString; direction: ansiString);'); if (FeliValidation.fixedValueCheck(direction, [FeliDirections.ascending, FeliDirections.descending])) then begin left := 0; right := data.count - 1; quicksort(data, left, right, key, direction); end; FeliStackTrace.trace('end', 'procedure FeliCollection.orderBy(key: ansiString; direction: ansiString);'); end; function FeliCollection.toTJsonArray(): TJsonArray; begin FeliStackTrace.trace('begin', 'function FeliCollection.toTJsonArray(): TJsonArray;'); result := self.data; FeliStackTrace.trace('end', 'function FeliCollection.toTJsonArray(): TJsonArray;'); end; function FeliCollection.toJson(): ansiString; var testArray: TJsonArray; begin FeliStackTrace.trace('begin', 'function FeliCollection.toJson(): ansiString;'); result := self.toTJsonArray().formatJson(); FeliStackTrace.trace('end', 'function FeliCollection.toJson(): ansiString;'); end; procedure FeliCollection.add(document: FeliDocument); begin FeliStackTrace.trace('begin', 'procedure FeliCollection.add(document: FeliDocument);'); data.add(document.toTJsonObject()); FeliStackTrace.trace('end', 'procedure FeliCollection.add(document: FeliDocument);'); end; function FeliCollection.shift(): TJsonObject; var removed: TJsonObject; begin FeliStackTrace.trace('begin', 'function FeliCollection.shift(): TJsonObject;'); if (self.length() > 0) then begin result := TJsonObject(data.extract(0)); end else begin result := nil; end; FeliStackTrace.trace('end', 'function FeliCollection.shift(): TJsonObject;'); end; function FeliCollection.length(): int64; begin FeliStackTrace.trace('begin', 'function FeliCollection.length(): int64;'); result := data.count; FeliStackTrace.trace('end', 'function FeliCollection.length(): int64;'); end; class function FeliCollection.fromTJsonArray(dataArray: TJsonArray): FeliCollection; static; var feliCollectionInstance: FeliCollection; begin FeliStackTrace.trace('begin', 'class function FeliCollection.fromTJsonArray(dataArray: TJsonArray): FeliCollection; static;'); feliCollectionInstance := FeliCollection.create(); feliCollectionInstance.data := dataArray; result := feliCollectionInstance; FeliStackTrace.trace('end', 'class function FeliCollection.fromTJsonArray(dataArray: TJsonArray): FeliCollection; static;'); end; end.
unit Class_CORD_IN_GKZF; //Result:=CheckField('CORD_IDEX','GKX_CORD',['UNIT_LINK',UNITLINK],AUniConnection); interface uses Classes,SysUtils,Uni,UniEngine; type TCORD=class(TUniEngine) private FUNITLINK: string; FCORDIDEX: Integer; FCORDCODE: string; FCORDNAME: string; FCORDMEMO: string; FCORDORDR: Integer; FCORDTYPE: string; FCODERULE: string; FWITHDASH: Integer; FWITHATTR: Integer; protected procedure SetParameters;override; function GetStrInsert:string;override; function GetStrUpdate:string;override; function GetStrDelete:string;override; public function GetStrsIndex:string;override; public function GetNextIdex:Integer;overload; function GetNextIdex(AUniConnection:TUniConnection):Integer;overload; function GetAttrIdex(AText:string):Integer; function GetAttrText(AIdex:Integer):string; public function CheckExist(AUniConnection:TUniConnection):Boolean;override; public destructor Destroy; override; constructor Create; published property UNITLINK: string read FUNITLINK write FUNITLINK; property CORDIDEX: Integer read FCORDIDEX write FCORDIDEX; property CORDCODE: string read FCORDCODE write FCORDCODE; property CORDNAME: string read FCORDNAME write FCORDNAME; property CORDMEMO: string read FCORDMEMO write FCORDMEMO; property CORDORDR: Integer read FCORDORDR write FCORDORDR; property CORDTYPE: string read FCORDTYPE write FCORDTYPE; property CODERULE: string read FCODERULE write FCODERULE; property WITHDASH: Integer read FWITHDASH write FWITHDASH; property WITHATTR: Integer read FWITHATTR write FWITHATTR; public class function ReadDS(AUniQuery:TUniQuery):TUniEngine;override; class procedure ReadDS(AUniQuery:TUniQuery;var Result:TUniEngine);override; class function CopyIt(ACORD:TCORD):TCORD;overload; class procedure CopyIt(ACORD:TCORD;var Result:TCORD);overload; end; implementation { TCORD } procedure TCORD.SetParameters; begin inherited; with FUniSQL.Params do begin case FOptTyp of otAddx: begin ParamByName('UNIT_LINK').Value := UNITLINK; ParamByName('CORD_IDEX').Value := CORDIDEX; ParamByName('CORD_CODE').Value := CORDCODE; ParamByName('CORD_NAME').Value := CORDNAME; ParamByName('CORD_MEMO').Value := CORDMEMO; ParamByName('CORD_ORDR').Value := CORDORDR; ParamByName('CORD_TYPE').Value := CORDTYPE; ParamByName('CODE_RULE').Value := CODERULE; ParamByName('WITH_DASH').Value := WITHDASH; ParamByName('WITH_ATTR').Value := WITHATTR; end; otEdit: begin ParamByName('UNIT_LINK').Value := UNITLINK; ParamByName('CORD_IDEX').Value := CORDIDEX; ParamByName('CORD_CODE').Value := CORDCODE; ParamByName('CORD_NAME').Value := CORDNAME; ParamByName('CORD_MEMO').Value := CORDMEMO; ParamByName('CORD_ORDR').Value := CORDORDR; ParamByName('CORD_TYPE').Value := CORDTYPE; ParamByName('CODE_RULE').Value := CODERULE; ParamByName('WITH_DASH').Value := WITHDASH; ParamByName('WITH_ATTR').Value := WITHATTR; end; otDelt: begin ParamByName('UNIT_LINK').Value := UNITLINK; ParamByName('CORD_IDEX').Value := CORDIDEX; end; end; end; end; function TCORD.CheckExist(AUniConnection: TUniConnection): Boolean; begin Result:=CheckExist('GKX_CORD',['UNIT_LINK',UNITLINK,'CORD_IDEX',CORDIDEX],AUniConnection); end; function TCORD.GetNextIdex: Integer; begin end; function TCORD.GetNextIdex(AUniConnection: TUniConnection): Integer; begin Result:=CheckField('CORD_IDEX','GKX_CORD',['UNIT_LINK',UNITLINK],AUniConnection); end; function TCORD.GetStrDelete: string; begin Result:='DELETE FROM GKX_CORD WHERE UNIT_LINK=:UNIT_LINK AND CORD_IDEX=:CORD_IDEX'; end; function TCORD.GetStrInsert: string; begin Result:='INSERT INTO GKX_CORD' +' ( UNIT_LINK, CORD_IDEX, CORD_CODE, CORD_NAME, CORD_MEMO' +' , CORD_ORDR, CORD_TYPE, CODE_RULE, WITH_DASH, WITH_ATTR)' +' VALUES' +' (:UNIT_LINK,:CORD_IDEX,:CORD_CODE,:CORD_NAME,:CORD_MEMO' +' ,:CORD_ORDR,:CORD_TYPE,:CODE_RULE,:WITH_DASH,:WITH_ATTR)'; end; function TCORD.GetStrsIndex: string; begin Result:=Format('%S-%D',[UNITLINK,CORDIDEX]); end; function TCORD.GetStrUpdate: string; begin Result:='UPDATE GKX_CORD SET' +' CORD_CODE=:CORD_CODE,' +' CORD_NAME=:CORD_NAME,' +' CORD_MEMO=:CORD_MEMO,' +' CORD_ORDR=:CORD_ORDR,' +' CORD_TYPE=:CORD_TYPE,' +' CODE_RULE=:CODE_RULE,' +' WITH_DASH=:WITH_DASH,' +' WITH_ATTR=:WITH_ATTR' +' WHERE UNIT_LINK=:UNIT_LINK' +' AND CORD_IDEX=:CORD_IDEX'; end; constructor TCORD.Create; begin end; destructor TCORD.Destroy; begin inherited; end; class function TCORD.ReadDS(AUniQuery: TUniQuery): TUniEngine; begin Result:=TCORD.Create; with TCORD(Result) do begin UNITLINK:=AUniQuery.FieldByName('UNIT_LINK').AsString; CORDIDEX:=AUniQuery.FieldByName('CORD_IDEX').AsInteger; CORDCODE:=AUniQuery.FieldByName('CORD_CODE').AsString; CORDNAME:=AUniQuery.FieldByName('CORD_NAME').AsString; CORDMEMO:=AUniQuery.FieldByName('CORD_MEMO').AsString; CORDORDR:=AUniQuery.FieldByName('CORD_ORDR').AsInteger; CORDTYPE:=AUniQuery.FieldByName('CORD_TYPE').AsString; CODERULE:=AUniQuery.FieldByName('CODE_RULE').AsString; WITHDASH:=AUniQuery.FieldByName('WITH_DASH').AsInteger; WITHATTR:=AUniQuery.FieldByName('WITH_ATTR').AsInteger; end; end; class procedure TCORD.ReadDS(AUniQuery: TUniQuery; var Result: TUniEngine); begin if Result=nil then Exit; with TCORD(Result) do begin UNITLINK:=AUniQuery.FieldByName('UNIT_LINK').AsString; CORDIDEX:=AUniQuery.FieldByName('CORD_IDEX').AsInteger; CORDCODE:=AUniQuery.FieldByName('CORD_CODE').AsString; CORDNAME:=AUniQuery.FieldByName('CORD_NAME').AsString; CORDMEMO:=AUniQuery.FieldByName('CORD_MEMO').AsString; CORDORDR:=AUniQuery.FieldByName('CORD_ORDR').AsInteger; CORDTYPE:=AUniQuery.FieldByName('CORD_TYPE').AsString; CODERULE:=AUniQuery.FieldByName('CODE_RULE').AsString; WITHDASH:=AUniQuery.FieldByName('WITH_DASH').AsInteger; WITHATTR:=AUniQuery.FieldByName('WITH_ATTR').AsInteger; end; end; class function TCORD.CopyIt(ACORD: TCORD): TCORD; begin Result:=TCORD.Create; TCORD.CopyIt(ACORD,Result) end; class procedure TCORD.CopyIt(ACORD:TCORD;var Result:TCORD); begin if Result=nil then Exit; Result.UNITLINK:=ACORD.UNITLINK; Result.CORDIDEX:=ACORD.CORDIDEX; Result.CORDCODE:=ACORD.CORDCODE; Result.CORDNAME:=ACORD.CORDNAME; Result.CORDMEMO:=ACORD.CORDMEMO; Result.CORDORDR:=ACORD.CORDORDR; Result.CORDTYPE:=ACORD.CORDTYPE; Result.CODERULE:=ACORD.CODERULE; Result.WITHDASH:=ACORD.WITHDASH; Result.WITHATTR:=ACORD.WITHATTR; end; function TCORD.GetAttrIdex(AText: string): Integer; begin Result:=-1; if Trim(AText)='[±àÂë]' then begin Result:=0; end else if Trim(AText)='[Ãû³Æ]' then begin Result:=1; end else if Trim(AText)='[±¸×¢]' then begin Result:=2; end; end; function TCORD.GetAttrText(AIdex: Integer): string; begin Result:=''; case AIdex of 0:Result:='[±àÂë]'; 1:Result:='[Ãû³Æ]'; 2:Result:='[±¸×¢]'; end; end; end.
unit AWSMain; interface uses IdHTTPServer, System.SysUtils, IdContext, IdCustomHTTPServer, System.Types; type TAWSMain = class(TObject) procedure httpServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); private FAdbPath: string; FServer: TIdHTTPServer; public constructor Create; destructor Destroy; override; procedure start(APort: Integer; AdbPath: string); end; implementation uses System.StrUtils, Winapi.Windows; constructor TAWSMain.Create; begin inherited; FServer := TIdHTTPServer.Create(nil); FServer.OnCommandGet := httpServerCommandGet; end; destructor TAWSMain.Destroy; begin FreeAndNil(FServer); inherited; end; procedure TAWSMain.httpServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var Uri: TStringDynArray; Cmd, Ip: string; begin Uri := SplitString(ARequestInfo.URI, '/'); if Length(Uri)<>3 then Exit; Cmd := Uri[1]; Ip := Uri[2]; if Cmd='c' then begin Writeln(Format('%s is ready, try to connect', [Ip])); WinExec(PAnsiChar(AnsiString(FAdbPath + ' connect '+Ip)), SW_NORMAL); end else if Cmd='d' then begin Writeln(Format('%s is offline!', [Ip])); WinExec(PAnsiChar(AnsiString(FAdbPath + ' disconnect '+Ip)), SW_NORMAL); end; ///connect is async£¨so wait Sleep(1000); WinExec(PAnsiChar(AnsiString(FAdbPath + ' devices')), SW_NORMAL); end; procedure TAWSMain.start(APort: Integer; AdbPath: string); begin FServer.DefaultPort := APort; FServer.Active := true; FAdbPath := AdbPath; if FAdbPath = '' then FAdbPath := 'adb'; end; end.
{$mode objfpc}{$H+} type TUnicodeToCharID = function(Unicode: cardinal): integer; function UnicodeToCP866(Unicode: cardinal): integer; begin case Unicode of 0..127: Result:=Unicode; 1040..1087 : Result := Unicode-912; 9617..9619 : Result := Unicode-9441; 9474 : Result := 179; 9508 : Result := 180; 9569 : Result := 181; 9570 : Result := 182; 9558 : Result := 183; 9557 : Result := 184; 9571 : Result := 185; 9553 : Result := 186; 9559 : Result := 187; 9565 : Result := 188; 9564 : Result := 189; 9563 : Result := 190; 9488 : Result := 191; 9492 : Result := 192; 9524 : Result := 193; 9516 : Result := 194; 9500 : Result := 195; 9472 : Result := 196; 9532 : Result := 197; 9566 : Result := 198; 9567 : Result := 199; 9562 : Result := 200; 9556 : Result := 201; 9577 : Result := 202; 9574 : Result := 203; 9568 : Result := 204; 9552 : Result := 205; 9580 : Result := 206; 9575 : Result := 207; 9576 : Result := 208; 9572 : Result := 209; 9573 : Result := 210; 9561 : Result := 211; 9560 : Result := 212; 9554 : Result := 213; 9555 : Result := 214; 9579 : Result := 215; 9578 : Result := 216; 9496 : Result := 217; 9484 : Result := 218; 9608 : Result := 219; 9604 : Result := 220; 9612 : Result := 221; 9616 : Result := 222; 9600 : Result := 223; 1088..1103 : Result := Unicode-864; 1025 : Result := 240; 1105 : Result := 241; 1028 : Result := 242; 1108 : Result := 243; 1031 : Result := 244; 1111 : Result := 245; 1038 : Result := 246; 1118 : Result := 247; 176 : Result := 248; 8729 : Result := 249; 183 : Result := 250; 8730 : Result := 251; 8470 : Result := 252; 164 : Result := 253; 9632 : Result := 254; 160 : Result := 255; else Result:=-1; end; end; function UTF8CharacterToUnicode(p: PChar; out CharLen: integer): Cardinal; { if p=nil then CharLen=0 otherwise CharLen>0 If there is an encoding error the Result is 0 and CharLen=1. Use UTF8FixBroken to fix UTF-8 encoding. It does not check if the codepoint is defined in the Unicode tables. } begin if p<>nil then begin if ord(p^)<%11000000 then begin // regular single byte character (#0 is a normal char, this is pascal ;) Result:=ord(p^); CharLen:=1; end else if ((ord(p^) and %11100000) = %11000000) then begin // starts with %110 => could be double byte character if (ord(p[1]) and %11000000) = %10000000 then begin CharLen:=2; Result:=((ord(p^) and %00011111) shl 6) or (ord(p[1]) and %00111111); if Result<(1 shl 7) then begin // wrong encoded, could be an XSS attack Result:=0; end; end else begin Result:=ord(p^); CharLen:=1; end; end else if ((ord(p^) and %11110000) = %11100000) then begin // starts with %1110 => could be triple byte character if ((ord(p[1]) and %11000000) = %10000000) and ((ord(p[2]) and %11000000) = %10000000) then begin CharLen:=3; Result:=((ord(p^) and %00011111) shl 12) or ((ord(p[1]) and %00111111) shl 6) or (ord(p[2]) and %00111111); if Result<(1 shl 11) then begin // wrong encoded, could be an XSS attack Result:=0; end; end else begin Result:=ord(p^); CharLen:=1; end; end else if ((ord(p^) and %11111000) = %11110000) then begin // starts with %11110 => could be 4 byte character if ((ord(p[1]) and %11000000) = %10000000) and ((ord(p[2]) and %11000000) = %10000000) and ((ord(p[3]) and %11000000) = %10000000) then begin CharLen:=4; Result:=((ord(p^) and %00001111) shl 18) or ((ord(p[1]) and %00111111) shl 12) or ((ord(p[2]) and %00111111) shl 6) or (ord(p[3]) and %00111111); if Result<(1 shl 16) then begin // wrong encoded, could be an XSS attack Result:=0; end; end else begin Result:=ord(p^); CharLen:=1; end; end else begin // invalid character Result:=ord(p^); CharLen:=1; end; end else begin Result:=0; CharLen:=0; end; end; function UTF8ToSingleByte(const s: string; const UTF8CharConvFunc: TUnicodeToCharID): string; var len: Integer; Src: PChar; Dest: PChar; c: Char; Unicode: LongWord; CharLen: integer; i: integer; begin if s='' then begin Result:=''; exit; end; len:=length(s); SetLength(Result,len); Src:=PChar(s); Dest:=PChar(Result); while len>0 do begin c:=Src^; if c<#128 then begin Dest^:=c; inc(Dest); inc(Src); dec(len); end else begin Unicode:=UTF8CharacterToUnicode(Src,CharLen); inc(Src,CharLen); dec(len,CharLen); i:=UTF8CharConvFunc(Unicode); if i>=0 then begin Dest^:=chr(i); inc(Dest); end; end; end; SetLength(Result,Dest-PChar(Result)); end; function UTF8ToCP866(const s: string): string; begin Result:=UTF8ToSingleByte(s,@UnicodeToCP866); end; begin // вызов UTF8ToCP866 end.
unit SpWorkModeEditDays; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, dxBar, dxBarExtItems, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxTextEdit, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxControls, cxGridCustomView, cxGrid, cxGridBandedTableView, cxClasses,ibase,SpWorkModeEditDays_Edit,TuCommonTypes, cxTimeEdit,TuCommonProc,TuCommonStyles, cxCurrencyEdit, dxStatusBar; type TFormEditDays = class(TForm) dxBarManager1: TdxBarManager; BtnRefresh: TdxBarLargeButton; BtnUpdate: TdxBarLargeButton; BtnExit: TdxBarLargeButton; BtnDel: TdxBarLargeButton; Grid: TcxGrid; GridDBTableEditDays: TcxGridDBTableView; GridIdDayWeek: TcxGridDBColumn; GridWorkBeg: TcxGridDBColumn; GridWorkEnd: TcxGridDBColumn; GridBreakBeg: TcxGridDBColumn; GridBreakEnd: TcxGridDBColumn; GridLevel1: TcxGridLevel; GridTodayHours: TcxGridDBColumn; GridTOMORROW_HOURS: TcxGridDBColumn; ButtonInsert: TdxBarLargeButton; GridTODAY_HOURS_NIGHT: TcxGridDBColumn; GridTOMORROW_HOURS_NIGHT: TcxGridDBColumn; dxStatusBar1: TdxStatusBar; procedure ButtonInsertClick(Sender: TObject); procedure BtnUpdateClick(Sender: TObject); procedure BtnDelClick(Sender: TObject); procedure BtnExitClick(Sender: TObject); procedure GridDBTableEditDaysDataControllerDataChanged( Sender: TObject); procedure BtnRefreshClick(Sender: TObject); procedure GridWorkBegCustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); procedure GridWorkBegGetDisplayText(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure GridTodayHoursGetDisplayText(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); private pStylesDM:TStyleDM; public { Public declarations } id:Integer; constructor Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE; Id_WorkMode:Integer);reintroduce; end; var FormEditDays: TFormEditDays; implementation uses SpWorkModeEditDays_DM, pFIBDataSet; {$R *.dfm} constructor TFormEditDays.Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;Id_WorkMode:Integer); var i: Integer; y, m, d: Word; begin inherited Create(AOwner); DModule:=TDModule.Create(AOwner); DModule.DB.Handle:=ADB_Handle; id:=Id_WorkMode; DModule.DSetDays.Close; DModule.DSetDays.SelectSQL.Text:= 'select * from TU_WORKREG_SELECT('+inttostr(id)+')'; DModule.DSetDays.Active:=true; GridDBTableEditDays.DataController.DataSource:=DModule.DSourceDays; DModule.DSourceDays.DataSet:=DModule.DSetDays; pStylesDM:=TStyleDM.Create(Self); GridDBTableEditDays.Styles.StyleSheet:=pStylesDM.GridTableViewStyleSheetDevExpress ; Caption :=GetConst('TranscriptWorkMode','Form'); BtnRefresh.Caption :=GetConst('Refresh','Button'); BtnUpdate.Caption :=GetConst('Update','Button'); ButtonInsert.Caption :=GetConst('Insert','Button'); BtnDel.Caption :=GetConst('Delete','Button'); BtnExit.Caption :=GetConst('Exit','Button'); GridIdDayWeek.Caption :=GetConst('Day','GridColumn'); GridWorkBeg.Caption :=GetConst('WorkBeg','GridColumn'); GridWorkBeg.Caption :=GetConst('WorkBeg','GridColumn'); GridWorkEnd.Caption :=GetConst('WorkEnd','GridColumn'); GridBreakBeg.Caption :=GetConst('BreakBeg','GridColumn'); GridBreakEnd.Caption :=GetConst('BreakEnd','GridColumn'); GridTodayHours.Caption :=GetConst('TodayHour','GridColumn'); GridTOMORROW_HOURS.Caption :=GetConst('TomorrowHours','GridColumn'); GridTODAY_HOURS_NIGHT.Caption :=GetConst('TodayHoursNight','GridColumn'); GridTOMORROW_HOURS_NIGHT.Caption :=GetConst('TomorrowHoursNight','GridColumn'); end; procedure TFormEditDays.ButtonInsertClick(Sender: TObject); var Param: TTuModeDay; K,max:Integer; begin Param :=TTuModeDay.Create; Param.Owner :=Self; Param.CFStyle :=tcfsInsert; Param.Id_Work_Mode :=Id; Param.Id_Day_Week :=DModule.DSetDays.RecordCountFromSrv+1 ; if View_SpWorkModeEditDays(Param) then begin DModule.DSetDays.SQLs.RefreshSQL.Text := 'SELECT * FROM DT_WORK_MODE_SELECT_BY_KEY('+VarToStr(id)+')'; DModule.DSetDays.SQLs.InsertSQL.Text := 'execute procedure z_empty_proc'; DModule.DSetDays.Insert; DModule.DSetDays.Post; DModule.DSetDays.CloseOpen(true); DModule.DSetDays.Locate('ID_DAY_WEEK', Param.Id_Day_Week,[]) ; end; Param.Destroy; end; procedure TFormEditDays.BtnUpdateClick(Sender: TObject); var Param: TTuModeDay; begin Param :=TTuModeDay.Create; Param.Owner :=Self; Param.CFStyle :=tcfsUpdate; Param.Id_Work_Mode :=Id; Param.Id_Day_Week :=DModule.DSetDays['ID_DAY_WEEK']; if DModule.DSetDays['WORK_BEG']=null then begin Param.Work_Beg :=0; Param.Work_End :=0 end else begin Param.Work_Beg :=DModule.DSetDays['WORK_BEG']; Param.Work_End :=DModule.DSetDays['WORK_END']; end; if DModule.DSetDays['BREAK_BEG']<>null then Param.Break_Beg := DModule.DSetDays['BREAK_BEG']; if DModule.DSetDays['BREAK_END']<>null then Param.Break_End := DModule.DSetDays['BREAK_END']; if View_SpWorkModeEditDays(Param) then begin DModule.DSetDays.SQLs.RefreshSQL.Text := 'SELECT * FROM DT_WORK_MODE_SELECT_BY_KEY('+VarToStr(id)+')'; DModule.DSetDays.SQLs.UpdateSQL.Text := 'execute procedure z_empty_proc'; DModule.DSetDays.Edit; DModule.DSetDays.Post; DModule.DSetDays.CloseOpen(true); DModule.DSetDays.Locate('ID_DAY_WEEK', Param.Id_Day_Week,[]) ; end; Param.Destroy; end; procedure TFormEditDays.BtnDelClick(Sender: TObject); var Param: TTuModeDay; begin Param :=TTuModeDay.Create; Param.Owner :=Self; Param.CFStyle :=tcfsDelete; Param.Id_Work_Mode :=Id; Param.Id_Day_Week :=DModule.DSetDays.RecordCountFromSrv; if View_SpWorkModeEditDays(Param) then begin BtnRefreshClick(sender); end; Param.Destroy; end; procedure TFormEditDays.BtnExitClick(Sender: TObject); begin ModalResult:=mrCancel; end; procedure TFormEditDays.GridDBTableEditDaysDataControllerDataChanged( Sender: TObject); begin if DModule=nil then Exit; if DModule.DSetDays.RecordCount=0 then begin BtnDel.Enabled:=False; BtnUpdate.Enabled:=False; end else begin BtnDel.Enabled:=True; BtnUpdate.Enabled:=True; end; end; procedure TFormEditDays.BtnRefreshClick(Sender: TObject); var T:Integer; begin if DModule.DSetDays.RecordCount =0 then Exit; T:=DModule.DSetDays['ID_DAY_WEEK']; DModule.DSetDays.CloseOpen(true); DModule.DSetDays.Locate('ID_DAY_WEEK',T,[]) ; end; procedure TFormEditDays.GridWorkBegCustomDrawCell( Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); begin // AViewInfo.Item.Caption:='45654'; end; procedure TFormEditDays.GridWorkBegGetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin if AText='' then AText:=GetConst('Holiday','CheckBox') end; procedure TFormEditDays.GridTodayHoursGetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); var i:integer; begin //for i:=length(AText) to 1 do // if AText[i]='0' then Delete(AText, I, 1) // else break; end; end.
{ Laz-Model Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde Portions (C) 2016 Peter Dyson. Initial Lazarus port This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit uRtfdComponents; {$mode objfpc}{$H+} interface uses Classes, Math, LCLIntf, LCLType, Controls, ExtCtrls, Graphics, uModel, uModelEntity, uListeners, uDiagramFrame, uRtfdLabel, uIterators, uConfig; type //Baseclass for a diagram-panel TRtfdBoxClass = class of TRtfdBox; TRtfdBox = class(TPanel, IModelEntityListener) private FMinVisibility : TVisibility; procedure SetMinVisibility(const Value: TVisibility); procedure OnChildMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); protected procedure Notification(AComponent: TComponent; Operation: Classes.TOperation); override; public Frame: TDiagramFrame; Entity: TModelEntity; public constructor Create(AOwner: TComponent; AEntity: TModelEntity; AFrame: TDiagramFrame; AMinVisibility : TVisibility); reintroduce; virtual; procedure RefreshEntities; virtual; abstract; procedure Paint; override; procedure Change(Sender: TModelEntity); virtual; procedure AddChild(Sender: TModelEntity; NewChild: TModelEntity); virtual; procedure Remove(Sender: TModelEntity); virtual; procedure EntityChange(Sender: TModelEntity); virtual; property MinVisibility : TVisibility write SetMinVisibility; end; TRtfdClass = class(TRtfdBox, IAfterClassListener) public constructor Create(AOwner: TComponent; AEntity: TModelEntity; AFrame: TDiagramFrame; AMinVisibility : TVisibility); override; destructor Destroy; override; procedure RefreshEntities; override; procedure AddChild(Sender: TModelEntity; NewChild: TModelEntity); override; end; TRtfdInterface = class(TRtfdBox, IAfterInterfaceListener) public constructor Create(AOwner: TComponent; AEntity: TModelEntity; AFrame: TDiagramFrame; AMinVisibility : TVisibility); override; destructor Destroy; override; procedure RefreshEntities; override; procedure AddChild(Sender: TModelEntity; NewChild: TModelEntity); override; end; TRtfdEnumeration = class(TRtfdBox, IAfterEnumerationListener) public constructor Create(AOwner: TComponent; AEntity: TModelEntity; AFrame: TDiagramFrame; AMinVisibility : TVisibility); override; destructor Destroy; override; procedure RefreshEntities; override; procedure AddChild(Sender: TModelEntity; NewChild: TModelEntity); override; end; TRtfdUnitPackage = class(TRtfdBox) public P: TUnitPackage; public constructor Create(AOwner: TComponent; AEntity: TModelEntity; AFrame: TDiagramFrame; AMinVisibility : TVisibility); override; procedure RefreshEntities; override; procedure DblClick; override; end; TRtfdCustomLabel = class(TRtfdODLabel) public constructor Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); override; end; TRtfdEnumName = class(TRtfdCustomLabel, IAfterEnumerationListener) public constructor Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); override; destructor Destroy; override; procedure EntityChange(Sender: TModelEntity); override; end; TRtfdEnumLiteral = class(TRtfdCustomLabel, IAfterEnumerationListener) public constructor Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); override; destructor Destroy; override; procedure EntityChange(Sender: TModelEntity); override; end; TRtfdClassName = class(TRtfdCustomLabel, IAfterClassListener) public constructor Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); override; destructor Destroy; override; procedure EntityChange(Sender: TModelEntity); override; end; TRtfdInterfaceName = class(TRtfdCustomLabel, IAfterInterfaceListener) public constructor Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); override; destructor Destroy; override; procedure EntityChange(Sender: TModelEntity); override; end; TVisibilityLabel = class(TRtfdCustomLabel) procedure Paint(width: integer); override; function WidthNeeded : integer; override; end; TRtfdOperation = class(TVisibilityLabel, IAfterOperationListener) private O: TOperation; public constructor Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); override; destructor Destroy; override; procedure EntityChange(Sender: TModelEntity); override; procedure IAfterOperationListener.EntityChange = EntityChange; end; TRtfdAttribute = class(TVisibilityLabel, IAfterAttributeListener) private A: TAttribute; public constructor Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); override; destructor Destroy; override; procedure EntityChange(Sender: TModelEntity); override; procedure IAfterAttributeListener.EntityChange = EntityChange; end; TRtfdSeparator = class(TRtfdCustomLabel) public constructor Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); override; constructor Create(AOwner: TComponent; Tp: integer); procedure Paint(width: integer); override; end; TRtfdStereotype = class(TRtfdCustomLabel) public constructor Create(AOwner: TComponent; AEntity: TModelEntity; ACaption: string); reintroduce; end; TRtfdUnitPackageName = class(TRtfdCustomLabel, IAfterUnitPackageListener) private P: TUnitPackage; public constructor Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); override; destructor Destroy; override; procedure EntityChange(Sender: TModelEntity); override; procedure IAfterUnitPackageListener.EntityChange = EntityChange; end; TRtfdUnitPackageDiagram = class(TRtfdCustomLabel, IAfterUnitPackageListener) private P: TUnitPackage; public constructor Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); override; destructor Destroy; override; procedure EntityChange(Sender: TModelEntity); override; procedure IAfterUnitPackageListener.EntityChange = EntityChange; end; implementation uses essConnectPanel, uRtfdDiagramFrame; constructor TRtfdEnumLiteral.Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); begin inherited Create(AOwner, AEntity, Tp); Entity.AddListener(IAfterEnumerationListener(Self)); EntityChange(nil); end; destructor TRtfdEnumLiteral.Destroy; begin Entity.RemoveListener(IAfterEnumerationListener(Self)); inherited Destroy; end; procedure TRtfdEnumLiteral.EntityChange(Sender: TModelEntity); begin // if ((Parent as TRtfdBox).Frame as TDiagramFrame).Diagram.Package<>Entity.Owner then // Caption := Entity.FullName // else Caption := Entity.Name; inherited EntityChange(Sender); end; constructor TRtfdEnumName.Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); begin inherited Create(AOwner, AEntity, Tp); Font.Style := [fsBold]; Transparent := True; Alignment := taCenter; Entity.AddListener(IAfterEnumerationListener(Self)); EntityChange(nil); end; destructor TRtfdEnumName.Destroy; begin Entity.RemoveListener(IAfterEnumerationListener(Self)); inherited Destroy; end; procedure TRtfdEnumName.EntityChange(Sender: TModelEntity); begin if ((Parent as TRtfdBox).Frame as TDiagramFrame).Diagram.Package<>Entity.Owner then Caption := Entity.FullName else Caption := Entity.Name; inherited EntityChange(Sender); end; constructor TRtfdEnumeration.Create(AOwner: TComponent; AEntity: TModelEntity; AFrame: TDiagramFrame; AMinVisibility: TVisibility); begin inherited Create(AOwner, AEntity, AFrame, AMinVisibility); PopupMenu := Frame.ClassInterfacePopupMenu; Entity.AddListener(IAfterEnumerationListener(Self)); RefreshEntities; end; destructor TRtfdEnumeration.Destroy; begin Entity.RemoveListener(IAfterEnumerationListener(Self)); inherited Destroy; end; procedure TRtfdEnumeration.RefreshEntities; var NeedH,NeedW,I : integer; E: TEnumeration; Lmi : IModelIterator; WasVisible : boolean; begin E := Entity as TEnumeration; WasVisible := Visible; Hide; DestroyComponents; NeedW := 0; NeedH := (ClassShadowWidth * 2) + 4; TRtfdStereotype.Create(Self, Entity, 'enumeration'); Inc(NeedH, TRtfdEnumName.Create(Self, Entity, 16).Height); if FMinVisibility < TVisibility( ord(high(TVisibility))+1) then begin Inc(NeedH, TRtfdSeparator.Create(Self, NeedH).Height); Lmi := TModelIterator.Create(E.GetFeatures); while Lmi.HasNext do Inc(NeedH, TRtfdEnumLiteral.Create(Self,Lmi.Next, NeedH).Height); end; for i:= 0 to ComponentCount - 1 do if (TComponent(Components[I]) is TRtfdODLabel) then NeedW := Max( TRtfdODLabel(Components[I]).WidthNeeded,NeedW); Height := Max(NeedH,cDefaultHeight) + 10; Width := Max(NeedW,cDefaultWidth); Visible := WasVisible; end; procedure TRtfdEnumeration.AddChild(Sender: TModelEntity; NewChild: TModelEntity ); begin RefreshEntities; end; constructor TRtfdCustomLabel.Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); begin inherited Create(AOwner, AEntity, Tp); end; constructor TRtfdBox.Create(AOwner: TComponent; AEntity: TModelEntity; AFrame: TDiagramFrame; AMinVisibility : TVisibility); begin inherited Create(AOwner); Color := clWhite; BorderWidth := ClassShadowWidth; Self.Frame := AFrame; Self.Entity := AEntity; Self.FMinVisibility := AMinVisibility; end; procedure TRtfdBox.Paint; const TopH = 39; var R: TRect; Sw: integer; i: integer; begin Sw := ClassShadowWidth; R := GetClientRect; with Canvas do begin //Shadow Brush.Color := clSilver; Pen.Color := clSilver; RoundRect(R.Right - Sw - 8, R.Top + Sw, R.Right, R.Bottom, 8, 8); FillRect(Rect(Sw, R.Bottom - Sw, R.Right, R.Bottom)); //Holes Brush.Color := (Parent as TessConnectPanel).Color; FillRect(Rect(R.Left, R.Bottom - Sw, R.Left + Sw, R.Bottom)); FillRect(Rect(R.Right - Sw, R.Top, R.Right, R.Top + Sw)); //Background Brush.Color := clWhite; Pen.Color := clBlack; Brush.Color := TopColor[ Config.IsLimitedColors ]; RoundRect(R.Left, R.Top, R.Right - Sw, R.Top + TopH, 8, 8); Brush.Color := clWhite; Rectangle(R.Left, R.Top + TopH - 8, R.Right - Sw, R.Bottom - Sw); FillRect( Rect(R.Left+1,R.Top + TopH - 8, R.Right - Sw - 1, R.Top + TopH + 1 - 8) ); end; for i:= 0 to ComponentCount - 1 do TRtfdODLabel(Components[i]).paint(ClientWidth); end; procedure TRtfdBox.AddChild(Sender: TModelEntity; NewChild: TModelEntity); begin //Stub end; procedure TRtfdBox.Change(Sender: TModelEntity); begin //Stub end; procedure TRtfdBox.EntityChange(Sender: TModelEntity); begin //Stub end; procedure TRtfdBox.Remove(Sender: TModelEntity); begin //Stub end; procedure TRtfdBox.SetMinVisibility(const Value: TVisibility); begin if Value<>FMinVisibility then begin FMinVisibility := Value; RefreshEntities; end; end; //The following declarations are needed for helping essconnectpanel to //catch all mouse actions. All controls that are inserted (classname etc) //in rtfdbox will get their mousedown-event redefined. type TCrackControl = class(TControl); procedure TRtfdBox.Notification(AComponent: TComponent; Operation: Classes.TOperation); begin inherited; //Owner=Self must be tested because notifications are being sent for all components //in the form. TRtfdLabels are created with Owner=box. // if (Operation = opInsert) and (Acomponent.Owner = Self) and (Acomponent is TControl) then // TCrackControl(AComponent).OnMouseDown := @OnChildMouseDown; end; procedure TRtfdBox.OnChildMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var pt: TPoint; begin inherited; pt.X := X; pt.Y := Y; pt := TControl(Sender).ClientToScreen(pt); pt := ScreenToClient(pt); MouseDown(Button,Shift,pt.X,pt.Y); end; constructor TRtfdClass.Create(AOwner: TComponent; AEntity: TModelEntity; AFrame: TDiagramFrame; AMinVisibility : TVisibility); begin inherited Create(AOwner, AEntity, AFrame, AMinVisibility); PopupMenu := Frame.ClassInterfacePopupMenu; Entity.AddListener(IAfterClassListener(Self)); RefreshEntities; end; destructor TRtfdClass.Destroy; begin Entity.RemoveListener(IAfterClassListener(Self)); inherited; end; procedure TRtfdClass.AddChild(Sender: TModelEntity; NewChild: TModelEntity); begin RefreshEntities; end; procedure TRtfdClass.RefreshEntities; var NeedH,NeedW,I : integer; C: TClass; Omi,Ami : IModelIterator; WasVisible : boolean; begin C := Entity as TClass; WasVisible := Visible; Hide; DestroyComponents; NeedW := 0; NeedH := (ClassShadowWidth * 2) + 4; Inc(NeedH, TRtfdClassName.Create(Self, Entity, 16).Height); //Get names in visibility order if FMinVisibility > Low(TVisibility) then begin Omi := TModelIterator.Create(C.GetOperations,TOperation,FMinVisibility,ioVisibility); Ami := TModelIterator.Create(C.GetAttributes,TAttribute,FMinVisibility,ioVisibility); end else begin Omi := TModelIterator.Create(C.GetOperations,ioVisibility); Ami := TModelIterator.Create(C.GetAttributes,ioVisibility); end; //Separator if (Ami.Count>0) or (Omi.Count>0) then Inc(NeedH, TRtfdSeparator.Create(Self, NeedH).Height); //Attributes while Ami.HasNext do Inc(NeedH, TRtfdAttribute.Create(Self,Ami.Next, NeedH).Height); //Separator if (Ami.Count>0) and (Omi.Count>0) then Inc(NeedH, TRtfdSeparator.Create(Self, NeedH).Height); //Operations while Omi.HasNext do Inc(NeedH, TRtfdOperation.Create(Self,Omi.Next, NeedH).Height); for i:= 0 to ComponentCount - 1 do if (TComponent(Components[I]) is TRtfdODLabel) then NeedW := Max( TRtfdODLabel(Components[I]).WidthNeeded,NeedW); Height := Max(NeedH,cDefaultHeight) + 10; Width := Max(NeedW,cDefaultWidth); Visible := WasVisible; end; constructor TRtfdUnitPackage.Create(AOwner: TComponent; AEntity: TModelEntity; AFrame: TDiagramFrame; AMinVisibility : TVisibility); begin inherited Create(AOwner, AEntity, AFrame, AMinVisibility); PopupMenu := Frame.PackagePopupMenu; P := Entity as TUnitPackage; RefreshEntities; end; procedure TRtfdUnitPackage.DblClick; begin // PostMessage(Frame.Handle, WM_ChangePackage, 0, 0); end; procedure TRtfdUnitPackage.RefreshEntities; begin DestroyComponents; TRtfdUnitPackageName.Create(Self, P, 50); Height := 45; end; procedure TVisibilityLabel.Paint(width: integer); var Al: integer; Pic : Graphics.TBitmap; tmpBox: TRect; oldFont: TFont; begin fbox.Right := width; oldFont := Canvas.Font; Canvas.Font := Font; tmpBox := FBox; case Entity.Visibility of viPrivate : Pic := ((Parent as TRtfdBox).Frame as TRtfdDiagramFrame).VisPrivateImage.Picture.Bitmap; viProtected : Pic := ((Parent as TRtfdBox).Frame as TRtfdDiagramFrame).VisProtectedImage.Picture.Bitmap; viPublic : Pic := ((Parent as TRtfdBox).Frame as TRtfdDiagramFrame).VisPublicImage.Picture.Bitmap; else Pic := ((Parent as TRtfdBox).Frame as TRtfdDiagramFrame).VisPublicImage.Picture.Bitmap; end; Canvas.Draw(tmpBox.Left,tmpBox.Top + 1, Pic ); tmpBox.Left := tmpBox.Left + cIconW + cMargin; Al := DT_LEFT; case Alignment of taLeftJustify: Al := DT_LEFT; taRightJustify: Al := DT_RIGHT; taCenter: Al := DT_CENTER; end; DrawText(Canvas.Handle,PChar(Caption),Length(Caption),tmpBox,Al); Canvas.Font := oldFont; end; function TVisibilityLabel.WidthNeeded: integer; begin Result := inherited; Result := Result + cIconW + cMargin; end; constructor TRtfdClassName.Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); begin inherited Create(AOwner, AEntity, Tp); Font.Style := [fsBold]; Transparent := True; Alignment := taCenter; Entity.AddListener(IAfterClassListener(Self)); EntityChange(nil); end; destructor TRtfdClassName.Destroy; begin Entity.RemoveListener(IAfterClassListener(Self)); inherited; end; procedure TRtfdClassName.EntityChange(Sender: TModelEntity); var Mi : IModelIterator; begin Mi := (Entity as TClass).GetOperations; while Mi.HasNext do if (Mi.Next as TOperation).IsAbstract then begin Font.Style := Font.Style + [fsItalic]; Break; end; if ((Parent as TRtfdBox).Frame as TDiagramFrame).Diagram.Package<>Entity.Owner then Caption := Entity.FullName else Caption := Entity.Name; inherited EntityChange(SEnder); end; constructor TRtfdInterfaceName.Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); begin inherited Create(AOwner, AEntity, Tp); Font.Style := [fsBold]; Transparent := True; Alignment := taCenter; Entity.AddListener(IAfterInterfaceListener(Self)); EntityChange(nil); end; destructor TRtfdInterfaceName.Destroy; begin Entity.RemoveListener(IAfterInterfaceListener(Self)); inherited; end; procedure TRtfdInterfaceName.EntityChange(Sender: TModelEntity); begin if ((Parent as TRtfdBox).Frame as TDiagramFrame).Diagram.Package<>Entity.Owner then Caption := Entity.FullName else Caption := Entity.Name; inherited EntityChange(Sender); end; constructor TRtfdSeparator.Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); begin Create(AOwner, Tp); end; constructor TRtfdSeparator.Create(AOwner: TComponent; Tp: integer); begin inherited Create(AOwner, nil, Tp); FBox.Left := 0; FBox.Right := cDefaultWidth - ClassShadowWidth ; end; procedure TRtfdSeparator.Paint(width: integer); begin Canvas.Pen.Color := clBlack; Canvas.MoveTo(FBox.Left, FBox.Top + (Height div 2)); Canvas.LineTo(Width - ClassShadowWidth, FBox.Top + (Height div 2)); end; constructor TRtfdUnitPackageName.Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); var th: integer; begin inherited Create(AOwner, AEntity, 0); Font.Style := [fsBold]; Alignment := taCenter; Transparent := True; th:=Height div 2; FBox.Top := FBox.Top + th; FBox.Bottom := FBox.Bottom + th; P := Entity as TUnitPackage; P.AddListener(IAfterUnitPackageListener(Self)); EntityChange(nil); end; destructor TRtfdUnitPackageName.Destroy; begin P.RemoveListener(IAfterUnitPackageListener(Self)); inherited; end; procedure TRtfdUnitPackageName.EntityChange(Sender: TModelEntity); begin Caption := P.Name; inherited EntityChange(Sender); end; constructor TRtfdOperation.Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); begin inherited Create(AOwner, AEntity, Tp); O := Entity as TOperation; O.AddListener(IAfterOperationListener(Self)); Self.EntityChange(nil); end; destructor TRtfdOperation.Destroy; begin O.RemoveListener(IAfterOperationListener(Self)); inherited; end; procedure TRtfdOperation.EntityChange(Sender: TModelEntity); const ColorMap: array[TOperationType] of TColor = (clGreen, clRed, clBlack, clGray); // otConstructor,otDestructor,otProcedure,otFunction); begin //Default uml-syntax //visibility name ( parameter-list ) : return-type-expression { property-string } { TODO : show parameters and returntype for operation } Caption := O.Name + '(...)'; Font.Style := []; Font.Color := ColorMap[O.OperationType]; if O.IsAbstract then Font.Style := [fsItalic]; inherited EntityChange(Sender); end; constructor TRtfdAttribute.Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); begin inherited Create(AOwner, AEntity, Tp); A := Entity as TAttribute; A.AddListener(IAfterAttributeListener(Self)); EntityChange(nil); end; destructor TRtfdAttribute.Destroy; begin A.RemoveListener(IAfterAttributeListener(Self)); inherited; end; procedure TRtfdAttribute.EntityChange(Sender: TModelEntity); begin //uml standard syntax is: //visibility name [ multiplicity ] : type-expression = initial-value { property-string } if Assigned(A.TypeClassifier) then Caption := A.Name + ' : ' + A.TypeClassifier.Name else Caption := A.Name; inherited EntityChange(Sender); end; constructor TRtfdUnitPackageDiagram.Create(AOwner: TComponent; AEntity: TModelEntity; Tp: integer); begin //This class is the caption in upper left corner for a unitdiagram inherited Create(AOwner, AEntity, Tp); // Color := clBtnFace; Font.Name := 'Times New Roman'; Font.Style := [fsBold]; Font.Size := 12; Alignment := taLeftJustify; P := AEntity as TUnitPackage; P.AddListener(IAfterUnitPackageListener(Self)); EntityChange(nil); end; destructor TRtfdUnitPackageDiagram.Destroy; begin P.RemoveListener(IAfterUnitPackageListener(Self)); inherited; end; procedure TRtfdUnitPackageDiagram.EntityChange(Sender: TModelEntity); begin Caption := ' ' + P.FullName; inherited EntityChange(Sender); end; constructor TRtfdInterface.Create(AOwner: TComponent; AEntity: TModelEntity; AFrame: TDiagramFrame; AMinVisibility : TVisibility); begin inherited Create(AOwner, AEntity, AFrame, AMinVisibility); Entity.AddListener(IAfterInterfaceListener(Self)); PopupMenu := Frame.ClassInterfacePopupMenu; RefreshEntities; end; destructor TRtfdInterface.Destroy; begin Entity.RemoveListener(IAfterInterfaceListener(Self)); inherited; end; procedure TRtfdInterface.RefreshEntities; var NeedW,NeedH,I : integer; OMi,AMi : IModelIterator; WasVisible : boolean; Int : TInterface; begin Int := Entity as TInterface; WasVisible := Visible; Hide; DestroyComponents; NeedW := 0; NeedH := (ClassShadowWidth * 2) + 4; TRtfdStereotype.Create(Self, Entity, 'interface'); Inc(NeedH, TRtfdInterfaceName.Create(Self, Entity, 16).Height); //Get names in visibility order if FMinVisibility > Low(TVisibility) then begin Omi := TModelIterator.Create(Int.GetOperations,TOperation,FMinVisibility,ioVisibility); Ami := TModelIterator.Create(Int.GetAttributes,TAttribute,FMinVisibility,ioVisibility); end else begin Omi := TModelIterator.Create(Int.GetOperations,ioVisibility); Ami := TModelIterator.Create(Int.GetAttributes,ioVisibility); end; //Separator if (Ami.Count>0) or (Omi.Count>0) then Inc(NeedH, TRtfdSeparator.Create(Self, NeedH).Height); //Attributes while Ami.HasNext do Inc(NeedH, TRtfdAttribute.Create(Self,Ami.Next, NeedH).Height); //Separator if (Ami.Count>0) and (Omi.Count>0) then Inc(NeedH, TRtfdSeparator.Create(Self, NeedH).Height); //Operations while Omi.HasNext do Inc(NeedH, TRtfdOperation.Create(Self,Omi.Next, NeedH).Height); for i:= 0 to ComponentCount - 1 do if (TComponent(Components[I]) is TRtfdCustomLabel) then NeedW := Max( TRtfdCustomLabel(Components[I]).WidthNeeded,NeedW); self.Height := Max(NeedH,cDefaultHeight) + 10; self.Width := Max(NeedW,cDefaultWidth); Visible := WasVisible; end; procedure TRtfdInterface.AddChild(Sender, NewChild: TModelEntity); begin RefreshEntities; end; constructor TRtfdStereotype.Create(AOwner: TComponent; AEntity: TModelEntity; ACaption: string); begin inherited Create(AOwner, AEntity, 2); Alignment := taCenter; Transparent := True; Self.Caption := '«' + ACaption + '»'; end; end.
unit MDB.BusinessObjects; interface uses System.Generics.Collections; const BaasSCollectionIdentifier = 'MBaasDemosRecipes'; type TRecipe = class(TObject) private FTitle : string; FBody : string; public constructor Create; property Title : string read FTitle write FTitle; property Body : string read FBody write FBody; end; TRecipesList = TList<TRecipe>; implementation { TRecipe } constructor TRecipe.Create; begin inherited; FTitle := ''; FBody := ''; end; end.
unit CustomAlphabetTest; {$mode objfpc}{$H+} interface uses SysUtils, fpcunit, testregistry, uEnums, uIntXLibTypes, uIntX; type { TTestCustomAlphabet } TTestCustomAlphabet = class(TTestCase) published procedure CallAlphabetNull(); procedure CallAlphabetShort(); procedure CallAlphabetRepeatingChars(); procedure Parse(); procedure ToStringTest(); private procedure AlphabetNull(); procedure AlphabetShort(); procedure AlphabetRepeatingChars(); end; implementation procedure TTestCustomAlphabet.AlphabetNull(); begin TIntX.Parse('', 20, pmFast); end; procedure TTestCustomAlphabet.CallAlphabetNull(); var TempMethod: TRunMethod; begin TempMethod := @AlphabetNull; AssertException(EArgumentNilException, TempMethod); end; procedure TTestCustomAlphabet.AlphabetShort(); begin TIntX.Parse('', 20, '1234'); end; procedure TTestCustomAlphabet.CallAlphabetShort(); var TempMethod: TRunMethod; begin TempMethod := @AlphabetShort; AssertException(EArgumentException, TempMethod); end; procedure TTestCustomAlphabet.AlphabetRepeatingChars(); begin TIntX.Parse('', 20, '0123456789ABCDEFGHIJ0'); end; procedure TTestCustomAlphabet.CallAlphabetRepeatingChars(); var TempMethod: TRunMethod; begin TempMethod := @AlphabetRepeatingChars; AssertException(EArgumentException, TempMethod); end; procedure TTestCustomAlphabet.Parse(); begin AssertEquals(integer(TIntX.Parse('JI', 20, '0123456789ABCDEFGHIJ')), 19 * 20 + 18); end; procedure TTestCustomAlphabet.ToStringTest(); begin AssertEquals(TIntX.Create(19 * 20 + 18).ToString(20, '0123456789ABCDEFGHIJ'), 'JI'); end; initialization RegisterTest(TTestCustomAlphabet); end.
unit MVVM.Messages.Engine; interface uses System.Classes, System.SysUtils, System.Types, System.SyncObjs, Spring, Spring.Collections, MVVM.Patched.ThreadedQueue, MVVM.Messages.Engine.Scheduler, MVVM.Interfaces, MVVM.Interfaces.Architectural, MVVM.Types, MVVM.Messages.Engine.Interfaces; const MAX_DEFAULT_POOLED_THREADS = 4; DEFAULT_CHANNEL_SINGLED_THREADED = 'CHANNEL.DEFAULT.SINGLE'; DEFAULT_CHANNEL_MULTI_THREADED = 'CHANNEL.DEFAULT.MULTI'; type { Forward Declarations } TMessage = class; TThreadMessageHandlerBase = class; TThreadMessageHandler = class; TMessageChannel = class; TChannel = class; TThreadMessageHandlerType = class of TThreadMessageHandler; {$REGION 'TMessage'} TMessage = class abstract(TInterfacedObject, IMessage) private FCreationDateTime: TDateTime; FSender : TObject; protected function GetCreationDateTime: TDateTime; function GetSender: TObject; public constructor Create; reintroduce; overload; constructor Create(ASender: TObject); overload; destructor Destroy; override; procedure Post; virtual; procedure Schedule(const AMilisecondsToExecute: Int64); overload; virtual; procedure Schedule(const ADateTimeWhenExecute: TDateTime); overload; virtual; function GetAsObject: TObject; property CreationDateTime: TDateTime read GetCreationDateTime; property Sender: TObject read GetSender; end; {$ENDREGION} {$REGION 'TMessageListener'} TMessageListener = class abstract(TInterfacedObject, IMessageListener, IObject) private FRegistered : Boolean; FIsCodeToExecuteInUIMainThread: Boolean; FChannelName : String; FChannel : TMessageChannel; FTypeRestriction : EMessageTypeRestriction; FFilterCondition : TListenerFilter; FEnabled : Boolean; function GetIsCodeToExecuteInUIMainThread: Boolean; procedure SetIsCodeToExecuteInUIMainThread(const AValue: Boolean); function GetTypeRestriction: EMessageTypeRestriction; procedure SetTypeRestriction(const ATypeRestriction: EMessageTypeRestriction); function GetListenerFilter: TListenerFilter; procedure SetListenerFilter(const AFilter: TListenerFilter); function GetEnabled: Boolean; procedure SetEnabled(const AValue: Boolean); function GetChannel: String; protected function GetDefaultTypeRestriction: EMessageTypeRestriction; virtual; function GetDefaultEnabled: Boolean; virtual; public procedure AfterConstruction; override; constructor Create(const AChannel: String = ''; const AFilterCondition: TListenerFilter = nil; const ACodeExecutesInMainUIThread: Boolean = False; const ATypeRestriction: EMessageTypeRestriction = EMessageTypeRestriction.mtrAllowDescendants); reintroduce; overload; virtual; destructor Destroy; override; function GetConditionsMatch(AMessage: IMessage): Boolean; virtual; function GetMessajeClass: TClass; virtual; abstract; procedure Register; procedure UnRegister; function GetAsObject: TObject; procedure DoOnNewMessage(AMessage: IMessage); virtual; property IsCodeToExecuteInUIMainThread: Boolean read GetIsCodeToExecuteInUIMainThread write SetIsCodeToExecuteInUIMainThread; property FilterCondition: TListenerFilter read GetListenerFilter write SetListenerFilter; property TypeRestriction: EMessageTypeRestriction read GetTypeRestriction write SetTypeRestriction; property Enabled : Boolean read GetEnabled write SetEnabled; property Channel : String read GetChannel; end; TMessageListener<T: IMessage> = class abstract(TMessageListener, IMessageListener<T>) private FOnMessage: IEvent<TNotifyMessage>; protected function GetOnMessage: IEvent<TNotifyMessage>; procedure DoOnNewMessage(AMessage: IMessage); override; final; public constructor Create(const AChannel: String = ''; const AFilterCondition: TListenerFilter = nil; const ACodeExecutesInMainUIThread: Boolean = False; const ATypeRestriction: EMessageTypeRestriction = EMessageTypeRestriction.mtrAllowDescendants); overload; override; destructor Destroy; override; function GetMessajeClass: TClass; override; final; property OnMessage: IEvent<TNotifyMessage> read GetOnMessage; end; {$ENDREGION} {$REGION 'TThreadMessageHandlerBase'} TThreadMessageHandlerBase = class abstract(TThread) const CTE_INITIAL_QUEUE_SIZE = 10; CTE_PUSH_TIMEOUT = 100; private FSynchronizer: TLightweightMREW; FLock : TSpinLock; FMessageCount: Int64; FMessages : TThreadedQueue<IMessage>; FIsBusy : Boolean; procedure AdquireWrite; procedure ReleaseWrite; procedure AdquireRead; procedure ReleaseRead; procedure ProcessQueuedMessage(AMessage: IMessage); procedure ProcessMessages; function GetNextMessage(out AQueueSize: Integer; var AMessage: IMessage): TWaitResult; protected procedure SetIsBusy(const AValue: Boolean); function GetIsBusy: Boolean; procedure Execute; override; function GetProcessedMessageCount: Int64; procedure ProcessMessage(AMessage: IMessage); virtual; abstract; public constructor Create; overload; virtual; destructor Destroy; override; procedure AddMessage(AMessage: IMessage); virtual; property ProcessedMessageCount: Int64 read GetProcessedMessageCount; property IsBusy: Boolean read GetIsBusy; end; {$ENDREGION} {$REGION 'TThreadMessageHandler'} TThreadMessageHandler = class(TThreadMessageHandlerBase) private FListeners : IList<IMessageListener>; FSynchronizerListeners: TLightweightMREW; FChannel : TMessageChannel; protected procedure ProcessMessage(AMessage: IMessage); override; procedure InitializeListeners; virtual; procedure FinalizeListeners; virtual; function GetListenersCount: Integer; function GetEventRelevant(AMessage: IMessage): Boolean; virtual; public procedure AfterConstruction; override; constructor Create; overload; override; constructor Create(const AChannel: TMessageChannel); overload; destructor Destroy; override; procedure RegisterListener(AMessageListener: IMessageListener); procedure UnregisterListener(AMessageListener: IMessageListener); property ListenersCount: Integer read GetListenersCount; procedure Register; procedure UnRegister; end; {$ENDREGION} {$REGION 'TMessageChannel'} TMessageChannel = class abstract(TThreadMessageHandlerBase) private FName : string; FSynchronizer : TLightweightMREW; FThreadsMessajes : IList<TThreadMessageHandler>; FExecutors : IList<TThreadMessageHandler>; FThreadCount : Integer; procedure AddThreadMensajes(const AThreadMensajes: TThreadMessageHandler); procedure RemoveThreadMensajes(const AThreadMensajes: TThreadMessageHandler); procedure CreateThreads; procedure DestroyThreads; function GetThreadCount: Integer; procedure AdquireWrite; procedure ReleaseWrite; procedure AdquireRead; procedure ReleaseRead; function GetName: string; protected function GetMessajeThreadType: TThreadMessageHandlerType; virtual; abstract; procedure ProcessMessage(AMessage: IMessage); override; procedure PoolMessage(AMessage: IMessage); virtual; public constructor Create(const AName: string; const AThreadCount: Integer); reintroduce; destructor Destroy; override; procedure AfterConstruction; override; //procedure Register; //procedure UnRegister; procedure RegisterListener(AMessageListener: IMessageListener); procedure UnregisterListener(AMessageListener: IMessageListener); property ThreadCount: Integer read GetThreadCount; property Name: string read GetName; end; {$ENDREGION} {$REGION 'TMessageChannel<T>'} TMessageChannel<T: TThreadMessageHandler> = class(TMessageChannel) protected function GetMessajeThreadType: TThreadMessageHandlerType; override; final; end; {$ENDREGION} TMessageChannelBase = class(TMessageChannel<TThreadMessageHandler>); TChannel = class(TMessageChannelBase); //TMessageChannel_Main = class(TMessageChannel<TThreadMessageHandler>); //TMessageChannel_Main_SingleThreaded = class(TMessageChannel<TThreadMessageHandler>); {$REGION 'MessageBus'} EMessageDeploymentKind = (mdkFifo, mdkPooled); MessageBus = record private class var FScheduler : TMessagesScheduler; class var FSynchronizerChannels : TLightweightMREW; class var FChannels : IList<TMessageChannel>; class var FChannelsByName : IDictionary<String, TMessageChannel>; class var FMessageDeploymentKind : EMessageDeploymentKind; class procedure CreateIni; static; class procedure DestroyIni; static; class procedure QueueInchannels(AMessage: IMessage); static; public class procedure RegisterChannel(const AChannelName: String; const AThreadCount: Integer); static; class procedure UnregisterChannel(const AChannelName: String); static; class function GetChannel(const AChannelName: String; out AChannel: TMessageChannel): Boolean; static; class procedure QueueMessage(AMessage: IMessage); static; class property MessageDeploymentKind : EMessageDeploymentKind read FMessageDeploymentKind write FMessageDeploymentKind; class property Scheduler: TMessagesScheduler read FScheduler; end; {$ENDREGION} {$REGION 'TMessage_Generic'} TMessage_Generic<T> = class(TMessage) public Data: T; end; {$ENDREGION} {$REGION 'TMessage_Base_ViewModel'} TMessageListenerViewModel<T: TMessage> = class(TMessageListener<T>) private FViewModel: IViewModel; protected function GetConditionsMatch(AMessage: IMessage): Boolean; override; public constructor Create(AViewModel: IViewModel; const AChannel: String = ''; const AFilterCondition: TListenerFilter = nil; const ACodeExecutesInMainUIThread: Boolean = False; const ATypeRestriction: EMessageTypeRestriction = EMessageTypeRestriction.mtrAllowDescendants); overload; end; {$ENDREGION} implementation uses System.Generics.Defaults, MVVM.Core, MVVM.Utils; {$REGION 'TMessage'} constructor TMessage.Create; begin inherited Create; FCreationDateTime := Now; FSender := nil; end; constructor TMessage.Create(ASender: TObject); begin Create; FSender := ASender; end; destructor TMessage.Destroy; begin inherited Destroy; end; function TMessage.GetAsObject: TObject; begin Result := Self; end; function TMessage.GetCreationDateTime: TDateTime; begin Result := FCreationDateTime; end; function TMessage.GetSender: TObject; begin Result := FSender; end; procedure TMessage.Post; begin MessageBus.QueueMessage(Self) end; procedure TMessage.Schedule(const ADateTimeWhenExecute: TDateTime); begin MessageBus.Scheduler.ScheduleMessage(Self, ADateTimeWhenExecute); end; procedure TMessage.Schedule(const AMilisecondsToExecute: Int64); begin MessageBus.Scheduler.ScheduleMessage(Self, AMilisecondsToExecute); end; {$ENDREGION} {$REGION 'TMessageListener'} procedure TMessageListener.AfterConstruction; begin inherited; Register; end; constructor TMessageListener.Create(const AChannel: String; const AFilterCondition: TListenerFilter; const ACodeExecutesInMainUIThread: Boolean; const ATypeRestriction: EMessageTypeRestriction); begin FChannelName := AChannel; if AChannel.IsEmpty then begin case MessageBus.FMessageDeploymentKind of EMessageDeploymentKind.mdkFifo: begin MessageBus.GetChannel(DEFAULT_CHANNEL_SINGLED_THREADED, FChannel); end; EMessageDeploymentKind.mdkPooled: begin MessageBus.GetChannel(DEFAULT_CHANNEL_MULTI_THREADED, FChannel); end; end; end else begin if not MessageBus.GetChannel(AChannel, FChannel) then raise Exception.Create('The channel ' + AChannel + ' is not registered'); end; inherited Create; FEnabled := GetDefaultEnabled; FIsCodeToExecuteInUIMainThread := ACodeExecutesInMainUIThread; FFilterCondition := AFilterCondition; end; destructor TMessageListener.Destroy; begin UnRegister; inherited; end; function TMessageListener.GetIsCodeToExecuteInUIMainThread: Boolean; begin Result := FIsCodeToExecuteInUIMainThread end; function TMessageListener.GetAsObject: TObject; begin Result := Self end; function TMessageListener.GetChannel: String; begin Result := FChannelName end; function TMessageListener.GetConditionsMatch(AMessage: IMessage): Boolean; begin if Assigned(FFilterCondition) then Result := FFilterCondition(AMessage) else Result := True end; function TMessageListener.GetDefaultEnabled: Boolean; begin Result := True; end; function TMessageListener.GetDefaultTypeRestriction: EMessageTypeRestriction; begin Result := mtrAllowDescendants; end; function TMessageListener.GetEnabled: Boolean; begin Result := FEnabled; end; function TMessageListener.GetListenerFilter: TListenerFilter; begin Result := FFilterCondition end; function TMessageListener.GetTypeRestriction: EMessageTypeRestriction; begin Result := FTypeRestriction; end; procedure TMessageListener.DoOnNewMessage(AMessage: IMessage); begin // end; procedure TMessageListener.Register; begin FChannel.RegisterListener(Self); end; procedure TMessageListener.SetEnabled(const AValue: Boolean); begin FEnabled := AValue; end; procedure TMessageListener.SetIsCodeToExecuteInUIMainThread(const AValue: Boolean); begin FIsCodeToExecuteInUIMainThread := AValue; end; procedure TMessageListener.SetListenerFilter(const AFilter: TListenerFilter); begin FFilterCondition := AFilter end; procedure TMessageListener.SetTypeRestriction(const ATypeRestriction: EMessageTypeRestriction); begin FTypeRestriction := ATypeRestriction; end; procedure TMessageListener.UnRegister; begin FChannel.UnregisterListener(Self); end; {$ENDREGION} {$REGION 'TMessageListener<T>'} constructor TMessageListener<T>.Create(const AChannel: String; const AFilterCondition: TListenerFilter; const ACodeExecutesInMainUIThread: Boolean; const ATypeRestriction: EMessageTypeRestriction); begin inherited; FOnMessage := Utils.CreateEvent<TNotifyMessage>; end; destructor TMessageListener<T>.Destroy; begin FOnMessage := nil; inherited; end; function TMessageListener<T>.GetMessajeClass: TClass; begin Result := PTypeInfo(TypeInfo(T))^.TypeData.ClassType; end; function TMessageListener<T>.GetOnMessage: IEvent<TNotifyMessage>; begin Result := FOnMessage end; procedure TMessageListener<T>.DoOnNewMessage(AMessage: IMessage); begin if FIsCodeToExecuteInUIMainThread then begin if not MVVMCore.PlatformServices.IsMainThreadUI then MVVMCore.DelegateExecution<IMessage>(AMessage, procedure(AAMessage: IMessage) begin FOnMessage.Invoke(AAMessage) end, EDelegatedExecutionMode.medQueue) else FOnMessage.Invoke(AMessage); end else FOnMessage.Invoke(AMessage); end; {$ENDREGION} {$REGION 'TThreadMessageHandlerBase'} procedure TThreadMessageHandlerBase.AdquireRead; begin FSynchronizer.BeginRead; end; procedure TThreadMessageHandlerBase.AdquireWrite; begin FSynchronizer.BeginWrite; end; constructor TThreadMessageHandlerBase.Create; begin inherited Create(False); FLock := TSpinLock.Create(False); FMessages := TThreadedQueue<IMessage>.Create(CTE_INITIAL_QUEUE_SIZE, CTE_PUSH_TIMEOUT, Cardinal.MaxValue); FMessageCount := 0; end; destructor TThreadMessageHandlerBase.Destroy; begin Terminate; FMessages.DoShutDown; WaitFor; FMessages.Free; inherited Destroy; end; function TThreadMessageHandlerBase.GetProcessedMessageCount: Int64; begin Result := FMessageCount end; function TThreadMessageHandlerBase.GetIsBusy: Boolean; begin FLock.Enter; try Result := FIsBusy; finally FLock.Exit; end; end; function TThreadMessageHandlerBase.GetNextMessage(out AQueueSize: Integer; var AMessage: IMessage): TWaitResult; begin Result := FMessages.PopItem(AQueueSize, AMessage); end; procedure TThreadMessageHandlerBase.ProcessMessages; var LRes : TWaitResult; LSize: Integer; LMsg : IMessage; begin while not(Terminated) do begin repeat LRes := GetNextMessage(LSize, LMsg); case LRes of wrSignaled: begin if not Terminated then begin try try SetIsBusy(True); ProcessQueuedMessage(LMsg); finally SetIsBusy(False); end; except on E: Exception do begin Utils.IdeDebugMsg('Exception at <TThreadMessageHandlerBase.ProcessEvents> ' + TThread.CurrentThread.ThreadID.ToString + ' - ' + LSize.ToString + ' - Error: ' + E.Message); end; end; end else begin Exit; end; end; wrAbandoned: begin Exit; end; end; until (LSize = 0) or (LRes = TWaitResult.wrTimeout); end; end; procedure TThreadMessageHandlerBase.ProcessQueuedMessage(AMessage: IMessage); begin ProcessMessage(AMessage); end; procedure TThreadMessageHandlerBase.AddMessage(AMessage: IMessage); var LSize: Integer; LRes : TWaitResult; begin repeat LRes := FMessages.PushItem(AMessage, LSize); case LRes of wrTimeout: begin FMessages.Grow(LSize); if Terminated then Exit; end; end; until LRes = TWaitResult.wrSignaled; Inc(FMessageCount); end; procedure TThreadMessageHandlerBase.ReleaseRead; begin FSynchronizer.EndRead; end; procedure TThreadMessageHandlerBase.ReleaseWrite; begin FSynchronizer.EndWrite; end; procedure TThreadMessageHandlerBase.SetIsBusy(const AValue: Boolean); begin FLock.Enter; try FIsBusy := AValue; finally FLock.Exit; end; end; procedure TThreadMessageHandlerBase.Execute; begin ProcessMessages; end; {$ENDREGION} {$REGION 'TThreadMessageHandler'} procedure TThreadMessageHandler.AfterConstruction; begin inherited; Register; end; constructor TThreadMessageHandler.Create; begin inherited Create; FChannel := nil; FListeners := TCollections.CreateList<IMessageListener>; InitializeListeners; end; constructor TThreadMessageHandler.Create(const AChannel: TMessageChannel); begin Create; FChannel := AChannel; end; destructor TThreadMessageHandler.Destroy; begin UnRegister; FinalizeListeners; FListeners := nil; inherited Destroy; end; procedure TThreadMessageHandler.FinalizeListeners; var LListener: IMessageListener; LList : IList<IMessageListener>; begin LList := TCollections.CreateList<IMessageListener>; FSynchronizerListeners.BeginRead; try LList.AddRange(FListeners.ToArray); finally FSynchronizerListeners.EndRead; end; for LListener in LList do LListener.UnRegister; end; function TThreadMessageHandler.GetEventRelevant(AMessage: IMessage): Boolean; begin Result := True; end; function TThreadMessageHandler.GetListenersCount: Integer; begin FSynchronizerListeners.BeginRead; try Result := FListeners.Count; finally FSynchronizerListeners.EndRead; end; end; procedure TThreadMessageHandler.InitializeListeners; begin // end; procedure TThreadMessageHandler.ProcessMessage(AMessage: IMessage); var I: Integer; begin FSynchronizerListeners.BeginRead; try for I := 0 to FListeners.Count - 1 do begin if (FListeners[I].Enabled) and (((FListeners[I].TypeRestriction = mtrAllowDescendants) and (AMessage is FListeners[I].GetMessajeClass)) or ((FListeners[I].GetTypeRestriction = mtrDefinedTypeOnly) and (AMessage.GetAsObject.ClassType = FListeners[I].GetMessajeClass))) and (FListeners[I].GetConditionsMatch(AMessage)) then begin try FListeners[I].DoOnNewMessage(AMessage); except on E: Exception do begin Utils.IdeDebugMsg('Exception executing the listener: ' + FListeners[I].GetAsObject.QualifiedClassName + ' - Error: ' + E.Message); Utils.IdeDebugMsg('Exception message class type: ' + AMessage.GetAsObject.QualifiedClassName); end; end; end; end; finally FSynchronizerListeners.EndRead; end; end; procedure TThreadMessageHandler.Register; begin FChannel.AddThreadMensajes(Self) end; procedure TThreadMessageHandler.RegisterListener(AMessageListener: IMessageListener); begin FSynchronizerListeners.BeginWrite; try if (not FListeners.Contains(AMessageListener)) then FListeners.Add(AMessageListener); finally FSynchronizerListeners.EndWrite; end; end; procedure TThreadMessageHandler.UnRegister; begin FChannel.RemoveThreadMensajes(Self) end; procedure TThreadMessageHandler.UnregisterListener(AMessageListener: IMessageListener); begin FSynchronizerListeners.BeginWrite; try if FListeners.Contains(AMessageListener) then FListeners.remove(AMessageListener); finally FSynchronizerListeners.EndWrite; end; end; {$ENDREGION} {$REGION 'Messages' } class procedure MessageBus.CreateIni; begin FChannels := TCollections.CreateList<TMessageChannel>; FChannelsByName := TCollections.CreateDictionary<String, TMessageChannel>; FMessageDeploymentKind:= EMessageDeploymentKind.mdkPooled; FScheduler := TMessagesScheduler.Create; RegisterChannel(DEFAULT_CHANNEL_SINGLED_THREADED, 1); RegisterChannel(DEFAULT_CHANNEL_MULTI_THREADED, Utils.iif<Integer>((TThread.ProcessorCount > MAX_DEFAULT_POOLED_THREADS), MAX_DEFAULT_POOLED_THREADS, TThread.ProcessorCount)); end; class procedure MessageBus.DestroyIni; var LChannel: TMessageChannel; begin FScheduler.Destroy; for LChannel in FChannelsByName.Values do LChannel.Free; FChannelsByName := nil; FChannels := nil; end; class function MessageBus.GetChannel(const AChannelName: String; out AChannel: TMessageChannel): Boolean; begin Result := FChannelsByName.TryGetValue(AChannelName, AChannel); end; class procedure MessageBus.QueueMessage(AMessage: IMessage); begin Guard.CheckNotNull(AMessage, 'The message can not be nil'); QueueInchannels(AMessage); end; class procedure MessageBus.QueueInchannels(AMessage: IMessage); var I: Integer; begin FSynchronizerChannels.BeginRead; try for I := 0 to FChannels.Count - 1 do begin FChannels[I].AddMessage(AMessage); end; finally FSynchronizerChannels.EndRead; end; end; class procedure MessageBus.RegisterChannel(const AChannelName: String; const AThreadCount: Integer); var LChannel: TChannel; begin FSynchronizerChannels.BeginWrite; try if (not FChannelsByName.ContainsKey(AChannelName)) then begin LChannel := TChannel.Create(AChannelName, AThreadCount); FChannels.Add(LChannel); FChannelsByName.Add(AChannelName, LChannel); end else raise Exception.Create('The channel ' + AChannelName + ' already is registered!'); finally FSynchronizerChannels.EndWrite end; end; class procedure MessageBus.UnregisterChannel(const AChannelName: String); var LIndex : Integer; LChannel: TMessageChannel; begin FSynchronizerChannels.BeginWrite; try if FChannelsByName.TryGetValue(AChannelName, LChannel) then begin FChannelsByName.Remove(AChannelName); LIndex := FChannels.IndexOf(LChannel); if LIndex > -1 then FChannels.Delete(LIndex); end; finally FSynchronizerChannels.EndWrite; end; end; {$ENDREGION} {$REGION 'TMessageChannel'} procedure TMessageChannel.AdquireRead; begin FSynchronizer.BeginRead; end; procedure TMessageChannel.AdquireWrite; begin FSynchronizer.BeginWrite; end; procedure TMessageChannel.AddThreadMensajes(const AThreadMensajes: TThreadMessageHandler); begin if not(AThreadMensajes is GetMessajeThreadType) then raise Exception.CreateFmt('Event Pool quiere Threads de Mensajes del tipo "%s", pero se ha intentado registrar un thread de mensajes del tipo "%s"', [GetMessajeThreadType.ClassName, AThreadMensajes.ClassName]); AdquireWrite; try if (not FThreadsMessajes.Contains(AThreadMensajes)) then FThreadsMessajes.Add(AThreadMensajes); finally ReleaseWrite; end; end; procedure TMessageChannel.AfterConstruction; begin inherited; CreateThreads; //Register; end; constructor TMessageChannel.Create(const AName: string; const AThreadCount: Integer); begin inherited Create; FName := AName; FThreadCount := AThreadCount; FThreadsMessajes := TCollections.CreateList<TThreadMessageHandler>; FExecutors := TCollections.CreateList<TThreadMessageHandler>; end; procedure TMessageChannel.CreateThreads; var I: Integer; begin for I := 1 to FThreadCount do begin GetMessajeThreadType.Create(Self); end; end; destructor TMessageChannel.Destroy; begin DestroyThreads; FThreadsMessajes := nil; FExecutors := nil; inherited; end; procedure TMessageChannel.DestroyThreads; var I, LCount: Integer; begin AdquireWrite; try FThreadCount := 0; AdquireWrite; try LCount := FThreadsMessajes.Count; for I := LCount - 1 downto 0 do FThreadsMessajes[I].Free; finally ReleaseWrite; end; finally ReleaseWrite; end; end; function TMessageChannel.GetName: string; begin Result := FName; end; function TMessageChannel.GetThreadCount: Integer; begin AdquireRead; try Result := FThreadCount; finally ReleaseRead; end; end; function Comparador_TThreadMessageHandler(const DatoI, DatoD: TThreadMessageHandler): Integer; var LThisThreadEventCountI, LThisThreadEventCountD: Int64; LBusyI, LBusyD : Boolean; begin Result := 0; if (DatoI = DatoD) then Exit(0); LBusyI := DatoI.IsBusy; LBusyD := DatoD.IsBusy; if (LBusyI or LBusyD) then begin if not (LBusyI and LBusyD) then begin if LBusyI then Exit(1) else Exit(-1); end; end; LThisThreadEventCountI := DatoI.ProcessedMessageCount; LThisThreadEventCountD := DatoD.ProcessedMessageCount; if LThisThreadEventCountI < LThisThreadEventCountD then Exit(-1); if LThisThreadEventCountI > LThisThreadEventCountD then Exit(1); end; procedure TMessageChannel.PoolMessage(AMessage: IMessage); var LSelected: TThreadMessageHandler; begin AdquireRead; try FExecutors.AddRange(FThreadsMessajes.ToArray); FExecutors.Sort(Comparador_TThreadMessageHandler); if FExecutors.Count <> 0 then begin LSelected := FExecutors.First; LSelected.AddMessage(AMessage); FExecutors.Clear; end; finally ReleaseRead; end; end; procedure TMessageChannel.ProcessMessage(AMessage: IMessage); begin if FThreadsMessajes.Count > 0 then PoolMessage(AMessage); end; (* procedure TMessageChannel.Register; begin MessageBus.RegisterChannel(Self); end; *) procedure TMessageChannel.RegisterListener(AMessageListener: IMessageListener); var I: Integer; begin AdquireRead; try for I := 0 to FThreadsMessajes.Count - 1 do begin FThreadsMessajes[I].RegisterListener(AMessageListener); end; finally ReleaseRead; end; end; procedure TMessageChannel.ReleaseRead; begin FSynchronizer.EndRead end; procedure TMessageChannel.ReleaseWrite; begin FSynchronizer.EndWrite end; procedure TMessageChannel.RemoveThreadMensajes(const AThreadMensajes: TThreadMessageHandler); var LIndex: Integer; begin AdquireWrite; try LIndex := FThreadsMessajes.IndexOf(AThreadMensajes); if LIndex > -1 then FThreadsMessajes.Delete(LIndex); finally ReleaseWrite; end; end; (* procedure TMessageChannel.UnRegister; begin MessageBus.UnregisterChannel(Self); end; *) procedure TMessageChannel.UnregisterListener(AMessageListener: IMessageListener); var I: Integer; begin AdquireRead; try for I := 0 to FThreadsMessajes.Count - 1 do begin FThreadsMessajes[I].UnregisterListener(AMessageListener); end; finally ReleaseRead; end; end; {$ENDREGION} {$REGION 'TMessageChannel<T>'} function TMessageChannel<T>.GetMessajeThreadType: TThreadMessageHandlerType; begin Result := T; end; {$ENDREGION} {$REGION 'TMessageListenerViewModel<T>'} constructor TMessageListenerViewModel<T>.Create(AViewModel: IViewModel; const AChannel: String; const AFilterCondition: TListenerFilter; const ACodeExecutesInMainUIThread: Boolean; const ATypeRestriction: EMessageTypeRestriction); begin FViewModel := AViewModel; Create(AChannel, AFilterCondition, ACodeExecutesInMainUIThread, ATypeRestriction); end; {$ENDREGION} function TMessageListenerViewModel<T>.GetConditionsMatch(AMessage: IMessage): Boolean; begin if (AMessage.Sender <> FViewModel.GetAsObject) then Exit(False); Result := inherited GetConditionsMatch(AMessage) end; initialization MessageBus.CreateIni; finalization MessageBus.DestroyIni; end.
unit ModflowSmsWriterUnit; interface uses SysUtils, CustomModflowWriterUnit, ModflowPackageSelectionUnit; type TSmsWriter = class(TCustomSolverWriter) private procedure WriteInnerMaximum; procedure WriteInnerHClose; procedure WritePreconditionerLevels; procedure WritePreconditionerDropTolerances; procedure WriteNumberOfOrthogonalizations; procedure WriteReorderingMethod; protected FSmsPackage: TSmsPackageSelection; function Package: TModflowPackageSelection; override; class function Extension: string; override; procedure WriteOptions; procedure WriteNonLinearBlock; function LinearSolver: TSmsLinearSolver; procedure WriteLinearBlock; procedure WriteXmdBlock; public procedure WriteFile(const AFileName: string); end; implementation uses ModflowUnitNumbers, PhastModelUnit, frmProgressUnit; { TSmsWriter } class function TSmsWriter.Extension: string; begin result := '.sms'; end; function TSmsWriter.LinearSolver: TSmsLinearSolver; begin result := slsDefault; if soLinearSolver in FSmsPackage.SmsOverrides then begin result := FSmsPackage.LinearSolver; end; end; function TSmsWriter.Package: TModflowPackageSelection; begin result := Model.ModflowPackages.SmsPackage; end; procedure TSmsWriter.WriteFile(const AFileName: string); var NameOfFile: string; begin if not Package.IsSelected then begin Exit end; if SolverFileGeneratedExternally then begin Exit; end; NameOfFile := FileName(AFileName); // write to simulation name file OpenFile(NameOfFile); try frmProgressMM.AddMessage('Writing SMS Package input'); WriteDataSet0; FSmsPackage := Model.ModflowPackages.SmsPackage; WriteOptions; WriteNonLinearBlock; case LinearSolver of slsDefault: WriteLinearBlock; slsXMD: WriteXmdBlock; else Assert(False); end; finally CloseFile; end; end; procedure TSmsWriter.WriteReorderingMethod; begin if soReorderingMethod in FSmsPackage.SmsOverrides then begin WriteString(' REORDERING_METHOD '); case FSmsPackage.ReorderingMethod of srmNone: WriteString('NONE'); srmReverseCuthillMcKee: WriteString('RKM'); srmMinimumDegreeOrdering: WriteString('MD'); else Assert(False); end; NewLine; end; end; procedure TSmsWriter.WriteNumberOfOrthogonalizations; begin if soNumberOfOrthoganalizations in FSmsPackage.SmsOverrides then begin WriteString(' NUMBER_ORTHOGONALIZATIONS'); WriteInteger(FSmsPackage.NumberOfOrthoganalizations); NewLine; end; end; procedure TSmsWriter.WritePreconditionerDropTolerances; begin if soPreconditionerDropTolerance in FSmsPackage.SmsOverrides then begin WriteString(' PRECONDITIONER_DROP_TOLERANCE'); WriteFloat(FSmsPackage.PreconditionerDropTolerance); NewLine; end; end; procedure TSmsWriter.WritePreconditionerLevels; begin if soPreconditionerLevel in FSmsPackage.SmsOverrides then begin WriteString(' PRECONDITIONER_LEVELS'); WriteInteger(FSmsPackage.PreconditionerLevel); NewLine; end; end; procedure TSmsWriter.WriteInnerHClose; begin WriteString(' INNER_HCLOSE'); if soInnerHclose in FSmsPackage.SmsOverrides then begin WriteFloat(FSmsPackage.InnerHclose); end else begin WriteFloat(0.0001); end; NewLine; end; procedure TSmsWriter.WriteInnerMaximum; begin WriteString(' INNER_MAXIMUM'); if soInnerMaxIterations in FSmsPackage.SmsOverrides then begin WriteInteger(FSmsPackage.InnerMaxIterations); end else begin WriteInteger(100); end; NewLine; end; procedure TSmsWriter.WriteLinearBlock; //var // UseNonLinear: Boolean; begin // UseNonLinear := [soInnerMaxIterations, soInnerHclose, soInnerRclose, // soLinLinearAcceleration, soRelaxationFactor, soPreconditionerLevel, // soPreconditionerDropTolerance, soNumberOfOrthoganalizations, // soScalingMethod, soReorderingMethod] * FSmsPackage.SmsOverrides <> []; // if not UseNonLinear then // begin // Exit; // end; WriteString('BEGIN LINEAR'); NewLine; WriteInnerMaximum; WriteInnerHClose; WriteString(' INNER_RCLOSE'); if soInnerRclose in FSmsPackage.SmsOverrides then begin WriteFloat(FSmsPackage.InnerRclose); if soRcloseOption in FSmsPackage.SmsOverrides then begin case FSmsPackage.RcloseOption of sroAbsolute: {do nothing}; sroL2Norm: WriteString(' L2NORM_RCLOSE'); sroRelative: WriteString(' RELATIVE_RCLOSE'); else Assert(False); end; end; end else begin WriteFloat(0.1); end; NewLine; WriteString(' LINEAR_ACCELERATION '); if soLinLinearAcceleration in FSmsPackage.SmsOverrides then begin case FSmsPackage.LinLinearAcceleration of sllaCg: WriteString('CG'); sllaBiCgStab: WriteString('BICGSTAB'); else Assert(False); end; end else begin WriteString('CG'); end; NewLine; if soRelaxationFactor in FSmsPackage.SmsOverrides then begin WriteString(' RELAXATION_FACTOR'); WriteFloat(FSmsPackage.RelaxationFactor); NewLine; end; WritePreconditionerLevels; WritePreconditionerDropTolerances; WriteNumberOfOrthogonalizations; if soScalingMethod in FSmsPackage.SmsOverrides then begin WriteString(' SCALING_METHOD '); case FSmsPackage.ScalingMethod of ssmNone: WriteString('NONE'); ssmDiagonal: WriteString('DIAGONAL'); ssmL2Norm: WriteString('L2NORM'); else Assert(False); end; NewLine; end; WriteReorderingMethod; WriteString('END LINEAR'); NewLine; NewLine; end; procedure TSmsWriter.WriteNonLinearBlock; //var // UseNonLinear: Boolean; begin // UseNonLinear := False; // if [soOuterHclose, soOuterMaxIt, soUnderRelax, soBacktrackingNumber] // * FSmsPackage.SmsOverrides <> [] then // begin // UseNonLinear := True; // end // else if (soLinearSolver in FSmsPackage.SmsOverrides) // and (FSmsPackage.LinearSolver = slsXMD) then // begin // UseNonLinear := True; // end; // // if not UseNonLinear then // begin // Exit; // end; WriteString('BEGIN NONLINEAR'); NewLine; WriteString(' OUTER_HCLOSE '); if soOuterHclose in FSmsPackage.SmsOverrides then begin WriteFloat(FSmsPackage.OuterHclose); end else begin WriteFloat(0.01); end; NewLine; WriteString(' OUTER_MAXIMUM '); if soOuterMaxIt in FSmsPackage.SmsOverrides then begin WriteInteger(FSmsPackage.MaxOuterIterations); end else begin WriteInteger(100); end; NewLine; WriteString(' UNDER_RELAXATION '); if soUnderRelax in FSmsPackage.SmsOverrides then begin case FSmsPackage.UnderRelaxation of surNone: WriteString('NONE'); surDbd: WriteString('DTD'); surCooley: WriteString('COOLEY'); else Assert(False); end; NewLine; if FSmsPackage.UnderRelaxation = surNone then begin if soUnderRelaxTheta in FSmsPackage.SmsOverrides then begin WriteString(' UNDER_RELAXATION_THETA '); WriteFloat(FSmsPackage.UnderRelaxTheta); NewLine; end; if soUnderRelaxKappa in FSmsPackage.SmsOverrides then begin WriteString(' UNDER_RELAXATION_KAPPA'); WriteFloat(FSmsPackage.UnderRelaxKappa); NewLine; end; if soUnderRelaxGamma in FSmsPackage.SmsOverrides then begin WriteString(' UNDER_RELAXATION_GAMMA'); WriteFloat(FSmsPackage.UnderRelaxGamma); NewLine; end; if soUnderRelaxMomentum in FSmsPackage.SmsOverrides then begin WriteString(' UNDER_RELAXATION_MOMENTUM'); WriteFloat(FSmsPackage.UnderRelaxMomentum); NewLine; end; end; end else begin WriteString('NONE'); NewLine; end; if soBacktrackingNumber in FSmsPackage.SmsOverrides then begin WriteString(' BACKTRACKING_NUMBER'); WriteInteger(FSmsPackage.BacktrackingNumber); NewLine; if FSmsPackage.BacktrackingNumber > 0 then begin if soBacktrackingTolerance in FSmsPackage.SmsOverrides then begin WriteString(' BACKTRACKING_TOLERANCE'); WriteFloat(FSmsPackage.BacktrackingTolerance); NewLine; end; if soBacktrackingReductionFactor in FSmsPackage.SmsOverrides then begin WriteString(' BACKTRACKING_REDUCTION_FACTOR'); WriteFloat(FSmsPackage.BacktrackingReductionFactor); NewLine; end; if soBacktrackingResidualLimit in FSmsPackage.SmsOverrides then begin WriteString(' BACKTRACKING_RESIDUAL_LIMIT'); WriteFloat(FSmsPackage.BacktrackingResidualLimit); NewLine; end; end; end; if (soLinearSolver in FSmsPackage.SmsOverrides) and (FSmsPackage.LinearSolver = slsXMD) then begin WriteString(' LINEAR_SOLVER XMD'); NewLine; end; WriteString('END NONLINEAR'); NewLine; NewLine; end; procedure TSmsWriter.WriteOptions; begin WriteBeginOptions; WriteString(' PRINT_OPTION '); case FSmsPackage.Print of spPrintNone: WriteString('NONE'); spSummary: WriteString('SUMMARY'); spFull: WriteString('ALL'); end; NewLine; WriteString(' COMPLEXITY '); case FSmsPackage.Complexity of scoSimple: WriteString('SIMPLE'); scoModerate: WriteString('MODERATE'); scoComplex: WriteString('COMPLEX'); scoSpecified: WriteString('SPECIFIED'); else Assert(False); end; NewLine; WriteEndOptions; end; procedure TSmsWriter.WriteXmdBlock; var UseXmd: Boolean; begin UseXmd := False; if [soInnerMaxIterations, soInnerHclose, soInnerRclose, soXmdLinearAcceleration, soPreconditionerLevel, soPreconditionerDropTolerance, soNumberOfOrthoganalizations, soReorderingMethod] * FSmsPackage.SmsOverrides <> [] then begin UseXmd := True; end else if (soRedBlackOrder in FSmsPackage.SmsOverrides) and FSmsPackage.RedBlackOrder then begin UseXmd := True; end; if not UseXmd then begin Exit; end; WriteString('BEGIN XMD'); NewLine; WriteInnerMaximum; WriteInnerHClose; WriteString(' INNER_RCLOSE'); if soInnerRclose in FSmsPackage.SmsOverrides then begin WriteFloat(FSmsPackage.InnerRclose); end else begin WriteFloat(0.1); end; NewLine; WriteString(' LINEAR_ACCELERATION '); if soXmdLinearAcceleration in FSmsPackage.SmsOverrides then begin case FSmsPackage.XmdLinearAcceleration of sxlaCg: WriteString('CG'); sxlaOrthomin: WriteString('ORTHOMIN'); sxlaBiCgStab: WriteString('BICGSTAB'); else Assert(False); end; end else begin WriteString('CG'); end; NewLine; WritePreconditionerLevels; WritePreconditionerDropTolerances; WriteNumberOfOrthogonalizations; if (soRedBlackOrder in FSmsPackage.SmsOverrides) and FSmsPackage.RedBlackOrder then begin WriteString(' RED_BLACK_ORDERING'); NewLine; end; WriteReorderingMethod; WriteString('END XMD'); NewLine; end; end.
PROGRAM Voorbeeld_Date; CONST weeks : ARRAY[0..6] OF STRING[9]= ('Zondag','Maanndag','Dinsdag','Woensdag','Donderdag', 'Vrijdag','Zaterdag'); maands : ARRAY[1..12] OF STRING[9]= ('Januari','Februari','Maart','April','Mei','Juni', 'Juli','Augustus','September','Oktober','November', 'December'); VAR jaar : INTEGER; maand,dag,weekdag : BYTE; BEGIN Date(jaar,maand,dag,weekdag); WRITELN('Het is vandaag ',weeks[weekdag],' ',dag,' ',maands[maand], ' ',jaar); END.
unit uPrintRepairStoreReceipt; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Db, DBTables, ComCtrls, ADODB, siComp, PaiDeForms, siLangRT, PaidePrinter; type TRepairReceipt = class TicketHeader : String; RepairNumber : String; Model : String; Description : String; RecDate : TDateTime; ReturnedBy : String; SerialNum : String; Qty : Double; Customer : String; Address : String; Obs : String; Vendor : String; Store : String; DefectType : String; end; TPrintRepairStoreReceipt = class(TFrmParentPrint) lblPrint: TLabel; pnlPrinter: TPanel; AniPrint: TAnimate; btOk: TButton; quRepair: TADOQuery; quRepairCustomer: TStringField; quRepairAddress: TStringField; quRepairReceiveDate: TDateTimeField; quRepairModel: TStringField; quRepairDescription: TStringField; quRepairOBSReceive: TStringField; quRepairIDRepair: TIntegerField; quRepairSysUser: TStringField; quRepairSerialNumber: TStringField; quRepairBackDate: TDateTimeField; quRepairOBSLine1: TStringField; quRepairOBSLine2: TStringField; quRepairOBSLine3: TStringField; quRepairOBSLine4: TStringField; quRepairTicketHeader: TMemoField; quRepairQty: TFloatField; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure btOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure quRepairAfterOpen(DataSet: TDataSet); private RepairReceipt : TRepairReceipt; //Translation sHeader, sRepairN, sDate, sVendor, sTime, sReturnedBy, sModel, sSerial, sDesc, sQty, sCustomer, sAddress, sOBS, sFooter, sRecImpresso, sClickOK : String; MyIDLancamento : Integer; Quit : Boolean; procedure PrintReceipt; procedure PrintSaleRepairReceipt(ARepairtList : TStringList); public procedure Start(IDRepairCli : Integer); overload; procedure Start(ARepairReceiptList : TStringList); overload; end; implementation uses uDM, uPassword, xBase, uMsgBox, uMsgConstant, uDMGlobal, Math; {$R *.DFM} procedure TPrintRepairStoreReceipt.PrintReceipt; var NotOk: Boolean; begin Quit := False; Show; Update; NotOk := True; Application.ProcessMessages; while NotOk do begin try DM.PrinterStart; NotOk := False; except if MsgBox(MSG_CRT_ERROR_PRINTING, vbCritical + vbYesNo) = vbYes then NotOk := True else begin Exit; end; end; end; DM.PrintLine(RepairReceipt.TicketHeader); DM.PrintLine(''); DM.PrintLine(sHeader); DM.PrintLine(' ----------------------------------'); DM.PrintLine(''); DM.PrintLine(sRepairN + RepairReceipt.RepairNumber); DM.PrintLine(sDate + FormatDateTime('ddddd', RepairReceipt.RecDate)); DM.PrintLine(sTime + TimeToStr(RepairReceipt.RecDate)); DM.PrintLine(sReturnedBy + RepairReceipt.ReturnedBy); DM.PrintLine(''); DM.PrintLine(sModel + RepairReceipt.Model); DM.PrintLine(sSerial + RepairReceipt.SerialNum); DM.PrintLine(sDesc + RepairReceipt.Description); DM.PrintLine(sQty + FormatFloat('0.##', RepairReceipt.Qty)); DM.PrintLine(''); DM.PrintLine(sCustomer + RepairReceipt.Customer); DM.PrintLine(sAddress + RepairReceipt.Address); DM.PrintLine(''); DM.PrintLine(sOBS + RepairReceipt.Obs); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(sFooter); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine('.'); DM.PrintLine(Chr(27)+Chr(12)); DM.PrinterStop; lblPrint.Caption := sRecImpresso; btOk.Visible := True; AniPrint.Active := False; AniPrint.Visible := False; pnlPrinter.Caption := sClickOK; Close; end; procedure TPrintRepairStoreReceipt.Start(IDRepairCli : Integer); begin try with quRepair do begin Parameters.ParambyName('IDRepairCli').Value := IDRepairCLi; Open; end; PrintReceipt; finally quRepair.Close; end; end; procedure TPrintRepairStoreReceipt.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; if Assigned(RepairReceipt) then FreeAndNil(RepairReceipt); end; procedure TPrintRepairStoreReceipt.FormShow(Sender: TObject); begin AniPrint.Active := True; btOk.Visible := False; end; procedure TPrintRepairStoreReceipt.btOkClick(Sender: TObject); begin Close; end; procedure TPrintRepairStoreReceipt.FormCreate(Sender: TObject); begin inherited; Case DMGlobal.IDLanguage of LANG_ENGLISH : begin sHeader := ' R E P A I R R E C E I P T'; sRepairN := 'Repair # '; sDate := 'Date : '; sVendor := 'Vendor : '; sTime := 'Time : '; sReturnedBy := 'Returned by: '; sModel := 'Model : '; sSerial := 'Serial # : '; sDesc := 'Description: '; sQty := 'Qty : '; sCustomer := 'Customer : '; sAddress := 'Address : '; sOBS := 'OBS : '; sFooter := '============= END OF TICKET =========='; sRecImpresso:= 'Receipt Printed'; sClickOK := 'Click OK to continue'; end; LANG_PORTUGUESE : begin sHeader := ' R E C I B O D E R E P A R O '; sRepairN := 'N. Reparo '; sDate := 'Data : '; sVendor := 'Fornecedor : '; sTime := 'Hora : '; sReturnedBy := 'Usuario : '; sModel := 'Modelo : '; sSerial := 'N. Série : '; sDesc := 'Descrição : '; sQty := 'Qtd : '; sCustomer := 'Cliente : '; sAddress := 'Endereco : '; sOBS := 'OBS : '; sFooter := '============ FINAL DO RECIBO ========='; sRecImpresso:= 'Recibo Impresso'; sClickOK := 'Clique OK para continuar'; end; LANG_SPANISH : begin sHeader := 'R E C I B O DE R E P A R A C I O N'; sRepairN := 'N. Reparación '; sDate := 'Fecha : '; sVendor := 'Fornecedor : '; sTime := 'Hora : '; sReturnedBy := 'Usuario : '; sModel := 'Modelo : '; sSerial := 'N. Serie : '; sDesc := 'Descripcion: '; sQty := 'Ctd : '; sCustomer := 'Cliente : '; sAddress := 'Dirección : '; sOBS := 'OBS : '; sFooter := '============ FINAL DEL RECIBO ========='; sRecImpresso:= 'Recibo Imprimido'; sClickOK := 'Clic OK para continuar'; end; end; RepairReceipt := TRepairReceipt.Create; end; procedure TPrintRepairStoreReceipt.quRepairAfterOpen(DataSet: TDataSet); begin inherited; RepairReceipt.RepairNumber := quRepairIDRepair.AsString; RepairReceipt.Model := quRepairModel.AsString; RepairReceipt.Description := quRepairDescription.AsString; RepairReceipt.RecDate := quRepairBackDate.AsDateTime; RepairReceipt.ReturnedBy := quRepairSysUser.AsString; RepairReceipt.SerialNum := quRepairSerialNumber.AsString; RepairReceipt.Qty := quRepairQty.AsFloat; RepairReceipt.Customer := quRepairCustomer.AsString; RepairReceipt.Address := quRepairAddress.AsString; RepairReceipt.Obs := quRepairOBSLine1.AsString + ' ' + quRepairOBSLine2.AsString + ' ' + quRepairOBSLine3.AsString + ' ' + quRepairOBSLine4.AsString; RepairReceipt.Vendor := ''; RepairReceipt.TicketHeader := quRepairTicketHeader.AsString; end; procedure TPrintRepairStoreReceipt.Start(ARepairReceiptList : TStringList); begin PrintSaleRepairReceipt(ARepairReceiptList); end; procedure TPrintRepairStoreReceipt.PrintSaleRepairReceipt(ARepairtList : TStringList); var NotOk: Boolean; i : Integer; begin Quit := False; Show; Update; NotOk := True; Application.ProcessMessages; for i := 0 to ARepairtList.Count-1 do begin while NotOk do begin try DM.PrinterStart; NotOk := False; except if MsgBox(MSG_CRT_ERROR_PRINTING, vbCritical + vbYesNo) = vbYes then NotOk := True else Exit; end; end; RepairReceipt.RepairNumber := TRepairReceipt(ARepairtList.Objects[i]).RepairNumber; RepairReceipt.Model := TRepairReceipt(ARepairtList.Objects[i]).Model; RepairReceipt.Description := TRepairReceipt(ARepairtList.Objects[i]).Description; RepairReceipt.RecDate := TRepairReceipt(ARepairtList.Objects[i]).RecDate; RepairReceipt.ReturnedBy := TRepairReceipt(ARepairtList.Objects[i]).ReturnedBy; RepairReceipt.SerialNum := TRepairReceipt(ARepairtList.Objects[i]).SerialNum; RepairReceipt.Qty := TRepairReceipt(ARepairtList.Objects[i]).Qty; RepairReceipt.Customer := TRepairReceipt(ARepairtList.Objects[i]).Customer; RepairReceipt.Address := TRepairReceipt(ARepairtList.Objects[i]).Address; RepairReceipt.Obs := TRepairReceipt(ARepairtList.Objects[i]).Obs; RepairReceipt.Vendor := TRepairReceipt(ARepairtList.Objects[i]).Vendor; RepairReceipt.Store := TRepairReceipt(ARepairtList.Objects[i]).Store; RepairReceipt.DefectType := TRepairReceipt(ARepairtList.Objects[i]).DefectType; DM.PrintLine(sHeader); DM.PrintLine(' ----------------------------------'); if RepairReceipt.RepairNumber <> '' then DM.PrintLine(sRepairN + RepairReceipt.RepairNumber); DM.PrintLine(sVendor + RepairReceipt.Vendor); DM.PrintLine(sDate + FormatDateTime('ddddd', RepairReceipt.RecDate) + ' ' + TimeToStr(RepairReceipt.RecDate)); DM.PrintLine(sReturnedBy + RepairReceipt.ReturnedBy); DM.PrintLine(sModel + RepairReceipt.Model); DM.PrintLine(sSerial + RepairReceipt.SerialNum); DM.PrintLine(sDesc + RepairReceipt.Description); DM.PrintLine(sQty + FormatFloat('0.##', RepairReceipt.Qty)); DM.PrintLine(sOBS + RepairReceipt.Obs); DM.PrintLine(sFooter); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(Chr(27)+Chr(12)); DM.PrinterStop; NotOk := True; end; lblPrint.Caption := sRecImpresso; btOk.Visible := True; AniPrint.Active := False; AniPrint.Visible := False; pnlPrinter.Caption := sClickOK; Close; end; end.
(* Copyright (c) 2016 Darian Miller 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, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation. 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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder. As of January 2016, latest version available online at: https://github.com/darianmiller/dxLib_Tests *) unit dxLib_Test_JSONObjectSimple; interface {$I '..\Dependencies\dxLib\Source\dxLib.inc'} uses TestFramework, dxLib_JSONObjects; type TTestEmployeeStatus = (esEmployeeUndefined, esEmployeeStandard, esEmployeeManager); //Basic example TExampleObjectTypical = class private fCurrentProcess:Integer; fFirstName:String; fLastName:String; fSalary:Currency; fStatus:TTestEmployeeStatus; public property CurrentProcess:Integer read fCurrentProcess write fCurrentProcess; property FirstName:String read fFirstName write fFirstName; property LastName:String read fLastName write fLastName; property Salary:Currency read fSalary write fSalary; property Status:TTestEmployeeStatus read fStatus write fStatus; end; //Change to support JSON: //1) Inherit from TdxJSONObject //2) Change the specific properties desired to be serialized into 'Published' properties TExampleObjectJSON = class(TdxJSONObject) private fCurrentProcess:Integer; fFirstName:String; fLastName:String; fSalary:Currency; fStatus:TTestEmployeeStatus; public property CurrentProcess:Integer read fCurrentProcess write fCurrentProcess; published property FirstName:String read fFirstName write fFirstName; property LastName:String read fLastName write fLastName; property Salary:Currency read fSalary write fSalary; property Status:TTestEmployeeStatus read fStatus write fStatus default esEmployeeStandard; end; (* can now use the object as normal, with the addition of: 1) SET/GET routines (via .AsJSON) 2) default values are respected for Ordinal types x := TExampleObjectJSON.Create(); //Assign from JSON x.AsJSON := {"FirstName":"Darian", "LastName":"Miller", "Salary":1234.56, "Status":"esEmployeeManager"} x.Salary := 2000; //Serialize to JSON ShowMessage(x.AsJSON); //will display {"FirstName":"Darian","LastName":"Miller","Salary":2000.00,"Status":"esEmployeeManager"} *) TestTdxJSONObjectSimple = class(TTestCase) published procedure TestDefaultValueChangedBehavior(); procedure TestExampleObjectBasicUsage(); end; implementation procedure TestTdxJSONObjectSimple.TestDefaultValueChangedBehavior(); var vOriginal:TExampleObjectTypical; vNewBehavior:TExampleObjectJSON; begin vOriginal := TExampleObjectTypical.Create(); vNewBehavior := TExampleObjectJSON.Create(); try //JSON objects respect DEFAULT values, typically reserved for Delphi form components //If you want to eliminate this new behavior, rebuild with an empty set: PROPERTIES_WITH_DEFAULT_VALUES CheckFalse(vOriginal.Status = vNewBehavior.Status); finally vOriginal.Free(); vNewBehavior.Free(); end; end; procedure TestTdxJSONObjectSimple.TestExampleObjectBasicUsage(); const EXAMPLE_DATA = '{"FirstName":"Darian","LastName":"Miller","Salary":1234.56,"Status":"esEmployeeManager"}'; EXAMPLE_DEFAULT = '{"FirstName":"","LastName":"","Salary":0.00,"Status":"esEmployeeStandard"}'; var x:TExampleObjectJSON; begin x := TExampleObjectJSON.Create(); try CheckEqualsString(EXAMPLE_DEFAULT, x.AsJSON); x.AsJSON := EXAMPLE_DATA; CheckEqualsString(EXAMPLE_DATA, x.AsJSON); finally x.Free(); end; end; initialization RegisterTest(TestTdxJSONObjectSimple.Suite); end.
{**************************************************************************************************} { } { Project JEDI Code Library (JCL) extension } { } { 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 DelphiInstall.pas. } { } { The Initial Developer of the Original Code is documented in the accompanying } { help file JCL.chm. Portions created by these individuals are Copyright (C) of these individuals. } { } {**************************************************************************************************} { } { Routines for getting infomation about installed versions of Delphi and peforming basic } { instalation tasks. } { } { Unit owner: Petr Vones } { Last modified: September 29, 2002 } { } {**************************************************************************************************} unit DelphiInstall; {$I jcl.inc} {$WEAKPACKAGEUNIT ON} interface uses Windows, Classes, SysUtils, IniFiles, {$IFDEF DELPHI5_UP} Contnrs, {$ENDIF DELPHI5_UP} JclBase; const //-------------------------------------------------------------------------------------------------- // Various definitions //-------------------------------------------------------------------------------------------------- // Object Repository DelphiRepositoryPagesSection = 'Repository Pages'; DelphiRepositoryDialogsPage = 'Dialogs'; DelphiRepositoryFormsPage = 'Forms'; DelphiRepositoryProjectsPage = 'Projects'; DelphiRepositoryDataModulesPage = 'Data Modules'; DelphiRepositoryObjectType = 'Type'; DelphiRepositoryFormTemplate = 'FormTemplate'; DelphiRepositoryProjectTemplate = 'ProjectTemplate'; DelphiRepositoryObjectName = 'Name'; DelphiRepositoryObjectPage = 'Page'; DelphiRepositoryObjectIcon = 'Icon'; DelphiRepositoryObjectDescr = 'Description'; DelphiRepositoryObjectAuthor = 'Author'; DelphiRepositoryObjectAncestor = 'Ancestor'; DelphiRepositoryObjectDesigner = 'Designer'; // Delphi 6+ only DelphiRepositoryDesignerDfm = 'dfm'; DelphiRepositoryDesignerXfm = 'xfm'; DelphiRepositoryObjectNewForm = 'DefaultNewForm'; DelphiRepositoryObjectMainForm = 'DefaultMainForm'; // Delphi path DelphiLibraryPathSeparator = ';'; //-------------------------------------------------------------------------------------------------- // Installed versions information classes //-------------------------------------------------------------------------------------------------- type TJclDelphiEdition = (deSTD, dePRO, deCSS); TJclDelphiPath = string; TJclDelphiInstallation = class; TJclDelphiInstallationObject = class (TObject) private FInstallation: TJclDelphiInstallation; protected constructor Create(AInstallation: TJclDelphiInstallation); public property Installation: TJclDelphiInstallation read FInstallation; end; TJclDelphiOpenHelp = class (TJclDelphiInstallationObject) private function GetContentFileName: string; function GetIndexFileName: string; function GetLinkFileName: string; function GetGidFileName: string; function GetProjectFileName: string; function ReadFileName(const FormatName: string): string; public function AddHelpFile(const HelpFileName, IndexName: string): Boolean; property ContentFileName: string read GetContentFileName; property GidFileName: string read GetGidFileName; property IndexFileName: string read GetIndexFileName; property LinkFileName: string read GetLinkFileName; property ProjectFileName: string read GetProjectFileName; end; TJclDelphiIdeTool = class (TJclDelphiInstallationObject) private FRegKey: string; function GetCount: Integer; function GetParameters(Index: Integer): string; function GetPath(Index: Integer): string; function GetTitle(Index: Integer): string; function GetWorkingDir(Index: Integer): string; procedure SetCount(const Value: Integer); procedure SetParameters(Index: Integer; const Value: string); procedure SetPath(Index: Integer; const Value: string); procedure SetTitle(Index: Integer; const Value: string); procedure SetWorkingDir(Index: Integer; const Value: string); protected constructor Create(AInstallation: TJclDelphiInstallation); procedure CheckIndex(Index: Integer); public property Count: Integer read GetCount write SetCount; function IndexOfPath(const Value: string): Integer; function IndexOfTitle(const Value: string): Integer; property Title[Index: Integer]: string read GetTitle write SetTitle; property Path[Index: Integer]: string read GetPath write SetPath; property RegKey: string read FRegKey; property Parameters[Index: Integer]: string read GetParameters write SetParameters; property WorkingDir[Index: Integer]: string read GetWorkingDir write SetWorkingDir; end; TJclDelphiIdePackages = class (TJclDelphiInstallationObject) private FDisabledPackages: TStringList; FKnownPackages: TStringList; function GetCount: Integer; function GetPackageDescriptions(Index: Integer): string; function GetPackageDisabled(Index: Integer): Boolean; function GetPackageFileNames(Index: Integer): string; protected constructor Create(AInstallation: TJclDelphiInstallation); function PackageEntryToFileName(const Entry: string): string; procedure ReadPackages; procedure RemoveDisabled(const FileName: string); public destructor Destroy; override; function AddPackage(const FileName, Description: string): Boolean; property Count: Integer read GetCount; property PackageDescriptions[Index: Integer]: string read GetPackageDescriptions; property PackageFileNames[Index: Integer]: string read GetPackageFileNames; property PackageDisabled[Index: Integer]: Boolean read GetPackageDisabled; end; TJclDelphiCompiler = class (TJclDelphiInstallationObject) private FDCC32Location: string; FOptions: TStrings; protected constructor Create(AInstallation: TJclDelphiInstallation); public destructor Destroy; override; procedure AddPathOption(const Option, Path: string); function Compile(const CommandLine: string): Boolean; function InstallPackage(const PackageName, BPLPath, DCPPath: string): Boolean; property DCC32Location: string read FDCC32Location; property Options: TStrings read FOptions; end; TJclDelphiPalette = class (TJclDelphiInstallationObject) private FRegKey: string; FTabNames: TStringList; function GetComponentsOnTab(Index: Integer): string; function GetHiddenComponentsOnTab(Index: Integer): string; function GetTabNameCount: Integer; function GetTabNames(Index: Integer): string; procedure ReadTabNames; protected constructor Create(AInstallation: TJclDelphiInstallation); public destructor Destroy; override; procedure ComponentsOnTabToStrings(Index: Integer; Strings: TStrings; IncludeUnitName: Boolean = False; IncludeHiddenComponents: Boolean = True); function DeleteTabName(const TabName: string): Boolean; function TabNameExists(const TabName: string): Boolean; property ComponentsOnTab[Index: Integer]: string read GetComponentsOnTab; property HiddenComponentsOnTab[Index: Integer]: string read GetHiddenComponentsOnTab; property TabNames[Index: Integer]: string read GetTabNames; property TabNameCount: Integer read GetTabNameCount; end; TJclDelphiRepository = class (TJclDelphiInstallationObject) private FIniFile: TIniFile; FFileName: string; FPages: TStrings; function GetIniFile: TIniFile; protected constructor Create(AInstallation: TJclDelphiInstallation); public destructor Destroy; override; procedure AddObject(const FileName, ObjectType, PageName, ObjectName, IconFileName, Description, Author, Designer: string; const Ancestor: string = ''); procedure CloseIniFile; function FindPage(const Name: string; OptionalIndex: Integer): string; procedure RemoveObjects(const PartialPath, FileName, ObjectType: string); property FileName: string read FFileName; property IniFile: TIniFile read GetIniFile; property Pages: TStrings read FPages; end; TJclDelphiInstallation = class (TObject) private FBinFolderName: string; FCompiler: TJclDelphiCompiler; FEdition: TJclDelphiEdition; FEnvironmentVariables: TStrings; FIdeExeFileName: string; FIdePackages: TJclDelphiIdePackages; FIdeTools: TJclDelphiIdeTool; FInstalledUpdatePack: Integer; FLatestUpdatePack: Integer; FOpenHelp: TJclDelphiOpenHelp; FPalette: TJclDelphiPalette; FRegKey: string; FRegKeyValues: TStrings; FRepository: TJclDelphiRepository; FRootDir: string; FVersionNumber: Byte; function GetBPLOutputPath: string; function GetComplier: TJclDelphiCompiler; function GetDCPOutputPath: string; function GetEditionAsText: string; function GetEnvironmentVariables: TStrings; function GetIdeExeBuildNumber: string; function GetIdePackages: TJclDelphiIdePackages; function GetLibrarySearchPath: TJclDelphiPath; function GetName: string; function GetRepository: TJclDelphiRepository; function GetUpdateNeeded: Boolean; function GetValid: Boolean; procedure SetLibrarySearchPath(const Value: TJclDelphiPath); function GetPalette: TJclDelphiPalette; protected constructor Create(const ARegKey: string); procedure ReadInformation; public destructor Destroy; override; class procedure ExtractPaths(const Path: TJclDelphiPath; List: TStrings); function AnyInstanceRunning: Boolean; function AddToLibrarySearchPath(const Path: string): Boolean; function FindFolderInDelphiPath(Folder: string; List: TStrings): Integer; function SubstitutePath(const Path: string): string; property BinFolderName: string read FBinFolderName; property BPLOutputPath: string read GetBPLOutputPath; property Compiler: TJclDelphiCompiler read GetComplier; property DCPOutputPath: string read GetDCPOutputPath; property Edition: TJclDelphiEdition read FEdition; property EditionAsText: string read GetEditionAsText; property EnvironmentVariables: TStrings read GetEnvironmentVariables; property IdePackages: TJclDelphiIdePackages read GetIdePackages; property IdeTools: TJclDelphiIdeTool read FIdeTools; property IdeExeBuildNumber: string read GetIdeExeBuildNumber; property IdeExeFileName: string read FIdeExeFileName; property InstalledUpdatePack: Integer read FInstalledUpdatePack; property LatestUpdatePack: Integer read FLatestUpdatePack; property LibrarySearchPath: TJclDelphiPath read GetLibrarySearchPath write SetLibrarySearchPath; property OpenHelp: TJclDelphiOpenHelp read FOpenHelp; property Name: string read GetName; property Palette: TJclDelphiPalette read GetPalette; property RegKey: string read FRegKey; property RegKeyValues: TStrings read FRegKeyValues; property Repository: TJclDelphiRepository read GetRepository; property RootDir: string read FRootDir; property UpdateNeeded: Boolean read GetUpdateNeeded; property Valid: Boolean read GetValid; property VersionNumber: Byte read FVersionNumber; end; TJclDelphiInstallations = class (TObject) private FList: TObjectList; function GetCount: Integer; function GetInstallations(Index: Integer): TJclDelphiInstallation; function GetVersionInstalled(VersionNumber: Byte): Boolean; function GetInstallationFromVersion(VersionNumber: Byte): TJclDelphiInstallation; protected procedure ReadInstallations; public constructor Create; destructor Destroy; override; function AnyInstanceRunning: Boolean; function AnyUpdatePackNeeded(var Text: string): Boolean; property Count: Integer read GetCount; property Installations[Index: Integer]: TJclDelphiInstallation read GetInstallations; default; property InstallationFromVersion[VersionNumber: Byte]: TJclDelphiInstallation read GetInstallationFromVersion; property VersionInstalled[VersionNumber: Byte]: Boolean read GetVersionInstalled; end; implementation uses JclFileUtils, JclLogic, JclMiscel, JclRegistry, JclStrings, JclSysInfo, JclSysUtils; //================================================================================================== // Internal //================================================================================================== type TUpdatePack = record DelphiVersion: Byte; LatestUpdatePack: Integer; end; const MSHelpSystemKeyName = 'Software\Microsoft\Windows\Help'; DelphiKeyName = 'SOFTWARE\Borland\Delphi'; RootDirValueName = 'RootDir'; VersionValueName = 'Version'; LibraryKeyName = 'Library'; LibrarySearchPathValueName = 'Search Path'; LibraryBPLOutputValueName = 'Package DPL Output'; LibraryDCPOutputValueName = 'Package DCP Output'; TransferKeyName = 'Transfer'; TransferCountValueName = 'Count'; TransferPathValueName = 'Path%d'; TransferParamsValueName = 'Params%d'; TransferTitleValueName = 'Title%d'; TransferWorkDirValueName = 'WorkingDir%d'; DisabledPackagesKeyName = 'Disabled Packages'; EnvVariablesKeyName = 'Environment Variables'; KnownPackagesKeyName = 'Known Packages'; PaletteKeyName = 'Palette'; PaletteHiddenTag = '.Hidden'; DelphiIdeFileName = 'Bin\delphi32.exe'; DelphiRepositoryFileName = 'Bin\delphi32.dro'; DCC32FileName = 'Bin\dcc32.exe'; DelphiHelpContentFileName = 'Help\%s.ohc'; DelphiHelpIndexFileName = 'Help\%s.ohi'; DelphiHelpLinkFileName = 'Help\%s.ohl'; DelphiHelpProjectFileName = 'Help\%s.ohp'; DelphiHelpGidFileName = 'Help\%s.gid'; DelphiHelpNamePart1 = 'delphi%d'; DelphiHelpNamePart2 = 'd%d'; LatestUpdatePacks: array [1..4] of TUpdatePack = ( // Updated Sep 5, 2002 (DelphiVersion: 4; LatestUpdatePack: 3), (DelphiVersion: 5; LatestUpdatePack: 1), (DelphiVersion: 6; LatestUpdatePack: 2), (DelphiVersion: 7; LatestUpdatePack: 0) ); resourcestring RsIndexOufOfRange = 'Index out of range'; RsDelphiName = 'Delphi %d %s'; RsNeedUpdate = 'You should install latest Update Pack #%d for %s'; RsUpdatePackName = 'Update Pack #%d'; RsStandard = 'Standard'; RsProfessional = 'Professional'; RsClientServer = 'Client/Server'; RsEnterprise = 'Enterprise'; RsPersonal = 'Personal'; //-------------------------------------------------------------------------------------------------- function RegGetValueNamesAndValues(const RootKey: HKEY; const Key: string; const List: TStrings): Boolean; var I: Integer; TempList: TStringList; begin TempList := TStringList.Create; try Result := RegKeyExists(RootKey, Key) and RegGetValueNames(RootKey, Key, TempList); if Result then begin for I := 0 to TempList.Count - 1 do TempList[I] := TempList[I] + '=' + RegReadStringDef(RootKey, Key, TempList[I], ''); List.AddStrings(TempList); end; finally TempList.Free; end; end; //================================================================================================== // TJclDelphiInstallationObject //================================================================================================== constructor TJclDelphiInstallationObject.Create(AInstallation: TJclDelphiInstallation); begin FInstallation := AInstallation; end; //================================================================================================== // TJclDelphiOpenHelp //================================================================================================== function TJclDelphiOpenHelp.AddHelpFile(const HelpFileName, IndexName: string): Boolean; var CntFileName, HelpName, CntName: string; List: TStringList; procedure AddToList(const FileName, Text: string); var I, Attr: Integer; Found: Boolean; begin List.LoadFromFile(FileName); Found := False; for I := 0 to List.Count - 1 do if AnsiSameText(Trim(List[I]), Text) then begin Found := True; Break; end; if not Found then begin List.Add(Text); Attr := FileGetAttr(FileName); FileSetAttr(FileName, faArchive); List.SaveToFile(FileName); FileSetAttr(FileName, Attr); end; end; begin CntFileName := ChangeFileExt(HelpFileName, '.cnt'); Result := FileExists(HelpFileName) and FileExists(CntFileName); if Result then begin HelpName := ExtractFileName(HelpFileName); CntName := ExtractFileName(CntFileName); RegWriteString(HKEY_LOCAL_MACHINE, MSHelpSystemKeyName, HelpName, ExtractFilePath(HelpFileName)); RegWriteString(HKEY_LOCAL_MACHINE, MSHelpSystemKeyName, CntName, ExtractFilePath(CntFileName)); List := TStringList.Create; try AddToList(ContentFileName, Format(':Include %s', [CntName])); AddToList(LinkFileName, Format(':Link %s', [HelpName])); AddToList(IndexFileName, Format(':Index %s=%s', [IndexName, HelpName])); SetFileLastWrite(ProjectFileName, Now); DeleteFile(GidFileName); finally List.Free; end; end; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiOpenHelp.GetContentFileName: string; begin Result := ReadFileName(DelphiHelpContentFileName); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiOpenHelp.GetGidFileName: string; begin Result := ReadFileName(DelphiHelpGidFileName); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiOpenHelp.GetIndexFileName: string; begin Result := ReadFileName(DelphiHelpIndexFileName); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiOpenHelp.GetLinkFileName: string; begin Result := ReadFileName(DelphiHelpLinkFileName); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiOpenHelp.GetProjectFileName: string; begin Result := ReadFileName(DelphiHelpProjectFileName); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiOpenHelp.ReadFileName(const FormatName: string): string; begin with Installation do begin Result := PathAddSeparator(RootDir) + Format(FormatName, [Format(DelphiHelpNamePart1, [VersionNumber])]); if not FileExists(Result) then Result := PathAddSeparator(RootDir) + Format(FormatName, [Format(DelphiHelpNamePart2, [VersionNumber])]); end; end; //================================================================================================== // TJclDelphiIdeTool //================================================================================================== procedure TJclDelphiIdeTool.CheckIndex(Index: Integer); begin if (Index < 0) or (Index >= Count) then raise EJclError.CreateResRec(@RsIndexOufOfRange); end; //-------------------------------------------------------------------------------------------------- constructor TJclDelphiIdeTool.Create(AInstallation: TJclDelphiInstallation); begin inherited; FRegKey := Installation.RegKey + '\' + TransferKeyName; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiIdeTool.GetCount: Integer; begin Result := RegReadIntegerDef(HKEY_CURRENT_USER, RegKey, TransferCountValueName, 0); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiIdeTool.GetParameters(Index: Integer): string; begin CheckIndex(Index); Result := RegReadStringDef(HKEY_CURRENT_USER, RegKey, Format(TransferParamsValueName, [Index]), ''); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiIdeTool.GetPath(Index: Integer): string; begin CheckIndex(Index); Result := RegReadStringDef(HKEY_CURRENT_USER, RegKey, Format(TransferPathValueName, [Index]), ''); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiIdeTool.GetTitle(Index: Integer): string; begin CheckIndex(Index); Result := RegReadStringDef(HKEY_CURRENT_USER, RegKey, Format(TransferTitleValueName, [Index]), ''); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiIdeTool.GetWorkingDir(Index: Integer): string; begin CheckIndex(Index); Result := RegReadStringDef(HKEY_CURRENT_USER, RegKey, Format(TransferWorkDirValueName, [Index]), ''); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiIdeTool.IndexOfPath(const Value: string): Integer; var I: Integer; begin Result := -1; for I := 0 to Count - 1 do if AnsiSameText(Title[I], Value) then begin Result := I; Break; end; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiIdeTool.IndexOfTitle(const Value: string): Integer; var I: Integer; begin Result := -1; for I := 0 to Count - 1 do if Title[I] = Value then begin Result := I; Break; end; end; //-------------------------------------------------------------------------------------------------- procedure TJclDelphiIdeTool.SetCount(const Value: Integer); begin if Value > Count then RegWriteInteger(HKEY_CURRENT_USER, RegKey, TransferCountValueName, Value); end; //-------------------------------------------------------------------------------------------------- procedure TJclDelphiIdeTool.SetParameters(Index: Integer; const Value: string); begin CheckIndex(Index); RegWriteString(HKEY_CURRENT_USER, RegKey, Format(TransferParamsValueName, [Index]), Value); end; //-------------------------------------------------------------------------------------------------- procedure TJclDelphiIdeTool.SetPath(Index: Integer; const Value: string); begin CheckIndex(Index); RegWriteString(HKEY_CURRENT_USER, RegKey, Format(TransferPathValueName, [Index]), Value); end; //-------------------------------------------------------------------------------------------------- procedure TJclDelphiIdeTool.SetTitle(Index: Integer; const Value: string); begin CheckIndex(Index); RegWriteString(HKEY_CURRENT_USER, RegKey, Format(TransferTitleValueName, [Index]), Value); end; //-------------------------------------------------------------------------------------------------- procedure TJclDelphiIdeTool.SetWorkingDir(Index: Integer; const Value: string); begin CheckIndex(Index); RegWriteString(HKEY_CURRENT_USER, RegKey, Format(TransferWorkDirValueName, [Index]), Value); end; //================================================================================================== // TJclDelphiIdePackages //================================================================================================== function TJclDelphiIdePackages.AddPackage(const FileName, Description: string): Boolean; begin Result := True; RemoveDisabled(FileName); RegWriteString(HKEY_CURRENT_USER, Installation.RegKey + '\' + KnownPackagesKeyName, FileName, Description); ReadPackages; end; //-------------------------------------------------------------------------------------------------- constructor TJclDelphiIdePackages.Create(AInstallation: TJclDelphiInstallation); begin inherited; FDisabledPackages := TStringList.Create; FDisabledPackages.Sorted := True; FDisabledPackages.Duplicates := dupIgnore; FKnownPackages := TStringList.Create; FKnownPackages.Sorted := True; FKnownPackages.Duplicates := dupIgnore; ReadPackages; end; //-------------------------------------------------------------------------------------------------- destructor TJclDelphiIdePackages.Destroy; begin FreeAndNil(FDisabledPackages); FreeAndNil(FKnownPackages); inherited; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiIdePackages.GetCount: Integer; begin Result := FKnownPackages.Count; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiIdePackages.GetPackageDescriptions(Index: Integer): string; begin Result := FKnownPackages.Values[FKnownPackages.Names[Index]]; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiIdePackages.GetPackageDisabled(Index: Integer): Boolean; begin Result := Boolean(FKnownPackages.Objects[Index]); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiIdePackages.GetPackageFileNames(Index: Integer): string; begin Result := PackageEntryToFileName(FKnownPackages.Names[Index]); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiIdePackages.PackageEntryToFileName(const Entry: string): string; begin Result := PathGetLongName2(Installation.SubstitutePath(Entry)); end; //-------------------------------------------------------------------------------------------------- procedure TJclDelphiIdePackages.ReadPackages; var I: Integer; begin FDisabledPackages.Clear; FKnownPackages.Clear; if RegGetValueNamesAndValues(HKEY_CURRENT_USER, Installation.RegKey + '\' + KnownPackagesKeyName, FKnownPackages) and RegGetValueNamesAndValues(HKEY_CURRENT_USER, Installation.RegKey + '\' + DisabledPackagesKeyName, FDisabledPackages) then for I := 0 to Count - 1 do if FDisabledPackages.IndexOfName(FKnownPackages.Names[I]) <> -1 then FKnownPackages.Objects[I] := Pointer(True); end; //-------------------------------------------------------------------------------------------------- procedure TJclDelphiIdePackages.RemoveDisabled(const FileName: string); var I: Integer; begin for I := 0 to FDisabledPackages.Count - 1 do if AnsiSameText(FileName, PackageEntryToFileName(FDisabledPackages.Names[I])) then begin RegDeleteEntry(HKEY_CURRENT_USER, Installation.RegKey + '\' + DisabledPackagesKeyName, FDisabledPackages.Names[I]); ReadPackages; Break; end; end; //================================================================================================== // TJclDelphiCompiler //================================================================================================== procedure TJclDelphiCompiler.AddPathOption(const Option, Path: string); begin Options.Add(Format('-%s"%s"', [Option, PathRemoveSeparator(Path)])); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiCompiler.Compile(const CommandLine: string): Boolean; const DCC32CFGFileName = 'DCC32.CFG'; var Cmd: string; begin FOptions.SaveToFile(DCC32CFGFileName); Cmd := Format('"%s" "%s"', [DCC32Location, CommandLine]); Result := WinExec32AndWait(Cmd, SW_HIDE) = 0; DeleteFile(DCC32CFGFileName); end; //-------------------------------------------------------------------------------------------------- constructor TJclDelphiCompiler.Create(AInstallation: TJclDelphiInstallation); begin inherited; FOptions := TStringList.Create; FDCC32Location := PathAddSeparator(Installation.RootDir) + DCC32FileName; end; //-------------------------------------------------------------------------------------------------- destructor TJclDelphiCompiler.Destroy; begin FreeAndNil(FOptions); inherited; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiCompiler.InstallPackage(const PackageName, BPLPath, DCPPath: string): Boolean; const DOFDirectoriesSection = 'Directories'; UnitOutputDirName = 'UnitOutputDir'; SearchPathName = 'SearchPath'; DescriptionOption = '{$DESCRIPTION '''; LibSuffixOption = '{$LIBSUFFIX '''; RunOnlyOption = '{$RUNONLY}'; var SaveDir, PackagePath, Description, LibSuffix, BPLFileName, S: string; RunOnly: Boolean; DOFFile: TIniFile; DPKFile: TStringList; I: Integer; begin PackagePath := PathRemoveSeparator(ExtractFilePath(PackageName)); SaveDir := GetCurrentDir; Win32Check(SetCurrentDir(PackagePath)); try DOFFile := TIniFile.Create(ChangeFileExt(PackageName, '.dof')); try Options.Clear; S := DOFFile.ReadString(DOFDirectoriesSection, SearchPathName, ''); AddPathOption('N', DOFFile.ReadString(DOFDirectoriesSection, UnitOutputDirName, '')); AddPathOption('I', S); AddPathOption('R', S); AddPathOption('LE', BPLPath); AddPathOption('LN', DCPPath); AddPathOption('U', StrEnsureSuffix(';', DCPPath) + S); finally DOFFile.Free; end; Result := Compile(PackageName); finally SetCurrentDir(SaveDir); end; if Result then begin DPKFile := TStringList.Create; try DPKFile.LoadFromFile(PackageName); Description := ''; LibSuffix := ''; RunOnly := False; for I := 0 to DPKFile.Count - 1 do begin S := TrimRight(DPKFile[I]); if Pos(DescriptionOption, S) = 1 then Description := Copy(S, Length(DescriptionOption), Length(S) - Length(DescriptionOption)) else if Pos(LibSuffixOption, S) = 1 then LibSuffix := Copy(S, Length(LibSuffixOption), Length(S) - Length(LibSuffixOption)) else if Pos(RunOnlyOption, S) = 1 then RunOnly := True; end; if not RunOnly then begin BPLFileName := PathAddSeparator(BPLPath) + PathExtractFileNameNoExt(PackageName) + LibSuffix + '.bpl'; Result := Installation.IdePackages.AddPackage(BPLFileName, Description); end; finally DPKFile.Free; end; end; end; //================================================================================================== // TJclDelphiPalette //================================================================================================== procedure TJclDelphiPalette.ComponentsOnTabToStrings(Index: Integer; Strings: TStrings; IncludeUnitName: Boolean; IncludeHiddenComponents: Boolean); var TempList: TStringList; procedure ProcessList(Hidden: Boolean); var D, I: Integer; List, S: string; begin if Hidden then List := HiddenComponentsOnTab[Index] else List := ComponentsOnTab[Index]; List := StrEnsureSuffix(';', List); while Length(List) > 1 do begin D := Pos(';', List); S := Trim(Copy(List, 1, D - 1)); if not IncludeUnitName then Delete(S, 1, Pos('.', S)); if Hidden then begin I := TempList.IndexOf(S); if I = -1 then TempList.AddObject(S, Pointer(True)) else TempList.Objects[I] := Pointer(True); end else TempList.Add(S); Delete(List, 1, D); end; end; begin TempList := TStringList.Create; try TempList.Duplicates := dupError; ProcessList(False); TempList.Sorted := True; if IncludeHiddenComponents then ProcessList(True); Strings.AddStrings(TempList); finally TempList.Free; end; end; //-------------------------------------------------------------------------------------------------- constructor TJclDelphiPalette.Create(AInstallation: TJclDelphiInstallation); begin inherited; FRegKey := Installation.RegKey + '\' + PaletteKeyName; FTabNames := TStringList.Create; FTabNames.Sorted := True; ReadTabNames; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiPalette.DeleteTabName(const TabName: string): Boolean; var I: Integer; begin I := FTabNames.IndexOf(TabName); Result := I >= 0; if Result then begin RegDeleteEntry(HKEY_CURRENT_USER, FRegKey, FTabNames[I]); RegDeleteEntry(HKEY_CURRENT_USER, FRegKey, FTabNames[I] + PaletteHiddenTag); FTabNames.Delete(I); end; end; //-------------------------------------------------------------------------------------------------- destructor TJclDelphiPalette.Destroy; begin FreeAndNil(FTabNames); inherited; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiPalette.GetComponentsOnTab(Index: Integer): string; begin Result := RegReadStringDef(HKEY_CURRENT_USER, FRegKey, FTabNames[Index], ''); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiPalette.GetHiddenComponentsOnTab(Index: Integer): string; begin Result := RegReadStringDef(HKEY_CURRENT_USER, FRegKey, FTabNames[Index] + PaletteHiddenTag, ''); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiPalette.GetTabNameCount: Integer; begin Result := FTabNames.Count; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiPalette.GetTabNames(Index: Integer): string; begin Result := FTabNames[Index]; end; //-------------------------------------------------------------------------------------------------- procedure TJclDelphiPalette.ReadTabNames; var TempList: TStringList; I: Integer; S: string; begin TempList := TStringList.Create; try if RegKeyExists(HKEY_CURRENT_USER, FRegKey) and RegGetValueNames(HKEY_CURRENT_USER, FRegKey, TempList) then for I := 0 to TempList.Count - 1 do begin S := TempList[I]; if Pos(PaletteHiddenTag, S) = 0 then FTabNames.Add(S); end; finally TempList.Free; end; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiPalette.TabNameExists(const TabName: string): Boolean; begin Result := FTabNames.IndexOf(TabName) <> -1; end; //================================================================================================== // TJclDelphiRepository //================================================================================================== procedure TJclDelphiRepository.AddObject(const FileName, ObjectType, PageName, ObjectName, IconFileName, Description, Author, Designer: string; const Ancestor: string); var SectionName: string; begin GetIniFile; SectionName := AnsiUpperCase(PathRemoveExtension(FileName)); FIniFile.EraseSection(FileName); FIniFile.EraseSection(SectionName); FIniFile.WriteString(SectionName, DelphiRepositoryObjectType, ObjectType); FIniFile.WriteString(SectionName, DelphiRepositoryObjectName, ObjectName); FIniFile.WriteString(SectionName, DelphiRepositoryObjectPage, PageName); FIniFile.WriteString(SectionName, DelphiRepositoryObjectIcon, IconFileName); FIniFile.WriteString(SectionName, DelphiRepositoryObjectDescr, Description); FIniFile.WriteString(SectionName, DelphiRepositoryObjectAuthor, Author); if Ancestor <> '' then FIniFile.WriteString(SectionName, DelphiRepositoryObjectAncestor, Ancestor); if Installation.VersionNumber >= 6 then FIniFile.WriteString(SectionName, DelphiRepositoryObjectDesigner, Designer); FIniFile.WriteBool(SectionName, DelphiRepositoryObjectNewForm, False); FIniFile.WriteBool(SectionName, DelphiRepositoryObjectMainForm, False); CloseIniFile; end; //-------------------------------------------------------------------------------------------------- procedure TJclDelphiRepository.CloseIniFile; begin FreeAndNil(FIniFile); end; //-------------------------------------------------------------------------------------------------- constructor TJclDelphiRepository.Create(AInstallation: TJclDelphiInstallation); begin inherited; FFileName := PathAddSeparator(Installation.RootDir) + DelphiRepositoryFileName; FPages := TStringList.Create; IniFile.ReadSection(DelphiRepositoryPagesSection, FPages); CloseIniFile; end; //-------------------------------------------------------------------------------------------------- destructor TJclDelphiRepository.Destroy; begin FreeAndNil(FPages); FreeAndNil(FIniFile); inherited; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiRepository.FindPage(const Name: string; OptionalIndex: Integer): string; var I: Integer; begin I := FPages.IndexOf(Name); if I >= 0 then Result := FPages[I] else begin if OptionalIndex < FPages.Count then Result := FPages[OptionalIndex] else Result := ''; end; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiRepository.GetIniFile: TIniFile; begin if not Assigned(FIniFile) then FIniFile := TIniFile.Create(FileName); Result := FIniFile; end; //-------------------------------------------------------------------------------------------------- procedure TJclDelphiRepository.RemoveObjects(const PartialPath, FileName, ObjectType: string); var Sections: TStringList; I: Integer; SectionName, FileNamePart, PathPart, DialogFileName: string; begin Sections := TStringList.Create; try GetIniFile; FIniFile.ReadSections(Sections); for I := 0 to Sections.Count - 1 do begin SectionName := Sections[I]; if FIniFile.ReadString(SectionName, DelphiRepositoryObjectType, '') = ObjectType then begin FileNamePart := PathExtractFileNameNoExt(SectionName); PathPart := StrRight(PathAddSeparator(ExtractFilePath(SectionName)), Length(PartialPath)); DialogFileName := PathExtractFileNameNoExt(FileName); if StrSame(FileNamePart, DialogFileName) and StrSame(PathPart, PartialPath) then FIniFile.EraseSection(SectionName); end; end; finally Sections.Free; end; end; //================================================================================================== // TJclDelphiInstallation //================================================================================================== function TJclDelphiInstallation.AddToLibrarySearchPath(const Path: string): Boolean; var Items: TStringList; TempLibraryPath: TJclDelphiPath; begin TempLibraryPath := LibrarySearchPath; Items := TStringList.Create; try ExtractPaths(TempLibraryPath, Items); Result := FindFolderInDelphiPath(Path, Items) = -1; if Result then begin TempLibraryPath := StrEnsureSuffix(DelphiLibraryPathSeparator, TempLibraryPath) + Path; LibrarySearchPath := TempLibraryPath; end; finally Items.Free; end; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.AnyInstanceRunning: Boolean; var Processes: TStringList; I: Integer; begin Result := False; Processes := TStringList.Create; try if RunningProcessesList(Processes) then begin for I := 0 to Processes.Count - 1 do if AnsiSameText(IdeExeFileName, Processes[I]) then begin Result := True; Break; end; end; finally Processes.Free; end; end; //-------------------------------------------------------------------------------------------------- constructor TJclDelphiInstallation.Create(const ARegKey: string); begin FRegKey := ARegKey; FRegKeyValues := TStringList.Create; ReadInformation; FIdeTools := TJclDelphiIdeTool.Create(Self); FOpenHelp := TJclDelphiOpenHelp.Create(Self); end; //-------------------------------------------------------------------------------------------------- destructor TJclDelphiInstallation.Destroy; begin FreeAndNil(FRegKeyValues); FreeAndNil(FRepository); FreeAndNil(FCompiler); FreeAndNil(FIdePackages); FreeAndNil(FIdeTools); FreeAndNil(FOpenHelp); FreeAndNil(FPalette); inherited; end; //-------------------------------------------------------------------------------------------------- class procedure TJclDelphiInstallation.ExtractPaths(const Path: TJclDelphiPath; List: TStrings); begin StrToStrings(Path, DelphiLibraryPathSeparator, List); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.FindFolderInDelphiPath(Folder: string; List: TStrings): Integer; var I: Integer; begin Result := -1; Folder := PathRemoveSeparator(Folder); for I := 0 to List.Count - 1 do if AnsiSameText(Folder, PathRemoveSeparator(SubstitutePath(List[I]))) then begin Result := I; Break; end; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.GetBPLOutputPath: string; begin Result := SubstitutePath(RegReadStringDef(HKEY_CURRENT_USER, RegKey + '\' + LibraryKeyName, LibraryBPLOutputValueName, '')); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.GetComplier: TJclDelphiCompiler; begin if not Assigned(FCompiler) then FCompiler := TJclDelphiCompiler.Create(Self); Result := FCompiler; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.GetDCPOutputPath: string; begin Result := SubstitutePath(RegReadStringDef(HKEY_CURRENT_USER, RegKey + '\' + LibraryKeyName, LibraryDCPOutputValueName, '')); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.GetEditionAsText: string; begin case Edition of deSTD: if VersionNumber >= 6 then Result := RsPersonal else Result := RsStandard; dePRO: Result := RsProfessional; deCSS: if VersionNumber >= 5 then Result := RsEnterprise else Result := RsClientServer; end; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.GetEnvironmentVariables: TStrings; var EnvNames: TStringList; EnvVarKeyName: string; I: Integer; begin if FEnvironmentVariables = nil then begin FEnvironmentVariables := TStringList.Create; if VersionNumber >= 6 then begin EnvNames := TStringList.Create; try EnvVarKeyName := RegKey + '\' + EnvVariablesKeyName; if RegKeyExists(HKEY_CURRENT_USER, EnvVarKeyName) and RegGetValueNames(HKEY_CURRENT_USER, EnvVarKeyName, EnvNames) then for I := 0 to EnvNames.Count - 1 do FEnvironmentVariables.Values[EnvNames[I]] := RegReadStringDef(HKEY_CURRENT_USER, EnvVarKeyName, EnvNames[I], ''); finally EnvNames.Free; end; end; FEnvironmentVariables.Values['DELPHI'] := RootDir; end; Result := FEnvironmentVariables; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.GetIdeExeBuildNumber: string; var FixedInfo: TVSFixedFileInfo; begin if VersionFixedFileInfo(IdeExeFileName, FixedInfo) then Result := FormatVersionString(LongRec(FixedInfo.dwFileVersionLS).Hi, LongRec(FixedInfo.dwFileVersionLS).Lo) else Result := ''; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.GetIdePackages: TJclDelphiIdePackages; begin if not Assigned(FIdePackages) then FIdePackages := TJclDelphiIdePackages.Create(Self); Result := FIdePackages; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.GetLibrarySearchPath: TJclDelphiPath; begin Result := RegReadStringDef(HKEY_CURRENT_USER, RegKey + '\' + LibraryKeyName, LibrarySearchPathValueName, ''); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.GetName: string; begin Result := Format(RsDelphiName, [VersionNumber, EditionAsText]); if InstalledUpdatePack > 0 then Result := Result + ' ' + Format(RsUpdatePackName, [InstalledUpdatePack]); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.GetPalette: TJclDelphiPalette; begin if not Assigned(FPalette) then FPalette := TJclDelphiPalette.Create(Self); Result := FPalette; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.GetRepository: TJclDelphiRepository; begin if not Assigned(FRepository) then FRepository := TJclDelphiRepository.Create(Self); Result := FRepository; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.GetUpdateNeeded: Boolean; begin Result := InstalledUpdatePack < LatestUpdatePack; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.GetValid: Boolean; begin Result := (RegKey <> '') and (RootDir <> '') and FileExists(IdeExeFileName); end; //-------------------------------------------------------------------------------------------------- procedure TJclDelphiInstallation.ReadInformation; const UpdateKeyName = 'Update #'; EditionNames: array [TJclDelphiEdition] of PChar = ('STD', 'PRO', 'CSS'); var Ed: TJclDelphiEdition; KeyLen, I: Integer; KeyName: string; begin FRootDir := RegReadStringDef(HKEY_LOCAL_MACHINE, RegKey, RootDirValueName, ''); FBinFolderName := PathAddSeparator(RootDir) + 'Bin\'; FIdeExeFileName := PathAddSeparator(RootDir) + DelphiIdeFileName; KeyName := RegReadStringDef(HKEY_LOCAL_MACHINE, RegKey, VersionValueName, ''); for Ed := Low(Ed) to High(Ed) do if EditionNames[Ed] = KeyName then FEdition := Ed; KeyLen := Length(FRegKey); if (KeyLen > 3) and StrIsDigit(FRegKey[KeyLen - 2]) and (FRegKey[KeyLen - 1] = '.') and (FRegKey[KeyLen] = '0') then FVersionNumber := Ord(FRegKey[KeyLen - 2]) - 48 else FVersionNumber := 0; if RegGetValueNamesAndValues(HKEY_LOCAL_MACHINE, RegKey, FRegKeyValues) then for I := 0 to RegKeyValues.Count - 1 do begin KeyName := RegKeyValues.Names[I]; KeyLen := Length(UpdateKeyName); if (Pos(UpdateKeyName, KeyName) = 1) and (Length(KeyName) > KeyLen) and StrIsDigit(KeyName[KeyLen + 1]) then FInstalledUpdatePack := Max(FInstalledUpdatePack, Integer(Ord(KeyName[KeyLen + 1]) - 48)); end; for I := Low(LatestUpdatePacks) to High(LatestUpdatePacks) do if LatestUpdatePacks[I].DelphiVersion = VersionNumber then begin FLatestUpdatePack := LatestUpdatePacks[I].LatestUpdatePack; Break; end; end; //-------------------------------------------------------------------------------------------------- procedure TJclDelphiInstallation.SetLibrarySearchPath(const Value: TJclDelphiPath); begin RegWriteString(HKEY_CURRENT_USER, RegKey + '\' + LibraryKeyName, LibrarySearchPathValueName, Value); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallation.SubstitutePath(const Path: string): string; var I: Integer; Name: string; begin Result := Path; if Pos('$(', Result) > 0 then with EnvironmentVariables do for I := 0 to Count - 1 do begin Name := Names[I]; Result := StringReplace(Result, Format('$(%s)', [Name]), Values[Name], [rfReplaceAll, rfIgnoreCase]); end; end; //================================================================================================== // TDelphiInstallations //================================================================================================== function TJclDelphiInstallations.AnyInstanceRunning: Boolean; var I: Integer; begin Result := False; for I := 0 to Count - 1 do if Installations[I].AnyInstanceRunning then begin Result := True; Break; end; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallations.AnyUpdatePackNeeded(var Text: string): Boolean; var I: Integer; begin Result := False; for I := 0 to Count - 1 do if Installations[I].UpdateNeeded then begin Result := True; Text := Format(RsNeedUpdate, [Installations[I].LatestUpdatePack, Installations[I].Name]); Break; end; end; //-------------------------------------------------------------------------------------------------- constructor TJclDelphiInstallations.Create; begin FList := TObjectList.Create; ReadInstallations; end; //-------------------------------------------------------------------------------------------------- destructor TJclDelphiInstallations.Destroy; begin FreeAndNil(FList); inherited; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallations.GetCount: Integer; begin Result := FList.Count; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallations.GetInstallationFromVersion(VersionNumber: Byte): TJclDelphiInstallation; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do if Installations[I].VersionNumber = VersionNumber then begin Result := Installations[I]; Break; end; end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallations.GetInstallations(Index: Integer): TJclDelphiInstallation; begin Result := TJclDelphiInstallation(FList[Index]); end; //-------------------------------------------------------------------------------------------------- function TJclDelphiInstallations.GetVersionInstalled(VersionNumber: Byte): Boolean; begin Result := InstallationFromVersion[VersionNumber] <> nil; end; //-------------------------------------------------------------------------------------------------- procedure TJclDelphiInstallations.ReadInstallations; var List: TStringList; I: Integer; VersionKeyName: string; Item: TJclDelphiInstallation; begin FList.Clear; List := TStringList.Create; try if RegGetKeyNames(HKEY_LOCAL_MACHINE, DelphiKeyName, List) then for I := 0 to List.Count - 1 do begin VersionKeyName := DelphiKeyName + '\' + List[I]; if RegKeyExists(HKEY_LOCAL_MACHINE, VersionKeyName) then begin Item := TJclDelphiInstallation.Create(VersionKeyName); FList.Add(Item); end; end; finally List.Free; end; end; //-------------------------------------------------------------------------------------------------- end.
unit TagQtyPriceBreakViewEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, cxCurrencyEdit, ADODB, db, DbClient; type TfrmTagQtyPriceBreak = class(TFrmParentAll) Label1: TLabel; Label2: TLabel; cedPrice: TcxCurrencyEdit; cedQty: TcxCurrencyEdit; procedure btCloseClick(Sender: TObject); private { Private declarations } fOper: String; fIdTag: Integer; procedure cleanUpScreen(); public { Public declarations } function start(arg_idTag: Integer; arg_oper: String = 'I'): Boolean; end; implementation uses uDM; {$R *.dfm} { TfrmTagQtyPriceBreak } function TfrmTagQtyPriceBreak.start(arg_idTag: Integer; arg_oper: String = 'I'): Boolean; begin fOper := arg_oper; if ( arg_oper = 'I' ) then begin cleanUpScreen; end; fIdTag := arg_idTag; showModal; result := true; end; procedure TfrmTagQtyPriceBreak.btCloseClick(Sender: TObject); begin dm.callSpTagQtyPriceBreakUpSert((cedPrice.EditValue/100), fIdTag, cedQty.EditValue); inherited; close; end; procedure TfrmTagQtyPriceBreak.cleanUpScreen; begin cedQty.Value := 0; cedPrice.Value := 0.00; end; end.
namespace XsdParser.Net; uses proholz.xsdparser; type Program = class public class method Main(args: array of String): Int32; begin // add your own code here writeLn('The magic happens here.'); var filename := if Environment.OS = OperatingSystem.Windows then 'X:/BTL/btlx_11.xsd'.ToPlatformPathFromUnixPath else '/Volumes/HD2/BTL/btlx_11.xsd'.ToPlatformPathFromUnixPath; // var filename := '/Volumes/HD2/BTL/x3d-3.3.xsd'; var Xsd := new XsdParser(filename); if Xsd.getUnsolvedReferences.Count > 0 then begin writeLn('There are unsolved References:'); for each item in Xsd.getUnsolvedReferences do begin writeLn(item.getUnsolvedReference.getRef); end; end else writeLn('All solved'); writeLn('solved : '); for each item in Xsd.getResultXsdSchemas do begin writeLn($" File: {item.getfilename()} Target: {item.getTargetNamespace}"); for each name in item.getNamespaces() do writeLn(name.Key); for each ele in item.getElements do begin case ele.getElement.GetType of typeOf(XsdElement) : writeLn($' {XsdElement(ele.getElement).getName} XSD Element'); typeOf(XsdSimpleType) : writeLn($' {XsdSimpleType(ele.getElement).getName} XSD Simple'); typeOf(XsdComplexType) : writeLn($' {XsdComplexType(ele.getElement).getName} XSD Complex'); end; // writeLn(ele.getElement.ToString); end; //if item.getChildrenComplexTypes.Any and false then begin //writeLn('Complextypes'); //for each child in item.getChildrenComplexTypes do begin //writeLn($" {child.getRawName}"); //end; //end; end; end; end; end.
unit LA.Vector.Main; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LA.Vector; procedure Main; implementation procedure Main; var vec1, vec2, zero, vec3: TVector; begin vec1 := TVector.Create([5, 2]); WriteLn(vec1.ToString); WriteLn(vec1.Len); WriteLn(Format('vec[0] = %s, vec[1] = %s', [vec1[0].ToString, vec1[1].ToString])); vec2 := TVector.Create([3, 1]); WriteLn(Format('%s + %s = %s', [vec1.ToString, vec2.ToString, (vec1 + vec2).ToString])); WriteLn(Format('%s - %s = %s', [vec1.ToString, vec2.ToString, (vec1 - vec2).ToString])); WriteLn(Format('%S * %s = %s', [(3).ToString, vec1.ToString, (3 * vec1).ToString])); WriteLn(Format('%s * %s = %s', [vec1.ToString, (3).ToString, (vec1 * 3).ToString])); WriteLn(Format('+%s = %s', [vec1.ToString, (+vec1).ToString])); WriteLn(Format('-%s = %s', [vec1.ToString, (-vec1).ToString])); zero := TVector.Zero(2); WriteLn(zero.ToString); WriteLn(Format('%s + %s = %s', [vec1.ToString, zero.ToString, (vec1 + zero).ToString])); WriteLn(Format('norm(%s) = %s', [vec1.ToString, vec1.Norm.ToString])); WriteLn(Format('norm(%s) = %s', [vec2.ToString, vec2.Norm.ToString])); WriteLn(Format('norm(%s) = %s', [zero.ToString, zero.Norm.ToString])); WriteLn(Format('normalize(%s) = %s', [vec1.ToString, vec1.Normalize.ToString])); WriteLn(vec1.Normalize.Norm.ToString); WriteLn(Format('normalize(%s) = %s', [vec2.ToString, vec2.Normalize.ToString])); WriteLn(vec2.Normalize.Norm.ToString); try zero.Normalize except WriteLn('Cannot normalize zero vector ', zero.ToString); end; WriteLn(Format('%s * %s = %s', [vec1.ToString, vec2.ToString, (vec1 * vec2).ToString])); WriteLn(vec1.Dot(vec2).ToString); vec3 := TVector.Create([0, 0]); WriteLn(Format('%s = %s ? %s', [zero.ToString, vec3.ToString, BoolToStr(zero = vec3, true)])); WriteLn(Format('%s = %s ? %s', [vec2.ToString, vec3.ToString, BoolToStr(vec2 = vec3, true)])); WriteLn(Format('%s = %s ? %s', [vec2.ToString, vec3.ToString, BoolToStr(vec2 <> vec3, true)])); end; end.
program HelloWorld; begin write('Hello, world.'); end.
unit ibSHUserConnectedFrm; interface uses SHDesignIntf, SHEvents, ibSHDesignIntf, ibSHComponentFrm, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, VirtualTrees, ExtCtrls; type TibSHUserConnectedForm = class(TibBTComponentForm) Panel1: TPanel; Tree: TVirtualStringTree; private { Private declarations } FUserNames: TStrings; { Tree } procedure TreeGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); procedure TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); procedure BuildTree; public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; end; var ibSHUserConnectedForm: TibSHUserConnectedForm; implementation uses ibSHConsts; {$R *.dfm} type PTreeRec = ^TTreeRec; TTreeRec = record NormalText: string; StaticText: string; ImageIndex: Integer; end; { TibSHUserConnectedForm } constructor TibSHUserConnectedForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); begin FUserNames := TStringList.Create; inherited Create(AOwner, AParent, AComponent, ACallString); Caption := Format(ACallString, []); if Assigned(ModalForm) then ModalForm.ButtonsMode := bmOK; Tree.Images := Designer.ImageList; Tree.OnGetNodeDataSize := TreeGetNodeDataSize; Tree.OnFreeNode := TreeFreeNode; Tree.OnGetImageIndex := TreeGetImageIndex; Tree.OnGetText := TreeGetText; BuildTree; end; destructor TibSHUserConnectedForm.Destroy; begin FUserNames.Free; inherited Destroy; end; procedure TibSHUserConnectedForm.BuildTree; var I: Integer; Node: PVirtualNode; NodeData: PTreeRec; begin if Supports(Component, IibSHDatabase) then FUserNames.Assign((Component as IibSHDatabase).DRVQuery.Database.UserNames); for I := 0 to Pred(FUserNames.Count) do begin Node := Tree.AddChild(nil); NodeData := Tree.GetNodeData(Node); NodeData.NormalText := FUserNames[I]; NodeData.ImageIndex := Designer.GetImageIndex(IibSHUser); end; Node := Tree.GetFirst; if Assigned(Node) then begin Tree.FocusedNode := Node; Tree.Selected[Tree.FocusedNode] := True; end; Caption := Format('%s: %d users connected', [Caption, FUserNames.Count]); end; { Tree } procedure TibSHUserConnectedForm.TreeGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); begin NodeDataSize := SizeOf(TTreeRec); end; procedure TibSHUserConnectedForm.TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if Assigned(Data) then Finalize(Data^); end; procedure TibSHUserConnectedForm.TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); if (Kind = ikNormal) or (Kind = ikSelected) then ImageIndex := Data.ImageIndex; end; procedure TibSHUserConnectedForm.TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var Data: PTreeRec; begin Data := Sender.GetNodeData(Node); case TextType of ttNormal: CellText := Data.NormalText; ttStatic: CellText := Data.StaticText; end; end; end.
(*----------------------------------------------------------------------------* * Direct3D sample from DirectX 9.0 SDK December 2006 * * Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) * * * * Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 * * * * Latest version can be downloaded from: * * http://www.clootie.ru * * http://sourceforge.net/projects/delphi-dx9sdk * *----------------------------------------------------------------------------* * $Id: Luminance.pas,v 1.5 2007/02/05 22:21:08 clootie Exp $ *----------------------------------------------------------------------------*) //====================================================================== // // HIGH DYNAMIC RANGE RENDERING DEMONSTRATION // Written by Jack Hoxley, November 2005 // //====================================================================== {$I DirectX.inc} unit Luminance; interface uses Windows, Direct3D9, D3DX9; // All functionality offered by this particular module // is being wrapped up in a C++ namespace so as to make // it clear what functions/etc.. belong together. // namespace Luminance // This function creates the various textures and shaders used // to compute the overall luminance of a given scene. function CreateResources(const pDevice: IDirect3DDevice9; const pDisplayDesc: TD3DSurfaceDesc): HRESULT; // The functional opposite to the above function - it's job is // to make sure that all resources are cleanly and safely tidied up. function DestroyResources: HRESULT; // This is the core function for this module - it will perform all // of the necessary rendering and sampling to compute the 1x1 // luminance texture. function MeasureLuminance(const pDevice: IDirect3DDevice9): HRESULT; // This function will display all stages of the luminance chain // so that the end-user can see exactly what happened. function DisplayLuminance(const pDevice: IDirect3DDevice9; const pFont: ID3DXFont; const pTextSprite: ID3DXSprite; const pArrowTex: IDirect3DTexture9): HRESULT; // The final, 1x1 texture, result of this module is needed to // compute the final image that the user sees, as such other // parts of this example need access to the luminance texture. function GetLuminanceTexture(out pTex: IDirect3DTexture9): HRESULT; // A simple statistic that reveals how much texture memory is // used by this particular module. function ComputeResourceUsage: DWORD; implementation uses Math, DXUT, DXUTcore, DXUTmisc, StrSafe, HDREnumeration, HDRScene; //-------------------------------------------------------------------------------------- // Data Structure Definitions //-------------------------------------------------------------------------------------- type TLVertex = record p: TD3DXVector4; t: TD3DXVector2; end; const FVF_TLVERTEX = D3DFVF_XYZRHW or D3DFVF_TEX1; //-------------------------------------------------------------------------------------- // Namespace-Level Variables //-------------------------------------------------------------------------------------- var g_pLumDispPS: IDirect3DPixelShader9 = nil; // PShader used to display the debug panel g_pLum1PS: IDirect3DPixelShader9 = nil; // PShader that does a 2x2 downsample and convert to greyscale g_pLum1PSConsts: ID3DXConstantTable = nil; // Interface to set the sampling points for the above PS g_pLum3x3DSPS: IDirect3DPixelShader9 = nil; // The PS that does each 3x3 downsample operation g_pLum3x3DSPSConsts: ID3DXConstantTable = nil; // Interface for the above PS const g_dwLumTextures = 6; // How many luminance textures we're creating // Be careful when changing this value, higher than 6 might // require you to implement code that creates an additional // depth-stencil buffer due to the luminance textures dimensions // being greater than that of the default depth-stencil buffer. var g_pTexLuminance: array[0..g_dwLumTextures-1] of IDirect3DTexture9; // An array of the downsampled luminance textures g_fmtHDR: TD3DFormat = D3DFMT_UNKNOWN; // Should be either G32R32F or G16R16F depending on the hardware //-------------------------------------------------------------------------------------- // Private Function Prototypes //-------------------------------------------------------------------------------------- function RenderToTexture(const pDev: IDirect3DDevice9): HRESULT; forward; //-------------------------------------------------------------------------------------- // CreateResources( ) // // DESC: // This function creates the necessary texture chain for downsampling the // initial HDR texture to a 1x1 luminance texture. // // PARAMS: // pDevice : The current device that resources should be created with/from // pDisplayDesc : Describes the back-buffer currently in use, can be useful when // creating GUI based resources. // // NOTES: // n/a //-------------------------------------------------------------------------------------- function CreateResources(const pDevice: IDirect3DDevice9; const pDisplayDesc: TD3DSurfaceDesc): HRESULT; var pCode: ID3DXBuffer; // Container for the compiled HLSL code iTextureSize: Integer; i: Integer; str: array[0..MAX_PATH-1] of WideChar; begin //[ 0 ] DECLARATIONS //------------------ //[ 1 ] DETERMINE FP TEXTURE SUPPORT //---------------------------------- Result := V(HDREnumeration.FindBestLuminanceFormat(Luminance.g_fmtHDR)); if FAILED(Result) then begin // Bad news! OutputDebugString('Luminance::CreateResources() - Current hardware does not support HDR rendering!'#10); Exit; end; //[ 2 ] CREATE HDR RENDER TARGETS //------------------------------- iTextureSize := 1; for i := 0 to Luminance.g_dwLumTextures - 1 do begin // Create this element in the array Result := V(pDevice.CreateTexture(iTextureSize, iTextureSize, 1, D3DUSAGE_RENDERTARGET, Luminance.g_fmtHDR, D3DPOOL_DEFAULT, Luminance.g_pTexLuminance[i], nil)); if FAILED(Result) then begin // Couldn't create this texture, probably best to inspect the debug runtime // for more information StringCchFormat(str, MAX_PATH, 'Luminance::CreateResources() : Unable to create luminance'+ ' texture of %dx%d (Element %d of %d).'#10, [iTextureSize, iTextureSize, (i+1), Luminance.g_dwLumTextures]); OutputDebugStringW(str); Exit; end; // Increment for the next texture iTextureSize := iTextureSize * 3; end; //[ 3 ] CREATE GUI DISPLAY SHADER //------------------------------- // Because the intermediary luminance textures are stored as either G32R32F // or G16R16F, we need a pixel shader that can convert this to a more meaningful // greyscale ARGB value. This shader doesn't actually contribute to the // luminance calculations - just the way they are presented to the user via the GUI. Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, 'Shader Code\Luminance.psh'); if V_Failed(Result) then Exit; Result := V(D3DXCompileShaderFromFileW( str, nil, nil, 'LuminanceDisplay', 'ps_2_0', 0, @pCode, nil, nil )); if FAILED(Result) then begin // Couldn't compile the shader, use the 'compile_shaders.bat' script // in the 'Shader Code' folder to get a proper compile breakdown. OutputDebugString('Luminance::CreateResources() - Compiling of ''LuminanceDisplay'' from ''Luminance.psh'' failed!'#10); Exit; end; Result := V(pDevice.CreatePixelShader(PDWORD(pCode.GetBufferPointer), Luminance.g_pLumDispPS)); if FAILED(Result) then begin // Couldn't turn the compiled shader into an actual, usable, pixel shader! OutputDebugString('Luminance::CreateResources() - Could not create a pixel shader object for ''LuminanceDisplay''.'#10); pCode := nil; Exit; end; pCode := nil; //[ 4 ] CREATE FIRST-PASS DOWNSAMPLE SHADER //----------------------------------------- // The first pass of down-sampling has to convert the RGB data to // a single luminance value before averaging over the kernel. This // is slightly different to the subsequent down-sampling shader. Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, 'Shader Code\Luminance.psh'); if V_Failed(Result) then Exit; Result := V(D3DXCompileShaderFromFileW( str, nil, nil, 'GreyScaleDownSample', 'ps_2_0', 0, @pCode, nil, @Luminance.g_pLum1PSConsts )); if FAILED(Result) then begin // Couldn't compile the shader, use the 'compile_shaders.bat' script // in the 'Shader Code' folder to get a proper compile breakdown. OutputDebugString('Luminance::CreateResources() - Compiling of ''GreyScaleDownSample'' from ''Luminance.psh'' failed!'#10); Exit; end; Result := V(pDevice.CreatePixelShader(PDWORD(pCode.GetBufferPointer), Luminance.g_pLum1PS)); if FAILED(Result) then begin // Couldn't turn the compiled shader into an actual, usable, pixel shader! OutputDebugString('Luminance::CreateResources() - Could not create a pixel shader object for ''GreyScaleDownSample''.'#10); pCode := nil; Exit; end; pCode := nil; //[ 5 ] CREATE DOWNSAMPLING PIXEL SHADER //-------------------------------------- // This down-sampling shader assumes that the incoming pixels are // already in G16R16F or G32R32F format, and of a paired luminance/maximum value. Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, 'Shader Code\Luminance.psh'); if V_Failed(Result) then Exit; Result := V(D3DXCompileShaderFromFileW( str, nil, nil, 'DownSample', 'ps_2_0', 0, @pCode, nil, @Luminance.g_pLum3x3DSPSConsts )); if FAILED(Result) then begin // Couldn't compile the shader, use the 'compile_shaders.bat' script // in the 'Shader Code' folder to get a proper compile breakdown. OutputDebugString('Luminance::CreateResources() - Compiling of ''DownSample'' from ''Luminance.psh'' failed!'#10); Exit; end; Result := V(pDevice.CreatePixelShader(PDWORD(pCode.GetBufferPointer), Luminance.g_pLum3x3DSPS)); if FAILED(Result) then begin // Couldn't turn the compiled shader into an actual, usable, pixel shader! OutputDebugString('Luminance::CreateResources() : Could not create a pixel shader object for ''DownSample''.'#10); pCode := nil; Exit; end; pCode := nil; end; //-------------------------------------------------------------------------------------- // DestroyResources( ) // // DESC: // Makes sure that the resources acquired in CreateResources() are cleanly // destroyed to avoid any errors and/or memory leaks. // //-------------------------------------------------------------------------------------- function DestroyResources: HRESULT; var i: Integer; begin for i := 0 to Luminance.g_dwLumTextures - 1 do Luminance.g_pTexLuminance[i] := nil; SAFE_RELEASE(Luminance.g_pLumDispPS); SAFE_RELEASE(Luminance.g_pLum1PS); SAFE_RELEASE(Luminance.g_pLum1PSConsts); SAFE_RELEASE(Luminance.g_pLum3x3DSPS); SAFE_RELEASE(Luminance.g_pLum3x3DSPSConsts); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // MeasureLuminance( ) // // DESC: // This is the core function for this particular part of the application, it's // job is to take the previously rendered (in the 'HDRScene' namespace) HDR // image and compute the overall luminance for the scene. This is done by // repeatedly downsampling the image until it is only 1x1 in size. Doing it // this way (pixel shaders and render targets) keeps as much of the work on // the GPU as possible, consequently avoiding any resource transfers, locking // and modification. // // PARAMS: // pDevice : The currently active device that will be used for rendering. // // NOTES: // The results from this function will eventually be used to compose the final // image. See OnFrameRender() in 'HDRDemo.cpp'. // //-------------------------------------------------------------------------------------- function MeasureLuminance(const pDevice: IDirect3DDevice9): HRESULT; type PSingleArray = ^TSingleArray; TSingleArray = array[0..3] of Single; var //[ 0 ] DECLARE VARIABLES AND ALIASES //----------------------------------- pSourceTex: IDirect3DTexture9; // We use this texture as the input pDestTex: IDirect3DTexture9; // We render to this texture... pDestSurf: IDirect3DSurface9; // ... Using this ptr to it's top-level surface offsets: array[0..3] of TD3DXVector4; srcDesc: TD3DSurfaceDesc; sU, sV: Single; i: Integer; srcTexDesc: TD3DSurfaceDesc; DSoffsets: array[0..8] of TD3DXVector4; idx: Integer; x, y: Integer; begin //[ 1 ] SET THE DEVICE TO RENDER TO THE HIGHEST // RESOLUTION LUMINANCE MAP. //--------------------------------------------- HDRScene.GetOutputTexture(pSourceTex); pDestTex := Luminance.g_pTexLuminance[ Luminance.g_dwLumTextures - 1 ]; if FAILED(pDestTex.GetSurfaceLevel(0, pDestSurf)) then begin // Couldn't acquire this surface level. Odd! OutputDebugString('Luminance::MeasureLuminance( ) : Couldn''t acquire surface level for hi-res luminance map!'#10); Result:= E_FAIL; Exit; end; pDevice.SetRenderTarget(0, pDestSurf); pDevice.SetTexture(0, pSourceTex); pDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); pDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); //[ 2 ] RENDER AND DOWNSAMPLE THE HDR TEXTURE // TO THE LUMINANCE MAP. //------------------------------------------- // Set which shader we're going to use. g_pLum1PS corresponds // to the 'GreyScaleDownSample' entry point in 'Luminance.psh'. pDevice.SetPixelShader(Luminance.g_pLum1PS); // We need to compute the sampling offsets used for this pass. // A 2x2 sampling pattern is used, so we need to generate 4 offsets. // // NOTE: It is worth noting that some information will likely be lost // due to the luminance map being less than 1/2 the size of the // original render-target. This mis-match does not have a particularly // big impact on the final luminance measurement. If necessary, // the same process could be used - but with many more samples, so as // to correctly map from HDR->Luminance without losing information. // Find the dimensions for the source data pSourceTex.GetLevelDesc(0, srcDesc); // Because the source and destination are NOT the same sizes, we // need to provide offsets to correctly map between them. sU := 1.0 / srcDesc.Width; sV := 1.0 / srcDesc.Height; // The last two components (z,w) are unused. This makes for simpler code, but if // constant-storage is limited then it is possible to pack 4 offsets into 2 float4's offsets[0] := D3DXVector4(-0.5 * sU, 0.5 * sV, 0.0, 0.0); offsets[1] := D3DXVector4( 0.5 * sU, 0.5 * sV, 0.0, 0.0); offsets[2] := D3DXVector4(-0.5 * sU, -0.5 * sV, 0.0, 0.0); offsets[3] := D3DXVector4( 0.5 * sU, -0.5 * sV, 0.0, 0.0); // Set the offsets to the constant table Luminance.g_pLum1PSConsts.SetVectorArray(pDevice, 'tcLumOffsets', @offsets, 4); // With everything configured we can now render the first, initial, pass // to the luminance textures. RenderToTexture(pDevice); // Make sure we clean up the remaining reference SAFE_RELEASE(pDestSurf); SAFE_RELEASE(pSourceTex); //[ 3 ] SCALE EACH RENDER TARGET DOWN // The results ("dest") of each pass feeds into the next ("src") //------------------------------------------------------------------- for i := (Luminance.g_dwLumTextures - 1) downto 1 do begin // Configure the render targets for this iteration pSourceTex := Luminance.g_pTexLuminance[ i ]; pDestTex := Luminance.g_pTexLuminance[ i - 1 ]; if FAILED(pDestTex.GetSurfaceLevel(0, pDestSurf)) then begin // Couldn't acquire this surface level. Odd! OutputDebugString('Luminance::MeasureLuminance( ) : Couldn''t acquire surface level for luminance map!'#10); Result:= E_FAIL; Exit; end; pDevice.SetRenderTarget(0, pDestSurf); pDevice.SetTexture(0, pSourceTex); // We don't want any filtering for this pass pDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); pDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); // Because each of these textures is a factor of 3 // different in dimension, we use a 3x3 set of sampling // points to downscale. pSourceTex.GetLevelDesc(0, srcTexDesc); // Create the 3x3 grid of offsets idx := 0; for x := -1 to 1 do begin for y := -1 to 1 do begin DSoffsets[idx] := D3DXVector4( x / srcTexDesc.Width, y / srcTexDesc.Height, 0.0, //unused 0.0 //unused ); Inc(idx); end; end; // Set them to the current pixel shader pDevice.SetPixelShader(Luminance.g_pLum3x3DSPS); Luminance.g_pLum3x3DSPSConsts.SetVectorArray(pDevice, 'tcDSOffsets', @DSoffsets, 9); // Render the display to this texture RenderToTexture(pDevice); // Clean-up by releasing the level-0 surface SAFE_RELEASE(pDestSurf); end; // ============================================================= // At this point, the g_pTexLuminance[0] texture will contain // a 1x1 texture that has the downsampled luminance for the // scene as it has currently been rendered. // ============================================================= Result:= S_OK; end; //-------------------------------------------------------------------------------------- // DisplayLuminance( ) // // DESC: // This function is for presentation purposes only - and isn't a *required* // part of the HDR rendering pipeline. It draws the 6 stages of the luminance // calculation to the appropriate part of the screen. // // PARAMS: // pDevice : The device to be rendered to. // pFont : The font to use when adding the annotations // pTextSprite : Used to improve performance of the text rendering // pArrowTex : Stores the 4 (up/down/left/right) icons used in the GUI // // NOTES: // This code uses several hard-coded ratios to position the elements correctly // - as such, changing the underlying diagram may well break this code. // //-------------------------------------------------------------------------------------- function DisplayLuminance(const pDevice: IDirect3DDevice9; const pFont: ID3DXFont; const pTextSprite: ID3DXSprite; const pArrowTex: IDirect3DTexture9): HRESULT; var pSurf: IDirect3DSurface9; d: TD3DSurfaceDesc; fW, fH: Single; fCellH, fCellW: Single; fLumCellSize: Single; fLumStartX: Single; v: array[0..3] of Luminance.TLVertex; txtHelper: CDXUTTextHelper; str: array[0..99] of WideChar; begin // [ 0 ] COMMON INITIALIZATION //---------------------------- if FAILED(pDevice.GetRenderTarget(0, pSurf)) then begin // Couldn't get the current render target! OutputDebugString('Luminance::DisplayLuminance() - Could not get current render target to extract dimensions.'#10); Result:= E_FAIL; Exit; end; pSurf.GetDesc(d); pSurf := nil; // Cache the dimensions as floats for later use fW := d.Width; fH := d.Height; fCellH := (fH - 36.0) / 4.0; fCellW := (fW - 48.0) / 4.0; fLumCellSize := ( ( fH - ( ( 2.0 * fCellH ) + 32.0 ) ) - 32.0 ) / 3.0; fLumStartX := (fCellW + 16.0) - ((2.0 * fLumCellSize) + 32.0); // Fill out the basic TLQuad information - this // stuff doesn't change for each stage v[0].t := D3DXVector2(0.0, 0.0); v[1].t := D3DXVector2(1.0, 0.0); v[2].t := D3DXVector2(0.0, 1.0); v[3].t := D3DXVector2(1.0, 1.0); // Configure the device for it's basic states pDevice.SetVertexShader(nil); pDevice.SetFVF(FVF_TLVERTEX); pDevice.SetPixelShader(g_pLumDispPS); txtHelper := CDXUTTextHelper.Create(pFont, pTextSprite, 12); txtHelper.SetForegroundColor(D3DXColor(1.0, 0.5, 0.0, 1.0)); // [ 1 ] RENDER FIRST LEVEL //------------------------- v[0].p := D3DXVector4(fLumStartX, (2.0 * fCellH) + 32.0, 0.0, 1.0); v[1].p := D3DXVector4(fLumStartX + fLumCellSize, (2.0 * fCellH) + 32.0, 0.0, 1.0); v[2].p := D3DXVector4(fLumStartX, (2.0 * fCellH) + 32.0 + fLumCellSize, 0.0, 1.0); v[3].p := D3DXVector4(fLumStartX + fLumCellSize, (2.0 * fCellH) + 32.0 + fLumCellSize, 0.0, 1.0); pDevice.SetTexture(0, Luminance.g_pTexLuminance[ 5 ]); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(Luminance.TLVertex)); txtHelper._Begin; begin txtHelper.SetInsertionPos(Trunc( fLumStartX ) + 2, Trunc( (2.0 * fCellH) + 32.0 + fLumCellSize ) - 24); txtHelper.DrawTextLine('1st Luminance'); Luminance.g_pTexLuminance[ 5 ].GetLevelDesc(0, d); StringCchFormat(str, 100, '%dx%d', [d.Width, d.Height]); txtHelper.DrawTextLine(str); end; txtHelper._End; // [ 2 ] RENDER SECOND LEVEL //-------------------------- v[0].p := D3DXVector4(fLumStartX, (2.0 * fCellH) + 48.0 + fLumCellSize, 0.0, 1.0); v[1].p := D3DXVector4(fLumStartX + fLumCellSize, (2.0 * fCellH) + 48.0 + fLumCellSize, 0.0, 1.0); v[2].p := D3DXVector4(fLumStartX, (2.0 * fCellH) + 48.0 + (2.0 * fLumCellSize), 0.0, 1.0); v[3].p := D3DXVector4(fLumStartX + fLumCellSize, (2.0 * fCellH) + 48.0 + (2.0 * fLumCellSize), 0.0, 1.0); pDevice.SetTexture(0, Luminance.g_pTexLuminance[ 4 ]); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(Luminance.TLVertex)); txtHelper._Begin; begin txtHelper.SetInsertionPos(Trunc( fLumStartX ) + 2, Trunc( (2.0 * fCellH) + 48.0 + (2.0 * fLumCellSize) ) - 24); txtHelper.DrawTextLine('2nd Luminance'); Luminance.g_pTexLuminance[ 4 ].GetLevelDesc(0, d); StringCchFormat(str, 100, '%dx%d', [d.Width, d.Height]); txtHelper.DrawTextLine(str); end; txtHelper._End; // [ 3 ] RENDER THIRD LEVEL //------------------------- v[0].p := D3DXVector4(fLumStartX, (2.0 * fCellH) + 64.0 + (2.0 * fLumCellSize), 0.0, 1.0); v[1].p := D3DXVector4(fLumStartX + fLumCellSize, (2.0 * fCellH) + 64.0 + (2.0 * fLumCellSize), 0.0, 1.0); v[2].p := D3DXVector4(fLumStartX, (2.0 * fCellH) + 64.0 + (3.0 * fLumCellSize), 0.0, 1.0); v[3].p := D3DXVector4(fLumStartX + fLumCellSize, (2.0 * fCellH) + 64.0 + (3.0 * fLumCellSize), 0.0, 1.0); pDevice.SetTexture(0, Luminance.g_pTexLuminance[ 3 ]); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(Luminance.TLVertex)); txtHelper._Begin; begin txtHelper.SetInsertionPos( Trunc( fLumStartX ) + 2, Trunc( (2.0 * fCellH) + 64.0 + (3.0 * fLumCellSize) ) - 24); txtHelper.DrawTextLine('3rd Luminance'); Luminance.g_pTexLuminance[ 3 ].GetLevelDesc(0, d); StringCchFormat(str,100, '%dx%d', [d.Width, d.Height]); txtHelper.DrawTextLine(str); end; txtHelper._End; // [ 4 ] RENDER FOURTH LEVEL //-------------------------- v[0].p := D3DXVector4(fLumStartX + fLumCellSize + 16.0, (2.0 * fCellH) + 64.0 + (2.0 * fLumCellSize), 0.0, 1.0); v[1].p := D3DXVector4(fLumStartX + (2.0 * fLumCellSize) + 16.0, (2.0 * fCellH) + 64.0 + (2.0 * fLumCellSize), 0.0, 1.0); v[2].p := D3DXVector4(fLumStartX + fLumCellSize + 16.0, (2.0 * fCellH) + 64.0 + (3.0 * fLumCellSize), 0.0, 1.0); v[3].p := D3DXVector4(fLumStartX + (2.0 * fLumCellSize) + 16.0, (2.0 * fCellH) + 64.0 + (3.0 * fLumCellSize), 0.0, 1.0); pDevice.SetTexture(0, Luminance.g_pTexLuminance[ 2 ]); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(Luminance.TLVertex)); txtHelper._Begin; begin txtHelper.SetInsertionPos( Trunc( fLumStartX + fLumCellSize + 16.0 ) + 2, Trunc( (2.0 * fCellH) + 64.0 + (3.0 * fLumCellSize) ) - 24); txtHelper.DrawTextLine('4th Luminance'); Luminance.g_pTexLuminance[ 2 ].GetLevelDesc(0, d); StringCchFormat(str, 100, '%dx%d', [d.Width, d.Height]); txtHelper.DrawTextLine(str); end; txtHelper._End; // [ 5 ] RENDER FIFTH LEVEL //-------------------------- v[0].p := D3DXVector4(fLumStartX + fLumCellSize + 16.0, (2.0 * fCellH) + 48.0 + (1.0 * fLumCellSize), 0.0, 1.0); v[1].p := D3DXVector4(fLumStartX + (2.0 * fLumCellSize) + 16.0, (2.0 * fCellH) + 48.0 + (1.0 * fLumCellSize), 0.0, 1.0); v[2].p := D3DXVector4(fLumStartX + fLumCellSize + 16.0, (2.0 * fCellH) + 48.0 + (2.0 * fLumCellSize), 0.0, 1.0); v[3].p := D3DXVector4(fLumStartX + (2.0 * fLumCellSize) + 16.0, (2.0 * fCellH) + 48.0 + (2.0 * fLumCellSize), 0.0, 1.0); pDevice.SetTexture(0, Luminance.g_pTexLuminance[ 1 ]); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(Luminance.TLVertex)); txtHelper._Begin; begin txtHelper.SetInsertionPos( Trunc( fLumStartX + fLumCellSize + 16.0 ) + 2, Trunc( (2.0 * fCellH) + 48.0 + (2.0 * fLumCellSize) ) - 24); txtHelper.DrawTextLine('5th Luminance'); Luminance.g_pTexLuminance[ 1 ].GetLevelDesc(0, d); StringCchFormat(str,100, '%dx%d', [d.Width, d.Height]); txtHelper.DrawTextLine(str); end; txtHelper._End; // [ 6 ] RENDER SIXTH LEVEL //-------------------------- v[0].p := D3DXVector4(fLumStartX + fLumCellSize + 16.0, (2.0 * fCellH) + 32.0 + (0.0 * fLumCellSize), 0.0, 1.0); v[1].p := D3DXVector4(fLumStartX + (2.0 * fLumCellSize) + 16.0, (2.0 * fCellH) + 32.0 + (0.0 * fLumCellSize), 0.0, 1.0); v[2].p := D3DXVector4(fLumStartX + fLumCellSize + 16.0, (2.0 * fCellH) + 32.0 + (1.0 * fLumCellSize), 0.0, 1.0); v[3].p := D3DXVector4(fLumStartX + (2.0 * fLumCellSize) + 16.0, (2.0 * fCellH) + 32.0 + (1.0 * fLumCellSize), 0.0, 1.0); pDevice.SetTexture(0, Luminance.g_pTexLuminance[ 0 ]); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(Luminance.TLVertex)); txtHelper._Begin; begin txtHelper.SetInsertionPos( Trunc( fLumStartX + fLumCellSize + 16.0 ) + 2, Trunc( (2.0 * fCellH) + 32.0 + (1.0 * fLumCellSize) ) - 24); txtHelper.DrawTextLine('6th Luminance'); Luminance.g_pTexLuminance[ 0 ].GetLevelDesc(0, d); StringCchFormat(str, 100, '%dx%d', [d.Width, d.Height]); txtHelper.DrawTextLine(str); end; txtHelper._End; // [ 7 ] RENDER ARROWS //-------------------- pDevice.SetPixelShader(nil); pDevice.SetTexture(0, pArrowTex); // Select the "down" arrow v[0].t := D3DXVector2(0.50, 0.0); v[1].t := D3DXVECTOR2(0.75, 0.0); v[2].t := D3DXVector2(0.50, 1.0); v[3].t := D3DXVector2(0.75, 1.0); // From 1st down to 2nd v[0].p := D3DXVector4(fLumStartX + (fLumCellSize / 2.0) - 8.0, (2.0 * fCellH) + 32.0 + (1.0 * fLumCellSize), 0.0, 1.0); v[1].p := D3DXVector4(fLumStartX + (fLumCellSize / 2.0) + 8.0, (2.0 * fCellH) + 32.0 + (1.0 * fLumCellSize), 0.0, 1.0); v[2].p := D3DXVector4(fLumStartX + (fLumCellSize / 2.0) - 8.0, (2.0 * fCellH) + 48.0 + (1.0 * fLumCellSize), 0.0, 1.0); v[3].p := D3DXVector4(fLumStartX + (fLumCellSize / 2.0) + 8.0, (2.0 * fCellH) + 48.0 + (1.0 * fLumCellSize), 0.0, 1.0); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(Luminance.TLVertex)); // From 2nd down to 3rd v[0].p := D3DXVector4(fLumStartX + (fLumCellSize / 2.0) - 8.0, (2.0 * fCellH) + 48.0 + (2.0 * fLumCellSize), 0.0, 1.0); v[1].p := D3DXVector4(fLumStartX + (fLumCellSize / 2.0) + 8.0, (2.0 * fCellH) + 48.0 + (2.0 * fLumCellSize), 0.0, 1.0); v[2].p := D3DXVector4(fLumStartX + (fLumCellSize / 2.0) - 8.0, (2.0 * fCellH) + 64.0 + (2.0 * fLumCellSize), 0.0, 1.0); v[3].p := D3DXVector4(fLumStartX + (fLumCellSize / 2.0) + 8.0, (2.0 * fCellH) + 64.0 + (2.0 * fLumCellSize), 0.0, 1.0); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(Luminance.TLVertex)); // Select "right" arrow v[0].t := D3DXVector2(0.25, 0.0); v[1].t := D3DXVector2(0.50, 0.0); v[2].t := D3DXVector2(0.25, 1.0); v[3].t := D3DXVector2(0.50, 1.0); // Across from 3rd to 4th v[0].p := D3DXVector4(fLumStartX + fLumCellSize, (2.0 * fCellH) + 56.0 + (2.5 * fLumCellSize), 0.0, 1.0); v[1].p := D3DXVector4(fLumStartX + fLumCellSize + 16.0, (2.0 * fCellH) + 56.0 + (2.5 * fLumCellSize), 0.0, 1.0); v[2].p := D3DXVector4(fLumStartX + fLumCellSize, (2.0 * fCellH) + 72.0 + (2.5 * fLumCellSize), 0.0, 1.0); v[3].p := D3DXVector4(fLumStartX + fLumCellSize + 16.0, (2.0 * fCellH) + 72.0 + (2.5 * fLumCellSize), 0.0, 1.0); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(Luminance.TLVertex)); // Select "up" arrow v[0].t := D3DXVector2(0.00, 0.0); v[1].t := D3DXVector2(0.25, 0.0); v[2].t := D3DXVector2(0.00, 1.0); v[3].t := D3DXVector2(0.25, 1.0); // Up from 4th to 5th v[0].p := D3DXVector4(fLumStartX + (1.5 * fLumCellSize) + 8.0, (2.0 * fCellH) + 48.0 + (2.0 * fLumCellSize), 0.0, 1.0); v[1].p := D3DXVector4(fLumStartX + (1.5 * fLumCellSize) + 24.0, (2.0 * fCellH) + 48.0 + (2.0 * fLumCellSize), 0.0, 1.0); v[2].p := D3DXVector4(fLumStartX + (1.5 * fLumCellSize) + 8.0, (2.0 * fCellH) + 64.0 + (2.0 * fLumCellSize), 0.0, 1.0); v[3].p := D3DXVector4(fLumStartX + (1.5 * fLumCellSize) + 24.0, (2.0 * fCellH) + 64.0 + (2.0 * fLumCellSize), 0.0, 1.0); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(Luminance.TLVertex)); // Up from 5th to 6th v[0].p := D3DXVector4(fLumStartX + (1.5 * fLumCellSize) + 8.0, (2.0 * fCellH) + 32.0 + (1.0 * fLumCellSize), 0.0, 1.0); v[1].p := D3DXVector4(fLumStartX + (1.5 * fLumCellSize) + 24.0, (2.0 * fCellH) + 32.0 + (1.0 * fLumCellSize), 0.0, 1.0); v[2].p := D3DXVector4(fLumStartX + (1.5 * fLumCellSize) + 8.0, (2.0 * fCellH) + 48.0 + (1.0 * fLumCellSize), 0.0, 1.0); v[3].p := D3DXVector4(fLumStartX + (1.5 * fLumCellSize) + 24.0, (2.0 * fCellH) + 48.0 + (1.0 * fLumCellSize), 0.0, 1.0); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(Luminance.TLVertex)); // Select "right" arrow v[0].t := D3DXVector2(0.25, 0.0); v[1].t := D3DXVector2(0.50, 0.0); v[2].t := D3DXVector2(0.25, 1.0); v[3].t := D3DXVector2(0.50, 1.0); // From 6th to final image composition v[0].p := D3DXVector4(fLumStartX + (2.0 * fLumCellSize) + 16.0, (2.0 * fCellH) + 24.0 + (0.5 * fLumCellSize), 0.0, 1.0); v[1].p := D3DXVector4(fLumStartX + (2.0 * fLumCellSize) + 32.0, (2.0 * fCellH) + 24.0 + (0.5 * fLumCellSize), 0.0, 1.0); v[2].p := D3DXVector4(fLumStartX + (2.0 * fLumCellSize) + 16.0, (2.0 * fCellH) + 40.0 + (0.5 * fLumCellSize), 0.0, 1.0); v[3].p := D3DXVector4(fLumStartX + (2.0 * fLumCellSize) + 32.0, (2.0 * fCellH) + 40.0 + (0.5 * fLumCellSize), 0.0, 1.0); pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(Luminance.TLVertex)); txtHelper.Free; Result:= S_OK; end; //-------------------------------------------------------------------------------------- // GetLuminanceTexture( ) // // DESC: // The final 1x1 luminance texture created by the MeasureLuminance() function // is required as an input into the final image composition. Because of this // it is necessary for other parts of the application to have access to this // particular texture. // // PARAMS: // pTexture : Should be NULL on entry, will be a valid reference on exit // // NOTES: // The code that requests the reference is responsible for releasing their // copy of the texture as soon as they are finished using it. // //-------------------------------------------------------------------------------------- function GetLuminanceTexture(out pTex: IDirect3DTexture9): HRESULT; begin // [ 0 ] ERASE ANY DATA IN THE INPUT //---------------------------------- // SAFE_RELEASE( *pTex ); // [ 1 ] COPY THE PRIVATE REFERENCE //--------------------------------- pTex := Luminance.g_pTexLuminance[ 0 ]; // [ 2 ] INCREMENT THE REFERENCE COUNT.. //-------------------------------------- //(*pTex)->AddRef( ); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // ComputeResourceUsage( ) // // DESC: // Based on the known resources this function attempts to make an accurate // measurement of how much VRAM is being used by this part of the application. // // NOTES: // Whilst the return value should be pretty accurate, it shouldn't be relied // on due to the way drivers/hardware can allocate memory. // // Only the first level of the render target is checked as there should, by // definition, be no mip levels. // //-------------------------------------------------------------------------------------- function ComputeResourceUsage: DWORD; var usage: DWORD; i: Integer; d: TD3DSurfaceDesc; begin usage := 0; for i := 0 to Luminance.g_dwLumTextures - 1 do begin Luminance.g_pTexLuminance[ i ].GetLevelDesc(0, d); usage := usage + ( (d.Width * d.Height) * DWORD(IfThen(Luminance.g_fmtHDR = D3DFMT_G32R32F, 8, 4)) ); end; Result:= usage; end; //-------------------------------------------------------------------------------------- // RenderToTexture( ) // // DESC: // A simple utility function that draws, as a TL Quad, one texture to another // such that a pixel shader (configured before this function is called) can // operate on the texture. Used by MeasureLuminance() to perform the // downsampling and filtering. // // PARAMS: // pDevice : The currently active device // // NOTES: // n/a // //-------------------------------------------------------------------------------------- function RenderToTexture(const pDev: IDirect3DDevice9): HRESULT; var desc: TD3DSurfaceDesc; pSurfRT: IDirect3DSurface9; fWidth, fHeight: Single; v: array[0..3] of Luminance.TLVertex; begin pDev.GetRenderTarget(0, pSurfRT); pSurfRT.GetDesc(desc); pSurfRT := nil; // To correctly map from texels->pixels we offset the coordinates // by -0.5f: fWidth := desc.Width - 0.5; fHeight := desc.Height - 0.5; // Now we can actually assemble the screen-space geometry v[0].p := D3DXVector4(-0.5, -0.5, 0.0, 1.0); v[0].t := D3DXVector2(0.0, 0.0); v[1].p := D3DXVector4(fWidth, -0.5, 0.0, 1.0); v[1].t := D3DXVECTOR2(1.0, 0.0); v[2].p := D3DXVector4(-0.5, fHeight, 0.0, 1.0); v[2].t := D3DXVector2(0.0, 1.0); v[3].p := D3DXVector4(fWidth, fHeight, 0.0, 1.0); v[3].t := D3DXVector2(1.0, 1.0); // Configure the device and render.. pDev.SetVertexShader(nil); pDev.SetFVF(Luminance.FVF_TLVERTEX); pDev.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(Luminance.TLVertex)); Result:= S_OK; end; end.
unit UTextProcessing; interface uses SysUtils, Dialogs, Classes, StrUtils, Math; type TArgs = set of Char; TSearchType = (stWholeWord, stMatchCase); TSearchTypes = set of TSearchType; type TStrProc = procedure(var S: string; BeginPos, EndPos: Integer; const OpenSymbol, CloseSymbol: Char); type TDir = (ToLeft, ToRight); type TSpacePosition = (spNone, spBeforeAndAfter, spBefore, spAfter); TSpacePositionParam = record IdentStr: string; SearchTypes: TSearchTypes; SpacePosition: TSpacePosition; end; TSpacePositionParams = array of TSpacePositionParam; function IsSpaceErrors(const S: string; const IdentStr: string; SpacePosition: TSpacePosition; SearchTypes: TSearchTypes = []): Boolean; overload; function IsSpaceErrors(const S: string): Boolean; overload; function CorrectSpaceErrors(const S: string): string; overload; function CorrectSpaceErrors(const S: string; IdentStr: string; SearchTypes: TSearchTypes; SpacePosition: TSpacePosition): string; overload; function CountGroupedSymb(S: string; Symb: Char; Position: Integer; Dir: TDir = ToRight): Integer; function CountSymbol(C: Char; S: string): Integer; procedure DelReiterativeSymb(var S: string; const Args: TArgs); overload; procedure DelReiterativeSymb(var S: string; const Args: TArgs; var CursorPos: Integer); overload; function PosNSymbLeft(InputString: string; Symbol: Char; N: Integer): Integer; function PosNSymbRight(InputString: string; Symbol: Char; N: Integer): Integer; function MyFindText(SearchStr: string; const Str: string; Options: TSearchTypes = []; StartPos: Integer = 1; Count: Integer = MaxInt): Integer; function PosExFromRightSide(const SearchStr: string; const S: string; Offset: Integer = MaxInt): Integer; function FindTextFromRightSide(SearchStr: string; const Str: string; Offset: Integer = MaxInt; Options: TSearchTypes = []): Integer; function ReplaceChars(S: string; Chars: TArgs; ReplacedStr: string): string; function ExceptString(S: string; const ExceptionsString: string): string; function ExceptAllStrings(S: string; ExceptionsStrings: TStringList): string; function ExceptAllStrings2(S: string; ExceptionsStrings: TStringList): string; //Функция similarity возвращает коэффициент "похожести" двух строк. function similarity(i: LongInt; a, b: string): Double; stdcall; external 'similar.dll'; const // символы - разграничители слов WordDelimeters: set of char = [' ', #10, #13, #9, ',', '.', ';', '(', ')', '"', '!', '?', '@', ':', '{', '}', '[', ']']; type TSetOfChar = set of Char; function ScatterStringToWords(Str: string; Delimeters: TSetOfChar = [' ', #13, #10]): TStringList; overload; procedure ScatterStringToWords(Str: string; out WordsList: TStringList; Delimeters: TSetOfChar = [' ', #13, #10]); overload; function IsKeysInString(KeysList: TStringList; const Str: string): Boolean; var DefaultSpacePositionParams: TSpacePositionParams; implementation function IsSpaceErrors(const S: string; const IdentStr: string; SpacePosition: TSpacePosition; SearchTypes: TSearchTypes = []): Boolean; overload; var CorrectedString: string; begin CorrectedString := CorrectSpaceErrors(S, IdentStr, SearchTypes, SpacePosition); if CorrectedString = S then Result := False else Result := True; end; function IsSpaceErrors(const S: string): Boolean; overload; var CorrectedString: string; begin CorrectedString := CorrectSpaceErrors(S); if CorrectedString = S then Result := False else Result := True; end; function CorrectSpaceErrors(const S: string): string; overload; var BeginPos, EndPos: Integer; InsertSpacePositions, DeleteSpacePositions: array of Integer; IdentStr: string; SearchTypes: TSearchTypes; SpacePosition: TSpacePosition; i: Integer; procedure InsertSpace(Position: Integer); var NewIndex: Integer; begin NewIndex := Length(InsertSpacePositions); SetLength(InsertSpacePositions, NewIndex + 1); InsertSpacePositions[NewIndex] := Position; end; procedure DeleteSpace(Position: Integer); var NewIndex: Integer; begin NewIndex := Length(DeleteSpacePositions); SetLength(DeleteSpacePositions, NewIndex + 1); DeleteSpacePositions[NewIndex] := Position; end; procedure DeleteSpacesBeforeAndAfter(BeginPos, EndPos: Integer); var j: Integer; begin for j := CountGroupedSymb(Result, ' ', BeginPos - 1, ToLeft) downto 1 do // Lфры хь тёх яюфЁ ф шфє•шх яЁюсхыv фю эрўрыр ёЄЁюъш DeleteSpace(BeginPos - j); for j := 1 to CountGroupedSymb(Result, ' ', EndPos + 1) do // Lфры хь тёх яюфЁ ф шфє•шх яЁюсхыv яюёых ъюэЎр ёЄЁюъш DeleteSpace(EndPos + j); end; function IndexPosititonInArray(Position: Integer; ArrayOfPositions: array of Integer): Integer; var j: Integer; begin Result := -1; for j := Length(ArrayOfPositions) - 1 downto 0 do if ArrayOfPositions[j] = Position then begin Result := j; Break; end; end; begin Result := S; if Length(S) < 2 then Exit; for i := 0 to Length(DefaultSpacePositionParams) - 1 do begin BeginPos := MaxInt; IdentStr := DefaultSpacePositionParams[i].IdentStr; SearchTypes := DefaultSpacePositionParams[i].SearchTypes; SpacePosition := DefaultSpacePositionParams[i].SpacePosition; while FindTextFromRightSide(IdentStr, Result, BeginPos - 1, SearchTypes) <> 0 do begin BeginPos := FindTextFromRightSide(IdentStr, Result, BeginPos - 1, SearchTypes); EndPos := BeginPos + Length(IdentStr) - 1; DeleteSpacesBeforeAndAfter(BeginPos, EndPos); case SpacePosition of spNone: ; // Зэ пробелз вже воз делейтэд бифор spBeforeAndAfter: begin InsertSpace(BeginPos); InsertSpace(EndPos + 1); end; spBefore: InsertSpace(BeginPos); spAfter: InsertSpace(EndPos + 1); end; end; end; for i := Length(Result) downto 1 do begin if IndexPosititonInArray(i, DeleteSpacePositions) <> -1 then Delete(Result, DeleteSpacePositions[IndexPosititonInArray(i, DeleteSpacePositions)], 1); if IndexPosititonInArray(i, InsertSpacePositions) <> -1 then Insert(' ', Result, InsertSpacePositions[IndexPosititonInArray(i, InsertSpacePositions)]); end; end; function CorrectSpaceErrors(const S: string; IdentStr: string; SearchTypes: TSearchTypes; SpacePosition: TSpacePosition): string; overload; var BeginPos, EndPos: Integer; InsertSpacePositions, DeleteSpacePositions: array of Integer; i: Integer; procedure InsertSpace(Position: Integer); var NewIndex: Integer; begin NewIndex := Length(InsertSpacePositions); SetLength(InsertSpacePositions, NewIndex + 1); InsertSpacePositions[NewIndex] := Position; end; procedure DeleteSpace(Position: Integer); var NewIndex: Integer; begin NewIndex := Length(DeleteSpacePositions); SetLength(DeleteSpacePositions, NewIndex + 1); DeleteSpacePositions[NewIndex] := Position; end; procedure DeleteSpacesBeforeAndAfter(BeginPos, EndPos: Integer); var j: Integer; begin for j := CountGroupedSymb(Result, ' ', BeginPos - 1, ToLeft) downto 1 do // Lфры хь тёх яюфЁ ф шфє•шх яЁюсхыv фю эрўрыр ёЄЁюъш DeleteSpace(BeginPos - j); for j := 1 to CountGroupedSymb(Result, ' ', EndPos + 1) do // Lфры хь тёх яюфЁ ф шфє•шх яЁюсхыv яюёых ъюэЎр ёЄЁюъш DeleteSpace(EndPos + j); end; function IndexPosititonInArray(Position: Integer; ArrayOfPositions: array of Integer): Integer; var j: Integer; begin Result := -1; for j := Length(ArrayOfPositions) - 1 downto 0 do if ArrayOfPositions[j] = Position then begin Result := j; Break; end; end; begin Result := S; if Length(S) < 2 then Exit; BeginPos := MaxInt; while FindTextFromRightSide(IdentStr, Result, BeginPos - 1, SearchTypes) <> 0 do begin BeginPos := FindTextFromRightSide(IdentStr, Result, BeginPos - 1, SearchTypes); EndPos := BeginPos + Length(IdentStr) - 1; DeleteSpacesBeforeAndAfter(BeginPos, EndPos); case SpacePosition of spNone: ; // Зэ пробелз вже воз делейтэд бифор spBeforeAndAfter: begin InsertSpace(BeginPos); InsertSpace(EndPos + 1); end; spBefore: InsertSpace(BeginPos); spAfter: InsertSpace(EndPos + 1); end; end; for i := Length(Result) downto 1 do begin if IndexPosititonInArray(i, DeleteSpacePositions) <> -1 then Delete(Result, DeleteSpacePositions[IndexPosititonInArray(i, DeleteSpacePositions)], 1); if IndexPosititonInArray(i, InsertSpacePositions) <> -1 then Insert(' ', Result, InsertSpacePositions[IndexPosititonInArray(i, InsertSpacePositions)]); end; end; function CountGroupedSymb(S: string; Symb: Char; Position: Integer; Dir: TDir = ToRight): Integer; var i: Integer; Step: Integer; begin if Dir = ToRight then Step := 1 else Step := -1; Result := 0; i := Position; while (i >= 1) and (i <= Length(S)) and (S[i] = Symb) do begin Inc(Result); i := i + Step; end; end; function CountSymbol(C: Char; S: string): Integer; // Количество символа в строке var i: Integer; begin Result := 0; for i := 1 to Length(S) do if S[i] = C then Inc(Result); end; procedure DelReiterativeSymb(var S: string; const Args: TArgs); overload; // Удаление повторяющихся символов (знаков пунктуации например...) "ООО Туалет,,," "ООО Туалет" var i : Integer; begin i := 2; while i <= Length(S) do if (S[i] in Args) and (S[i] = S[i - 1]) then Delete(S, i, 1) else Inc(i); end; procedure DelReiterativeSymb(var S: string; const Args: TArgs; var CursorPos: Integer); overload; // Удаление повторяющихся символов (знаков пунктуации например...) "ООО Туалет,,," "ООО Туалет" var i : Integer; begin i := 2; while i <= Length(S) do if (S[i] in Args) and (S[i] = S[i - 1]) then begin if CursorPos >= i then Dec(CursorPos); Delete(S, i, 1); end else Inc(i); end; function PosNSymbLeft(InputString: string; Symbol: Char; N: Integer): Integer; // находим N ковычку слева var i: Integer; begin Result := 0; for i := 1 to Length(InputString) do begin if InputString[i] = Symbol then if N = 1 then begin Result := i; Exit; end else Dec(N); end; end; function PosNSymbRight(InputString: string; Symbol: Char; N: Integer): Integer; // находим N ковычку справа var i: Integer; begin Result := 0; for i := Length(InputString) downto 1 do begin if InputString[i] = Symbol then if N = 1 then begin Result := i; Exit; end else Dec(N); end; end; function MyFindText(SearchStr: string; const Str: string; Options: TSearchTypes = []; StartPos: Integer = 1; Count: Integer = MaxInt): Integer; // 2004 написана но 20.07.2006 кардинально переделана (а 21.09.2006 неайдена и исправлена ошибочка) var EndPos: Integer; BeginPos: Integer; S: string; begin if StartPos < 1 then StartPos := 1; S := Copy(Str, StartPos, Count); if not (stMatchCase in Options) then begin S := LowerCase(S); SearchStr := LowerCase(SearchStr); end; Result := 0; if stWholeWord in Options then begin EndPos := 0; while PosEx(SearchStr, S, EndPos + 1) <> 0 do begin BeginPos := PosEx(SearchStr, S, EndPos + 1); EndPos := BeginPos + Length(SearchStr) - 1; if ((BeginPos <= 1) xor (S[BeginPos - 1] in WordDelimeters)) and ((EndPos >= Length(S)) xor (S[EndPos + 1] in WordDelimeters)) then begin Result := BeginPos; Break; end; end; end else Result := Pos(SearchStr, S); if Result <> 0 then Result := StartPos + Result - 1; end; function PosExFromRightSide(const SearchStr: string; const S: string; Offset: Integer = MaxInt): Integer; var LenSearchStr: Integer; // Длина искомой подстроки PosSearchStr: Integer; // "Предположительная" позиция искомой подстроки i: Integer; IsMath: Boolean; // Одинаковые begin LenSearchStr := Length(SearchStr); if Offset > Length(S) then Offset := Length(S); if LenSearchStr > Offset then // begin Result := 0; Exit; end; PosSearchStr := Offset - LenSearchStr + 1; IsMath := False; while (PosSearchStr >= 1) and not IsMath do begin Dec(PosSearchStr); for i := 1 to LenSearchStr do if S[PosSearchStr + i] = SearchStr[i] then IsMath := True else begin IsMath := False; Break; end; end; if IsMath then Result := PosSearchStr + 1 else Result := 0; end; function FindTextFromRightSide(SearchStr: string; const Str: string; Offset: Integer = MaxInt; Options: TSearchTypes = []): Integer; // 2006 var EndPos: Integer; BeginPos: Integer; S: string; begin if not (stMatchCase in Options) then begin S := Copy(LowerCase(Str), 1, Offset); SearchStr := LowerCase(SearchStr); end; Result := 0; if stWholeWord in Options then begin BeginPos := MaxInt; while PosExFromRightSide(SearchStr, S, BeginPos - 1) <> 0 do begin BeginPos := PosExFromRightSide(SearchStr, S, BeginPos - 1); EndPos := BeginPos + Length(SearchStr) - 1; if ((BeginPos <= 1) xor (S[BeginPos - 1] in WordDelimeters)) and ((EndPos >= Length(S)) xor (S[EndPos + 1] in WordDelimeters)) then begin Result := BeginPos; Break; end; end; end else Result := PosExFromRightSide(SearchStr, S); end; function ReplaceChars(S: string; Chars: TArgs; ReplacedStr: string): string; // Заменяет все символы Chars на строку ReplacedStr // Если ReplacedStr задать '' то получите удаление var i: Integer; begin i := 1; while i <= Length(S) do begin if S[i] in Chars then begin Delete(S, i, 1); Insert(ReplacedStr, S, i); i := i + Length(ReplacedStr); end else Inc(i); end; Result := S; end; function ExceptString(S: string; const ExceptionsString: string): string; // Исключает из S строку ExceptionsString var PosExceptionStr: Integer; begin Result := S; PosExceptionStr := MyFindText(ExceptionsString, Result, [stWholeWord]); while PosExceptionStr <> 0 do begin Result := Copy(Result, 1, PosExceptionStr - 1) + Copy(Result, PosExceptionStr + Length(ExceptionsString), MaxInt); PosExceptionStr := MyFindText(ExceptionsString, Result, [stWholeWord]); end; end; function ExceptAllStrings(S: string; ExceptionsStrings: TStringList): string; // Исключает из строки S все строки из ExceptionsStrings var Row: Integer; begin Result := S; for Row := 1 to ExceptionsStrings.Count - 1 do Result := ExceptString(Result, ExceptionsStrings[Row]); end; function ExceptAllStrings2(S: string; ExceptionsStrings: TStringList): string; // Исключает из строки S все строки из ExceptionsStrings var Row: Integer; begin Result := S; for Row := 1 to ExceptionsStrings.Count - 1 do Result := StringReplace(Result, ExceptionsStrings[Row], '', [rfReplaceAll, rfIgnoreCase]); end; procedure ScatterStringToWords(Str: string; out WordsList: TStringList; Delimeters: TSetOfChar = [' ', #13, #10]); // Разложить строку (Str) на список слов (WordsList). В качестве разделителся пробел. var i: Integer; Word: string; // "Слово" LengthWord: Integer; // Длина "слова" LengthStr: Integer; // Длина всей "строки" begin Str := Trim(Str); // Удаляем лишние пробелы в "строке" if Str = '' then // Если "строка" пуста то и слов в ней нет Exit; WordsList.Clear; // В "списке слов" уже могут быть строки, потому как он нам передаются из вне // После Trim и проверки что "строка" не пуста мы точно знаем что её длина точно не меньше одного символа Word := Str[1]; // первый символ полюбому не пробел, потому сразу его вносим в "слово" LengthWord := 1; LengthStr := Length(Str); SetLength(Word, LengthStr); // Выделяем память для "слова" с запасом. Полюбому "слово" не может быть длинее самой "строки", где оно находится // Начинаем перебор "строки" со второго символа, потому как первый символ мы уже внесли в "слово" for i := 2 to LengthStr do if not (Str[i] in Delimeters) then // Если это не пробел дописываем его в слово begin Inc(LengthWord); Word[LengthWord] := Str[i] end else if not (Str[i - 1] in Delimeters) then begin // Мы выделяли для "слова" память с запасом, потому что не могли знать сразу его длину. // Теперь длину мы узнали и устанавливаем её "слову". SetLength(Word, LengthWord); // Записываем "слово" в список слов WordsList.Append(Word); // Всё теперь сбрасываем перемнную "слово" LengthWord := 0; // Выделяем память для слова с запасом. // При этом мы уже выбрали из первых i символов "строки" все слова. SetLength(Word, LengthStr - i); end; // Заканчиваем "слово" SetLength(Word, LengthWord); // Записываем "слово" в список слов WordsList.Append(Word); end; function ScatterStringToWords(Str: string; Delimeters: TSetOfChar = [' ', #13, #10]): TStringList; // Разложить строку на слова begin Result := TStringList.Create; ScatterStringToWords(Str, Result); end; function IsKeysInString(KeysList: TStringList; const Str: string): Boolean; // Проверка совпадения строки: все ключевые слова есть в строке var i: Integer; begin for i := 0 to KeysList.Count - 1 do if Pos(KeysList[i], Str) = 0 then // Если ключ есть в название ассортимета begin Result := False; Exit; end; Result := True; end; initialization SetLength(DefaultSpacePositionParams, 6); DefaultSpacePositionParams[0].IdentStr := ','; DefaultSpacePositionParams[0].SearchTypes := []; DefaultSpacePositionParams[0].SpacePosition := spAfter; DefaultSpacePositionParams[1].IdentStr := '.'; DefaultSpacePositionParams[1].SearchTypes := []; DefaultSpacePositionParams[1].SpacePosition := spAfter; DefaultSpacePositionParams[2].IdentStr := ')'; DefaultSpacePositionParams[2].SearchTypes := []; DefaultSpacePositionParams[2].SpacePosition := spAfter; DefaultSpacePositionParams[3].IdentStr := '('; DefaultSpacePositionParams[3].SearchTypes := []; DefaultSpacePositionParams[3].SpacePosition := spBefore; DefaultSpacePositionParams[4].IdentStr := ''''; DefaultSpacePositionParams[4].SearchTypes := []; DefaultSpacePositionParams[4].SpacePosition := spNone; DefaultSpacePositionParams[5].IdentStr := '-'; DefaultSpacePositionParams[5].SearchTypes := []; DefaultSpacePositionParams[5].SpacePosition := spNone; finalization DefaultSpacePositionParams := nil; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; procedure dbupdate(aDsn ,aSql : string ); Function dbquery(aDsn ,aSql : string ):Array of TStringList; implementation {$R *.DFM} uses odbc ; Function dbquery(aDsn ,aSql : string ):Array of TStringList; var query1 : Todbcst; r : Array of TStringList; begin try PSQLAllocEnv; PSQLAllocConnect; If PSQLConnect(pchar(aDsn),'','') = 0 Then Begin Try Query1 := Todbcst.Create; With Query1 do Begin Try Sql := asql; execute; Except On E: Error_Odbc do ; End; End; Finally Query1.Free; End; End; Finally PSQLDisconnect; PSQLFreeConnect; PSQLFreeEnv; End; end; procedure dbquery(aDsn ,aSql : string ); var query1 : Todbcst; i : integer ; begin try PSQLAllocEnv; PSQLAllocConnect; If PSQLConnect(pchar(aDsn),'','') = 0 Then Begin Try Query1 := Todbcst.Create; With Query1 do Begin Try Sql := asql; execute; // table - While Next do Begin // table - for i :=1 to NumbCols do form1.caption := form1.caption + cellstring(i) ; End; Except On E: Error_Odbc do ; End; End; Finally Query1.Free; End; End; Finally PSQLDisconnect; PSQLFreeConnect; PSQLFreeEnv; End; end; procedure TForm1.Button1Click(Sender: TObject); begin //dbupdate('gongjiao','update [三日表] set [车号]=12305' ); dbquery('gongjiao','select * from [三日表] ' ); end; end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PAXCOMP_ERROR.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} {$O-} unit PAXCOMP_ERROR; interface uses {$I uses.def} PAXCOMP_TYPES, SysUtils, Classes; type TError = class private kernel: Pointer; fMessage: String; fPCodeLineNumber: Integer; fModuleName: String; fSourceLineNumber: Integer; fSourceLine: String; fLinePos: Integer; fSourceFileName: String; public constructor Create(i_kernel: Pointer; const i_Message: String); overload; constructor Create(i_kernel: Pointer); overload; function Clone(i_kernel: Pointer): TError; property Message: String read fMessage; property PCodeLineNumber: Integer read fPCodeLineNumber; property ModuleName: String read fModuleName; property SourceLine: String read fSourceLine; property SourceLineNumber: Integer read fSourceLineNumber; property LinePos: Integer read fLinePos; property SourceFileName: String read fSourceFileName; end; TErrorList = class(TTypedList) private kernel: Pointer; function GetRecord(I: Integer): TError; public constructor Create(i_kernel: Pointer); procedure Reset; procedure Add(E: TError); function IndexOf(E: TError): Integer; property Records[I: Integer]: TError read GetRecord; default; end; implementation uses PAXCOMP_KERNEL, PAXCOMP_PARSER, PAXCOMP_MODULE; constructor TError.Create(i_kernel: Pointer); begin inherited Create; kernel := i_kernel; end; constructor TError.Create(i_kernel: Pointer; const i_Message: String); var M: TModule; begin inherited Create; fMessage := i_Message; kernel := i_kernel; fPCodeLineNumber := TKernel(kernel).Code.N; if (fPCodeLineNumber < 1) or (fPCodeLineNumber > TKernel(kernel).Code.Card) then fPCodeLineNumber := TKernel(kernel).Code.Card; M := TKernel(kernel).Code.GetModule(fPCodeLineNumber); if M <> nil then begin fModuleName := M.Name; fSourceLine := TKernel(kernel).Code.GetSourceLine(fPCodeLineNumber); fSourceLineNumber := TKernel(kernel).Code.GetSourceLineNumber(fPCodeLineNumber); fLinePos := TKernel(kernel).Code.GetLinePos(fPCodeLineNumber); fSourceFileName := TKernel(kernel).Code.GetIncludedFileName(fPCodeLineNumber); if fSourceFileName = '' then fSourceFileName := M.FileName; end else begin fModuleName := ''; fSourceLine := ''; fSourceLineNumber := 0; fLinePos := 0; end; end; function TError.Clone(i_kernel: Pointer): TError; begin result := TError.Create(i_Kernel); result.fMessage := fMessage; result.fPCodeLineNumber := fPCodeLineNumber; result.fModuleName := fModuleName; result.fSourceLineNumber := fSourceLineNumber; result.fSourceLine := fSourceLine; result.fLinePos := fLinePos; result.fSourceFileName := fSourceFileName; end; constructor TErrorList.Create(i_kernel: Pointer); begin inherited Create; Self.kernel := i_kernel; end; procedure TErrorList.Reset; begin Clear; end; function TErrorList.GetRecord(I: Integer): TError; begin result := TError(L[I]); end; function TErrorList.IndexOf(E: TError): Integer; var I: Integer; begin result := -1; for I := 0 to Count - 1 do if Records[I].fSourceLineNumber = E.fSourceLineNumber then if Records[I].fMessage = E.fMessage then begin result := I; Exit; end; end; procedure TErrorList.Add(E: TError); begin if IndexOf(E) = -1 then L.Add(E) else FreeAndNil(E); end; end.
(* Category: SWAG Title: FILE & ENCRYPTION ROUTINES Original name: 0011.PAS Description: PASSWORD.PAS Author: SWAG SUPPORT TEAM Date: 05-28-93 13:40 *) { JL>Help me guys. I'm learning about reading from a File. I am creating a JL>Program that will let you set passWord and test a passWord. JL>Also how do you make the screen print a Character like .... instead of a JL>Word. So when you enter in a passWord like in BBS it won't show it? ------------------------------------X---------------------------------------- } Program TestPW; { Programmer : Chet Kress (FidoNet 1:283/120.4) Been Tested? : YES, this has been tested. It works! original Date : 01/01/93 Current Version : v1.0 Language : Turbo Pascal v7.0 Purpose : Make a passWord routine } Uses Crt; Procedure TestPassWord; Const DataFile = 'PW.DAT'; {The name of the data File containing the passWord} {Just have one line in the PW.DAT File, and use that as the passWord} Var PassWordFile : Text; {The name assigned to the data File} PassCH : Char; {A Character that the user has entered} TempPassWord : String; {The temporary passWord from the user} ThePW : String; {The Real passWord from the data File} begin {TestPassWord} Assign (PassWordFile, DataFile); Reset (PassWordFile); ClrScr; TempPassWord := ''; Write ('Enter passWord: '); { I replaced the Readln With this Repeat..Until loop so you can see the "periods" instead of the Characters (like you wanted). This is a simple routine, but it should suffice For what you want it to do. It has some error checking and backspacing is available too. } Repeat PassCH := ReadKey; if (PassCH = #8) and (Length(TempPassWord) > 0) then begin Delete (TempPassWord, Length(TempPassWord), 1); GotoXY (WhereX-1, WhereY); Write (' '); GotoXY (WhereX-1, WhereY); end; if (PassCH >= #32) and (PassCH <= #255) then begin TempPassWord := TempPassWord + PassCH; Write ('.'); end; Until (PassCH = #13); Writeln; Readln (PassWordFile, ThePW); { <-- You Forgot to add this line } if TempPassWord = ThePW then begin Writeln ('You have received access.'); Writeln ('Loading Program.'); { Do whatever else you want to here } end else begin Writeln ('Wrong PassWord.'); end; Close (PassWordFile); end; {TestPassWord} begin {Main} TestPassWord; end. {Main}
{..............................................................................} { Summary Moves objects within the defined boundary set by the user } { User can choose which objects to move. } { } { Version 1.2 } {..............................................................................} Var Board : IPCB_Board; X1,Y1,X2,Y2 : TCoord; {..............................................................................} {..............................................................................} Procedure MovePCBObjects; Begin // get the PCB document interface Board := PCBServer.GetCurrentPCBBoard; If Board = Nil Then Begin ShowWarning('This is not a PCB document.'); formMovePCBObjects.Close; End; End; {..............................................................................} {..............................................................................} procedure TformMovePCBObjects.buttonMove1Click(Sender: TObject); begin If Not (Board.ChooseRectangleByCorners( 'Choose first corner', 'Choose final corner', x1,y1,x2,y2)) Then Exit; ExecuteMove(True, cbDesignObjects); End; {..............................................................................} {..............................................................................} procedure TformMovePCBObjects.buttonMove2Click(Sender: TObject); begin If Not (Board.ChooseRectangleByCorners( 'Choose first corner', 'Choose final corner', x1,y1,x2,y2)) Then Exit; ExecuteMove(False, cbDesignObjects); end; {..............................................................................} {..............................................................................} procedure TformMovePCBObjects.bCloseClick(Sender: TObject); begin Close; end; {..............................................................................} {..............................................................................}
unit ImageIOUtils; interface uses Graphics, Jpeg, PCXCtrl, SysUtils, PNGImage, TARGA, TextureBankItem, Dialogs; function GetBMPFromImageFile(_filename: string): TBitmap; overload; function GetBMPFromJPGImageFile(_filename: string): TBitmap; function GetBMPFromPCXImageFile(_filename: string): TBitmap; function GetBMPFromPNGImageFile(_filename: string): TBitmap; function GetBMPFromTGAImageFile(_filename: string): TBitmap; function GetBMPFromDDSImageFile(_filename: string): TBitmap; procedure SaveImage(const _FileName: string; const _Bitmap:TBitmap); procedure SaveBMPAsJPGImageFile(const _FileName: string; const _Bitmap:TBitmap); procedure SaveBMPAsPCXImageFile(const _FileName: string; const _Bitmap:TBitmap); procedure SaveBMPAsPNGImageFile(const _FileName: string; const _Bitmap:TBitmap); procedure SaveBMPAsTGAImageFile(const _FileName: string; const _Bitmap:TBitmap); procedure SaveBMPAsDDSImageFile(const _FileName: string; const _Bitmap:TBitmap); implementation function GetBMPFromTGAImageFile(_filename: string): TBitmap; var Bitmap: TBitmap; begin Bitmap := TBitmap.Create; Result := TBitmap.Create; LoadFromFileX(_Filename, Bitmap); Result.Assign(Bitmap); Bitmap.Free; end; function GetBMPFromPNGImageFile(_filename: string): TBitmap; var PNGImage: TPNGObject; Bitmap: TBitmap; begin Bitmap := TBitmap.Create; PNGImage := TPNGObject.Create; PNGImage.LoadFromFile(_Filename); Bitmap.Assign(PNGImage); PNGImage.Free; Result := Bitmap; end; function GetBMPFromJPGImageFile(_filename: string): TBitmap; var JPEGImage: TJPEGImage; Bitmap: TBitmap; begin Bitmap := TBitmap.Create; JPEGImage := TJPEGImage.Create; JPEGImage.LoadFromFile(_Filename); Bitmap.Assign(JPEGImage); JPEGImage.Free; Result := Bitmap; end; function GetBMPFromPCXImageFile(_filename: string): TBitmap; var PCXBitmap: TPCXBitmap; Bitmap: TBitmap; begin Bitmap := TBitmap.Create; PCXBitmap := TPCXBitmap.Create; try try PCXBitmap.LoadFromFile(_Filename); Bitmap.Assign(TBitmap(PCXBitmap)); except ShowMessage( 'Atenção: O suporte para arquivos PCX neste programa é limitado e, por algum motivo, esse arquivo não pode ser lido. Escolha outro arquivo.'); end; finally PCXBitmap.Free; end; Result := Bitmap; end; function GetBMPFromDDSImageFile(_filename: string): TBitmap; var Texture: TTextureBankItem; begin Texture := TTextureBankItem.Create(_Filename); Result := Texture.DownloadTexture(0); Texture.Free; end; function GetBMPFromImageFile(_filename: string): TBitmap; overload; var Bmp: TBitmap; Ext: string; begin Bmp := TBitmap.Create; Ext := ansilowercase(extractfileext(_filename)); if Ext = '.bmp' then begin Bmp.LoadFromFile(_Filename); end else if (Ext = '.jpg') or (Ext = '.jpeg') then begin bmp := GetBMPFromJPGImageFile(_Filename); end else if (Ext = '.pcx') then begin bmp := GetBMPFromPCXImageFile(_Filename); end else if (Ext = '.png') then begin bmp := GetBMPFromPNGImageFile(_Filename); end else if (Ext = '.tga') then begin bmp := GetBMPFromTGAImageFile(_Filename); end else if (Ext = '.dds') then begin bmp := GetBMPFromDDSImageFile(_Filename); end; Result := bmp; end; procedure SaveImage(const _FileName: string; const _Bitmap:TBitmap); var Ext: string; begin Ext := ansilowercase(extractfileext(_FileName)); if Ext = '.bmp' then begin _Bitmap.SaveToFile(_FileName); end else if (Ext = '.jpg') or (Ext = '.jpeg') then begin SaveBMPAsJPGImageFile(_FileName,_Bitmap); end else if (Ext = '.pcx') then begin SaveBMPAsPCXImageFile(_FileName,_Bitmap); end else if (Ext = '.png') then begin SaveBMPAsPNGImageFile(_FileName,_Bitmap); end else if (Ext = '.tga') then begin SaveBMPAsTGAImageFile(_FileName,_Bitmap); end else if (Ext = '.dds') then begin SaveBMPAsDDSImageFile(_FileName,_Bitmap); end; end; procedure SaveBMPAsJPGImageFile(const _FileName: string; const _Bitmap:TBitmap); var JPEGImage: TJPEGImage; begin JPEGImage := TJPEGImage.Create; JPEGImage.Assign(_Bitmap); JPEGImage.SaveToFile(_Filename); JPEGImage.Free; end; procedure SaveBMPAsPCXImageFile(const _FileName: string; const _Bitmap:TBitmap); var PCXImage: TPCXBitmap; begin PCXImage := TPCXBitmap.Create; PCXImage.Assign(_Bitmap); PCXImage.SaveToFile(_Filename); PCXImage.Free; end; procedure SaveBMPAsPNGImageFile(const _FileName: string; const _Bitmap:TBitmap); var PNGImage: TPNGObject; begin PNGImage := TPNGObject.Create; PNGImage.Assign(_Bitmap); PNGImage.SaveToFile(_FileName); PNGImage.Free; end; procedure SaveBMPAsTGAImageFile(const _FileName: string; const _Bitmap:TBitmap); begin SaveToFileX(_Filename,_Bitmap,2); end; procedure SaveBMPAsDDSImageFile(const _FileName: string; const _Bitmap:TBitmap); var Texture: TTextureBankItem; begin Texture := TTextureBankItem.Create(_Bitmap); Texture.SaveTexture(_Filename); Texture.Free; end; end.
Program rpg; uses crt; const ile_zdarzen=14; type r_zdarzenia = ( wrog, nieznajomy, przedmiot, nic ); r_nieznajomego = ( zlodziej, dobry_d, zly_d, czarodziej ); r_przedmiotu = ( miecz, zbroja, eliksir, mieso, zloto, trucizna ); zdarzenie = record opis: string; prawdo: integer; case rodzaj: r_zdarzenia of wrog: ( sila: integer ); przedmiot: ( rzecz: r_przedmiotu ); nieznajomy: ( kto: r_nieznajomego ); end; bohater = record wytrzymalosc: integer; sila: integer; bagaz: set of r_przedmiotu; zloto: integer; end; const hero: bohater = ( wytrzymalosc: 4; sila: 4; bagaz: []; zloto: 0); swiat: array[1..ile_zdarzen] of zdarzenie = ( (opis:'nic'; prawdo:40; rodzaj:wrog; sila:1), (opis:'oblesny gnom'; prawdo:10; rodzaj:wrog; sila:2), (opis:'wielki smok'; prawdo:5; rodzaj:wrog; sila:7), (opis:'straszny troll'; prawdo:10; rodzaj:wrog; sila:3), (opis:'zlodzieja'; prawdo:1; rodzaj:nieznajomy; sila:1), (opis:'czarodzieja'; prawdo:6; rodzaj:nieznajomy; sila:1), (opis:'dobrego duszka'; prawdo:5; rodzaj:nieznajomy; sila:1), (opis:'zlego ducha'; prawdo:5; rodzaj:nieznajomy; sila:1), (opis:'miecz'; prawdo:2; rodzaj:przedmiot; sila:1), (opis:'zbroje'; prawdo:2; rodzaj:przedmiot; sila:1), (opis:'magiczny eliksir'; prawdo:4; rodzaj:przedmiot; sila:1), (opis:'sztuke miesa'; prawdo:4; rodzaj:przedmiot; sila:1), (opis:'zloto'; prawdo:5; rodzaj:przedmiot; sila:1), (opis:'trucizne'; prawdo:3; rodzaj:przedmiot; sila:1) ); nazwa_p: array [miecz..trucizna] of string = ('miecz', 'zbroja', 'eliksir', 'mieso', 'zloto', 'trucizna'); var ile: integer; klawisz: char; Procedure opisz_bohatera; var przed: r_przedmiotu; begin clrscr; writeln('Wtrzymalosc: ', hero.wytrzymalosc, ', Sila: ', hero.sila, ', Zloto: ', hero.zloto); write('Bagaz: '); for przed:=miecz to trucizna do if przed in hero.bagaz then write(nazwa_p[przed],' '); writeln; writeln('*******************************'); end; procedure spotkaj_wroga( kto: zdarzenie ); var sila: integer; pieniadz: integer; ekwipunek: integer; decyz: char; walka: boolean; begin ekwipunek:=0; sila:=random(6)+kto.sila; writeln('Zza krzkow wyskoczyl ', kto.opis, ' o sile ', sila); writeln('W]alczysz, U]ciekasz, N]egocjujesz?'); decyz:=upcase(readkey); walka:=true; if decyz='U' then begin if hero.sila>random(6) then begin writeln('Udalo ci sie ujsc z zyciem.'); walka:=false; end else writeln('Zostales zlapany.'); end; if decyz='N' then begin write('Ile zlota proponujesz za uwolnienie?'); readln(pieniadz); if(pieniadz > (sila+random(5))*5)and(pieniadz<hero.zloto) then begin writeln('Twoja propozycja zostala przyjeta.'); walka:=false; hero.zloto:=hero.zloto-pieniadz; end else writeln('Propozycja zostala odrzucona. Czeka cie walka.'); end; if walka then begin writeln('Atakujesz...'); if miecz in hero.bagaz then ekwipunek:=ekwipunek+2; if sila >= hero.sila+ekwipunek+random(6) then begin writeln('Przegrywasz'); if (zbroja in hero.bagaz) and (random(6)>3) then writeln('Jednak chroni Cie zbroja.') else begin hero.wytrzymalosc:=hero.wytrzymalosc-1; hero.zloto:=hero.zloto div 3; end end else begin writeln('Wygrywasz'); hero.zloto:=hero.zloto+sila+5; end end; end; procedure spotkaj_nieznajomego(ktos: zdarzenie); begin writeln('Spotkales ', ktos.opis); case ktos.kto of zlodziej: begin hero.zloto:=0; hero.bagaz:=[]; end; dobry_d: hero.sila:=hero.sila+1; zly_d: if hero.sila>0 then hero.sila:=hero.sila-1; czarodziej: hero.wytrzymalosc:=hero.wytrzymalosc+1; end; end; procedure znajdz_przedmiot(co: zdarzenie); var los: integer; begin writeln('Znalazles ', co.opis); los:=random(20)+20; case co.rzecz of miecz: hero.bagaz:= hero.bagaz+[miecz]; zbroja: hero.bagaz:= hero.bagaz+[zbroja]; eliksir: hero.wytrzymalosc:=hero.wytrzymalosc+1; mieso: hero.sila:=hero.sila+1; zloto: hero.zloto:=hero.zloto+1; trucizna: begin hero.wytrzymalosc:= hero.wytrzymalosc div 2; hero.sila:= hero.sila div 2; end; end; end; begin randomize; opisz_bohatera; while hero.wytrzymalosc>0 do begin ile:=1; repeat if random(100) < swiat[ile].prawdo then begin case swiat[ile].rodzaj of wrog: spotkaj_wroga(swiat[ile]); nieznajomy: spotkaj_nieznajomego(swiat[ile]); przedmiot: znajdz_przedmiot(swiat[ile]); end; writeln('I]dziesz dalej. K]onczysz gre'); klawisz:=readkey; if upcase(klawisz)='K' then hero.wytrzymalosc:=0 else opisz_bohatera; end; ile:=ile+1; until (ile>ile_zdarzen) or (hero.wytrzymalosc<1); end; writeln('Koniec gry'); if hero.zloto>1000 then writeln('Wygrales'); klawisz:=readkey; end.
unit MotionCloud2; interface uses math, util1, stmdef, stmObj,stmPg,Ncdef2,stmMat1, ippdefs17 ,ipps17 , ippi17, mathKernel0, MKL_dfti, Laguerre1; { Utilisation de TmotionCloud Dans l'ordre, il faut: - appeler Init qui fixe les paramètres généraux (taille des matrices, seed et ss - installer un filtre avec InstallGaborFilter, InstallMaternFilter ou InstallFilter - appeler InitNoise qui initialise les tableaux Xe1 et Xe2 - appeler GetFrame pour chaque image générée Si on veut faire évoluer un ou plusieurs paramètres de filtre, on peut appeler InstallFilter entre deux getFrame. Dans ce cas, on n'appelle pas InitNoise. GetFilter permet de récupérer dans une matrice le filtre calculé. } { Condition de calcul: ss< (4-2*sqrt(2))/(N*Dt) } type TmotionCloud= class(typeUO) private Nx,Ny:integer; Finit: boolean; // mis à true avec Init // Init est toujours obligatoire FinitNoise: boolean; // mis à true avec InitNoise // InitNoise est obligatoire avant le premier getFrame LastFrame: PtabDouble; fftNoise: PtabDoubleComp; Xn2,Xn1,Xn0: PtabDoubleComp; seed: longint; procedure paramAR(ss:float); procedure ComputeNoise(fftNoise: PtabDoubleComp ;filter: PtabDouble); procedure InitFilterConstants; procedure Autoreg; procedure expand(src,dest:PtabDouble;Dx,x0,Dy,y0: float); public a,b,c,filter: PtabDouble; mu,sigma: float; DxF,x0F,DyF,y0F:float; dtAR:float; Nsample: integer; constructor create;override; destructor destroy;override; class function STMClassName:AnsiString;override; procedure InstallGaborFilter( ss, r0, sr0, stheta0: float); procedure AdjustLogGaborParams(var r0,sr0,ss:float); procedure InstallLogGaborFilter( ss, r0, sr0, stheta0: float); procedure InstallMaternFilter( ss, eta, alpha: float); procedure InstallFilter( var mat: Tmatrix); procedure Init( Nx1,Ny1:integer;seed1:integer; const Fmem:boolean=true); procedure InitNoise; procedure done; procedure getFrame(mat: Tmatrix); procedure getFilter(mat: Tmatrix); end; procedure proTmotionCloud_Create(var pu:typeUO);pascal; procedure proTmotionCloud_Init(dt: float;Nsample1:integer; Nx1,Ny1: integer; seed: longword;var pu:typeUO);pascal; procedure proTmotionCloud_InstallGaborFilter( ss, r0, sr0, stheta0: float; var pu:typeUO);pascal; procedure proTmotionCloud_InstallMaternFilter( ss, eta, alpha: float; var pu:typeUO);pascal; procedure proTmotionCloud_InstallFilter(var mat: Tmatrix;var pu:typeUO);pascal; procedure proTmotionCloud_getFilter(var mat: Tmatrix;var pu:typeUO);pascal; procedure proTmotionCloud_done(var pu:typeUO);pascal; procedure proTmotionCloud_getFrame(var mat: Tmatrix; var pu:typeUO);pascal; procedure proTmotionCloud_SetExpansion(DxF1,x0F1,DyF1,y0F1:float;var pu:typeUO);pascal; implementation (* Jonathan: Dans les 3 fonctions suivantes, il faut diviser les filtres obtenus par leur variance *) procedure TmotionCloud.InstallGaborFilter( ss,r0, sr0, stheta0: float); var x,y,r,theta: float; i,j:integer; begin paramAR(ss); (* for i:=0 to nx-1 do for j:=0 to ny-1 do begin x:= i*2*PI/nx; if x>=pi then x:= x- 2*PI; y:= j*2*PI/ny; if y>=pi then y:= y-2*PI; r:= sqrt(sqr(x)+sqr(y)); theta:= arctan2(y,x){-theta0}; filter[i+j*nx]:= (exp(- sqr(theta)/(2*sqr(stheta0))) + exp( -sqr(theta+ PI)/(2*sqr(stheta0)) )) * exp(-sqr(r-r0)/(2*sqr(sr0))); end; *) for i:=0 to nx div 2-1 do for j:=0 to ny div 2-1 do begin x:= i; y:= j; r:= sqrt(sqr(x)+sqr(y)); theta:= arctan2(y,x){-theta0}; filter[i+j*nx]:= (exp(- sqr(theta)/(2*sqr(stheta0))) {+ exp( -sqr(theta+ PI)/(2*sqr(stheta0)) )}) * exp(-sqr(r-r0)/(2*sqr(sr0))); filter[(Nx-1-i) +j*Nx]:= filter[i +j*Nx]; end; for i:=0 to nx -1 do for j:=0 to ny div 2-1 do filter[(Nx-1-i) +(Ny-j-1)*Nx]:= filter[i +j*Nx]; (* for i:=0 to nx -1 do for j:=0 to ny -1 do begin x:= i*2*PI/nx; if x>pi then x:=x-2*pi; y:= j*2*PI/ny; if y>pi then y:=y-2*pi; r:= sqrt(sqr(x)+sqr(y)); theta:= arctan2(y,x){-theta0}; if theta>pi/2 filter[i+j*nx]:= (exp(- sqr(theta)/(2*sqr(stheta0))) + exp( -sqr(theta+ PI)/(2*sqr(stheta0)) )) * exp(-sqr(r-r0)/(2*sqr(sr0))); filter[(Nx-1-i) +j*Nx]:= filter[i +j*Nx]; end; *) InitFilterConstants; end; procedure TmotionCloud.AdjustLogGaborParams(var r0,sr0,ss:float); var Degree: integer; Poly : TNCompVector; InitGuess : TNcomplex; Tol : Float; MaxIter : integer; NumRoots : integer; Roots : TNCompVector; yRoots : TNCompVector; Iter : TNIntVector; Error : byte; stR:string; i,i0:integer; GoodRoot: double; Const Eps=1E-10; begin Degree:=8; Poly[0]:=Doublecomp(-sr0/sqr(r0),0); // Poly[1]:=Doublecomp(0,0); Poly[2]:=Doublecomp(1,0); Poly[3]:=Doublecomp(0,0); Poly[4]:=Doublecomp(3,0); Poly[5]:=Doublecomp(0,0); Poly[6]:=Doublecomp(3,0); Poly[7]:=Doublecomp(0,0); Poly[8]:=Doublecomp(1,0); fillchar(InitGuess,sizeof(InitGuess),0); Tol:= 1e-6; MaxIter:=1000; Laguerre( Degree, Poly, InitGuess, Tol, MaxIter, NumRoots, Roots, yRoots, Iter, Error); { stR:='NumRoots= '+Istr(NumRoots)+' Roots= '; for i:=0 to 8 do stR:= stR+ Estr(Roots[i].x,3)+' '+Estr(Roots[i].y,3)+crlf; stR:=stR+crlf +' error= '+Istr(error); messageCentral(stR); } // ranger la racine réelle positive dans sr0 // dans r0, ranger r0*(1+sqr(sr0)) i0:=-1; for i:=1 to 8 do if (abs(Roots[i].y)<Eps) and (Roots[i].x>0) then i0:=i; if (i0<0) or (error<>0) then begin messageCentral('Error AdjustLogGaborParams'); exit; end; sr0:=Roots[i0].x; r0:= r0*(1+sqr(sr0)); ss:=ss/r0; end; procedure TmotionCloud.InstallLogGaborFilter( ss ,r0, sr0, stheta0: float); var x,y,r,theta: float; i,j:integer; fN: float; Const eps=1E-6; begin //ss:=1/ss; AdjustLogGaborParams(r0,sr0,ss); paramAR(ss); for i:=0 to nx div 2 do for j:=0 to ny div 2 do begin x:= i; y:= j; r:= sqrt(sqr(x)+sqr(y))+Eps; theta:= arctan2(y,x){-theta0}; filter[i+j*nx]:= exp( cos(2*theta)/stheta0 ) * exp(-1/2*sqr(ln(r/r0)) /ln(1+sqr(sr0))) * power(r0/r,3)*ss*r; if i>0 then filter[(Nx-i) +j*Nx]:= filter[i +j*Nx]; end; for i:=0 to nx -1 do for j:=1 to ny div 2 do filter[i +(Ny-j)*Nx]:= filter[i +j*Nx]; fN:=0; for i:=0 to nx-1 do for j:=0 to ny-1 do begin if i>=nx div 2 then x:= nx-i else x:= i; if j>=ny div 2 then y:= ny-j else y:= j; r:= sqrt(sqr(x)+sqr(y))+Eps; if (x>0) or (y>0) then fN:= fN + filter[i+j*nx]/(4*power(ss*r,3)); end; for i:=0 to nx*ny-1 do filter[i]:= sqrt(filter[i]*nx*ny/dtAR/fN); end; procedure TmotionCloud.InstallMaternFilter( ss, eta, alpha: float); var x,y: float; i,j:integer; Const theta0=0; begin paramAR(ss); for i:=0 to nx-1 do for j:=0 to ny-1 do begin x:= i; if i>nx div 2 then x:= x- nx/2; y:= j; if j> ny div 2 then y:= y- ny/2; filter[i+j*nx] := 1/power(2*pi/Nx+(power(cos(theta0),2)+eta*power(sin(theta0),2))*x*x +(eta*power(cos(theta0),2)+power(sin(theta0),2))*y*y +2*(eta-1)*cos(theta0)*sin(theta0)*x*y, alpha/2); end; InitFilterConstants; end; (* Jonathan: la nouvelle fonction paramAR renvoit les listes a, b et c utilisées dans autoreg attention il y a un argument en plus "dt" que je n'ai pas répercuté ailleurs ("dt" est un pas de temps") *) procedure TmotionCloud.paramAR(ss: float); var x,y,r: float; i,j:integer; min,max:double; Const eps=1E-12; begin //ss:=1/ss; for i:=0 to nx div 2 do for j:=0 to ny div 2 do begin x:= i; y:= j; r:= sqrt(sqr(x)+sqr(y))+Eps; a[i+j*nx] := 2-dtAR*2*ss*r-sqr(dtAR*ss*r); b[i+j*nx] := -1+dtAR*2*ss*r; c[i+j*nx] := 50*sqr(dtAR); if i>0 then begin a[(Nx-i) +j*Nx]:= a[i +j*Nx]; b[(Nx-i) +j*Nx]:= b[i +j*Nx]; c[(Nx-i) +j*Nx]:= c[i +j*Nx]; end; end; for i:=0 to nx -1 do for j:=1 to ny div 2 do begin a[i +(Ny-j)*Nx]:= a[i +j*Nx]; b[i +(Ny-j)*Nx]:= b[i +j*Nx]; c[i +(Ny-j)*Nx]:= c[i +j*Nx]; end; { min:=0; max:=0; for i:=0 to nx*ny-1 do begin if a[i]<min then min:=a[i]; if a[i]>max then max:=a[i]; if b[i]<min then min:=b[i]; if b[i]>max then max:=b[i]; if c[i]<min then min:=c[i]; if c[i]>max then max:=c[i]; end; messageCentral('min='+Estr(min,9)+crlf+'max='+Estr(max,9)) ; } end; procedure RandGauss64(noise: PDouble; nb: integer; mu,sigma: double; Seed: longword); var state: pointer; stateSize: integer; begin ippsRandGaussGetSize_64f( @StateSize); state:= ippsMalloc_8u(stateSize); ippsRandGaussInit_64f(State, mu, sigma, seed); // Avec cette version , on perd l'état du générateur ippsRandGauss_64f(noise, nb, State); // Il faudrait donc sortir state ippsFree(state); end; procedure TmotionCloud.ComputeNoise(fftNoise: PtabDoubleComp ;filter: PtabDouble); var i:integer; Noise: PtabDouble; res:integer; dim:array[1..2] of integer; Hdfti: pointer; w:float; begin mkltest; ippstest; getmem( Noise, nx*ny * sizeof(Double)); RandGauss64(PDouble(noise),Nx*Ny,mu,sigma, Seed); //noise = random en complexes res:= ippsRealToCplx_64f(PDouble(noise),nil, PDoubleComp(fftNoise) ,nx*ny); // Calculer la DFT de fftNoise dim[1]:=Nx; dim[2]:=Ny; res:=DftiCreateDescriptor(Hdfti,dfti_Double, dfti_complex ,2, @Dim); if res<>0 then exit; res:= DftiSetValueI(Hdfti, DFTI_FORWARD_DOMAIN, DFTI_COMPLEX); res:=DftiCommitDescriptor(Hdfti); res:=DftiComputeForward1(hdfti,fftNoise); DftiFreeDescriptor(hdfti); // multiplier fftNoise par filter { for i:=0 to Nx*Ny-1 do begin fftNoise^[i].x:= fftNoise^[i].x* filter^[i]; fftNoise^[i].y:= fftNoise^[i].y* filter^[i]; end; } // On garde la transformée de Fourier filtrée freemem(Noise); // Pas le bruit initial ippsEnd; mklEnd; end; constructor TmotionCloud.create; begin inherited; Nx:=256; Ny:=256; DxF:=1; x0F:=128; DyF:=1; y0F:=128; mu:=0; sigma:=1; end; destructor TmotionCloud.destroy; begin done; inherited; end; procedure TmotionCloud.done; begin Finit:=false; FinitNoise:=false; freemem(LastFrame); LastFrame:=nil; freemem(fftnoise); fftnoise:=nil; freemem(filter); filter := nil; freemem(a); a := nil; freemem(b); b := nil; freemem(c); c := nil; freemem(Xn0); Xn0 := nil; freemem(Xn1); Xn1 := nil; freemem(Xn2); Xn2 := nil; end; procedure TmotionCloud.getFrame(mat: Tmatrix); var i,j:integer; res:integer; dim:array[1..2] of integer; Hdfti: pointer; w:float; begin if not Finit then sortieErreur('TmotionCloud : TmotionCloud is not initialized'); if not FinitNoise then initNoise; ComputeNoise(fftnoise, filter); Autoreg; dim[1]:=Nx; dim[2]:=Ny; res:=DftiCreateDescriptor(Hdfti,dfti_Double, dfti_complex ,2, @Dim); if res<>0 then exit; res:= DftiSetValueI(Hdfti, DFTI_FORWARD_DOMAIN, DFTI_COMPLEX); w:= 1/( Nx*Ny); res:=DftiSetValueS(hdfti,DFTI_BACKWARD_SCALE,w); res:=DftiCommitDescriptor(Hdfti); res:=DftiComputeBackward1(hdfti,Xn2); DftiFreeDescriptor(hdfti); // La partie réelle donne LastFrame ippsReal_64fc(PDoubleComp(Xn2),PDouble(LastFrame),Nx*Ny); mat.initTemp(0,Nx-1,0,Ny-1,g_single); for j:=0 to Ny-1 do for i:=0 to Nx-1 do mat[i,j]:= LastFrame^[i+Nx*j]; end; procedure TmotionCloud.getFilter(mat: Tmatrix); var i,j:integer; begin if not Finit then sortieErreur('TmotionCloud.getFilter : TmotionCloud is not initialized'); mat.initTemp(0,Nx-1,0,Ny-1,g_single); for j:=0 to Ny-1 do for i:=0 to Nx-1 do mat[i,j]:= filter^[i+Nx*j]; //mat[i,j]:= c^[i+Nx*j]; end; procedure TmotionCloud.InstallFilter(var mat: Tmatrix); var i,j:integer; begin if not Finit then sortieErreur('TmotionCloud.InstallFilter : TmotionCloud is not initialized'); if (mat.Icount<>Nx) or (mat.Jcount<>Ny) then sortieErreur('TmotionCloud.InstallFilter : matrix with bad size'); for i:=0 to Nx-1 do for j:=0 to Ny-1 do filter^[i+Nx*j]:=mat[mat.Istart+i,mat.Jstart+j]; InitFilterConstants; end; procedure TmotionCloud.Init( Nx1,Ny1:integer;seed1:integer; const Fmem:boolean=true); begin done; Finit:=true; FinitNoise:=false; Nx:= Nx1; Ny:= Ny1; seed:=seed1; getmem(filter,nx*ny*sizeof(Double)); getmem(a,nx*ny*sizeof(Double)); getmem(b,nx*ny*sizeof(Double)); getmem(c,nx*ny*sizeof(Double)); if Fmem then begin getmem(LastFrame,nx*ny*sizeof(Double)); getmem(fftNoise,nx*ny*sizeof(TDoubleComp)); getmem(Xn0,nx*ny*sizeof(TDoubleComp)); getmem(Xn1,nx*ny*sizeof(TDoubleComp)); getmem(Xn2,nx*ny*sizeof(TDoubleComp)); fillchar(Xn0^,nx*ny*sizeof(TDoubleComp),0); fillchar(Xn1^,nx*ny*sizeof(TDoubleComp),0); end; DxF:=1; x0F:=Nx1/2; DyF:=1; y0F:=Ny1/2; end; procedure TmotionCloud.InitFilterConstants; var i:integer; wm,wstd, wnorm: Double; begin ippsSqrt_64f_I(PDouble(filter),Nx*Ny); //ippsNorm_L2(PDouble(filter),Nx*Ny,@wnorm); //ippsMulC(1/wnorm, PDouble(filter),Nx*Ny); ippsStdDev_64f(PDouble(filter),Nx*Ny,@wstd); if wstd>0 then for i:=0 to Nx*Ny-1 do begin filter[i]:= filter[i]/wstd; end; end; procedure TmotionCloud.InitNoise; var i,j:integer; begin FinitNoise:=true; //ComputeNoise(Xn1, filter); //ComputeNoise(Xn0, filter); for j:=0 to 499 do begin ComputeNoise(fftnoise,filter); Autoreg; end; end; procedure TmotionCloud.Autoreg; var i:integer; begin for i:=0 to nx*ny-1 do begin Xn2[i].x := a[i]*Xn1[i].x + b[i]*Xn0[i].x + c[i]* fftnoise[i].x; Xn2[i].y := a[i]*Xn1[i].y + b[i]*Xn0[i].y + c[i]* fftnoise[i].y; end; if (DxF<>1) or (x0F<>Nx/2) or (DyF<>1) or (y0F<>Ny/2) then begin { expand(Xn1,Xn0,DxF, x0F *(1-DxF) ,DyF,y0F *(1-DyF)); expand(Xn2,Xn1,DxF, x0F *(1-DxF) ,DyF,y0F *(1-DyF)); } end else begin move(Xn1^,Xn0^,nx*ny*sizeof(TDoubleComp)); move(Xn2^,Xn1^,nx*ny*sizeof(TDoubleComp)); end; { ippsMulC( PDouble(@Xn1[0]), a, PDouble(@Xn2[0]), Nx*Ny); ippsMulC( b, PDouble(@Xn0[0]),Nx*Ny); ippsAdd( PDouble(@Xn0[0]), PDouble(@Xn2[0]), Nx*Ny); ippsAdd( PDouble(@noise[0]), PDouble(@Xn2[0]), Nx*Ny); move(Xn1[0], Xn0[0], Nx*Ny*sizeof(Double)); move(Xn2[0], Xn1[0], Nx*Ny*sizeof(Double)); } end; class function TmotionCloud.STMClassName: AnsiString; begin result:='MotionCloud'; end; procedure TmotionCloud.expand(src, dest: PtabDouble; Dx, x0, Dy, y0: float); var srcSize: IppiSize; srcROI,dstROI:IppiRect; pBuffer: pointer; size:integer; begin (* A refaire pour ippi17 srcSize.width:= Ny*8; srcSize.height:=Nx*8; with srcROI do begin x:=0; y:=0; width:=Ny; height:=Nx; end; with dstROI do begin x:=0; y:=0; width:= Ny; height:=Nx; end; // sizes in bytes // steps in bytes // inverser X et Y à tous les niveaux ippitest; size:=0; if ippiResizeGetBufSize(srcROI,dstROI, 1 , IPPI_INTER_LINEAR, Size)=0 then try getmem(pBuffer,size*8); ippiResizeSqrPixel_32f_C1R( Src, srcSize, Ny*8, srcROI, Dest, Ny*8, dstROI, Dy, Dx, y0, x0, IPPI_INTER_LINEAR, pBuffer); finally freemem(pBuffer); end; ippiEnd; *) end; {************************************************ STM functions *********************************************************} procedure proTmotionCloud_Create(var pu:typeUO); begin createPgObject('',pu,TmotionCloud); end; procedure proTmotionCloud_Init(dt: float;Nsample1:integer; Nx1,Ny1: integer; seed: longword;var pu:typeUO); begin verifierObjet(pu); with TmotionCloud(pu) do begin dtAR:=dt; Nsample:=Nsample1; init(Nx1,Ny1, seed); end; end; procedure proTmotionCloud_InstallGaborFilter( ss, r0, sr0, stheta0: float; var pu:typeUO); begin verifierObjet(pu); with TmotionCloud(pu) do begin InstallLogGaborFilter( ss, r0, sr0, stheta0); end; end; procedure proTmotionCloud_InstallMaternFilter( ss, eta, alpha: float; var pu:typeUO); begin verifierObjet(pu); with TmotionCloud(pu) do begin InstallMaternFilter( ss, eta, alpha); end; end; procedure proTmotionCloud_done(var pu:typeUO); begin verifierObjet(pu); with TmotionCloud(pu) do done; end; procedure proTmotionCloud_getFrame(var mat: Tmatrix; var pu:typeUO); begin verifierObjet(pu); verifierMatrice(mat); with TmotionCloud(pu) do getFrame(mat); end; procedure proTmotionCloud_getFilter(var mat: Tmatrix;var pu:typeUO); begin verifierObjet(pu); verifierMatrice(mat); with TmotionCloud(pu) do getFilter(mat); end; procedure proTmotionCloud_InstallFilter(var mat: Tmatrix;var pu:typeUO); begin verifierObjet(pu); verifierMatrice(mat); with TmotionCloud(pu) do begin installFilter(mat); end; end; procedure proTmotionCloud_SetExpansion(DxF1,x0F1,DyF1,y0F1:float;var pu:typeUO); begin verifierObjet(pu); with TmotionCloud(pu) do begin DxF := DxF1; x0F := x0F1; DyF := DyF1; y0F := y0F1; end; end; end. Initialization registerObject(TmotionCloud,sys); end.
unit ibSHDDLWizardCustomFrm; interface uses SHDesignIntf, ibSHDesignIntf, ibSHComponentFrm, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, SynEdit, pSHSynEdit; type TibSHDDLWizardCustomForm = class(TibBTComponentForm, ISHDDLWizard) private { Private declarations } FDBObjectIntf: IibSHDBObject; FDBState: TSHDBComponentState; FDDLInfoIntf: IibSHDDLInfo; FDDLFormIntf: IibSHDDLForm; FDDLGenerator: TComponent; FDDLGeneratorIntf: IibSHDDLGenerator; FTMPComponent: TComponent; FTMPObjectIntf: IibSHDBObject; FEditorDescr: TpSHSynEdit; FOutDDL: TStrings; procedure CreateOutputDDL; protected { Protected declarations } procedure DoOnBeforeModalClose(Sender: TObject; var ModalResult: TModalResult; var Action: TCloseAction); override; procedure DoOnAfterModalClose(Sender: TObject; ModalResult: TModalResult); override; procedure SetTMPDefinitions; virtual; public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; procedure InitPageCtrl(APageCtrl: TPageControl); procedure InitDescrEditor(AEditor: TpSHSynEdit; ARealDescr: Boolean = True); function NormalizeCaption(ACaption: string): string; function IsKeyword(const S: string): Boolean; property DBObject: IibSHDBObject read FDBObjectIntf; property DBState: TSHDBComponentState read FDBState; property DDLInfo: IibSHDDLInfo read FDDLInfoIntf; property DDLForm: IibSHDDLForm read FDDLFormIntf; property DDLGenerator: IibSHDDLGenerator read FDDLGeneratorIntf; property TMPComponent: TComponent read FTMPComponent; property TMPObject: IibSHDBObject read FTMPObjectIntf; property EditorDescr: TpSHSynEdit read FEditorDescr; property OutDDL: TStrings read FOutDDL; end; implementation uses ibSHValues; { TibSHDDLWizardCustomForm } constructor TibSHDDLWizardCustomForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); var vComponentClass: TSHComponentClass; S: string; begin FOutDDL := TStringList.Create; inherited Create(AOwner, AParent, AComponent, ACallString); Supports(Component, IibSHDBObject, FDBObjectIntf); Supports(Component, IibSHDDLInfo, FDDLInfoIntf); Supports(Designer.CurrentComponentForm, IibSHDDLForm, FDDLFormIntf); FDBState := DBObject.State; // // Установка Caption диалога // case DBObject.State of csCreate: S := 'CREATE DDL'; csAlter: S := 'ALTER DDL'; csDrop: S := 'DROP DDL'; csRecreate: S := 'RECREATE DDL'; end; Caption := Format('%s [%s] \ %s', [AnsiUpperCase(GUIDToName(Component.ClassIID)), Component.Caption, S]); // // Создание DDL генератора // vComponentClass := Designer.GetComponent(IibSHDDLGenerator); if Assigned(vComponentClass) then begin FDDLGenerator := vComponentClass.Create(nil); Supports(FDDLGenerator, IibSHDDLGenerator, FDDLGeneratorIntf); end; Assert(DDLGenerator <> nil, 'DDLGenerator = nil'); // // Создание TMP компонента для генерации с него искомого DDL // vComponentClass := Designer.GetComponent(Component.ClassIID); if Assigned(vComponentClass) then begin FTMPComponent := vComponentClass.Create(nil); Supports(FTMPComponent, IibSHDBObject, FTMPObjectIntf); end; Assert(TMPObject <> nil, 'TMPObject = nil'); // // Копирование необходимых свойств из DBObject в TMPObject // TMPObject.OwnerIID := DBObject.OwnerIID; TMPObject.Caption := DBObject.Caption; TMPObject.ObjectName := DBObject.ObjectName; TMPObject.State := DBObject.State; end; destructor TibSHDDLWizardCustomForm.Destroy; begin FOutDDL.Free; FDBObjectIntf := nil; FDDLInfoIntf := nil; FDDLFormIntf := nil; FDDLGeneratorIntf := nil; FDDLGenerator.Free; FTMPObjectIntf := nil; FTMPComponent.Free; inherited Destroy; end; procedure TibSHDDLWizardCustomForm.InitPageCtrl(APageCtrl: TPageControl); begin PageCtrl := APageCtrl; PageCtrl.ActivePageIndex := 0; PageCtrl.TabStop := False; PageCtrl.HotTrack := True; PageCtrl.Images := Designer.ImageList; PageCtrl.Pages[0].ImageIndex := Designer.GetImageIndex(DBObject.ClassIID); PageCtrl.Pages[1].ImageIndex := -1; Flat := True; PageCtrl.Pages[1].TabVisible := (DBState = csCreate) and (Component.Tag = 0); end; procedure TibSHDDLWizardCustomForm.InitDescrEditor(AEditor: TpSHSynEdit; ARealDescr: Boolean = True); begin AEditor.Lines.Clear; AEditor.Highlighter := nil; // Принудительная установка фонта AEditor.Font.Charset := 1; AEditor.Font.Color := clWindowText; AEditor.Font.Height := -13; AEditor.Font.Name := 'Courier New'; AEditor.Font.Pitch := fpDefault; AEditor.Font.Size := 10; AEditor.Font.Style := []; if ARealDescr then begin FEditorDescr := AEditor; FEditorDescr.Lines.AddStrings(DBObject.Description); end; end; function TibSHDDLWizardCustomForm.NormalizeCaption(ACaption: string): string; var vCodeNormalizer: IibSHCodeNormalizer; begin Result := ACaption; if Supports(Designer.GetDemon(IibSHCodeNormalizer), IibSHCodeNormalizer, vCodeNormalizer) then Result := vCodeNormalizer.InputValueToMetadata(DBObject.BTCLDatabase, Result); end; function TibSHDDLWizardCustomForm.IsKeyword(const S: string): Boolean; var vCodeNormalizer: IibSHCodeNormalizer; begin Result := Supports(Designer.GetDemon(IibSHCodeNormalizer), IibSHCodeNormalizer, vCodeNormalizer); if Result then Result := vCodeNormalizer.IsKeyword(DBObject.BTCLDatabase, S); end; procedure TibSHDDLWizardCustomForm.DoOnBeforeModalClose(Sender: TObject; var ModalResult: TModalResult; var Action: TCloseAction); begin // if ModalResult <> mrOK then // begin // if DBObject.Embedded then // if (DDLForm as ISHRunCommands).CanPause then (DDLForm as ISHRunCommands).Pause; // end else // CreateOutputDDL; end; procedure TibSHDDLWizardCustomForm.DoOnAfterModalClose(Sender: TObject; ModalResult: TModalResult); begin if ModalResult = mrOK then CreateOutputDDL; end; procedure TibSHDDLWizardCustomForm.SetTMPDefinitions; begin // Empty end; procedure TibSHDDLWizardCustomForm.CreateOutputDDL; begin OutDDL.Clear; // // Для RECREATE предварительно получаем DROP DDL из текущего объекта // // if DBState = csRecreate then // begin // try // OutDDL.Add('/* Delete OLD object -------------------------------------------------------- */'); // DBObject.State := csDrop; // DDLGenerator.UseFakeValues := False; // Designer.TextToStrings(DDLGenerator.GetDDLText(DBObject), OutDDL); // OutDDL.Add(''); // OutDDL.Add('/* Create NEW object -------------------------------------------------------- */'); // finally // DBObject.State := DBState; // DDLGenerator.UseFakeValues := True; // end; // end; // // Заполнение значениями свойств TMPObject (virtual) для генерации DDL // SetTMPDefinitions; // // Если RECREATE, то отдельно получаем CREATE DDL // if (DBState = csCreate) or (DBState = csRecreate) then begin try // TMPObject.State := csCreate; DDLGenerator.UseFakeValues := False; Designer.TextToStrings(DDLGenerator.GetDDLText(TMPObject), OutDDL); finally DDLGenerator.UseFakeValues := True; // TMPObject.State := DBState; end; end; if DBState = csAlter then Designer.TextToStrings(DDLGenerator.GetDDLText(TMPObject), OutDDL); if Assigned(DDLInfo) then begin DDLInfo.DDL.Clear; DDLInfo.DDL.AddStrings(OutDDL); end; case Component.Tag of 0: DDLForm.ShowDDLText; // DBObjects 100: DDLForm.DDLText.Assign(OutDDL); // SQLEditor // 200: begin // SQLPlayer // DDLForm.DDLText.Add(''); // DDLForm.DDLText.AddStrings(OutDDL); // end; end; // // Установка Descriptions // if Assigned(EditorDescr) and EditorDescr.Modified then DBObject.Description.Assign(EditorDescr.Lines); end; end.
unit uZipFiles; interface uses VCLZip; type TParent = class private FZip : TVCLZip; FZipFileName : String; public property ZipFileName : String read FZipFileName write FZipFileName; Constructor Create; Destructor Destroy; override; end; TZip = class(TParent) private FRecurse : Boolean; //Recurse directories FSavePath : Boolean; //Keep path information FPackLevel : Integer; //Highest level of compression = 9 procedure SetPackLevel(PackLevel : Integer); public property Recurse : Boolean read FRecurse write FRecurse; property SavePath : Boolean read FSavePath write FSavePath; property PackLevel : Integer read FPackLevel write SetPackLevel; procedure AddFile(sFileName:String); procedure DeleteFile(sFileName:String); function Zip : integer; Constructor Create; Destructor Destroy; override; end; implementation {--------- TZip ---------} function TZip.Zip : integer; begin Result := -100; if FZip.FilesList.Count > 0 then begin //Properties FZip.Recurse := FRecurse; FZip.StorePaths := FSavePath; FZip.PackLevel := FPackLevel; FZip.ZipName := FZipFileName; FZip.ZipAction := zaReplace; Result := FZip.Zip; end; end; procedure TZip.DeleteFile(sFileName:String); var index : integer; begin index := FZip.FilesList.IndexOf(sFileName); if index <> -1 then FZip.FilesList.Delete(index); end; procedure TZip.AddFile(sFileName:String); begin DeleteFile(sFileName); FZip.FilesList.Add(sFileName); end; procedure TZip.SetPackLevel(PackLevel : Integer); begin if not (PackLevel in [0..9]) then FPackLevel := 9 //Higest else FPackLevel := PackLevel; end; Constructor TZip.Create; begin inherited Create; FRecurse := False; FSavePath := False; FPackLevel := 9; //Higest; end; Destructor TZip.Destroy; begin inherited Destroy; end; {---------- TParent -----------} Constructor TParent.Create; begin inherited Create; FZip := TVCLZip.Create(nil); end; Destructor TParent.Destroy; begin FZip.Free; inherited Destroy; end; end.
unit feedFusion; interface uses eaterReg; type TFusionFeedProcessor=class(TFeedProcessor) private FURLPrefix:WideString; public function Determine(Store: IFeedStore; const FeedURL: WideString; var FeedData: WideString; const FeedDataType: WideString): Boolean; override; procedure ProcessFeed(Handler: IFeedHandler; const FeedData: WideString); override; end; implementation uses eaterSanitize, jsonDoc, Variants, eaterUtils; { TFusionFeedProcessor } function TFusionFeedProcessor.Determine(Store: IFeedStore; const FeedURL: WideString; var FeedData: WideString; const FeedDataType: WideString): Boolean; var i,l:integer; begin Result:=Store.CheckLastLoadResultPrefix('Fusion') and FindPrefixAndCrop(FeedData,'Fusion.globalContent='); if Result then begin l:=Length(FeedURL); i:=1; while (i<=l) and (FeedURL[i]<>':') do inc(i); inc(i);// if (i<=l) and (FeedURL[i]='/') then inc(i); if (i<=l) and (FeedURL[i]='/') then inc(i); while (i<=l) and (FeedURL[i]<>'/') do inc(i); FURLPrefix:=Copy(FeedURL,1,i-1); end; end; procedure TFusionFeedProcessor.ProcessFeed(Handler: IFeedHandler; const FeedData: WideString); var jnodes:IJSONDocArray; jdoc,jd1,je1,jn0,jn1:IJSONDocument; jd0,je0,jw0:IJSONEnumerator; p1,p2,itemid,itemurl:string; pubDate:TDateTime; title,content:WideString; v,vNodes:Variant; inode:integer; begin jnodes:=JSONDocArray; jd1:=JSON; jdoc:=JSON( ['result',JSON(['articles',jnodes,'section',jd1]) ,'arcResult',JSON(['articles',jnodes]) ,'sophiResult',JSON(['articles',jnodes]) ]); try jdoc.Parse(FeedData); except on EJSONDecodeException do ;//ignore "data past end" end; Handler.UpdateFeedName(VarToStr(jd1['title'])); jn0:=JSON; p1:=''; p2:=''; if jnodes.Count<>0 then for inode:=0 to jnodes.Count-1 do begin jnodes.LoadItem(inode,jn0); itemid:=jn0['id']; itemurl:=VarToStr(jn0['canonical_url']); try pubDate:=ConvDate1(VarToStr(jn0['display_time']));//published_time? except pubDate:=UtcNow; end; if (itemurl<>'') and (Handler.CheckNewPost(itemid,itemurl,pubDate)) then begin title:=SanitizeTitle(jn0['title']); v:=jn0['subtitle']; if not(VarIsNull(v)) then title:=title+' '#$2014' '+v; content:=HTMLEncode(jn0['description']); jn1:=JSON(jn0['thumbnail']); if jn1<>nil then content:='<img class="postthumb" referrerpolicy="no-referrer'+ '" src="'+HTMLEncodeQ(jn1['url'])+ '" alt="'+HTMLEncodeQ(VarToStr(jn1['caption']))+ '" /><br />'#13#10+content; Handler.RegisterPost(title,content); end; end else begin content:=FeedData; if FindPrefixAndCrop(content,'Fusion.contentCache=') then begin jdoc:=JSON; try jdoc.Parse(content); except on EJSONDecodeException do ;//ignore "data past end" end; jd0:=JSONEnum(jdoc); while jd0.Next do if jd0.Key='site-service-hierarchy' then begin //first of site-service-content? jd1:=JSON(jd0.Value);//jd1:=JSON(jdoc['site-service-hierarchy']); if jd1<>nil then jd1:=JSON(jd1['{"hierarchy":"default"}']); if jd1<>nil then jd1:=JSON(jd1['data']); if jd1<>nil then handler.UpdateFeedName(jd1['name']); end else if Copy(jd0.Key,1,5)='site-' then //ignore else begin je0:=JSONEnum(JSON(jd0.Value)); while je0.Next do begin je1:=JSON(je0.Value); if je1<>nil then je1:=JSON(je1['data']); if je1=nil then vNodes:=Null else vNodes:=je1['content_elements']; if not VarIsNull(vNodes) then for inode:=VarArrayLowBound(vNodes,1) to VarArrayHighBound(vNodes,1) do begin jn0:=JSON(vNodes[inode]); itemid:=jn0['_id']; title:='';//see below if VarIsNull(jn0['canonical_url']) then begin jw0:=JSONEnum(jn0['websites']); if jw0.Next then begin itemurl:=JSON(jw0.Value)['website_url']; end else itemurl:='';//raise? jw0:=nil; if itemurl='' then begin itemurl:=VarToStr(JSON(JSON(jn0['taxonomy'])['primary_section'])['_id']); title:=#$D83D#$DD17#$2009; end; if itemurl<>'' then itemurl:=FURLPrefix+itemurl; end else itemurl:=FURLPrefix+jn0['canonical_url']; try p1:=VarToStr(jn0['display_date']); if p1='' then p1:=VarToStr(jn0['publish_date']); if p1='' then p1:=VarToStr(jn0['created_date']); if p1='' then pubDate:=UtcNow else pubDate:=ConvDate1(p1); except pubDate:=UtcNow; end; if Handler.CheckNewPost(itemid,itemurl,pubDate) then begin jn1:=JSON(jn0['headlines']); if jn1=nil then title:=title+SanitizeTitle(VarToStr(jn0['headline']))//fallback else title:=title+SanitizeTitle(VarToStr(jn1['basic'])); jn1:=JSON(jn0['subheadlines']); if jn1=nil then content:=HTMLEncode(VarToStr(jn0['subheadline']))//fallback else content:=HTMLEncode(VarToStr(jn1['basic'])); //TODO: labels -> Handler.PostTags() jn1:=JSON(jn0['promo_items']); if jn1<>nil then jn1:=JSON(jn1['basic']); if jn1<>nil then content:='<img class="postthumb" referrerpolicy="no-referrer'+ '" src="'+HTMLEncodeQ(jn1['url'])+ '" alt="'+HTMLEncodeQ(VarToStr(jn1['caption']))+ '" /><br />'#13#10+content; Handler.RegisterPost(title,content); end; end; end; je0:=nil; end; jd0:=nil; end; end; Handler.ReportSuccess('Fusion'); end; initialization RegisterFeedProcessor(TFusionFeedProcessor.Create); end.
unit impressao; { Função: Impressão de Pré Venda Autor: Daniel Cunha Data: 10/06/2014 Funcionamento: Bematech : Utiliza a DLL MP2032.dll Impressora Padrão : Utiliza CharPrinter com comandos ESC/POS (Impressora padrão do Windows) 18-11-2014 > Iniciada a mudança para comandos unificados, assim fica mais facil a manutenção das impressoes; 19-12-2014 > Iniciada mudança de arq TXT para record; 23-02-2015 > [Fabio Luiz Franzini] Acerto nas variaveis de fachamento do caixa 25-02-2015 > [Daniel Brandão da Cunha] Criada a função para imprimir detalhe da sangria 19-08-2015 > [Daniel Brandão da Cunha] Retidado CNPJ e IE do Cabeçalho } interface uses declaracoes, DB, Forms, sysutils, controls, windows, CharPrinter; type THPortas = (hCOM1,hCOM2, hCOM3, hCOM4, hLPT1, hLPT2, hEthernet, hUSB); THImpressora = (hBematech, hElgin, hDaruma, hEpson, hDiebold, hMatricial, hImpPadrao); THModeloIMP = ( //Bematech // // // hMP20MI = 1, hMP20CI = 0, hMP20TH = 0, hMP2000CI = 0, hMP2000TH = 0, hMP2100TH = 0, hMP4000TH = 5, hMP4200TH = 7, hMP2500TH = 8, //Matricial hGenericText); THTipoImp = (hVenda, hRVenda, hConsignacao, hRecibo, hRRecibo, hCarne, hVendaCliente, hRVendaCliente, hPromissoria, hRpromissoria, hComanda); THDevice = record aImp : THImpressora; aMod : THModeloIMP; aPrt : THPortas; aIP : String; aTsk : THTipoImp; end; THCostumer = record aCod, aName, aAddr, aProv, aCPF, aRG, aType : String; end; THDadosCaixa = record aDinheiro, aCartao, aCheque, aSuprimento, aSangria : Double; end; THInformativoVendas = record aTDinheiro, aTCheque, aTCartao, aTCliente, aTDesconto, aTRecebido : Double; end; THTotais = record aCancelados, aVlrCancelados, aItmCancelados, aVlrItmCancelados : Double; end; var //para uso de imppadrao prn : TAdvancedPrinter; //Para organizar as variaveis foi criado o record device : THDevice; //para setar cliente client : THCostumer; //aux cupom aSubTotal :Double; //dados caixa aDinheiro, aCartao, aCheque, aSuprimento, aSangria : Double; //informativo de Venda aTDinheiro, aTCheque, aTCartao, aTCliente, aTDesconto, aTRecebido : Double; //Totais aCancelados, aVlrCancelados, aItmCancelados, aVlrItmCancelados : Double; {$REGION 'COMANDOS BASE'} function Bematech_Pequeno(aTexto : string):integer; function Bematech_Normal(aTexto : string):integer; function Bematech_Grande(aTexto : string):integer; procedure Prn_Pequeno(aTexto : String); procedure Prn_Normal(aTexto : String); procedure Prn_Grande(aTexto : String); procedure Prn_Comando(aTexto : String); //gaveta procedure AbreGaveta(impressora : THImpressora; modelo : THModeloIMP; porta : THPortas; ip : String);overload; procedure AbreGaveta(impressora, modelo, porta : integer; ip : String);overload; //Guilhotina procedure Guilhotina(corta : boolean); //comandos unificados procedure hPrintPequeno(aTexto : String); procedure hPrintNormal(aTexto : String); procedure hPrintGrande(aTexto : String); procedure hPrintComando(aTexto : String); procedure hPrintFechar(); procedure hAbregaveta(); procedure AvancaLinhas(linhas : integer); //Ativação procedure AtivaImpressora(impressora : THImpressora; modelo: THModeloIMP; porta : THPortas ; IP : String);overload; procedure AtivaImpressora(impressora : integer; modelo: integer; porta : integer; IP : String);overload ; //Zera Variaveis procedure zeraVariaveis(); {$endregion} {$REGION 'CONFIGURAÇAO'} function Bematech_lestatus():String; function RetornaStrPorta(porta : THPortas): String; function setImpressora(imp : integer) : THImpressora; function setModelo(modelo : integer) : THModeloIMP; function setPorta(porta : integer) : THPortas; function RetornaModelo(modelo : THModeloIMP):integer; procedure TesteImpressora(impressora, modelo, porta, avanco :Integer; ip : String); {$ENDREGION} {$REGION 'IMPRESSAO'} procedure ImpCabecalho(); procedure AdicionaItem (item, barras: String; qtde, unitario, total : Double); procedure RemoveItem (item, barras: String; qtde, unitario : Double); procedure ImprimeTipo (impressora : THImpressora; tipo : THTipoImp ;numeroimp, pdv : integer; data, hora, vendedor : String); procedure InformaCliente(Ficha, Cliente, Endereco, Bairro, Tipo : String);overload; procedure InformaCliente(Ficha : integer ; Cliente, CPF, RG, Endereco, Bairro, Tipo : String); overload ; {Manutenção Aqui} //Será retirado o tipo da impressao e passado para o tipo que iniciou Procedure FechaImpressao (tipo : THTipoImp ; Desconto, Acrescimo, Total, Recebido : Double; OBS: String); {Fim Manutencão } procedure IniciaImp(tipo : THTipoImp; numeroimp, pdv :integer; vendedor : String); procedure IniciaRImp(tipo : THTipoImp; numeroimp, pdv :integer; vendedor : String; data: Tdate; hora : TTime); procedure AdicionaParcela (parcela : integer; vecto : String ; valor : Double);overload; Procedure AdicionaParcela ( vecto : String ; valor : Double);overload; procedure DadosTemporarios(dados, campo, valor :String); procedure AdicionaForma (forma : String; valor : Double); procedure DetalheSangria( Data, Hora, Operador,Descricao : String; Valor : Double ); {$ENDREGION} {$REGION 'CODIGOS'} procedure ImprimeBarras(aCodigo : String); procedure ImprimeQR(aCodigo : String); {$ENDREGION} {$REGION 'IMPRESSOES OPERACIONAIS'} procedure ImpSangria(caixa : integer; supervisor, operador, descricao : String; valor : Double); procedure ImpSuprimento(caixa : integer; supervisor, operador, descricao : String; valor : Double); procedure ImpAbertura(caixa : integer; supervisor, operador : String; valor : Double); procedure CancelaCupom(caixa, cupom : integer; operador : String ; datahoravenda: TDateTime ;subtotal, desconto, total : Double); procedure ImpFechamento(caixa, controle : integer; supervisorab,supervisorf, operador : String; aData: TDate; aHora : TTime; valor, valorinformado : Double); procedure informaDadosCaixa(Dinheiro, Cheque, Cartao, Suprimento, Sangria : Double); procedure informaDadosVenda(TDinheiro, TCheque, TCartao, TCliente, TDesconto, TRecebido : Double); procedure informaTotais(Cancelados, VlrCancelados, ItmCancelados, VlrItmCancelados : Double); {$ENDREGION} implementation uses funcoes; function Bematech_Pequeno (aTexto : string):integer; begin if trim(atexto) <> '' then begin aTexto := aTexto + #13 + #10; Bematech_Pequeno := FormataTX(pchar(aTexto), 1, 0, 0, 0, 0); end; end; function Bematech_Normal (aTexto : string):integer; begin if trim( atexto ) <> '' then begin aTexto := aTexto + #13 + #10; Bematech_normal := FormataTX(pchar(aTexto), 2, 0, 0, 0, 0); end; end; function Bematech_Grande (aTexto : string): integer; begin if trim( atexto ) <> '' then begin aTexto := aTexto + #13 + #10; Bematech_grande := FormataTX(pchar(aTexto), 3, 0, 0, 1, 0); end; end; function Bematech_lestatus():String; var aStatus: integer; s_stporta: String; begin // ANÁLISE DO RETORNO DE STATUS DAS IMPRESSORAS FISCAIS case device.aPrt of hCOM1: s_stporta:='serial'; hCOM2: s_stporta:='serial'; hCOM3: s_stporta:='serial'; hCOM4: s_stporta:='serial'; hLPT1: s_stporta:='lpt'; hLPT2: s_stporta:='lpt'; hEthernet: s_stporta:='rede'; end; AtivaImpressora(device.aImp , device.aMod ,device.aPrt, device.aIP); aStatus := Le_Status(); //******************IMPRESSORAS MP 20 CI E MI - CONEXÃO SERIAL****************** if (device.aMod = hMP20MI) and (s_stporta='serial') then Begin if aStatus= 24 then Bematech_lestatus :='24 - ON LINE'; if aStatus= 0 then Bematech_lestatus :='0 - OFF LINE'; if aStatus= 32 then Bematech_lestatus :='32 - SEM PAPEL'; End; //****************************************************************************** //******************IMPRESSORAS MP 20 CI E MI - CONEXÃO PARALELA**************** if (device.aMod = hMP20MI) and (s_stporta='lpt') then Begin if aStatus= 144 then Bematech_lestatus :='144 - ON LINE'; if aStatus= 0 then Bematech_lestatus :='0 - OFF LINE OU IMP. SEM PAPEL'; End; //****************************************************************************** //******IMPRESSORAS MP 20 TH, 2000 CI 2000 TH 2100 TH - CONEXÃO SERIAL********** if (device.aMod=hMP20TH) and (s_stporta='serial') then Begin if aStatus= 0 then Bematech_lestatus :='0 - OFF LINE'; if aStatus= 24 then Bematech_lestatus :='24 - ON LINE OU POUCO PAPEL'; if aStatus= 32 then Bematech_lestatus :='32 - IMP. SEM PAPEL'; End; //****************************************************************************** //******IMPRESSORAS MP 20 TH, 2000 CI 2000 TH 2100 TH - CONEXÃO PARALELA******** if (device.aMod=hMP20TH) and (s_stporta='lpt') then Begin if aStatus= 79 then Bematech_lestatus :='79 - OFF LINE'; if aStatus= 144 then Bematech_lestatus :='144 - ON LINE OU POUCO PAPEL'; if aStatus= 32 then Bematech_lestatus :='32 - IMP. SEM PAPEL'; if aStatus= 0 then Bematech_lestatus :='0 - ERRO DE COMUNICAÇÃO'; End; //****************************************************************************** //******************IMPRESSORAS MP 4000 TH CONEXÃO PARALELA********************* if (device.aMod=hMP4000TH) and (s_stporta='lpt') then Begin if aStatus= 40 then Bematech_lestatus :='40 - IMP. OFF LINE/SEM COMUNICAÇÃO'; if aStatus= 24 then Bematech_lestatus :='24 - IMPRESSORA ON LINE'; if aStatus= 128 then Bematech_lestatus :='128 - IMP. SEM PAPEL'; if aStatus= 0 then Bematech_lestatus :='0 - POUCO PAPEL'; End; //****************************************************************************** //******************IMPRESSORAS MP 4000 TH CONEXÃO ETHERNET********************* if (device.aMod=hMP4000TH) and (s_stporta='rede') then Begin if aStatus= 24 then Bematech_lestatus :='24 - IMPRESSORA ON LINE'; if aStatus= 0 then Bematech_lestatus :='0 - IMP. OFF LINE/SEM COMUNICAÇÃO'; if aStatus= 32 then Bematech_lestatus :='32 - IMP. SEM PAPEL'; if aStatus= 24 then Bematech_lestatus :='24 - ON LINE - POUCO PAPEL'; End; //****************************************************************************** //******************IMPRESSORAS MP 4000 TH CONEXÃO SERIAL*********************** if (device.aMod=hMP4000TH) and (s_stporta='serial') then Begin if aStatus= 24 then Bematech_lestatus :='24 - IMPRESSORA ON LINE'; if aStatus= 0 then Bematech_lestatus :='0 - IMP. OFF LINE/SEM COMUNICAÇÃO'; if aStatus= 32 then Bematech_lestatus :='32 - IMP. SEM PAPEL'; if aStatus= 5 then Bematech_lestatus :='5 - ON LINE - POUCO PAPEL'; End; //****************************************************************************** //*********************IMPRESSORAS MP 4000 TH CONEXÃO USB*********************** if (device.aMod=hMP4000TH) and (s_stporta='serial') then Begin if aStatus= 24 then Bematech_lestatus :='24 - IMPRESSORA ON LINE'; if aStatus= 68 then Bematech_lestatus :='68 - IMP. OFF LINE/SEM COMUNICAÇÃO'; if aStatus= 32 then Bematech_lestatus :='32 - IMP. SEM PAPEL'; if aStatus= 24 then Bematech_lestatus :='24 - ON LINE - POUCO PAPEL'; End; //****************************************************************************** //*******************IMPRESSORAS MP 4200 TH CONEXÃO TODAS*********************** if (device.aMod=hMP4200TH) then Begin if aStatus= 24 then Bematech_lestatus :='24 - IMPRESSORA ON LINE'; if aStatus= 0 then Bematech_lestatus :='0 - IMP. OFF LINE/SEM COMUNICAÇÃO'; if aStatus= 32 then Bematech_lestatus :='32 - IMP. SEM PAPEL'; if aStatus= 5 then Bematech_lestatus :='5 - ON LINE - POUCO PAPEL'; if aStatus= 9 then Bematech_lestatus :='9 - TAMPA ABERTA'; End; //****************************************************************************** FechaPorta; end; procedure ImpCabecalho (); begin hPrintNormal(alinhaCentro(Length(LeIni('EMPRESA','LIN000'))) + LeIni('EMPRESA','LIN000')); hPrintNormal(alinhaCentro(Length(LeIni('EMPRESA','LIN001')+ ' '+ LeIni('EMPRESA','LIN002'))) + LeIni('EMPRESA','LIN001')+' ' +LeIni('EMPRESA','LIN002')); // hPrintNormal(alinhaCentro(Length(LeIni('EMPRESA','LIN002'))) + LeIni('EMPRESA','LIN002')); hPrintNormal(alinhaCentro(Length(LeIni('EMPRESA','LIN003')+ ' '+LeIni('EMPRESA','LIN005'))) + LeIni('EMPRESA','LIN003')+' '+ LeIni('EMPRESA','LIN005')); // hPrintNormal(alinhaCentro(Length(LeIni('EMPRESA','LIN005'))) + LeIni('EMPRESA','LIN005')); hPrintNormal( TracoDuplo(47)); end; Procedure AdicionaItem (item, barras: String; qtde, unitario, total : Double); var aLinha : String; begin aLinha := #18 + subs( alltrim( item ), 1, 47 ) + #$12 + ' ' + subs( barras, 1, 13 ) + #$12 + ' ' + FormatFloat('#,###0.000',qtde) + #$12 + ' ' + FormatFloat('#,##0.00',unitario) + #$12 + ' ' + FormatFloat('#,##0.00',RoundSemArredondar(unitario * qtde)); aSubTotal := aSubTotal + total;//(unitario * qtde); hPrintNormal( copy ( aLinha, 1, Length(aLinha))); end; Procedure RemoveItem (item, barras: String; qtde, unitario : Double); var aLinha : String; begin aLinha := #18 + subs( alltrim( item ), 1, 47 )+ #$12 + ' ' + subs( barras, 1, 13 )+ #$12 + ' -' + FormatFloat('#,###0.000',qtde)+ #$12 + ' -' + FormatFloat('#,##0.00',unitario)+ #$12 + ' ' + FormatFloat('#,##0.00',RoundSemArredondar(unitario * qtde)); aSubTotal := aSubTotal - (unitario * qtde); hPrintNormal( copy ( aLinha, 1, Length(aLinha))); end; function RetornaStrPorta(porta : THPortas): String; begin case porta of hCOM1: RetornaStrPorta := 'COM1' ; hCOM2: RetornaStrPorta := 'COM2' ; hCOM3: RetornaStrPorta := 'COM3' ; hCOM4: RetornaStrPorta := 'COM4' ; hLPT1: RetornaStrPorta := 'LPT1' ; hLPT2: RetornaStrPorta := 'LPT2' ; hEthernet: RetornaStrPorta := device.aIP ; hUSB: RetornaStrPorta := 'USB'; end; end; Procedure ImprimeTipo (impressora : THImpressora; tipo : THTipoImp ;numeroimp, pdv : integer; data, hora, vendedor : String); var Arq : TextFile; aLinha : String; begin case device.aTsk of hVenda:begin hPrintNormal('Num:' +IntToStr(numeroimp) + ' PDV:' + IntToStr(pdv) + ' Data:' + Trim(data) + ' ' + copy(hora,0,5)); if client.aName <> '' then hPrintNormal('Cliente:' + client.aName); // hPrintNormal('Data.....: ' + Trim(data) + ' Hora.: ' + hora ); if length(vendedor) > 0 then hPrintNormal('Vendedor.: ' + Trim(vendedor) ); hPrintNormal(Traco(47)); hPrintNormal('Descricao'); hPrintNormal(' Cod. Barras Qtd Unit. Total'); hPrintNormal(Traco(47)); end; hRVenda:begin hPrintNormal('Num:' +IntToStr(numeroimp) + ' PDV:' + IntToStr(pdv) + ' Data:' + Trim(data) + ' ' + copy(hora,0,5)); // hPrintNormal('Data.....: ' + Trim(data) + ' Hora.: ' + hora ); if length(vendedor) > 0 then hPrintNormal('Vendedor.: ' + Trim(vendedor) ); hPrintNormal(Traco(47)); hPrintNormal(alinhaCentro(Length('***REIMPRESSAO***'))+'***REIMPRESSAO***'); hPrintNormal(Traco(47)); hPrintNormal('Descricao'); hPrintNormal(' Cod. Barras Qtd Unit. Total'); hPrintNormal(Traco(47)); end; hVendaCliente:begin hPrintNormal('Num:' +IntToStr(numeroimp) + ' PDV:' + IntToStr(pdv) + ' Data:' + Trim(data) + ' ' + copy(hora,0,5)); // hPrintNormal('Data.....: ' + Trim(data) + ' Hora.: ' + hora ); if length(vendedor) > 0 then hPrintNormal('Vendedor.: ' + Trim(vendedor) ); hPrintNormal(Traco(47)); if client.aName <> '' then begin if client.aType = 'F' then begin hPrintNormal('Matricula:' + client.aCod); hPrintNormal('Funcionario..:' + client.aName); end else begin hPrintNormal('Codigo...:' + client.aCod); hPrintNormal('Cliente..:' + client.aName); end; if client.aCPF <> '' then hPrintNormal('CPF......:' + client.aCPF); if client.aRG <> '' then hPrintNormal('RG.......:' + client.aRG); hPrintNormal('Endereco.:' + client.aAddr); hPrintNormal('Bairro...:' + client.aProv); end; hPrintNormal(Traco(47)); hPrintNormal('Descricao'); hPrintNormal(' Cod. Barras Qtd Unit. Total'); hPrintNormal(Traco(47)); end; hRVendaCliente:begin hPrintNormal('Num:' +IntToStr(numeroimp) + ' PDV:' + IntToStr(pdv) + ' Data:' + Trim(data) + ' ' + copy(hora,0,5)); // hPrintNormal('Data.....: ' + Trim(data) + ' Hora.: ' + hora ); if length(vendedor) > 0 then hPrintNormal('Vendedor.: ' + Trim(vendedor) ); hPrintNormal(Traco(47)); hPrintNormal(alinhaCentro(Length('***REIMPRESSAO***'))+'***REIMPRESSAO***'); if client.aName <> '' then begin hPrintNormal(Traco(47)); hPrintNormal('Codigo...:' + client.aCod); if client.aType = 'F' then hPrintNormal('Funcionario..:' + client.aName) else hPrintNormal('Cliente..:' + client.aName); if client.aCPF <> '' then hPrintNormal('CPF......:' + client.aCPF); if client.aRG <> '' then hPrintNormal('RG.......:' + client.aRG); hPrintNormal('Endereco.:' + client.aAddr); hPrintNormal('Bairro...:' + client.aProv); end; hPrintNormal(Traco(47)); hPrintNormal('Descricao'); hPrintNormal(' Cod. Barras Qtd Unit. Total'); hPrintNormal(Traco(47)); end; hPromissoria:begin hPrintNormal('Num:' +IntToStr(numeroimp) + ' PDV:' + IntToStr(pdv) + ' Data:' + Trim(data) + ' ' + copy(hora,0,5)); // hPrintNormal('Data.....: ' + Trim(data) + ' Hora.: ' + hora ); if length(vendedor) > 0 then hPrintNormal('Vendedor.: ' + Trim(vendedor) ); hPrintNormal(Traco(47)); hPrintNormal(alinhaCentro(Length('***PRESTACOES***'))+ '***PRESTACOES***'); hPrintNormal('N Vencimento Valor'); if FileExists(ExtractFilePath(Application.ExeName)+'hparcelas.txt') then begin AssignFile(Arq, 'hparcelas.txt'); try Reset(Arq); except end; while not Eof(Arq) do begin Readln(Arq, aLinha); hPrintNormal ( copy ( aLinha, 1, Length(aLinha))); end; CloseFile(Arq); while FileExists('hparcelas.txt') do DeleteFile('hparcelas.txt'); end; hPrintNormal(Traco(47)); hPrintPequeno('No pagamento em atraso, sera cobrado multa de 2% e juros de '); hPrintPequeno(' 0,33% ao dia'); hPrintNormal(Traco(47)); hPrintNormal(alinhaCentro(Length('*NOTA PROMISSORIA*'))+ '*NOTA PROMISSORIA*'); hPrintNormal(Traco(47)); hPrintNormal('Vencimento em '+ LeIniTemp('PARCELAS','VECTO')); hPrintNormal('Valor em R$ '+ LeIniTemp('PARCELAS','TOTAL')); AvancaLinhas(1); hPrintPequeno( 'A ' +LeIniTemp('PARCELAS','VECTOEXT')); hPrintPequeno('Pagarei esta NOTA PROMISSORIA a : ' + LeIniTemp('EMPRESA','RAZAO')); hPrintPequeno('CNPJ: ' +LeIniTemp('EMPRESA','CNPJ') + ' ou a sua ordem,'); hPrintPequeno('em moeda corrente deste pais a quantia de'); hPrintPequeno( LeIniTemp('PARCELAS', 'TOTALEXT')); hPrintPequeno('Pagavel em ' + LeIniTemp('EMPRESA','CIDADEUF')); AvancaLinhas(1); hPrintPequeno(LeIniTemp('PARCELAS','DATAEXT')); AvancaLinhas(1); hPrintPequeno('Cod.: ' + LeIniTemp('CLIENTE','CODIGO')); hPrintPequeno('Nome.: ' + LeIniTemp('CLIENTE','NOME ')); if Length(Trim(LeIniTemp('CLIENTE','CPF'))) <= 14 then begin hPrintPequeno('CPF.: ' + LeIniTemp('CLIENTE','CPF')); hPrintPequeno('RG.: ' + LeIniTemp('CLIENTE','RG')); end else begin hPrintPequeno('CNPJ.: ' + LeIniTemp('CLIENTE','CPF')); hPrintPequeno('IE.: ' + LeIniTemp('CLIENTE','RG')); end; hPrintPequeno('Endereco.: ' + LeIniTemp('CLIENTE','END')); hPrintPequeno('Bairro.: ' + LeIniTemp('CLIENTE','BAIRRO')); hPrintPequeno('Cidade.: ' + LeIniTemp('CLIENTE','CCIDADEUF')); while FileExists('Temp.ini') do DeleteFile('Temp.ini'); end; hConsignacao:begin hPrintNormal(alinhaCentro(length('CONSIGNACAO')) + 'CONSIGNACAO'); hPrintNormal(Traco(47)); hPrintNormal('Consignacao.:' +IntToStr(numeroimp) + ' PDV : ' + IntToStr(pdv)); hPrintNormal('Data..... : ' + Trim(data) + ' Hora.: ' + hora ); if length(vendedor) > 0 then hPrintNormal('Vendedor.: ' + Trim(vendedor) ); hPrintNormal(Traco(47)); hPrintNormal('Descricao'); hPrintNormal(' Cod. Barras Qtd Unit. Total'); hPrintNormal(Traco(47)); end; hRecibo:begin hPrintNormal(alinhaCentro(length('RECIBO')) + 'RECIBO'); hPrintNormal(Traco(47)); hPrintNormal('Recibo Nr .:' +IntToStr(numeroimp) + ' PDV : ' + IntToStr(pdv)); hPrintNormal('Data..... : ' + Trim(data) + ' Hora.: ' + hora ); if length(vendedor) > 0 then hPrintNormal('Vendedor.: ' + Trim(vendedor) ); end; hRRecibo:begin hPrintNormal(alinhaCentro(length('REIMPRESSAO RECIBO')) + 'REIMPRESSAO RECIBO'); hPrintNormal(Traco(47)); hPrintNormal('Recibo Nr .:' +IntToStr(numeroimp) + ' PDV : ' + IntToStr(pdv)); hPrintNormal('Data..... : ' + Trim(data) + ' Hora.: ' + hora ); if length(vendedor) > 0 then hPrintNormal('Vendedor.: ' + Trim(vendedor) ); end; hCarne: hPrintNormal('Carne...:' +IntToStr(numeroimp) + ' PDV : ' + IntToStr(pdv)); hComanda:begin hPrintNormal(alinhaCentro(length('CONFERENCIA')) + 'CONFERENCIA'); hPrintNormal(Traco(47)); hPrintNormal('Comanda.:' +IntToStr(numeroimp) ); hPrintNormal('Data..... : ' + Trim(data) + ' Hora.: ' + hora ); hPrintNormal(Traco(47)); hPrintNormal('Descricao'); hPrintNormal(' Cod. Barras Qtd Unit. Total'); hPrintNormal(Traco(47)); end; end; end; Procedure InformaCliente(Ficha, Cliente, Endereco, Bairro, Tipo : String); overload ; begin {C = Cliente, F = Funcionário} client.aCod := Ficha; client.aName := Cliente; client.aAddr := Endereco; client.aProv := Bairro; client.aType := Tipo; end; Procedure InformaCliente(Ficha : integer ; Cliente, CPF, RG, Endereco, Bairro, Tipo : String); overload ; begin {C = Cliente, F = Funcionário} client.aCod := IntToStr(Ficha); client.aName := Cliente; client.aAddr := Endereco; client.aProv := Bairro; client.aCPF := CPF; client.aRG := RG; client.aType := Tipo; end; Procedure FechaImpressao (tipo : THTipoImp ; Desconto, Acrescimo, Total, Recebido : Double; OBS: String); var Arq : TextFile; aLinha : String; begin hPrintNormal(Traco(47)); case tipo of hVenda:begin hPrintNormal('Valor da Venda '+ FormatFloat('#,##0.00',Total)); if Desconto > 0 then begin hPrintNormal('Valor Desconto '+ FormatFloat('#,##0.00',Desconto)); hPrintNormal('Valor Total '+ FormatFloat('#,##0.00',Total - desconto )); end; hPrintNormal(Traco(47)); if FileExists(ExtractFilePath(Application.ExeName)+'hFormas.txt') then begin AssignFile(Arq, 'hFormas.txt'); Reset(Arq); while not Eof(Arq) do begin Readln(Arq, aLinha); hPrintNormal ( copy ( aLinha, 1, Length(aLinha))); end; CloseFile(Arq); while FileExists('hFormas.txt') do DeleteFile('hFormas.txt'); end; { DONE : Acertar tipos de impressão } hPrintNormal('Valor Total Recebido '+ FormatFloat('#,##0.00',Recebido)); if Recebido > Total then hPrintNormal('Troco '+ FormatFloat('#,##0.00',(Recebido-(Total-desconto)))); if client.aName <> '' then begin hPrintNormal(Traco(47)); if client.aType = 'C' then begin hPrintNormal('Codigo...:' + client.aCod); hPrintNormal('Cliente..:' + client.aName); end else begin hPrintNormal('Matricula:' + client.aCod); hPrintNormal('Funcionario:' + client.aName); end; if client.aCPF <> '' then hPrintNormal('CPF......:' + client.aCPF); if client.aRG <> '' then hPrintNormal('RG.......:' + client.aRG); hPrintNormal('Endereco.:' + client.aAddr); hPrintNormal('Bairro...:' + client.aProv); end; end; hConsignacao:begin hPrintNormal('Total Consignado.: '+ aLinhaDireita(FormatFloat('#,##0.00',Total),20)) ; hPrintNormal(Traco(47)); hPrintNormal('Consignado em nome de ' + LeIniTemp('CLIENTE','NOME')); hPrintNormal('CPF/CNPJ.: '+ LeIniTemp('CLIENTE','CNPJCPF')+ ' RG/IE: ' + LeIniTemp('CLIENTE', 'IERG')); if LeIniTemp('IMP','NUMERO') = '1' then begin AvancaLinhas(3); hPrintNormal(alinhaCentro(length('____________________________'))+ '____________________________'); hPrintNormal(alinhaCentro(length(' Responsavel '))+ ' Responsavel '); end; end; hRecibo:begin hPrintNormal('Recebemos de:' + LeIniTemp('CLIENTE', 'NOME')); hPrintNormal('O valor de ' + FormatFloat('#,##0.00',Total)); hPrintNormal(LeIniTemp('PARCELAS', 'TOTALEXT')); if Desconto > 0 then hPrintNormal('C/ desconto de :' + FormatFloat('#,##0.00',Desconto)); hPrintNormal(Traco(47)); hPrintNormal('Referente a:'); hPrintNormal('Venda Vencimento Valor'); if FileExists(ExtractFilePath(Application.ExeName)+'hparcelas.txt') then begin AssignFile(Arq, 'hparcelas.txt'); Reset(Arq); while not Eof(Arq) do begin Readln(Arq, aLinha); hPrintNormal ( copy ( aLinha, 1, Length(aLinha))); end; CloseFile(Arq); while FileExists('hparcelas.txt') do DeleteFile('hparcelas.txt'); end; hPrintNormal(Traco(47)); hPrintNormal('Forma de Pagamento: ' + LeIniTemp('PARCELAS','FORMA')); if Length(OBS) > 0 then begin hPrintNormal(Traco(47)); hPrintNormal(' Observações'); hPrintNormal(OBS); hPrintNormal(Traco(47)); end; AvancaLinhas(2); hPrintNormal(alinhaCentro(length('____________________________'))+ '____________________________'); hPrintNormal(alinhaCentro(length(' Responsavel '))+ ' Responsavel '); end; hVendaCliente:begin hPrintNormal('Valor da Venda '+ FormatFloat('#,##0.00',Total)); if Desconto > 0 then begin hPrintNormal('Valor Desconto '+ FormatFloat('#,##0.00',Desconto)); hPrintNormal('Valor Total '+ FormatFloat('#,##0.00',Total - desconto )); end; hPrintNormal(Traco(47)); hPrintNormal(alinhaCentro(Length('***PRESTACOES***'))+ '***PRESTACOES***'); hPrintNormal('N Vencimento Valor'); if FileExists(ExtractFilePath(Application.ExeName)+'hparcelas.txt') then begin AssignFile(Arq, ExtractFilePath(Application.ExeName)+'hparcelas.txt'); try Reset(Arq); except end; while not Eof(Arq) do begin Readln(Arq, aLinha); hPrintNormal ( copy ( aLinha, 1, Length(aLinha))); end; CloseFile(Arq); while FileExists(ExtractFilePath(Application.ExeName)+'hparcelas.txt') do DeleteFile('hparcelas.txt'); end; AvancaLinhas(1); hPrintNormal(Traco(47)); if FileExists(ExtractFilePath(Application.ExeName)+'hFormas.txt') then begin AssignFile(Arq, ExtractFilePath(Application.ExeName)+'hFormas.txt'); Reset(Arq); while not Eof(Arq) do begin Readln(Arq, aLinha); hPrintNormal ( copy ( aLinha, 1, Length(aLinha))); end; CloseFile(Arq); while FileExists(ExtractFilePath(Application.ExeName)+'hFormas.txt') do DeleteFile('hFormas.txt'); end; if Recebido > Total then hPrintNormal('Troco '+ FormatFloat('#,##0.00',(Recebido-Total))); {aqui havia uma reimpressao de cliente sendo que o mesmo´já é impresso no imptipo} end; hCarne:begin // hPrintNormal('Valor da Venda'+ FormatFloat('#,##0.00',SubTotal)); end; hComanda:begin hPrintNormal('Valor da Venda '+ FormatFloat('#,##0.00',aSubTotal)); if Desconto > 0 then begin hPrintNormal('Valor Desconto '+ FormatFloat('#,##0.00',Desconto)); hPrintNormal('Valor Total '+ FormatFloat('#,##0.00',aSubTotal - desconto )); end; end; end; while FileExists('temp.txt') do DeleteFile('temp.txt'); while FileExists('Temp.ini') do DeleteFile('Temp.ini'); aSubTotal := 0; ZeroMemory(@client,SizeOf(client)); // limpa record hPrintFechar; end; procedure AbreGaveta(impressora : THImpressora; modelo : THModeloIMP; porta : THPortas; IP : String); overload ; var Arq : TextFile; aLinha : String; aComando : String; begin aComando := #27+#118+#140; case impressora of hBematech:begin AtivaImpressora(impressora,modelo,porta, ip ); ComandoTX(aComando,Length(aComando)); FechaPorta; end; hElgin:begin end; hDaruma:begin end; hEpson:begin end; hDiebold:begin prn_comando(#27+'&0'+#12 +#48); end; hImpPadrao:begin // prn_comando(#27+#112+#0+#60+#120); prn_comando(#27+#118+#140); end; end; end; procedure AbreGaveta(impressora, modelo, porta : integer; ip : String);overload; var Arq : TextFile; aLinha : String; aComando : String; begin aComando := #27+#118+#140; case setImpressora(impressora) of hBematech:begin AtivaImpressora(impressora,modelo,porta, ip); ComandoTX(aComando,Length(aComando)); FechaPorta; end; hElgin:begin end; hDaruma:begin end; hEpson:begin end; hDiebold:begin prn_comando(#27+'&0'+#12 +#48); end; hImpPadrao:begin // prn_comando(#27+#112+#0+#60+#120); prn_comando(#27+#118+#140); end; end; end; function RetornaModelo(modelo : THModeloIMP):integer; begin case modelo of hMP20MI: RetornaModelo := 1 ; hMP4000TH: RetornaModelo := 5 ; hMP4200TH:RetornaModelo := 7 ; hMP2500TH: RetornaModelo := 8 ; end; if modelo = hMP20CI then RetornaModelo := 0; if modelo = hMP20TH then RetornaModelo := 0; if modelo = hMP2000CI then RetornaModelo := 0; if modelo = hMP2000TH then RetornaModelo := 0; if modelo = hMP2100TH then RetornaModelo := 0; end; procedure AtivaImpressora(impressora : THImpressora; modelo: THModeloIMP; porta : THPortas; ip : String); overload ; var teste : String; begin device.aImp := impressora; device.aMod := modelo; device.aPrt := porta; device.aIP := ip; teste := GetDefaultPrinter; case impressora of hBematech:begin aSubTotal := 0; ConfiguraModeloImpressora(RetornaModelo(device.aMod)); if (IniciaPorta(RetornaStrPorta(device.aPrt)) <> 1) then begin Application.MessageBox('Sem conexão com a impressora','Aviso!', MB_OK + MB_ICONWARNING); Exit; end; ComandoTX(#29#249#32#0#27#116#8,Length(#29#249#32#0#27#116#8) ); ComandoTX(#27#51#18, Length(#27#51#18)); end; hElgin: ; hDaruma: ; hEpson: ; hMatricial: ; hImpPadrao, hDiebold:begin aSubTotal := 0; prn := TAdvancedPrinter.Create; prn.OpenDoc('Impressão Documentos'); prn_Comando(#27+#51+#18); end; end; end; procedure AtivaImpressora(impressora : integer; modelo: integer; porta : integer; ip : String);overload ; var teste : String; begin device.aImp := setImpressora(impressora); device.aMod := setModelo(modelo); device.aPrt := setPorta(porta); device.aIP := ip; teste := GetDefaultPrinter; case setImpressora(impressora) of hBematech:begin aSubTotal := 0; ConfiguraModeloImpressora(RetornaModelo(device.aMod)); if (IniciaPorta(RetornaStrPorta(device.aPrt)) <> 1) then begin Application.MessageBox('Sem conexão com a impressora','Aviso!', MB_OK + MB_ICONWARNING); Exit; end; ComandoTX(#29#249#32#0#27#116#8,Length(#29#249#32#0#27#116#8) ); ComandoTX(#27#51#18, Length(#27#51#18)); end; hElgin: ; hDaruma: ; hEpson: ; hMatricial: ; hImpPadrao, hDiebold:begin aSubTotal := 0; prn := TAdvancedPrinter.Create; prn.OpenDoc('Impressão Documentos'); prn_Comando(#27+#51+#18); end; end; end; procedure IniciaImp(tipo : THTipoImp; numeroimp, pdv :integer; vendedor : String); begin device.aTsk := tipo; ImpCabecalho; ImprimeTipo(device.aImp, tipo,numeroimp,pdv,DateToStr(now),TimeToStr(now),vendedor); end; procedure IniciaRImp(tipo : THTipoImp; numeroimp, pdv :integer; vendedor : String; data: Tdate; hora : TTime); begin device.aTsk := tipo; ImpCabecalho; ImprimeTipo(device.aImp, tipo,numeroimp,pdv,DateToStr(Data),TimeToStr(Hora),vendedor); end; Procedure AdicionaForma (forma : String; valor : Double); var Arq : TextFile; aLinha : String; begin AssignFile(Arq,ExtractFilePath(Application.ExeName)+ 'hFormas.txt'); if not FileExists(ExtractFilePath(Application.ExeName)+ 'hFormas.txt') then Rewrite(Arq) else Append(Arq); Writeln(Arq,'Total em ' + forma +' '+FormatFloat('#,##0.00',valor)); CloseFile(Arq); end; procedure ImprimeBarras(aCodigo : String); begin case device.aImp of hBematech:begin end; hElgin:begin end; hDaruma:begin end; hEpson:begin end; hDiebold:begin end; end; end; procedure ImprimeQR(aCodigo : String); begin case device.aImp of hBematech:begin FechaPorta; end; hElgin:begin end; hDaruma:begin end; hEpson:begin end; hDiebold:begin end; end; end; procedure Guilhotina(corta : boolean); begin if corta = True then begin case device.aImp of hBematech:begin AtivaImpressora(device.aImp,device.aMod, device.aPrt, device.aIP); AcionaGuilhotina(0); FechaPorta; end; hImpPadrao,hDiebold:begin AtivaImpressora(device.aImp,device.aMod, device.aPrt, device.aIP); prn_comando(#27+#109); end; end; end; end; procedure ImpSangria(caixa : integer; supervisor, operador, descricao : String; valor : Double); begin ImpCabecalho; hPrintNormal(alinhaCentro(Length('SANGRIA '))+'SANGRIA '); hPrintNormal(TracoDuplo(47)); hPrintNormal('PDV :' + IntToStr(caixa)); hPrintNormal('Supervisor.: ' + supervisor); hPrintNormal('Operador...: ' + operador); hPrintNormal('Data: '+ DateToStr(Date)+ ' ' + 'Hora: '+ TimeToStr(Time)); hPrintNormal(Traco(47)); hPrintNormal('Valor da Retirada....: ' + FormatFloat('#,##0.00',valor)); if Length(trim(descricao)) > 0 then hPrintNormal('Descricao da Retirada: ' + descricao); hPrintNormal(Traco(47)); AvancaLinhas(2); hPrintNormal(Alinhacentro(LengTh('__________________________'))+'__________________________'); hPrintNormal(Alinhacentro(LengTh(' Responsavel '))+' Responsavel '); hPrintFechar; end; procedure ImpSuprimento(caixa : integer; supervisor, operador, descricao : String; valor : Double); begin ImpCabecalho; hPrintNormal(alinhaCentro(Length('SUPRIMENTO '))+'SUPRIMENTO '); hPrintNormal(TracoDuplo(47)); hPrintNormal('PDV :' + IntToStr(caixa)); hPrintNormal('Supervisor.: ' + supervisor); hPrintNormal('Operador...: ' + operador); hPrintNormal('Data: '+ DateToStr(Date)+ ' ' + 'Hora: '+ TimeToStr(Time)); hPrintNormal(Traco(47)); hPrintNormal('Valor do Suprimento....: ' + FormatFloat('#,##0.00',valor)); if Length(trim(descricao)) > 0 then hPrintNormal('Descricao do Suprimento: ' + descricao); hPrintNormal(Traco(47)); AvancaLinhas(2); hPrintNormal(Alinhacentro(LengTh('__________________________'))+'__________________________'); hPrintNormal(Alinhacentro(LengTh(' Responsavel '))+' Responsavel '); hPrintFechar; end; procedure CancelaCupom(caixa, cupom : integer; operador : String ; datahoravenda: TDateTime ;subtotal, desconto, total : Double); begin ImpCabecalho; hPrintNormal(alinhaCentro(Length('CANCELAMENTO '))+'CANCELAMENTO '); hPrintNormal(TracoDuplo(47)); hPrintNormal('PDV..........:' + IntToStr(caixa)); hPrintNormal('Nr. Cancelado :' + IntToStr(cupom)); hPrintNormal(Traco(47)); if Desconto > 0 then begin hPrintNormal('Sub Total....: ' + FormatFloat('#,##0.00',subtotal)); hPrintNormal('Desconto.....: ' + FormatFloat('#,##0.00',desconto)); hPrintNormal('Valor Total..: ' + FormatFloat('#,##0.00',total)); end else hPrintNormal('Valor Total..: ' + FormatFloat('#,##0.00',total)); hPrintNormal('Data da Venda: ' + FormatDateTime('DD/MM/YYYY',datahoravenda)); hPrintNormal('Data da Venda: ' + FormatDateTime('DD/MM/YYYY',now)); hPrintNormal('Operador.....:' + operador); hPrintNormal(Traco(47)); hPrintFechar; end; procedure ImpAbertura(caixa : integer; supervisor, operador : String; valor : Double); begin ImpCabecalho; hPrintNormal(alinhaCentro(Length('ABERTURA'))+'ABERTURA'); hPrintNormal(TracoDuplo(47)); hPrintNormal('PDV : ' + IntToStr(caixa)); hPrintNormal('Supervisor.: ' + supervisor); hPrintNormal('Operador...: ' + operador); hPrintNormal('Data: '+ DateToStr(Date)+ ' ' + 'Hora: '+ TimeToStr(Time)); hPrintNormal(Traco(47)); hPrintNormal('Valor Abertura: ' + FormatFloat('#,##0.00',valor)); AvancaLinhas(2); hPrintNormal(Alinhacentro(LengTh('__________________________'))+'__________________________'); hPrintNormal(Alinhacentro(LengTh(' Responsavel '))+' Responsavel '); hPrintFechar; end; procedure ImpFechamento(caixa, controle : integer; supervisorab,supervisorf, operador : String; aData: TDate; aHora: TTime; valor, valorinformado : Double); var aTotalCaixa, aTotalVendas, aValorFinal, aDiferenca : Double; Arq : TextFile; aTexto : String; begin ImpCabecalho; hPrintNormal(alinhaCentro(Length('FECHAMENTO DO PDV'))+'FECHAMENTO DO PDV'); hPrintNormal(TracoDuplo(47)); hPrintNormal('PDV : ' + IntToStr(caixa)+ ' Controle : ' + IntToStr(controle)); hPrintNormal('Superv. Abertura : ' + supervisorab); hPrintNormal('Data/Hora Abertura : '+ DateToStr(aData) +' as '+TimeToStr(aHora)); hPrintNormal('Superv. Fechamento: ' + supervisorf); hPrintNormal('Data/Hora Fechamento : '+ DateToStr(Date) +' as '+TimeToStr(Time)); hPrintNormal('Operador : ' + operador); hPrintNormal(Traco(47)); hPrintNormal(alinhaCentro(Length('Dados do PDV'))+ 'Dados do PDV'); hPrintNormal(Traco(47)); hPrintNormal('+ Valor Inicial do PDV....:' + aLinhaDireita(FormatFloat('#,##0.00',valor),20)); hPrintNormal('+ Dinheiro................:'+ aLinhaDireita(FormatFloat('#,##0.00',aDinheiro),20)); hPrintNormal('+ Cheque..................:'+ aLinhaDireita(FormatFloat('#,##0.00',aCheque),20)); hPrintNormal('+ Cartao..................:'+ aLinhaDireita(FormatFloat('#,##0.00',aCartao),20)); hPrintNormal('+ Suprimento..............:'+ aLinhaDireita(FormatFloat('#,##0.00',aSuprimento),20)); hPrintNormal('- Sangria.................:'+ aLinhaDireita(FormatFloat('#,##0.00',aSangria),20)); if FileExists(ExtractFilePath(Application.ExeName)+ 'hdetsangria.txt') then begin AssignFile(Arq, ExtractFilePath(Application.ExeName)+ 'hdetsangria.txt'); Reset(arq); while not Eof(Arq) do begin Readln(Arq, aTexto); hPrintNormal(aTexto); end; CloseFile(Arq); DeleteFile('hdetsangria.txt'); hPrintNormal(TracoDuplo(47)); end; aTotalCaixa := (valor + aDinheiro + aCartao + aCheque + aSuprimento) - aSangria; hPrintNormal('= Valor Final em Caixa....:'+ aLinhaDireita(FormatFloat('#,##0.00',aTotalCaixa),20)); if valorinformado <> 0 then begin hPrintNormal('Valor Informado...........:'+ aLinhaDireita(FormatFloat('#,##0.00',valorinformado),20)); aDiferenca := valorinformado - aTotalCaixa; hPrintNormal('Valor Diferenca...........:'+ aLinhaDireita(FormatFloat('#,##0.00',aDiferenca),20)); end; hPrintNormal(Traco(47)); hPrintNormal(alinhaCentro(Length('Informativo de Vendas'))+ 'Informativo de Vendas'); hPrintNormal(Traco(47)); hPrintNormal('+ Vendas em Dinheiro......:'+ aLinhaDireita(FormatFloat('#,##0.00',aTDinheiro),20)); hPrintNormal('+ Vendas em Cheque........:'+ aLinhaDireita(FormatFloat('#,##0.00',aTCheque),20)); hPrintNormal('+ Vendas em Cartao........:'+ aLinhaDireita(FormatFloat('#,##0.00',aTCartao),20)); hPrintNormal('+ Vendas para Cliente/Func:'+ aLinhaDireita(FormatFloat('#,##0.00',aTCliente),20)); //<< aTotalVendas := aTDinheiro + aTCheque + aTCartao + aTCliente; hPrintNormal('= Total de Vendas.........:'+ aLinhaDireita(FormatFloat('#,##0.00',aTotalVendas),20)); hPrintNormal(Traco(47)); hPrintNormal('= Total em Descontos......:'+ aLinhaDireita(FormatFloat('#,##0.00',aTDesconto),20)); hPrintNormal('= Recebimento de Clientes.:'+ aLinhaDireita(FormatFloat('#,##0.00',aTRecebido),20)); hPrintNormal(TracoDuplo(47)); hPrintNormal('Cupuns Cancelados.........:'+ aLinhaDireita(FormatFloat('###,#0',aCancelados),20)); hPrintNormal('Valor Cupons Cancelados...:'+ aLinhaDireita(FormatFloat('#,##0.00',aVlrCancelados),20)); hPrintNormal('Itens Cancelados..........:'+ aLinhaDireita(FormatFloat('###,#0',aItmCancelados),20)); hPrintNormal('Valor Itens Cancelados....:'+ aLinhaDireita(FormatFloat('#,##0.00',aVlrItmCancelados),20)); hPrintNormal(Traco(47)); zeraVariaveis(); hPrintFechar; end; procedure informaDadosCaixa(Dinheiro, Cheque, Cartao, Suprimento, Sangria : Double); begin aDinheiro := Dinheiro; aCartao := Cartao; aCheque := Cheque; aSuprimento := Suprimento; aSangria := Sangria; end; procedure informaDadosVenda(TDinheiro, TCheque, TCartao, TCliente, TDesconto, TRecebido : Double); begin aTDinheiro := TDinheiro; aTCheque := TCheque; aTCartao := TCartao; aTCliente := TCliente; aTDesconto := TDesconto; aTRecebido := TRecebido; end; procedure informaTotais(Cancelados, VlrCancelados, ItmCancelados, VlrItmCancelados : Double); begin aCancelados := Cancelados; aVlrCancelados := VlrCancelados; aItmCancelados := ItmCancelados; aVlrItmCancelados := VlrItmCancelados; end; procedure zeraVariaveis(); begin aDinheiro := 0; aCartao := 0; aCheque := 0; aSuprimento := 0; aSangria := 0; aTDinheiro := 0; aTCheque := 0; aTCartao := 0; aTCliente := 0; aTDesconto := 0; aTRecebido := 0; aCancelados := 0; aVlrCancelados := 0; aItmCancelados := 0; aVlrItmCancelados := 0; end; function setImpressora(imp : integer) : THImpressora; //hBematech, hElgin, hDaruma, hEpson, hDiebold, hMatricial, hImpPadrao; begin case imp of 0: setImpressora := hBematech; 1: setImpressora := hElgin; 2: setImpressora := hDaruma; 3: setImpressora := hEpson; 4: setImpressora := hDiebold; 5: setImpressora := hMatricial; 6: setImpressora := hImpPadrao; end; end; function setModelo(modelo : integer) : THModeloIMP; //Bematech //hMP20MI = 0, //hMP20CI = 1, //hMP20TH = 2, //hMP2000CI = 3, //hMP2000TH = 4, //hMP2100TH = 5, //hMP4000TH = 6, //hMP4200TH = 7, //hMP2500TH = 8, //Matricial //hGenericText = 9 begin case modelo of 0: setModelo := hMP20MI; 1: setModelo := hMP20CI; 2: setModelo := hMP20TH; 3: setModelo := hMP2000CI; 4: setModelo := hMP2000TH; 5: setModelo := hMP2100TH; 6: setModelo := hMP4000TH; 7: setModelo := hMP4200TH; 8: setModelo := hMP2500TH; 9: setModelo := hGenericText; end; end; function setPorta(porta : integer) : THPortas; // 0 - hCOM1, 1 - hCOM2, 2 - hCOM3, 3 - hCOM4, // 4 - hLPT1, 5 - hLPT2, 6 - hEthernet, 7 - hUSB begin case porta of 0: setPorta := hCOM1; 1: setPorta := hCOM2; 2: setPorta := hCOM3; 3: setPorta := hCOM4; 4: setPorta := hLPT1; 5: setPorta := hLPT2; 6: setPorta := hEthernet; 7: setPorta := hUSB; end; end; procedure DadosTemporarios(dados, campo, valor :String); begin GeraIniTemp(dados,campo,valor); end; Procedure AdicionaParcela (vecto : String ; valor : Double);overload; var Arq : TextFile; aLinha : String; begin AssignFile(Arq,ExtractFilePath(Application.ExeName)+ 'hparcelas.txt'); if not FileExists(ExtractFilePath(Application.ExeName)+ 'hparcelas.txt') then Rewrite(Arq) else Append(Arq); Writeln(Arq,' ' + vecto +' '+FormatFloat('#,##0.00',valor)); CloseFile(Arq); end; Procedure AdicionaParcela (parcela : integer; vecto : String ; valor : Double); overload; var Arq : TextFile; aLinha : String; begin AssignFile(Arq,ExtractFilePath(Application.ExeName)+ 'hparcelas.txt'); if not FileExists(ExtractFilePath(Application.ExeName)+ 'hparcelas.txt') then Rewrite(Arq) else Append(Arq); Writeln(Arq,IntToStr(parcela)+ ' ' + vecto +' '+FormatFloat('#,##0.00',valor)); CloseFile(Arq); end; procedure Prn_Pequeno(aTexto : String); begin prn.SendData(#15 + aTexto + #10); end; procedure Prn_Normal(aTexto : String); begin prn.SendData(#18 + aTexto + #10); end; procedure Prn_Grande(aTexto : String); begin prn.SendData(#14 + aTexto + #10); end; procedure Prn_Comando(aTexto : String); var cmd : TAdvancedPrinter; begin cmd := TAdvancedPrinter.Create; cmd.OpenDoc('CMD'); cmd.SendData(aTexto); cmd.CloseDoc; end; procedure AvancaLinhas(linhas : integer); var I : integer; begin case device.aImp of hBematech :begin AtivaImpressora(device.aImp,device.aMod,device.aPrt,device.aIP); for I := 0 to linhas - 1 do ComandoTX(#13#10, Length(#13#10)); end; hImpPadrao, hDiebold:begin for I := 0 to linhas - 1 do Prn_Comando(#10); end; end; end; procedure TesteImpressora(impressora, modelo, porta, avanco :Integer; ip : String); begin AtivaImpressora(impressora,modelo,porta, ip); hPrintPequeno('Fonte Pequena'); hPrintNormal('Fonte Normal'); hPrintGrande('Fonte Grande'); hPrintNormal('Fim Teste'); AvancaLinhas(avanco); hPrintFechar(); end; procedure DetalheSangria( Data, Hora, Operador, Descricao : String; Valor : Double ); var Arq : TextFile; begin AssignFile(Arq,ExtractFilePath(Application.ExeName)+ 'hdetsangria.txt'); if not FileExists(ExtractFilePath(Application.ExeName)+ 'hdetsangria.txt') then Rewrite(Arq) else Append(Arq); WriteLn(Arq, Data + ' ' + Hora + ' ' + copy(operador, 0, 15)+ ' R$ ' + FormatFloat('#,##0.00',Valor) + ' ' + Descricao ); CloseFile(Arq); end; {$REGION 'COMANDOS UNIFICADOS'} procedure hPrintPequeno(aTexto : String); begin case device.aImp of hBematech:begin Bematech_Pequeno(aTexto); end; hElgin:begin end; hDaruma:begin end; hEpson:begin end; hImpPadrao,hDiebold:begin Prn_Pequeno(aTexto); end; end; end; procedure hPrintNormal(aTexto : String); begin case device.aImp of hBematech:begin Bematech_Normal(aTexto); end; hElgin:begin end; hDaruma:begin end; hEpson:begin end; hImpPadrao,hDiebold:begin Prn_Normal(aTexto); end; end; end; procedure hPrintGrande(aTexto : String); begin case device.aImp of hBematech:begin Bematech_Grande(aTexto); end; hElgin:begin end; hDaruma:begin end; hEpson:begin end; hImpPadrao,hDiebold:begin Prn_Grande(aTexto); end; end; end; procedure hPrintComando(aTexto : String); begin case device.aImp of hBematech:begin ComandoTX(aTexto,Length(aTexto)); end; hElgin:begin end; hDaruma:begin end; hEpson:begin end; hImpPadrao,hDiebold:begin Prn_Comando(aTexto); end; end; end; procedure hPrintFechar(); begin case device.aImp of hBematech:begin FechaPorta; end; hElgin:begin end; hDaruma:begin end; hEpson:begin end; hImpPadrao,hDiebold:begin prn.CloseDoc; FreeAndNil(prn); end; end; end; procedure hAbregaveta(); begin AbreGaveta(device.aImp,device.aMod,device.aPrt, device.aIP); end; {$ENDREGION} end.
unit FSearchBar; interface uses Windows, SysUtils, Forms, Classes, NLDSBExplorerBar, NLDSBForm, OleCtrls, Controls, StdCtrls, ImgList, ComCtrls, ToolWin, SHDocVw, Dialogs, ExtCtrls, Menus; type TfrmSearchBar = class(TNLDSBForm) ilsSearch: TImageList; tlbSearch: TToolBar; tbSearch: TToolButton; pnlSearch: TPanel; cmbSearch: TComboBox; tlbNLDelphi: TToolBar; tbNLDelphi: TToolButton; ilsNLDelphi: TImageList; mnuNLDelphi: TPopupMenu; mnuWebsite: TMenuItem; mnuForum: TMenuItem; procedure FormCreate(Sender: TObject); procedure tbSearchClick(Sender: TObject); procedure cmbSearchKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cmbSearchKeyPress(Sender: TObject; var Key: Char); procedure mnuWebsiteClick(Sender: TObject); procedure mnuForumClick(Sender: TObject); private procedure Search(const AQuery: String; const ANewWindow: Boolean = False); procedure OpenURL(const AURL: String); protected procedure BeforeNavigate(Sender: TObject; var pDisp: OleVariant; var URL: OleVariant; var Flags: OleVariant; var TargetFrameName: OleVariant; var PostData: OleVariant; var Headers: OleVariant; var Cancel: OleVariant); override; end; implementation uses IdURI, Registry; const // The URL to match when checking for search queries CMatchURLPrefix = 'http://www.nldelphi.com/cgi-bin/texis.exe/' + 'Webinator/search/'; // This should be the default, however, due to a server configuration // mistake we'll just work around it for now... //CSearchURL: String = 'http://zoek.nldelphi.com/?query=%s'; CSearchURL = CMatchURLPrefix + '?query=%s'; // Some links CWebsiteURL = 'http://www.nldelphi.com/'; CForumURL = CWebsiteURL + 'forum/'; // Maybe add an option for this later? CMaxHistory = 20; {$R *.dfm} {**************************************** TfrmSearchBar ****************************************} procedure TfrmSearchBar.FormCreate; var regHistory: TRegistry; iSize: Integer; sData: String; begin regHistory := TRegistry.Create(); try regHistory.RootKey := HKEY_CURRENT_USER; if regHistory.OpenKey('Software\NLDelphi\NLDSearchBar', False) then begin if regHistory.ValueExists('Data') then begin iSize := regHistory.GetDataSize('Data'); SetLength(sData, iSize); regHistory.ReadBinaryData('Data', PChar(sData)^, iSize); cmbSearch.Items.Text := sData; end; end; finally FreeAndNil(regHistory); end; end; procedure TfrmSearchBar.tbSearchClick; begin Search(cmbSearch.Text); end; procedure TfrmSearchBar.cmbSearchKeyDown; begin if Key = VK_RETURN then Search(cmbSearch.Text, (ssShift in Shift)); end; procedure TfrmSearchBar.cmbSearchKeyPress; begin if Key = #13 then Key := #0; end; {**************************************** Search ****************************************} procedure TfrmSearchBar.Search; var sQuery: String; ifNewBrowser: IWebBrowser2; regHistory: TRegistry; iSize: Integer; sData: String; iItem: Integer; bFound: Boolean; begin sQuery := Trim(AQuery); if Length(sQuery) = 0 then exit; // Add the item to the history, or move it to the front... bFound := False; for iItem := 0 to cmbSearch.Items.Count - 1 do if CompareText(cmbSearch.Items[iItem], sQuery) = 0 then begin cmbSearch.Items.Move(iItem, 0); bFound := True; break; end; if not bFound then cmbSearch.Items.Insert(0, sQuery); // Write new URL list regHistory := TRegistry.Create(); try regHistory.RootKey := HKEY_CURRENT_USER; if regHistory.OpenKey('Software\NLDelphi\NLDSearchBar', True) then begin sData := cmbSearch.Items.Text; iSize := Length(sData); regHistory.WriteBinaryData('Data', PChar(sData)^, iSize); end; finally FreeAndNil(regHistory); end; sQuery := Format(CSearchURL, [sQuery]); // We *could* use either the flags parameter (navOpenInNewWindow) or // set the target frame to '_blank'. However, testing showed that using // either method in combination with XenoBar (a popup killer), XenoBar will // recognize the action as a 'popup' action instead of a 'new window' action, // thus block it by default. if ANewWindow then begin ifNewBrowser := CoInternetExplorer.Create(); ifNewBrowser._AddRef(); ifNewBrowser.Visible := True; ifNewBrowser.RegisterAsBrowser := True; ifNewBrowser.Navigate(sQuery, EmptyParam, EmptyParam, EmptyParam, EmptyParam); ifNewBrowser := nil; end else OpenURL(sQuery); end; procedure TfrmSearchBar.OpenURL; begin Browser.Navigate(AURL, EmptyParam, EmptyParam, EmptyParam, EmptyParam); end; {**************************************** Before Navigation ****************************************} procedure TfrmSearchBar.BeforeNavigate; var sURL: String; idURI: TIdURI; slParams: TStringList; pParams: PChar; pSearch: PChar; sParam: String; begin sURL := URL; // Check for valid URL if CompareText(Copy(sURL, 1, Length(CMatchURLPrefix)), CMatchURLPrefix) = 0 then begin idURI := TIdURI.Create(sURL); try // Kind of 'stolen' from IdHTTP slParams := TStringList.Create(); try sURL := Copy(idURI.Params, 2, MaxInt); pParams := PChar(sURL); pSearch := pParams; while (pSearch <> nil) and (pSearch[0] <> #0) do begin pSearch := StrScan(pParams, '&'); if pSearch = nil then begin pSearch := StrEnd(pParams); end; SetString(sParam, pParams, pSearch - pParams); slParams.Add(TIdURI.URLDecode(sParam)); pParams := pSearch + 1; end; // Check for 'query' parameter sURL := slParams.Values['query']; if Length(sURL) > 0 then cmbSearch.Text := sURL; finally FreeAndNil(slParams); end; finally FreeAndNil(idURI); end; end; end; procedure TfrmSearchBar.mnuWebsiteClick; begin OpenURL(CWebsiteURL); end; procedure TfrmSearchBar.mnuForumClick; begin OpenURL(CForumURL); end; initialization // Register band class NLDSBExplorerBar.BandClass := TfrmSearchBar; end.
unit PE.Image; interface uses System.Classes, System.SysUtils, System.Generics.Collections, PE.Common, PE.Headers, PE.DataDirectories, PE.Msg, PE.Utils, PE.Image.Defaults, PE.Image.Saving, PE.Types, PE.Types.DOSHeader, PE.Types.Directories, PE.Types.FileHeader, PE.Types.NTHeaders, PE.Types.Sections, PE.Types.Relocations, PE.Types.Imports, PE.Types.Export, PE.ExportSym, PE.TLS, PE.Section, PE.Sections, PE.Imports, PE.Resources, PE.Parser.Headers, PE.Parser.Export, PE.Parser.Import, PE.Parser.ImportDelayed, PE.Parser.Relocs, PE.Parser.TLS, PE.Parser.Resources, PE.COFF, PE.COFF.Types, PE.MemoryStream, PE.ProcessModuleStream, PE.ParserCallbacks; type { TPEImage } TPEImage = class private FImageKind: TPEImageKind; FParseStages: TParserFlags; FParseCallbacks: IPEParserCallbacks; FOptions: TParserOptions; // Used only for loading from mapped image. Nil for disk images. FPEMemoryStream: TPEMemoryStream; FFileName: string; FFileSize: UInt64; FDefaults: TPEDefaults; FImageBitSize: byte; // 32/64 FImageWordSize: byte; // 4/8 FCOFF: TCOFF; FDosHeader: TImageDOSHeader; // DOS header. FLFANew: uint32; // Address of new header next after DOS. FDosBlock: TBytes; // Bytes between DOS header and next header. FSecHdrGap: TBytes; // Gap after section headers. FFileHeader: TImageFileHeader; FOptionalHeader: TPEOptionalHeader; FSections: TPESections; FRelocs: TRelocs; FImports: TPEImport; // of TPEImportFunction FImportsDelayed: TPEImport; // of TPEImportFunctionDelayed FExports: TPEExportSyms; FExportedName: String; FTLS: TTLS; FResourceTree: TResourceTree; FOverlay: TOverlay; FParsers: array [TParserFlag] of TPEParserClass; FMsg: TMsgMgr; FDataDirectories: TDataDirectories; private // Used for read/write. FCurrentSec: TPESection; // Current section. FPositionRVA: TRVA; // Current RVA. FCurrentOfs: uint32; // Current offset in section. procedure SetPositionRVA(const Value: TRVA); procedure SetPositionVA(const Value: TVA); function GetPositionVA: TVA; function ReadWrite(Buffer: Pointer; Count: cardinal; Read: boolean): uint32; private // Add new section to have range of addresses for image header. procedure LoadingAddHeaderAsASection(Stream: TStream); private { Notifiers } procedure DoReadError; { Parsers } procedure InitParsers; { Base loading } function LoadSectionHeaders(AStream: TStream): boolean; function LoadSectionData(AStream: TStream): UInt16; // Replace /%num% to name from COFF string table. procedure ResolveSectionNames; function GetImageBase: TRVA; inline; procedure SetImageBase(Value: TRVA); inline; function GetSizeOfImage: UInt64; inline; procedure SetSizeOfImage(Value: UInt64); inline; function EntryPointRVAGet: TRVA; inline; procedure EntryPointRVASet(Value: TRVA); inline; function FileAlignmentGet: uint32; inline; procedure FileAlignmentSet(const Value: uint32); inline; function SectionAlignmentGet: uint32; inline; procedure SectionAlignmentSet(const Value: uint32); inline; function GetFileHeader: PImageFileHeader; inline; function GetImageDOSHeader: PImageDOSHeader; inline; function GetOptionalHeader: PPEOptionalHeader; inline; function GetIsDll: boolean; procedure SetIsDll(const Value: boolean); protected // If image is disk-based, result is created TFileStream. // If it's memory mapped, result is opened memory stream. function SourceStreamGet(Mode: word): TStream; // If image is disk-based, stream is freed. // If it's memory mapped, nothing happens. procedure SourceStreamFree(Stream: TStream); public // Create without message proc. constructor Create(); overload; // Create with message proc. constructor Create(AMsgProc: TMsgProc); overload; destructor Destroy; override; // Check if stream at offset Ofs is MZ/PE image. // Result is False if either failed to make check or it's not valid image. class function IsPE(AStream: TStream; Ofs: UInt64 = 0): boolean; overload; static; // Check if file is PE. class function IsPE(const FileName: string): boolean; overload; static; // Check if image is 32/64 bit. function Is32bit: boolean; inline; function Is64bit: boolean; inline; // Get image bitness. 32/64 or 0 if unknown. function GetImageBits: UInt16; inline; procedure SetImageBits(Value: UInt16); { PE Streaming } // Seek RVA or VA and return True on success. function SeekRVA(RVA: TRVA): boolean; function SeekVA(VA: TVA): boolean; // Read Count bytes from current RVA/VA position to Buffer and // return number of bytes read. // It cannot read past end of section. function Read(Buffer: Pointer; Count: cardinal): uint32; overload; function Read(var Buffer; Count: cardinal): uint32; overload; inline; // Read Count bytes to Buffer and return True if all bytes were read. function ReadEx(Buffer: Pointer; Count: cardinal): boolean; overload; inline; function ReadEx(var Buffer; Size: cardinal): boolean; overload; inline; // Read 1/2/4/8-sized word. // If WordSize is 0 size native to image is used (4 for PE32, 8 for PE64). function ReadWord(WordSize: byte = 0): UInt64; // Try to read 1/2/4/8-sized word. // Result shows if all bytes are read. function ReadWordEx(WordSize: byte; OutValue: PUInt64): boolean; // Skip Count bytes. procedure Skip(Count: integer); // Read 1-byte 0-terminated string. function ReadAnsiString: String; // MaxLen: 0 - no limit function ReadAnsiStringLen(MaxLen: integer; out Len: integer; out Str: string): boolean; // Read 2-byte UTF-16 string with length prefix (2 bytes). function ReadUnicodeStringLenPfx2: String; // Reading values. // todo: these functions should be Endianness-aware. function ReadUInt8: UInt8; overload; inline; function ReadUInt16: UInt16; overload; inline; function ReadUInt32: uint32; overload; inline; function ReadUInt64: UInt64; overload; inline; function ReadUIntPE: UInt64; overload; inline; // 64/32 depending on PE format. function ReadUInt8(OutData: PUInt8): boolean; overload; inline; function ReadUInt16(OutData: PUInt16): boolean; overload; inline; function ReadUInt32(OutData: PUInt32): boolean; overload; inline; function ReadUInt64(OutData: PUInt64): boolean; overload; inline; function ReadUIntPE(OutData: PUInt64): boolean; overload; inline; // 64/32 depending on PE format. // Write Count bytes from Buffer to current position. function Write(Buffer: Pointer; Count: cardinal): uint32; overload; function Write(const Buffer; Count: cardinal): uint32; overload; function WriteEx(Buffer: Pointer; Count: cardinal): boolean; overload; inline; function WriteEx(const Buffer; Count: cardinal): boolean; overload; inline; { Address conversions } // Check if RVA exists. function RVAExists(RVA: TRVA): boolean; // Convert RVA to memory pointer. function RVAToMem(RVA: TRVA): Pointer; // Convert RVA to file offset. OutOfs can be nil. function RVAToOfs(RVA: TRVA; OutOfs: PDword): boolean; // Find Section by RVA. OutSec can be nil. function RVAToSec(RVA: TRVA; OutSec: PPESection): boolean; // Convert RVA to VA. function RVAToVA(RVA: TRVA): TVA; inline; // Check if VA exists. function VAExists(VA: TRVA): boolean; // Convert VA to memory pointer. function VAToMem(VA: TVA): Pointer; inline; // Convert VA to file offset. OutOfs can be nil. function VAToOfs(VA: TVA; OutOfs: PDword): boolean; inline; // Find Section by VA. OutSec can be nil. function VAToSec(VA: TRVA; OutSec: PPESection): boolean; // Convert VA to RVA. // Make sure VA is >= ImageBase. function VAToRVA(VA: TVA): TRVA; inline; // Check if RVA/VA belongs to image. function ContainsRVA(RVA: TRVA): boolean; inline; function ContainsVA(VA: TVA): boolean; inline; { Image } // Clear image. procedure Clear; // Calculate not aligned size of headers. function CalcHeadersSizeNotAligned: uint32; inline; // Calculate valid aligned size of image. function CalcVirtualSizeOfImage: UInt64; inline; // Calc raw size of image (w/o overlay), or 0 if failed. // Can be used if image loaded from stream and exact image size is unknown. // Though we still don't know overlay size. function CalcRawSizeOfImage: UInt64; inline; // Calc offset of section headers. function CalcSecHdrOfs: TFileOffset; // Calc offset of section headers end. function CalcSecHdrEndOfs: TFileOffset; // Calc size of optional header w/o directories. function CalcSizeOfPureOptionalHeader: uint32; // Set aligned SizeOfHeaders. procedure FixSizeOfHeaders; inline; // Set valid size of image. procedure FixSizeOfImage; inline; { Loading } // Load image from stream. function LoadFromStream(AStream: TStream; AParseStages: TParserFlags = DEFAULT_PARSER_FLAGS; ImageKind: TPEImageKind = PEIMAGE_KIND_DISK): boolean; // Load image from file. function LoadFromFile(const AFileName: string; AParseStages: TParserFlags = DEFAULT_PARSER_FLAGS): boolean; // Load PE image from image in memory of current process. // Won't help if image in memory has spoiled headers. function LoadFromMappedImage(const AFileName: string; AParseStages: TParserFlags = DEFAULT_PARSER_FLAGS): boolean; overload; function LoadFromMappedImage(ModuleBase: NativeUInt; AParseStages: TParserFlags = DEFAULT_PARSER_FLAGS): boolean; overload; // Load PE image from running process. // Address defines module to load. function LoadFromProcessImage(ProcessId: DWORD; Address: NativeUInt; AParseStages: TParserFlags = DEFAULT_PARSER_FLAGS): boolean; { Saving } // Save image to stream. function SaveToStream(AStream: TStream): boolean; // Save image to file. function SaveToFile(const AFileName: string): boolean; { Sections } // Get last section containing raw offset and size. // Get nil if no good section found. function GetLastSectionWithValidRawData: TPESection; { Overlay } // Get overlay record pointer. function GetOverlay: POverlay; // Save overlay to file. It can be either appended to existing file or new // file will be created. function SaveOverlayToFile(const AFileName: string; Append: boolean = false): boolean; // Remove overlay from current image file. function RemoveOverlay: boolean; // Set overlay for current image file from file data of AFileName file. // If Offset and Size are 0, then whole file is appended. function LoadOverlayFromFile(const AFileName: string; Offset: UInt64 = 0; Size: UInt64 = 0): boolean; overload; { Writing to external stream } // Write RVA to stream (32/64 bit sized depending on image). function StreamWriteRVA(AStream: TStream; RVA: TRVA): boolean; { Dump } // Save memory region to stream/file (in section boundary). // Result is number of bytes written. // If trying to save more bytes than section contains it will save until // section end. // AStream can be nil if you want just check how many bytes can be saved. // todo: maybe also add cross-section dumps. function SaveRegionToStream(AStream: TStream; RVA: TRVA; Size: uint32): uint32; function SaveRegionToFile(const AFileName: string; RVA: TRVA; Size: uint32): uint32; // Load data from Stream at Offset to memory. RVA and Size must define region // that completely fit into some section. If region is larger than file or // section it is truncated. // ReadSize is optional param to get number of bytes read. function LoadRegionFromStream(AStream: TStream; Offset: UInt64; RVA: TRVA; Size: uint32; ReadSize: PUInt32 = nil): boolean; function LoadRegionFromFile(const AFileName: string; Offset: UInt64; RVA: TRVA; Size: uint32; ReadSize: PUInt32 = nil): boolean; { Regions } procedure RegionRemove(RVA: TRVA; Size: uint32); // Check if region belongs to some section and has enough raw/virtual size. function RegionExistsRaw(RVA: TRVA; RawSize: uint32): boolean; function RegionExistsVirtual(RVA: TRVA; VirtSize: uint32): boolean; { Properties } property Msg: TMsgMgr read FMsg; property Defaults: TPEDefaults read FDefaults; property ImageBitSize: byte read FImageBitSize; property ImageWordSize: byte read FImageWordSize; property ParseCallbacks: IPEParserCallbacks read FParseCallbacks write FParseCallbacks; // Current read/write position. property PositionRVA: TRVA read FPositionRVA write SetPositionRVA; property PositionVA: TVA read GetPositionVA write SetPositionVA; property ImageKind: TPEImageKind read FImageKind; property FileName: string read FFileName; // Offset of NT headers, used building new image. property LFANew: uint32 read FLFANew write FLFANew; property DosBlock: TBytes read FDosBlock; property SecHdrGap: TBytes read FSecHdrGap; // Headers. property DOSHeader: PImageDOSHeader read GetImageDOSHeader; property FileHeader: PImageFileHeader read GetFileHeader; property OptionalHeader: PPEOptionalHeader read GetOptionalHeader; // Directories. property DataDirectories: TDataDirectories read FDataDirectories; // Image sections. property Sections: TPESections read FSections; // Relocations. property Relocs: TRelocs read FRelocs; // Import items. property Imports: TPEImport read FImports; property ImportsDelayed: TPEImport read FImportsDelayed; // Export items. property ExportSyms: TPEExportSyms read FExports; // Image exported name. property ExportedName: String read FExportedName write FExportedName; // Thread Local Storage items. property TLS: TTLS read FTLS; // Resource items. property ResourceTree: TResourceTree read FResourceTree; property ImageBase: TRVA read GetImageBase write SetImageBase; property SizeOfImage: UInt64 read GetSizeOfImage write SetSizeOfImage; // 32/64 property ImageBits: UInt16 read GetImageBits write SetImageBits; property EntryPointRVA: TRVA read EntryPointRVAGet write EntryPointRVASet; property FileAlignment: uint32 read FileAlignmentGet write FileAlignmentSet; property SectionAlignment: uint32 read SectionAlignmentGet write SectionAlignmentSet; property IsDLL: boolean read GetIsDll write SetIsDll; property Options: TParserOptions read FOptions write FOptions; end; implementation const VM_PAGE_SIZE = $1000; // 4 KB page { TPEImage } function TPEImage.EntryPointRVAGet: TRVA; begin Result := FOptionalHeader.AddressOfEntryPoint; end; procedure TPEImage.EntryPointRVASet(Value: TRVA); begin FOptionalHeader.AddressOfEntryPoint := Value; end; function TPEImage.GetImageBase: TRVA; begin Result := FOptionalHeader.ImageBase; end; procedure TPEImage.SetImageBase(Value: TRVA); begin FOptionalHeader.ImageBase := Value; end; function TPEImage.GetSizeOfImage: UInt64; begin Result := FOptionalHeader.SizeOfImage; end; procedure TPEImage.SetSizeOfImage(Value: UInt64); begin FOptionalHeader.SizeOfImage := Value; end; function TPEImage.StreamWriteRVA(AStream: TStream; RVA: TRVA): boolean; var rva32: uint32; rva64: UInt64; begin if Is32bit then begin rva32 := RVA; Result := AStream.Write(rva32, 4) = 4; exit; end; if Is64bit then begin rva64 := RVA; Result := AStream.Write(rva64, 8) = 8; exit; end; exit(false); end; constructor TPEImage.Create; begin Create(nil); end; constructor TPEImage.Create(AMsgProc: TMsgProc); begin FOptions := DEFAULT_OPTIONS; FMsg := TMsgMgr.Create(AMsgProc); FDefaults := TPEDefaults.Create(self); FDataDirectories := TDataDirectories.Create(self); FSections := TPESections.Create(self); FRelocs := TRelocs.Create; FImports := TPEImport.Create; FImportsDelayed := TPEImport.Create; FExports := TPEExportSyms.Create; FTLS := TTLS.Create; FResourceTree := TResourceTree.Create; FCOFF := TCOFF.Create(self); InitParsers; FDefaults.SetAll; end; procedure TPEImage.Clear; begin if FImageKind = PEIMAGE_KIND_MEMORY then raise Exception.Create('Can''t clear mapped in-memory image.'); FLFANew := 0; SetLength(FDosBlock, 0); SetLength(FSecHdrGap, 0); FCOFF.Clear; FDataDirectories.Clear; FSections.Clear; FImports.Clear; FImportsDelayed.Clear; FExports.Clear; FTLS.Clear; FResourceTree.Clear; end; function TPEImage.ContainsRVA(RVA: TRVA): boolean; begin if FSections.Count = 0 then raise Exception.Create('Image contains no sections.'); Result := (RVA >= FSections.First.RVA) and (RVA < FSections.Last.GetEndRVA); end; function TPEImage.ContainsVA(VA: TVA): boolean; begin Result := (VA >= ImageBase) and ContainsRVA(VAToRVA(VA)); end; destructor TPEImage.Destroy; begin FPEMemoryStream.Free; FResourceTree.Free; FTLS.Free; FExports.Free; FImports.Free; FImportsDelayed.Free; FRelocs.Free; FSections.Free; FDataDirectories.Free; FCOFF.Free; inherited Destroy; end; procedure TPEImage.DoReadError; begin raise Exception.Create('Read Error.'); end; function TPEImage.SaveRegionToStream(AStream: TStream; RVA: TRVA; Size: uint32): uint32; const BUFSIZE = 8192; var Sec: TPESection; Ofs, TmpSize: uint32; pCur: PByte; begin if not RVAToSec(RVA, @Sec) then exit(0); Ofs := RVA - Sec.RVA; // offset to read from // If end position is over section end then override size to read until end // of section. if Ofs + Size > Sec.GetAllocatedSize then Size := Sec.GetAllocatedSize - Ofs; Result := Size; if Assigned(AStream) then begin pCur := Sec.Mem + Ofs; // memory to read from while Size <> 0 do begin if Size >= BUFSIZE then TmpSize := BUFSIZE else TmpSize := Size; AStream.Write(pCur^, TmpSize); inc(pCur, TmpSize); dec(Size, TmpSize); end; end; end; function TPEImage.SaveRegionToFile(const AFileName: string; RVA: TRVA; Size: uint32): uint32; var fs: TFileStream; begin fs := TFileStream.Create(AFileName, fmCreate); try Result := SaveRegionToStream(fs, RVA, Size); finally fs.Free; end; end; function TPEImage.LoadRegionFromStream(AStream: TStream; Offset: UInt64; RVA: TRVA; Size: uint32; ReadSize: PUInt32): boolean; var Sec: TPESection; p: PByte; ActualSize: uint32; begin if Size = 0 then exit(true); if Offset >= AStream.Size then exit(false); if (Offset + Size) > AStream.Size then Size := AStream.Size - Offset; if not RVAToSec(RVA, @Sec) then exit(false); if (RVA + Size) > Sec.GetEndRVA then Size := Sec.GetEndRVA - RVA; AStream.Position := Offset; p := Sec.Mem + (RVA - Sec.RVA); ActualSize := AStream.Read(p^, Size); if Assigned(ReadSize) then ReadSize^ := ActualSize; exit(true); end; function TPEImage.LoadRegionFromFile(const AFileName: string; Offset: UInt64; RVA: TRVA; Size: uint32; ReadSize: PUInt32): boolean; var fs: TFileStream; begin fs := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try Result := LoadRegionFromStream(fs, Offset, RVA, Size, ReadSize); finally fs.Free; end; end; procedure TPEImage.InitParsers; begin FParsers[PF_EXPORT] := TPEExportParser; FParsers[PF_IMPORT] := TPEImportParser; FParsers[PF_IMPORT_DELAYED] := TPEImportDelayedParser; FParsers[PF_RELOCS] := TPERelocParser; FParsers[PF_TLS] := TPETLSParser; FParsers[PF_RESOURCES] := TPEResourcesParser; end; function TPEImage.CalcHeadersSizeNotAligned: uint32; begin Result := CalcSecHdrEndOfs; end; procedure TPEImage.FixSizeOfHeaders; begin FOptionalHeader.SizeOfHeaders := AlignUp(CalcHeadersSizeNotAligned, FileAlignment); end; function TPEImage.CalcVirtualSizeOfImage: UInt64; begin with FSections do begin if Count <> 0 then Result := AlignUp(Last.RVA + Last.VirtualSize, SectionAlignment) else Result := AlignUp(CalcHeadersSizeNotAligned, SectionAlignment); end; end; function TPEImage.CalcRawSizeOfImage: UInt64; var Last: TPESection; begin Last := GetLastSectionWithValidRawData; if (Last <> nil) then Result := Last.GetEndRawOffset else Result := 0; end; procedure TPEImage.FixSizeOfImage; begin SizeOfImage := CalcVirtualSizeOfImage; end; function TPEImage.CalcSecHdrOfs: TFileOffset; var SizeOfPureOptionalHeader: uint32; begin SizeOfPureOptionalHeader := CalcSizeOfPureOptionalHeader(); Result := FLFANew + 4 + SizeOf(TImageFileHeader) + SizeOfPureOptionalHeader + FDataDirectories.Count * SizeOf(TImageDataDirectory); end; function TPEImage.CalcSecHdrEndOfs: TFileOffset; begin Result := CalcSecHdrOfs + FSections.Count * SizeOf(TImageSectionHeader); end; function TPEImage.CalcSizeOfPureOptionalHeader: uint32; begin Result := FOptionalHeader.CalcSize(ImageBits); end; function TPEImage.GetFileHeader: PImageFileHeader; begin Result := @self.FFileHeader; end; function TPEImage.LoadSectionHeaders(AStream: TStream): boolean; var Sec: TPESection; i: integer; sh: TImageSectionHeader; NumberOfSections: UInt16; SizeOfHeader, SizeOfHeaderMapped: uint32; HeaderList: TList<TImageSectionHeader>; VSizeToBeMapped: uint32; CorrectRawDataPositions: integer; StreamSize: UInt64; SecNameOldHex: string; begin NumberOfSections := FFileHeader.NumberOfSections; // Header comes from offset: 0 to SizeOfHeader SizeOfHeader := CalcHeadersSizeNotAligned; SizeOfHeaderMapped := AlignUp(SizeOfHeader, VM_PAGE_SIZE); FSections.Clear; // it clears FFileHeader.NumberOfSections if NumberOfSections = 0 then begin Msg.Write(SCategorySections, 'There are no sections in the image'); exit(true); end; HeaderList := TList<TImageSectionHeader>.Create; try // ------------------------------------------------------------------------- // Load section headers. CorrectRawDataPositions := 0; StreamSize := AStream.Size; for i := 1 to NumberOfSections do begin if not StreamRead(AStream, sh, SizeOf(sh)) then break; if (sh.SizeOfRawData = 0) or (sh.PointerToRawData < AStream.Size) then begin inc(CorrectRawDataPositions); HeaderList.Add(sh); end else Msg.Write(SCategorySections, 'Raw data is outside of stream (0x%x>0x%x). Skipped.', [sh.PointerToRawData, StreamSize]); end; if CorrectRawDataPositions = 0 then begin Msg.Write(SCategorySections, 'No good raw data positions found.'); exit(false); end else if CorrectRawDataPositions <> NumberOfSections then begin Msg.Write(SCategorySections, '%d of %d sections contain correct raw data positions.', [CorrectRawDataPositions, NumberOfSections]); end; // ------------------------------------------------------------------------- // Check section count. if HeaderList.Count <> NumberOfSections then FMsg.Write(SCategorySections, 'Found %d of %d section headers.', [HeaderList.Count, NumberOfSections]); // ------------------------------------------------------------------------- for i := 0 to HeaderList.Count - 1 do begin sh := HeaderList[i]; if sh.SizeOfRawData <> 0 then begin // If section data points into header. if (sh.PointerToRawData < SizeOfHeader) then begin Msg.Write(SCategorySections, 'Section # %d is inside of headers', [i]); // Headers are always loaded at image base with // RawSize = SizeOfHeaders // VirtualSize = SizeOfHeaderMapped // Override section header. sh.PointerToRawData := 0; sh.SizeOfRawData := Min(sh.SizeOfRawData, FFileSize, SizeOfHeaderMapped); sh.VirtualSize := SizeOfHeaderMapped; end; end; if (sh.VirtualSize = 0) and (sh.SizeOfRawData = 0) then begin Msg.Write(SCategorySections, 'Section # %d has vsize and rsize = 0, skipping it', [i]); continue; end; if (sh.SizeOfRawData > sh.VirtualSize) then begin // Correct virtual size to be sure all raw data will be loaded. VSizeToBeMapped := AlignUp(sh.VirtualSize, VM_PAGE_SIZE); sh.VirtualSize := PE.Utils.Min(sh.SizeOfRawData, VSizeToBeMapped); end; { * Raw size can be 0 * Virtual size can't be 0 as it won't be mapped } if sh.VirtualSize = 0 then begin Msg.Write(SCategorySections, 'Section # %d has vsize = 0', [i]); if PO_SECTION_VSIZE_FALLBACK in FOptions then begin sh.VirtualSize := AlignUp(sh.SizeOfRawData, SectionAlignment); end else begin Msg.Write(SCategorySections, 'Option to fallback to RSize isn''t included, skipping'); continue; end; end; Sec := TPESection.Create(sh, nil, @FMsg); if Sec.Name.IsEmpty or (not IsAlphaNumericString(Sec.Name)) then begin if PO_SECTION_AUTORENAME_NON_ALPHANUMERIC in FOptions then begin SecNameOldHex := Sec.NameAsHex; Sec.Name := format('sec_%4.4x', [i]); Msg.Write(SCategorySections, 'Section name can be garbage (hex: %s). Overriding to %s', [SecNameOldHex, Sec.Name]); end; end; FSections.Add(Sec); // changes FFileHeader.NumberOfSections end; finally HeaderList.Free; end; exit(true); end; function TPEImage.LoadSectionData(AStream: TStream): UInt16; var i: integer; Sec: TPESection; begin Result := 0; // todo: check if section overlaps existing sections. for i := 0 to FSections.Count - 1 do begin Sec := FSections[i]; // Process only normal sections. // Section like "image header" is skipped. if Sec.ClassType = TPESection then begin if FImageKind = PEIMAGE_KIND_DISK then begin if Sec.LoadDataFromStream(AStream) then inc(Result); end else begin if Sec.LoadDataFromStreamEx(AStream, Sec.RVA, Sec.VirtualSize) then inc(Result); end; end; end; end; procedure TPEImage.ResolveSectionNames; var StringOfs, err: integer; Sec: TPESection; t: string; begin for Sec in FSections do begin if Sec.Name.StartsWith('/') then begin val(Sec.Name.Substring(1), StringOfs, err); if (err = 0) and (FCOFF.GetString(StringOfs, t)) and (not t.IsEmpty) then Sec.Name := t; // long name from COFF strings end; end; end; function TPEImage.Is32bit: boolean; begin Result := FOptionalHeader.Magic = PE_MAGIC_PE32; end; function TPEImage.Is64bit: boolean; begin Result := FOptionalHeader.Magic = PE_MAGIC_PE32PLUS; end; class function TPEImage.IsPE(const FileName: string): boolean; var Stream: TFileStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try Result := TPEImage.IsPE(Stream); finally Stream.Free; end; end; class function TPEImage.IsPE(AStream: TStream; Ofs: UInt64): boolean; var dos: TImageDOSHeader; peSig: TNTSignature; begin if not StreamSeek(AStream, Ofs) then exit(false); if StreamRead(AStream, dos, SizeOf(dos)) then if dos.e_magic.IsMZ then begin Ofs := Ofs + dos.e_lfanew; if Ofs >= AStream.Size then exit(false); if StreamSeek(AStream, Ofs) then if StreamRead(AStream, peSig, SizeOf(peSig)) then exit(peSig.IsPE00); end; exit(false); end; function TPEImage.GetImageBits: UInt16; begin Result := FImageBitSize; end; function TPEImage.GetImageDOSHeader: PImageDOSHeader; begin Result := @self.FDosHeader; end; procedure TPEImage.SetImageBits(Value: UInt16); begin case Value of 32: FOptionalHeader.Magic := PE_MAGIC_PE32; 64: FOptionalHeader.Magic := PE_MAGIC_PE32PLUS; else begin FOptionalHeader.Magic := 0; raise Exception.Create('Value unsupported.'); end; end; FImageBitSize := Value; FImageWordSize := Value div 8; end; procedure TPEImage.SetPositionRVA(const Value: TRVA); begin if not SeekRVA(Value) then raise Exception.CreateFmt('Invalid RVA position (0x%x)', [Value]); end; procedure TPEImage.SetPositionVA(const Value: TVA); begin SetPositionRVA(VAToRVA(Value)); end; function TPEImage.GetPositionVA: TVA; begin Result := RVAToVA(FPositionRVA); end; function TPEImage.GetIsDll: boolean; begin Result := (FFileHeader.Characteristics and IMAGE_FILE_DLL) <> 0; end; procedure TPEImage.SetIsDll(const Value: boolean); begin if Value then FFileHeader.Characteristics := FFileHeader.Characteristics or IMAGE_FILE_DLL else FFileHeader.Characteristics := FFileHeader.Characteristics and (not IMAGE_FILE_DLL); end; function TPEImage.FileAlignmentGet: uint32; begin Result := FOptionalHeader.FileAlignment; end; procedure TPEImage.FileAlignmentSet(const Value: uint32); begin FOptionalHeader.FileAlignment := Value; end; function TPEImage.SectionAlignmentGet: uint32; begin Result := FOptionalHeader.SectionAlignment; end; procedure TPEImage.SectionAlignmentSet(const Value: uint32); begin FOptionalHeader.SectionAlignment := Value; end; function TPEImage.SeekRVA(RVA: TRVA): boolean; begin // Section. if not RVAToSec(RVA, @FCurrentSec) then exit(false); // RVA/Offset. FPositionRVA := RVA; FCurrentOfs := FPositionRVA - FCurrentSec.RVA; exit(true); end; function TPEImage.SeekVA(VA: TVA): boolean; begin Result := (VA >= ImageBase) and SeekRVA(VAToRVA(VA)); end; procedure TPEImage.Skip(Count: integer); begin inc(FPositionRVA, Count); end; procedure TPEImage.SourceStreamFree(Stream: TStream); begin if FImageKind = PEIMAGE_KIND_DISK then Stream.Free; end; function TPEImage.SourceStreamGet(Mode: word): TStream; begin if FImageKind = PEIMAGE_KIND_DISK then Result := TFileStream.Create(FFileName, Mode) else Result := FPEMemoryStream; end; function TPEImage.ReadWord(WordSize: byte): UInt64; begin if not ReadWordEx(WordSize, @Result) then raise Exception.Create('Read error'); end; function TPEImage.ReadWordEx(WordSize: byte; OutValue: PUInt64): boolean; var tmp: UInt64; begin case WordSize of 0: WordSize := FImageWordSize; 1, 2, 4, 8: ; // allowed size else raise Exception.Create('Unsupported word size for ReadWord'); end; tmp := 0; Result := ReadEx(tmp, WordSize); if Assigned(OutValue) then OutValue^ := tmp; end; procedure TPEImage.RegionRemove(RVA: TRVA; Size: uint32); begin // Currently it's just placeholder. // Mark memory as free. FSections.FillMemory(RVA, Size, $CC); end; function TPEImage.RegionExistsRaw(RVA: TRVA; RawSize: uint32): boolean; var Sec: TPESection; Ofs: uint32; begin if not RVAToSec(RVA, @Sec) then exit(false); Ofs := RVA - Sec.RVA; Result := Ofs + RawSize <= Sec.RawSize; end; function TPEImage.RegionExistsVirtual(RVA: TRVA; VirtSize: uint32): boolean; var Sec: TPESection; Ofs: uint32; begin if not RVAToSec(RVA, @Sec) then exit(false); Ofs := RVA - Sec.RVA; Result := Ofs + VirtSize <= Sec.VirtualSize; end; function TPEImage.ReadWrite(Buffer: Pointer; Count: cardinal; Read: boolean): uint32; begin // If count is 0 or no valid position was set we cannot do anything. if (Count = 0) or (not Assigned(FCurrentSec)) then exit(0); // Check how many bytes we can process. Result := Min(Count, FCurrentSec.AllocatedSize - FCurrentOfs); if Result = 0 then exit; if Assigned(Buffer) then begin if Read then Move(FCurrentSec.Mem[FCurrentOfs], Buffer^, Result) else Move(Buffer^, FCurrentSec.Mem[FCurrentOfs], Result); end; // Move next. inc(FPositionRVA, Result); inc(FCurrentOfs, Result); end; function TPEImage.Read(Buffer: Pointer; Count: cardinal): uint32; begin Result := ReadWrite(Buffer, Count, true); end; function TPEImage.Read(var Buffer; Count: cardinal): uint32; begin Result := Read(@Buffer, Count); end; function TPEImage.ReadEx(Buffer: Pointer; Count: cardinal): boolean; begin Result := Read(Buffer, Count) = Count; end; function TPEImage.ReadEx(var Buffer; Size: cardinal): boolean; begin Result := ReadEx(@Buffer, Size); end; function TPEImage.ReadAnsiString: string; var Len: integer; begin if not ReadAnsiStringLen(0, Len, Result) then Result := ''; end; function TPEImage.ReadAnsiStringLen(MaxLen: integer; out Len: integer; out Str: string): boolean; var available: uint32; pBegin, pCur, pEnd: PAnsiChar; begin Len := 0; Str := ''; Result := false; if not Assigned(FCurrentSec) then exit; available := FCurrentSec.AllocatedSize - FCurrentOfs; if (MaxLen <> 0) and (MaxLen < available) then available := MaxLen; pBegin := @FCurrentSec.Mem[FCurrentOfs]; pCur := pBegin; pEnd := pBegin + available; while pCur < pEnd do begin if pCur^ = #0 then begin Result := true; break; end; inc(pCur); end; Len := pCur - pBegin; if Result then begin // String. Str := string(pBegin); // Include null at end. inc(Len); // Move current position. inc(FPositionRVA, Len); inc(FCurrentOfs, Len); end; end; function TPEImage.ReadUnicodeStringLenPfx2: string; var Size: uint32; Bytes: TBytes; begin // Check if there is at least 2 bytes for length. if Assigned(FCurrentSec) and (FCurrentOfs + 2 <= FCurrentSec.AllocatedSize) then begin Size := ReadUInt16 * 2; if Size <> 0 then begin // Check if there is enough space to read string. if FCurrentOfs + Size <= FCurrentSec.AllocatedSize then begin SetLength(Bytes, Size); Read(Bytes[0], Size); Result := TEncoding.Unicode.GetString(Bytes); exit; end; end; end; exit(''); end; function TPEImage.ReadUInt8: UInt8; begin if not ReadUInt8(@Result) then DoReadError; end; function TPEImage.ReadUInt16: UInt16; begin if not ReadUInt16(@Result) then DoReadError; end; function TPEImage.ReadUInt32: uint32; begin if not ReadUInt32(@Result) then DoReadError; end; function TPEImage.ReadUInt64: UInt64; begin if not ReadUInt64(@Result) then DoReadError; end; function TPEImage.ReadUIntPE: UInt64; begin if not ReadUIntPE(@Result) then DoReadError; end; function TPEImage.ReadUInt8(OutData: PUInt8): boolean; begin Result := ReadEx(OutData, 1); end; function TPEImage.ReadUInt16(OutData: PUInt16): boolean; begin Result := ReadEx(OutData, 2); end; function TPEImage.ReadUInt32(OutData: PUInt32): boolean; begin Result := ReadEx(OutData, 4); end; function TPEImage.ReadUInt64(OutData: PUInt64): boolean; begin Result := ReadEx(OutData, 8); end; function TPEImage.ReadUIntPE(OutData: PUInt64): boolean; begin if OutData <> nil then OutData^ := 0; case ImageBits of 32: Result := ReadEx(OutData, 4); 64: Result := ReadEx(OutData, 8); else begin DoReadError; Result := false; // compiler friendly end; end; end; function TPEImage.Write(Buffer: Pointer; Count: cardinal): uint32; begin Result := ReadWrite(Buffer, Count, false); end; function TPEImage.Write(const Buffer; Count: cardinal): uint32; begin Result := Write(@Buffer, Count); end; function TPEImage.WriteEx(Buffer: Pointer; Count: cardinal): boolean; begin Result := Write(Buffer, Count) = Count; end; function TPEImage.WriteEx(const Buffer; Count: cardinal): boolean; begin Result := Write(@Buffer, Count) = Count; end; function TPEImage.RVAToMem(RVA: TRVA): Pointer; var Ofs: integer; s: TPESection; begin if RVAToSec(RVA, @s) and (s.Mem <> nil) then begin Ofs := RVA - s.RVA; exit(@s.Mem[Ofs]); end; exit(nil); end; function TPEImage.RVAExists(RVA: TRVA): boolean; begin Result := RVAToSec(RVA, nil); end; function TPEImage.RVAToOfs(RVA: TRVA; OutOfs: PDword): boolean; begin Result := FSections.RVAToOfs(RVA, OutOfs); end; function TPEImage.RVAToSec(RVA: TRVA; OutSec: PPESection): boolean; begin Result := FSections.RVAToSec(RVA, OutSec); end; function TPEImage.RVAToVA(RVA: TRVA): UInt64; begin Result := RVA + FOptionalHeader.ImageBase; end; function TPEImage.VAExists(VA: TRVA): boolean; begin Result := (VA >= ImageBase) and RVAToSec(VAToRVA(VA), nil); end; function TPEImage.VAToMem(VA: TVA): Pointer; begin Result := RVAToMem(VAToRVA(VA)); end; function TPEImage.VAToOfs(VA: TVA; OutOfs: PDword): boolean; begin Result := (VA >= ImageBase) and RVAToOfs(VAToRVA(VA), OutOfs); end; function TPEImage.VAToSec(VA: TRVA; OutSec: PPESection): boolean; begin Result := (VA >= ImageBase) and RVAToSec(VAToRVA(VA), OutSec); end; function TPEImage.VAToRVA(VA: TVA): TRVA; begin if VA >= FOptionalHeader.ImageBase then Result := VA - FOptionalHeader.ImageBase else raise Exception.Create('VAToRVA: VA argument must be >= ImageBase.'); end; function TPEImage.LoadFromFile(const AFileName: string; AParseStages: TParserFlags): boolean; var fs: TFileStream; begin if not FileExists(AFileName) then begin FMsg.Write(SCategoryLoadFromFile, 'File not found.'); exit(false); end; fs := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try FFileName := AFileName; fs.Position := 0; Result := LoadFromStream(fs, AParseStages); finally fs.Free; end; end; function TPEImage.LoadFromMappedImage(const AFileName: string; AParseStages: TParserFlags): boolean; begin FPEMemoryStream := TPEMemoryStream.Create(AFileName); Result := LoadFromStream(FPEMemoryStream, AParseStages, PEIMAGE_KIND_MEMORY); end; function TPEImage.LoadFromMappedImage(ModuleBase: NativeUInt; AParseStages: TParserFlags): boolean; begin FPEMemoryStream := TPEMemoryStream.Create(ModuleBase); Result := LoadFromStream(FPEMemoryStream, AParseStages, PEIMAGE_KIND_MEMORY); end; function TPEImage.LoadFromProcessImage(ProcessId: DWORD; Address: NativeUInt; AParseStages: TParserFlags): boolean; var Stream: TProcessModuleStream; begin Stream := TProcessModuleStream.CreateFromPidAndAddress(ProcessId, Address); try Result := LoadFromStream(Stream, AParseStages, PEIMAGE_KIND_MEMORY); finally Stream.Free; end; end; function TPEImage.LoadFromStream(AStream: TStream; AParseStages: TParserFlags; ImageKind: TPEImageKind): boolean; const PE_HEADER_ALIGN = 4; var OptHdrOfs, DataDirOfs, SecHdrOfs, SecHdrEndOfs, SecDataOfs: TFileOffset; SecHdrGapSize: integer; OptHdrSizeRead: int32; // w/o directories Stage: TParserFlag; Parser: TPEParser; Signature: TNTSignature; DOSBlockSize: uint32; begin Result := false; FImageKind := ImageKind; FFileSize := AStream.Size; FParseStages := AParseStages; // DOS header. if not LoadDosHeader(AStream, FDosHeader) then begin Msg.Write(SCategoryDOSHeader, 'No DOS header found.'); exit; end; if (FDosHeader.e_lfanew = 0) then begin Msg.Write(SCategoryDOSHeader, 'This is probably 16-bit executable.'); exit; end; // Check PE ofs < 256 MB (see RtlImageNtHeaderEx) if (FDosHeader.e_lfanew >= 256 * 1024 * 1024) then begin Msg.Write(SCategoryDOSHeader, 'e_lfanew >= 256 MB'); exit; end; if (FDosHeader.e_lfanew mod PE_HEADER_ALIGN) <> 0 then begin Msg.Write(SCategoryDOSHeader, 'PE header is not properly aligned.'); exit; end; if (FDosHeader.e_lfanew < SizeOf(TImageDOSHeader)) then begin Msg.Write(SCategoryDOSHeader, 'e_lfanew points into itself (0x%x)', [FDosHeader.e_lfanew]); end; // Check if e_lfanew is ok if not StreamSeek(AStream, FDosHeader.e_lfanew) then exit; // e_lfanew is wrong // @ e_lfanew // Store offset of NT headers. FLFANew := FDosHeader.e_lfanew; // Read DOS Block self.FDosBlock := nil; if FDosHeader.e_lfanew > SizeOf(FDosHeader) then begin DOSBlockSize := FDosHeader.e_lfanew - SizeOf(FDosHeader); SetLength(self.FDosBlock, DOSBlockSize); if (DOSBlockSize <> 0) then if StreamSeek(AStream, SizeOf(FDosHeader)) then begin if not StreamRead(AStream, self.FDosBlock[0], DOSBlockSize) then SetLength(self.FDosBlock, 0); end; end; // Go back to new header. if not StreamSeek(AStream, FDosHeader.e_lfanew) then exit; // e_lfanew is wrong // Load signature. if not StreamRead(AStream, Signature, SizeOf(Signature)) then exit; // Check signature. if not Signature.IsPE00 then exit; // not PE file // Load File Header. if not LoadFileHeader(AStream, FFileHeader) then exit; // File Header failed. // Get offsets of Optional Header and Section Headers. OptHdrOfs := AStream.Position; SecHdrOfs := OptHdrOfs + FFileHeader.SizeOfOptionalHeader; SecHdrEndOfs := SecHdrOfs + SizeOf(TImageSectionHeader) * FFileHeader.NumberOfSections; // Read opt.hdr. magic to know if image is 32 or 64 bit. AStream.Position := OptHdrOfs; if not StreamPeek(AStream, FOptionalHeader.Magic, SizeOf(FOptionalHeader.Magic)) then exit; // Set some helper fields. case FOptionalHeader.Magic of PE_MAGIC_PE32: begin FImageBitSize := 32; FImageWordSize := 4; end; PE_MAGIC_PE32PLUS: begin FImageBitSize := 64; FImageWordSize := 8; end else raise Exception.Create('Image type is unknown.'); end; // Safe read optional header. OptHdrSizeRead := FOptionalHeader.ReadFromStream(AStream, FImageBitSize, -1); // Can't read more bytes then available. if OptHdrSizeRead > FFileHeader.SizeOfOptionalHeader then raise Exception.Create('Read size of opt. header > FileHeader.SizeOfOptionalHeader'); DataDirOfs := AStream.Position; // Load Section Headers. AStream.Position := SecHdrOfs; if not LoadSectionHeaders(AStream) then exit; // Add header as a section. // LoadingAddHeaderAsASection(AStream); // Read data directories. if OptHdrSizeRead <> 0 then begin AStream.Position := DataDirOfs; FDataDirectories.LoadDirectoriesFromStream(AStream, Msg, FOptionalHeader.NumberOfRvaAndSizes, // declared count FFileHeader.SizeOfOptionalHeader - OptHdrSizeRead // bytes left in optional header ); end; // Mapped image can't have overlay, so correct total size. if FImageKind = PEIMAGE_KIND_MEMORY then FFileSize := CalcRawSizeOfImage; // Read COFF. FCOFF.LoadFromStream(AStream); // Convert /%num% section names to long names if possible. ResolveSectionNames; // Read Gap after Section Header. if FSections.Count <> 0 then begin SecDataOfs := FSections.First.RawOffset; if SecDataOfs >= SecHdrEndOfs then begin SecHdrGapSize := SecDataOfs - SecHdrEndOfs; SetLength(self.FSecHdrGap, SecHdrGapSize); if SecHdrGapSize <> 0 then begin AStream.Position := SecHdrEndOfs; AStream.Read(self.FSecHdrGap[0], SecHdrGapSize); end; end; end; Result := true; // Load section data. LoadSectionData(AStream); // Now base headers loaded. // Define regions loaded before. // Execute parsers. if AParseStages <> [] then begin for Stage in AParseStages do if Assigned(FParsers[Stage]) then begin Parser := FParsers[Stage].Create(self); try case Parser.Parse of PR_ERROR: Msg.Write('[%s] Parser returned error.', [Parser.ToString]); PR_SUSPICIOUS: Msg.Write('[%s] Parser returned status SUSPICIOUS.', [Parser.ToString]); end; finally Parser.Free; end; end; end; end; procedure TPEImage.LoadingAddHeaderAsASection(Stream: TStream); var sh: TImageSectionHeader; Sec: TPESection; oldPos: int64; begin oldPos := Stream.Position; try sh.Clear; sh.Name := 'header'; sh.SizeOfRawData := FOptionalHeader.SizeOfHeaders; sh.VirtualSize := AlignUp(FOptionalHeader.SizeOfHeaders, FOptionalHeader.SectionAlignment); Sec := TPESection(TPESectionImageHeader.Create(sh, nil)); FSections.Insert(0, Sec); Stream.Position := 0; Stream.Read(Sec.Mem^, sh.SizeOfRawData); finally Stream.Position := oldPos; end; end; function TPEImage.SaveToStream(AStream: TStream): boolean; begin Result := PE.Image.Saving.SaveImageToStream(self, AStream); end; function TPEImage.SaveToFile(const AFileName: string): boolean; var fs: TFileStream; begin fs := TFileStream.Create(AFileName, fmCreate); try Result := SaveToStream(fs); finally fs.Free; end; end; function TPEImage.GetOptionalHeader: PPEOptionalHeader; begin Result := @self.FOptionalHeader; end; function TPEImage.GetOverlay: POverlay; var lastSec: TPESection; begin lastSec := GetLastSectionWithValidRawData; if (lastSec <> nil) then begin FOverlay.Offset := lastSec.GetEndRawOffset; // overlay offset // Check overlay offet present in file. if FOverlay.Offset < FFileSize then begin FOverlay.Size := FFileSize - FOverlay.Offset; exit(@FOverlay); end; end; exit(nil); end; function TPEImage.GetLastSectionWithValidRawData: TPESection; var i: integer; begin for i := FSections.Count - 1 downto 0 do if (FSections[i].RawOffset <> 0) and (FSections[i].RawSize <> 0) then exit(FSections[i]); exit(nil); end; function TPEImage.SaveOverlayToFile(const AFileName: string; Append: boolean = false): boolean; var src, dst: TStream; ovr: POverlay; begin Result := false; ovr := GetOverlay; if Assigned(ovr) then begin // If no overlay, we're done. if ovr^.Size = 0 then exit(true); try src := SourceStreamGet(fmOpenRead or fmShareDenyWrite); if Append and FileExists(AFileName) then begin dst := TFileStream.Create(AFileName, fmOpenReadWrite or fmShareDenyWrite); dst.Seek(0, soFromEnd); end else dst := TFileStream.Create(AFileName, fmCreate); try src.Seek(ovr^.Offset, TSeekOrigin.soBeginning); dst.CopyFrom(src, ovr^.Size); Result := true; finally SourceStreamFree(src); dst.Free; end; except end; end; end; function TPEImage.RemoveOverlay: boolean; var ovr: POverlay; fs: TFileStream; begin Result := false; if FImageKind = PEIMAGE_KIND_MEMORY then begin FMsg.Write('Can''t remove overlay from mapped image.'); exit; end; ovr := GetOverlay; if (ovr <> nil) and (ovr^.Size <> 0) then begin try fs := TFileStream.Create(FFileName, fmOpenWrite or fmShareDenyWrite); try fs.Size := fs.Size - ovr^.Size; // Trim file. self.FFileSize := fs.Size; // Update filesize. Result := true; finally fs.Free; end; except end; end; end; function TPEImage.LoadOverlayFromFile(const AFileName: string; Offset, Size: UInt64): boolean; var ovr: POverlay; fs: TFileStream; src: TStream; newImgSize: uint32; begin Result := false; if FImageKind = PEIMAGE_KIND_MEMORY then begin FMsg.Write('Can''t append overlay to mapped image.'); exit; end; fs := TFileStream.Create(FFileName, fmOpenWrite or fmShareDenyWrite); src := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try if (Offset = 0) and (Size = 0) then Size := src.Size; if Size <> 0 then begin if (Offset + Size) > src.Size then exit(false); src.Position := Offset; ovr := GetOverlay; if (ovr <> nil) and (ovr^.Size <> 0) then fs.Size := fs.Size - ovr^.Size // Trim file. else begin newImgSize := CalcRawSizeOfImage(); fs.Size := newImgSize; end; fs.Position := fs.Size; fs.CopyFrom(src, Size); self.FFileSize := fs.Size; // Update filesize. end; Result := true; finally src.Free; fs.Free; end; end; end.
unit trtm_main; interface uses trtm_types, trtm_table, sysutils; type TTRTMProblem = class(TObject) private fproblem : TTRTM_Object_Analysis; function FindMethods ( obj_num : word; obj : word; bad : word; Var met : TPTRTM_Methods_Cell ): integer; function MarkUsedMethods : integer; function ShowAllMethods : string; function ShowPopularMethods : string; function ShowPopularMethodsContent : string; public constructor Create; destructor Destroy; override; procedure Clean; function ProcessTask( obj : word; bobj : TTRTM_Objects_Set ) : integer; published property AllMethods : string read ShowAllMethods; property PopularMethods : string read ShowPopularMethods; property PopularMethodsContent : string read ShowPopularMethodsContent; property Problem : TTRTM_Object_Analysis read fproblem; end; implementation constructor TTRTMProblem.Create; begin Clean; end; destructor TTRTMProblem.Destroy; begin Clean; end; //******************************************************************************* // ProcessTask // //******************************************************************************* function TTRTMProblem.ProcessTask( obj : word; bobj : TTRTM_Objects_Set ) : integer; Var cnt, len : word; res : integer; met : TTRTM_Methods_Cell; pmet : TPTRTM_Methods_Cell; metn : word; begin Clean; fproblem.obj_id := obj; fproblem.all := nil; fproblem.bobj_ids := nil; len := length( bobj ); SetLength( fproblem.bobj_ids, len ); Result := -1; if len = 0 then Exit; pmet := @met; // Copy all modified properties to the fproblem.bobj_ids[] array // and fill fproblem.all[][1..4] with methods. for cnt := 0 to len-1 do begin fproblem.bobj_ids[cnt] := bobj[cnt]; res := FindMethods( 0, obj, bobj[cnt], pmet ); if ( res = 0 ) then begin SetLength( fproblem.all, length( fproblem.all ) + 1 ); for metn := 1 to MAX_METHODS_PER_CELL do begin fproblem.all[cnt][metn] := met[metn]; end; end; end; MarkUsedMethods; end; // ProcessTask //******************************************************************************* // FindMethods - 04/14/2005 12:25 // //******************************************************************************* function TTRTMProblem.FindMethods ( obj_num : word; obj : word; bad : word; Var met : TPTRTM_Methods_Cell ): integer; Var cnt : word; begin for cnt := 1 to MAX_METHODS_PER_CELL do met[cnt] := trtm_main_table[ obj ].sol[ bad ][cnt]; Result := 0; end; // FindMethods //******************************************************************************* // MarkUsedMethods - 04/14/2005 1:04 // Parameters: // // Result: // // Notes: // //******************************************************************************* function TTRTMProblem.MarkUsedMethods : integer; Var len, metn, cnt : word; begin Result := 0; len := length( fproblem.all ); if ( len = 0 ) then begin Exit; end; for cnt := 0 to len-1 do begin for metn := 1 to MAX_METHODS_PER_CELL do begin if ( fproblem.all[cnt][metn] <> 0 ) then inc(fproblem.unique[fproblem.all[cnt][metn]]); end; end; Result := 0; end; // MarkUsedMethods function TTRTMProblem.ShowAllMethods : string; Var cnt, bcnt, blen : word; need_comma : boolean; begin Result := ''; need_comma := False; blen := length( fproblem.all ); if blen = 0 then Exit; for bcnt := 0 to blen-1 do begin Result := Result + '(' + IntToStr(fproblem.bobj_ids[bcnt]) + ')'; for cnt := 1 to MAX_METHODS_PER_CELL do begin if fproblem.all[bcnt][cnt] > 0 then begin if need_comma then Result := Result + ', ' else need_comma := True; Result := Result + IntToStr( fproblem.all[bcnt][cnt] ); end; end; Result := Result + '; '; need_comma := False; end; end; // Этот метод возвращает список и расшифровку всех // методов, которые встречаются хотя-бы 1 раз. function TTRTMProblem.ShowPopularMethodsContent : string; Var cnt : word; begin Result := ''; if fproblem.all = nil then Exit; for cnt := 1 to MAX_METHODS do begin if ( fproblem.unique[cnt] >= 1 ) then begin if Result <> '' then Result := Result + #13#10 + #13#10; Result := Result + IntToStr(cnt) + '. ' + trtm_methods_txt[cnt].mname + #13#10 + trtm_methods_txt[cnt].mexample1; end; end; end; // Этот метод возвращает список всех // методов, которые встречаются более 1 раза!!! function TTRTMProblem.ShowPopularMethods : string; Var cnt : word; begin Result := ''; if fproblem.all = nil then Exit; for cnt := 1 to MAX_METHODS do begin if ( fproblem.unique[cnt] > 1 ) then begin if Result <> '' then Result := Result + ', ' + IntToStr( cnt ) else Result := IntToStr( cnt ); end; end; end; procedure TTRTMProblem.Clean; Var cnt : word; begin // release the memory taken for problems and methods fproblem.all := nil; fproblem.bobj_ids := nil; // clear popularity of methods for cnt := 1 to MAX_METHODS do fproblem.unique[cnt] := 0; end; end.
unit GifImgs; { Exports TGifImage component. See also the unit GifUnit.pas. by Reinier Sterkenburg (August 1997) r.p.sterkenburg@dataweb.nl www.dataweb.nl/~r.p.sterkenburg 24 Jul 97: - Added Register procedure - Added a property StartImmediately (default False; at design time animation probably not wanted) - Added procedure AnimateOnce (which works through extra boolean field NoRepeat 2 Aug 97: - Added LoadFromBmpfile and SaveToFile } interface uses Classes, { Imports TComponent } ColorTbl, { Imports TColorTable } DynArrB, { Imports TByteArray2D } ExtCtrls, { Imports TImage } Forms, { Imports Application } GifUnit, { Imports TGifFile } Graphics; { Imports TBitmap } type TGifImage = class(TImage) private Freeing: Boolean; NoRepeat: Boolean; FGifFile: TGifFile; FTimer: TTimer; FCurrSubImageNo: Integer; FStartImmediately: Boolean; destructor Destroy; override; procedure NextImage; procedure NextImageEvent(Sender: TObject); function GetAnimating: Boolean; procedure SetAnimating(NewValue: Boolean); public constructor Create(AnOwner: TComponent); override; procedure AnimateOnce; procedure LoadFromGifFile(GifFilename: String); procedure LoadFromBmpFile(BmpFilename: String); procedure SaveToFile(Filename: String); procedure Slower; property Animating: Boolean read GetAnimating write SetAnimating; published property StartImmediately: Boolean read FStartImmediately write FStartImmediately default False; end; { TGifImage } procedure Register; implementation procedure Register; begin RegisterComponents('Additional', [TGifImage]) end; constructor TGifImage.Create(AnOwner: TComponent); begin { TGifImage.Create } inherited Create(AnOwner); FTimer := TTimer.Create(Self); FTimer.Enabled := False; FTimer.OnTimer := NextImageEvent; Freeing := False; FStartImmediately := False; NoRepeat := False; end; { TGifImage.Create } destructor TGifImage.Destroy; begin { TGifImage.Destroy } FTimer.Enabled := False; FTimer.Free; FGifFile.Free; inherited Destroy; end; { TGifImage.Destroy } procedure TGifImage.AnimateOnce; begin { TGifImage.AnimateOnce } if not NoRepeat then begin NoRepeat := True; Animating := True; end; end; { TGifImage.AnimateOnce } procedure TGifImage.NextImageEvent(Sender: TObject); begin { TGifImage.NextImageEvent } if not Freeing then NextImage; end; { TGifImage.NextImageEvent } procedure TGifImage.NextImage; var SubImage: TGifSubImage; begin { TGifImage.NextImage } Inc(FCurrSubImageNo); if FCurrSubImageNo > FGifFile.SubImages.Count then begin FCurrSubImageNo := 1; if NoRepeat then begin Animating := False; NoRepeat := False; end; end; SubImage := FGifFile.GetSubImage(FCurrSubImageNo); if FCurrSubImageNo = 1 then Picture.Bitmap := SubImage.AsBitmap else with SubImage.ImageDescriptor do Picture.BitMap.Canvas.Draw (ImageLeftPos, ImageTopPos, SubImage.AsBitmap); end; { TGifImage.NextImage } procedure TGifImage.LoadFromBmpFile(BmpFilename: String); var Bitmap: TBitmap; Colormap: TColorTable; Pixels: TByteArray2D; begin { TGifImage.LoadFromBmpFile } Freeing := True; Application.ProcessMessages; FGifFile.Free; FGifFile := TGifFile.Create; Bitmap := TBitmap.Create; Bitmap.LoadFromFile(BmpFilename); Picture.Bitmap := Bitmap; BitmapToPixelmatrix(Bitmap, Colormap, Pixels); FGifFile.AddSubImage(Colormap, Pixels); Freeing := False; end; { TGifImage.LoadFromBmpFile } procedure TGifImage.LoadFromGifFile(GifFilename: String); begin { TGifImage.LoadFromGifFile } Freeing := True; Application.ProcessMessages; FGifFile.Free; FGifFile := TGifFile.Create; FCurrSubImageNo := 1; FGifFile.LoadFromFile(GifFilename); FTimer.Enabled := False; if FGifFile.SubImages.Count <> 1 then begin FTimer.Interval := FGifFile.AnimateInterval*10; if StartImmediately then FTimer.Enabled := True; end; Picture.Bitmap := FGifFile.GetSubImage(FCurrSubImageNo).AsBitmap; Freeing := False; end; { TGifImage.LoadFromGifFile } procedure TGifImage.SaveToFile(Filename: String); begin { TGifImage.SaveToFile } FGifFile.SaveToFile(Filename) end; { TGifImage.SaveToFile } procedure TGifImage.Slower; begin { TGifImage.Slower } FTimer.Interval := FTimer.Interval * 2; end; { TGifImage.Slower } function TGifImage.GetAnimating: Boolean; begin { TGifImage.GetAnimating } Result := FTimer.Enabled; end; { TGifImage.GetAnimating } procedure TGifImage.SetAnimating(NewValue: Boolean); begin { TGifImage.SetAnimating } if FTimer.Enabled <> NewValue then FTimer.Enabled := NewValue end; { TGifImage.SetAnimating } end. { unit GifImgs }
unit TextureAtlasExtractorIDC; interface uses TextureAtlasExtractorBase, TextureAtlasExtractorOrigami, BasicMathsTypes, BasicDataTypes, NeighborDetector, MeshPluginBase, VertexTransformationUtils, NeighborhoodDataPlugin, IntegerList, OrderedWeightList; {$INCLUDE source/Global_Conditionals.inc} type CTextureAtlasExtractorIDC = class (CTextureAtlasExtractorOrigami) const C_MIN_ANGLE = pi / 6; C_HALF_MIN_ANGLE = C_MIN_ANGLE / 2; C_MAX_ANGLE = pi - (2 * C_MIN_ANGLE); C_IDEAL_ANGLE = pi / 3; C_MIN_TO_IDEAL_ANGLE_INTERVAL = C_IDEAL_ANGLE - C_MIN_ANGLE; C_IDEAL_TO_MAX_ANGLE_INTERVAL = C_MAX_ANGLE - C_IDEAL_ANGLE; protected FPriorityList: COrderedWeightList; FFaceList, FPreviousFaceList: auint32; FBorderEdges, FBorderEdgesMap: aint32; FBorderEdgeCounter: integer; FMeshAngleCount, FParamAngleCount: afloat; FVertNeighborsLeft: auint32; FAngleFactor: afloat; FMeshAng0, FMeshAng1, FMeshAngTarget, FUVAng0, FUVAng1, FUVAngTarget: single; // Execute function GetTexCoords(_MeshID: integer; var _Vertices : TAVector3f; var _FaceNormals,_VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces: auint32; var _Opposites : aint32; _VerticesPerFace: integer; var _Seeds: TSeedSet; var _VertsSeed : aint32; var _NeighborhoodPlugin: PMeshPluginBase): TAVector2f; // Seed creation function GetNewSeed(_ID,_MeshID,_StartingFace: integer; var _Vertices : TAVector3f; var _FaceNormals, _VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32; var _Opposites: aint32; var _TextCoords: TAVector2f; var _FaceSeeds,_VertsSeed: aint32; const _FaceNeighbors: TNeighborDetector; var _NeighborhoodPlugin: PMeshPluginBase; _VerticesPerFace,_MaxVerts: integer; var _CheckFace: abool): TTextureSeed; overload; procedure BuildFirstTriangle(_ID,_MeshID,_StartingFace: integer; var _Vertices : TAVector3f; var _FaceNormals, _VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32; const _Opposites: aint32; var _TextCoords: TAVector2f; var _FaceSeeds,_VertsSeed: aint32; _VerticesPerFace: integer; var _VertexUtil: TVertexTransformationUtils; var _TextureSeed: TTextureSeed; var _FaceEdgeCounter: auint32; const _CheckFace: abool); reintroduce; procedure ObtainCommonEdgeFromFaces(var _Faces: auint32; var _Opposites: aint32; const _VerticesPerFace,_CurrentFace,_PreviousFace: integer; var _CurrentVertex,_PreviousVertex,_CommonVertex1,_CommonVertex2,_inFaceCurrVertPosition: integer); reintroduce; procedure AddNeighborFaces(_CurrentFace: integer; var _FaceEdgeCounter: auint32; const _Faces: auint32; const _Opposites: aint32; var _TextCoords: TAVector2f; const _FaceSeeds: aint32; const _CheckFace: abool; _VerticesPerFace: integer); procedure AssignVertex(_VertexID, _SeedID: integer; _U, _V: single; var _TextCoords: TAVector2f; var _VertsSeed: aint32; var _TextureSeed: TTextureSeed); procedure CloneVertex(_VertexID, _SeedID, _FaceIndex: integer; _U, _V: single; var _TextCoords: TAVector2f; var _VertsSeed: aint32; var _TextureSeed: TTextureSeed; var _Vertices : TAVector3f; var _VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32); procedure UpdateBorderEdges(_CurrentFace: integer; const _Faces: auint32; const _Opposites: aint32; _VerticesPerFace: integer); procedure UpdateAngleCount(_Edge0, _Edge1, _Target: integer); function IsValidUVPoint(const _Vertices: TAVector3f; const _Faces : auint32; var _TexCoords: TAVector2f; _Target,_Edge0,_Edge1,_OriginVert: integer; var _CheckFace: abool; var _UVPosition: TVector2f; _CurrentFace, _PreviousFace, _VerticesPerFace: integer): boolean; override; function IsValidUVTriangle(const _Faces : auint32; const _Opposites: aint32; var _TexCoords: TAVector2f; const _Vertices: TAVector3f; _Target,_Edge0,_Edge1,_OriginVert: integer; var _CheckFace: abool; _CurrentFace, _PreviousFace, _VerticesPerFace: integer): boolean; reintroduce; // Aux functions function GetDistortionFactor(_ID:integer; _Angle: single): single; procedure GetAnglesFromCoordinates(const _Vertices: TAVector3f; _Edge0, _Edge1, _Target: integer); public procedure ExecuteWithDiffuseTexture(_Size: integer); override; end; implementation uses GlobalVars, TextureGeneratorBase, DiffuseTextureGenerator, MeshBRepGeometry, GLConstants, ColisionCheck, BasicFunctions, HalfEdgePlugin, math3d, math, MeshCurvatureMeasure, SysUtils; procedure CTextureAtlasExtractorIDC.ExecuteWithDiffuseTexture(_Size: integer); var i : integer; Seeds: TSeedSet; VertsSeed : TInt32Map; TexGenerator: CTextureGeneratorBase; NeighborhoodPlugin, HalfEdgePlugin: PMeshPluginBase; begin // First, we'll build the texture atlas. SetLength(VertsSeed,High(FLOD.Mesh)+1); SetLength(Seeds,0); TexGenerator := CDiffuseTextureGenerator.Create(FLOD,_Size,0,0); for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin SetLength(VertsSeed[i],0); NeighborhoodPlugin := FLOD.Mesh[i].GetPlugin(C_MPL_NEIGHBOOR); if NeighborhoodPlugin = nil then begin FLOD.Mesh[i].AddNeighborhoodPlugin; NeighborhoodPlugin := FLOD.Mesh[i].GetPlugin(C_MPL_NEIGHBOOR); end; HalfEdgePlugin := FLOD.Mesh[i].GetPlugin(C_MPL_HALFEDGE); if HalfEdgePlugin = nil then begin FLOD.Mesh[i].AddHalfEdgePlugin; HalfEdgePlugin := FLOD.Mesh[i].GetPlugin(C_MPL_HALFEDGE); end; FLOD.Mesh[i].Geometry.GoToFirstElement; FLOD.Mesh[i].TexCoords := GetTexCoords(i,FLOD.Mesh[i].Vertices,(FLOD.Mesh[i].Geometry.Current^ as TMeshBRepGeometry).Normals,FLOD.Mesh[i].Normals,FLOD.Mesh[i].Colours,(FLOD.Mesh[i].Geometry.Current^ as TMeshBRepGeometry).Faces,(HalfEdgePlugin^ as THalfEdgePlugin).Opposites,(FLOD.Mesh[i].Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,Seeds,VertsSeed[i],NeighborhoodPlugin); if NeighborhoodPlugin <> nil then begin TNeighborhoodDataPlugin(NeighborhoodPlugin^).DeactivateQuadFaces; end; end; MergeSeeds(Seeds); for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin GetFinalTextureCoordinates(Seeds,VertsSeed[i],FLOD.Mesh[i].TexCoords); end; // Now we build the diffuse texture. TexGenerator.Execute(); // Free memory. for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do begin SetLength(VertsSeed[i],0); end; SetLength(VertsSeed,0); TexGenerator.Free; end; function CTextureAtlasExtractorIDC.GetTexCoords(_MeshID: integer; var _Vertices : TAVector3f; var _FaceNormals,_VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces: auint32; var _Opposites : aint32; _VerticesPerFace: integer; var _Seeds: TSeedSet; var _VertsSeed : aint32; var _NeighborhoodPlugin: PMeshPluginBase): TAVector2f; const C_2PI = 2 * pi; var i, MaxVerts, NumSeeds, ExpectedMaxFaces: integer; FaceSeed : aint32; FacePriority: AFloat; FaceOrder : auint32; CheckFace: abool; FaceNeighbors: TNeighborDetector; Tool: TMeshCurvatureMeasure; {$ifdef ORIGAMI_TEST} Temp: string; {$endif} begin SetupMeshSeeds(_Vertices,_FaceNormals,_Faces,_VerticesPerFace,_Seeds,_VertsSeed,FaceNeighbors,Result,MaxVerts,FaceSeed,FacePriority,FaceOrder,CheckFace); ExpectedMaxFaces := ((High(CheckFace)+1) * 2) + 1; SetLength(FFaceList, ExpectedMaxFaces); SetLength(FPreviousFaceList, ExpectedMaxFaces); FPriorityList := COrderedWeightList.Create; FPriorityList.SetRAMSize(ExpectedMaxFaces); // Calculate the remaining angle left for each vertex in the mesh and locally. Tool := TMeshCurvatureMeasure.Create; SetLength(FMeshAngleCount, High(_Vertices)+1); SetLength(FParamAngleCount, High(_Vertices)+1); SetLength(FVertNeighborsLeft, High(_Vertices)+1); SetLength(FAngleFactor, High(_Vertices)+1); for i := Low(FMeshAngleCount) to High(FMeshAngleCount) do begin FParamAngleCount[i] := C_2PI; FMeshAngleCount[i] := Tool.GetVertexAngleSum(i, _Vertices, _VertsNormals, (_NeighborhoodPlugin^ as TNeighborhoodDataPlugin).VertexNeighbors); FVertNeighborsLeft[i] := (_NeighborhoodPlugin^ as TNeighborhoodDataPlugin).VertexNeighbors.GetNumNeighbors(i); FAngleFactor[i] := Tool.GetVertexAngleSumFactor(FMeshAngleCount[i]); end; Tool.Free; // Let's build the seeds. NumSeeds := High(_Seeds)+1; SetLength(_Seeds,NumSeeds + High(FaceSeed)+1); for i := Low(FaceSeed) to High(FaceSeed) do begin if FaceSeed[FaceOrder[i]] = -1 then begin // Make new seed. {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Seed = ' + IntToStr(NumSeeds) + ' and i = ' + IntToStr(i)); {$endif} _Seeds[NumSeeds] := GetNewSeed(NumSeeds,_MeshID,FaceOrder[i],_Vertices,_FaceNormals,_VertsNormals,_VertsColours,_Faces,_Opposites,Result,FaceSeed,_VertsSeed,FaceNeighbors,_NeighborhoodPlugin,_VerticesPerFace,MaxVerts,CheckFace); inc(NumSeeds); end; end; SetLength(_Seeds,NumSeeds); // Re-align vertexes and seed bounds to start at (0,0) ReAlignSeedsToCenter(_Seeds,_VertsSeed,FaceNeighbors,Result,FacePriority,FaceOrder,CheckFace,_NeighborhoodPlugin); // Clear memory SetLength(FaceSeed, 0); SetLength(FacePriority, 0); SetLength(FaceOrder, 0); SetLength(CheckFace, 0); SetLength(FFaceList, 0); SetLength(FPreviousFaceList, 0); FPriorityList.Free; SetLength(FMeshAngleCount, 0); SetLength(FParamAngleCount, 0); SetLength(FVertNeighborsLeft, 0); SetLength(FAngleFactor, 0); end; function CTextureAtlasExtractorIDC.GetNewSeed(_ID,_MeshID,_StartingFace: integer; var _Vertices : TAVector3f; var _FaceNormals, _VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32; var _Opposites: aint32; var _TextCoords: TAVector2f; var _FaceSeeds,_VertsSeed: aint32; const _FaceNeighbors: TNeighborDetector; var _NeighborhoodPlugin: PMeshPluginBase; _VerticesPerFace,_MaxVerts: integer; var _CheckFace: abool): TTextureSeed; var Index,v,f,i,imax,Value,FaceIndex,PreviousFace : integer; CurrentVertex,PreviousVertex,SharedEdge0,SharedEdge1: integer; found: boolean; VertexUtil : TVertexTransformationUtils; CandidateUVPosition: TVector2f; FaceBackup: auint32; FaceEdgeCounter: auint32; {$ifdef ORIGAMI_TEST} Temp: string; {$endif} begin VertexUtil := TVertexTransformationUtils.Create; SetLength(FaceBackup,_VerticesPerFace); // Setup VertsLocation SetLength(FVertsLocation,High(_Vertices)+1); for v := Low(FVertsLocation) to High(FVertsLocation) do begin FVertsLocation[v] := -1; end; // Setup neighbor detection list // Avoid unlimmited loop SetLength(FaceEdgeCounter, High(_CheckFace) + 1); for f := Low(_CheckFace) to High(_CheckFace) do begin _CheckFace[f] := false; FFaceList[f] := 0; FPreviousFaceList[f] := 0; FaceEdgeCounter[f] := 0; end; // Setup the edge descriptor from the Seed (Chart), for collision detection. FBorderEdgeCounter := 0; SetLength(FBorderEdges, High(_Faces) + 1); SetLength(FBorderEdgesMap, High(_Faces) + 1); for f := Low(_Faces) to High(_Faces) do begin FBorderEdges[f] := -1; FBorderEdgesMap[f] := -1; end; // Add starting face {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Starting Face of the seed is ' + IntToStr(_StartingFace)); {$endif} _FaceSeeds[_StartingFace] := _ID; _CheckFace[_StartingFace] := true; Result.MinBounds.U := 999999; Result.MaxBounds.U := -999999; Result.MinBounds.V := 999999; Result.MaxBounds.V := -999999; Result.MeshID := _MeshID; BuildFirstTriangle(_ID, _MeshID, _StartingFace, _Vertices, _FaceNormals, _VertsNormals, _VertsColours, _Faces, _Opposites, _TextCoords, _FaceSeeds, _VertsSeed, _VerticesPerFace, VertexUtil, Result, FaceEdgeCounter, _CheckFace); // Neighbour Face Scanning starts here. // Wel'll check face by face and add the vertexes that were not added Index := FPriorityList.GetFirstElement; while Index <> -1 do begin FPriorityList.Delete(Index); Value := FFaceList[Index]; PreviousFace := FPreviousFaceList[Index]; if not _CheckFace[Value] then begin // Backup current face just in case the face gets rejected FaceIndex := Value * _VerticesPerFace; v := 0; while v < _VerticesPerFace do begin FaceBackup[v] := _Faces[FaceIndex + v]; inc(v); end; {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Veryfing Face ' + IntToStr(Value) + ' <' + IntToStr(_Faces[FaceIndex]) + ', ' + IntToStr(_Faces[FaceIndex + 1]) + ', ' + IntToStr(_Faces[FaceIndex + 2]) + '> that was added by previous face ' + IntToStr(PreviousFace)); {$endif} // The first idea is to get the vertex that wasn't added yet. ObtainCommonEdgeFromFaces(_Faces,_Opposites,_VerticesPerFace,Value,PreviousFace,CurrentVertex,PreviousVertex,SharedEdge0,SharedEdge1,v); {$ifdef ORIGAMI_TEST} Temp := 'VertsSeed = ['; for i := Low(_VertsSeed) to High(_VertsSeed) do begin Temp := Temp + IntToStr(_VertsSeed[i]) + ' '; end; Temp := Temp + ']'; GlobalVars.OrigamiFile.Add(Temp); GlobalVars.OrigamiFile.Add('Current Vertex = ' + IntToStr(CurrentVertex) + '; Previous Vertex = ' + IntToStr(PreviousVertex) + '; Share Edge = [' + IntToStr(SharedEdge0) + ', ' + IntToStr(SharedEdge1) + ']'); {$endif} // If the vertex was added before, let's see if the triangle matches. if (_VertsSeed[CurrentVertex] <> -1) then begin if (_VertsSeed[CurrentVertex] = _ID) and IsValidUVTriangle(_Faces,_Opposites,_TextCoords,_Vertices,CurrentVertex,SharedEdge0,SharedEdge1,PreviousVertex,_CheckFace,Value,PreviousFace,_VerticesPerFace) then begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(Value) + ' has been validated using its original coordinates: [' + FloatToStr(_TextCoords[CurrentVertex].U) + ', ' + FloatToStr(_TextCoords[CurrentVertex].V) + '].'); {$endif} // Add the face only _CheckFace[Value] := true; _FaceSeeds[Value] := _ID; UpdateAngleCount(SharedEdge0, SharedEdge1, CurrentVertex); UpdateBorderEdges(Value, _Faces, _Opposites, _VerticesPerFace); // Check if other neighbors are elegible for this partition/seed. AddNeighborFaces(Value, FaceEdgeCounter, _Faces, _Opposites, _TextCoords, _FaceSeeds, _CheckFace, _VerticesPerFace); end else begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(Value) + ' has been rejected using its original coordinates: [' + FloatToStr(_TextCoords[CurrentVertex].U) + ', ' + FloatToStr(_TextCoords[CurrentVertex].V) + ']. Attempting nearby coordinates...'); {$endif} // sometimes the triangle that may match may have another cloned // vertex instead of CurrentVertex. f := _FaceNeighbors.GetNeighborFromID(Value); while f <> -1 do begin if _CheckFace[f] then begin i := f * _VerticesPerFace; imax := i + _VerticesPerFace; Found := false; while (i < imax) and (not found) do begin if GetVertexLocationID(CurrentVertex) = GetVertexLocationID(_Faces[i]) then begin Found := true; end else begin inc(i); end; end; if Found then begin if (_Faces[i] <> CurrentVertex) and (_VertsSeed[_Faces[i]] = _ID) then begin if IsValidUVTriangle(_Faces,_Opposites,_TextCoords,_Vertices,_Faces[i],SharedEdge0,SharedEdge1,PreviousVertex,_CheckFace,Value,PreviousFace,_VerticesPerFace) then begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(Value) + ' has been validated using coordinates from ' + IntToStr(_Faces[i]) + ' instead of ' + IntToStr(CurrentVertex) + '. These coordinates are: [' + FloatToStr(_TextCoords[_Faces[i]].U) + ', ' + FloatToStr(_TextCoords[_Faces[i]].V) + '].'); {$endif} // Add the face only _CheckFace[Value] := true; _FaceSeeds[Value] := _ID; UpdateAngleCount(SharedEdge0, SharedEdge1, _Faces[i]); UpdateBorderEdges(Value, _Faces, _Opposites, _VerticesPerFace); {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face item ' + IntToStr(FaceIndex+v) + ' has been changed from ' + IntToStr(CurrentVertex) + ' to ' + IntToStr(_Faces[i])); {$endif} _Faces[FaceIndex + v] := _Faces[i]; f := -1; end else begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(Value) + ' has not been validated using coordinates from ' + IntToStr(_Faces[i]) + ' instead of ' + IntToStr(CurrentVertex) + '[' + FloatToStr(_TextCoords[_Faces[i]].U) + ', ' + FloatToStr(_TextCoords[_Faces[i]].V) + '].'); {$endif} end; end; end; end; if f <> -1 then begin f := _FaceNeighbors.GetNextNeighbor; end; end; // if the previous operation fails, try to clone it or reject it. if not _CheckFace[Value] then begin // Find coordinates and check if we won't hit another face. if IsValidUVPoint(_Vertices,_Faces,_TextCoords,CurrentVertex,SharedEdge0,SharedEdge1,PreviousVertex,_CheckFace,CandidateUVPosition,Value,PreviousFace,_VerticesPerFace) then begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(Value) + ' has been validated.'); {$endif} // Add the face and its vertexes _CheckFace[Value] := true; _FaceSeeds[Value] := _ID; // Clone the vertex. CloneVertex(CurrentVertex, _ID, FaceIndex+v, CandidateUVPosition.U, CandidateUVPosition.V, _TextCoords, _VertsSeed, Result, _Vertices, _VertsNormals, _VertsColours, _Faces); UpdateAngleCount(SharedEdge0, SharedEdge1, _Faces[FaceIndex+v]); UpdateBorderEdges(Value, _Faces, _Opposites, _VerticesPerFace); // Check if other neighbors are elegible for this partition/seed. AddNeighborFaces(Value, FaceEdgeCounter, _Faces, _Opposites, _TextCoords, _FaceSeeds, _CheckFace, _VerticesPerFace); end else // Face has been rejected. begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(Value) + ' has been rejected when the following coordinates were used: [' + FloatToStr(CandidateUVPosition.U) + ', ' + FloatToStr(CandidateUVPosition.V) + '].'); {$endif} // Restore current face due to rejection v := 0; while v < _VerticesPerFace do begin _Faces[FaceIndex + v] := FaceBackup[v]; inc(v); end; end; end else begin // Check if other neighbors are elegible for this partition/seed. AddNeighborFaces(Value, FaceEdgeCounter, _Faces, _Opposites, _TextCoords, _FaceSeeds, _CheckFace, _VerticesPerFace); end; end; end else begin // Find coordinates and check if we won't hit another face. if IsValidUVPoint(_Vertices,_Faces,_TextCoords,CurrentVertex,SharedEdge0,SharedEdge1,PreviousVertex,_CheckFace,CandidateUVPosition,Value,PreviousFace,_VerticesPerFace) then begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(Value) + ' has been validated.'); {$endif} // Add the face and its vertexes _CheckFace[Value] := true; _FaceSeeds[Value] := _ID; // This seed is the first seed to use this vertex. // Does this vertex has coordinates already? if (FVertsLocation[CurrentVertex] <> -1) or ((_VertsSeed[CurrentVertex] <> -1) and (_VertsSeed[CurrentVertex] <> _ID)) then begin CloneVertex(CurrentVertex, _ID, FaceIndex+v, CandidateUVPosition.U, CandidateUVPosition.V, _TextCoords, _VertsSeed, Result, _Vertices, _VertsNormals, _VertsColours, _Faces); end else begin AssignVertex(CurrentVertex, _ID, CandidateUVPosition.U, CandidateUVPosition.V, _TextCoords, _VertsSeed, Result); end; UpdateAngleCount(SharedEdge0, SharedEdge1, _Faces[FaceIndex + v]); UpdateBorderEdges(Value, _Faces, _Opposites, _VerticesPerFace); // Check if other neighbors are elegible for this partition/seed. AddNeighborFaces(Value, FaceEdgeCounter, _Faces, _Opposites, _TextCoords, _FaceSeeds, _CheckFace, _VerticesPerFace); end else // Face has been rejected. begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(Value) + ' has been rejected when the following coordinates were used: [' + FloatToStr(CandidateUVPosition.U) + ', ' + FloatToStr(CandidateUVPosition.V) + '].'); {$endif} // Restore current face due to rejection v := 0; while v < _VerticesPerFace do begin _Faces[FaceIndex + v] := FaceBackup[v]; inc(v); end; end; end; end; Index := FPriorityList.GetFirstElement; end; if _NeighborhoodPlugin <> nil then begin TNeighborhoodDataPlugin(_NeighborhoodPlugin^).UpdateEquivalencesOrigami(FVertsLocation); end; SetLength(FVertsLocation,0); VertexUtil.Free; end; procedure CTextureAtlasExtractorIDC.BuildFirstTriangle(_ID,_MeshID,_StartingFace: integer; var _Vertices : TAVector3f; var _FaceNormals, _VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32; const _Opposites: aint32; var _TextCoords: TAVector2f; var _FaceSeeds,_VertsSeed: aint32; _VerticesPerFace: integer; var _VertexUtil: TVertexTransformationUtils; var _TextureSeed: TTextureSeed; var _FaceEdgeCounter: auint32; const _CheckFace: abool); var vertex, FaceIndex: integer; Target,Edge0,Edge1: integer; cosAng0, cosAng1, sinAng0, sinAng1, Edge0Size: single; UVPosition: TVector2f; begin // The first triangle is dealt in a different way. // We'll project it in the plane XY and the first vertex is on (0,0,0). {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Starting Face is ' + IntToStr(_StartingFace) + ' and it is being added now'); {$endif} FaceIndex := _StartingFace * _VerticesPerFace; {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Vertex ' + IntToStr(_Faces[FaceIndex]) + ' position is [' + FloatToStr(_Vertices[_Faces[FaceIndex]].X) + ', ' + FloatToStr(_Vertices[_Faces[FaceIndex]].Y) + ', ' + FloatToStr(_Vertices[_Faces[FaceIndex]].Z) + '].'); GlobalVars.OrigamiFile.Add('Vertex ' + IntToStr(_Faces[FaceIndex+1]) + ' position is [' + FloatToStr(_Vertices[_Faces[FaceIndex+1]].X) + ', ' + FloatToStr(_Vertices[_Faces[FaceIndex+1]].Y) + ', ' + FloatToStr(_Vertices[_Faces[FaceIndex+1]].Z) + '].'); GlobalVars.OrigamiFile.Add('Vertex ' + IntToStr(_Faces[FaceIndex+2]) + ' position is [' + FloatToStr(_Vertices[_Faces[FaceIndex+2]].X) + ', ' + FloatToStr(_Vertices[_Faces[FaceIndex+2]].Y) + ', ' + FloatToStr(_Vertices[_Faces[FaceIndex+2]].Z) + '].'); {$endif} // First vertex is (1,0). vertex := _Faces[FaceIndex]; if _VertsSeed[vertex] <> -1 then begin CloneVertex(vertex, _ID, FaceIndex, 1, 0, _TextCoords, _VertsSeed, _TextureSeed, _Vertices, _VertsNormals, _VertsColours, _Faces); end else begin AssignVertex(vertex, _ID, 1, 0, _TextCoords, _VertsSeed, _TextureSeed); end; // Second vertex is (0,0). vertex := _Faces[FaceIndex+1]; if _VertsSeed[vertex] <> -1 then begin CloneVertex(vertex, _ID, FaceIndex+1, 0, 0, _TextCoords, _VertsSeed, _TextureSeed, _Vertices, _VertsNormals, _VertsColours, _Faces); end else begin AssignVertex(vertex, _ID, 0, 0, _TextCoords, _VertsSeed, _TextureSeed); end; // Now, finally we have to figure out the 3rd vertex. That one depends on the angles. Target := _Faces[FaceIndex + 2]; Edge0 := _Faces[FaceIndex]; Edge1 := _Faces[FaceIndex + 1]; GetAnglesFromCoordinates(_Vertices, Edge0, Edge1, Target); cosAng0 := cos(FUVAng0); cosAng1 := cos(FUVAng1); sinAng0 := sin(FUVAng0); sinAng1 := sin(FUVAng1); Edge0Size := sinAng1 / ((cosAng0 * sinAng1) + (cosAng1 * sinAng0)); // Write the UV Position UVPosition.U := Edge0Size * cosAng0; UVPosition.V := Edge0Size * sinAng0; vertex := Target; if _VertsSeed[vertex] <> -1 then begin CloneVertex(vertex, _ID, FaceIndex+2, UVPosition.U, UVPosition.V, _TextCoords, _VertsSeed, _TextureSeed, _Vertices, _VertsNormals, _VertsColours, _Faces); end else begin AssignVertex(vertex, _ID, UVPosition.U, UVPosition.V, _TextCoords, _VertsSeed, _TextureSeed); end; UpdateAngleCount(Edge0, Edge1, Target); UpdateBorderEdges(_StartingFace, _Faces, _Opposites, _VerticesPerFace); // Add neighbour faces to the list. AddNeighborFaces(_StartingFace, _FaceEdgeCounter, _Faces, _Opposites, _TextCoords, _FaceSeeds, _CheckFace, _VerticesPerFace); end; procedure CTextureAtlasExtractorIDC.AddNeighborFaces(_CurrentFace: integer; var _FaceEdgeCounter: auint32; const _Faces: auint32; const _Opposites: aint32; var _TextCoords: TAVector2f; const _FaceSeeds: aint32; const _CheckFace: abool; _VerticesPerFace: integer); var i,j,jNext,f,fi: integer; MidEdgePosition: TVector2f; begin // Add neighbour faces to the list. fi := _CurrentFace * _VerticesPerFace; j := 0; while j < _VerticesPerFace do begin f := _Opposites[fi + j] div _VerticesPerFace; {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(f) + ' is neighbour of ' + IntToStr(_CurrentFace)); {$endif} inc(_FaceEdgeCounter[f]); // do some verification here if not _CheckFace[f] then begin if (_FaceSeeds[f] = -1) then begin if _FaceEdgeCounter[f] = 3 then begin i := FPriorityList.Add(0); // add as first element. end else begin jNext := (j + 1) mod _VerticesPerFace; MidEdgePosition.U := (_TextCoords[_Faces[fi + j]].U + _TextCoords[_Faces[fi + jNext]].U) / 2; MidEdgePosition.V := (_TextCoords[_Faces[fi + j]].V + _TextCoords[_Faces[fi + jNext]].V) / 2; i := FPriorityList.Add(GetVectorLength(MidEdgePosition)); end; FPreviousFaceList[i] := _CurrentFace; FFaceList[i] := f; {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face ' + IntToStr(f) + ' has been added to the list'); {$endif} end; end; inc(j); end; end; procedure CTextureAtlasExtractorIDC.AssignVertex(_VertexID, _SeedID: integer; _U, _V: single; var _TextCoords: TAVector2f; var _VertsSeed: aint32; var _TextureSeed: TTextureSeed); begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Vertex ' + IntToStr(_VertexID) + ' is new.'); {$endif} // This seed is the first seed to use this vertex. _VertsSeed[_VertexID] := _SeedID; FVertsLocation[_VertexID] := _VertexID; // Get temporary texture coordinates. _TextCoords[_VertexID].U := _U; _TextCoords[_VertexID].V := _V; {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Vertex is ' + IntToStr(_VertexID) + ' and Position is: [' + FloatToStr(_U) + ' ' + FloatToStr(_V) + ']'); {$endif} // Now update the bounds of the seed. if _U < _TextureSeed.MinBounds.U then _TextureSeed.MinBounds.U := _U; if _U > _TextureSeed.MaxBounds.U then _TextureSeed.MaxBounds.U := _U; if _V < _TextureSeed.MinBounds.V then _TextureSeed.MinBounds.V := _V; if _V > _TextureSeed.MaxBounds.V then _TextureSeed.MaxBounds.V := _V; end; procedure CTextureAtlasExtractorIDC.CloneVertex(_VertexID, _SeedID, _FaceIndex: integer; _U, _V: single; var _TextCoords: TAVector2f; var _VertsSeed: aint32; var _TextureSeed: TTextureSeed; var _Vertices : TAVector3f; var _VertsNormals : TAVector3f; var _VertsColours : TAVector4f; var _Faces : auint32); begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Vertex ' + IntToStr(_VertexID) + ' is used and it is being cloned as ' + IntToStr(High(_Vertices)+1)); {$endif} // this vertex was used by a previous seed, therefore, we'll clone it SetLength(_Vertices,High(_Vertices)+2); SetLength(_VertsSeed,High(_Vertices)+1); _VertsSeed[High(_VertsSeed)] := _SeedID; SetLength(FVertsLocation,High(_Vertices)+1); FVertsLocation[High(_Vertices)] := _VertexID; // _VertsLocation works slightly different here than in the non-origami version. {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Face item ' + IntToStr(_FaceIndex) + ' has been changed to ' + IntToStr(High(_Vertices))); {$endif} _Faces[_FaceIndex] := High(_Vertices); _Vertices[High(_Vertices)].X := _Vertices[_VertexID].X; _Vertices[High(_Vertices)].Y := _Vertices[_VertexID].Y; _Vertices[High(_Vertices)].Z := _Vertices[_VertexID].Z; SetLength(_VertsNormals,High(_Vertices)+1); _VertsNormals[High(_Vertices)].X := _VertsNormals[_VertexID].X; _VertsNormals[High(_Vertices)].Y := _VertsNormals[_VertexID].Y; _VertsNormals[High(_Vertices)].Z := _VertsNormals[_VertexID].Z; SetLength(_VertsColours,High(_Vertices)+1); _VertsColours[High(_Vertices)].X := _VertsColours[_VertexID].X; _VertsColours[High(_Vertices)].Y := _VertsColours[_VertexID].Y; _VertsColours[High(_Vertices)].Z := _VertsColours[_VertexID].Z; _VertsColours[High(_Vertices)].W := _VertsColours[_VertexID].W; // Get temporarily texture coordinates. SetLength(_TextCoords,High(_Vertices)+1); _TextCoords[High(_Vertices)].U := _U; _TextCoords[High(_Vertices)].V := _V; {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Vertex is ' + IntToStr(_VertexID) + ' and Position is: [' + FloatToStr(_U) + ' ' + FloatToStr(_V) + ']'); {$endif} // Now update the bounds of the seed. if _U < _TextureSeed.MinBounds.U then _TextureSeed.MinBounds.U := _U; if _U > _TextureSeed.MaxBounds.U then _TextureSeed.MaxBounds.U := _U; if _V < _TextureSeed.MinBounds.V then _TextureSeed.MinBounds.V := _V; if _V > _TextureSeed.MaxBounds.V then _TextureSeed.MaxBounds.V := _V; // Update our angle counter system SetLength(FParamAngleCount, High(_Vertices)+1); FParamAngleCount[High(_Vertices)] := 2 * pi; SetLength(FAngleFactor, High(_Vertices)+1); FAngleFactor[High(_Vertices)] := 1; end; // Update the FBorderEdges descriptor. The order of the edges doesn't matter at all. procedure CTextureAtlasExtractorIDC.UpdateBorderEdges(_CurrentFace: integer; const _Faces: auint32; const _Opposites: aint32; _VerticesPerFace: integer); var FaceIndex, i, iNext, oNext: integer; {$ifdef ORIGAMI_TEST} Temp: string; {$endif} begin FaceIndex := _CurrentFace * _VerticesPerFace; i := 0; while i < _VerticesPerFace do begin if FBorderEdgesMap[_Opposites[FaceIndex + i]] <> -1 then begin // Check if the edge and its twin have the same vertices. // If they don't, then we should add this edge instead of removing one. oNext := ((_Opposites[FaceIndex + i] + 1) mod _VerticesPerFace) + ((_Opposites[FaceIndex + i] div _VerticesPerFace) * _VerticesPerFace); iNext := (i + 1) mod _VerticesPerFace; if (_Faces[FaceIndex + i] = _Faces[oNext]) and (_Faces[FaceIndex + iNext] = _Faces[_Opposites[FaceIndex + i]]) then begin // remove edge. dec(FBorderEdgeCounter); FBorderEdges[FBorderEdgesMap[_Opposites[FaceIndex + i]]] := FBorderEdges[FBorderEdgeCounter]; FBorderEdgesMap[FBorderEdges[FBorderEdgeCounter]] := FBorderEdgeCounter; FBorderEdges[FBorderEdgeCounter] := -1; FBorderEdgesMap[_Opposites[FaceIndex + i]] := -1; FBorderEdgesMap[FaceIndex + i] := -1; end else begin // add edge FBorderEdgesMap[FaceIndex + i] := FBorderEdgeCounter; FBorderEdges[FBorderEdgeCounter] := FaceIndex + i; inc(FBorderEdgeCounter); end; end else // add edge. begin FBorderEdgesMap[FaceIndex + i] := FBorderEdgeCounter; FBorderEdges[FBorderEdgeCounter] := FaceIndex + i; inc(FBorderEdgeCounter); end; inc(i); end; {$ifdef ORIGAMI_TEST} i := 0; Temp := 'Border Edges are: ['; while i < (FBorderEdgeCounter - 1) do begin iNext := ((FBorderEdges[i] + 1) mod _VerticesPerFace) + ((FBorderEdges[i] div _VerticesPerFace) * _VerticesPerFace); Temp := Temp + '(' + IntToStr(_Faces[FBorderEdges[i]]) + ', ' + IntToStr(_Faces[iNext]) + '), '; inc(i); end; iNext := ((FBorderEdges[i] + 1) mod _VerticesPerFace) + ((FBorderEdges[i] div _VerticesPerFace) * _VerticesPerFace); Temp := Temp + '(' + IntToStr(_Faces[FBorderEdges[i]]) + ', ' + IntToStr(_Faces[iNext]) + ')]'; GlobalVars.OrigamiFile.Add(Temp); {$endif} end; procedure CTextureAtlasExtractorIDC.UpdateAngleCount(_Edge0, _Edge1, _Target: integer); begin FMeshAngleCount[GetVertexLocationID(_Edge0)] := FMeshAngleCount[GetVertexLocationID(_Edge0)] - FMeshAng0; FMeshAngleCount[GetVertexLocationID(_Edge1)] := FMeshAngleCount[GetVertexLocationID(_Edge1)] - FMeshAng1; FMeshAngleCount[GetVertexLocationID(_Target)] := FMeshAngleCount[GetVertexLocationID(_Target)] - FMeshAngTarget; FParamAngleCount[_Edge0] := FParamAngleCount[_Edge0] - FUVAng0; FParamAngleCount[_Edge1] := FParamAngleCount[_Edge1] - FUVAng1; FParamAngleCount[_Target] := FParamAngleCount[_Target] - FUVAngTarget; FAngleFactor[_Edge0] := epsilon((FMeshAngleCount[GetVertexLocationID(_Edge0)] / FParamAngleCount[_Edge0]) - 1) + 1; FAngleFactor[_Edge1] := epsilon((FMeshAngleCount[GetVertexLocationID(_Edge1)] / FParamAngleCount[_Edge1]) - 1) + 1; FAngleFactor[_Target] := epsilon((FMeshAngleCount[GetVertexLocationID(_Target)] / FParamAngleCount[_Target]) - 1) + 1; dec(FVertNeighborsLeft[GetVertexLocationID(_Edge0)]); dec(FVertNeighborsLeft[GetVertexLocationID(_Edge1)]); dec(FVertNeighborsLeft[GetVertexLocationID(_Target)]); end; // That's basically an interpolation. I'm still in doubt if it should be linear or not. // At the moment, it is linear. function CTextureAtlasExtractorIDC.GetDistortionFactor(_ID:integer; _Angle: single): single; var AvgAngle: single; NumNeighborsFactor: integer; begin NumNeighborsFactor := (FVertNeighborsLeft[_ID] -1); AvgAngle := (FParamAngleCount[_ID] - _Angle) / NumNeighborsFactor; if AvgAngle < C_MIN_ANGLE then begin Result := 0; end else if AvgAngle < C_IDEAL_ANGLE then begin Result := ((AvgAngle - C_MIN_ANGLE) / (C_MIN_TO_IDEAL_ANGLE_INTERVAL)) * (NumNeighborsFactor * NumNeighborsFactor); end else if AvgAngle < C_MAX_ANGLE then begin Result := (1 - ((AvgAngle - C_IDEAL_ANGLE) / (C_IDEAL_TO_MAX_ANGLE_INTERVAL))) * (NumNeighborsFactor * NumNeighborsFactor); end else Result := 0; end; procedure CTextureAtlasExtractorIDC.GetAnglesFromCoordinates(const _Vertices: TAVector3f; _Edge0, _Edge1, _Target: integer); var i: integer; DirEdge,DirEdge0,DirEdge1: TVector3f; AngSum, DistortionSum: single; IdealAngles: afloat; DistortionFactor: afloat; IDs: auint32; begin // Set memory SetLength(IDs, 3); SetLength(IdealAngles, 3); SetLength(DistortionFactor, 3); IDs[0] := _Edge0; IDs[1] := _Edge1; IDs[2] := _Target; // Gather basic data DirEdge := SubtractVector(_Vertices[_Edge1],_Vertices[_Edge0]); Normalize(DirEdge); DirEdge0 := SubtractVector(_Vertices[_Target],_Vertices[_Edge0]); Normalize(DirEdge0); DirEdge1 := SubtractVector(_Vertices[_Target],_Vertices[_Edge1]); Normalize(DirEdge1); FMeshAng0 := ArcCos(DotProduct(DirEdge0, DirEdge)); FMeshAng1 := ArcCos(-1 * DotProduct(DirEdge1, DirEdge)); FMeshAngTarget := ArcCos(DotProduct(DirEdge0, DirEdge1)); IdealAngles[0] := FMeshAng0 / FAngleFactor[GetVertexLocationID(IDs[0])]; IdealAngles[1] := FMeshAng1 / FAngleFactor[GetVertexLocationID(IDs[1])]; IdealAngles[2] := FMeshAngTarget / FAngleFactor[GetVertexLocationID(IDs[2])]; AngSum := IdealAngles[0] + IdealAngles[1] + IdealAngles[2]; // Calculate resulting angles. if AngSum < pi then begin // We'll priorize the highest distortion factor. AngSum := pi - AngSum; DistortionSum := 0; for i := 0 to 2 do begin if FVertNeighborsLeft[IDs[i]] > 1 then begin DistortionFactor[i] := GetDistortionFactor(IDs[i], IdealAngles[i]); end else begin DistortionFactor[i] := 0; end; DistortionSum := DistortionSum + DistortionFactor[i]; end; if DistortionSum > 0 then begin FUVAng0 := IdealAngles[0] + (AngSum * (DistortionFactor[0] / DistortionSum)); FUVAng1 := IdealAngles[1] + (AngSum * (DistortionFactor[1] / DistortionSum)); end else begin FUVAng0 := IdealAngles[0] + (AngSum / 3); FUVAng1 := IdealAngles[1] + (AngSum / 3); end; {$ifdef ORIGAMI_TEST} AngSum := pi - AngSum; {$endif} end else if AngSum = pi then begin FUVAng0 := (IdealAngles[0] / AngSum) * pi; FUVAng1 := (IdealAngles[1] / AngSum) * pi; end else begin // We'll priorize the highest distortion factor. AngSum := AngSum - pi; DistortionSum := 0; for i := 0 to 2 do begin if FVertNeighborsLeft[IDs[i]] > 1 then begin DistortionFactor[i] := GetDistortionFactor(IDs[i], IdealAngles[i]); end else begin DistortionFactor[i] := 0; end; DistortionSum := DistortionSum + DistortionFactor[i]; end; if DistortionSum > 0 then begin FUVAng0 := IdealAngles[0] - (AngSum * (DistortionFactor[0] / DistortionSum)); FUVAng1 := IdealAngles[1] - (AngSum * (DistortionFactor[1] / DistortionSum)); end else begin FUVAng0 := IdealAngles[0] - (AngSum / 3); FUVAng1 := IdealAngles[1] - (AngSum / 3); end; {$ifdef ORIGAMI_TEST} AngSum := AngSum + pi; {$endif} end; // Self-Defense against absurdly deformed triangles. FUVAngTarget := pi - (FUVAng0 + FUVAng1); if FUVAng0 < C_MIN_ANGLE then begin FUVAng0 := C_MIN_ANGLE; FUVAng1 := FUVAng1 - C_HALF_MIN_ANGLE; FUVAngTarget := FUVAngTarget - C_HALF_MIN_ANGLE; end; if FUVAng1 < C_MIN_ANGLE then begin FUVAng0 := FUVAng0 - C_HALF_MIN_ANGLE; FUVAng1 := C_MIN_ANGLE; FUVAngTarget := FUVAngTarget - C_HALF_MIN_ANGLE; end; if (FUVAngTarget) < C_MIN_ANGLE then begin FUVAng0 := FUVAng0 - C_HALF_MIN_ANGLE; FUVAng1 := FUVAng1 - C_HALF_MIN_ANGLE; FUVAngTarget := C_MIN_ANGLE; end; // Report result if required. {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Triangle with the angles: (' + FloatToStr(FMeshAng0) + ', ' + FloatToStr(FMeshAng1) + ', ' + FloatToStr(FMeshAngTarget) + ') has been deformed with the angles: (' + FloatToStr(IdealAngles[0]) + ', ' + FloatToStr(IdealAngles[1]) + ', ' + FloatToStr(IdealAngles[2]) + ') and, it generates the following angles: (' + FloatToStr(FUVAng0) + ', ' + FloatToStr(FUVAng1) + ', ' + FloatToStr(FUVAngTarget) + ') where the factors are respectively ( ' + FloatToStr(FAngleFactor[GetVertexLocationID(_Edge0)]) + ', ' + FloatToStr(FAngleFactor[GetVertexLocationID(_Edge1)]) + ', ' + FloatToStr(FAngleFactor[GetVertexLocationID(_Target)]) + ') and AngleSum is ' + FloatToStr(AngSum) + ' .'); {$endif} // Free memory. SetLength(IDs, 0); SetLength(IdealAngles, 0); SetLength(DistortionFactor, 0); end; procedure CTextureAtlasExtractorIDC.ObtainCommonEdgeFromFaces(var _Faces: auint32; var _Opposites: aint32; const _VerticesPerFace,_CurrentFace,_PreviousFace: integer; var _CurrentVertex,_PreviousVertex,_CommonVertex1,_CommonVertex2,_inFaceCurrVertPosition: integer); var i,j,mincface,minpface : integer; Found: boolean; {$ifdef ORIGAMI_TEST} Temp: String; {$endif} begin mincface := _CurrentFace * _VerticesPerFace; minpface := _PreviousFace * _VerticesPerFace; {$ifdef ORIGAMI_TEST} Temp := 'VertexLocation = ['; for i := Low(FVertsLocation) to High(FVertsLocation) do begin Temp := Temp + IntToStr(FVertsLocation[i]) + ' '; end; Temp := Temp + ']'; GlobalVars.OrigamiFile.Add(Temp); {$endif} j := 0; found := false; while (j < _VerticesPerFace) and (not found) do begin if (_Opposites[minpface + j] div _VerticesPerFace) = _CurrentFace then begin Found := true; i := _Opposites[minpface + j] mod _VerticesPerFace; _CommonVertex2 := _Faces[minpface + j]; //_Faces[mincface + i]; _CommonVertex1 := _Faces[minpface + ((j + 1) mod _VerticesPerFace)]; //_Faces[mincface + ((i + 1) mod _VerticesPerFace)]; _inFaceCurrVertPosition := (i + 2) mod _VerticesPerFace; _CurrentVertex := _Faces[mincface + _inFaceCurrVertPosition]; _PreviousVertex := _Faces[minpface + ((j + 2) mod _VerticesPerFace)]; _Faces[mincface + ((_inFaceCurrVertPosition + 1) mod _VerticesPerFace)] := _CommonVertex1; _Faces[mincface + ((_inFaceCurrVertPosition + 2) mod _VerticesPerFace)] := _CommonVertex2; end else inc(j); end; end; function CTextureAtlasExtractorIDC.IsValidUVPoint(const _Vertices: TAVector3f; const _Faces : auint32; var _TexCoords: TAVector2f; _Target,_Edge0,_Edge1,_OriginVert: integer; var _CheckFace: abool; var _UVPosition: TVector2f; _CurrentFace, _PreviousFace, _VerticesPerFace: integer): boolean; var cosAng0,cosAng1,sinAng0,sinAng1,Edge0Size: single; EdgeSizeInMesh,EdgeSizeInUV,SinProjectionSizeInUV,ProjectionSizeInUV: single; EdgeDirectionInUV,PositionOfTargetAtEdgeInUV,SinDirectionInUV: TVector2f; EdgeDirectionInMesh: TVector3f; SourceSide: single; i,v: integer; ColisionUtil : CColisionCheck;//TVertexTransformationUtils; begin Result := false; ColisionUtil := CColisionCheck.Create; //TVertexTransformationUtils.Create; // Get edge size in mesh EdgeSizeInMesh := VectorDistance(_Vertices[_Edge0],_Vertices[_Edge1]); if EdgeSizeInMesh > 0 then begin // Get the direction of the edge (Edge0 to Edge1) in Mesh and UV space EdgeDirectionInMesh := SubtractVector(_Vertices[_Edge1],_Vertices[_Edge0]); EdgeDirectionInUV := SubtractVector(_TexCoords[_Edge1],_TexCoords[_Edge0]); // Get edge size in UV space. EdgeSizeInUV := Sqrt((EdgeDirectionInUV.U * EdgeDirectionInUV.U) + (EdgeDirectionInUV.V * EdgeDirectionInUV.V)); // Directions must be normalized. Normalize(EdgeDirectionInMesh); Normalize(EdgeDirectionInUV); // Find the angles of the vertexes of the main edge in Mesh. GetAnglesFromCoordinates(_Vertices, _Edge0, _Edge1, _Target); cosAng0 := cos(FUVAng0); cosAng1 := cos(FUVAng1); sinAng0 := sin(FUVAng0); sinAng1 := sin(FUVAng1); // We'll now use these angles to find the projection directly in UV. Edge0Size := (EdgeSizeInUV * sinAng1) / ((cosAng0 * sinAng1) + (cosAng1 * sinAng0)); {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Edge0Size is ' + FloatToStr(Edge0Size) + '.'); {$endif} if (Edge0Size <= 10) and (Edge0Size >= 0.1) then begin // Get the size of projection of (Vertex - Edge0) at the Edge, in UV already ProjectionSizeInUV := Edge0Size * cosAng0; // Obtain the position of this projection at the edge, in UV PositionOfTargetatEdgeInUV := AddVector(_TexCoords[_Edge0],ScaleVector(EdgeDirectionInUV,ProjectionSizeInUV)); // Find out the distance between that and the _Target in UV. SinProjectionSizeInUV := Edge0Size * sinAng0; // Rotate the edgeze in 90' in UV space. SinDirectionInUV := Get90RotDirectionFromDirection(EdgeDirectionInUV); // We need to make sure that _Target and _OriginVert are at opposite sides // the universe, if it is divided by the Edge0 to Edge1. SourceSide := Get2DOuterProduct(_TexCoords[_OriginVert],_TexCoords[_Edge0],_TexCoords[_Edge1]); if SourceSide > 0 then begin SinDirectionInUV := ScaleVector(SinDirectionInUV,-1); end; // Write the UV Position _UVPosition := AddVector(PositionOfTargetatEdgeInUV,ScaleVector(SinDirectionInUV,SinProjectionSizeInUV)); // Let's check if this UV Position will hit another UV project face. Result := true; // the change in the _AddedFace temporary optimization for the upcoming loop. i := 0; while i < FBorderEdgeCounter do begin v := ((FBorderEdges[i] + 1) mod _VerticesPerFace) + ((FBorderEdges[i] div _VerticesPerFace) * _VerticesPerFace); // Check if the candidate position is inside this triangle. // If it is inside the triangle, then point is not validated. Exit. if ColisionUtil.Is2DTriangleColidingEdge(_UVPosition,_TexCoords[_Edge0],_TexCoords[_Edge1],_TexCoords[_Faces[FBorderEdges[i]]],_TexCoords[_Faces[v]]) then begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Vertex textured coordinate (' + FloatToStr(_UVPosition.U) + ', ' + FloatToStr(_UVPosition.V) + ') conflicts with edge ' + IntToStr(FBorderEdges[i]) + ' which is the edge [' + IntToStr(_Faces[FBorderEdges[i]]) + ', ' + IntToStr(_Faces[v]) + '].'); {$endif} Result := false; ColisionUtil.Free; exit; end; inc(i); end; end; end else begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('New triangle causes too much distortion. Edge size is: ' + FloatToStr(Edge0Size) + '.'); {$endif} Result := false; end; ColisionUtil.Free; end; function CTextureAtlasExtractorIDC.IsValidUVTriangle(const _Faces : auint32; const _Opposites: aint32; var _TexCoords: TAVector2f; const _Vertices: TAVector3f; _Target,_Edge0,_Edge1,_OriginVert: integer; var _CheckFace: abool; _CurrentFace, _PreviousFace, _VerticesPerFace: integer): boolean; var i,v, FaceIndex,OppFaceIndex: integer; ColisionUtil : CColisionCheck;//TVertexTransformationUtils; DirMeshTE0,DirMeshE1T,DirMeshE0E1: TVector3f; DirUVTE0,DirUVE1T,DirUVE0E1: TVector2f; begin // Do we have a valid triangle? DirUVTE0 := SubtractVector(_TexCoords[_Edge0], _TexCoords[_Target]); if Epsilon(Normalize(DirUVTE0)) = 0 then begin Result := false; exit; end; DirUVE1T := SubtractVector(_TexCoords[_Target], _TexCoords[_Edge1]); if Epsilon(Normalize(DirUVE1T)) = 0 then begin Result := false; exit; end; DirUVE0E1 := SubtractVector(_TexCoords[_Edge1], _TexCoords[_Edge0]); Normalize(DirUVE0E1); // Is the orientation correct? if Epsilon(Get2DOuterProduct(_TexCoords[_Target],_TexCoords[_Edge0],_TexCoords[_Edge1])) > 0 then begin Result := false; exit; end; // Are angles acceptable? FUVAng0 := ArcCos(-1 * DotProduct(DirUVTE0, DirUVE0E1)); FUVAng1 := ArcCos(-1 * DotProduct(DirUVE0E1, DirUVE1T)); FUVAngTarget := ArcCos(-1 * DotProduct(DirUVE1T, DirUVTE0)); if Epsilon(abs(DotProduct(DirUVTE0,DirUVE1T)) - 1) = 0 then begin Result := false; exit; end; // Check if half edges related to the current vertex were already projected // and are coherent. i := 0; v := 0; FaceIndex := _CurrentFace * _VerticesPerFace; while i < _VerticesPerFace do begin if _Faces[FaceIndex + i] = _Target then begin v := i; i := _VerticesPerFace; end; inc(i); end; // Now we know that _Faces[FaceIndex + v] points to _Target, we need to know // if the two twin half edges that points to it are really related to _Target OppFaceIndex := (_Opposites[FaceIndex + v] div _VerticesPerFace) * _VerticesPerFace; i := OppFaceIndex + ((_Opposites[FaceIndex + v] + 1) mod _VerticesPerFace); if _Faces[i] <> _Faces[FaceIndex + v] then begin Result := false; {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('New triangle has an undesirable configuration.'); {$endif} exit; end; i := OppFaceIndex + ((i + 2) mod _VerticesPerFace); if _Faces[i] <> _Faces[FaceIndex + ((v + 1) mod _VerticesPerFace)] then begin Result := false; {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('New triangle has an undesirable configuration.'); {$endif} exit; end; // Are all angles above threshold? if FUVAng0 < C_HALF_MIN_ANGLE then begin Result := false; exit; end; if FUVAng1 < C_HALF_MIN_ANGLE then begin Result := false; exit; end; if FUVAngTarget < C_HALF_MIN_ANGLE then begin Result := false; exit; end; DirMeshE0E1 := SubtractVector(_Vertices[_Edge1],_Vertices[_Edge0]); Normalize(DirMeshE0E1); DirMeshTE0 := SubtractVector(_Vertices[_Target],_Vertices[_Edge0]); Normalize(DirMeshTE0); DirMeshE1T := SubtractVector(_Vertices[_Target],_Vertices[_Edge1]); Normalize(DirMeshE1T); FMeshAng0 := ArcCos(DotProduct(DirMeshTE0, DirMeshE0E1)); FMeshAng1 := ArcCos(-1 * DotProduct(DirMeshE1T, DirMeshE0E1)); FMeshAngTarget := ArcCos(DotProduct(DirMeshTE0, DirMeshE1T)); ColisionUtil := CColisionCheck.Create; //TVertexTransformationUtils.Create; // Let's check if this UV Position will hit another UV project face. Result := true; // the change in the _AddedFace temporary optimization for the upcoming loop. i := 0; while i < FBorderEdgeCounter do begin v := ((FBorderEdges[i] + 1) mod _VerticesPerFace) + ((FBorderEdges[i] div _VerticesPerFace) * _VerticesPerFace); // Check if the candidate position is inside this triangle. // If it is inside the triangle, then point is not validated. Exit. if ColisionUtil.Is2DTriangleOverlappingEdge(_TexCoords[_Target],_TexCoords[_Edge0],_TexCoords[_Edge1],_TexCoords[_Faces[FBorderEdges[i]]],_TexCoords[_Faces[v]]) then begin {$ifdef ORIGAMI_TEST} GlobalVars.OrigamiFile.Add('Vertex textured coordinate (' + FloatToStr(_TexCoords[_Target].U) + ', ' + FloatToStr(_TexCoords[_Target].V) + ') conflicts with edge ' + IntToStr(FBorderEdges[i]) + ' which is the edge [' + IntToStr(_Faces[FBorderEdges[i]]) + ', ' + IntToStr(_Faces[v]) + '].'); {$endif} Result := false; ColisionUtil.Free; exit; end; inc(i); end; ColisionUtil.Free; end; end.
unit CadastroProdutos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.ExtCtrls, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.VCLUI.Wait; type TFProdutos = class(TForm) PnFundo: TPanel; TBProdutos: TFDTable; TBProdutosID: TIntegerField; TBProdutosNome: TStringField; TBProdutosDescricao: TStringField; TBProdutosCusto: TCurrencyField; DSProdutos: TDataSource; LbID: TLabel; EdID: TDBEdit; LbNome: TLabel; EdNome: TDBEdit; LbDescricao: TLabel; LbCusto: TLabel; EdCusto: TDBEdit; LbMargem: TLabel; EdMargem: TDBEdit; MnDescricao: TDBMemo; PnButtons: TPanel; BtGravar: TButton; BtCancelar: TButton; TBProdutosMargem: TFloatField; procedure BtGravarClick(Sender: TObject); procedure BtCancelarClick(Sender: TObject); private public ID: Integer; DBConexao: TFDConnection; procedure AdicionaProduto; procedure EditarProduto(ID: Integer); end; var FProdutos: TFProdutos; implementation {$R *.dfm} { TFProdutos } { TFProdutos } procedure TFProdutos.AdicionaProduto; var Query: TFDQuery; begin TBProdutos.Connection := DBConexao; TBProdutos.TableName := 'Produtos'; TBProdutos.Open(); TBProdutos.Append; Query := TFDQuery.Create(nil); try Query.Connection := DBConexao; Query.SQL.Text := 'SELECT CASE WHEN MAX(ID) IS NULL THEN 1 ELSE (MAX(ID) +1) END ID FROM PRODUTOS'; Query.Open(); TBProdutos.FieldByName('ID').AsInteger := Query.FieldByName('ID').AsInteger; finally Query.free; end; ShowModal; end; procedure TFProdutos.BtCancelarClick(Sender: TObject); begin Close; end; procedure TFProdutos.BtGravarClick(Sender: TObject); begin TBProdutos.Post; DBConexao.Commit; Close; end; procedure TFProdutos.EditarProduto(ID: Integer); begin TBProdutos.Connection := DBConexao; TBProdutos.TableName := 'Produtos'; TBProdutos.Open(); if ID > 0 then begin TBProdutos.First; while not TBProdutos.Eof do begin if TBProdutos['id'] = ID then break; TBProdutos.Next; end; TBProdutos.Edit; end; ShowModal; end; end.
unit LrDocumentList; interface uses Classes, Controls, LrObserverList, LrDocument; type TLrDocumentList = class(TList) private FOnChange: TNotifyEvent; protected function GetDocuments(inIndex: Integer): TLrDocument; function GoodIndex(inIndex: Integer): Boolean; procedure SetDocuments(inIndex: Integer; const Value: TLrDocument); public constructor Create; virtual; destructor Destroy; override; function FindDocument(const inDocument: TLrDocument): Integer; overload; function FindDocument(const inFilename: string): TLrDocument; overload; procedure Change; virtual; property Documents[inIndex: Integer]: TLrDocument read GetDocuments write SetDocuments; default; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; implementation { TLrDocumentList } constructor TLrDocumentList.Create; begin end; destructor TLrDocumentList.Destroy; begin inherited; end; procedure TLrDocumentList.Change; begin if Assigned(OnChange) then OnChange(Self); end; function TLrDocumentList.GoodIndex(inIndex: Integer): Boolean; begin Result := (inIndex >= 0) and (inIndex < Count); end; function TLrDocumentList.GetDocuments(inIndex: Integer): TLrDocument; begin Result := TLrDocument(Items[inIndex]); end; procedure TLrDocumentList.SetDocuments(inIndex: Integer; const Value: TLrDocument); begin Items[inIndex] := Value; end; function TLrDocumentList.FindDocument( const inDocument: TLrDocument): Integer; begin Result := IndexOf(inDocument); end; function TLrDocumentList.FindDocument( const inFilename: string): TLrDocument; var i: Integer; begin Result := nil; for i := 0 to Pred(Count) do if Documents[i].Filename = inFilename then begin Result := Documents[i]; break; end; end; end.
unit RS232; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Comms ,Main; var com :Tcomport; // Eintrag um die Comms Unit benutzen zu können Port :TPortType = COM1; BauRate :TBaudRate = br9600; DBit :TDataBits = dbEight; Parit :TParityBits = prNone; StpBit :TStopBits = sbOneStopBit; DTR_Enable :TDtrFlowControl = dtrEnable; RTS_Enable :TRtsFlowControl = rtsEnable; RsEvents :TEvent; //[evCTS, evDSR, evRLSD]; RS232_Ergebn : real; RS232_Einheit : string; // COM Port procedure ComSettings; procedure OpenCom; procedure CloseCom; // RS232 Aufrufe function RS232_Write(kommand:string):string; function RS232_Read:string; Function RS232_PunktToKomma(s: string):string; implementation procedure ComSettings; begin Com.SetPort(Port); Com.SetBaudRate(BauRate); Com.DataBits := DBit; Com.Parity.Bits := Parit; Com.StopBits := StpBit; com.FlowControl.ControlDtr := DTR_Enable; com.FlowControl.ControlRts := RTS_Enable; com.SyncMethod := smSynchronize; // Synchrone datenübertragung benötigt ?????? com.Events := [evRxChar, evTxEmpty, evRxFlag, evRing, evBreak, evCTS, evDSR, evError, evRLSD, evRx80Full]; end; procedure OpenCom; begin if not Com.Connected then begin Com.Open; end; end; procedure CloseCom; begin Com.close; end; // ******************************************************* // ******* Command senden ********* // ******************************************************* function RS232_Write(kommand:string):string; var TextLang : Dword; begin kommand := kommand + #13; TextLang := com.WriteString(kommand,true); end; // ******************************************************* // ******* Buffer read ********* // ******************************************************* function RS232_Read:string; var i : DWord; // Time out Zähler u : word; Echar : Dword; Zeichen : char; ErgebnStr: string; switch : byte; begin ErgebnStr:=''; i := 0; u:= 0; switch := 0; main.Form1.Memo2.Clear; repeat Echar := Com.InQue; if Echar > 0 then begin Com.Read(Zeichen, 1,True); main.Form1.memo2.Lines.Add(' '+ inttostr(Echar) + ' ' +inttostr(ord(Zeichen)) + ' ' + Zeichen); ErgebnStr := ErgebnStr + zeichen; if zeichen = #13 then switch := 1 //if zeichen <> #10 then ErgebnStr := ErgebnStr + zeichen; end; if switch = 1 then begin sleep(1); Echar := Com.InQue; if Echar > 0 then begin Com.Read(Zeichen, 1,True); main.Form1.memo2.Lines.Add(' '+ inttostr(Echar) + ' ' +inttostr(ord(Zeichen)) + ' ' + Zeichen); ErgebnStr := ErgebnStr + zeichen; switch := 0; //if zeichen <> #10 then ErgebnStr := ErgebnStr + zeichen; end; end; // sleep(1); //Application.ProcessMessages; //main.form1.label2.Caption:= inttostr(i); inc(i); until (Zeichen = #13) or (I > 500000); if I >= 500000 Then Showmessage('RS232 lese Time Out'); //showmessage('ErgebnStr = >'+ErgebnStr+'<' + 'I = '+ inttostr(i)); result := ErgebnStr; end; // ***************************************************** // **** Im String Punkt durch komma resetzen **** // ***************************************************** Function RS232_PunktToKomma(s: string):string; begin result:=copy(s,0,pos('.',s)-1)+','+copy( s, pos('.',s)+1, length(s)-pos('.',s)); end; end.
unit GLDSphere; interface uses Classes, GL, GLDTypes, GLDConst, GLDClasses, GLDObjects; type TGLDSphere = class(TGLDEditableObject) protected FRadius: GLfloat; FSegments: GLushort; FSides: GLushort; FStartAngle1: GLfloat; FSweepAngle1: GLfloat; FStartAngle2: GLfloat; FSweepAngle2: GLfloat; FNormals: PGLDVector3fArray; FPoints: PGLDVector3fArray; function GetMode: GLubyte; function GetPoint(i, j: GLushort): PGLDVector3f; function GetNormal(i, j: GLushort): PGLDVector3f; procedure SetRadius(Value: GLfloat); procedure SetSegments(Value: GLushort); procedure SetSides(Value: GLushort); procedure SetStartAngle1(Value: GLfloat); procedure SetSweepAngle1(Value: GLfloat); procedure SetStartAngle2(Value: GLfloat); procedure SetSweepAngle2(Value: GLfloat); function GetParams: TGLDSphereParams; procedure SetParams(Value: TGLDSphereParams); protected procedure CalcBoundingBox; override; procedure CreateGeometry; override; procedure DestroyGeometry; override; procedure DoRender; override; procedure SimpleRender; override; public constructor Create(AOwner: TPersistent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function SysClassType: TGLDSysClassType; override; class function VisualObjectClassType: TGLDVisualObjectClass; override; class function RealName: string; override; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; function CanConvertTo(_ClassType: TClass): GLboolean; override; function ConvertTo(Dest: TPersistent): GLboolean; override; function ConvertToTriMesh(Dest: TPersistent): GLboolean; virtual; function ConvertToQuadMesh(Dest: TPersistent): GLboolean; function ConvertToPolyMesh(Dest: TPersistent): GLboolean; property Params: TGLDSphereParams read GetParams write SetParams; published property Radius: GLfloat read FRadius write SetRadius; property Segments: GLushort read FSegments write SetSegments default GLD_SPHERE_SEGMENTS_DEFAULT; property Sides: GLushort read FSides write SetSides default GLD_SPHERE_SIDES_DEFAULT; property StartAngle1: GLfloat read FStartAngle1 write SetStartAngle1; property SweepAngle1: GLfloat read FSweepAngle1 write SetSweepAngle1; property StartAngle2: GLfloat read FStartAngle2 write SetStartAngle2; property SweepAngle2: GLfloat read FSweepAngle2 write SetSweepAngle2; end; implementation uses dialogs, SysUtils, GLDGizmos, GLDX, GLDMesh, GLDUtils; var vSphereCounter: GLuint = 0; constructor TGLDSphere.Create(AOwner: TPersistent); begin inherited Create(AOwner); Inc(vSphereCounter); FName := GLD_SPHERE_STR + IntToStr(vSphereCounter); FRadius := GLD_STD_SPHEREPARAMS.Radius; FSegments := GLD_STD_SPHEREPARAMS.Segments; FSides := GLD_STD_SPHEREPARAMS.Sides; FStartAngle1 := GLD_STD_SPHEREPARAMS.StartAngle1; FSweepAngle1 := GLD_STD_SPHEREPARAMS.SweepAngle1; FStartAngle2 := GLD_STD_SPHEREPARAMS.StartAngle2; FSweepAngle2 := GLD_STD_SPHEREPARAMS.SweepAngle2; FPosition.Vector3f := GLD_STD_PLANEPARAMS.Position; FRotation.Params := GLD_STD_PLANEPARAMS.Rotation; CreateGeometry; end; destructor TGLDSphere.Destroy; begin inherited Destroy; end; procedure TGLDSphere.Assign(Source: TPersistent); begin if (Source = nil) or (Source = Self) then Exit; if not (Source is TGLDSphere) then Exit; inherited Assign(Source); SetParams(TGLDSphere(Source).GetParams); end; procedure TGLDSphere.DoRender; var iSegs, iP: GLushort; //i, j: GLushort; begin for iSegs := 1 to FSegments do begin glBegin(GL_QUAD_STRIP); for iP := 2 to FSides + 2 do begin glNormal3fv(@FNormals^[iSegs * (FSides + 3) + iP]); glVertex3fv(@FPoints^[iSegs * (FSides + 3) + iP]); glNormal3fv(@FNormals^[(iSegs + 1) * (FSides + 3) + iP]); glVertex3fv(@FPoints^[(iSegs + 1) * (FSides + 3) + iP]); end; glEnd; end; {glPushAttrib(GL_LIGHTING_BIT); glDisable(GL_LIGHTING); glColor3f(0, 0, 1); glBegin(GL_LINES); for iP := 1 to (FSegments + 3) * (FSides + 3) do begin with GLDXVectorAdd(FPoints^[iP], FNormals^[iP]) do glVertex3f(X, Y, Z); glVertex3fv(@FPoints^[iP]); end; glEnd; glColor3f(1, 0, 0); glPointSize(6); glBegin(GL_POINTS); for i := 2 to FSegments + 2 do for j := 2 to FSides + 2 do glVertex3fv(PGLfloat(GetPoint(i, j))); glEnd; glPopAttrib; } end; procedure TGLDSphere.SimpleRender; var iSegs, iP: GLushort; begin for iSegs := 1 to FSegments do begin glBegin(GL_QUAD_STRIP); for iP := 2 to FSides + 2 do begin glVertex3fv(@FPoints^[iSegs * (FSides + 3) + iP]); glVertex3fv(@FPoints^[(iSegs + 1) * (FSides + 3) + iP]); end; glEnd; end; end; procedure TGLDSphere.CalcBoundingBox; begin FBoundingBox := GLDXCalcBoundingBox(FPoints, (FSegments + 3) * (FSides + 3)); end; procedure TGLDSphere.CreateGeometry; var iSegs, iP: GLushort; A1, A2: GLfloat; N: TGLDVector3f; begin if FSegments < 1 then FSegments := 1 else if FSegments > 1000 then FSegments := 1000; if FSides < 1 then FSides := 1 else if FSides > 1000 then FSides := 1000; if FStartAngle2 < 0 then FStartAngle2 := 0 else if FStartAngle2 > 180 then FStartAngle2 := 180; if FSweepAngle2 < 0 then FSweepAngle2 := 0 else if FSweepAngle2 > 180 then FSweepAngle2 := 180; if FSweepAngle2 < FStartAngle2 then FSweepAngle2 := FStartAngle2; ReallocMem(FNormals, (FSegments + 3) * (FSides + 3) * SizeOf(TGLDVector3f)); ReallocMem(FPoints, (FSegments + 3) * (FSides + 3) * SizeOf(TGLDVector3f)); A1 := GLDXGetAngleStep(FStartAngle1, FSweepAngle1, FSides); A2 := GLDXGetAngleStep(FStartAngle2, FSweepAngle2, FSegments); if (A2 = 360) and (FSegments < 2) then FSegments := 2; if (A1 = 360) and (FSides < 3) then FSides := 3; for iSegs := 1 to FSegments + 3 do for iP := 1 to FSides + 3 do begin FPoints^[(iSegs - 1) * (FSides + 3) + iP] := // GetPoint(iSegs, iP)^ := GLDXVector3f( GLDXCoSinus(FStartAngle1 + (iP - 2) * A1) * GLDXCoSinus(90 - (FStartAngle2 + ((iSegs - 2) * A2))) * FRadius, GLDXSinus(90 - (FStartAngle2 + ((iSegs - 2) * A2))) * FRadius, -GLDXSinus(FStartAngle1 + (iP - 2) * A1) * GLDXCoSinus(90 - (FStartAngle2 + ((iSegs - 2) * A2))) * FRadius); end; FModifyList.ModifyPoints( [GLDXVector3fArrayData(FPoints, (FSegments + 3) * (FSides + 3))]); GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f( GLDXVector3fArrayData(FPoints, (FSegments + 3) * (FSides + 3)), GLDXVector3fArrayData(FNormals, (FSegments + 3) * (FSides + 3)), FSegments + 2, FSides + 2)); if FStartAngle2 < A2 then begin N := GLD_VECTOR3F_ZERO; for iP := 1 to FSides + 2 do begin N := GLDXVectorAdd(N, GLDXQuadNormal( GetPoint(1, iP-1)^, GetPoint(2, iP-1)^, GetPoint(1, iP + 0)^, GetPoint(2, iP + 0)^)); GetNormal(1, iP)^ := GLDXVectorNormalize(N); end; end; if FSweepAngle2 > (180 - A2) then begin N := GLD_VECTOR3F_ZERO; for iP := 1 to FSides + 2 do begin N := GLDXVectorAdd(N, GLDXQuadNormal( GetPoint(FSegments + 0, iP-1)^, GetPoint(FSegments + 1, iP-1)^, GetPoint(FSegments + 0, iP + 0)^, GetPoint(FSegments + 1, iP + 0)^)); GetNormal(FSegments + 1, iP)^ := GLDXVectorNormalize(N); end; end; CalcBoundingBox; end; procedure TGLDSphere.DestroyGeometry; begin ReallocMem(FNormals, 0); ReallocMem(FPoints, 0); FNormals := nil; FPoints := nil; end; class function TGLDSphere.SysClassType: TGLDSysClassType; begin Result := GLD_SYSCLASS_SPHERE; end; class function TGLDSphere.VisualObjectClassType: TGLDVisualObjectClass; begin Result := TGLDSphere; end; class function TGLDSphere.RealName: string; begin Result := GLD_SPHERE_STR; end; procedure TGLDSphere.LoadFromStream(Stream: TStream); begin inherited LoadFromStream(Stream); Stream.Read(FRadius, SizeOf(GLfloat)); Stream.Read(FSegments, SizeOf(GLushort)); Stream.Read(FSides, SizeOf(GLushort)); Stream.Read(FStartAngle1, SizeOf(GLfloat)); Stream.Read(FSweepAngle1, SizeOf(GLfloat)); Stream.Read(FStartAngle2, SizeOf(GLfloat)); Stream.Read(FSweepAngle2, SizeOf(GLfloat)); CreateGeometry; end; procedure TGLDSphere.SaveToStream(Stream: TStream); begin inherited SaveToStream(Stream); Stream.Write(FRadius, SizeOf(GLfloat)); Stream.Write(FSegments, SizeOf(GLushort)); Stream.Write(FSides, SizeOf(GLushort)); Stream.Write(FStartAngle1, SizeOf(GLfloat)); Stream.Write(FSweepAngle1, SizeOf(GLfloat)); Stream.Write(FStartAngle2, SizeOf(GLfloat)); Stream.Write(FSweepAngle2, SizeOf(GLfloat)); end; function TGLDSphere.CanConvertTo(_ClassType: TClass): GLboolean; begin Result := (_ClassType = TGLDSphere) or (_ClassType = TGLDTriMesh) or (_ClassType = TGLDQuadMesh) or (_ClassType = TGLDPolyMesh); end; function TGLDSphere.ConvertTo(Dest: TPersistent): GLboolean; begin Result := False; if not Assigned(Dest) then Exit; if Dest.ClassType = Self.ClassType then begin Dest.Assign(Self); Result := True; end else if Dest is TGLDTriMesh then Result := ConvertToTriMesh(Dest) else if Dest is TGLDQuadMesh then Result := ConvertToQuadMesh(Dest) else if Dest is TGLDPolyMesh then Result := ConvertToPolyMesh(Dest); end; {$WARNINGS OFF} function TGLDSphere.ConvertToTriMesh(Dest: TPersistent): GLboolean; var M: GLubyte; i, j: GLuint; F: TGLDTriFace; begin Result := False; if not Assigned(Dest) then Exit; if not (Dest is TGLDTriMesh) then Exit; M := GetMode; with TGLDTriMesh(Dest) do begin F.Smoothing := GLD_SMOOTH_ALL; if M = 0 then begin VertexCapacity := 2 + (FSegments - 1) * FSides; AddVertex(GetPoint(1, 1)^, True); AddVertex(GetPoint(FSegments + 1, 1)^, True); for i := 1 to FSegments - 1 do for j := 1 to FSides do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; F.Point2 := 2 + j; if j = FSides then F.Point3 := 3 else F.Point3 := 3 + j; AddFace(F); F.Point1 := 2 + (FSegments - 2) * FSides + j; F.Point2 := 2; if j = FSides then F.Point3 := 3 + (FSegments - 2) * FSides else F.Point3 := 2 + (FSegments - 2) * FSides + j + 1; AddFace(F); end; if FSegments > 2 then for i := 1 to FSegments - 2 do for j := 1 to FSides do begin F.Point1 := 2 + (i - 1) * FSides + j; F.Point2 := 2 + i * FSides + j; if j = FSides then F.Point3 := 2 + (i - 1) * FSides + 1 else F.Point3 := 2 + (i - 1) * FSides + j + 1; AddFace(F); F.Point2 := 2 + i * FSides + j; if j = FSides then begin F.Point1 := 2 + (i - 1) * FSides + 1; F.Point3 := 2 + i * FSides + 1; end else begin F.Point1 := 2 + (i - 1) * FSides + j + 1; F.Point3 := 2 + i * FSides + j + 1; end; AddFace(F); end; end else //M = 0 if M = 1 then begin VertexCapacity := 1 + FSegments * FSides; AddVertex(GetPoint(1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; F.Point2 := 1 + j; if j = FSides then F.Point3 := 2 else F.Point3 := 2 + j; AddFace(F); end; if FSegments > 1 then for i := 1 to FSegments - 1 do for j := 1 to FSides do begin F.Point1 := 1 + (i - 1) * FSides + j; F.Point2 := 1 + i * FSides + j; if j = FSides then F.Point3 := 1 + (i - 1) * FSides + 1 else F.Point3 := 1 + (i - 1) * FSides + j + 1; AddFace(F); F.Point2 := 1 + i * FSides + j; if j = FSides then begin F.Point1 := 1 + (i - 1) * FSides + 1; F.Point3 := 1 + i * FSides + 1; end else begin F.Point1 := 1 + (i - 1) * FSides + j + 1; F.Point3 := 1 + i * FSides + j + 1; end; AddFace(F); end; end else //M = 1 if M = 2 then begin VertexCapacity := 1 + FSegments * FSides; AddVertex(GetPoint(FSegments + 1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides do AddVertex(GetPoint(i, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; if j = FSides then F.Point2 := 2 + (FSegments - 1) * FSides else F.Point2 := 2 + (FSegments - 1) * FSides + j; F.Point3 := 1 + (FSegments - 1) * FSides + j; AddFace(F); end; if FSegments > 1 then for i := 1 to FSegments - 1 do for j := 1 to FSides do begin F.Point1 := 1 + (i - 1) * FSides + j; F.Point2 := 1 + i * FSides + j; if j = FSides then F.Point3 := 1 + (i - 1) * FSides + 1 else F.Point3 := 1 + (i - 1) * FSides + j + 1; AddFace(F); F.Point2 := 1 + i * FSides + j; if j = FSides then begin F.Point1 := 1 + (i - 1) * FSides + 1; F.Point3 := 1 + i * FSides + 1; end else begin F.Point1 := 1 + (i - 1) * FSides + j + 1; F.Point3 := 1 + i * FSides + j + 1; end; AddFace(F); end; end else //M = 2 if M = 3 then begin VertexCapacity := (FSegments + 1) * FSides; for i := 1 to FSegments + 1 do for j := 1 to FSides do AddVertex(GetPoint(i, j)^, True); for i := 1 to FSegments do for j := 1 to FSides do begin F.Point1 := (i - 1) * FSides + j; F.Point2 := i * FSides + j; if j = FSides then F.Point3 := (i - 1) * FSides + 1 else F.Point3 := (i - 1) * FSides + j + 1; AddFace(F); F.Point2 := i * FSides + j; if j = FSides then begin F.Point1 := (i - 1) * FSides + 1; F.Point3 := i * FSides + 1; end else begin F.Point1 := (i - 1) * FSides + j + 1; F.Point3 := i * FSides + j + 1; end; AddFace(F); end; end else //M = 3 if M = 4 then begin VertexCapacity := 2 + (FSegments - 1) * (FSides + 1); AddVertex(GetPoint(1, 1)^, True); AddVertex(GetPoint(FSegments + 1, 1)^, True); for i := 1 to FSegments - 1 do for j := 1 to FSides + 1 do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; F.Point2 := 2 + j; F.Point3 := 3 + j; AddFace(F); F.Point1 := 2; F.Point2 := 3 + (FSegments - 2) * (FSides + 1) + j; F.Point3 := 2 + (FSegments - 2) * (FSides + 1) + j; AddFace(F); end; if FSegments > 2 then for i := 1 to FSegments - 2 do for j := 1 to FSides do begin F.Point1 := 2 + (i - 1) * (FSides + 1) + j; F.Point2 := 2 + i * (FSides + 1) + j; F.Point3 := 2 + (i - 1) * (FSides + 1) + j + 1; AddFace(F); F.Point1 := 2 + (i - 1) * (FSides + 1) + j + 1; F.Point2 := 2 + i * (FSides + 1) + j; F.Point3 := 2 + i * (FSides + 1) + j + 1; AddFace(F); end; end else //M = 4 if M = 5 then begin VertexCapacity := 1 + FSegments * (FSides + 1); AddVertex(GetPoint(1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides + 1 do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; F.Point2 := 1 + j; F.Point3 := 2 + j; AddFace(F); end; if FSegments > 1 then for i := 1 to FSegments - 1 do for j := 1 to FSides do begin F.Point1 := 1 + (i - 1) * (FSides + 1) + j; F.Point2 := 1 + i * (FSides + 1) + j; F.Point3 := 1 + (i - 1) * (FSides + 1) + j + 1; AddFace(F); F.Point1 := 1 + (i - 1) * (FSides + 1) + j + 1; F.Point2 := 1 + i * (FSides + 1) + j; F.Point3 := 1 + i * (FSides + 1) + j + 1; AddFace(F); end; end else //M = 5 if M = 6 then begin VertexCapacity := 1 + FSegments * (FSides + 1); AddVertex(GetPoint(FSegments + 1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides + 1 do AddVertex(GetPoint(i, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; F.Point2 := 2 + (FSegments - 1) * (FSides + 1) + j; F.Point3 := 1 + (FSegments - 1) * (FSides + 1) + j; AddFace(F); end; if FSegments > 1 then for i := 1 to FSegments - 1 do for j := 1 to FSides do begin F.Point1 := 1 + (i - 1) * (FSides + 1) + j; F.Point2 := 1 + i * (FSides + 1) + j; F.Point3 := 1 + (i - 1) * (FSides + 1) + j + 1; AddFace(F); F.Point1 := 1 + (i - 1) * (FSides + 1) + j + 1; F.Point2 := 1 + i * (FSides + 1) + j; F.Point3 := 1 + i * (FSides + 1) + j + 1; AddFace(F); end; end else //M = 6 if M = 7 then begin VertexCapacity := (FSegments + 1) * (FSides + 1); for i := 1 to FSegments + 1 do for j := 1 to FSides + 1 do AddVertex(GetPoint(i, j)^, True); for i := 1 to FSegments do for j := 1 to FSides do begin F.Point1 := (i - 1) * (FSides + 1) + j; F.Point2 := i * (FSides + 1) + j; F.Point3 := (i - 1) * (FSides + 1) + j + 1; AddFace(F); F.Point1 := (i - 1) * (FSides + 1) + j + 1; F.Point2 := i * (FSides + 1) + j; F.Point3 := i * (FSides + 1) + j + 1; AddFace(F); end; end; //M = 7 CalcNormals; CalcBoundingBox; PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f; PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f; PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params; TGLDTriMesh(Dest).Selected := Self.Selected; TGLDTriMesh(Dest).Name := Self.Name; end; Result := True; end; function TGLDSphere.ConvertToQuadMesh(Dest: TPersistent): GLboolean; var M: GLubyte; i, j: GLuint; F: TGLDQuadFace; begin Result := False; if not Assigned(Dest) then Exit; if not (Dest is TGLDQuadMesh) then Exit; M := GetMode; with TGLDQuadMesh(Dest) do begin F.Smoothing := GLD_SMOOTH_ALL; if M = 0 then begin VertexCapacity := 2 + (FSegments - 1) * FSides; AddVertex(GetPoint(1, 1)^, True); AddVertex(GetPoint(FSegments + 1, 1)^, True); for i := 1 to FSegments - 1 do for j := 1 to FSides do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; F.Point2 := 2 + j; if j = FSides then F.Point3 := 3 else F.Point3 := 3 + j; F.Point4 := F.Point1; AddFace(F); F.Point1 := 2 + (FSegments - 2) * FSides + j; F.Point2 := 2; if j = FSides then F.Point3 := 3 + (FSegments - 2) * FSides else F.Point3 := 2 + (FSegments - 2) * FSides + j + 1; F.Point4 := F.Point1; AddFace(F); end; if FSegments > 2 then for i := 1 to FSegments - 2 do for j := 1 to FSides do begin F.Point1 := 2 + (i - 1) * FSides + j; F.Point2 := 2 + i * FSides + j; if j = FSides then begin F.Point3 := 2 + i * FSides + 1; F.Point4 := 2 + (i - 1) * FSides + 1; end else begin F.Point3 := 2 + i * FSides + j + 1; F.Point4 := 2 + (i - 1) * FSides + j + 1; end; AddFace(F); end; end else //M = 0 if M = 1 then begin VertexCapacity := 1 + FSegments * FSides; AddVertex(GetPoint(1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; F.Point2 := 1 + j; if j = FSides then F.Point3 := 2 else F.Point3 := 2 + j; F.Point4 := F.Point1; AddFace(F); end; if FSegments > 1 then for i := 1 to FSegments - 1 do for j := 1 to FSides do begin F.Point1 := 1 + (i - 1) * FSides + j; F.Point2 := 1 + i * FSides + j; if j = FSides then begin F.Point3 := 1 + i * FSides + 1; F.Point4 := 1 + (i - 1) * FSides + 1; end else begin F.Point3 := 1 + i * FSides + j + 1; F.Point4 := 1 + (i - 1) * FSides + j + 1; end; AddFace(F); end; end else //M = 1 if M = 2 then begin VertexCapacity := 1 + FSegments * FSides; AddVertex(GetPoint(FSegments + 1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides do AddVertex(GetPoint(i, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; if j = FSides then F.Point2 := 2 + (FSegments - 1) * FSides else F.Point2 := 2 + (FSegments - 1) * FSides + j; F.Point3 := 1 + (FSegments - 1) * FSides + j; F.Point4 := F.Point1; AddFace(F); end; if FSegments > 1 then for i := 1 to FSegments - 1 do for j := 1 to FSides do begin F.Point1 := 1 + (i - 1) * FSides + j; F.Point2 := 1 + i * FSides + j; if j = FSides then begin F.Point3 := 1 + i * FSides + 1; F.Point4 := 1 + (i - 1) * FSides + 1; end else begin F.Point3 := 1 + i * FSides + j + 1; F.Point4 := 1 + (i - 1) * FSides + j + 1; end; AddFace(F); end; end else //M = 2 if M = 3 then begin VertexCapacity := (FSegments + 1) * FSides; for i := 1 to FSegments + 1 do for j := 1 to FSides do AddVertex(GetPoint(i, j)^, True); for i := 1 to FSegments do for j := 1 to FSides do begin F.Point1 := (i - 1) * FSides + j; F.Point2 := i * FSides + j; if j = FSides then begin F.Point3 := i * FSides + 1; F.Point4 := (i - 1) * FSides + 1; end else begin F.Point3 := i * FSides + j + 1; F.Point4 := (i - 1) * FSides + j + 1; end; AddFace(F); end; end else //M = 3 if M = 4 then begin VertexCapacity := 2 + (FSegments - 1) * (FSides + 1); AddVertex(GetPoint(1, 1)^, True); AddVertex(GetPoint(FSegments + 1, 1)^, True); for i := 1 to FSegments - 1 do for j := 1 to FSides + 1 do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; F.Point2 := 2 + j; F.Point3 := 3 + j; F.Point4 := F.Point1; AddFace(F); F.Point1 := 2; F.Point2 := 3 + (FSegments - 2) * (FSides + 1) + j; F.Point3 := 2 + (FSegments - 2) * (FSides + 1) + j; F.Point4 := F.Point1; AddFace(F); end; if FSegments > 2 then for i := 1 to FSegments - 2 do for j := 1 to FSides do begin F.Point1 := 2 + (i - 1) * (FSides + 1) + j; F.Point2 := 2 + i * (FSides + 1) + j; F.Point3 := 2 + i * (FSides + 1) + j + 1; F.Point4 := 2 + (i - 1) * (FSides + 1) + j + 1; AddFace(F); end; end else //M = 4 if M = 5 then begin VertexCapacity := 1 + FSegments * (FSides + 1); AddVertex(GetPoint(1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides + 1 do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; F.Point2 := 1 + j; F.Point3 := 2 + j; F.Point4 := F.Point1; AddFace(F); end; if FSegments > 1 then for i := 1 to FSegments - 1 do for j := 1 to FSides do begin F.Point1 := 1 + (i - 1) * (FSides + 1) + j; F.Point2 := 1 + i * (FSides + 1) + j; F.Point3 := 1 + i * (FSides + 1) + j + 1; F.Point4 := 1 + (i - 1) * (FSides + 1) + j + 1; AddFace(F); end; end else //M = 5 if M = 6 then begin VertexCapacity := 1 + FSegments * (FSides + 1); AddVertex(GetPoint(FSegments + 1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides + 1 do AddVertex(GetPoint(i, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; F.Point2 := 2 + (FSegments - 1) * (FSides + 1) + j; F.Point3 := 1 + (FSegments - 1) * (FSides + 1) + j; F.Point4 := F.Point1; AddFace(F); end; if FSegments > 1 then for i := 1 to FSegments - 1 do for j := 1 to FSides do begin F.Point1 := 1 + (i - 1) * (FSides + 1) + j; F.Point2 := 1 + i * (FSides + 1) + j; F.Point3 := 1 + i * (FSides + 1) + j + 1; F.Point4 := 1 + (i - 1) * (FSides + 1) + j + 1; AddFace(F); end; end else //M = 6 if M = 7 then begin VertexCapacity := (FSegments + 1) * (FSides + 1); for i := 1 to FSegments + 1 do for j := 1 to FSides + 1 do AddVertex(GetPoint(i, j)^, True); for i := 1 to FSegments do for j := 1 to FSides do begin F.Point1 := (i - 1) * (FSides + 1) + j; F.Point2 := i * (FSides + 1) + j; F.Point3 := i * (FSides + 1) + j + 1; F.Point4 := (i - 1) * (FSides + 1) + j + 1; AddFace(F); end; end; //M = 7 CalcNormals; CalcBoundingBox; PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f; PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f; PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params; TGLDQuadMesh(Dest).Selected := Self.Selected; TGLDQuadMesh(Dest).Name := Self.Name; end; Result := True; end; function TGLDSphere.ConvertToPolyMesh(Dest: TPersistent): GLboolean; var M: GLubyte; i, j: GLuint; P: TGLDPolygon; begin Result := False; if not Assigned(Dest) then Exit; if not (Dest is TGLDPolyMesh) then Exit; M := GetMode; with TGLDPolyMesh(Dest) do begin if M = 0 then begin VertexCapacity := 2 + (FSegments - 1) * FSides; AddVertex(GetPoint(1, 1)^, True); AddVertex(GetPoint(FSegments + 1, 1)^, True); for i := 1 to FSegments - 1 do for j := 1 to FSides do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 3); P.Data^[1] := 1; P.Data^[2] := 2 + j; if j = FSides then P.Data^[3] := 3 else P.Data^[3] := 3 + j; //F.Point4 := F.Point1; AddFace(P); P := GLD_STD_POLYGON; GLDURealloc(P, 3); P.Data^[1] := 2 + (FSegments - 2) * FSides + j; P.Data^[2] := 2; if j = FSides then P.Data^[3] := 3 + (FSegments - 2) * FSides else P.Data^[3] := 2 + (FSegments - 2) * FSides + j + 1; //F.Point4 := F.Point1; AddFace(P); end; if FSegments > 2 then for i := 1 to FSegments - 2 do for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 4); P.Data^[1] := 2 + (i - 1) * FSides + j; P.Data^[2] := 2 + i * FSides + j; if j = FSides then begin P.Data^[3] := 2 + i * FSides + 1; P.Data^[4] := 2 + (i - 1) * FSides + 1; end else begin P.Data^[3] := 2 + i * FSides + j + 1; P.Data^[4] := 2 + (i - 1) * FSides + j + 1; end; AddFace(P); end; end else //M = 0 if M = 1 then begin VertexCapacity := 1 + FSegments * FSides; AddVertex(GetPoint(1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 3); P.Data^[1] := 1; P.Data^[2] := 1 + j; if j = FSides then P.Data^[3] := 2 else P.Data^[3] := 2 + j; //F.Point4 := F.Point1; AddFace(P); end; if FSegments > 1 then for i := 1 to FSegments - 1 do for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 4); P.Data^[1] := 1 + (i - 1) * FSides + j; P.Data^[2] := 1 + i * FSides + j; if j = FSides then begin P.Data^[3] := 1 + i * FSides + 1; P.Data^[4] := 1 + (i - 1) * FSides + 1; end else begin P.Data^[3] := 1 + i * FSides + j + 1; P.Data^[4] := 1 + (i - 1) * FSides + j + 1; end; AddFace(P); end; end else //M = 1 if M = 2 then begin VertexCapacity := 1 + FSegments * FSides; AddVertex(GetPoint(FSegments + 1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides do AddVertex(GetPoint(i, j)^, True); for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 3); P.Data^[1] := 1; if j = FSides then P.Data^[2] := 2 + (FSegments - 1) * FSides else P.Data^[2] := 2 + (FSegments - 1) * FSides + j; P.Data^[3] := 1 + (FSegments - 1) * FSides + j; //F.Point4 := F.Point1; AddFace(P); end; if FSegments > 1 then for i := 1 to FSegments - 1 do for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 4); P.Data^[1] := 1 + (i - 1) * FSides + j; P.Data^[2] := 1 + i * FSides + j; if j = FSides then begin P.Data^[3] := 1 + i * FSides + 1; P.Data^[4] := 1 + (i - 1) * FSides + 1; end else begin P.Data^[3] := 1 + i * FSides + j + 1; P.Data^[4] := 1 + (i - 1) * FSides + j + 1; end; AddFace(P); end; end else //M = 2 if M = 3 then begin VertexCapacity := (FSegments + 1) * FSides; for i := 1 to FSegments + 1 do for j := 1 to FSides do AddVertex(GetPoint(i, j)^, True); for i := 1 to FSegments do for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 4); P.Data^[1] := (i - 1) * FSides + j; P.Data^[2] := i * FSides + j; if j = FSides then begin P.Data^[3] := i * FSides + 1; P.Data^[4] := (i - 1) * FSides + 1; end else begin P.Data^[3] := i * FSides + j + 1; P.Data^[4] := (i - 1) * FSides + j + 1; end; AddFace(P); end; end else //M = 3 if M = 4 then begin VertexCapacity := 2 + (FSegments - 1) * (FSides + 1); AddVertex(GetPoint(1, 1)^, True); AddVertex(GetPoint(FSegments + 1, 1)^, True); for i := 1 to FSegments - 1 do for j := 1 to FSides + 1 do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 3); P.Data^[1] := 1; P.Data^[2] := 2 + j; P.Data^[3] := 3 + j; //F.Point4 := F.Point1; AddFace(P); P := GLD_STD_POLYGON; GLDURealloc(P, 3); P.Data^[1] := 2; P.Data^[2] := 3 + (FSegments - 2) * (FSides + 1) + j; P.Data^[3] := 2 + (FSegments - 2) * (FSides + 1) + j; //F.Point4 := F.Point1; AddFace(P); end; if FSegments > 2 then for i := 1 to FSegments - 2 do for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 4); P.Data^[1] := 2 + (i - 1) * (FSides + 1) + j; P.Data^[2] := 2 + i * (FSides + 1) + j; P.Data^[3] := 2 + i * (FSides + 1) + j + 1; P.Data^[4] := 2 + (i - 1) * (FSides + 1) + j + 1; AddFace(P); end; end else //M = 4 if M = 5 then begin VertexCapacity := 1 + FSegments * (FSides + 1); AddVertex(GetPoint(1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides + 1 do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 3); P.Data^[1] := 1; P.Data^[2] := 1 + j; P.Data^[3] := 2 + j; //F.Point4 := F.Point1; AddFace(P); end; if FSegments > 1 then for i := 1 to FSegments - 1 do for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 4); P.Data^[1] := 1 + (i - 1) * (FSides + 1) + j; P.Data^[2] := 1 + i * (FSides + 1) + j; P.Data^[3] := 1 + i * (FSides + 1) + j + 1; P.Data^[4] := 1 + (i - 1) * (FSides + 1) + j + 1; AddFace(P); end; end else //M = 5 if M = 6 then begin VertexCapacity := 1 + FSegments * (FSides + 1); AddVertex(GetPoint(FSegments + 1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides + 1 do AddVertex(GetPoint(i, j)^, True); for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 3); P.Data^[1] := 1; P.Data^[2] := 2 + (FSegments - 1) * (FSides + 1) + j; P.Data^[3] := 1 + (FSegments - 1) * (FSides + 1) + j; //F.Point4 := F.Point1; AddFace(P); end; if FSegments > 1 then for i := 1 to FSegments - 1 do for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 4); P.Data^[1] := 1 + (i - 1) * (FSides + 1) + j; P.Data^[2] := 1 + i * (FSides + 1) + j; P.Data^[3] := 1 + i * (FSides + 1) + j + 1; P.Data^[4] := 1 + (i - 1) * (FSides + 1) + j + 1; AddFace(P); end; end else //M = 6 if M = 7 then begin VertexCapacity := (FSegments + 1) * (FSides + 1); for i := 1 to FSegments + 1 do for j := 1 to FSides + 1 do AddVertex(GetPoint(i, j)^, True); for i := 1 to FSegments do for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 4); P.Data^[1] := (i - 1) * (FSides + 1) + j; P.Data^[2] := i * (FSides + 1) + j; P.Data^[3] := i * (FSides + 1) + j + 1; P.Data^[4] := (i - 1) * (FSides + 1) + j + 1; AddFace(P); end; end; //M = 7 CalcNormals; CalcBoundingBox; PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f; PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f; PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params; TGLDPolyMesh(Dest).Selected := Self.Selected; TGLDPolyMesh(Dest).Name := Self.Name; end; Result := True; end; {$WARNINGS ON} function TGLDSphere.GetMode: GLubyte; begin if (FStartAngle2 = 0) and (FSweepAngle2 = 180) then Result := 0 else if (FStartAngle2 = 0) and (FSweepAngle2 < 180) then Result := 1 else if (FStartAngle2 > 0) and (FSweepAngle2 = 180) then Result := 2 else if (FStartAngle2 > 0) and (FSweepAngle2 < 180) then Result := 3 else Result := 8; if GLDXGetAngle(FStartAngle1, FSweepAngle1) <> 360 then Inc(Result, 4); end; function TGLDSphere.GetPoint(i, j: GLushort): PGLDVector3f; begin Result := @FPoints^[i * (FSides + 3) + j + 1]; end; function TGLDSphere.GetNormal(i, j: GLushort): PGLDVector3f; begin Result := @FNormals^[i * (FSides + 3) + j + 1]; end; procedure TGLDSphere.SetRadius(Value: GLfloat); begin if FRadius = Value then Exit; FRadius := Value; CreateGeometry; Change; end; procedure TGLDSphere.SetSegments(Value: GLushort); begin if FSegments = Value then Exit; FSegments := Value; CreateGeometry; Change; end; procedure TGLDSphere.SetSides(Value: GLushort); begin if FSides = Value then Exit; FSides := Value; CreateGeometry; Change; end; procedure TGLDSphere.SetStartAngle1(Value: GLfloat); begin if FStartAngle1 = Value then Exit; FStartAngle1 := Value; CreateGeometry; Change; end; procedure TGLDSphere.SetSweepAngle1(Value: GLfloat); begin if FSweepAngle1 = Value then Exit; FSweepAngle1 := Value; CreateGeometry; Change; end; procedure TGLDSphere.SetStartAngle2(Value: GLfloat); begin if FStartAngle2 = Value then Exit; FStartAngle2 := Value; CreateGeometry; Change; end; procedure TGLDSphere.SetSweepAngle2(Value: GLfloat); begin if FSweepAngle2 = Value then Exit; FSweepAngle2 := Value; CreateGeometry; Change; end; function TGLDSphere.GetParams: TGLDSphereParams; begin Result := GLDXSphereParams(FColor.Color3ub, FRadius, FSegments, FSides, FStartAngle1, FSweepAngle1, FStartAngle2, FSweepAngle2, FPosition.Vector3f, FRotation.Params); end; procedure TGLDSphere.SetParams(Value: TGLDSphereParams); begin if GLDXSphereParamsEqual(GetParams, Value) then Exit; PGLDColor3f(FColor.GetPointer)^ := GLDXColor3f(Value.Color); FRadius := Value.Radius; FSegments := Value.Segments; FSides := Value.Sides; FStartAngle1 := Value.StartAngle1; FSweepAngle1 := Value.SweepAngle1; FStartAngle2 := Value.StartAngle2; FSweepAngle2 := Value.SweepAngle2; PGLDVector3f(FPosition.GetPointer)^ := Value.Position; PGLDRotation3D(FRotation.GetPointer)^ := Value.Rotation; CreateGeometry; Change; end; end.
unit SendEMail; interface Uses Classes, IdComponent, IdTCPConnection, IdTCPClient, IdMessageClient, IdSMTP, IdBaseComponent, IdMessage; Type TSendEMail = Class(TObject) protected { Protected declarations } IdMsgSend : TIdMessage; SMTP : TIdSMTP; public { Public declarations } Constructor Create; Destructor Destroy; override; Procedure Send; private { Private declarations } FNeedToLogin : Boolean; Function GetHost:String; Procedure SetHost(Value:String); Function GetPort:Integer; Procedure SetPort(Value:Integer); Function GetUserName:String; Procedure SetUserName(Value:String); Function GetPassword:String; Procedure SetPassword(Value:String); Function GetContent:String; Procedure SetContent(Value:String); Function GetFromAddr:String; Procedure SetFromAddr(Value:String); Function GetToAddr:String; Procedure SetToAddr(Value:String); Function GetSubject:String; Procedure SetSubject(Value:String); Function GetPriority:Integer; Procedure SetPriority(Value:Integer); Function GetCCList:String; Procedure SetCCList(Value:String); Function GetBCCList:String; Procedure SetBCCList(Value:String); Published { Published declarations } Property Host : String read GetHost write SetHost; Property Port : Integer read GetPort write SetPort; Property UserName : String read GetUserName write SetUserName; Property Password : String read GetPassword write SetPassword; Property NeedToLogin : Boolean read FNeedToLogin write FNeedToLogin default False; Property Content : String read GetContent write SetContent; Property FromAddr : String read GetFromAddr write SetFromAddr; Property ToAddr : String read GetToAddr write SetToAddr; Property Subject : String read GetSubject write SetSubject; Property Priority : Integer read GetPriority write SetPriority; Property CCList : String read GetCCList write SetCCList; Property BCCList : String read GetBCCList write SetBCCList; End; implementation Constructor TSendEMail.Create; Begin Inherited Create; IdMsgSend:= TIdMessage.Create(Nil); SMTP:= TIdSMTP.Create(Nil); End; Destructor TSendEMail.Destroy; Begin IdMsgSend.Free; SMTP.Free; Inherited Destroy; End; Procedure TSendEMail.Send; Begin If FNeedToLogin = True then SMTP.AuthenticationType:= atLogin Else SMTP.AuthenticationType:= atNone; SMTP.Connect; Try SMTP.Send(IdMsgSend); Finally SMTP.Disconnect; End; End; Function TSendEMail.GetHost:String; Begin Result:= SMTP.Host; End; Procedure TSendEMail.SetHost(Value:String); Begin SMTP.Host:= Value; End; Function TSendEMail.GetPort:Integer; Begin Result:= SMTP.Port; End; Procedure TSendEMail.SetPort(Value:Integer); Begin SMTP.Port:= Value; End; Function TSendEMail.GetUserName:String; Begin Result:= SMTP.UserName; End; Procedure TSendEMail.SetUserName(Value:String); Begin SMTP.UserName:= Value; End; Function TSendEMail.GetPassword:String; Begin Result:= SMTP.Password; End; Procedure TSendEMail.SetPassword(Value:String); Begin SMTP.Password:= Value; End; Function TSendEMail.GetContent:String; Begin Result:= IdMsgSend.Body.Text; End; Procedure TSendEMail.SetContent(Value:String); Begin IdMsgSend.Body.Text:= Value; End; Function TSendEMail.GetFromAddr:String; Begin Result:= IdMsgSend.From.Text; End; Procedure TSendEMail.SetFromAddr(Value:String); Begin IdMsgSend.From.Text:= Value; IdMsgSend.ReplyTo.EMailAddresses:= Value; IdMsgSend.ReceiptRecipient.Text:= Value; End; Function TSendEMail.GetToAddr:String; Begin Result:= IdMsgSend.Recipients.EMailAddresses; End; Procedure TSendEMail.SetToAddr(Value:String); Begin IdMsgSend.Recipients.EMailAddresses:= Value; End; Function TSendEMail.GetSubject:String; Begin Result:= IdMsgSend.Subject; End; Procedure TSendEMail.SetSubject(Value:String); Begin IdMsgSend.Subject:= Value; End; Function TSendEMail.GetPriority:Integer; Begin Result:= Integer(IdMsgSend.Priority); End; Procedure TSendEMail.SetPriority(Value:Integer); Begin IdMsgSend.Priority:= TIdMessagePriority(Value); End; Function TSendEMail.GetCCList:String; Begin Result:= IdMsgSend.CCList.EMailAddresses; End; Procedure TSendEMail.SetCCList(Value:String); Begin IdMsgSend.CCList.EMailAddresses:= Value; End; Function TSendEMail.GetBCCList:String; Begin Result:= IdMsgSend.BCCList.EMailAddresses; End; Procedure TSendEMail.SetBCCList(Value:String); Begin IdMsgSend.BCCList.EMailAddresses:= Value; End; end.
unit Lfddir; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, Buttons, ExtCtrls, StdCtrls, M_Global, L_Util, Clipbrd; type TLFDDIRWindow = class(TForm) SpeedBar: TPanel; SpeedButtonExit: TSpeedButton; SP_Main: TPanel; SP_Time: TPanel; SP_Text: TPanel; SP_Time_: TTimer; LFDDIRContents: TMemo; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; SpeedButton1: TSpeedButton; Panel5: TPanel; PanelLFDName: TPanel; PanelSize: TPanel; PanelDate: TPanel; procedure SpeedButtonExitClick(Sender: TObject); procedure SP_Time_Timer(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormActivate(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure DisplayHint(Sender: TObject); end; var LFDDIRWindow: TLFDDIRWindow; implementation {$R *.DFM} procedure TLFDDIRWindow.SpeedButtonExitClick(Sender: TObject); begin LFDDIRWindow.Close; end; procedure TLFDDIRWindow.SP_Time_Timer(Sender: TObject); begin SP_Time.Caption := FormatDateTime('hh:mm', Time); end; procedure TLFDDIRWindow.FormShow(Sender: TObject); begin SP_Time.Caption := FormatDateTime('hh:mm', Time); end; procedure TLFDDIRWindow.DisplayHint(Sender: TObject); begin SP_Text.Caption := Application.Hint; end; procedure TLFDDIRWindow.FormActivate(Sender: TObject); var f : Integer; begin Application.OnHint := DisplayHint; f := FileOpen(CurrentLFD, fmOpenRead); PanelLFDName.Caption := CurrentLFD; PanelSize.Caption := 'Size:' + IntToStr(FileSizing(f)) + ' bytes'; PanelDate.Caption := 'Timestamp: ' + DateToStr(FileDateToDateTime(FileGetDate(f))) + ' ' + TimeToStr(FileDateToDateTime(FileGetDate(f))); FileClose(f); CASE LFD_GetDetailedDirList(CurrentLFD , LFDDIRWindow.LFDDirContents) OF -1 : Application.MessageBox('File does not exist', 'LFD File Manager Error', mb_Ok or mb_IconExclamation); -2 : Application.MessageBox('File is not a LFD file', 'LFD File Manager Error', mb_Ok or mb_IconExclamation); END; end; procedure TLFDDIRWindow.SpeedButton1Click(Sender: TObject); begin LFDDIRContents.SelectAll; LFDDIRContents.CopyToClipboard; LFDDIRContents.SelLength := 0; end; end.
unit sgDriverInput; interface uses sgDriverSDL2Types, sgBackendTypes, sgTypes; function GetInputCallbackFunction() : sg_input_callbacks; function WindowForPointer(p: Pointer): WindowPtr; function IsKeyPressed(virtKeyCode : LongInt) : Boolean; procedure ProcessEvents(); function RelativeMouseState(var x : LongInt; var y : LongInt) : Byte; function MouseState(var x : LongInt; var y : LongInt): Byte; function ShowCursor(toggle : LongInt): LongInt; procedure WarpMouse(x,y : Word); procedure MoveWindow(wnd: WindowPtr; x, y: Longint); function WindowPosition(wnd: WindowPtr): Point2D; implementation uses sgInputBackend, sgShared, sgWindowManager, sgGeometry; function WindowForPointer(p: Pointer): WindowPtr; var i, count: Integer; begin count := WindowCount(); for i := 0 to count - 1 do begin result := WindowPtr(WindowAtIndex(i)); // WriteLn('TEsting: ', HexStr(p), ' = ', HexStr(result), ' ', HexStr(result^.image.surface._data)); if result^.image.surface._data = p then begin exit; end; end; result := nil; end; procedure MoveWindow(wnd: WindowPtr; x, y: Longint); begin _sg_functions^.input.move_window(@wnd^.image.surface, x, y); end; function WindowPosition(wnd: WindowPtr): Point2D; var x, y: Integer; begin _sg_functions^.input.window_position(@wnd^.image.surface, @x, @y); // WriteLn('Window at ', x, ',', y); result := PointAt(x, y); end; function IsKeyPressed(virtKeyCode : LongInt) : Boolean; begin result := _sg_functions^.input.key_pressed(virtKeyCode) <> 0; end; procedure ProcessEvents(); begin _sg_functions^.input.process_events(); end; function RelativeMouseState(var x : LongInt; var y : LongInt) : Byte; begin result := _sg_functions^.input.mouse_relative_state(@x, @y); end; function MouseState(var x : LongInt; var y : LongInt): Byte; var wind: Window; begin result := _sg_functions^.input.mouse_state(@x, @y); if _CurrentWindow^.eventData.has_focus = 0 then begin wind := WindowWithFocus(); x := x + ToWindowPtr(wind)^.x - _CurrentWindow^.x; y := y + ToWindowPtr(wind)^.y - _CurrentWindow^.y; // WriteLn('Changing X: focus ', ToWindowPtr(wind)^.x, ' to ', _CurrentWindow^.x); end; end; function ShowCursor(toggle : LongInt):LongInt; begin result := _sg_functions^.input.mouse_cursor_state(toggle); end; procedure WarpMouse(x,y : Word); begin if Assigned(_CurrentWindow) then _sg_functions^.input.warp_mouse(@_CurrentWindow^.image.surface, x, y); end; procedure HandleKeydownEventCallback(code: Longint); cdecl; begin HandleKeydownEvent(code, code); end; procedure HandleKeyupEventCallback(code: Longint); cdecl; begin HandleKeyupEvent(code); end; procedure ProcessMouseEventCallback(code: Longint); cdecl; begin ProcessMouseEvent(code); end; procedure ProcessMouseWheelCallback(x, y: Longint); cdecl; begin ProcessMouseWheelEvent(x, y); end; procedure DoQuitCallback(); cdecl; begin DoQuit(); end; procedure HandleInputTextCallback(ttext: PChar); cdecl; begin ProcessTextEntry(ttext); end; procedure HandleWindowResize(p: Pointer; w, h: Longint); cdecl; var wind: WindowPtr; begin wind := WindowForPointer(p); if Assigned(wind) then begin wind^.image.surface.width := w; wind^.image.surface.height := h; end; end; procedure HandleWindowMove(p: Pointer; x, y: Longint); cdecl; var wind: WindowPtr; begin // WriteLn('Move to ', x, ',', y); wind := WindowForPointer(p); // WriteLn(HexStr(wind)); if Assigned(wind) then begin // WriteLn('Assigning window'); wind^.x := x; wind^.y := y; end; end; function GetInputCallbackFunction() : sg_input_callbacks; begin result.do_quit := @DoQuitCallback; result.handle_key_down := @HandleKeydownEventCallback; result.handle_key_up := @HandleKeyupEventCallback; result.handle_mouse_up := @ProcessMouseEventCallback; // click occurs on up result.handle_mouse_down := nil; result.handle_mouse_wheel := @ProcessMouseWheelCallback; // click occurs on up result.handle_input_text := @HandleInputTextCallback; result.handle_window_resize := @HandleWindowResize; result.handle_window_move := @HandleWindowMove; end; end.
unit TurboPhpDocument; interface uses SysUtils, Classes, Controls, LrDocument, htStyle, htDocument, htGenerator, Design, {Generator,} Project; type TTurboPhpDocumentData = class(TComponent) private FJavaScript: TStringList; FPHP: TStringList; FBodyAttributes: string; FBodyStyle: ThtStyle; protected procedure SetBodyAttributes(const Value: string); procedure SetBodyStyle(const Value: ThtStyle); procedure SetJavaScript(const Value: TStringList); procedure SetPHP(const Value: TStringList); public constructor Create(inOwner: TComponent); override; destructor Destroy; override; published property BodyStyle: ThtStyle read FBodyStyle write SetBodyStyle; property BodyAttributes: string read FBodyAttributes write SetBodyAttributes; property JavaScript: TStringList read FJavaScript write SetJavaScript; property PHP: TStringList read FPHP write SetPHP; end; // TTurboMarkup = class(ThtDocument) public procedure BuildHtml(inStrings: TStrings); procedure Generate(inDesignSurface: TWinControl); end; // TTurboJsPublisher = class private FJavaScript: TStringList; protected procedure NewJavaScriptSource; procedure PublishJavaScript(const inTarget: string); public constructor Create; destructor Destroy; override; published property JavaScript: TStringList read FJavaScript write FJavaScript; end; // TTurboPhpDocument = class(TPublishableDocument) public class function DocumentExt: string; class function DocumentDescription: string; private FData: TTurboPhpDocumentData; FDesignForm: TDesignForm; PhpIncludes: TStringList; PublishPath: string; protected PublishName: string; function CreateMarkup: TTurboMarkup; virtual; function GetConfigTarget: string; function GetHtmlName: string; function GetHtmlTarget: string; function GetJavaScriptTarget: string; function GetPageName: string; function GetPhpName: string; function GetPhpTarget: string; procedure CustomizeMarkup(inMarkup: TTurboMarkup); virtual; procedure CreateData; procedure DoPublish; virtual; procedure InitializeIncludes; procedure NewPhpSource; procedure NewJavaScriptSource; procedure PublishHtml; virtual; procedure PublishJavaScript; procedure PublishPhp; procedure PublishPhpConfig; public constructor Create; override; destructor Destroy; override; function Publish(const inProject: TProject): string; override; procedure Activate; override; procedure Deactivate; override; procedure GenerateHtml(inStrings: TStrings); procedure New; override; procedure Open(const inFilename: string); override; procedure Save; override; property Data: TTurboPhpDocumentData read FData; property DesignForm: TDesignForm read FDesignForm; property PageName: string read GetPageName; end; implementation uses LrVclUtils, LrTagParser, Documents, TurboDocumentHost; { TTurboMarkup } procedure TTurboMarkup.Generate(inDesignSurface: TWinControl); begin with ThtGenerator.Create do try Generate(inDesignSurface, Self); finally Free; end; end; procedure TTurboMarkup.BuildHtml(inStrings: TStrings); begin Build(inStrings); LrFormatHtml(inStrings); end; { TTurboPhpDocumentData } constructor TTurboPhpDocumentData.Create(inOwner: TComponent); begin inherited; FBodyStyle := ThtStyle.Create(Self); FJavaScript := TStringList.Create; FPHP := TStringList.Create; end; destructor TTurboPhpDocumentData.Destroy; begin FBodyStyle.Free; FPHP.Free; FJavaScript.Free; inherited; end; procedure TTurboPhpDocumentData.SetBodyAttributes(const Value: string); begin FBodyAttributes := Value; end; procedure TTurboPhpDocumentData.SetBodyStyle(const Value: ThtStyle); begin FBodyStyle.Assign(Value); end; procedure TTurboPhpDocumentData.SetJavaScript(const Value: TStringList); begin FJavaScript.Assign(Value); end; procedure TTurboPhpDocumentData.SetPHP(const Value: TStringList); begin FPHP.Assign(Value); end; { TTurboJsPublisher } constructor TTurboJsPublisher.Create; begin inherited; end; destructor TTurboJsPublisher.Destroy; begin inherited; end; procedure TTurboJsPublisher.NewJavaScriptSource; begin with JavaScript do Add('// JavaScript'); end; procedure TTurboJsPublisher.PublishJavaScript(const inTarget: string); begin JavaScript.SaveToFile(ChangeFileExt(inTarget, '.js')); end; { TTurboPhpDocument } class function TTurboPhpDocument.DocumentDescription: string; begin Result := 'TurboPhp Pages'; end; class function TTurboPhpDocument.DocumentExt: string; begin Result := '.tphp'; end; constructor TTurboPhpDocument.Create; begin inherited; EnableSaveAs(DocumentDescription, DocumentExt); FDesignForm := TDesignForm.Create(nil); DesignForm.Visible := false; DesignForm.SetBounds(12, 12, 800 - 12, 600 - 12); CreateData; PhpIncludes := TStringList.Create; end; destructor TTurboPhpDocument.Destroy; begin PhpIncludes.Free; DesignForm.Free; inherited; end; procedure TTurboPhpDocument.CreateData; begin FData := TTurboPhpDocumentData.Create(FDesignForm); FData.Name := 'Document'; end; procedure TTurboPhpDocument.Activate; begin inherited; TurboDocumentHostForm.Document := Self; end; procedure TTurboPhpDocument.Deactivate; begin inherited; TurboDocumentHostForm.Document := nil; end; function TTurboPhpDocument.GetPageName: string; begin Result := ChangeFileExt(DisplayName, ''); end; procedure TTurboPhpDocument.NewPhpSource; begin with Data.Php do begin Add('<?php'); Add(''); Add('// Configure'); Add(''); Add('include_once("support/Page%%.config.php");'); Add(''); Add('// Define page class'); Add(''); Add('class TPage%% extends TTpPage'); Add('{'); Add(' // Implementation'); Add('}'); Add(''); Add('// Create and display page'); Add(''); Add('$Page%% = new TPage%%($tpTemplateFile);'); Add('$Page%%->Run();'); Add(''); Add('?>'); end; end; procedure TTurboPhpDocument.NewJavaScriptSource; begin with Data.JavaScript do begin Add('// JavaScript'); end; end; procedure TTurboPhpDocument.New; begin NewJavaScriptSource; NewPhpSource; end; procedure TTurboPhpDocument.Open(const inFilename: string); begin Filename := inFilename; DesignForm.LoadFromFile(Filename); LrFindComponentByClass(FData, DesignForm, TTurboPhpDocumentData); if FData = nil then CreateData; inherited; end; procedure TTurboPhpDocument.Save; begin if Filename <> '' then begin DesignForm.SaveToFile(Filename); inherited; end; end; function TTurboPhpDocument.GetHtmlName: string; begin Result := ChangeFileExt(PublishName, '.html'); end; function TTurboPhpDocument.GetHtmlTarget: string; begin Result := PublishPath + 'support\' + GetHtmlName; end; function TTurboPhpDocument.GetPhpName: string; begin Result := ChangeFileExt(PublishName, '.php'); end; function TTurboPhpDocument.GetPhpTarget: string; begin Result := PublishPath + GetPhpName; end; function TTurboPhpDocument.GetJavaScriptTarget: string; begin Result := PublishPath + 'support\' + ChangeFileExt(PublishName, '.js'); end; function TTurboPhpDocument.GetConfigTarget: string; begin Result := PublishPath + 'support\' + ChangeFileExt(PublishName, '.config.php'); end; procedure TTurboPhpDocument.InitializeIncludes; begin PhpIncludes.Clear; PhpIncludes.Add('TpParser.php'); PhpIncludes.Add('TpLib.php'); // if Page.Debug then // PhpIncludes.Add('TpDebug.php'); // // with TThComponentIterator.Create(DesignForm) do // try // while Next do // if IsAs(Component, ITpIncludeLister, l) then // l.ListPhpIncludes(PhpIncludes); // finally // Free; // end; // DeDupeStrings(PhpIncludes); end; procedure TTurboPhpDocument.PublishPhpConfig; const cLibPath = '$tpLibPath'; cSupportPath = '$tpSupportPath'; cTemplate = '$tpTemplateFile'; var i: Integer; begin with TStringList.Create do try Add('<?php'); Add(''); //Add(cSupportPath + ' = "' + SupportFolder + '";'); //Add(cLibPath + ' = "' + RemoteLibFolder + '";'); Add(cSupportPath + ' = "' + 'support/' + '";'); Add(cLibPath + ' = "' + 'lib/' + '";'); Add(cTemplate + ' = $tpSupportPath . "' + GetHtmlName + '";'); Add(''); for i := 0 to Pred(PhpIncludes.Count) do Add('include_once($tpLibPath . "' + PhpIncludes[i] + '");'); Add(''); Add('?>'); SaveToFile(GetConfigTarget); finally Free; end; end; procedure TTurboPhpDocument.PublishPhp; var i: Integer; s: TStringList; begin s := TStringList.Create; with Data.Php do try for i := 0 to Pred(Count) do s.Add( StringReplace(Strings[i], 'Page%%', GetPageName, [ rfReplaceAll ])); s.SaveToFile(GetPhpTarget); finally s.Free; end; end; procedure TTurboPhpDocument.PublishJavaScript; begin Data.JavaScript.SaveToFile(GetJavaScriptTarget); end; function TTurboPhpDocument.CreateMarkup: TTurboMarkup; begin Result := TTurboMarkup.Create; end; procedure TTurboPhpDocument.CustomizeMarkup(inMarkup: TTurboMarkup); begin // end; procedure TTurboPhpDocument.GenerateHtml(inStrings: TStrings); var markup: TTurboMarkup; begin markup := CreateMarkup; try markup.Generate(DesignForm); CustomizeMarkup(markup); inStrings.Clear; markup.BuildHtml(inStrings); finally markup.Free; end; end; procedure TTurboPhpDocument.PublishHtml; var html: TStringList; begin html := TStringList.Create; try GenerateHtml(html); html.SaveToFile(GetHtmlTarget); finally html.Free; end; end; procedure TTurboPhpDocument.DoPublish; begin InitializeIncludes; PublishHtml; PublishPhpConfig; PublishPhp; PublishJavaScript; end; { procedure TTurboPhpDocument.Generate(const inTarget: string); begin PublishPath := ExtractFilePath(inTarget); PublishName := ExtractFileName(inTarget); InitializeIncludes; PublishHtml; PublishPhpConfig; PublishPhp; PublishJavaScript; end; } function TTurboPhpDocument.Publish(const inProject: TProject): string; begin PublishPath := inProject.PublishFolder[Self]; PublishName := PageName; DoPublish; Result := inProject.PublishUrl[Self] + GetPhpName; end; initialization RegisterClass(TTurboPhpDocumentData); end.
object Form9: TForm9 Left = 0 Top = 0 BorderStyle = bsDialog Caption = 'youtube-dl MSO list' ClientHeight = 498 ClientWidth = 561 Color = clBtnFace DefaultMonitor = dmMainForm Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False Position = poMainFormCenter PixelsPerInch = 96 TextHeight = 13 object msolist: TListBox Left = 0 Top = 0 Width = 561 Height = 498 Align = alClient Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Courier New' Font.Style = [] Items.Strings = ( 'Supported TV Providers:' 'mso mso name' 'dtc010 DTC Cable (Delhi)' 'wat025 City Of Monroe' 'ced010 Hartelco TV' 'weh010-camtel Cam-Tel Company' 'fbc-tele F&B Communications' 'cit025 Bardstown Cable TV' 'bea020 Beaver Valley Cable' 'gri010 Gridley Cable Inc' 'wes130 Wiatel' 'wal010 Walnut Communications' 'dtc020 DTC' 'spi005 Spillway Communications, Inc.' 'coa030 Coaxial Cable TV' 'otter Park Region Telephone & Otter Tail Telcom' 'ote010 OTEC Communication Company' 'htccomm HTC Communications, Inc. - IA' 'midrivers Mid-Rivers Communications' 'car050 Carnegie Cable' 'cha060 Chatmoss Cablevision' 'bra050 Brandenburg Telephone Co.' 'mid055 Cobalt TV (Mid-State Community TV)' 'cen100 CentraCom' 'pan010 Panora Telco/Guthrie Center Communications' 'gar040 Gardonville Cooperative Telephone Association' 'nel020 Nelsonville TV Cable' 'arkwest Arkwest Communications' 'har020 Hart Communications' 'tel095 Beaver Creek Cooperative Telephone' 'net010-02 Cellcom/Nsight Telservices' 'mar010 Marne & Elk Horn Telephone Company' 'nktelco NKTelco' 'nor115 NCC' 'tel160-csp C Spire SNAP' 'win010 Windomnet/SMBS' 'DTV DIRECTV' 'mhtc MHTC' 'wbi010 WBI' 'rte010 RTEC Communications' 'bte010 Bristol Tennessee Essential Services' 'spe010 Spencer Municipal Utilities' 'mad030 Madison County Cable Inc.' 'conwaycorp Conway Corporation' 'jam030 NVC' 'nor200 Empire Access' 'loc010 LocalTel Communications' 'onesource OneSource Communications' 'weh010-talequah Tahlequah Cable TV' 'she010 Shentel' 'rrc010 Inland Networks' 'sou035 South Slope Cooperative Communications' 'sou065 South Holt Cablevision, Inc.' 'for080 Forsyth CableNet' 'dem010-03 Celect-Citizens Connected Area' 'westianet Western Iowa Networks' 'cfunet Cedar Falls Utilities' 'fib010 Pathway' 'all025 Allen'#39's Communications' 'tvc030 TV Cable of Rensselaer' 'sul015 Venture Communications Cooperative, Inc.' 'cit180 Citizens Cablevision - Floyd, VA' 'hae010 Haefele TV Inc.' 'mou050 Mountain Village Cable' 'car030 Cameron Communications' 'gpcom Great Plains Communications' 'war040 Citizens Telephone Corporation' 'phi010 Philippi Communications System' 'int050 Interstate Telecommunications Coop' 'fbcomm Frankfort Plant Board' 'spa020 Spanish Fork Community Network' 'doy010 Doylestown Cable TV' 'pioncomm Pioneer Communications' 'woo010 Solarus' 'bci010-02 Vyve Broadband' 'riv030 River Valley Telecommunications Coop' 'nor105 Communications 1 Cablevision, Inc.' 'tri025 TriCounty Telecom' 'mtc010 MTC Cable' 'mtc030 MTCO Communications' 'phe030 CTV-Beam - East Alabama' 'nor125 Norwood Light Broadband' 'man060 MTCC' 'cra010 Craw-Kan Telephone' 'rct010 RC Technologies' 'pro035 PMT' 'coa020 Coast Communications' 'mpw Muscatine Power & Water' 'merrimac Merrimac Communications Ltd.' 'com140 Access Montana' 'mtacomm MTA Communications, LLC' 'mid050 Partner Communications Cooperative' 'com025 Complete Communication Services' 'tel140 LivCom' 'val025 Valley Telecommunications' 'nttcash010 Ashland Home Net' 'cross Cross TV' 'mid045 Midstate Communications' 'cit220 Tullahoma Utilities Board' 'she030 Sherwood Mutual Telephone Association, Inc.' 'ind060-ssc Silver Star Communications' 'coy010 commZoom' 'coo080 Cooperative Telephone Company' 'cccsmc010 St. Maarten Cable TV' 'sweetwater Sweetwater Cable Television Co' 'nttcdel010 Delcambre Telephone LLC' 'loc020 LISCO' 'nulink NuLink' 'hoodcanal Hood Canal Communications' 'nttcvtx010 VTX1' 'wil070 Wilkes Communications, Inc./RiverStreet Networ' + 'ks' 'dum010 Dumont Telephone Company' 'com160 Co-Mo Connect' 'nortex Nortex Communications' 'cci010 Duo County Telecom' 'res020 Reserve Telecommunications' 'rtc RTC Communication Corp' 'cns CNS' 'car100 Innovative Cable TV St Thomas-St John' 'weh010-east East Arkansas Cable TV' 'nctc Nebraska Central Telecom, Inc.' 'pem020 Pembroke Telephone Company' 'nttcmah010 Mahaska Communication Group' 'psc010 PSC' 'sou075 South Central Rural Telephone Cooperative' 'rai030 Rainier Connect' 'har005 Harlan Municipal Utilities' 'weh010-longview Longview - Kilgore Cable TV' 'allwest All West Communications' 'endeavor Endeavor Communications' 'art030 Arthur Mutual Telephone Company' 'war020 CLICK1.NET' 'crestview Crestview Cable Communications' 'csicable Cable Services Inc.' 'wir030 Beehive Broadband' 'nttcftc010 FTC' 'rsf010 RS Fiber' 'col070 Columbia Power & Water Systems' 'cun010 Cunningham Telephone & Cable' 'mck010 Peoples Rural Telephone Cooperative' 'pan020 PTCI' 'mol010 Reliance Connects- Oregon' 'she030-02 Ayersville Communications' 'astound Astound (now Wave)' 'swa010 Swayzee Communications' 'wes110 West River Cooperative Telephone Company' 'dem010-02 Celect-Bruce Telephone Area' 'med040 MTC Technologies' 'sum010 Sumner Cable TV' 'red040 Red River Communications' 'cit250 Citizens Mutual' 'sta025 Star Communications' 'she005 USA Communications/Shellsburg, IA' 'nor100 CL Tel' 'lon030 Lonsdale Video Ventures, LLC' 'com130-01 American Warrior Networks' 'uis010 Union Telephone Company' 'hin020 Hinton CATV Co.' 'stc020 Innovative Cable TV St Croix' 'com065 ETC' 'nttchig010 Highland Communication Services' 'pie010 Surry TV/PCSI TV' 'uss020 US Sonet' 'thr020 Three River' 'twi040 Twin Lakes' 'pottawatomie Pottawatomie Telephone Co.' 'cat020 Comporium' 'wes005 West Alabama TV Cable' 'tcc Tri County Communications Cooperative' 'san020 San Bruno Cable TV' 'cam010 Pinpoint Communications' 'spc010 Hilliary Communications' 'cab140 Town & Country Technologies' 'pin070 Pine Belt Communications, Inc.' 'pioneer Pioneer DTV' 'wil015 Wilson Communications' 'daltonutilities OptiLink' 'srt010 SRT' 'car040 Rainbow Communications' 'mcc040 McClure Telephone Co.' 'tri110 TrioTel Communications, Inc.' 'tra010 Trans-Video' 'cccomm CC Communications' 'wtc010 WTC' 'cou060 Zito Media' 'lumos Lumos Networks' 'ell010 ECTA' 'tec010 Genuine Telecom' 'scr010 Scranton Telephone Company' 'horizoncable Horizon Cable TV, Inc.' 'bev010 BEVCOMM' 'lau020 Laurel Highland Total Communications, Inc.' 'big020 Big Sandy Broadband' 'bel020 Bellevue Municipal Cable' 'emerytelcom Emery Telcom Video LLC' 'hin020-02 X-Stream Services' 'sal060 fibrant' 'sou025 SKT' 'tvtinc Twin Valley' 'mon060 Mon-Cre TVE' 'dem010-05 Celect-West WI Telephone Area' 'spl010 Alliance Communications' 'alpine Alpine Communications' 'gle010 Glenwood Telecommunications' 'waitsfield Waitsfield Cable' 'eatel EATEL Video, LLC' 'kpu010 KPU Telecommunications' 'bee010 Bee Line Cable' 'mul050 Mulberry Telecommunications' 'hea040 Heart of Iowa Communications Cooperative' 'nor140 North Central Telephone Cooperative' 'irv010 Irvine Cable' 'dur010 Ntec' 'mid030 enTouch' 'tsc TSC' 'cableamerica CableAmerica' 'yel010 Yelcot Communications' 'hor040 Horizon Chillicothe Telephone' 'wya010 Wyandotte Cable' 'kal010 Kalida Telephone Company, Inc.' 'tel160-del Delta Telephone Company' 'metronet Metronet' 'weh010-white White County Cable TV' 'wavebroadband Wave' 'premiercomm Premier Communications' 'san040-02 Mitchell Telecom' 'fal010 Falcon Broadband' 'com150 Community Cable & Broadband' 'nttcsli010 myEVTV.com' 'stc010 S&T' 'dix030 ATC Broadband' 'consolidatedcable Consolidated' 'foo010 Foothills Communications' 'ani030 WesTel Systems' 'cab038 CableSouth Media 3' 'int100 Integra Telecom' 'nttcche010 Cherokee Communications' 'sky050 SkyBest TV' 'tct TCT' 'ind060-dc Direct Communications' 'ble020 Bledsoe Telephone Cooperative' 'jea010 EPlus Broadband' 'qco010 QCOL' 'net010 Nsight Telservices' 'vis070 Vision Communications' 'wik010 Wiktel' 'wct010 West Central Telephone Association' 'new045 NU-Telecom' 'nttccde010 CDE Lightband' 'cpt010 CP-TEL' 'paulbunyan Paul Bunyan Communications' 'mlg010 MLGC' 'lit020 Litestream' 'uni110 United Communications - TN' 'kuh010 Kuhn Communications, Inc.' 'cit040 Citizens Fiber' 'wil040 WTC Communications, Inc.' 'tac020 Click! Cable TV' 'fid010 Fidelity Communications' 'selco SELCO' 'wadsworth CityLink' 'coo050 Coon Valley Telecommunications Inc' 'clr010 Giant Communications' 'sun045 Enhanced Telecommunications Corporation' 'nttclpc010 LPC Connect' 'btc010 BTC Communications' 'web020 Webster-Calhoun Cooperative Telephone Associat' + 'ion' 'sco050 Scottsboro Electric Power Board' 'but010 Butler-Bremer Communications' 'volcanotel Volcano Vision, Inc.' 'nor240 NICP' 'rockportcable Rock Port Cablevision' 'phonoscope Phonoscope Cable' 'ind040 Independence Telecommunications' 'far035 OmniTel Communications' 'ver025 Vernon Communications Co-op' 'pin060 Pineland Telephone Cooperative' 'cci020 Packerland Broadband' 'hometel HomeTel Entertainment, Inc.' 'bra010 Limestone Cable/Bracken Cable' 'xit010 XIT Communications' 'bvt010 Blue Valley Tele-Communications' 'gbt010 GBT Communications, Inc.' 'tre010 Trenton TV Cable Company' 'pio060 Pioneer Broadband' 'dak030 Dakota Central Telecommunications' 'sal040 DiamondNet' 'com050 The Community Agency' 'dem010-04 Celect-Elmwood/Spring Valley Area' 'ral010 Ralls Technologies' 'mur010 Murray Electric System' 'Rogers Rogers' 'mid180-01 yondoo' 'cit210 Citizens Cablevision, Inc.' 'nttcmin010 Minford TV' 'weh010-pine Pine Bluff Cable TV' 'arvig Arvig' 'eagle Eagle Communications' 'win090 Windstream Cable TV' 'cit230 Opelika Power Services' 'rad010 Radcliffe Telephone Company' 'pul010 PES Energize' 'nttcwhi010 Whidbey Telecom' 'tom020 Amherst Telephone/Tomorrow Valley' 'nttccst010 Central Scott / CSTV' 'bul010 Bulloch Telephone Cooperative' 'ete010 Etex Communications' 'hig030 Highland Media' 'ctc040 CTC - Brainerd MN' 'casscomm CASSCOMM' 'midhudson Mid-Hudson Cable' 'fam010 FamilyView CableVision' 'bal040 Ballard TV' 'dem010-01 Celect-Bloomer Telephone Area' 'lns010 Lost Nation-Elwood Telephone Co.' 'com130-02 American Community Networks' 'tvc020 Andycable' 'mou110 Mountain Telephone' 'ara010 ATC Communications' 'tvc015 TVC Cable' 'cro030 Crosslake Communications' 'uin010 STRATA Networks' 'kmt010 KMTelecom' 'canbytel Canby Telcom' 'nttcsmi010 Smithville Communications' 'annearundel Broadstripe' 'ree010 Reedsburg Utility Commission' 'nwc010 American Broadband Missouri' 'madison Madison Communications' 'for030 FJ Communications' 'che050 Chesapeake Bay Communications' 'bra020 BELD' 'htc030 HTC Communications Co. - IL' 'res040 RTC-Reservation Telephone Coop.' 'cla050 Vast Broadband' 'rld010 Richland Grant Telephone Cooperative, Inc.' 'mid140 OPTURA' 'par010 PLWC' 'fay010 Fayetteville Public Utilities' 'wab020 Wabash Mutual Telephone' 'gla010 Glasgow EPB' 'ver070 VTel' 'dem010-06 Celect-Mosaic Telecom' 'col080 Columbus Telephone' 'dpc010 D & P Communications' 'btc040 BTC Vision - Nahunta' 'nor075 Northwest Communications' 'sjoberg Sjoberg'#39's Inc.' 'bay030 Bay Country Communications' 'imon ImOn Communications' 'musfiber MUS FiberNET' 'goldenwest Golden West Cablevision' 'fullchannel Full Channel, Inc.' 'weh010-vicksburg Vicksburg Video' 'acecommunications AcenTek' 'far030 FMT - Jesup' 'lak130 Lakeland Communications' 'vol040-01 Ben Lomand Connect / BLTV' 'crt020 CapRock Tv' 'alb020 Albany Mutual Telephone' 'cab180 TVision' 'vik011 Polar Cablevision' 'wal005 Huxley Communications' 'dic010 DRN' 'htc020 Hickory Telephone Company' 'cab060 USA Communications' 'mctv MCTV' 'val030 Valparaiso Broadband' 'dun010 Dunkerton Telephone Cooperative' 'tel050 Tele-Media Company' 'vis030 Grantsburg Telcom' 'acm010 Acme Communications' 'cha050 Chariton Valley Communication Corporation, Inc' + '.' 'cml010 CML Telephone Cooperative Association' 'hbc010 H&B Cable Services' 'nor260 NDTC' 'leh010 Lehigh Valley Cooperative Telephone' 'wcta Winnebago Cooperative Telecom Association' 'pla020 Plant TiftNet, Inc.' 'cic010 NineStar Connect' 'cha035 Chaparral CableVision' 'tro010 Troy Cablevision, Inc.' 'cimtel Cim-Tel Cable, LLC.' 'weh010-hope Hope - Prescott Cable TV' 'sco020 STE' 'qua010 Quality Cablevision' 'com071 ComSouth Telesys' 'far020 Farmers Mutual Telephone Company' 'uni120 United Services' 'ser060 Clear Choice Communications' 'mil080 Milford Communications' 'mid180-02 Catalina Broadband Solutions' 'new075 New Hope Telephone Cooperative' 'lan010 Langco' 'all070 ALLO Communications' 'nem010 Nemont' 'vol040-02 VolFirst / BLTV' 'hun015 American Broadband' 'thr030 3 Rivers Communications' 'algona Algona Municipal Utilities' 'kal030 Kalona Cooperative Telephone Company' 'tel160-fra Franklin Telephone Company' 'carolinata West Carolina Communications' 'weh010-resort Resort TV Cable' 'val040 Valley TeleCom Group' 'htc010 Halstad Telephone Company' 'cla010 Clarence Telephone and Cedar Communications' 'Comcast_SSO Comcast XFINITY' 'gra060 GLW Broadband Inc.' 'k2c010 K2 Communications' 'baldwin Baldwin Lightstream' 'sav010 SCI Broadband-Savage Communications Inc.' 'cas CAS Cable' 'san040-01 Santel' 'min030 MINET' 'ada020 Adams Cable Service' 'nor030 Northland Communications' 'fli020 Flint River Communications' 'com020 Community Communications Company' 'icc010 Inside Connect Cable' 'wav030 Waverly Communications Utility' 'nts010 NTS Communications' 'epb020 EPB Smartnet') ParentFont = False TabOrder = 0 ExplicitWidth = 551 ExplicitHeight = 488 end end
unit FornecedorOperacaoAlterar.Controller; interface uses Fornecedor.Controller.Interf, Fornecedor.Model.Interf, TPAGFORNECEDOR.Entidade.Model; type TFornecedorOperacaoAlterarController = class(TInterfacedObject, IFornecedorOperacaoAlterarController) private FFornecedorModel: IFornecedorModel; FRegistro: TTPAGFORNECEDOR; FNomeFantasia: string; FCNPJ: string; FIE: string; FTelefone: string; FEmail: string; public constructor Create; destructor Destroy; override; class function New: IFornecedorOperacaoAlterarController; function fornecedorModel(AValue: IFornecedorModel) : IFornecedorOperacaoAlterarController; function fornecedorSelecionado(AValue: TTPAGFORNECEDOR) : IFornecedorOperacaoAlterarController; function nomeFantasia(AValue: string): IFornecedorOperacaoAlterarController; function cnpj(AValue: string): IFornecedorOperacaoAlterarController; function ie(AValue: string): IFornecedorOperacaoAlterarController; function telefone(AValue: string): IFornecedorOperacaoAlterarController; function email(AValue: string): IFornecedorOperacaoAlterarController; procedure finalizar; end; implementation { TFornecedorOperacaoAlterarController } function TFornecedorOperacaoAlterarController.cnpj( AValue: string): IFornecedorOperacaoAlterarController; begin Result := Self; FCNPJ := AValue; end; constructor TFornecedorOperacaoAlterarController.Create; begin end; destructor TFornecedorOperacaoAlterarController.Destroy; begin inherited; end; function TFornecedorOperacaoAlterarController.email( AValue: string): IFornecedorOperacaoAlterarController; begin Result := Self; FEmail := AValue; end; procedure TFornecedorOperacaoAlterarController.finalizar; begin FFornecedorModel.DAO.Modify(FRegistro); FRegistro.NOMEFANTASIA := FNomeFantasia; FRegistro.CNPJ := FCNPJ; FRegistro.IE := FIE; FRegistro.TELEFONE := FTelefone; FRegistro.EMAIL := FEmail; FFornecedorModel.DAO.Update(FRegistro); end; function TFornecedorOperacaoAlterarController.fornecedorModel (AValue: IFornecedorModel): IFornecedorOperacaoAlterarController; begin Result := Self; FFornecedorModel := AValue; end; function TFornecedorOperacaoAlterarController.fornecedorSelecionado( AValue: TTPAGFORNECEDOR): IFornecedorOperacaoAlterarController; begin Result := Self; FRegistro := AValue; end; function TFornecedorOperacaoAlterarController.ie( AValue: string): IFornecedorOperacaoAlterarController; begin Result := Self; FIE := AValue; end; class function TFornecedorOperacaoAlterarController.New : IFornecedorOperacaoAlterarController; begin Result := Self.Create; end; function TFornecedorOperacaoAlterarController.nomeFantasia( AValue: string): IFornecedorOperacaoAlterarController; begin Result := Self; FNomeFantasia := AValue; end; function TFornecedorOperacaoAlterarController.telefone( AValue: string): IFornecedorOperacaoAlterarController; begin Result := Self; FTelefone := AValue; end; end.
unit Commasplit; interface uses System.Sysutils, System.Classes, Vcl.Controls, Graphics; type TCommaSplitter = class(TComponent) private fText: String; fItems: TStringList; fDelimiter: String; function GetText: String; procedure SetItems(Value: TStringList); procedure SetText(Value: String); protected procedure Loaded; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function IsIn(S: String): Boolean; published property Delimiter: string read fDelimiter write fDelimiter; property Items: TStringList read fItems write SetItems; property Text: string read GetText write SetText; end; procedure Register; //============================================================ implementation //============================================================ function TCommaSplitter.GetText: String; var i: integer; begin Result := ''; for i := 0 to fItems.Count - 1 do Result := Format('%s%s%s',[Result,Delimiter,fItems.Strings[i]]); Result := Copy(Result,Length(Delimiter)+1,Length(Result)); end; procedure TCommaSplitter.SetItems(Value:TStringList); begin fItems.Assign(Value); end; procedure TCommaSplitter.SetText(Value: String); var s1,s2: string; begin fText := Value; s1 := Value; fItems.Clear; while (s1 <> '') do begin if (Pos(Delimiter,s1) > 0) then begin s2 := Copy(s1,1,Pos(Delimiter,s1)-1); s1 := Copy(s1,Pos(Delimiter,s1)+Length(Delimiter),Length(s1)); end else begin s2 := s1; s1 := ''; end; fItems.Add(s2); end; end; procedure TCommaSplitter.Loaded; begin inherited Loaded; {** default to comma seperated value} if (Delimiter = '') then Delimiter := ','; end; constructor TCommaSplitter.Create(AOwner: TComponent); begin inherited Create(AOwner); fItems := TStringList.Create; fDelimiter := ','; end; destructor TCommaSplitter.Destroy; begin fItems.Free; inherited Destroy; end; function TCommaSplitter.IsIn(S: String): Boolean; var i: integer; begin result:=false; for i := 0 to fItems.Count - 1 do begin if (fItems.Strings[i] = S) then begin result := true; exit; end; end; end; procedure Register; begin RegisterComponents('PB Power', [TCommaSplitter]); end; end.
unit uPUB_SP_SPEC; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uSpec_SpravOneLevel, cxGraphics, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, dxBar, dxBarExtItems, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, ImgList, ActnList, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, dxStatusBar,uPrK_Resources, cxCheckBox, cxLookAndFeelPainters, StdCtrls, cxButtons, cxContainer, cxTextEdit, ExtCtrls; type TFormPUB_SP_SPEC = class(TFormSpec_SpravOneLevel) colUSPEC_NAME: TcxGridDBColumn; colMOVA_NAME: TcxGridDBColumn; colFULL_NAME: TcxGridDBColumn; ColIS_OLD: TcxGridDBColumn; ActionMakeOld: TAction; dxBarLargeButtonMakeOld: TdxBarLargeButton; procedure FormCreate(Sender: TObject); procedure ActionADDExecute(Sender: TObject); procedure ActionChangeExecute(Sender: TObject); procedure ActionViewExecute(Sender: TObject); procedure ActionMakeOldExecute(Sender: TObject); private { Private declarations } FStoredProcMakeOldName: String; procedure SetStoredProcMakeOldName(const Value: string); public ID_USER_GLOBAL,ID_GOD_NABORA_GLOBAL : int64; property StoredProcMakeOldName:string read FStoredProcMakeOldName write SetStoredProcMakeOldName; end; type TDataPrKSpravSPEC=class(TDataPrKSprav) private FFullName: string; FID_SP_USPEC: int64; FUSPEC_NAME: string; FID_SP_MOVA: int64; FMOVA_NAME: string; constructor Create(aKodMax: Integer;aNppMax: Integer);overload;override; constructor Create(aId:int64; aName:String; aShortName:String; aFullName:String; aKod:Integer;aNpp : Integer; aID_SP_USPEC : int64; aUSPEC_NAME : string; aID_SP_MOVA : int64; aMOVA_NAME : string);overload; procedure SetUSPEC_NAME(const Value: string); procedure SetID_SP_USPEC(const Value: int64); procedure SetMOVA_NAME(const Value: string); procedure SetID_SP_MOVA(const Value: int64); procedure SetFullName(const Value: string); public property ID_SP_USPEC :int64 read FID_SP_USPEC write SetID_SP_USPEC; property USPEC_NAME :string read FUSPEC_NAME write SetUSPEC_NAME; property ID_SP_MOVA :int64 read FID_SP_MOVA write SetID_SP_MOVA; property MOVA_NAME :string read FMOVA_NAME write SetMOVA_NAME; property FullName :string read FFullName write SetFullName; end; var FormPUB_SP_SPEC: TFormPUB_SP_SPEC; implementation uses uConstants,uPUB_SP_SPEC_Edit, uSpecKlassSprav; {$R *.dfm} procedure TFormPUB_SP_SPEC.FormCreate(Sender: TObject); var p:Boolean; begin inherited; if Assigned(ParamSprav) then p:=ParamSprav['Input']['ShowOld'].AsVariant else p:=False; ColIS_OLD.Visible:=p; ActionMakeOld.Visible:=p; {ID_NAME должен стоять первым так как в SelectSQLText может делаться CloseOpen} ID_NAME :='ID_SP_SPEC'; if p then SelectSQLText :='Select * from PUB_SP_SPEC_SELECT(0)' else SelectSQLText :='Select * from PUB_SP_SPEC_SELECT(1)'; ShowNpp := false; StoredProcAddName :='PUB_SP_SPEC_ADD'; StoredProcChangeName :='PUB_SP_SPEC_CHANGE'; StoredProcDelName :='PUB_SP_SPEC_DEL'; StoredProcMakeOldName:='PUB_SP_SPEC_MAKE_OLD'; // NamePrKSpravEdit := SpecSpravEditStandart;// возможно это не надо будет InicFormCaption :=nFormPUB_SP_SPEC_Caption[IndexLanguage]; // colUSPEC_NAME.Caption:=ncolUSPEC_NAME[IndexLanguage]; colUSPEC_NAME.DataBinding.FieldName:='USPEC_NAME'; colMOVA_NAME.DataBinding.FieldName:='MOVA_NAME'; colFULL_NAME.DataBinding.FieldName:='FULL_NAME'; ColIS_OLD.DataBinding.FieldName :='IS_OLD'; colUSPEC_NAME.Caption:=ncolUSPEC_NAME[IndexLanguage]; colMOVA_NAME.Caption:=ncolMOVA[IndexLanguage]; ColIS_OLD.Caption:=ncolIS_OLD[IndexLanguage]; colFULL_NAME.Caption:=ncolFullName[IndexLanguage]; ActionMakeOld.Caption:=nActionMakeOld[IndexLanguage]; ActionMakeOld.Hint:=nHintActionMakeOld[IndexLanguage]; // ??? ID_USER_GLOBAL :=ParamSprav['Input']['ID_USER_GLOBAL'].AsInt64; // ??? ID_GOD_NABORA_GLOBAL :=ParamSprav['Input']['God_Nabora'].AsInt64; //CheckAccessAdd :=''; //CheckAccessChange :=''; //CheckAccessDel :=''; SearchPanel.Visible:=True; end; procedure TFormPUB_SP_SPEC.SetStoredProcMakeOldName(const Value: string); begin FStoredProcMakeOldName := Value; end; { TDataPrKSpravDISC } constructor TDataPrKSpravSPEC.Create(aId: int64; aName, aShortName: String; aFullName:String; aKod, aNpp: Integer; aID_SP_USPEC: int64; aUSPEC_NAME: string; aID_SP_MOVA: int64; aMOVA_NAME: string); begin Create(aId, aName, aShortName,aKod,aNpp); ID_SP_USPEC :=aID_SP_USPEC; USPEC_NAME :=aUSPEC_NAME; ID_SP_MOVA :=aID_SP_MOVA; MOVA_NAME :=aMOVA_NAME; FullName := aFullName; end; constructor TDataPrKSpravSPEC.Create(aKodMax, aNppMax: Integer); begin inherited; ID_SP_USPEC :=-1; USPEC_NAME :=''; ID_SP_MOVA :=-1; MOVA_NAME :=''; FullName := ''; end; procedure TDataPrKSpravSPEC.SetUSPEC_NAME(const Value: string); begin FUSPEC_NAME := Value; end; procedure TDataPrKSpravSPEC.SetID_SP_USPEC(const Value: int64); begin FID_SP_USPEC := Value; end; procedure TDataPrKSpravSPEC.SetMOVA_NAME(const Value: string); begin FMOVA_NAME := Value; end; procedure TDataPrKSpravSPEC.SetID_SP_MOVA(const Value: int64); begin FID_SP_MOVA := Value; end; procedure TDataPrKSpravSPEC.SetFullName(const Value: string); begin FFullName := Value; end; procedure TFormPUB_SP_SPEC.ActionADDExecute(Sender: TObject); var DataPrKSpravAdd :TDataPrKSpravSPEC; T:TFormPUB_SP_SPEC_Edit; TryAgain :boolean; begin TryAgain:=false; DataPrKSpravAdd:=TDataPrKSpravSPEC.Create(StrToInt(DataSetPrKSprav.FieldValues['KOD_MAX']), StrToInt(DataSetPrKSprav.FieldValues['NPP_MAX'])); if DataSetPrKSprav.FieldValues[ID_NAME]<>Null then DataPrKSpravAdd.Id:=StrToInt64(DataSetPrKSprav.FieldValues[ID_NAME]); T := TFormPUB_SP_SPEC_Edit.Create(self,DataPrKSpravAdd,AllDataKods,AllDataNpps); T.cxLabelFormCaption.Caption :=nFormKlassSpravEdit_Add[IndexLanguage]; if ShowNpp=true then begin T.cxLabelNPP.Visible :=true; T.cxTextEditNPP.Visible :=true; end; if T.ShowModal=MrOk then begin StoredProcPrKSprav.Transaction.StartTransaction; StoredProcPrKSprav.StoredProcName:=StoredProcAddName; StoredProcPrKSprav.Prepare; StoredProcPrKSprav.ParamByName('IS_OLD').AsInteger :=0; StoredProcPrKSprav.ParamByName('NAME').AsString :=DataPrKSpravAdd.Name; StoredProcPrKSprav.ParamByName('SHORT_NAME').AsString :=DataPrKSpravAdd.ShortName; StoredProcPrKSprav.ParamByName('FULL_NAME').AsString :=DataPrKSpravAdd.FullName; StoredProcPrKSprav.ParamByName('KOD').AsInteger :=DataPrKSpravAdd.Kod; StoredProcPrKSprav.ParamByName('NPP').AsInteger :=DataPrKSpravAdd.Npp; StoredProcPrKSprav.ParamByName('ID_SP_USPEC').AsInt64 :=DataPrKSpravAdd.ID_SP_USPEC; StoredProcPrKSprav.ParamByName('ID_SP_MOVA').AsInt64 :=DataPrKSpravAdd.ID_SP_MOVA; try StoredProcPrKSprav.ExecProc; StoredProcPrKSprav.Transaction.commit; DataPrKSpravAdd.Id:=StoredProcPrKSprav.FieldByName('ID_OUT').AsInt64; except on e: Exception do begin MessageBox(Handle,Pchar(nMsgErrorTransaction[IndexLanguage]+chr(13)+ nMsgTryAgain[IndexLanguage]+nMsgOr[IndexLanguage]+nMsgToAdmin[IndexLanguage]+chr(13)+ e.Message),Pchar(nMsgBoxTitle[IndexLanguage]),MB_OK or MB_ICONWARNING); StoredProcPrKSprav.Transaction.Rollback; TryAgain:=true; end; end; end; T.Free; T:=nil; Obnovit(DataPrKSpravAdd.Id); DataPrKSpravAdd.Free; DataPrKSpravAdd:=nil; if TryAgain=true then ActionADDExecute(Sender); end; procedure TFormPUB_SP_SPEC.ActionChangeExecute(Sender: TObject); var DataPrKSpravChange :TDataPrKSpravSPEC; T:TFormPUB_SP_SPEC_Edit; TryAgain :boolean; ID_SP_USPEC_loc:Int64; USPEC_NAME_loc :String; ID_SP_MOVA_loc:Int64; MOVA_NAME_loc :String; begin TryAgain:=false; if DataSetPrKSprav.FieldValues[ID_NAME]<>Null then begin if (DataSetPrKSprav.FieldValues['ID_SP_USPEC']=Null) or (DataSetPrKSprav.FieldValues['ID_SP_USPEC']=-1) then begin ID_SP_USPEC_loc := -1; USPEC_NAME_loc := ''; end else begin ID_SP_USPEC_loc := DataSetPrKSprav.FieldValues['ID_SP_USPEC']; USPEC_NAME_loc := DataSetPrKSprav.FieldValues['USPEC_NAME']; end; if (DataSetPrKSprav.FieldValues['ID_SP_MOVA']=Null) or (DataSetPrKSprav.FieldValues['ID_SP_MOVA']=-1) then begin ID_SP_MOVA_loc := -1; MOVA_NAME_loc := ''; end else begin ID_SP_MOVA_loc := DataSetPrKSprav.FieldValues['ID_SP_MOVA']; MOVA_NAME_loc := DataSetPrKSprav.FieldValues['MOVA_NAME']; end; DataPrKSpravChange:=TDataPrKSpravSPEC.Create(StrToInt64(DataSetPrKSprav.FieldValues[ID_NAME]), DataSetPrKSprav.FieldValues['NAME'], DataSetPrKSprav.FieldValues['SHORT_NAME'], DataSetPrKSprav.FieldValues['FULL_NAME'], StrToInt(DataSetPrKSprav.FieldValues['KOD']), StrToInt(DataSetPrKSprav.FieldValues['NPP']), ID_SP_USPEC_loc, USPEC_NAME_loc, ID_SP_MOVA_loc, MOVA_NAME_loc); T:=TFormPUB_SP_SPEC_Edit.Create(self,DataPrKSpravChange,AllDataKods,AllDataNpps); T.cxLabelFormCaption.Caption :=nFormKlassSpravEdit_Change[IndexLanguage]; if ShowNpp=true then begin T.cxLabelNPP.Visible :=true; T.cxTextEditNPP.Visible :=true; end; if T.ShowModal=MrOk then begin StoredProcPrKSprav.Transaction.StartTransaction; StoredProcPrKSprav.StoredProcName:=StoredProcChangeName; StoredProcPrKSprav.Prepare; StoredProcPrKSprav.ParamByName(ID_NAME).AsInt64 :=DataPrKSpravChange.Id; StoredProcPrKSprav.ParamByName('IS_OLD').AsInteger :=DataSetPrKSprav['IS_OLD']; StoredProcPrKSprav.ParamByName('NAME').AsString :=DataPrKSpravChange.Name; StoredProcPrKSprav.ParamByName('SHORT_NAME').AsString :=DataPrKSpravChange.ShortName; StoredProcPrKSprav.ParamByName('FULL_NAME').AsString :=DataPrKSpravChange.FullName; StoredProcPrKSprav.ParamByName('KOD').AsInteger :=DataPrKSpravChange.Kod; StoredProcPrKSprav.ParamByName('NPP').AsInteger :=DataPrKSpravChange.Npp; StoredProcPrKSprav.ParamByName('ID_SP_USPEC').AsInt64 :=DataPrKSpravChange.ID_SP_USPEC; StoredProcPrKSprav.ParamByName('ID_SP_MOVA').AsInt64 :=DataPrKSpravChange.ID_SP_MOVA; try StoredProcPrKSprav.ExecProc; StoredProcPrKSprav.Transaction.Commit; except on e: Exception do begin MessageBox(Handle,Pchar(nMsgErrorTransaction[IndexLanguage]+chr(13)+ nMsgTryAgain[IndexLanguage]+nMsgOr[IndexLanguage]+nMsgToAdmin[IndexLanguage]+chr(13)+ e.Message),Pchar(nMsgBoxTitle[IndexLanguage]),MB_OK or MB_ICONWARNING); StoredProcPrKSprav.Transaction.Rollback; TryAgain:=true; end; end; end; T.Free; T:=nil; Obnovit(DataPrKSpravChange.Id); DataPrKSpravChange.Free; DataPrKSpravChange:=nil; end; if TryAgain=true then ActionChangeExecute(sender); end; procedure TFormPUB_SP_SPEC.ActionViewExecute(Sender: TObject); var DataPrKSpravView :TDataPrKSpravSPEC; T:TFormPUB_SP_SPEC_Edit; ID_SP_USPEC_loc:Int64; USPEC_NAME_loc :String; ID_SP_MOVA_loc:Int64; MOVA_NAME_loc :String; begin if DataSetPrKSprav.FieldValues[ID_NAME]<>Null then begin if (DataSetPrKSprav.FieldValues['ID_SP_USPEC']=Null) or (DataSetPrKSprav.FieldValues['ID_SP_USPEC']=-1) then begin ID_SP_USPEC_loc := -1; USPEC_NAME_loc := ''; end else begin ID_SP_USPEC_loc := DataSetPrKSprav.FieldValues['ID_SP_USPEC']; USPEC_NAME_loc := DataSetPrKSprav.FieldValues['USPEC_NAME']; end; if (DataSetPrKSprav.FieldValues['ID_SP_MOVA']=Null) or (DataSetPrKSprav.FieldValues['ID_SP_MOVA']=-1) then begin ID_SP_MOVA_loc := -1; MOVA_NAME_loc := ''; end else begin ID_SP_MOVA_loc := DataSetPrKSprav.FieldValues['ID_SP_MOVA']; MOVA_NAME_loc := DataSetPrKSprav.FieldValues['MOVA_NAME']; end; DataPrKSpravView:=TDataPrKSpravSPEC.Create(StrToInt64(DataSetPrKSprav.FieldValues[ID_NAME]), DataSetPrKSprav.FieldValues['NAME'], DataSetPrKSprav.FieldValues['SHORT_NAME'], DataSetPrKSprav.FieldValues['FULL_NAME'], StrToInt(DataSetPrKSprav.FieldValues['KOD']), StrToInt(DataSetPrKSprav.FieldValues['NPP']), ID_SP_USPEC_loc, USPEC_NAME_loc, ID_SP_MOVA_loc, MOVA_NAME_loc); T:=TFormPUB_SP_SPEC_Edit.Create(self,DataPrKSpravView,AllDataKods,AllDataNpps); if ShowNpp=true then begin T.cxLabelNPP.Visible :=true; T.cxTextEditNPP.Visible :=true; end; T.cxLabelFormCaption.Caption :=nFormKlassSpravEdit_View[IndexLanguage]; T.cxButtonEditUSpec.Properties.ReadOnly :=true; T.cxButtonEditUSpec.Properties.Buttons[0].Visible:=false; T.cxButtonEditMova.Properties.ReadOnly :=true; T.cxButtonEditMova.Properties.Buttons[0].Visible :=false; T.cxTextEditName.Properties.ReadOnly :=true; T.cxTextEditFullName.Properties.ReadOnly :=true; T.cxTextEditShortName.Properties.ReadOnly :=true; T.cxTextEditKod.Properties.ReadOnly :=true; T.cxTextEditNpp.Properties.ReadOnly :=true; T.cxButtonEditUSpec.Style.Color :=TextViewColor; T.cxButtonEditMova.Style.Color :=TextViewColor; T.cxTextEditName.Style.Color :=TextViewColor; T.cxTextEditFullName.Style.Color :=TextViewColor; T.cxTextEditShortName.Style.Color :=TextViewColor; T.cxTextEditKod.Style.Color :=TextViewColor; T.cxTextEditNpp.Style.Color :=TextViewColor; T.ShowModal; T.Free; T:=nil; DataPrKSpravView.Free; DataPrKSpravView:=nil; end; end; procedure TFormPUB_SP_SPEC.ActionMakeOldExecute(Sender: TObject); begin inherited; if DataSetPrKSprav['IS_OLD']=1 then exit; if prkMessageDlg(nMsgBoxTitle[IndexLanguage],nMsgMakeOld[IndexLanguage], mtInformation,mbOKCancel,IndexLanguage)<>mrOK then EXIT; StoredProcPrKSprav.Transaction.StartTransaction; StoredProcPrKSprav.StoredProcName:=StoredProcMakeOldName; StoredProcPrKSprav.Prepare; StoredProcPrKSprav.ParamByName(ID_NAME).AsInt64 :=DataSetPrKSprav[ID_NAME]; try StoredProcPrKSprav.ExecProc; StoredProcPrKSprav.Transaction.Commit; except on e: Exception do begin MessageBox(Handle,Pchar(nMsgErrorTransaction[IndexLanguage]+chr(13)+ nMsgTryAgain[IndexLanguage]+nMsgOr[IndexLanguage]+nMsgToAdmin[IndexLanguage]+chr(13)+ e.Message),Pchar(nMsgBoxTitle[IndexLanguage]),MB_OK or MB_ICONWARNING); StoredProcPrKSprav.Transaction.Rollback; end; end; Obnovit(DataSetPrKSprav[ID_NAME]); end; end.
//------------------------------------------------------------------------------ //CommClient UNIT //------------------------------------------------------------------------------ // What it does - // This is an extension of the tIdTCPClient which uses a thread to read // incoming data into a buffer. // // Notes - // Followed idea of TIdTelnet, with a thread checking data. // Original Code by Tsusai, with corrections given by Gambit of the Indy // team. // // Changes - // January 4th, 2007 - RaX - Created Header. // January 20th, 2007 - Tsusai - Reusing TIdThread. It doesn't raise as // many exceptions due to conflicts with the process threadlist // //------------------------------------------------------------------------------ unit CommClient; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses Classes, IdTCPClient, IdThread; type //Forward declarations TInterClient = class; //Event Types TDataAvailableEvent = procedure (AClient : TInterClient) of object; //------------------------------------------------------------------------------ //TClientThread CLASS //------------------------------------------------------------------------------ TClientThread = class(TIdThread) protected fClient : TInterClient; procedure Run; override; public constructor Create( AClient : TInterClient ); reintroduce; property Client : TInterClient read fClient ; end;{TClientThread} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //TReconnectThread CLASS //------------------------------------------------------------------------------ TReconnectThread = class(TIdThread) protected fClient : TInterClient; procedure Run( ); override; public constructor Create( AClient : TInterClient ); reintroduce; end;{TReconnectThread} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //TInterClient CLASS //------------------------------------------------------------------------------ TInterClient = class(TIdTCPClient) protected fReadThread : TClientThread; fReconnectThread : TReconnectThread; fOnReceive : TDataAvailableEvent; fOnReconnect : TNotifyEvent; fActive : Boolean; procedure SetActive( Value : Boolean ); procedure DoReceiveEvent; procedure DoReconnectEvent; public AutoReconnect : Boolean; ReconnectDelay : LongWord; SourceName : string; DestinationName : string; ShutDown : Boolean; constructor Create( ASource : string; ADestination : string; AnAutoReconnect : Boolean; AReconnectDelay : LongWord = 3000 ); destructor Destroy( ); override; procedure Connect( ); override; procedure Disconnect( ANotifyPeer : Boolean ); override; procedure Reconnect( ); property Active : Boolean read fActive write SetActive ; property OnReceive : TDataAvailableEvent read fOnReceive write fOnReceive ; property OnReconnect : TNotifyEvent read fOnReconnect write fOnReconnect ; end;{TInterClient} //------------------------------------------------------------------------------ implementation uses SysUtils, Globals; //------------------------------------------------------------------------------ //Create CONSTRUCTOR //------------------------------------------------------------------------------ // What it does - // Creates our client thread. // // Changes - // January 4th, 2007 - RaX - Created Header. // January 20th, 2007 - Tsusai - Updated create call, removed FreeOnTerminate // //------------------------------------------------------------------------------ constructor TClientThread.Create( AClient : TInterClient ); begin inherited Create(True, True, AClient.SourceName + ' Client'); fClient := AClient; Priority := tpLowest; Start; end;{Create} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Run PROCEDURE //------------------------------------------------------------------------------ // What it does - // This is the actual executing code of the thread. // // Changes - // January 4th, 2007 - RaX - Created Header. // January 14th, 2007 - Tsusai - Modified the error response. // January 20th, 2007 - Tsusai - Now TIdThread.Run, removed while statement // //------------------------------------------------------------------------------ procedure TClientThread.Run; begin try fClient.IOHandler.CheckForDisconnect(true); fClient.IOHandler.CheckForDataOnSource(10); if not fClient.IOHandler.InputBufferIsEmpty then begin fClient.DoReceiveEvent; end; except if NOT fClient.ShutDown then begin Console.Message('Connection to '+fClient.DestinationName+' Server lost.', fClient.SourceName + ' Server', MS_ALERT); fClient.Reconnect; end; end; end;{Run} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Create CONSTRUCTOR //------------------------------------------------------------------------------ // What it does - // Creates our reconnect thread. // // Changes - // January 30th, 2008 - RaX - Created Header. // //------------------------------------------------------------------------------ constructor TReconnectThread.Create( AClient : TInterClient ); begin inherited Create(false); fClient := AClient; end;{Create} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Run PROCEDURE //------------------------------------------------------------------------------ // What it does - // Fires for each interation of our ReconnectThread. Attempts to reconnect // to the destination. // // Changes - // January 30th, 2008 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TReconnectThread.Run( ); begin Sleep(fClient.ReconnectDelay); Console.Message('Attempting to reconnect...', fClient.SourceName + ' Server', MS_ALERT); if Assigned(fClient.fReadThread) then begin fClient.fReadThread.Terminate; fClient.fReadThread.WaitFor; FreeAndNil(fClient.fReadThread); end; fClient.Connect; //Apparently indy threads' FreeOnTerminate does NOT work, this was added to //force it. Terminate; end;{Run} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Create CONSTRUCTOR //------------------------------------------------------------------------------ // What it does - // Creates our interclient. // // Changes - // January 4th, 2007 - RaX - Created Header. // January 14th, 2007 - Tsusai - Added setup of source and destination // Server names. // //------------------------------------------------------------------------------ constructor TInterClient.Create( ASource : string; ADestination : string; AnAutoReconnect : Boolean; AReconnectDelay : LongWord = 3000 ); begin inherited Create; SourceName := ASource; AutoReconnect := AnAutoReconnect; ReconnectDelay := AReconnectDelay; DestinationName := ADestination; end;{Create} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Connect PROCEDURE //------------------------------------------------------------------------------ // What it does - // Connects our interclient. // // Changes - // March 12th, 2007 - Aeomin - Created Header. // //------------------------------------------------------------------------------ procedure TInterClient.Connect( ); begin try inherited Connect; fReadThread := TClientThread.Create(Self); except Disconnect(false); Reconnect; end; end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Disconnect PROCEDURE //------------------------------------------------------------------------------ // What it does - // Connects our interclient. // // Changes - // March 12th, 2007 - Aeomin - Created Header. // //------------------------------------------------------------------------------ procedure TInterClient.Disconnect( ANotifyPeer: Boolean ); begin if Assigned(fReadThread) then begin fReadThread.Terminate; end; try inherited Disconnect(ANotifyPeer); finally if Assigned(fReadThread) then begin fReadThread.WaitFor; FreeAndNil(fReadThread); end; end; end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Destroy DESTRUCTOR //------------------------------------------------------------------------------ // What it does - // Destroys our interclient. // // Changes - // January 4th, 2007 - RaX - Created Header. // January 20th, 2007 - Tsusai - Changed how the readthread ends. // //------------------------------------------------------------------------------ destructor TInterClient.Destroy( ); begin Active := false; if Assigned(fReconnectThread) then begin if not fReconnectThread.Terminated then begin fReconnectThread.Terminate; end; end; if Assigned(fReadThread) then begin fReadThread.Terminate; fReadThread.WaitFor; fReadThread.Free; end; inherited Destroy; end;{Destroy} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetActive PROCEDURE //------------------------------------------------------------------------------ // What it does - // This is the actual executing code of the thread. // // Changes - // January 4th, 2007 - RaX - Created Header. // January 20th, 2007 - Tsusai - Updated for TIdThread. // //------------------------------------------------------------------------------ procedure TInterClient.SetActive( Value : Boolean ); begin ShutDown := not value; if Value then begin try Connect; except fActive := Connected; end; end else begin Disconnect; fActive := Connected; end; end;{SetActive} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Reconnect PROCEDURE //------------------------------------------------------------------------------ // What it does - // Starts the reconnect thread which tries to reconnect to the destination. // // Changes - // January 30th, 2008 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TInterClient.Reconnect( ); begin if fActive then begin DoReconnectEvent; fReconnectThread := TReconnectThread.Create(Self); if Assigned(fReadThread) then begin if not fReadThread.Terminated then begin fReadThread.Terminate; end; end; end; end;{Reconnect} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //DoReconnectEvent PROCEDURE //------------------------------------------------------------------------------ // What it does - // Attempts to fire the OnReconnect event. // // Changes - // January 30th, 2008 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TInterClient.DoReceiveEvent( ); begin try if Assigned(fOnReceive) then begin fOnReceive(self); end; finally //nothing to do end; end;{DoReceiveEvent} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //DoReconnectEvent PROCEDURE //------------------------------------------------------------------------------ // What it does - // Attempts to fire the OnReconnect event. // // Changes - // January 30th, 2008 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TInterClient.DoReconnectEvent( ); begin try if Assigned(fOnReconnect) then begin fOnReconnect(self); end; finally //nothing to do end; end;{DoReconnectEvent} //------------------------------------------------------------------------------ end.
//------------------------------------------------------------------------------ //WinLinux UNIT //------------------------------------------------------------------------------ // What it does- // This keeps our code clean. Certain operating systems need certain // things. // // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ unit WinLinux; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses Classes; type TIPSet = record Full : string; //Partial is just missing a value for the 4th octect (192.168.1.) Partial : string; end; function GetLongWordFromIPString(IPString : string) : LongWord; function GetIPStringFromHostname(Hostname : String) : TIPSet; procedure SetupTerminationCapturing; procedure KillTerminationCapturing; function GetTick : Cardinal; procedure LowerPriority(AThread : TThread); function ExtractFileNameMod(Path : String) : string; function IsValidFolderName(FolderName : String) :Boolean; implementation uses {$IFDEF MSWINDOWS} Windows, MMSystem, Winsock, {$ENDIF} {$IFDEF LINUX} Libc,//For Socket stuff. Hopefully temporarily. {$ENDIF} SysUtils, DateUtils, Version, Globals; //This is used for our tick counting. Linux doesn't have a "uptime" counter //So we store the linux time we started the application, and then take a //difference later on. {$IFDEF LINUX} var StartTime : TDateTime; {$ENDIF} //------------------------------------------------------------------------------ //GetLongWordFromIPString FUNCTION //------------------------------------------------------------------------------ // What it does- // Gets a LongWord IP value from an IP in string form. // // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ function GetLongWordFromIPString(IPString : string) : LongWord; begin Result := LongWord(inet_addr(PChar(IPString))); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetIPStringFromHostname FUNCTION //------------------------------------------------------------------------------ // What it does- // Returns an IP from a hostname. // // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ function GetIPStringFromHostname(Hostname : string) : TIPSet; var h: PHostEnt; begin h := gethostbyname(PChar(Hostname)); if h <> nil then begin with h^ do begin Result.Partial := Format('%d.%d.%d.', [ord(h_addr^[0]), ord(h_addr^[1]), ord(h_addr^[2])]); Result.Full := Result.Partial + IntToStr(ord(h_addr^[3])); end; end else begin Result.Full := '0.0.0.0'; Result.Partial := '0.0.0.'; end; end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ConProc STDCALL //------------------------------------------------------------------------------ // What it does- // Checks to see if windows is trying to terminate Helios, if it is it // shuts itself down. // // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ {$IFDEF MSWINDOWS} function ConProc(CtrlType : DWord) : Bool; stdcall; far; begin if CtrlType in [CTRL_C_EVENT,CTRL_BREAK_EVENT, CTRL_CLOSE_EVENT,CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT] then begin TerminateApplication; end; Result := true; end;{ConProc} {$ENDIF} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetupTerminationCapturing PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets us up to shutdown helios normally when windows or linux tries to // kill it. // // Changes - // December 22nd, 2006 - RaX - Created Header. // April 24th, 2007 - Tsusai - Linux goes ahead and sets the current // time. // //------------------------------------------------------------------------------ procedure SetupTerminationCapturing; begin {$IFDEF MSWINDOWS} SetConsoleCtrlHandler(@ConProc,true); SetConsoleTitle(PChar(HeliosVersion)); {$ENDIF} {$IFDEF LINUX} //Set our Starttime for our uptime calculations. StartTime := Now; //These control ctrl c and stuff for linux Signal(SIGINT,@TerminateApplication); Signal(SIGTERM,@TerminateApplication); Signal(SIGKILL,@TerminateApplication); {$ENDIF} end;{SetupTerminationCapturing} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //KillTerminationCapturing PROCEDURE //------------------------------------------------------------------------------ // What it does- // Removes termination capturing from our executeable. // // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure KillTerminationCapturing; begin {$IFDEF MSWINDOWS} SetConsoleCtrlHandler(@ConProc,False); {$ENDIF} end;{KillTerminationCapturing} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetTick FUNCTION //------------------------------------------------------------------------------ // What it does- // Gets current time in milliseconds since system start. // // Changes - // December 22nd, 2006 - RaX - Created Header. // April 24th, 2007 - Tsusai - Changed linux portion to compare // current time with the time that was stored on startup. // //------------------------------------------------------------------------------ function GetTick : Cardinal; begin {$IFDEF LINUX} Result := MilliSecondsBetween( Now() , StartTime ); {$ENDIF} //timegettime() gets Window's "How long has the PC been on for?" counter {$IFDEF MSWINDOWS} Result := timegettime(); {$ENDIF} end; {GetTick} //---------------------------------------------------------------------------- //------------------------------------------------------------------------------ //LowerPriority PROCEDURE //------------------------------------------------------------------------------ // What it does- // Set Helios process to lowest Priority, it also affects // performance. // // Changes - // December 22nd, 2006 - RaX - Created Header. // March 13th, 2007 - Aeomin - Modify Header // //------------------------------------------------------------------------------ procedure LowerPriority(AThread : TThread); begin {$IFDEF MSWINDOWS} AThread.Priority := tpLowest; {$ENDIF} {$IFDEF LINUX} //Tsusai 012107: CANNOT modify priority directly. Libc.Nice isn't //helping, takes only 1 unknown var, SetPriority may have //root only restrictions. This will be blank for now. {$ENDIF} end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ExtractFileNameMod FUNCTION //------------------------------------------------------------------------------ // What it does- // Extract filename from a string // // Changes - // December 22nd, 2006 - RaX - Created Header. // March 13th, 2007 - Aeomin - Modify Header // //------------------------------------------------------------------------------ function ExtractFileNameMod(Path : String) : string; begin //Tsusai 012507: ExtractFileName does not like / in windows paths, //since that method uses \ as a delimiter, so we correct it //before calling :) {$IFDEF MSWINDOWS} Path := StringReplace(Path, '/', '\', [rfReplaceAll]); {$ENDIF} Result := ExtractFileName(Path); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //IsValidFolderName FUNCTION //------------------------------------------------------------------------------ // What it does- // Checks to see if a folder name is void of banned characters, if it isn't // it returns FALSE. // // Changes - // February 25th, 2006 - RaX - Created. // //------------------------------------------------------------------------------ function IsValidFolderName(FolderName : String) : Boolean; const //Tsusai - if the forbidden characters are different in linux, change this. ForbiddenChars : set of Char = ['<', '>', '|', '"', ':', '*', '?']; var Index : Integer; begin Result := TRUE; if FolderName = '' then begin Result := FALSE; Exit; end; for Index := 1 to Length(FolderName) do begin if (FolderName[Index] in ForbiddenChars) then begin Result := FALSE; Exit; end; end; end; //------------------------------------------------------------------------------ end.