text stringlengths 14 6.51M |
|---|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2020-2020 Skybuck Flying
// Copyright (c) 2020-2020 The Delphicoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Bitcoin file: src/primitives/transaction.h
// Bitcoin file: src/primitives/transaction.cpp
// Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c
unit Unit_TTransaction;
interface
/** The basic transaction that is broadcasted on the network and contained in
* blocks. A transaction can contain multiple inputs and outputs.
*/
class CTransaction
{
public:
// Default transaction version.
static const int32_t CURRENT_VERSION=2;
// The local variables are made const to prevent unintended modification
// without updating the cached hash value. However, CTransaction is not
// actually immutable; deserialization and assignment are implemented,
// and bypass the constness. This is safe, as they update the entire
// structure, including the hash.
const std::vector<CTxIn> vin;
const std::vector<CTxOut> vout;
const int32_t nVersion;
const uint32_t nLockTime;
private:
/** Memory only. */
const uint256 hash;
const uint256 m_witness_hash;
uint256 ComputeHash() const;
uint256 ComputeWitnessHash() const;
public:
/** Convert a CMutableTransaction into a CTransaction. */
explicit CTransaction(const CMutableTransaction& tx);
CTransaction(CMutableTransaction&& tx);
template <typename Stream>
inline void Serialize(Stream& s) const {
SerializeTransaction(*this, s);
}
/** This deserializing constructor is provided instead of an Unserialize method.
* Unserialize is not possible, since it would require overwriting const fields. */
template <typename Stream>
CTransaction(deserialize_type, Stream& s) : CTransaction(CMutableTransaction(deserialize, s)) {}
bool IsNull() const {
return vin.empty() && vout.empty();
}
const uint256& GetHash() const { return hash; }
const uint256& GetWitnessHash() const { return m_witness_hash; };
// Return sum of txouts.
CAmount GetValueOut() const;
/**
* Get the total transaction size in bytes, including witness data.
* "Total Size" defined in BIP141 and BIP144.
* @return Total transaction size in bytes
*/
unsigned int GetTotalSize() const;
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull());
}
friend bool operator==(const CTransaction& a, const CTransaction& b)
{
return a.hash == b.hash;
}
friend bool operator!=(const CTransaction& a, const CTransaction& b)
{
return a.hash != b.hash;
}
std::string ToString() const;
bool HasWitness() const
{
for (size_t i = 0; i < vin.size(); i++) {
if (!vin[i].scriptWitness.IsNull()) {
return true;
}
}
return false;
}
};
implementation
#include <primitives/transaction.h>
#include <hash.h>
#include <tinyformat.h>
#include <util/strencodings.h>
#include <assert.h>
uint256 CTransaction::ComputeHash() const
{
return SerializeHash(*this, SER_GETHASH, SERIALIZE_TRANSACTION_NO_WITNESS);
}
uint256 CTransaction::ComputeWitnessHash() const
{
if (!HasWitness()) {
return hash;
}
return SerializeHash(*this, SER_GETHASH, 0);
}
CTransaction::CTransaction(const CMutableTransaction& tx) : vin(tx.vin), vout(tx.vout), nVersion(tx.nVersion), nLockTime(tx.nLockTime), hash{ComputeHash()}, m_witness_hash{ComputeWitnessHash()} {}
CTransaction::CTransaction(CMutableTransaction&& tx) : vin(std::move(tx.vin)), vout(std::move(tx.vout)), nVersion(tx.nVersion), nLockTime(tx.nLockTime), hash{ComputeHash()}, m_witness_hash{ComputeWitnessHash()} {}
CAmount CTransaction::GetValueOut() const
{
CAmount nValueOut = 0;
for (const auto& tx_out : vout) {
if (!MoneyRange(tx_out.nValue) || !MoneyRange(nValueOut + tx_out.nValue))
throw std::runtime_error(std::string(__func__) + ": value out of range");
nValueOut += tx_out.nValue;
}
assert(MoneyRange(nValueOut));
return nValueOut;
}
unsigned int CTransaction::GetTotalSize() const
{
return ::GetSerializeSize(*this, PROTOCOL_VERSION);
}
std::string CTransaction::ToString() const
{
std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u)\n",
GetHash().ToString().substr(0,10),
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (const auto& tx_in : vin)
str += " " + tx_in.ToString() + "\n";
for (const auto& tx_in : vin)
str += " " + tx_in.scriptWitness.ToString() + "\n";
for (const auto& tx_out : vout)
str += " " + tx_out.ToString() + "\n";
return str;
}
end.
|
unit TestPreprocessorTokens;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestPreprocessorTokens
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
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/NPL/
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.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses
TestFrameWork,
PreProcessorParseTree;
type
TTestPreprocessorTokens = class(TTestCase)
private
fcPreProcessor: TPreProcessorParseTree;
function EvalPreProcessorExpression(const ps: string): boolean;
procedure TestTrue(const ps: string);
procedure TestFalse(const ps: string);
procedure TestExcept(const ps: string);
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestTrueExpressions;
procedure TestFalseExpressions;
procedure TestIllegalExpressions;
end;
implementation
uses
SysUtils,
JcfRegistrySettings,
TestConstants;
function TTestPreprocessorTokens.EvalPreProcessorExpression(const ps: string): boolean;
begin
Result := fcPreProcessor.EvalPreProcessorExpression(ps);
end;
procedure TTestPreprocessorTokens.TestFalse(const ps: string);
begin
Check( not EvalPreProcessorExpression(ps), ps + ' is true');
end;
procedure TTestPreprocessorTokens.TestTrue(const ps: string);
begin
Check(EvalPreProcessorExpression(ps), ps + ' is false');
end;
procedure TTestPreprocessorTokens.TestExcept(const ps: string);
begin
try
EvalPreProcessorExpression(ps);
Fail('No exception in ' + ps);
except
// ok
end;
end;
procedure TTestPreprocessorTokens.Setup;
var
lsSettingsFileName: string;
begin
inherited;
lsSettingsFileName := GetTestSettingsFileName;
Check(FileExists(lsSettingsFileName), 'Settings file ' + lsSettingsFileName +
' not found');
GetRegSettings.FormatConfigFileName := lsSettingsFileName;
fcPreProcessor := TPreProcessorParseTree.Create;
fcPreProcessor.AddDefinedSymbol('foo');
fcPreProcessor.AddDefinedSymbol('bar');
fcPreProcessor.AddDefinedSymbol('fish');
end;
procedure TTestPreprocessorTokens.TearDown;
begin
inherited;
FreeAndNil(fcPreProcessor);
end;
procedure TTestPreprocessorTokens.TestFalseExpressions;
begin
// should return false
// foo and bar are defined, soy and spon aren't
TestFalse('defined(spon)');
TestFalse('defined(spon) or defined(soy)');
TestFalse('defined(foo) and defined(soy)');
TestFalse('not defined(foo) and (defined(bar))');
TestFalse('not defined(foo)');
TestFalse('not not not defined(foo)');
TestFalse('false');
TestFalse('(false)');
TestFalse('not true');
TestFalse('true and false');
TestFalse('(not true) and (not false)');
TestFalse('(not true) or false');
TestFalse('not true or false');
TestFalse('defined(foo) and false');
end;
procedure TTestPreprocessorTokens.TestTrueExpressions;
begin
// should return true if these are defined
TestTrue('defined(foo)');
TestTrue('defined(foo) and defined(bar)');
TestTrue('defined(foo) and defined(bar) and defined(fish)');
TestTrue('defined(foo) or defined(bar) or defined(fish)');
TestTrue('(defined(foo))');
TestTrue('((defined(foo)))');
TestTrue('(((defined(foo))))');
TestTrue('(((defined(foo)))) or defined(bar)');
TestTrue('(defined(foo) or defined(bar))');
TestTrue('(((defined(foo)) or defined(bar)))');
TestTrue('not not defined(foo)');
TestTrue('true');
TestTrue('(true)');
TestTrue('((true))');
TestTrue('(((true)))');
TestTrue('true or false');
TestTrue('true and true');
TestTrue('true and (true or false)');
TestTrue('not not true');
TestTrue('not false');
TestTrue('defined(foo) or false');
TestTrue('defined(foo) and true');
end;
procedure TTestPreprocessorTokens.TestIllegalExpressions;
begin
// should not parse at all
TestExcept('saef');
TestExcept('saefdsafsd fsdaf');
TestExcept('saefdsafsd fsdaf asdf adsf');
TestExcept('true and');
TestExcept('true true');
TestExcept('true false');
TestExcept('true)');
TestExcept('(true');
TestExcept('(true))');
TestExcept('((true)');
TestExcept('');
TestExcept('(');
TestExcept(')');
TestExcept('and');
TestExcept('or');
TestExcept('foo');
TestExcept('defined');
TestExcept('defined foo');
TestExcept('defined(foo');
TestExcept('defined(foo(');
TestExcept('(defined(foo)))');
end;
initialization
TestFramework.RegisterTest(TTestPreprocessorTokens.Suite);
end.
|
{
MP3Utils.pas
Object pascal unit with utility functions to analyze MP3 files.
Copyright (C) 2005 Volker Siebert, Germany
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
}
unit MP3Utils;
interface
uses
SysUtils, Classes;
//======================================================================
// Hilfsfunktionen
//======================================================================
function l3f_umuldiv_trunc(a, b, c: integer): integer; register;
function l3f_umuldiv_round(a, b, c: integer): integer; register;
function l3f_udiv_round(a, c: integer): integer; register;
//======================================================================
//
// Aufbau des MPEG Audio Synchronisationswort
//
// ========0======== ========1======== ========2======== ========3======== Byte
// 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 Bit
//
// 1 1 1 1 1 1 1 1 1 1 1 1 ~0-0 ~1-1-1-1 1-1~ Valid
// X x x x x x x X X 1-1 Compatible
//
// +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
// |1 1 1 1 1 1 1 1| |1 1 1 1| | | | | | | | | | | | | | |
// +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
// | | | | | | | | | | | |
// | | | | | | | | | | | +-- emphasis
// | | | | | | | | | | +----- original
// | | | | | | | | | +------- copyright
// | | | | | | | | +---------- mode extension
// | | | | | | | +-------------- mode
// | | | | | | +------------------- extension
// | | | | | +--------------------- padding
// | | | | +------------------------ frequency (0,1,2)
// | | | +------------------------------ bitrate (1-14)
// | | +------------------------------------- no crc check
// | +---------------------------------------- layer (1,2,3)
// +------------------------------------------- version (0,1)
//
//======================================================================
const
// l3f.version
L3F_MPEG_2 = 0;
L3F_MPEG_1 = 1;
// l3f.layer
L3F_LAYER_1 = 3;
L3F_LAYER_2 = 2;
L3F_LAYER_3 = 1;
L3F_LAYER_INVALID = 0;
// l3f.mode
L3F_MODE_STEREO = 0;
L3F_MODE_JOINT_STEREO = 1;
L3F_MODE_DUAL_CHANNEL = 2;
L3F_MODE_MONO = 3;
type
PL3FSyncWord = ^TL3FSyncWord;
TL3FSyncWord = packed record
case integer of
0: ( sw_b: array [0 .. 3] of byte; );
1: ( sw_l: cardinal; );
end;
function L3F_SYNC_VALID(const sw: TL3FSyncWord): boolean; inline;
function L3F_SYNC_COMPATIBLE(const s1, s2: TL3FSyncWord): boolean; inline;
const
//======================================================================
//
// Wie die Länge des aktuellen Frames in Bytes ermittelt wird:
//
// Dazu benutzen wir die Werte:
//
// spf = Samples/Frame
// l3f_spframe[h.version][h.layer]
//
// bps = Bytes/Slot
// l3f_bpslot[h.layer]
//
// freq = Samples/Sekunde
// l3f_frequency[h.version][h.frequency]
//
// kbps = Byte/Sekunde
// 125 * l3f_kbps[h.version][h.layer][h.bitrate]
//
// Aus der Formel:
//
// spf x kbps
// ----------
// freq
//
// erhalten wir
//
// Samples Bytes Sekunden Bytes
// ------- x ------- x -------- = -------
// Frame Sekunde Sample Frame
//
// h.padding gibt an, ob noch ein zusätzlicher Füllslot folgt, der
// die Länge bps (Bytes/Slot) hat.
//
// Hier ist eine Tabelle mit den Basislängen (ohne Padding) für alle
// möglichen Werte von h.version, h.layer, h.frequency und h.bitrate.
//
// V/L F | 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// === ===+==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ====
// 0-0 0-3| -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
// 1 | -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
// 2 | -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
// 3 | -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
// MPEG 2 Layer 3 ------------------------------------------------------------------------
// 0-1 0 | 0 26 52 78 104 130 156 182 208 261 313 365 417 470 522 -1
// 1 | 0 24 48 72 96 120 144 168 192 240 288 336 384 432 480 -1
// 2 | 0 36 72 108 144 180 216 252 288 360 432 504 576 648 720 -1
// 3 | -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
// MPEG 2 Layer 2 ------------------------------------------------------------------------
// 0-2 0 | 0 52 104 156 208 261 313 365 417 522 626 731 835 940 1044 -1
// 1 | 0 48 96 144 192 240 288 336 384 480 576 672 768 864 960 -1
// 2 | 0 72 144 216 288 360 432 504 576 720 864 1008 1152 1296 1440 -1
// 3 | -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
// MPEG 2 Layer 1 ------------------------------------------------------------------------
// 0-3 0 | 0 69 104 121 139 174 208 243 278 313 348 383 417 487 557 -1
// 1 | 0 64 96 112 128 160 192 224 256 288 320 352 384 448 512 -1
// 2 | 0 96 144 168 192 240 288 336 384 432 480 528 576 672 768 -1
// 3 | -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
// === ===+==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ====
// 1-0 0 | -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
// 1 | -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
// 2 | -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
// 3 | -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
// MPEG 1 Layer 3 ------------------------------------------------------------------------
// 1-1 0 | 0 104 130 156 182 208 261 313 365 417 522 626 731 835 1044 -1
// 1 | 0 96 120 144 168 192 240 288 336 384 480 576 672 768 960 -1
// 2 | 0 144 180 216 252 288 360 432 504 576 720 864 1008 1152 1440 -1
// 3 | -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
// MPEG 1 Layer 2 ------------------------------------------------------------------------
// 1-2 0 | 0 104 156 182 208 261 313 365 417 522 626 731 835 1044 1253 -1
// 1 | 0 96 144 168 192 240 288 336 384 480 576 672 768 960 1152 -1
// 2 | 0 144 216 252 288 360 432 504 576 720 864 1008 1152 1440 1728 -1
// 3 | -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
// MPEG 1 Layer 1 ------------------------------------------------------------------------
// 1-3 0 | 0 34 69 104 139 174 208 243 278 313 348 383 417 452 487 -1
// 1 | 0 32 64 96 128 160 192 224 256 288 320 352 384 416 448 -1
// 2 | 0 48 96 144 192 240 288 336 384 432 480 528 576 624 672 -1
// 3 | -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
// === ===+==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ==== ====
//
// (ANMERKUNG: Zitat von mir, 1998)
//
// Wie man sieht, ist der größte mögliche Frame 1728+1 Bytes groß.
// Dies ist aber ein Extremfall für (MPEG-1 Layer 2 mit 384 kBit/s,
// was nicht speziell optimiert werden muß.
//
// Die wahrscheinlichste Größe liegt bei 417+1 Bytes (MPEG 1 Layer 3,
// 44.100 Hz) bzw. zwischen 365+1 und 522+1. Wenn jedoch die Computer
// in Zukunft schneller werden, werden auch einige "Spezis" auf die
// Idee kommen, mit mehr als 160 kBit/s zu komprimieren.
//
// Wenn wir diese Werte als Tabelle hinterlegen, benötigen wir dafür
// 4 x 2 x 4 x 16 = 512 Werte ~= 2048 Bytes.
//
//======================================================================
// Bitrate in kBit/Sekunde
// Indiziert über [l3f.version][l3f.layer][l3f.bitrate]
l3f_kbps: array [L3F_MPEG_2 .. L3F_MPEG_1,
L3F_LAYER_INVALID .. L3F_LAYER_1,
0 .. 15] of smallint = (
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// l3f.version 0 = MPEG 2
( ( -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ), // 0 = invalid
( 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160, -1 ), // 1 = Layer 3
( 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160, -1 ), // 2 = Layer 2
( 0, 32, 48, 56, 64, 80, 96,112,128,144,160,176,192,224,256, -1 ) ), // 3 = Layer 1
// l3f.version 1 = MPEG 1
( ( -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ), // 0 = invalid
( 0, 32, 40, 48, 56, 64, 80, 96,112,128,160,192,224,256,320, -1 ), // 1 = Layer 3
( 0, 32, 48, 56, 64, 80, 96,112,128,160,192,224,256,320,384, -1 ), // 2 = Layer 2
( 0, 32, 64, 96,128,160,192,224,256,288,320,352,384,416,448, -1 ) ) // 3 = Layer 1
);
// Sampling-Frequenz (Samples pro Sekunde)
// Indiziert über [l3f.version][l3f.frequency]
l3f_frequency: array [L3F_MPEG_2 .. L3F_MPEG_1, 0 .. 3] of integer = (
( 22050, 24000, 16000, -1 ), // l3f.version 0 = MPEG 2
( 44100, 48000, 32000, -1 ) // l3f.version 1 = MPEG 1
);
// Bytes pro Slot
// Indiziert über [l3f.layer]
l3f_bpslot: array [L3F_LAYER_INVALID .. L3F_LAYER_1] of smallint = (
-1, 1, 1, 4
);
// Länge des festen Headers
// Indiziert über [l3f.version][l3f.mode]
l3f_hdrlen: array [L3F_MPEG_2 .. L3F_MPEG_1,
L3F_MODE_STEREO .. L3F_MODE_MONO] of smallint = (
( 17, 17, 17, 9 ),
( 32, 32, 32, 17 )
);
// Samples pro Frame
// Indiziert über [l3f.version][l3f.layer]
//
// Diese Zahl ist *IMMER* ein Vielfaches von 192:
// 384 = 2 * 192
// 576 = 3 * 192
// 1152 = 6 * 192
l3f_spframe: array [L3F_MPEG_2 .. L3F_MPEG_1,
L3F_LAYER_INVALID .. L3F_LAYER_1] of smallint = (
( -1, 576, 1152, 384 ),
( -1, 1152, 1152, 384 )
);
type
TL3FHeader = record
FileOffset: longint; // Dateioffset
FileSize: longint; // Dateigröße
SyncWord: TL3FSyncWord; // Gefundenes Syncword
XingHeader: longint; // Dateioffset des Xing-Header
Version: integer; // MPEG Version (0=2, 1=1)
Layer: integer; // MPEG Layer (0=4 .. 3=1)
Bitrate: integer; // Übertragungsrate (0 .. 15)
Frequency: integer; // Sampling-Frequenz (0 .. 3)
Padding: integer; // Füll-Slot (1/4 Bytes)
Mode: integer; // Kanalmodus (0 .. 3, 3 = Mono)
ModeExt: integer; // Information für Kanalmodus
Emphasis: integer; // Hervorhebung ???
NoCrc: shortint; // CRC Prüfung (0 = ja)
Extension: shortint; // Erweiterung ???
Copyright: shortint; // Urheberrechtlich geschützt
Original: shortint; // Original oder verändert?
LengthInSamples: longint; // Länge des Frames in Samples
LengthInBytes: longint; // Länge des Frames in Bytes
TotalFrames: longint; // Gesamte Anzahl von Frames in der Datei
end;
function l3f_header_rate_kbps(const hdr: TL3FHeader): integer; inline;
function l3f_header_freq_hz(const hdr: TL3FHeader): integer; inline;
function l3f_header_bytes_per_slot(const hdr: TL3FHeader): integer; inline;
procedure l3f_header_clear(var hdr: TL3FHeader);
function l3f_header_set_syncword(var hdr: TL3FHeader; offs: longint; const sw: TL3FSyncWord): boolean;
function Layer3EstimateLengthEx(const Buffer; BufSize, TotalSize: longint; var Header: TL3FHeader): longint;
function Layer3EstimateLength(Stream: TStream; var Header: TL3FHeader): longint; overload;
function Layer3EstimateLength(const Filename: string; var Header: TL3FHeader): longint; overload;
implementation
//
// | a x b |
// Berechnet | ------- | für positive Zahlen a, b und c
// +- c -+
//
// Register calling convention:
// a = eax
// b = edx
// c = ecx
function l3f_umuldiv_trunc(a, b, c: integer): integer; register;
assembler;
asm
mul edx
div ecx
end;
//
// | a x b + c / 2 |
// Berechnet | -------------- | für positive Zahlen a, b und c
// +- c -+
//
function l3f_umuldiv_round(a, b, c: integer): integer; register;
assembler;
asm
mul edx
push ecx
shr ecx, 1
add eax, ecx
adc edx, 0
pop ecx
div ecx
end;
//
// | a + c / 2 |
// Berechnet | ---------- | für positive Zahlen a und c
// +- c -+
//
function l3f_udiv_round(a, c: integer): integer; register;
assembler;
asm
mov ecx, edx
shr edx, 1
add eax, edx
rcl edx, 1
and edx, 1
div ecx
end;
//======================================================================
function L3F_SYNC_VALID(const sw: TL3FSyncWord): boolean;
inline;
begin
Result := (sw.sw_b[0] = $FF) and
((sw.sw_b[1] and $F0) = $f0) and
((sw.sw_b[1] and $06) <> $00) and
((sw.sw_b[2] and $F0) <> $F0) and
((sw.sw_b[2] and $0C) <> $0C);
end;
function L3F_SYNC_COMPATIBLE(const s1, s2: TL3FSyncWord): boolean;
inline;
begin
Result := ((s1.sw_b[1] and $0E) = (s2.sw_b[1] and $0E)) and
((s1.sw_b[2] and $FC) = (s2.sw_b[2] and $FC)) and
(((s1.sw_b[3] and $C0) = $C0) = ((s2.sw_b[3] and $C0) = $C0));
end;
//======================================================================
function l3f_header_rate_kbps(const hdr: TL3FHeader): integer;
inline;
begin
Result := l3f_kbps[hdr.Version, hdr.Layer, hdr.Bitrate];
end;
function l3f_header_freq_hz(const hdr: TL3FHeader): integer;
inline;
begin
Result := l3f_frequency[hdr.Version, hdr.Frequency];
end;
function l3f_header_bytes_per_slot(const hdr: TL3FHeader): integer;
inline;
begin
Result := l3f_bpslot[hdr.Layer];
end;
procedure l3f_header_clear(var hdr: TL3FHeader);
begin
FillChar(hdr, SizeOf(hdr), 0);
hdr.FileOffset := -1;
end;
function l3f_header_set_syncword(var hdr: TL3FHeader; offs: longint; const sw: TL3FSyncWord): boolean;
var
sb, spf, bps, freq, kbps: integer;
begin
hdr.FileOffset := offs;
hdr.SyncWord := sw;
sb := sw.sw_b[1];
hdr.Version := (sb shr 3) and 1;
hdr.Layer := (sb shr 1) and 3;
hdr.NoCrc := (sb ) and 1;
sb := sw.sw_b[2];
hdr.Bitrate := (sb shr 4) and 15;
hdr.Frequency := (sb shr 2) and 3;
hdr.Padding := (sb shr 1) and 1;
hdr.Extension := (sb ) and 1;
sb := sw.sw_b[3];
hdr.Mode := (sb shr 6) and 3;
hdr.ModeExt := (sb shr 4) and 3;
hdr.Copyright := (sb shr 3) and 1;
hdr.Original := (sb shr 2) and 1;
hdr.Emphasis := (sb ) and 3;
// Framelänge berechnen
spf := l3f_spframe[hdr.Version, hdr.Layer];
bps := l3f_bpslot[hdr.Layer];
freq := l3f_frequency[hdr.Version][hdr.Frequency];
kbps := 125 * l3f_kbps[hdr.Version][hdr.Layer][hdr.Bitrate];
// Auf irgendwelche ungültigen Indizes testen
Result := (spf > 0) and (bps > 0) and (freq > 0) and (kbps > 0);
if Result then
begin
hdr.LengthInBytes := l3f_umuldiv_trunc(spf, kbps, freq) + bps * hdr.Padding;
hdr.LengthInSamples := spf;
end;
end;
//======================================================================
{ Schätzt die Länge eines MP3-Files
Parameter:
Buffer: array [0 .. BufSize - 1] of byte
BufSize: Größe des Puffers
TotalSize: Größe der gesamten Datei
Header: TL3FHeader, der mit Informationen gefüllt wird.
Rückgabewerte:
Geschätzte Länge (Dauer) der Datei in Millisekunden.
}
function Layer3EstimateLengthEx(const Buffer; BufSize, TotalSize: longint; var Header: TL3FHeader): longint;
type
PByteArray = ^TByteArray;
TByteArray = packed array [0 .. MaxInt div 4] of byte;
var
buf: PByteArray;
fb64k, tfr, tsm: longint;
n, n2, ff, nf, padding: integer;
sw1, sw2: TL3FSyncWord;
hdr1, hdr2: TL3FHeader;
begin
l3f_header_clear(hdr1);
padding := 0;
ff := 0;
buf := @Buffer;
n := 0;
while n + 3 < BufSize do
begin
sw1 := PL3FSyncWord(@buf^[n])^;
if L3F_SYNC_VALID(sw1) then
begin
if l3f_header_set_syncword(hdr1, n, sw1) then
begin
inc(ff);
if ff = 1 then
begin
// Nachsehen, ob ein Xing VBR Header vorhanden ist
// Wenn ja, benutzen!
n2 := n + l3f_hdrlen[hdr1.Version, hdr1.Mode] + 4;
if (n2 + 12 < BufSize) and
(Chr(buf^[n2 + 0]) = 'X') and
(Chr(buf^[n2 + 1]) = 'i') and
(Chr(buf^[n2 + 2]) = 'n') and
(Chr(buf^[n2 + 3]) = 'g') and
((buf^[n2 + 7] and 1) <> 0) then
begin
tfr := buf^[n2 + 8];
tfr := tfr shl 8;
tfr := tfr or buf^[n2 + 9];
tfr := tfr shl 8;
tfr := tfr or buf^[n2 + 10];
tfr := tfr shl 8;
tfr := tfr or buf^[n2 + 11];
hdr1.XingHeader := n2;
hdr1.TotalFrames := tfr;
tsm := tfr * hdr1.LengthInSamples;
Result := l3f_umuldiv_trunc(tsm, 1000, l3f_header_freq_hz(hdr1));
Header := hdr1;
exit;
end;
end;
padding := hdr1.Padding;
nf := 1;
n2 := n + hdr1.LengthInBytes;
while n2 + 3 < BufSize do
begin
sw2 := PL3FSyncWord(@buf^[n2])^;
if not L3F_SYNC_VALID(sw2) then break;
if not L3F_SYNC_COMPATIBLE(sw1, sw2) then break;
if not l3f_header_set_syncword(hdr2, n2, sw2) then break;
inc(nf);
padding := padding or hdr2.Padding;
if nf >= 8 then
break;
inc(n2, hdr2.LengthInBytes);
end;
if nf > 2 then
break;
end;
l3f_header_clear(hdr1);
end;
inc(n);
end;
if hdr1.FileOffset < 0 then
Result := 0
else
begin
hdr1.Padding := padding;
if padding = 0 then
fb64k := hdr1.LengthInBytes shl 16
else
fb64k := l3f_umuldiv_round(8192000, l3f_header_rate_kbps(hdr1) * hdr1.LengthInSamples, l3f_header_freq_hz(hdr1));
//tfr := l3f_umuldiv_trunc(TotalSize - hdr1.FileOffset - 4, 65535, fb64k) + 2;
tfr := l3f_umuldiv_trunc(TotalSize - hdr1.FileOffset + 2, 65536, fb64k) + 1;
tsm := tfr * hdr1.LengthInSamples;
hdr1.TotalFrames := tfr;
Result := l3f_umuldiv_trunc(tsm, 1000, l3f_header_freq_hz(hdr1));
Header := hdr1;
end;
end;
//======================================================================
const
ANALYZE_LENGTH = 8192;
function Layer3EstimateLength(Stream: TStream; var Header: TL3FHeader): longint;
var
Buffer: packed array [0 .. ANALYZE_LENGTH - 1] of byte;
Pos, BufSize, Size: longint;
begin
Pos := Stream.Position;
Size := Stream.Size - Pos;
// ID3-Tag am Ende erkennen
if Size > 128 then
begin
Stream.Position := Size - 128;
Stream.ReadBuffer(Buffer, 128);
Stream.Position := Pos;
if (Chr(Buffer[0]) = 'T') and (Chr(Buffer[1]) = 'A') and (Chr(Buffer[2]) = 'G') then
dec(Size, 128);
end;
BufSize := Size;
if BufSize > ANALYZE_LENGTH then
BufSize := ANALYZE_LENGTH;
Stream.ReadBuffer(Buffer, BufSize);
Stream.Position := Pos;
Result := Layer3EstimateLengthEx(Buffer, BufSize, Size, Header);
if Header.FileOffset >= 0 then
begin
Header.FileSize := Size - Header.FileOffset;
inc(Header.FileOffset, Pos);
end;
end;
//======================================================================
function Layer3EstimateLength(const Filename: string; var Header: TL3FHeader): longint;
var
fs: TFileStream;
begin
fs := TFileStream.Create(Filename, fmOpenRead or fmShareDenyWrite);
try
Result := Layer3EstimateLength(fs, Header);
finally
fs.Free;
end;
end;
end.
|
unit SuchenFrm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Generics.Collections,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Vcl.StdCtrls, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Mask, Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids, Helpers;
type
TSuchenForm = class(TForm)
SuchbegriffEdit: TEdit;
AuswahlFelderBox: TComboBox;
SuchenButton: TButton;
AbbrechenButton: TButton;
procedure FormShow(Sender: TObject);
procedure SuchenButtonClick(Sender: TObject);
procedure SuchbegriffEditKeyPress(Sender: TObject; var Key: Char);
private
SqlQuery : TFDQuery;
FSuchEintraege: TList<TSuchEintrag>;
FTabellenName : string;
FErgebnis : integer;
procedure SucheStarten();
procedure ComboBoxFuellen();
public
constructor Create(AOwner: Tcomponent; Tabelle: string; Suche: TList<TSuchEintrag>;
Connection: TFDConnection); overload;
property SuchEintraege: TList<TSuchEintrag> read FSuchEintraege write FSuchEintraege;
property TabellenName: string read FTabellenName write FTabellenName;
property Ergebnis : integer read FErgebnis write FErgebnis;
end;
var
SuchenForm: TSuchenForm;
implementation
{$R *.dfm}
{ TSuchenForm }
procedure TSuchenForm.ComboBoxFuellen;
var
I: integer;
begin
self.AuswahlFelderBox.Items.Add('- Alle Felder -');
for I := 0 to self.SuchEintraege.Count - 1 do
begin
self.AuswahlFelderBox.Items.Add(self.SuchEintraege[I].AnzeigeName);
end;
self.AuswahlFelderBox.ItemIndex := 0;
end;
constructor TSuchenForm.Create(AOwner: Tcomponent; Tabelle: string; Suche: TList<TSuchEintrag>;
Connection: TFDConnection);
begin
inherited Create(AOwner);
self.TabellenName := Tabelle;
self.SuchEintraege := Suche;
self.SqlQuery := TFDQuery.Create(nil);
self.SqlQuery.Connection := Connection;
end;
procedure TSuchenForm.FormShow(Sender: TObject);
begin
self.ComboBoxFuellen;
end;
procedure TSuchenForm.SuchbegriffEditKeyPress(Sender: TObject; var Key: Char);
begin
If Key = #13 then
begin
SuchenButton.Click;
Key := #0;
end;
end;
procedure TSuchenForm.SuchenButtonClick(Sender: TObject);
begin
if SuchbegriffEdit.Text <> '' then
self.SucheStarten;
end;
procedure TSuchenForm.SucheStarten;
var
I: integer;
begin
with self.SqlQuery, SQL do
begin
Clear;
Add('Select Id FROM ' + self.TabellenName);
Add('WHERE ' + self.SuchEintraege[0].SpaltenName + ' = ' + QuotedStr(self.SuchbegriffEdit.Text));
for I := 1 to self.SuchEintraege.Count - 1 do
begin
add('OR '+ self.SuchEintraege[i].SpaltenName + ' = ' + QuotedStr(self.SuchbegriffEdit.Text));
end;
end;
self.SqlQuery.Open();
if self.SqlQuery.RecordCount = 1 then begin
self.Ergebnis:= self.SqlQuery.FieldByName('Id').AsInteger;
ModalResult := mrOk;
self.CloseModal;
end;
end;
end.
|
unit SMCnst;
interface
{Ukrainian strings}
const
strMessage = 'Друк...';
strSaveChanges = 'Ви бажаете зберегти внесенi змiни на серверi?';
strErrSaveChanges = 'Даннi не вдалося зберегти! Перевiрте з''єднання з сервером та коректнiсть внесених данних.';
strDeleteWarning = 'Ви дiйсно бажаєте видалити таблицю %s?';
strEmptyWarning = 'Ви дiйсно бажаєте видалити данi з таблицi %s?';
const PopUpCaption: array [0..22] of string[33] =
('Додати запис',
'Вставити запис',
'Редактувати запис',
'Видалити запис',
'-',
'Друк ...',
'Експорт данних ...',
'-',
'Зберегти змiни',
'Вiдмiнити змiни',
'Обновити даннi',
'-',
'Помiтка/Зняти відмутку з записiв',
'Помiтити запис',
'Помiтити усi записи',
'-',
'Зняти відмітку запис',
'Зняти відмітку з усiх записів',
'-',
'Зберегти положення колонок',
'Відновити положення колонок',
'-',
'Налаштування...');
const //for TSMSetDBGridDialog
SgbTitle = ' Заголовок ';
SgbData = ' Данi ';
STitleCaption = 'Назва:';
STitleAlignment = 'Вирiвнювання:';
STitleColor = 'Колір фону:';
STitleFont = 'Шрифт:';
SWidth = 'Ширина:';
SWidthFix = 'символiв';
SAlignLeft = 'злiва';
SAlignRight = 'зправа';
SAlignCenter = 'по центру';
const //for TSMDBFilterDialog
strEqual = 'рiвно';
strNonEqual = 'не рiвно';
strNonMore = 'не бiльше';
strNonLess = 'не менше';
strLessThan = 'меньше нiж';
strLargeThan = 'бiльше нiж';
strExist = 'пусте';
strNonExist = 'не пусте';
strIn = 'в списку';
strBetween = 'мiж';
strOR = 'АБО';
strAND = 'ТА';
strField = 'Поле';
strCondition = 'Умова';
strValue = 'Значення';
strAddCondition = ' Введiть додаткову умову:';
strSelection = ' Вибiр записiв згiдно наступних умов:';
strAddToList = 'Додати до списку';
strEditInList = 'Редактувати';
strDeleteFromList = 'Видалити з списку';
strTemplate = 'Шаблони фiльтрiв';
strFLoadFrom = 'Загрузити з...';
strFSaveAs = 'Зберегти як..';
strFDescription = 'Опис';
strFFileName = 'Ім''я файла';
strFCreate = 'Створено: %s';
strFModify = 'Модифiковано: %s';
strFProtect = 'Захист вiд перезапису';
strFProtectErr = 'Файл закритий вiд запису!';
const //for SMDBNavigator
SFirstRecord = 'Перший запис';
SPriorRecord = 'Попередній запис';
SNextRecord = 'Наступний запис';
SLastRecord = 'Останній запис';
SInsertRecord = 'Вставка запису';
SCopyRecord = 'Копіювання запису';
SDeleteRecord = 'Видалення запису';
SEditRecord = 'Редагування запису';
SFilterRecord = 'Вiдбiр записiв';
SFindRecord = 'Пошук запису';
SPrintRecord = 'Друк записiв';
SExportRecord = 'Експорт записiв';
SPostEdit = 'Збереження змiн';
SCancelEdit = 'Вiдмiна змiн';
SRefreshRecord = 'Оновлення даних';
SChoice = 'Вибiр даних';
SClear = 'Очистити данi';
SDeleteRecordQuestion = 'Видалити запис?';
SDeleteMultipleRecordsQuestion = 'Видалити усi вибранi записи?';
SRecordNotFound = 'Запис не знайдено';
SFirstName = 'Початок';
SPriorName = 'Попер.';
SNextName = 'Наступ.';
SLastName = 'Кiнець';
SInsertName = 'Вставка';
SCopyName = 'Копiювання';
SDeleteName = 'Видалення';
SEditName = 'Корегування';
SFilterName = 'Фiльтр';
SFindName = 'Пошук';
SPrintName = 'Друк';
SExportName = 'Експорт';
SPostName = 'Збереження';
SCancelName = 'Скасувати';
SRefreshName = 'Оновлення';
SChoiceName = 'Вибiр';
SClearName = 'Зброс';
SBtnOk = '&OK';
SBtnCancel = '&Вiдмiна';
SBtnLoad = 'Загрузити';
SBtnSave = 'Зберегти';
SBtnCopy = 'Копiювати';
SBtnPaste = 'Вставити';
SBtnClear = 'Очистити';
SRecNo = '№';
SRecOf = ' з ';
const //for EditTyped
etValidNumber = 'коректним числом';
etValidInteger = 'коректним цiлым числом';
etValidDateTime = 'коректною датою та часом';
etValidDate = 'коректною датою';
etValidTime = 'коректним часом';
etValid = 'коректним';
etIsNot = 'не є';
etOutOfRange = 'Значення %s не лежить в діапазонi %s..%s';
SApplyAll = 'Применити усiм';
implementation
end.
|
{ Module of routines that manipulate the edit string object. Each of
* these routines take an edit string object ESTR passed by reference as
* their first parameter.
*
* An ESTR is a low level object intended for imbedding in other objects.
* It displays a rectangle with a text string and lets the user edit the
* string. ESTR only draws the text string and its background.
}
module gui_estr;
define gui_estr_create;
define gui_estr_delete;
define gui_estr_make_seed;
define gui_estr_set_string;
define gui_estr_edit1;
define gui_estr_edit;
%include 'gui2.ins.pas';
{
*************************************************************************
*
* Local subroutine GUI_ESTR_DRAW (WIN, ESTR)
*
* This is the offical draw routine for the ESTR private window.
}
procedure gui_estr_draw ( {draw routine for ESTR private window}
in out win: gui_win_t; {window to draw}
in out estr: gui_estr_t); {edit string object begin drawn}
val_param; internal;
var
poly: array[1..3] of vect_2d_t; {scratch polygon descriptor}
begin
rend_set.text_parms^ (estr.tparm); {set our text control parameters}
{
* Draw the background.
}
if estr.orig {set background color}
then rend_set.rgb^ (estr.col_bo.red, estr.col_bo.grn, estr.col_bo.blu)
else rend_set.rgb^ (estr.col_bn.red, estr.col_bn.grn, estr.col_bn.blu);
rend_prim.clear_cwind^; {draw background}
{
* Draw the cursor.
}
if gui_estrf_curs_k in estr.flags then begin {cursor drawing enabled ?}
if estr.orig {set cursor color}
then rend_set.rgb^ (estr.col_co.red, estr.col_co.grn, estr.col_co.blu)
else rend_set.rgb^ (estr.col_cn.red, estr.col_cn.grn, estr.col_cn.blu);
poly[1].x := estr.curs; {tip}
poly[1].y := estr.by;
poly[2].x := estr.curs - estr.curswh; {bottom left corner}
poly[2].y := estr.bc;
poly[3].x := estr.curs + estr.curswh; {lower right corner}
poly[3].y := estr.bc;
rend_prim.poly_2d^ (3, poly); {draw the cursor}
end;
{
* Draw the text string.
}
if estr.orig {set text color}
then rend_set.rgb^ (estr.col_fo.red, estr.col_fo.grn, estr.col_fo.blu)
else rend_set.rgb^ (estr.col_fn.red, estr.col_fn.grn, estr.col_fn.blu);
rend_set.cpnt_2d^ (estr.lx, estr.by); {go to char string bottom left corner}
rend_prim.text^ (estr.str.str, estr.str.len); {draw the text string}
end;
{
*************************************************************************
*
* Subroutine GUI_ESTR_CREATE (ESTR, PARENT, LX, RX, BY, TY)
*
* Create a new edit string object in ESTR. PARENT is the parent window
* this object will be drawn within. LX and RX are the left and right
* edges for the new object within the parent window. BY and TY are the
* bottom and top edges within the parent window. The current
* RENDlib text control parameters will be saved and used for displaying
* the string. The object is made displayable, although it is not
* explicitly displayed.
}
procedure gui_estr_create ( {create edit string object}
out estr: gui_estr_t; {newly created object}
in out parent: gui_win_t; {window to draw object within}
in lx, rx: real; {left and right edges within parent window}
in by, ty: real); {top and bottom edges within parent window}
val_param;
var
dy: real; {requested drawing height}
thigh: real; {text character cell height}
lspace: real; {vertical gap between text lines}
begin
rend_set.enter_rend^; {push one level into graphics mode}
dy := ty - by; {total height requested by caller}
gui_win_child ( {create private window for this object}
estr.win, {returned new window object}
parent, {parent window}
lx, by, {a corner of the new window}
rx - lx, dy); {displacement from the corner point}
gui_win_set_app_pnt (estr.win, addr(estr)); {set app data passed to draw routine}
gui_win_set_draw (estr.win, univ_ptr(addr(gui_estr_draw))); {set draw routine}
rend_get.text_parms^ (estr.tparm); {get current text control parameters}
estr.tparm.rot := 0.0; {set some required parameters our way}
estr.tparm.start_org := rend_torg_ll_k;
thigh := estr.tparm.size * estr.tparm.height; {character cell height}
lspace := estr.tparm.size * estr.tparm.lspace; {gap between text lines}
estr.lxh := {set text left edge home position}
estr.tparm.size * estr.tparm.width * 0.6;
estr.lx := estr.lxh; {init to text is at home position}
estr.by := max( {figure where text string bottom goes}
dy * 0.5 - thigh * 0.5, {center vertically}
dy - lspace - thigh); {leave one lspace room above}
estr.bc := max(0.0, estr.by - thigh); {cursor bottom Y}
estr.curs := estr.lx; {init cursor to first character position}
estr.curswh := {half width of widest part of cursor}
estr.tparm.size * estr.tparm.width * 0.5;
estr.col_bn.red := 0.7; {normal background color}
estr.col_bn.grn := 0.7;
estr.col_bn.blu := 0.7;
estr.col_fn.red := 0.0; {normal foreground color}
estr.col_fn.grn := 0.0;
estr.col_fn.blu := 0.0;
estr.col_cn.red := 1.0; {normal cursor color}
estr.col_cn.grn := 1.0;
estr.col_cn.blu := 0.0;
estr.col_bo.red := 0.15; {background color for seed text}
estr.col_bo.grn := 0.15;
estr.col_bo.blu := 0.60;
estr.col_fo.red := 1.0; {foreground color for seed text}
estr.col_fo.grn := 1.0;
estr.col_fo.blu := 1.0;
estr.col_co.red := 1.0; {cursor color for seed text}
estr.col_co.grn := 1.0;
estr.col_co.blu := 0.0;
estr.str.max := size_char(estr.str.str);
estr.str.len := 0;
estr.ind := 1;
estr.flags := [
gui_estrf_orig_k, {enable seed string mode}
gui_estrf_curs_k]; {enable drawing the cursor}
estr.orig := false;
estr.cmoved := false;
rend_set.exit_rend^; {pop one level from graphics mode}
end;
{
*************************************************************************
*
* Local subroutine GUI_ESTR_CURSOR_PUT (ESTR)
*
* Determine the cursor position by setting the CURS field. No other
* state is changed. The text parameters for this window must already
* be set current.
}
procedure gui_estr_cursor_put ( {determine cursor position}
in out estr: gui_estr_t); {edit string object}
val_param; internal;
var
bv, up, ll: vect_2d_t; {text string size and position parameters}
begin
if estr.ind <= 1
then begin {cursor is at start of string}
estr.curs := estr.lx;
end
else begin {cursor is past start of string}
rend_set.enter_rend^; {make sure we are in graphics mode}
rend_set.text_parms^ (estr.tparm); {set appropriate text parameters}
rend_get.txbox_txdraw^ ( {measure string to left of cursor}
estr.str.str, estr.ind - 1, {string and string length}
bv, up, ll); {returned string metrics}
estr.curs := estr.lx + bv.x; {set cursor X coordinate}
rend_set.exit_rend^; {pop one level from graphics mode}
end
;
end;
{
*************************************************************************
*
* Subroutine GUI_ESTR_MAKE_SEED (ESTR)
*
* Set the current string to be the seed string if everything is properly
* enabled. This window is not explicitly redrawn.
}
procedure gui_estr_make_seed ( {make current string the seed string}
in out estr: gui_estr_t); {edit string object}
val_param;
begin
estr.orig := {TRUE if treat this as undedited seed string}
(estr.str.len > 0) and (gui_estrf_orig_k in estr.flags);
end;
{
*************************************************************************
*
* Subroutine GUI_ESTR_SET_STRING (ESTR, STR, CURS, SEED)
*
* Set the current string being edited to STR. SEED TRUE indicates that
* the new string should be considered a "seed" string that is displayed
* differently until first edited by the user. A seed string is also
* automatically deleted if the user just starts typing characters. For
* the new string to be considered a seed string all of the following
* conditions must be met:
*
* 1 - SEED is TRUE.
*
* 2 - STR contains at least one character.
*
* 3 - Seed strings are enabled with the GUI_ESTRF_ORIG_K flag
* in ESTR.FLAGS.
}
procedure gui_estr_set_string ( {init string to be edited}
in out estr: gui_estr_t; {edit string object}
in str: univ string_var_arg_t; {seed string}
in curs: string_index_t; {char position where next input char goes}
in seed: boolean); {TRUE if treat as seed string before mods}
val_param;
begin
string_copy (str, estr.str); {copy new string into object}
estr.ind := max(1, min(estr.str.len + 1, curs)); {set cursor string index}
gui_estr_cursor_put (estr); {calculate new cursor X coordinate}
if seed then begin {make new string the seed string ?}
gui_estr_make_seed (estr);
end;
gui_win_draw ( {redraw the whole window}
estr.win, 0.0, estr.win.rect.dx, 0.0, estr.win.rect.dy);
end;
{
*************************************************************************
*
* Subroutine GUI_ESTR_DELETE (ESTR)
*
* Delete the edit string object.
}
procedure gui_estr_delete ( {delete edit string object}
in out estr: gui_estr_t); {object to delete}
val_param;
begin
gui_win_delete (estr.win); {delete the private window}
end;
{
*************************************************************************
*
* Function GUI_ESTR_EDIT1 (ESTR)
*
* Perform one edit operation on the edit string object ESTR. This routine
* gets and processes events until one of these two things happen:
*
* 1 - The event causes the string or the cursor position to change.
* The string is redrawn and the function returns TRUE.
*
* 2 - The event can not be handled by this routine. The event is pushed
* back onto the event queue and the function returns FALSE.
}
function gui_estr_edit1 ( {perform one edit string operation}
in out estr: gui_estr_t) {edit string object}
:boolean; {FALSE on encountered event not handled}
val_param;
var
rend_level: sys_int_machine_t; {initial RENDlib graphics mode level}
ev: rend_event_t; {event descriptor}
lx, rx: real; {scratch left and right limits}
ty: real; {scratch top Y coordinate}
clx, crx: real; {old cursor left and right limits}
p: vect_2d_t; {scratch 2D coordinate}
pnt: vect_2d_t; {pointer coordinate in our window space}
xb, yb, ofs: vect_2d_t; {save copy of old RENDlib 2D transform}
bv, up, ll: vect_2d_t; {text string size and position parameters}
i: sys_int_machine_t; {scratch integer}
indc: string_index_t; {string index of left-most changed char}
ocurs: string_index_t; {old cursor string index}
modk: rend_key_mod_t; {modifier keys}
kid: gui_key_k_t; {key ID}
c: char; {character from key event}
label
event_next, khome, kend, delete, leave_true, leave_false, leave;
{
************************************************
*
* Local subroutine ORIG_CLEAR
* This routine is local to GUI_ESTR_EDIT1.
*
* An edit is about to be performed that would require first clearing
* the seed string, if the current string is a seed string.
}
procedure orig_clear;
begin
if estr.orig then begin {current string is seed string ?}
estr.str.len := 0; {clear current string}
estr.ind := 1;
indc := 0; {force redraw of everything}
estr.orig := false; {this is no longer a seed string}
end;
end;
{
************************************************
*
* Local subroutine ORIG_KEEP
* This routine is local to GUI_ESTR_EDIT1.
*
* An edit is about to be performed such that if the current string is a
* seed string, it should be converted to a permanent string.
}
procedure orig_keep;
begin
if estr.orig then begin {current string is seed string ?}
estr.orig := false; {this is no longer a seed string}
indc := 0; {force redraw of everything}
end;
end;
{
************************************************
*
* Start of routine GUI_ESTR_EDIT1.
}
begin
rend_get.enter_level^ (rend_level); {save initial graphics mode level}
rend_set.enter_rend^; {make sure we are in graphics mode}
rend_get.xform_2d^ (xb, yb, ofs); {save 2D transform}
gui_win_xf2d_set (estr.win); {set 2D transform for our window}
indc := estr.str.max + 1; {init to no part of string changed}
ocurs := estr.ind; {save starting cursor index}
estr.cmoved := false;
clx := estr.curs - estr.curswh; {save cursor left edge}
crx := estr.curs + estr.curswh; {save curser right edge}
event_next: {back here to get each new event}
rend_set.enter_level^ (0); {make sure not in graphics mode}
rend_event_get (ev); {get the next event}
case ev.ev_type of {what kind of event is this ?}
{
************************************************
*
* Event POINTER MOTION
}
rend_ev_pnt_move_k: ; {pointer movement is ingored}
{
************************************************
*
* Event KEY
}
rend_ev_key_k: begin {a key just transitioned}
if not ev.key.down then goto event_next; {ignore key releases}
modk := ev.key.modk; {get modifier keys}
if rend_key_mod_alt_k in modk {ALT active, this key not for us ?}
then goto leave_false;
kid := gui_key_k_t(ev.key.key_p^.id_user); {make GUI library ID for this key}
modk := modk - [rend_key_mod_shiftlock_k]; {ignore shift lock}
p.x := ev.key.x;
p.y := ev.key.y;
rend_set.enter_rend^; {make sure in graphics mode}
rend_get.bxfpnt_2d^ (p, pnt); {PNT is pointer coordinate in our space}
case kid of {which one of our keys is it ?}
gui_key_arrow_up_k, {these keys are ignored}
gui_key_arrow_down_k: ;
gui_key_arrow_right_k: begin {RIGHT ARROW}
if rend_key_mod_ctrl_k in modk then begin {go to end of line ?}
modk := modk - [rend_key_mod_ctrl_k];
goto kend;
end;
if modk <> [] then goto event_next;
orig_keep; {convert seed string to permanent, if any}
estr.ind := min(estr.str.len + 1, estr.ind + 1); {move cursor right one char}
goto leave_true;
end;
gui_key_arrow_left_k: begin {LEFT ARROW}
if rend_key_mod_ctrl_k in modk then begin {go to beginning of line ?}
modk := modk - [rend_key_mod_ctrl_k];
goto khome;
end;
if modk <> [] then goto event_next;
orig_keep; {convert seed string to permanent, if any}
estr.ind := max(1, estr.ind - 1); {move cursor left one char}
goto leave_true;
end;
gui_key_home_k: begin {HOME key}
khome:
if modk <> [] then goto event_next;
orig_keep; {convert seed string to permanent, if any}
estr.ind := 1; {move cursor to left end of string}
goto leave_true;
end;
gui_key_end_k: begin {END key}
kend:
if modk <> [] then goto event_next;
orig_keep; {convert seed string to permanent, if any}
estr.ind := estr.str.len + 1; {move cursor to right end of string}
goto leave_true;
end;
gui_key_del_k: begin {DELETE key}
if modk <> [] then goto event_next;
delete: {common code with RUBOUT character key}
orig_keep; {convert seed string to permanent, if any}
if estr.ind > estr.str.len then goto event_next; {nothing to delete ?}
for i := estr.ind + 1 to estr.str.len do begin {once for each char to move}
estr.str.str[i - 1] := estr.str.str[i]; {move this character}
end; {back to move the next character}
estr.str.len := estr.str.len - 1; {one less character in edit string}
indc := min(indc, estr.ind); {update to left most char that got altered}
goto leave_true;
end;
gui_key_mouse_left_k: begin {LEFT MOUSE BUTTON}
if {pointer outside our area ?}
(pnt.x < 0.0) or (pnt.x > estr.win.rect.dx) or
(pnt.y < 0.0) or (pnt.y > estr.win.rect.dy)
then begin
goto leave_false; {this event is for someone else}
end;
if modk <> [] then goto event_next;
orig_keep; {convert seed string to permanent, if any}
if pnt.x <= estr.lx then begin {left of whole string ?}
estr.ind := 1; {move cursor to string start}
goto leave_true;
end;
lx := estr.lx; {init current position to string left edge}
for i := 1 to estr.str.len do begin {loop thru the string looking for pointer pos}
rend_get.txbox_txdraw^ ( {measure this string character}
estr.str.str[i], 1, {string and string length to measure}
bv, up, ll); {returned string metrics}
lx := lx + bv.x; {update X to right of this character}
if pnt.x < lx then begin {click was within this character ?}
estr.ind := i;
goto leave_true;
end
end; {back to check next character in string}
estr.ind := estr.str.len + 1; {put cursor at end of last character}
goto leave_true;
end;
gui_key_mouse_right_k: begin {RIGHT MOUSE BUTTON}
if {pointer outside our area ?}
(pnt.x < 0.0) or (pnt.x > estr.win.rect.dx) or
(pnt.y < 0.0) or (pnt.y > estr.win.rect.dy)
then begin
goto leave_false; {this event is for someone else}
end;
end;
gui_key_char_k: begin {character key}
c := gui_event_char (ev); {get character code from key event}
case ord(c) of {check for special characters}
8: begin {backspace}
orig_keep; {convert seed string to permanent, if any}
if estr.ind <= 1 then goto event_next; {nothing to delete left of cursor ?}
for i := estr.ind to estr.str.len do begin {once for each char to move left}
estr.str.str[i - 1] := estr.str.str[i]; {move this character}
end; {back to move the next character}
estr.str.len := estr.str.len - 1; {one less character in edit string}
estr.ind := estr.ind - 1; {update where next character goes}
indc := min(indc, estr.ind); {update to left most char that got altered}
goto leave_true;
end;
127: begin {delete}
goto delete; {to common code with DELETE key}
end;
end; {end of special character cases}
if not string_char_printable (c) {this is not a printable character ?}
then goto event_next; {ignore it}
orig_clear; {delete seed string, if any}
if estr.ind > estr.str.max {this char would go past end of string ?}
then goto event_next; {ignore it}
if estr.ind <= estr.str.len then begin {inserting into middle of string ?}
for i := estr.str.len downto estr.ind do begin {once for each char to move}
if i < estr.str.max then begin {there is room to put this char ?}
estr.str.str[i + 1] := estr.str.str[i]; {move this character}
end;
end; {back to move next char}
end;
estr.str.str[estr.ind] := c; {put new character into string}
estr.str.len := min(estr.str.max, estr.str.len + 1); {update string length}
indc := min(indc, estr.ind); {update to left most char that got altered}
estr.ind := min(estr.str.len + 1, estr.ind + 1); {update index for next char}
goto leave_true;
end; {end of character key case}
otherwise {abort on any key not explicitly handled}
goto leave_false;
end; {end of key ID cases}
end; {end of event KEY case}
{
************************************************
*
* Event WIPED_RECT
}
rend_ev_wiped_rect_k: begin {rectangular region needs redraw}
gui_win_draw ( {redraw a region}
estr.win.all_p^.root_p^, {redraw from the root window down}
ev.wiped_rect.x, {left X}
ev.wiped_rect.x + ev.wiped_rect.dx, {right X}
estr.win.all_p^.root_p^.rect.dy - ev.wiped_rect.y - ev.wiped_rect.dy, {bottom Y}
estr.win.all_p^.root_p^.rect.dy - ev.wiped_rect.y); {top Y}
end;
{
************************************************
}
otherwise {any event type we don't explicitly handle}
goto leave_false;
end; {end of event type cases}
goto event_next; {back to process next event}
{
* One or more events were processed which resulted in the ESTR state to
* change. INDC is the left-most string index of any character that got
* changed. INDC must be set to the special value of 0 if the whole string
* got moved, not just changed.
}
leave_true:
gui_estr_edit1 := true; {indicate all events processed normally}
lx := estr.win.rect.dx; {init changed limits to nothing changed}
rx := 0.0;
ty := estr.by; {init to not redraw higher than cursor}
if {cursor got moved on display ?}
(estr.ind <> ocurs) or {cursor string index changed ?}
(estr.ind > indc) {chars changed left of cursor ?}
then begin
estr.cmoved := true; {indicate cursor got moved}
gui_estr_cursor_put (estr); {calculate new cursor position}
lx := min(lx, clx, estr.curs - estr.curswh); {update min region to redraw}
rx := max(rx, crx, estr.curs + estr.curswh);
ocurs := min(ocurs, estr.ind); {update left index already flagged for redraw}
end; {done dealing with cursor position changes}
if indc <= estr.str.max then begin {part of string got changed ?}
ty := estr.win.rect.dy; {redraw all the way to window top edge}
rx := estr.win.rect.dx; {redraw all the way to window right edge}
if indc <= 1
then begin {whole string changed}
lx := 0.0; {redraw whole window}
end
else begin {left part of string didn't change}
if indc >= ocurs
then begin {all change was right of cursor}
lx := min(lx, estr.curs); {redraw all to right of cursor position}
end
else begin {string changed left of cursor}
lx := 0.0; {just redraw the whole string}
end
;
end
;
end;
if lx < rx then begin {need to redraw something ?}
gui_win_draw ( {redraw the modified region}
estr.win, {window to redraw}
lx, rx, {left and right limits to redraw}
0.0, ty); {bottom and top limits to redraw}
end;
goto leave;
{
* The last event can not be handled by this routine. It will be pushed
* back onto the event queue for some other routine to handle.
}
leave_false:
gui_estr_edit1 := false; {indicate returned due to unhandled event}
if ev.ev_type <> rend_ev_none_k then begin {there is an event ?}
rend_event_push (ev); {push event back onto head or queue}
end;
{
* Common exit point.
}
leave:
rend_set.xform_2d^ (xb, yb, ofs); {restore original 2D transform}
rend_set.enter_level^ (rend_level); {restore original graphics level}
end;
{
*************************************************************************
*
* Subroutine GUI_ESTR_EDIT (ESTR)
*
* This routine allows the user to perform continuous edit operations on the
* string until an event is encountered that is not handled by the low
* level edit routine. The unhandled event is pushed back onto the event
* queue. It is up to the calling routine to decide whether this event
* indicates the user is done editing the string, cancelled the edit, or
* whatever.
}
procedure gui_estr_edit ( {edit string until unhandled event}
in out estr: gui_estr_t); {edit string object}
val_param;
begin
while gui_estr_edit1(estr) do ; {keep looping until unhandled event}
end;
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit ExpertsBaseCreators;
interface
uses Windows, Messages, SysUtils, Controls,
Forms, Dialogs, DesignIntf, DesignEditors,
DMForm, Consts, IStreams, ToolsAPI;
type
TCreator = class(TInterfacedObject)
protected
{ IOTACreator }
function GetExisting: Boolean;
function GetFileSystem: string;
function GetOwner: IOTAModule;
function GetUnnamed: Boolean;
end;
TUnitCreator = class(TCreator, IOTACreator, IOTAModuleCreator)
private
FNewImplFileName: string;
FFileName: string;
function GetNewUnitFileName: string;
protected
{ IOTACreator }
function GetCreatorType: string;
function GetOwner: IOTAModule;
{ IOTAModuleCreator }
function GetAncestorName: string;
function GetImplFileName: string;
function GetIntfFileName: string;
function GetFormName: string;
function GetMainForm: Boolean;
function GetShowForm: Boolean;
function GetShowSource: Boolean;
function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
procedure FormCreated(const FormEditor: IOTAFormEditor);
protected
constructor Create(const AFileName: string);
end;
TTextFileCreator = class(TCreator, IOTACreator, IOTAModuleCreator)
private
FNewTextFileName: string;
FFileName: string;
FFileNameExt: string;
procedure GetNewTextFileName(out ATextFileName: string);
protected
{ IOTACreator }
function GetCreatorType: string;
function GetOwner: IOTAModule;
{ IOTAModuleCreator }
function GetAncestorName: string;
function GetImplFileName: string;
function GetIntfFileName: string;
function GetFormName: string;
function GetMainForm: Boolean;
function GetShowForm: Boolean;
function GetShowSource: Boolean;
function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
procedure FormCreated(const FormEditor: IOTAFormEditor);
public
constructor Create(const AFileName, AFileNameExt: string);
end;
TModuleCreator = class(TCreator, IOTACreator, IOTAModuleCreator)
private
FHaveNames: Boolean;
FFormName: string;
FFileName: string;
FImplFileName: string;
FImplFormName: string;
procedure GetNewModuleAndClassName(out AFormName, AImplFileName: string);
protected
{ IOTACreator }
function GetCreatorType: string;
function GetOwner: IOTAModule;
{ IOTAModuleCreator }
function GetAncestorName: string;
function GetImplFileName: string;
function GetIntfFileName: string;
function GetFormName: string;
function GetMainForm: Boolean;
function GetShowForm: Boolean;
function GetShowSource: Boolean;
function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
procedure FormCreated(const FormEditor: IOTAFormEditor);
public
constructor Create(const AFileName, AFormName: string);
end;
TOTAFile = class(TInterfacedObject, IOTAFile)
private
FContent: string;
public
constructor Create(const AContent: string);
{ IOTAFile }
function GetSource: string;
function GetAge: TDateTime;
end;
function GetNewModuleFileName(const APrefix, AOptionalDirectory,
AOptionalFileName: string; AUseDefaultFileExt: Boolean; out LSuffix: string): string;
implementation
uses ExpertsResStrs;
function GetNewModuleFileName(const APrefix, AOptionalDirectory,
AOptionalFileName: string; AUseDefaultFileExt: Boolean;
out LSuffix: string): string;
var
LServices: IOTAModuleServices;
function ModuleOrFileExists(const AFileName: string): Boolean;
begin
Result := FileExists(AFileName) or
((BorlandIDEServices as IOTAModuleServices).FindModule(AFileName) <> nil);
end;
function CanFormatFileName(const AFileName: string): Boolean;
begin
Result := (Pos('%d', Lowercase(AFileName)) >= 1) or (Pos('%0:d', Lowercase(AFileName)) >= 1);
end;
function MakeFileName(const ADirectory, AFileName, AFileExt: string): string; overload;
begin
Result := Format('%0:s%1:s%2:d%3:s', [ADirectory, AFileName, AFileExt]);
end;
function MakeFileName(const ADirectory, AFileName, AIndex, AFileExt: string): string; overload;
begin
Assert(AFileName <> Format(AFileName, [AIndex]));
Result := MakeFileName(ADirectory, Format(AFileName, [AIndex]), AFileExt);
end;
function FindNextAvailableFileName(const AFileName: string; out LSuffix: string): string;
var
I: Integer;
LFileNameFormat: string;
begin
LSuffix := '';
LFileNameFormat := AFileName;
if not CanFormatFileName(LFileNameFormat) then
LFileNameFormat := ExtractFilePath(LFileNameFormat) +
ChangeFileExt(ExtractFileName(LFileNameFormat), '') + '%d' +
ExtractFileExt(LFileNameFormat);
I := 1;
Result := Format(LFileNameFormat, [I]);
while ModuleOrFileExists(Result) do
begin
Inc(I);
Result := Format(LFileNameFormat, [I]);
end;
LSuffix := IntToStr(I);
end;
function GetDefaultFileExt: string;
var
LNewTextFileIdent, LNewClassName, LNewFileName: string;
begin
LServices.GetNewModuleAndClassName(APrefix, // Do not localize
LNewTextFileIdent, LNewClassName, LNewFileName);
Result := ExtractFileExt(LNewFileName);
end;
function GetDefaultDirectory: string;
var
LNewTextFileIdent, LNewClassName, LNewFileName: string;
begin
LServices.GetNewModuleAndClassName(APrefix, // Do not localize
LNewTextFileIdent, LNewClassName, LNewFileName);
Result := ExtractFilePath(LNewFileName);
end;
var
LFileName:string;
LDirectory: string;
begin
LSuffix := '';
LServices := (BorlandIDEServices as IOTAModuleServices);
if AOptionalFileName = '' then
LFileName := ChangeFileExt(APrefix + '%d', GetDefaultFileExt) // do not localize
else
begin
LFileName := AOptionalFileName;
if AUseDefaultFileExt then
LFileName := ChangeFileExt(LFileName, GetDefaultFileExt);
end;
if AOptionalDirectory <> '' then
LDirectory := ExtractFilePath(AOptionalDirectory)
else
LDirectory := GetDefaultDirectory;
if not CanFormatFileName(LFileName) then
begin
Result := LDirectory + LFileName;
if ModuleOrFileExists(Result) then
Result := FindNextAvailableFileName(Result, LSuffix);
end
else
Result := FindNextAvailableFileName(LDirectory + LFileName, LSuffix);
end;
{ TCreator }
function TCreator.GetExisting: Boolean;
begin
Result := False;
end;
function TCreator.GetFileSystem: string;
begin
Result := '';
end;
function TCreator.GetOwner: IOTAModule;
begin
Result := nil;
end;
function TCreator.GetUnnamed: Boolean;
begin
Result := True;
end;
{ TUnitCreator }
constructor TUnitCreator.Create(const AFileName: string);
begin
FFileName := AFileName;
end;
procedure TUnitCreator.FormCreated(const FormEditor: IOTAFormEditor);
begin
end;
function TUnitCreator.GetAncestorName: string;
begin
Result := '';
end;
function TUnitCreator.GetCreatorType: string;
begin
Result := sUnit;
end;
function TUnitCreator.GetIntfFileName: string;
begin
Result := '';
end;
function TUnitCreator.GetMainForm: Boolean;
begin
Result := False;
end;
function TUnitCreator.GetOwner: IOTAModule;
begin
Result := GetActiveProject;
end;
function TUnitCreator.GetShowForm: Boolean;
begin
Result := True;
end;
function TUnitCreator.GetShowSource: Boolean;
begin
Result := True;
end;
function TUnitCreator.NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
function TUnitCreator.NewImplSource(const ModuleIdent, FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
function TUnitCreator.NewIntfSource(const ModuleIdent, FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
function TUnitCreator.GetNewUnitFileName: string;
var
LSuffix: string;
begin
if FNewImplFileName = '' then
begin
FNewImplFileName := GetNewModuleFileName('Unit',
ExtractFilePath(Self.FFileName), ExtractFileName(Self.FFileName), True, LSuffix);
end;
Result := FNewImplFileName;
end;
function TUnitCreator.GetFormName: String;
begin
Result := '';
end;
function TUnitCreator.GetImplFileName: String;
begin
Result := GetNewUnitFileName;
end;
{ TTextFileCreator }
constructor TTextFileCreator.Create(const AFileName,
AFileNameExt: string);
begin
inherited Create;
FFileName := AFileName;
if AFileName = '' then
FFileName := 'Text%d';
FFileNameExt := AFileNameExt;
end;
procedure TTextFileCreator.FormCreated(const FormEditor: IOTAFormEditor);
begin
end;
function TTextFileCreator.GetAncestorName: string;
begin
Result := '';
end;
function TTextFileCreator.GetCreatorType: string;
begin
Result := sText;
end;
function TTextFileCreator.GetIntfFileName: string;
begin
Result := '';
end;
function TTextFileCreator.GetMainForm: Boolean;
begin
Result := False;
end;
function TTextFileCreator.GetOwner: IOTAModule;
begin
Result := GetActiveProject;
end;
function TTextFileCreator.GetShowForm: Boolean;
begin
Result := True;
end;
function TTextFileCreator.GetShowSource: Boolean;
begin
Result := True;
end;
function TTextFileCreator.NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
function TTextFileCreator.NewImplSource(const ModuleIdent, FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
function TTextFileCreator.NewIntfSource(const ModuleIdent, FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
procedure TTextFileCreator.GetNewTextFileName(out ATextFileName: string);
var
LSuffix: string;
begin
if FNewTextFileName = '' then
begin
FNewTextFileName := GetNewModuleFileName('Text',
ExtractFilePath(Self.FFileName),
ExtractFileName(Self.FFileName) + Self.FFileNameExt, False, LSuffix);
end;
ATextFileName := FNewTextFileName;
end;
function TTextFileCreator.GetFormName: String;
begin
Result := '';
end;
function TTextFileCreator.GetImplFileName: String;
var
LImplFileName: string;
begin
GetNewTextFileName(LImplFileName);
Result := LImplFileName;
end;
{ TModuleCreator }
constructor TModuleCreator.Create(const AFileName, AFormName: string);
begin
FFileName := AFileName;
FFormName := AFormName;
end;
procedure TModuleCreator.FormCreated(const FormEditor: IOTAFormEditor);
begin
end;
function TModuleCreator.GetAncestorName: string;
begin
Result := '';
end;
function TModuleCreator.GetCreatorType: string;
begin
Result := sForm;
end;
function TModuleCreator.GetIntfFileName: string;
begin
Result := '';
end;
function TModuleCreator.GetMainForm: Boolean;
begin
Result := False;
end;
function TModuleCreator.GetOwner: IOTAModule;
begin
Result := GetActiveProject;
end;
function TModuleCreator.GetShowForm: Boolean;
begin
Result := True;
end;
function TModuleCreator.GetShowSource: Boolean;
begin
Result := True;
end;
function TModuleCreator.NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
function TModuleCreator.NewImplSource(const ModuleIdent, FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
function TModuleCreator.NewIntfSource(const ModuleIdent, FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
procedure TModuleCreator.GetNewModuleAndClassName(out AFormName: string; out AImplFileName: string);
function FormExists(const AFormName, AFileName: string): Boolean;
begin
// Form can't have same name as the file
Result :=
((BorlandIDEServices as IOTAModuleServices).FindFormModule(AFormName) <> nil) or
SameFileName(ExtractFileName(ChangeFileExt(AFileName, '')),
AFormName);
end;
function CanFormatName(const AName: string): Boolean;
begin
Result := (Pos('%d', Lowercase(AName)) >= 1) or (Pos('%0:d', Lowercase(AName)) >= 1);
end;
var
LSuffix: string;
LFormNameFormat: string;
I: Integer;
begin
if not FHaveNames then
begin
FHaveNames := True;
if Self.FFileName <> '' then
begin
FImplFileName := GetNewModuleFileName('Unit',
ExtractFilePath(Self.FFileName), ExtractFileName(Self.FFileName), True, LSuffix);
if FFormName <> '' then
begin
if CanFormatName(FFormName) and (LSuffix <> '') then
FImplFormName := Format(FFormName, [StrToInt(LSuffix)]);
if FormExists(FImplFormName, FImplFileName) then
begin
if not CanFormatName(FFormName) then
LFormNameFormat := FFormName + '%d'
else
LFormNameFormat := FFormName;
I := 1;
while FormExists(Format(LFormNameFormat, [I]), FImplFileName) do
Inc(I);
FImplFormName := Format(LFormNameFormat, [I]);
end;
end
end;
end;
AImplFileName := FImplFileName;
AFormName := FImplFormName;
end;
function TModuleCreator.GetFormName: String;
var
LFormName: string;
LImplFileName: string;
begin
GetNewModuleAndClassName(LFormName, LImplFileName);
Result := LFormName;
end;
function TModuleCreator.GetImplFileName: String;
var
LFormName: string;
LImplFileName: string;
begin
GetNewModuleAndClassName(LFormName, LImplFileName);
Result := LImplFileName;
end;
{ TOTAFile }
constructor TOTAFile.Create(const AContent: string);
begin
FContent := AContent;
end;
function TOTAFile.GetAge: TDateTime;
begin
Result := -1;
end;
function TOTAFile.GetSource: string;
begin
Result := FContent;
end;
end.
|
{ ********************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ Component and Property Editor Source }
{ }
{ Copyright (C) 2000, 2001 Borland Software Corporation }
{ }
{ All Rights Reserved. }
{ }
{ ********************************************************************** }
unit ClxNodeEdit;
interface
uses
SysUtils, Classes, QGraphics, QControls, QForms, QDialogs,
DesignIntf, DesignEditors, DsnConst, LibHelp, QConsts, QStdCtrls, QComCtrls;
type
TClxTreeViewItems = class(TForm)
GroupBox1: TGroupBox;
PropGroupBox: TGroupBox;
New: TButton;
Delete: TButton;
Label1: TLabel;
Label2: TLabel;
TreeView: TTreeView;
NewSub: TButton;
Text: TEdit;
Image: TEdit;
Button4: TButton;
Cancel: TButton;
Apply: TButton;
Help: TButton;
SelectedIndex: TEdit;
Label4: TLabel;
Load: TButton;
OpenDialog1: TOpenDialog;
gbSubItems: TGroupBox;
lbSubItems: TListBox;
btnAddSub: TButton;
btnDelSub: TButton;
gbSubItemProps: TGroupBox;
lblSubText: TLabel;
edtSubText: TEdit;
lblSubImgIndex: TLabel;
edtSubImgIndex: TEdit;
procedure NewClick(Sender: TObject);
procedure NewSubClick(Sender: TObject);
procedure DeleteClick(Sender: TObject);
procedure ValueChange(Sender: TObject);
procedure TextExit(Sender: TObject);
procedure ImageExit(Sender: TObject);
procedure ApplyClick(Sender: TObject);
procedure TreeViewChange(Sender: TObject; Node: TTreeNode);
procedure TreeViewChanging(Sender: TObject; Node: TTreeNode;
var AllowChange: Boolean);
procedure SelectedIndexExit(Sender: TObject);
procedure LoadClick(Sender: TObject);
procedure TreeViewDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure TreeViewDragDrop(Sender, Source: TObject; X, Y: Integer);
procedure TreeViewEdited(Sender: TObject; Node: TTreeNode;
var S: WideString);
procedure HelpClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure edtSubTextExit(Sender: TObject);
procedure edtSubImgIndexExit(Sender: TObject);
procedure btnAddSubClick(Sender: TObject);
procedure btnDelSubClick(Sender: TObject);
procedure lbSubItemsClick(Sender: TObject);
procedure edtSubTextChange(Sender: TObject);
private
FItems: TTreeNodes;
FDropping: Boolean;
FPutting: Boolean;
procedure FlushControls;
procedure SetItem(Value: TTreeNode);
procedure SetStates;
function SubItemsShouldBeDisabled: Boolean;
procedure PutSubItemText(const Str: string);
public
property Items: TTreeNodes read FItems;
end;
{ TTreeViewEditor }
type
TEditInvoker = class
private
FDesigner: IDesigner;
FComponent: TComponent;
procedure InvokeEdit;
public
constructor Create(ADesigner: IDesigner; AComponent: TComponent);
end;
TTreeViewEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TTreeViewItemsProperty = class(TClassProperty)
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
TTreeViewColumnsProperty = class(TClassProperty)
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
function EditTreeViewItems(AItems: TTreeNodes): Boolean;
implementation
{$R *.xfm}
uses
{$IFDEF MSWINDOWS}
Qt, ColnEdit;
{$ENDIF}
{$IFDEF LINUX}
Qt, ColnEdit, Libc;
{$ENDIF}
function EditTreeViewItems(AItems: TTreeNodes): Boolean;
begin
with TClxTreeViewItems.Create(Application) do
try
TreeView.SortType := TTreeView(AItems.Owner).SortType;
FItems := AItems;
TreeView.Items.Assign(Items);
with TreeView do
if Items.Count > 0 then
begin
Selected := Items.GetFirstNode;
TreeViewChange(nil, Selected);
end;
SetStates;
Apply.Enabled := False;
Result := ShowModal = mrOK;
if Result and Apply.Enabled then
ApplyClick(nil);
finally
Free;
end;
end;
procedure ConvertError(Value: TEdit);
begin
with Value do
begin
SetFocus;
SelectAll;
end;
end;
{ TClxTreeViewItems }
procedure TClxTreeViewItems.SetStates;
begin
Delete.Enabled := TreeView.Items.Count > 0;
PropGroupBox.Enabled := Delete.Enabled;
NewSub.Enabled := TreeView.Selected <> nil;
btnAddSub.Enabled := TreeView.Selected <> nil;
btnDelSub.Enabled := lbSubItems.ItemIndex <> -1;
gbSubItemProps.Enabled := btnDelSub.Enabled;
end;
procedure TClxTreeViewItems.SetItem(Value: TTreeNode);
begin
if Assigned(Value) then
with Value do
begin
Self.Text.Text := Text;
Image.Text := IntToStr(ImageIndex);
Self.SelectedIndex.Text := IntToStr(SelectedIndex);
lbSubItems.Items.Assign(SubItems);
if lbSubItems.Items.Count = 0 then
begin
PutSubItemText('');
edtSubImgIndex.Text := '-1';
end;
end
else
begin
Text.Text := '';
Image.Text := '';
SelectedIndex.Text := '';
lbSubItems.Items.Clear;
if lbSubItems.ItemIndex = -1 then
begin
PutSubItemText('');
edtSubImgIndex.Text := '-1';
end;
end;
SetStates;
end;
procedure TClxTreeViewItems.FlushControls;
begin
edtSubTextExit(nil);
edtSubImgIndexExit(nil);
TextExit(nil);
ImageExit(nil);
SelectedIndexExit(nil);
end;
procedure TClxTreeViewItems.TreeViewChanging(Sender: TObject; Node: TTreeNode;
var AllowChange: Boolean);
begin
if not FDropping then
FlushControls;
end;
procedure TClxTreeViewItems.TreeViewChange(Sender: TObject; Node: TTreeNode);
var
TempEnabled: Boolean;
begin
if not FDropping then
begin
TempEnabled := Apply.Enabled;
SetStates;
SetItem(Node);
Apply.Enabled := TempEnabled;
end;
end;
procedure TClxTreeViewItems.NewClick(Sender: TObject);
var
Node: TTreeNode;
begin
Node := TreeView.Selected;
Node := TreeView.Items.Add(Node, '');
Node.MakeVisible;
TreeView.Selected := Node;
SetItem(Node);
Text.SetFocus;
Apply.Enabled := True;
end;
procedure TClxTreeViewItems.NewSubClick(Sender: TObject);
var
Node: TTreeNode;
begin
with TreeView do
begin
Node := Selected;
if Assigned(Node) then
begin
Node := Items.AddChild(Node, '');
Node.MakeVisible;
Selected := Node;
end;
end;
Text.SetFocus;
Apply.Enabled := True;
end;
procedure TClxTreeViewItems.DeleteClick(Sender: TObject);
begin
TreeView.Selected.Free;
if TreeView.Items.Count = 0 then
SetItem(nil)
else if Assigned(TreeView.Selected) then
SetItem(TreeView.Selected);
SetStates;
Apply.Enabled := True;
end;
procedure TClxTreeViewItems.ValueChange(Sender: TObject);
begin
Apply.Enabled := True;
if Sender = Text then
TextExit(Sender);
end;
procedure TClxTreeViewItems.TextExit(Sender: TObject);
var
Node: TTreeNode;
begin
Node := TreeView.Selected;
if Assigned(Node) then
Node.Text := Text.Text;
end;
procedure TClxTreeViewItems.ImageExit(Sender: TObject);
var
Node: TTreeNode;
begin
if ActiveControl <> Cancel then
try
Node := TreeView.Selected;
if Assigned(Node) then
Node.ImageIndex := StrToInt(Image.Text);
except
ConvertError(Image);
raise;
end;
end;
procedure TClxTreeViewItems.SelectedIndexExit(Sender: TObject);
var
Node: TTreeNode;
begin
if ActiveControl <> Cancel then
try
Node := TreeView.Selected;
if not Assigned(Node) then
Exit;
Node.SelectedIndex := StrToInt(SelectedIndex.Text);
except
ConvertError(SelectedIndex);
raise;
end;
end;
procedure TClxTreeViewItems.ApplyClick(Sender: TObject);
begin
FlushControls;
Items.Assign(TreeView.Items);
Apply.Enabled := False;
end;
procedure TClxTreeViewItems.LoadClick(Sender: TObject);
begin
OpenDialog1.Title := SOpenFileTitle;
with OpenDialog1 do
if Execute then
begin
TreeView.LoadFromFile(FileName);
SetStates;
Apply.Enabled := True;
end;
end;
procedure TClxTreeViewItems.TreeViewDragOver(Sender, Source: TObject; X,
Y: Integer; State: TDragState; var Accept: Boolean);
begin
Accept := True;
end;
procedure TClxTreeViewItems.TreeViewDragDrop(Sender, Source: TObject; X,
Y: Integer);
var
Node: TTreeNode;
AddMode: TNodeAttachMode;
begin
FDropping := True;
try
with TreeView do
if Assigned(Selected) then
begin
if ssCtrl in Application.KeyState then
AddMode := naAddChildFirst
else
AddMode := naInsert;
Node := TreeView.DropTarget;
if Assigned(Node) then
Selected.MoveTo(Node, AddMode);
Apply.Enabled := True;
{ if Node = nil then
begin
Node := Items[Items.Count - 1];
while Assigned(Node) and not Node.IsVisible do
Node := Node.GetPrev;
end;
if Assigned(Node) then
with Selected do
try
FDropping := True;
MoveTo(Node, AddMode);
Selected := True;
Apply.Enabled := True;
finally
FDropping := False;
end; }
end;
finally
FDropping := False;
end;
end;
procedure TClxTreeViewItems.TreeViewEdited(Sender: TObject; Node: TTreeNode;
var S: WideString);
begin
Text.Text := S;
TextExit(nil);
end;
procedure TClxTreeViewItems.edtSubTextExit(Sender: TObject);
var
Node: TTreeNode;
ItemIndex: Integer;
begin
if SubItemsShouldBeDisabled then
Exit;
Node := TreeView.Selected;
ItemIndex := lbSubItems.ItemIndex;
if ItemIndex <> -1 then
begin
lbSubItems.Items[ItemIndex] := edtSubText.Text;
Node.SubItems[ItemIndex] := lbSubItems.Items[ItemIndex];
end;
end;
procedure TClxTreeViewItems.edtSubImgIndexExit(Sender: TObject);
var
Node: TTreeNode;
ItemIndex: Integer;
begin
if SubItemsShouldBeDisabled then
Exit;
Node := TreeView.Selected;
ItemIndex := lbSubItems.ItemIndex;
if ItemIndex <> -1 then
try
Node.SubItemImages[ItemIndex] := StrToInt(edtSubImgIndex.Text);
except
ConvertError(edtSubImgIndex);
raise;
end;
end;
procedure TClxTreeViewItems.HelpClick(Sender: TObject);
begin
InvokeHelp;
end;
procedure TClxTreeViewItems.FormCreate(Sender: TObject);
begin
HelpContext := hcDTreeViewItemEdit;
OpenDialog1.Filter := SOpenDialogFilter;
end;
procedure TClxTreeViewItems.btnAddSubClick(Sender: TObject);
begin
if not Assigned(TreeView.Selected) then
begin
PutSubItemText('');
edtSubImgIndex.Text := '-1';
gbSubItemProps.Enabled := False;
Exit;
end;
TreeView.Selected.SubItems.Add('');
lbSubItems.ItemIndex := lbSubItems.Items.Add('');
gbSubItemProps.Enabled := True;
PutSubItemText('');
edtSubImgIndex.Text := '-1';
Apply.Enabled := True;
edtSubText.SetFocus;
end;
procedure TClxTreeViewItems.btnDelSubClick(Sender: TObject);
var
ItemIndex: Integer;
begin
if SubItemsShouldBeDisabled then
Exit;
ItemIndex := lbSubItems.ItemIndex;
lbSubItems.Items.Delete(ItemIndex);
TreeView.Selected.SubItems.Delete(ItemIndex);
if lbSubItems.Items.Count <> 0 then
if ItemIndex <> 0 then
lbSubItems.ItemIndex := ItemIndex - 1
else
lbSubItems.ItemIndex := 0;
gbSubItemProps.Enabled := lbSubItems.Items.Count <> 0;
if lbSubItems.ItemIndex <> -1 then
begin
edtSubText.Text := lbSubItems.Items.Strings[lbSubItems.Itemindex];
edtSubImgIndex.Text := IntToStr(TreeView.Selected.SubItemImages[lbSubItems.ItemIndex]);
end;
Apply.Enabled := True;
end;
procedure TClxTreeViewItems.PutSubItemText(const Str: string);
begin
FPutting := True;
try
edtSubText.Text := Str;
finally
FPutting := False;
end;
end;
procedure TClxTreeViewItems.lbSubItemsClick(Sender: TObject);
begin
if not btnAddSub.Enabled then
Exit;
if SubItemsShouldBeDisabled then
Exit;
edtSubImgIndex.Text := IntToStr(TreeView.Selected.SubItemImages[lbSubItems.ItemIndex]);
if TreeView.Selected.SubItems.Count > lbSubItems.ItemIndex then
PutSubItemText(TreeView.Selected.SubItems[lbSubItems.ItemIndex])
else
PutSubItemText('');
SetStates;
end;
function TClxTreeViewItems.SubItemsShouldBeDisabled: Boolean;
begin
if (not Assigned(TreeView.Selected)) or (lbSubItems.ItemIndex = -1) then
begin
PutSubItemText('');
edtSubImgIndex.Text := '-1';
gbSubItemProps.Enabled := False;
Result := True;
end
else
Result := False;
end;
procedure TClxTreeViewItems.edtSubTextChange(Sender: TObject);
var
ItemIndex: Integer;
begin
if FPutting then
Exit;
Apply.Enabled := True;
if Sender = edtSubText then
begin
ItemIndex := lbSubItems.ItemIndex;
if ItemIndex = -1 then
Exit;
lbSubItems.Items[ItemIndex] := edtSubText.Text;
TreeView.Selected.SubItems[ItemIndex] := lbSubItems.Items[ItemIndex];
end;
end;
{ TEditInvoker }
constructor TEditInvoker.Create(ADesigner: IDesigner; AComponent: TComponent);
begin
inherited Create;
FDesigner := ADesigner;
FComponent := AComponent;
end;
procedure TEditInvoker.InvokeEdit;
begin
ShowCollectionEditor(FDesigner, FComponent, TTreeView(FComponent).Columns, 'Columns');
Free;
end;
{ TTreeViewEditor }
procedure TTreeViewEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0:
if EditTreeViewItems(TTreeView(Component).Items) and
Assigned(Designer) then
Designer.Modified;
1: TEditInvoker.Create(Designer, Component).InvokeEdit;
end;
end;
function TTreeViewEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := STreeItemsEditor;
1: Result := STreeColumnsEditor;
end;
end;
function TTreeViewEditor.GetVerbCount: Integer;
begin
Result := 2;
end;
{ TTreeViewItemsProperty }
procedure TTreeViewItemsProperty.Edit;
var
Component: TComponent;
begin
Component := TComponent(GetComponent(0));
if not Assigned(Component) then
Exit;
if EditTreeViewItems(TTreeView(Component).Items) and Assigned(Designer) then
Designer.Modified;
end;
function TTreeViewItemsProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paMultiSelect, paRevertable];
end;
{ TTreeViewColumnsProperty }
procedure TTreeViewColumnsProperty.Edit;
var
Component: TComponent;
begin
Component := TComponent(GetComponent(0));
if not Assigned(Component) then
Exit;
ShowCollectionEditor(Designer, Component, TTreeView(Component).Columns, 'Columns');
end;
function TTreeViewColumnsProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paMultiSelect, paRevertable, paVCL];
end;
end.
|
{
IsZRDOS: return TRUE if we're running ZRDOS (for file timestamps)
}
FUNCTION IsZRDOS : BOOLEAN;
CONST
GetDosVersion = 48;
BEGIN
IsZRDOS := ((BdosHL(GetDosVersion) AND $FF00) SHR 8) = 0;
END;
|
unit pFIBExports;
interface
{$I FIBPlus.inc}
uses SysUtils,{$IFNDEF D6+}Windows,{$ELSE}FIBPlatforms,{$ENDIF}Classes,
pFIBInterfaces,FIBDatabase,FIBQuery,FIBDataSet,pFIBDataSet,pFIBQuery,
StrUtil,pFIBDatabase,SqlTxtRtns, pFIBMetaData;
type
TFIBStringer= class(TComponent, IFIBStringer)
private
function FormatIdentifier(Dialect: Integer; const Value: string): string;
procedure DispositionFromClause(const SQLText:string;var X,Y:integer);
function PosCh(aCh:Char; const s:string):integer;
function PosCh1(aCh:Char; const s:string; StartPos:integer):integer;
function PosCI(const Substr,Str:string):integer;
function EmptyStrings(SL:TStrings):boolean;
function EquelStrings(const s,s1:string; CaseSensitive:boolean):boolean;
procedure DeleteEmptyStr(Src:TStrings);//
procedure AllTables(const SQLText:string;aTables:TStrings; WithSP:boolean =False
;WithAliases:boolean =False
);
function WordCount(const S: string; const WordDelims: TCharSet): Integer;
function ExtractWord(Num:integer;const Str: string;const WordDelims:TCharSet):string;
function PosInRight(const substr,Str:string;BeginPos:integer):integer;
function LastChar(const Str:string):Char;
function TableByAlias(const SQLText,Alias:string):string;
function AliasForTable(const SQLText,TableName:string):string;
function SetOrderClause(const SQLText,Order:string):string;
function AddToMainWhereClause(const SQLText,Condition:string):string;
end;
TMetaDataExtractor=class(TpFIBDBSchemaExtract, IFIBMetaDataExtractor)
private
function DBPrimaryKeys(const TableName:string;Transaction:TObject):string;
function IsCalculatedField(const TableName,FieldName:string;Transaction:TObject):boolean;
function ObjectDDLTxt(Transaction:TObject;ObjectType:Integer; const ObjectName:string; ForceLoad:boolean=True): string ;
procedure SetDatabase(aDatabase:TObject);
function GetTableName(Index:integer): string;
function GetViewName(Index:integer): string;
function GetProcedureName(Index:integer): string;
function GetUDFName(Index:integer): string;
function GetGeneratorName(Index:integer): string;
function ObjectListFields(const ObjectName:string; var DDL:string ;ForceLoad:boolean=True;IncludeOBJName:boolean=False): string ;
public
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
end;
TiSQLParser=class(TSQLParser,ISQLParser)
protected
{ IInterface }
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
// procedure SetSQLText(const Value: string);
function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall;
function iPosInSections(Position:integer):TiSQLSections;
function SectionInArray(Section:TiSQLSection ;ArrS:TiSQLSections):boolean;
function CutAlias(const SQLString:string;AliasPosition:integer=0):string;
function CutTableName(const SQLString:string;AliasPosition:integer=0):string;
function AliasForTable(const SQLText,TableName:string):string;
function TableByAlias(const SQLText,Alias:string):string;
end;
TFIBClassesExporter =class (TComponent, IFIBClassesExporter,IFIBStringer,IFIBMetaDataExtractor,
ISQLParser
)
private
FStringer:TFIBStringer;
FMetaDataExtractor:TMetaDataExtractor;
FSQLParser :TiSQLParser;
function iGetStringer:IFIBStringer;
function iGetMetaExtractor:IFIBMetaDataExtractor;
function iGetSQLParser:ISQLParser;
public
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
property Stringer:TFIBStringer read FStringer implements IFIBStringer;
property MetaDataExtractor:TMetaDataExtractor read FMetaDataExtractor implements IFIBMetaDataExtractor;
property SQLParser:TiSQLParser read FSQLParser implements iSQLParser;
end
;
implementation
uses pFIBDataInfo,IB_Services;
var vFIBClassesExporter:TFIBClassesExporter;
{ TFIBClassesExporter }
constructor TFIBClassesExporter.Create(AOwner: TComponent);
begin
inherited;
FIBClassesExporter:=Self;
FStringer:=TFIBStringer.Create(Self);
FMetaDataExtractor:=TMetaDataExtractor.Create(Self);
FSQLParser:=TiSQLParser.Create;
end;
destructor TFIBClassesExporter.Destroy;
begin
if Self= vFIBClassesExporter then
vFIBClassesExporter:=nil;
FSQLParser.Free;
inherited;
end;
function TFIBClassesExporter.iGetMetaExtractor: IFIBMetaDataExtractor;
begin
Result:=FMetaDataExtractor
end;
function TFIBClassesExporter.iGetSQLParser: ISQLParser;
begin
Result:=FSQLParser
end;
function TFIBClassesExporter.iGetStringer: IFIBStringer;
begin
Result:=FStringer;
end;
procedure CreateExporter;
begin
vFIBClassesExporter:=TFIBClassesExporter.Create(nil);
with vFIBClassesExporter do
begin
Name:='FIBClassesExporter'
end;
end;
{ TFIBStringer }
function TFIBStringer.AddToMainWhereClause(const SQLText,
Condition: string): string;
begin
Result:=SqlTxtRtns.AddToWhereClause(SQLText,Condition)
end;
function TFIBStringer.AliasForTable(const SQLText,
TableName: string): string;
begin
Result:=SqlTxtRtns.AliasForTable(SQLText,TableName)
end;
procedure TFIBStringer.AllTables(const SQLText: string; aTables: TStrings;
WithSP, WithAliases: boolean);
begin
SqlTxtRtns.AllTables(SQLText,aTables,WithSP,WithAliases);
end;
procedure TFIBStringer.DeleteEmptyStr(Src: TStrings);
begin
StrUtil.DeleteEmptyStr(Src);
end;
procedure TFIBStringer.DispositionFromClause(const SQLText:string;var X,Y:integer);
var
p:TPosition;
begin
p:=SqlTxtRtns.DispositionFrom(SQLText);
X:=P.X;
Y:=P.Y
end;
function TFIBStringer.EmptyStrings(SL: TStrings): boolean;
begin
Result:=StrUtil.EmptyStrings(SL)
end;
function TFIBStringer.EquelStrings(const s, s1: string;
CaseSensitive: boolean): boolean;
begin
Result:=StrUtil.EquelStrings(s, s1, CaseSensitive)
end;
function TFIBStringer.ExtractWord(Num: integer; const Str: string;
const WordDelims: TCharSet): string;
begin
Result:=StrUtil.ExtractWord(Num, Str,WordDelims)
end;
function TFIBStringer.FormatIdentifier(Dialect: Integer;
const Value: string): string;
begin
Result:=StrUtil.FormatIdentifier(Dialect,Value)
end;
function TFIBStringer.LastChar(const Str: string): Char;
begin
Result:=StrUtil.LastChar(Str)
end;
function TFIBStringer.PosCh(aCh: Char; const s: string): integer;
begin
Result:=StrUtil.PosCh(aCh,s)
end;
function TFIBStringer.PosCh1(aCh: Char; const s: string;
StartPos: integer): integer;
begin
Result:=StrUtil.PosCh1(aCh,s,StartPos)
end;
function TFIBStringer.PosCI(const Substr, Str: string): integer;
begin
Result:=StrUtil.PosCI(Substr, Str)
end;
function TFIBStringer.PosInRight(const substr, Str: string;
BeginPos: integer): integer;
begin
Result:=StrUtil.PosInRight(substr, Str, BeginPos)
end;
function TFIBStringer.SetOrderClause(const SQLText, Order: string): string;
begin
Result:=SqlTxtRtns.SetOrderClause(SQLText,Order)
end;
function TFIBStringer.TableByAlias(const SQLText, Alias: string): string;
begin
Result:=SqlTxtRtns.TableByAlias(SQLText,Alias)
end;
function TFIBStringer.WordCount(const S: string;
const WordDelims: TCharSet): Integer;
begin
Result:=StrUtil.WordCount(S,WordDelims)
end;
{ TMetaDataExtractor }
constructor TMetaDataExtractor.Create(AOwner: TComponent);
begin
inherited;
end;
function TMetaDataExtractor.DBPrimaryKeys(const TableName: string;
Transaction: TObject): string;
begin
Result:=pFIBDataInfo.DBPrimaryKeyFields(TableName,TFIBTransaction(Transaction))
end;
destructor TMetaDataExtractor.Destroy;
begin
inherited;
end;
function TMetaDataExtractor.GetGeneratorName(Index: integer): string;
begin
Result:=Generators[Index].Name
end;
function TMetaDataExtractor.GetProcedureName(Index: integer): string;
begin
Result:=Procedures[Index].Name
end;
function TMetaDataExtractor.GetTableName(Index: integer): string;
begin
Result:=Tables[Index].Name
end;
function TMetaDataExtractor.GetUDFName(Index: integer): string;
begin
Result:=UDFS[Index].Name
end;
function TMetaDataExtractor.GetViewName(Index: integer): string;
begin
Result:=Views[Index].Name
end;
function TMetaDataExtractor.IsCalculatedField(const TableName,
FieldName: string; Transaction: TObject): boolean;
var
vpFIBTableInfo:TpFIBTableInfo;
vFi:TpFIBFieldInfo;
begin
ListTableInfo.Clear;
vpFIBTableInfo:=ListTableInfo.GetTableInfo(TFIBTransaction(Transaction).MainDatabase,TableName,False);
vFi:=vpFIBTableInfo.FieldInfo(FieldName);
Result:= (vFi=nil) or vFi.IsComputed or vFi.IsTriggered ;
end;
function TMetaDataExtractor.ObjectDDLTxt(Transaction:TObject;ObjectType: Integer;
const ObjectName: string; ForceLoad: boolean): string;
var
Extractor:TpFIBDBSchemaExtract;
begin
Result:='';
if (Transaction=nil ) or (TFIBTransaction(Transaction).DefaultDatabase=nil) then
Exit;
Extractor:=TpFIBDBSchemaExtract.Create(nil);
try
Extractor.Database:=TFIBTransaction(Transaction).DefaultDatabase;
Result:=Extractor.GetObjectDDL(TDBObjectType(ObjectType), ObjectName, ForceLoad);
finally
Extractor.Free
end;
end;
function TMetaDataExtractor.ObjectListFields(
const ObjectName: string; var DDL:string ;ForceLoad: boolean=True;IncludeOBJName:boolean=False): string;
var
obj:TCustomMetaObject;
i:integer;
begin
obj:=FMetaDatabase.GetDBObject(Database,otTable,ObjectName,ForceLoad);
if obj=nil then
obj:=FMetaDatabase.GetDBObject(Database,otView,ObjectName,ForceLoad);
if obj=nil then
obj:=FMetaDatabase.GetDBObject(Database,otProcedure,ObjectName,ForceLoad);
Result:='';
DDL:='';
if obj=nil then
Exit;
if obj is TMetaTable then
begin
with TMetaTable(obj) do
for i:=0 to FieldsCount-1 do
begin
if IncludeOBJName then
DDL:=Result+FormatIdentifier(3,ObjectName)+'.'+ Fields[i].FormatName+#13#10
else
DDL:=Result+Fields[i].FormatName+#13#10;
Result:=DDL
end;
end
else
if obj is TMetaView then
begin
with TMetaView(obj) do
for i:=0 to FieldsCount-1 do
begin
// DDL:=DDL+Fields[i].AsDDL;
if IncludeOBJName then
DDL:=Result+FormatIdentifier(3,ObjectName)+'.'+ Fields[i].FormatName+#13#10
else
DDL:=Result+Fields[i].FormatName+#13#10;
Result:=DDL
end;
end
else
if obj is TMetaProcedure then
begin
with TMetaProcedure(obj) do
for i:=0 to OutputFieldsCount-1 do
begin
// DDL:=DDL+Fields[i].AsDDL;
if IncludeOBJName then
DDL:=Result+FormatIdentifier(3,ObjectName)+'.'+ OutputFields[i].FormatName+#13#10
else
DDL:=Result+OutputFields[i].FormatName+#13#10;
Result:=DDL
end;
end
end;
procedure TMetaDataExtractor.SetDatabase(aDatabase: TObject);
begin
if Database<>aDatabase then
Database:=TFIBDatabase(aDatabase)
end;
{ TiSQLParser }
function TiSQLParser._AddRef: Integer;
begin
Result := -1 // -1 indicates no reference counting is taking place
end;
function TiSQLParser._Release: Integer;
begin
Result := -1 // -1 indicates no reference counting is taking place
end;
function TiSQLParser.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then Result := S_OK
else Result := E_NOINTERFACE
end;
{
procedure TiSQLParser.SetSQLText(const Value: string);
begin
SQLText:=Value
end;
}
function TiSQLParser.iPosInSections(Position: integer): TiSQLSections;
begin
Result:=TiSQLSections(PosInSections(Position))
end;
function TiSQLParser.SectionInArray(Section: TiSQLSection;
ArrS: TiSQLSections): boolean;
var
i,L:integer;
begin
Result:=False;
L:=Length(ArrS)-1;
for i:=0 to L do
if ArrS[i]=Section then
begin
Result:=True; Exit
end;
end;
function TiSQLParser.TableByAlias(const SQLText, Alias: string): string;
begin
Result:=SqlTxtRtns.TableByAlias(SQLText, Alias)
end;
function TiSQLParser.CutAlias(const SQLString: string;
AliasPosition: integer): string;
begin
Result:=SqlTxtRtns.CutAlias(SQLString,AliasPosition)
end;
function TiSQLParser.CutTableName(const SQLString: string;
AliasPosition: integer): string;
begin
Result:=SqlTxtRtns.CutTableName(SQLString,AliasPosition)
end;
function TiSQLParser.AliasForTable(const SQLText,
TableName: string): string;
begin
Result:=SqlTxtRtns.AliasForTable(SQLText,TableName)
end;
initialization
CreateExporter;
finalization
FIBClassesExporter:=nil;
if vFIBClassesExporter<>nil then
vFIBClassesExporter.Free
end.
|
unit FileLoader;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Dialogs,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, DBGrids, Grids,
IdFTP, IdFTPList, IdFTPCommon, IniFiles, StrUtils, ComCtrls,
Themes, Forms, DB, URegIni1, Logger;
type
PMemItems = ^TMemItems;
PMemItem = ^TMemItem;
TMemItem = record
List : PMemItems;
Name : string;
Dir : boolean;
DirList : PMemItems;
Modified : TDateTime;
LocModified : TDateTime;
NewVer : boolean;
Selected : boolean;
FileSize : integer;
Loaded : boolean;
end;
TMemItems = record
UpItems : PMemItems;
RemDir, LocDir : string;
Items : TList;
end;
TBeforeLoadFile = procedure (FileName : string; Dir : boolean; var Accept : boolean) of object;
TOnProgress = procedure (ProgressPercent : integer; FileName : string) of object;
TAfterGetItem = procedure (FileName : string; Dir : boolean; var Accept : boolean) of object;
TOnGetFileType = procedure (FileName : string; var Index : integer; var FileTypeName : string) of object;
TLoadMode = (lmAll, lmSelected, lmModified);
TLoadModes = set of TLoadMode;
TCustomFTPLoader = class(TComponent)
private
FRemote : boolean;
FHost : string;
FLocalRoot: string;
FRootMemItems : PMemItems;
FAfterLoad : TNotifyEvent;
FAfterGetItem : TAfterGetItem;
FBeforeLoadFile : TBeforeLoadFile;
FOnGetFileType : TOnGetFileType;
FOnProgress : TOnProgress;
FTotalSize : integer;
FTP : TIdFTP;
FLoadedSize : integer;
LoadErr : boolean;
FCheckOnly : boolean;
FFlat : boolean;
FSelectModified : boolean;
FModifiedOnly : boolean;
FLoadSelf : boolean;
FView : TListView;
procedure SetAfterLoad(const Value: TNotifyEvent);
procedure SetAfterGetItem(const Value: TAfterGetItem);
procedure SetBeforeLoadFile(const Value: TBeforeLoadFile);
procedure SetOnGetFileType(const Value: TOnGetFileType);
procedure SetHost(const Value: string);
procedure SetLocalRoot(const Value: string);
procedure SetOnProgress(const Value: TOnProgress);
procedure SetRemote(const Value: boolean);
procedure SetCheckOnly(const Value: boolean);
procedure SetFlat(const Value: boolean);
procedure SetSelectModified(const Value: boolean);
procedure SetModifiedOnly(const Value: boolean);
function GetConnected : boolean;
procedure SetConnected(const Value: boolean);
procedure SetView(Value : TListView);
procedure ClearTree;
function GetDir(AMemItem : PMemItem) : PMemItems;
function RemoteGetDir(AMemItem : PMemItem) : PMemItems;
function NewFile(FileName : string; Modified : TDateTime; Size : integer; Item : PMemItem) : boolean;
procedure GetAll;
function GetPort : integer;
procedure CheckInactive;
procedure SetPort(Value : integer);
function FileType(FileName : string; var Index : integer) : string;
procedure Connect;
procedure Disconnect;
procedure SetFlatList;
procedure SetList(List : PMemItems = nil);
procedure Click(Sender : TObject);
procedure DblClick(Sender : TObject);
procedure SelectNew;
procedure ShowView;
procedure CheckListFormat(ASender: TObject; const ALine: String; Var VListFormat: TIdFTPListFormat);
procedure CreateFTPList(ASender: TObject; Var VFTPList: TIdFTPListItems);
procedure ParseCustomListFormat(AItem: TIdFTPListItem);
protected
procedure DoAfterGetItem(FileName : string; Dir : boolean; var Accept : boolean; Item : PMemItems); virtual;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
function NeedUpdate : boolean;
procedure Load(LoadMode : TLoadModes);
procedure LoadFile(Item : PMemItem);
function GetFile(var PutName : string; GetName : string) : boolean;
function FindItem(AMemItems : PMemItems; ItemName : string) : PMemItem;
property TotalSize : integer read FTotalSize;
property LoadedSize : integer read FLoadedSize;
property RootMemItems : PMemItems read FRootMemItems;
property Connected : boolean read GetConnected write SetConnected;
property Flat : boolean read FFlat write SetFlat;
property SelectModified : boolean read FSelectModified write SetSelectModified;
property ModifiedOnly : boolean read FModifiedOnly write SetModifiedOnly;
property View : TListView read FView write SetView;
property Remote : boolean read FRemote write SetRemote;
property Host : string read FHost write SetHost;
property LocalRoot: string read FLocalRoot write SetLocalRoot;
property AfterLoad : TNotifyEvent read FAfterLoad write SetAfterLoad;
property AfterGetItem : TAfterGetItem read FAfterGetItem write SetAfterGetItem;
property BeforeLoadFile : TBeforeLoadFile read FBeforeLoadFile write SetBeforeLoadFile;
property OnGetFileType : TOnGetFileType read FOnGetFileType write SetOnGetFileType;
property OnProgress : TOnProgress read FOnProgress write SetOnProgress;
property Port : integer read GetPort write SetPort;
property CheckOnly : boolean read FCheckOnly write SetCheckOnly;
property LoadSelf : boolean read FLoadSelf;
end;
TFTPLoader = class(TCustomFTPLoader)
published
property Remote;
property Host;
property LocalRoot;
property AfterLoad;
property AfterGetItem;
property BeforeLoadFile;
property OnGetFileType;
property OnProgress;
property Port;
property CheckOnly;
end;
procedure Register;
implementation
uses UTimeBias;
var
LastError : integer = 0;
{ TCustomFTPLoader }
function SortCompare(Item1, Item2: Pointer): Integer;
begin
if PMemItem(Item1).Dir and not PMemItem(Item2).Dir then
Result := -1
else if not PMemItem(Item1).Dir and PMemItem(Item2).Dir then
Result := 1
else
Result := CompareText(PMemItem(Item1).Name, PMemItem(Item2).Name);
end;
function TCustomFTPLoader.GetPort : integer;
begin
Result := FTP.Port;
end;
function TCustomFTPLoader.GetConnected : boolean;
begin
Result := not Remote and (RootMemItems <> nil) or FTP.Connected;
end;
procedure TCustomFTPLoader.SetConnected(const Value : boolean);
begin
if Connected <> Value then
begin
if Value then
Connect
else
Disconnect;
end;
end;
procedure TCustomFTPLoader.CheckInactive;
begin
if not (csDesigning in ComponentState) then
Disconnect;
end;
procedure TCustomFTPLoader.SetPort(Value : integer);
begin
CheckInactive;
FTP.Port := Value;
end;
function TCustomFTPLoader.FileType(FileName : string; var Index : integer) : string;
var Ext : string;
begin
Ext := ExtractFileExt(FileName);
Index := -1;
Result := UpperCase(Copy(Ext, 2, MAXINT)) + ' ' + ExtractFileName(FileName);
if Assigned(OnGetFileType) then
OnGetFileType(FileName, Index, Result);
end;
procedure TCustomFTPLoader.SetList(List : PMemItems = nil);
var I, Ind : integer;
ListItem : TListItem;
begin
Flat := False;
if List = nil then
List := RootMemItems;
with List^, View.Items do
begin
BeginUpdate;
try
Clear;
if Assigned(UpItems) then
begin
ListItem := Add;
ListItem.Caption := '..';
ListItem.SubItems.Add('<DIR>');
ListItem.ImageIndex := 7;
ListItem.Data := List;
end;
for I := 0 to Items.Count - 1 do with PMemItem(Items[ I ])^ do
begin
if ModifiedOnly and not NewVer and not Dir then
Continue;
ListItem := Add;
ListItem.Caption := Name;
ListItem.Data := Items[ I ];
if not Dir then
begin
ListItem.Selected := not ModifiedOnly and SelectModified and NewVer;
ListItem.SubItems.Add(FileType(Name, Ind));
ListItem.ImageIndex := Ind;
ListItem.SubItems.Add(IntToStr(FileSize));
ListItem.SubItems.Add(FormatDateTime('dd.mm.yyyy hh:nn', Modified));
end else
begin
ListItem.SubItems.Add('<DIR>');
ListItem.ImageIndex := 7;
ListItem.SubItems.Add('');
end;
end;
finally
EndUpdate;
end;
end;
end;
function TCustomFTPLoader.FindItem(AMemItems : PMemItems; ItemName : string) : PMemItem;
var I : integer;
LevName : string;
begin
I := Pos('\', ItemName);
if I = 0 then
begin
LevName := ItemName;
ItemName := '';
end else
begin
LevName := Copy(ItemName, 1, I - 1);
ItemName := Copy(ItemName, I + 1, MaxInt);
end;
Result := nil;
if AMemItems <> nil then with AMemItems^ do
for I := 0 to Items.Count - 1 do with PMemItem(Items[ I ])^ do
begin
if SameText(Name, LevName) then
begin
if ItemName = '' then
Result := PMemItem(Items[ I ])
else
Result := FindItem(PMemItem(Items[ I ])^.DirList, ItemName);
Exit;
end;
end;
end;
procedure TCustomFTPLoader.SetFlatList;
var Indent : integer;
procedure RollOut(AMemItems : PMemItems);
var I, Ind : integer;
ListItem : TListItem;
begin
with AMemItems^ do
for I := 0 to Items.Count - 1 do with PMemItem(Items[ I ])^ do
begin
if ModifiedOnly and not NewVer and not Dir then
Continue;
ListItem := View.Items.Add;
ListItem.Caption := Name;
ListItem.Data := Items[ I ];
ListItem.Indent:= Indent;
if not Dir then
begin
ListItem.Selected := not ModifiedOnly and SelectModified and NewVer;
ListItem.SubItems.Add(FileType(Name, Ind));
ListItem.ImageIndex := Ind;
ListItem.SubItems.Add(IntToStr(FileSize));
ListItem.SubItems.Add(FormatDateTime('dd.mm.yyyy hh:nn', Modified));
end else
begin
ListItem.SubItems.Add('<DIR>');
ListItem.ImageIndex := 7;
ListItem.SubItems.Add('');
Inc(Indent);
RollOut(DirList);
end;
end;
end;
begin
Flat := True;
with View.Items do
begin
BeginUpdate;
try
Clear;
Indent := 0;
RollOut(RootMemItems);
finally
EndUpdate;
end;
end;
end;
procedure TCustomFTPLoader.Disconnect;
begin
if Remote then
FTP.Disconnect;
ClearTree;
end;
procedure TCustomFTPLoader.Connect;
begin
if Remote then with FTP do
begin
Username := 'anonymous';
Password := 'idftp@client.com';
Host := FHost;
try
if Assigned(FOnProgress) then
FOnProgress(0, 'Connecting');
Connect;
except
Disconnect;
raise;
end;
end;
if Assigned(FOnProgress) then
FOnProgress(0, 'Checking files');
GetAll;
if not CheckOnly and Assigned(View) then
ShowView;
end;
procedure TCustomFTPLoader.ParseCustomListFormat(AItem: TIdFTPListItem);
var S : string;
D, T : TDateTime;
iMin, iHour : integer;
begin
S := AItem.Data;
// Log(S);
if Pos('<', S) <> 0 then
AItem.ItemType := ditDirectory
else
begin
AItem.ItemType := ditFile;
AItem.Size := StrToInt(Trim(Copy(S, 31, 8)));
// Log(IntToStr(AItem.Size));
end;
AItem.FileName := Copy(S, 40, MaxInt);
// Log(AItem.FileName);
SetLength(S, 30);
S := UpperCase(S);
D := EncodeDate(2000 + StrToInt(Copy(S, 7, 2)), StrToInt(Copy(S, 1, 2)), StrToInt(Copy(S, 4, 2)));
iHour := StrToInt(Copy(S, 11, 2));
iMin := StrToInt(Copy(S, 14, 2));
if Pos('P', S) <> 0 then
begin
if iHour < 12 then
Inc(iHour, 12);
end;
if Pos('A', S) <> 0 then
begin
if iHour = 12 then
iHour := 0;
end;
T := EncodeTime(iHour, iMin, 0, 0);
AItem.ModifiedDate := D + T;
// Log(DateTimeToStr(AItem.ModifiedDate));
// Log('-----------');
end;
procedure TCustomFTPLoader.CheckListFormat(ASender: TObject; const ALine: String; Var VListFormat: TIdFTPListFormat);
begin
VListFormat := flfCustom;
end;
procedure TCustomFTPLoader.CreateFTPList(ASender: TObject; Var VFTPList: TIdFTPListItems);
begin
VFTPList := TIdFTPListItems.Create;
VFTPList.OnParseCustomListFormat := ParseCustomListFormat;
end;
constructor TCustomFTPLoader.Create(AOwner : TComponent);
begin
inherited Create(Aowner);
FTP := TIdFTP.Create(Self);
FTP.OnCheckListFormat := CheckListFormat;
FTP.OnCreateFTPList := CreateFTPList;
end;
procedure TCustomFTPLoader.ClearTree;
procedure ClrItem(MemItems : PMemItems);
var I : integer;
begin
if MemItems <> nil then with MemItems^ do
begin
for I := 0 to Items.Count - 1 do with PMemItem(Items[ I ])^ do
begin
if Dir then
ClrItem(DirList);
Dispose(PMemItem(Items[ I ]));
end;
Items.Free;
Dispose(MemItems);
end;
end;
begin
ClrItem(RootMemItems);
FRootMemItems := nil;
end;
destructor TCustomFTPLoader.Destroy;
begin
ClearTree;
try
FTP.Free;
except
end;
inherited;
end;
//var II : byte;
function TCustomFTPLoader.NewFile(FileName : string; Modified : TDateTime; Size : integer; Item : PMemItem) : boolean;
var F : TSearchRec;
FName : string;
begin
Result := True;
FName := ExtractFileName(Trim(Filename));
// if SameText('equipment.exe', FName) then
// II := 1;
Item.LocModified := 0;
if FindFirst(FileName, faAnyFile, F) = 0 then
begin
Item.LocModified := ModifiedDate(F);
Result := CompareFileDateTime(Modified, Item.LocModified) > 0;
FindClose(F);
end;
if Result and SameText(Fname, 'Cipher.dll') then
Result := False;
end;
function TCustomFTPLoader.GetFile(var PutName : string; GetName : string) : boolean;
var PutStream : TFileStream;
begin
ForceDirectories(ExtractFileDir(PutName));
if SameText(ExtractFileName(PutName), ExtractFileName(ParamStr(0))) then
begin
FLoadSelf := True;
PutName := ChangeFileExt(PutName, '.ex');
end;
Result := True;
try
if Remote then
begin
PutStream := TFileStream.Create(PutName, fmCreate);
try
FTP.TransferType := ftBinary;
FTP.Get('/' + GetName, PutStream, False);
Sleep(50);
finally
PutStream.Free;
end;
end else
Result := CopyFile(PChar(GetName), PChar(PutName), False);
except
Result := False;
end;
end;
procedure TCustomFTPLoader.LoadFile(Item : PMemItem);
var PutName : string;
begin
with Item^, List^ do
begin
PutName := LocDir + '\' + Name;
Loaded := GetFile(PutName, RemDir + '\' + Name);
if Loaded then
begin
FileSetDate(PutName, DateTimeToFileDate(Modified));
Inc(FLoadedSize, Item^.FileSize);
if Assigned(FOnProgress) and (FTotalSize <> 0) then
FOnProgress(MulDiv(LoadedSize, 100, FTotalSize), Name);
Log(PutName + ', Modified : ' + DateTimeToStr(Modified) + ', LocModified : ' + DateTimeToStr(LocModified));
end else
begin
LastError := GetLastError;
Log(SysErrorMessage(LastError));
Log('From : ' + RemDir + '\' + Name);
Log('Failed : ' + PutName + ', Modified : ' + DateTimeToStr(Modified) + ', LocModified : ' + DateTimeToStr(LocModified));
LoadErr := True;
end;
end;
end;
function TCustomFTPLoader.GetDir(AMemItem : PMemItem) : PMemItems;
var F : TSearchRec;
tItem : PMemItem;
Accepted : boolean;
begin
if Remote then
Result := RemoteGetDir(AMemItem)
else
begin
if (AMemItem = nil) and not DirectoryExists(FHost) then
raise Exception.Create('Directory ' + FHost + ' not found');
New(Result);
with Result^ do
begin
if AMemItem = nil then
begin
LocDir := LocalRoot;
RemDir := FHost;
UpItems := nil;
end else with AMemItem^ do
begin
RemDir := List.RemDir + '\' + Name;
LocDir := List.LocDir + '\' + Name;;
UpItems := List;
end;
Items := TList.Create;
if FindFirst(RemDir + '\*.*', faAnyFile, F) = 0 then
try
repeat
Accepted := True;
if F.Attr and faDirectory <> 0 then
begin
if F.Name[ 1 ] = '.' then
Accepted := False
else
DoAfterGetItem(F.Name, True, Accepted, Result);
end else
DoAfterGetItem(F.Name, False, Accepted, Result);
if Accepted then
begin
New(tItem);
Result^.Items.Add(tItem);
with tItem^ do
begin
List := Result;
Name := F.Name;
Modified := ModifiedDate(F);
Dir := F.Attr and faDirectory <> 0;
NewVer := not Dir and NewFile(Result.LocDir + '\' + F.Name, Modified, F.Size, tItem);
DirList:= nil;
Selected := False;
Loaded := False;
end;
tItem.FileSize := F.Size;
end;
until FindNext(F) <> 0;
finally
FindClose(F);
end;
end;
end;
Result.Items.Sort(SortCompare);
end;
procedure TCustomFTPLoader.DoAfterGetItem(FileName : string; Dir : boolean; var Accept : boolean; Item : PMemItems);
begin
if Assigned(FAfterGetItem) then
begin
AfterGetItem(Copy(Item.LocDir, Length(LocalRoot) + 2, MAXINT) + '\' + FileName, False, Accept);
end;
end;
function TCustomFTPLoader.RemoteGetDir(AMemItem : PMemItem) : PMemItems;
var I : integer;
tItem : PMemItem;
DirListing : TIdFTPListItems;
Accepted : boolean;
begin
New(Result);
with Result^, FTP do
begin
Sleep(50);
TransferType := ftASCII;
if AMemItem = nil then
begin
LocDir := LocalRoot;
ChangeDir('\' + SysRegIni.SourceDir);
end else with AMemItem^ do
begin
RemDir := List.RemDir + '\' + Name;
LocDir := List.LocDir + '\' + Name;;
ChangeDir('\' + RemDir);
end;
Sleep(50);
List(nil);
if AMemItem = nil then
begin
Sleep(50);
RemDir := RetrieveCurrentDir;
UpItems := nil;
end else
UpItems := AMemItem.List;
Items := TList.Create;
DirListing := DirectoryListing;
end;
for I := 0 to DirListing.Count - 1 do with DirListing[ I ] do
begin
FileName := Trim(FileName);
Accepted := True;
if ItemType = ditFile then
DoAfterGetItem(FileName, False, Accepted, Result)
else if (ItemType <> ditDirectory) or (FileName[ 1 ] = '.') then
Accepted := False
else
DoAfterGetItem(FileName, True, Accepted, Result);
if not Accepted then
Continue;
New(tItem);
Result^.Items.Add(tItem);
with tItem^ do
begin
List := Result;
Name := Trim(FileName);
Dir := ItemType <> ditFile;
NewVer := not Dir and NewFile(Result.LocDir + '\' + FileName, ModifiedDate, Size, tItem);
DirList := nil;
Modified := ModifiedDate;
Selected := False;
Loaded := False;
end;
tItem.FileSize := Size;
end;
end;
function TCustomFTPLoader.NeedUpdate : boolean;
procedure Check(AMemItems : PMemItems);
var I : integer;
Accept : boolean;
begin
if AMemItems <> nil then
begin
for I := 0 to AMemItems.Items.Count - 1 do with PMemItem(AMemItems.Items[ I ])^ do
begin
Accept := True;
if Assigned(FBeforeLoadFile) then
FBeforeLoadFile(List.LocDir + '\' + Name, Dir, Accept);
if not Accept then
Continue;
if Dir then
Check(DirList)
else if NewVer then
begin
if CheckOnly then
Log('new ' + List.LocDir + '\' + Name + ', Modified : ' + DateTimeToStr(Modified) + ', LocModified : ' + DateTimeToStr(LocModified));
Abort;
end;
end;
end;
end;
begin
Result := False;
try
Check(FRootMemItems);
except
Result := True;
end;
end;
procedure TCustomFTPLoader.GetAll;
procedure RollOut(AMemItems : PMemItems);
var I : integer;
begin
with AMemItems^ do
begin
if Remote and Assigned(OnProgress) then
OnProgress(0, LocDir);
for I := 0 to Items.Count - 1 do with PMemItem(Items[ I ])^ do
if Dir then
begin
DirList := GetDir(Items[ I ]);
RollOut(DirList);
end;
end;
end;
begin
ClearTree;
FRootMemItems := GetDir(nil);
if FRootMemItems <> nil then
RollOut(FRootMemItems);
end;
procedure TCustomFTPLoader.Load(LoadMode: TLoadModes);
procedure CountSize(MemItems : PMemItems; DirSelected : boolean = False);
var I : integer;
Accept : boolean;
begin
if MemItems <> nil then with MemItems^ do
begin
for I := 0 to Items.Count - 1 do with PMemItem(Items[ I ])^ do
begin
Accept := True;
if Assigned(FBeforeLoadFile) then
FBeforeLoadFile(List.LocDir + '\' + Name, Dir, Accept);
if not Accept then
else if Dir then
begin
if not Assigned(DirList) then
DirList := GetDir(Items[ I ]);
CountSize(DirList, Selected);
end else if ((lmAll in LoadMode) or (lmSelected in LoadMode) and (DirSelected or Selected)
or (lmModified in LoadMode) and NewVer) and not Loaded then
Inc(FTotalSize, FileSize);
end;
end;
end;
procedure DoLoad(MemItems : PMemItems; DirSelected : boolean = False);
var I : integer;
Accept : boolean;
begin
if MemItems <> nil then with MemItems^ do
begin
for I := 0 to Items.Count - 1 do with PMemItem(Items[ I ])^ do
begin
Accept := True;
if Assigned(FBeforeLoadFile) then
FBeforeLoadFile(List.LocDir + '\' + Name, Dir, Accept);
if not Accept then
else if Dir then
begin
if not Assigned(DirList) then
DirList := GetDir(Items[ I ]);
DoLoad(DirList, Selected);
end else if ((lmAll in LoadMode) or (lmSelected in LoadMode) and (DirSelected or Selected)
or (lmModified in LoadMode) and NewVer) and not Loaded then
LoadFile(Items[ I ]);
end;
end;
end;
begin
if RootMemItems = nil then
Exit;
if lmAll in LoadMode then
Log('Load all');
if lmSelected in LoadMode then
Log('Load Selected');
if lmModified in LoadMode then
Log('Load Modified');
FLoadedSize := 0;
FTotalSize := 0;
CountSize(RootMemItems);
Log(IntToStr(FTotalSize) + '-FTotalSize');
LoadErr := False;
try
DoLoad(RootMemItems);
while LoadErr do
begin
if MessageDlg(SysErrorMessage(LastError) + ', Close all applications and hit OK', mtConfirmation, [ mbOK, mbCancel ], 0) = mrCancel then
Abort;
LoadErr := False;
DoLoad(RootMemItems);
end;
except
Disconnect;
raise;
end;
if Assigned(FAfterLoad) then
FAfterLoad(Self);
end;
procedure TCustomFTPLoader.DblClick(Sender : TObject);
begin
with View do
if Selected <> nil then with Selected do
begin
if Caption = '..' then
SetList(PMemItems(Data)^.UpItems)
else if SubItems[ 0 ] = '<DIR>' then with PMemItem(Data)^ do
begin
if not Flat then
SetList(DirList);
end else
begin
FLoadedSize:= 0;
FTotalSize := 0;
LoadFile(Data);
if not PMemItem(Data)^.Loaded then
ShowMessage(SysErrorMessage(LastError) + ', Close all applications and repeat Loading');
LoadErr := False;
if Assigned(FAfterLoad) then
FAfterLoad(Self);
end;
end;
end;
procedure TCustomFTPLoader.Click(Sender : TObject);
var I : integer;
begin
with View do
for I := 0 to Items.Count - 1 do with Items[ I ] do
if Caption = '..' then
PMemItem(Data)^.Selected := Selected;
end;
procedure TCustomFTPLoader.SelectNew;
var I : integer;
Item : PMemItem;
begin
with View do
begin
Items.BeginUpdate;
try
for I := 0 to Items.Count - 1 do
begin
if Items[ I ].Caption = '..' then
Continue;
Item := PMemItem(Items[ I ].Data);
if Item.NewVer then
Items[ I ].Selected := SelectModified;
end;
finally
Items.EndUpdate;
end;
end;
end;
procedure TCustomFTPLoader.SetAfterLoad(const Value: TNotifyEvent);
begin
FAfterLoad := Value;
end;
procedure TCustomFTPLoader.SetAfterGetItem(const Value: TAfterGetItem);
begin
FAfterGetItem := Value;
end;
procedure TCustomFTPLoader.SetOnGetFileType(const Value: TOnGetFileType);
begin
FOnGetFileType := Value;
end;
procedure TCustomFTPLoader.SetBeforeLoadFile(const Value: TBeforeLoadFile);
begin
FBeforeLoadFile := Value;
end;
procedure TCustomFTPLoader.SetHost(const Value: string);
begin
if FHost <> Value then
begin
CheckInactive;
FHost := Value;
end;
end;
procedure TCustomFTPLoader.SetLocalRoot(const Value: string);
begin
if FLocalRoot <> Value then
begin
CheckInactive;
FLocalRoot := Value;
end;
end;
procedure TCustomFTPLoader.SetOnProgress(const Value: TOnProgress);
begin
FOnProgress := Value;
end;
procedure TCustomFTPLoader.ShowView;
begin
if RootMemItems = nil then
Exit;
if FFlat then
SetFlatList
else
SetList;
end;
procedure TCustomFTPLoader.SetFlat(const Value: boolean);
begin
if FFlat <> Value then
begin
FFlat := Value;
ShowView;
end;
end;
procedure TCustomFTPLoader.SetSelectModified(const Value: boolean);
begin
if FSelectModified <> Value then
begin
FSelectModified:= Value;
if Value then
FModifiedOnly := False;
SelectNew;
end;
end;
procedure TCustomFTPLoader.SetModifiedOnly(const Value: boolean);
begin
if FModifiedOnly <> Value then
begin
FModifiedOnly := Value;
if Value then
FSelectModified := False;
ShowView;
end;
end;
procedure TCustomFTPLoader.SetCheckOnly(const Value: boolean);
begin
if FCheckOnly <> Value then
begin
CheckInactive;
FCheckOnly := Value;
end;
end;
procedure TCustomFTPLoader.SetView(Value : TListView);
begin
if FView <> nil then
raise Exception.Create('View already assigned');
FView := Value;
FView.OnClick := Click;
FView.OnDblClick := DblClick;
end;
procedure TCustomFTPLoader.SetRemote(const Value: boolean);
begin
if FRemote <> Value then
begin
CheckInactive;
FRemote := Value;
end;
end;
procedure Register;
begin
RegisterComponents('TSES', [TFTPLoader]);
end;
end.
|
unit ncPrinterConstsAndTypes;
interface
uses windows, sysutils, classes;
type
PPrinterInfo8A = ^TPrinterInfo8A;
PPrinterInfo8W = ^TPrinterInfo8W;
PPrinterInfo8 = PPrinterInfo8A;
{$EXTERNALSYM _PRINTER_INFO_8A}
_PRINTER_INFO_8A = record
pDevMode: PDeviceModeA;
end;
{$EXTERNALSYM _PRINTER_INFO_8W}
_PRINTER_INFO_8W = record
pDevMode: PDeviceModeW;
end;
{$EXTERNALSYM _PRINTER_INFO_8}
_PRINTER_INFO_8 = _PRINTER_INFO_8A;
TPrinterInfo8A = _PRINTER_INFO_8A;
TPrinterInfo8W = _PRINTER_INFO_8W;
TPrinterInfo8 = TPrinterInfo8A;
{$EXTERNALSYM PRINTER_INFO_8A}
PRINTER_INFO_8A = _PRINTER_INFO_8A;
{$EXTERNALSYM PRINTER_INFO_8W}
PRINTER_INFO_8W = _PRINTER_INFO_8W;
{$EXTERNALSYM PRINTER_INFO_8}
PRINTER_INFO_8 = PRINTER_INFO_8A;
TPaper = class(TObject)
private
FName: string;
FShortName: string;
FAdobeName: string;
FSize: TPoint;
FDMPaper: Integer;
function GetHeight: Integer;
function GetWidth: Integer;
procedure SetHeight(Value: Integer);
procedure SetWidth(Value: Integer);
public
constructor Create(const AName, AShortName, AAdobeName: string;
AWidth, AHeight: Integer; ADMPaper: Integer);
property DMPaper: Integer read FDMPaper;
property Height: Integer read GetHeight write SetHeight;
property Name: string read FName;
property ShortName: string read FShortName;
property AdobeName: string read FAdobeName;
property Size: TPoint read FSize write FSize;
property Width: Integer read GetWidth write SetWidth;
end;
TPapers = class(TObject)
private
FPapers: TList;
function GetCount: Integer;
function GetPaper(Index: Integer): TPaper;
protected
procedure AddPapers; virtual;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Clear;
procedure Delete(AIndex: Integer);
function getByDMPaper(ADMPaper: Integer): TPaper;
function FindByDMPaper(ADMPaper: Integer): Integer;
function FindByName(const AName: string): Integer;
function FindByShortName(const AShortName: string): Integer;
function FindByAdobeName(const AAdobeName: string): Integer;
function FindBySize(AWidth, AHeight: Integer): Integer;
procedure Refresh;
property Count: Integer read GetCount;
property Papers[Index: Integer]: TPaper read GetPaper; default;
end;
function getPaperConstsAsText(aPaper : integer):string;
function getSourceConsts(aPaper : integer):string;
function getSourceNames(aPaper : integer):string;
var
FPaperlist: TPapers;
Const
kDM_Max_Paper = 118;
DMPAPER_LETTER = 1;
DMPAPER_LETTERSMALL = 2;
DMPAPER_TABLOID = 3;
DMPAPER_LEDGER = 4;
DMPAPER_LEGAL = 5;
DMPAPER_STATEMENT = 6;
DMPAPER_EXECUTIVE = 7;
DMPAPER_A3 = 8;
DMPAPER_A4 = 9;
DMPAPER_A4SMALL = 10;
DMPAPER_A5 = 11;
DMPAPER_B4 = 12;
DMPAPER_B5 = 13;
DMPAPER_FOLIO = 14;
DMPAPER_QUARTO = 15;
DMPAPER_10X14 = 16;
DMPAPER_11X17 = 17;
DMPAPER_NOTE = 18;
DMPAPER_ENV_9 = 19;
DMPAPER_ENV_10 = 20;
DMPAPER_ENV_11 = 21;
DMPAPER_ENV_12 = 22;
DMPAPER_ENV_14 = 23;
DMPAPER_CSHEET = 24;
DMPAPER_DSHEET = 25;
DMPAPER_ESHEET = 26;
DMPAPER_ENV_DL = 27;
DMPAPER_ENV_C5 = 28;
DMPAPER_ENV_C3 = 29;
DMPAPER_ENV_C4 = 30;
DMPAPER_ENV_C6 = 31;
DMPAPER_ENV_C65 = 32;
DMPAPER_ENV_B4 = 33;
DMPAPER_ENV_B5 = 34;
DMPAPER_ENV_B6 = 35;
DMPAPER_ENV_ITALY = 36;
DMPAPER_ENV_MONARCH = 37;
DMPAPER_ENV_PERSONAL = 38;
DMPAPER_FANFOLD_US = 39;
DMPAPER_FANFOLD_STD_GERMAN = 40;
DMPAPER_FANFOLD_LGL_GERMAN = 41;
DMPAPER_ISO_B4 = 42;
DMPAPER_JAPANESE_POSTCARD = 43;
DMPAPER_9X11 = 44;
DMPAPER_10X11 = 45;
DMPAPER_15X11 = 46;
DMPAPER_ENV_INVITE = 47;
DMPAPER_RESERVED_48 = 48;
DMPAPER_RESERVED_49 = 49;
DMPAPER_LETTER_EXTRA = 50;
DMPAPER_LEGAL_EXTRA = 51;
DMPAPER_TABLOID_EXTRA = 52;
DMPAPER_A4_EXTRA = 53;
DMPAPER_LETTER_TRANSVERSE = 54;
DMPAPER_A4_TRANSVERSE = 55;
DMPAPER_LETTER_EXTRA_TRANSVERSE = 56;
DMPAPER_A_PLUS = 57;
DMPAPER_B_PLUS = 58;
DMPAPER_LETTER_PLUS = 59;
DMPAPER_A4_PLUS = 60;
DMPAPER_A5_TRANSVERSE = 61;
DMPAPER_B5_TRANSVERSE = 62;
DMPAPER_A3_EXTRA = 63;
DMPAPER_A5_EXTRA = 64;
DMPAPER_B5_EXTRA = 65;
DMPAPER_A2 = 66;
DMPAPER_A3_TRANSVERSE = 67;
DMPAPER_A3_EXTRA_TRANSVERSE = 68;
DMPAPER_DBL_JAPANESE_POSTCARD = 69;
DMPAPER_A6 = 70;
DMPAPER_JENV_KAKU2 = 71;
DMPAPER_JENV_KAKU3 = 72;
DMPAPER_JENV_CHOU3 = 73;
DMPAPER_JENV_CHOU4 = 74;
DMPAPER_LETTER_ROTATED = 75;
DMPAPER_A3_ROTATED = 76;
DMPAPER_A4_ROTATED = 77;
DMPAPER_A5_ROTATED = 78;
DMPAPER_B4_JIS_ROTATED = 79;
DMPAPER_B5_JIS_ROTATED = 80;
DMPAPER_JAPANESE_POSTCARD_ROTATED = 81;
DMPAPER_DBL_JAPANESE_POSTCARD_ROTATED = 82;
DMPAPER_A6_ROTATED = 83;
DMPAPER_JENV_KAKU2_ROTATED = 84;
DMPAPER_JENV_KAKU3_ROTATED = 85;
DMPAPER_JENV_CHOU3_ROTATED = 86;
DMPAPER_JENV_CHOU4_ROTATED = 87;
DMPAPER_B6_JIS = 88;
DMPAPER_B6_JIS_ROTATED = 89;
DMPAPER_12X11 = 90;
DMPAPER_JENV_YOU4 = 91;
DMPAPER_JENV_YOU4_ROTATED = 92;
DMPAPER_P16K = 93;
DMPAPER_P32K = 94;
DMPAPER_P32KBIG = 95;
DMPAPER_PENV_1 = 96;
DMPAPER_PENV_2 = 97;
DMPAPER_PENV_3 = 98;
DMPAPER_PENV_4 = 99;
DMPAPER_PENV_5 = 100;
DMPAPER_PENV_6 = 101;
DMPAPER_PENV_7 = 102;
DMPAPER_PENV_8 = 103;
DMPAPER_PENV_9 = 104;
DMPAPER_PENV_10 = 105;
DMPAPER_P16K_ROTATED = 106;
DMPAPER_P32K_ROTATED = 107;
DMPAPER_P32KBIG_ROTATED = 108;
DMPAPER_PENV_1_ROTATED = 109;
DMPAPER_PENV_2_ROTATED = 110;
DMPAPER_PENV_3_ROTATED = 111;
DMPAPER_PENV_4_ROTATED = 112;
DMPAPER_PENV_5_ROTATED = 113;
DMPAPER_PENV_6_ROTATED = 114;
DMPAPER_PENV_7_ROTATED = 115;
DMPAPER_PENV_8_ROTATED = 116;
DMPAPER_PENV_9_ROTATED = 117;
DMPAPER_PENV_10_ROTATED = 118;
DMBIN_AUTO = 7;
DMBIN_CASSETTE = 14;
DMBIN_ENVELOPE = 5;
DMBIN_ENVMANUAL = 6;
DMBIN_FORMSOURCE = 15;
DMBIN_LARGECAPACITY = 11;
DMBIN_LARGEFMT = 10;
DMBIN_LOWER = 2;
DMBIN_MANUAL = 4;
DMBIN_MIDDLE = 3;
DMBIN_ONLYONE = 1;
DMBIN_SMALLFMT = 9;
DMBIN_TRACTOR = 8;
DMBIN_UPPER = 1;
DMBIN_USER = 256;
DMRES_DRAFT = -1;
DMRES_HIGH = -4;
DMRES_LOW = -2;
DMRES_MEDIUM = -3;
DMCOLOR_COLOR = 2;
DMCOLOR_MONOCHROME = 1;
DMDUP_HORIZONTAL = 3;
DMDUP_SIMPLEX = 1;
DMDUP_VERTICAL = 2;
DMTT_BITMAP = 1;
DMTT_DOWNLOAD = 2;
DMTT_DOWNLOAD_OUTLINE = 4;
DMTT_SUBDEV = 3;
DMCOLLATE_FALSE = 0;
DMCOLLATE_TRUE = 1;
DM_GRAYSCALE = 1;// This flag is no longer valid
DM_INTERLACED = 2; // This flag is no longer valid
DMICMMETHOD_DEVICE = 4;
DMICMMETHOD_DRIVER = 3;
DMICMMETHOD_NONE = 1;
DMICMMETHOD_SYSTEM = 2;
DMICMMETHOD_USER = 256;
DMICM_ABS_COLORIMETRIC = 4;
DMICM_COLORIMETRIC = 3;
DMICM_CONTRAST = 2;
DMICM_SATURATE = 1;
DMICM_USER = 256;
DMMEDIA_GLOSSY = 3;
DMMEDIA_STANDARD = 1;
DMMEDIA_TRANSPARENCY = 2;
DMMEDIA_USER = 256;
DMDITHER_COARSE = 2;
DMDITHER_ERRORDIFFUSION = 5;
DMDITHER_FINE = 3;
DMDITHER_GRAYSCALE = 10;
DMDITHER_LINEART = 4;
DMDITHER_NONE = 1;
DMDITHER_RESERVED6 = 6;
DMDITHER_RESERVED7 = 7;
DMDITHER_RESERVED8 = 8;
DMDITHER_RESERVED9 = 9;
DMDITHER_USER = 256;
var
_SourceNames : array [1..256] of string;
_SourceConsts : array [1..256] of string;
Const
_PaperConsts : array [1..kDM_Max_Paper] of string = (
'DMPAPER_LETTER',
'DMPAPER_LETTERSMALL',
'DMPAPER_TABLOID',
'DMPAPER_LEDGER',
'DMPAPER_LEGAL',
'DMPAPER_STATEMENT',
'DMPAPER_EXECUTIVE',
'DMPAPER_A3',
'DMPAPER_A4',
'DMPAPER_A4SMALL',
'DMPAPER_A5',
'DMPAPER_B4',
'DMPAPER_B5',
'DMPAPER_FOLIO',
'DMPAPER_QUARTO',
'DMPAPER_10X14',
'DMPAPER_11X17',
'DMPAPER_NOTE',
'DMPAPER_ENV_9',
'DMPAPER_ENV_10',
'DMPAPER_ENV_11',
'DMPAPER_ENV_12',
'DMPAPER_ENV_14',
'DMPAPER_CSHEET',
'DMPAPER_DSHEET',
'DMPAPER_ESHEET',
'DMPAPER_ENV_DL',
'DMPAPER_ENV_C5',
'DMPAPER_ENV_C3',
'DMPAPER_ENV_C4',
'DMPAPER_ENV_C6',
'DMPAPER_ENV_C65',
'DMPAPER_ENV_B4',
'DMPAPER_ENV_B5',
'DMPAPER_ENV_B6',
'DMPAPER_ENV_ITALY',
'DMPAPER_ENV_MONARCH',
'DMPAPER_ENV_PERSONAL',
'DMPAPER_FANFOLD_US',
'DMPAPER_FANFOLD_STD_GERMAN',
'DMPAPER_FANFOLD_LGL_GERMAN',
'DMPAPER_ISO_B4',
'DMPAPER_JAPANESE_POSTCARD',
'DMPAPER_9X11',
'DMPAPER_10X11',
'DMPAPER_15X11',
'DMPAPER_ENV_INVITE',
'DMPAPER_RESERVED_48',
'DMPAPER_RESERVED_49',
'DMPAPER_LETTER_EXTRA',
'DMPAPER_LEGAL_EXTRA',
'DMPAPER_TABLOID_EXTRA',
'DMPAPER_A4_EXTRA',
'DMPAPER_LETTER_TRANSVERSE',
'DMPAPER_A4_TRANSVERSE',
'DMPAPER_LETTER_EXTRA_TRANSVERSE',
'DMPAPER_A_PLUS',
'DMPAPER_B_PLUS',
'DMPAPER_LETTER_PLUS',
'DMPAPER_A4_PLUS',
'DMPAPER_A5_TRANSVERSE',
'DMPAPER_B5_TRANSVERSE',
'DMPAPER_A3_EXTRA',
'DMPAPER_A5_EXTRA',
'DMPAPER_B5_EXTRA',
'DMPAPER_A2',
'DMPAPER_A3_TRANSVERSE',
'DMPAPER_A3_EXTRA_TRANSVERSE',
'DMPAPER_DBL_JAPANESE_POSTCARD',
'DMPAPER_A6',
'DMPAPER_JENV_KAKU2',
'DMPAPER_JENV_KAKU3',
'DMPAPER_JENV_CHOU3',
'DMPAPER_JENV_CHOU4',
'DMPAPER_LETTER_ROTATED',
'DMPAPER_A3_ROTATED',
'DMPAPER_A4_ROTATED',
'DMPAPER_A5_ROTATED',
'DMPAPER_B4_JIS_ROTATED',
'DMPAPER_B5_JIS_ROTATED',
'DMPAPER_JAPANESE_POSTCARD_ROTATED',
'DMPAPER_DBL_JAPANESE_POSTCARD_ROTATED',
'DMPAPER_A6_ROTATED',
'DMPAPER_JENV_KAKU2_ROTATED',
'DMPAPER_JENV_KAKU3_ROTATED',
'DMPAPER_JENV_CHOU3_ROTATED',
'DMPAPER_JENV_CHOU4_ROTATED',
'DMPAPER_B6_JIS',
'DMPAPER_B6_JIS_ROTATED',
'DMPAPER_12X11',
'DMPAPER_JENV_YOU4',
'DMPAPER_JENV_YOU4_ROTATED',
'DMPAPER_P16K',
'DMPAPER_P32K',
'DMPAPER_P32KBIG',
'DMPAPER_PENV_1',
'DMPAPER_PENV_2',
'DMPAPER_PENV_3',
'DMPAPER_PENV_4',
'DMPAPER_PENV_5',
'DMPAPER_PENV_6',
'DMPAPER_PENV_7',
'DMPAPER_PENV_8',
'DMPAPER_PENV_9',
'DMPAPER_PENV_10',
'DMPAPER_P16K_ROTATED',
'DMPAPER_P32K_ROTATED',
'DMPAPER_P32KBIG_ROTATED',
'DMPAPER_PENV_1_ROTATED',
'DMPAPER_PENV_2_ROTATED',
'DMPAPER_PENV_3_ROTATED',
'DMPAPER_PENV_4_ROTATED',
'DMPAPER_PENV_5_ROTATED',
'DMPAPER_PENV_6_ROTATED',
'DMPAPER_PENV_7_ROTATED',
'DMPAPER_PENV_8_ROTATED',
'DMPAPER_PENV_9_ROTATED',
'DMPAPER_PENV_10_ROTATED'
);
implementation
function getPaperConstsAsText(aPaper : integer):string;
begin
if (aPaper>0) and (aPaper<=kDM_Max_Paper) then
Result := _PaperConsts[aPaper]
else
Result := 'DMPAPER_USER';
end;
function getSourceConsts(aPaper : integer):string;
begin
if (aPaper>0) and (aPaper<=kDM_Max_Paper) then
Result := _SourceConsts[aPaper]
else
Result := '';
end;
function getSourceNames(aPaper : integer):string;
begin
if (aPaper>0) then
Result := _SourceNames[aPaper]
else
Result := '';
end;
function InchToLoMetric(Value: Extended): Integer;
begin
Result := Round(Value * 254);
end;
{ TPaper }
constructor TPaper.Create(const AName, AShortName, AAdobeName: string; AWidth, AHeight,
ADMPaper: Integer);
begin
inherited Create;
FName := AName;
FShortName := AShortName;
FAdobeName := AAdobeName;
FSize.X := AWidth;
FSize.Y := AHeight;
FDMPaper := ADMPaper;
end;
function TPaper.GetHeight: Integer;
begin
Result := FSize.Y;
end;
function TPaper.GetWidth: Integer;
begin
Result := FSize.X;
end;
procedure TPaper.SetHeight(Value: Integer);
begin
FSize.Y := Value;
end;
procedure TPaper.SetWidth(Value: Integer);
begin
FSize.X := Value;
end;
{ TPapers }
constructor TPapers.Create;
begin
inherited;
FPapers := TList.Create;
Refresh;
end;
destructor TPapers.Destroy;
begin
Clear;
FreeAndNil(FPapers);
inherited;
end;
procedure TPapers.Clear;
begin
while Count > 0 do Delete(Count - 1);
end;
procedure TPapers.Delete(AIndex: Integer);
begin
TObject(FPapers[AIndex]).Free;
FPapers.Delete(AIndex);
end;
function TPapers.FindByDMPaper(ADMPaper: Integer): Integer;
begin
for Result := 0 to Count - 1 do
if Papers[Result].DMPaper = ADMPaper then Exit;
Result := -1;
end;
function TPapers.getByDMPaper(ADMPaper: Integer): TPaper;
var
id : integer;
begin
result := nil;
id := FindByDMPaper(ADMPaper);
if id >-1 then
result := getPaper(id);
end;
function TPapers.FindByName(const AName: string): Integer;
begin
for Result := 0 to Count - 1 do
if SameText(Papers[Result].Name, AName) then
Exit;
Result := -1;
end;
function TPapers.FindByShortName(const AShortName: string): Integer;
begin
for Result := 0 to Count - 1 do
if SameText(Papers[Result].ShortName, AShortName) then
Exit;
Result := -1;
end;
function TPapers.FindByAdobeName(const AAdobeName: string): Integer;
begin
for Result := 0 to Count - 1 do
if SameText(Papers[Result].AdobeName, AAdobeName) then
Exit;
Result := -1;
end;
function TPapers.FindBySize(AWidth, AHeight: Integer): Integer;
begin
for Result := 0 to Count - 1 do
if (Abs(Papers[Result].Width - AWidth) < 2) and (Abs(Papers[Result].Height - AHeight) < 2) then
Exit;
Result := -1;
end;
procedure TPapers.Refresh;
begin
Clear;
AddPapers;
end;
procedure TPapers.AddPapers;
procedure Add(const AName, AShortName: string; AWidth, AHeight: Integer; DMPaper: Integer);
begin
FPapers.Add(TPaper.Create(AName, AShortName, '', AWidth, AHeight, DMPaper));
end;
procedure AddAdobe(const AName: string; AWidth, AHeight: double;const DMPaper: Integer=-1);
var
aPaper : TPaper;
begin
if DMPaper>-1 then begin
aPaper := getByDMPaper(DMPaper);
if aPaper<>nil then
aPaper.FAdobeName := AName;
end else
aPaper := TPaper.Create(AName, AName, AName, trunc(AWidth), trunc(AHeight), DMPaper)
end;
begin
Add('Letter 8 1/2 x 11 in', 'Letter', InchToLoMetric(8.5), InchToLoMetric(11), DMPAPER_LETTER);
Add('Letter Small 8 1/2 x 11 in ', 'Letter Small', InchToLoMetric(8.5), InchToLoMetric(11), DMPAPER_LETTERSMALL);
Add('Tabloid 11 x 17 in', 'Tabloid', InchToLoMetric(11), InchToLoMetric(17), DMPAPER_TABLOID);
Add('Ledger 17 x 11 in', 'Ledger', InchToLoMetric(17), InchToLoMetric(11), DMPAPER_LEDGER);
Add('Legal 8 1/2 x 14 in', 'Legal', InchToLoMetric(8.5), InchToLoMetric(14), DMPAPER_LEGAL);
Add('Statement 5 1/2 x 8 1/2 in', 'Statement', InchToLoMetric(5.5), InchToLoMetric(8.5), DMPAPER_STATEMENT);
Add('Executive 7 1/4 x 10 1/2 in', 'Executive', InchToLoMetric(7.25), InchToLoMetric(10.5), DMPAPER_EXECUTIVE);
Add('A3 297 x 420 mm', 'A3', 2970, 4200, DMPAPER_A3);
Add('A4 210 x 297 mm', 'A4', 2100, 2970, DMPAPER_A4);
Add('A4 Small 210 x 297 mm', 'A4 Small', 2100, 2970, DMPAPER_A4SMALL);
Add('A5 148 x 210 mm', 'A5', 1480, 2100, DMPAPER_A5);
Add('B4 (JIS) 250 x 354', 'B4 (JIS)', 2500, 3540, DMPAPER_B4);
Add('B5 (JIS) 182 x 257 mm', 'B5 (JIS)', 1820, 2570, DMPAPER_B5);
Add('Folio 8 1/2 x 13 in', 'Folio', InchToLoMetric(8.5), InchToLoMetric(13), DMPAPER_FOLIO);
Add('Quarto 215 x 275 mm', 'Quarto', 2150, 2750, DMPAPER_QUARTO);
Add('10x14 in', '10x14 in', InchToLoMetric(10), InchToLoMetric(14), DMPAPER_10X14);
Add('11x17 in', '11x17 in', InchToLoMetric(11), InchToLoMetric(17), DMPAPER_11X17);
Add('Note 8 1/2 x 11 in', 'Note', InchToLoMetric(8.5), InchToLoMetric(11), DMPAPER_NOTE);
Add('Envelope #9 3 7/8 x 8 7/8', 'Envelope #9', InchToLoMetric(3 + 7 / 8), InchToLoMetric(8 + 7 / 8), DMPAPER_ENV_9);
Add('Envelope #10 4 1/8 x 9 1/2', 'Envelope #10', InchToLoMetric(4 + 1 / 8), InchToLoMetric(9.5), DMPAPER_ENV_10);
Add('Envelope #11 4 1/2 x 10 3/8', 'Envelope #11', InchToLoMetric(4.5), InchToLoMetric(10 + 3 / 8), DMPAPER_ENV_11);
Add('Envelope #12 4 3/4 x 11', 'Envelope #12', InchToLoMetric(4 + 3 / 4), InchToLoMetric(11), DMPAPER_ENV_12);
Add('Envelope #14 5 x 11 1/2', 'Envelope #14', InchToLoMetric(5), InchToLoMetric(11.5), DMPAPER_ENV_14);
Add('C sheet 17 x 22 in', 'C sheet', InchToLoMetric(17), InchToLoMetric(22), DMPAPER_CSHEET);
Add('D sheet 22 x 34 in', 'D sheet', InchToLoMetric(22), InchToLoMetric(34), DMPAPER_DSHEET);
Add('E sheet 34 x 44 in', 'E sheet', InchToLoMetric(34), InchToLoMetric(44), DMPAPER_ESHEET);
Add('Envelope DL 110 x 220mm', 'Envelope DL', 1100, 2200, DMPAPER_ENV_DL);
Add('Envelope C5 162 x 229 mm', 'Envelope C5', 1620, 2290, DMPAPER_ENV_C5);
Add('Envelope C3 324 x 458 mm', 'Envelope C3', 3240, 4580, DMPAPER_ENV_C3);
Add('Envelope C4 229 x 324 mm', 'Envelope C4', 2290, 3240, DMPAPER_ENV_C4);
Add('Envelope C6 114 x 162 mm', 'Envelope C6', 1140, 1620, DMPAPER_ENV_C6);
Add('Envelope C65 114 x 229 mm', 'Envelope 65', 1140, 2290, DMPAPER_ENV_C65);
Add('Envelope B4 250 x 353 mm', 'Envelope B4', 2500, 3530, DMPAPER_ENV_B4);
Add('Envelope B5 176 x 250 mm', 'Envelope B5', 1760, 2500, DMPAPER_ENV_B5);
Add('Envelope B6 176 x 125 mm', 'Envelope B6', 1760, 1250, DMPAPER_ENV_B6);
Add('Envelope 110 x 230 mm', 'Envelope 110', 1100, 2300, DMPAPER_ENV_ITALY);
Add('Envelope Monarch 3 7/8 x 7 1/2 in', 'Envelope Monarch', InchToLoMetric(3 + 7 / 8), InchToLoMetric(7.5), DMPAPER_ENV_MONARCH);
Add('6 3/4 Envelope 3 5/8 x 6 1/2 in', '6 3/4 Envelope', InchToLoMetric(3 + 5 / 8), InchToLoMetric(6.5), DMPAPER_ENV_PERSONAL);
Add('US Std Fanfold 14 7/8 x 11 in', 'US Std Fanfold', InchToLoMetric(14 + 7 / 8), InchToLoMetric(11), DMPAPER_FANFOLD_US);
Add('German Std Fanfold 8 1/2 x 12 in', 'German Std Fanfold', InchToLoMetric(8.5), InchToLoMetric(12), DMPAPER_FANFOLD_STD_GERMAN);
Add('German Legal Fanfold 8 1/2 x 13 in', 'German Legal Fanfold', InchToLoMetric(8.5), InchToLoMetric(13), DMPAPER_FANFOLD_LGL_GERMAN);
Add('B4 (ISO) 250 x 353 mm', 'B4 (ISO)', 2500, 3530, DMPAPER_ISO_B4);
Add('Japanese Postcard 100 x 148 mm', 'Japanese Postcard', 1000, 1480, DMPAPER_JAPANESE_POSTCARD);
Add('9 x 11 in', '9 x 11 in', InchToLoMetric(90), InchToLoMetric(110), DMPAPER_9X11);
Add('10 x 11 in', '10 x 11 in', InchToLoMetric(10), InchToLoMetric(11), DMPAPER_10X11);
Add('15 x 11 in', '15 x 11 in', InchToLoMetric(15), InchToLoMetric(11), DMPAPER_15X11);
Add('Envelope Invite 220 x 220 mm', 'Envelope Invite', 2200, 2200, DMPAPER_ENV_INVITE);
// DMPAPER_RESERVED_48 = 48; { RESERVED--DO NOT USE }
// DMPAPER_RESERVED_49 = 49; { RESERVED--DO NOT USE }
Add('Letter Extra 9 \275 x 12 in', 'Legal Extra', InchToLoMetric(9 + 1 / 275), InchToLoMetric(12), DMPAPER_LETTER_EXTRA);
Add('Legal Extra 9 \275 x 15 in', 'Legal Extra', InchToLoMetric(9 + 1 / 275), InchToLoMetric(15), DMPAPER_LEGAL_EXTRA);
Add('Tabloid Extra 11.69 x 18 in', 'Tabloid Extra', InchToLoMetric(11.69), InchToLoMetric(18), DMPAPER_TABLOID_EXTRA);
Add('A4 Extra 9.27 x 12.69 in', 'A4 Extra', InchToLoMetric(9.27), InchToLoMetric(12.69), DMPAPER_A4_EXTRA);
Add('Letter Transverse 8 \275 x 11 in', 'Letter Transverse', InchToLoMetric(8 + 1 / 275), InchToLoMetric(11), DMPAPER_LETTER_TRANSVERSE);
Add('A4 Transverse 210 x 297 mm', 'A4 Transverse', 2100, 2970, DMPAPER_LETTER_EXTRA_TRANSVERSE);
Add('Letter Extra Transverse 9\275 x 12 in', 'Letter Extra Transverse', InchToLoMetric(9 + 1 / 275), InchToLoMetric(12), DMPAPER_LETTER_EXTRA_TRANSVERSE);
Add('SuperASuperAA4 227 x 356 mm', 'SuperASuperAA4', 2270, 3560, DMPAPER_A_PLUS);
Add('SuperBSuperBA3 305 x 487 mm', 'SuperBSuperBA3', 3050, 4870, DMPAPER_B_PLUS);
Add('Letter Plus 8.5 x 12.69 in', 'Letter Plus', InchToLoMetric(8.5), InchToLoMetric(12.69), DMPAPER_LETTER_PLUS);
Add('A4 Plus 210 x 330 mm', 'A4 Plus', 2100, 3300, DMPAPER_A4_PLUS);
Add('A5 Transverse 148 x 210 mm', 'A5 Transverse', 1480, 2100, DMPAPER_A5_TRANSVERSE);
Add('B5 (JIS) Transverse 182 x 257 mm', 'B5 (JIS) Transverse', 1820, 2570, DMPAPER_B5_TRANSVERSE);
Add('A3 Extra 322 x 445 mm', 'A3 Extra', 3220, 4450, DMPAPER_A3_EXTRA);
Add('A5 Extra 174 x 235 mm', 'A5 Extra', 1740, 2350, DMPAPER_A5_EXTRA);
Add('B5 (ISO) Extra 201 x 276 mm', 'B5 (ISO) Extra', 2010, 2760, DMPAPER_B5_EXTRA);
Add('A2 420 x 594 mm', 'A2', 4200, 5940, DMPAPER_A2);
Add('A3 Transverse 297 x 420 mm', 'A3 Transverse', 2970, 4200, DMPAPER_A3_TRANSVERSE);
Add('A3 Extra Transverse 322 x 445 mm', 'A3 Extra Transverse', 3220, 4450, DMPAPER_A3_EXTRA_TRANSVERSE);
if Win32MajorVersion >= 5 then
begin
Add('Japanese Double Postcard 200 x 148 mm', 'Japanese Double Postcard', 2000, 148, DMPAPER_DBL_JAPANESE_POSTCARD);
Add('A6 105 x 148 mm', 'A6', 1050, 1480, DMPAPER_A6);
// Add('Japanese Envelope Kaku #2', 'Japanese Envelope Kaku #2', 0, 0, DMPAPER_JENV_KAKU2);
// Add('Japanese Envelope Kaku #3', 'Japanese Envelope Kaku #3', 0, 0, DMPAPER_JENV_KAKU3);
// Add('Japanese Envelope Chou #3', 'Japanese Envelope Kaku #3', 0, 0, DMPAPER_JENV_CHOU3);
// Add('Japanese Envelope Chou #4', 'Japanese Envelope Kaku #4', 0, 0, DMPAPER_JENV_CHOU4);
Add('Letter Rotated 11 x 8 1/2 11 in', 'Letter Rotated', InchToLoMetric(11), InchToLoMetric(8.5), DMPAPER_LETTER_ROTATED);
Add('A3 Rotated 420 x 297 mm', 'A3 Rotated', 4200, 2970, DMPAPER_A3_ROTATED);
Add('A4 Rotated 297 x 210 mm', 'A4 Rotated', 2970, 2100, DMPAPER_A4_ROTATED);
Add('A5 Rotated 210 x 148 mm', 'A5 Rotated', 2100, 1480, DMPAPER_A5_ROTATED);
Add('B4 (JIS) Rotated 364 x 257 mm', 'B4 (JIS) Rotated', 3640, 2570, DMPAPER_B4_JIS_ROTATED);
Add('B5 (JIS) Rotated 257 x 182 mm', 'B5 (JIS) Rotated', 2570, 1820, DMPAPER_B5_JIS_ROTATED);
Add('Japanese Postcard Rotated 148 x 100 mm', 'Japanese Postcard Rotated', 1480, 1000, DMPAPER_JAPANESE_POSTCARD_ROTATED);
Add('A6 Rotated 148 x 105 mm', 'A6 Rotated', 1480, 1050, DMPAPER_A6_ROTATED);
// Add('Japanese Envelope Kaku #2 Rotated', 'Japanese Envelope Kaku #2 Rotated', 0, 0, DMPAPER_JENV_KAKU2_ROTATED);
// Add('Japanese Envelope Kaku #3 Rotated', 'Japanese Envelope Kaku #4 Rotated', 0, 0, DMPAPER_JENV_KAKU3_ROTATED);
// Add('Japanese Envelope Chou #3 Rotated', 'Japanese Envelope Chou #3 Rotated', 0, 0, DMPAPER_JENV_CHOU3_ROTATED);
// Add('Japanese Envelope Chow #4 Rotated', 'Japanese Envelope Chou #4 Rotated', 0, 0, DMPAPER_JENV_CHOU4_ROTATED);
Add('B6 (JIS) 128 x 182 mm', 'B6 (JIS)', 1280, 1820, DMPAPER_B6_JIS);
Add('B6 (JIS) Rotated 182 x 128 mm', 'B6 (JIS) Rotated', 1820, 1280, DMPAPER_B6_JIS_ROTATED);
Add('12X11 12 x 11 in', '12X11', InchToLoMetric(12), InchToLoMetric(11), DMPAPER_12X11);
// Add('Japanese Envelope You #4', 'Japanese Envelope You #4', 0, 0, DMPAPER_JENV_YOU4);
// Add('Japanese Envelope You #4 Rotated', 'Japanese Envelope You #4 Rotated', 0, 0, DMPAPER_JENV_YOU4_ROTATED);
Add('PRC 16K 146 x 215 mm', 'PRC 16K', 1460, 2150, DMPAPER_P16K);
Add('PRC 32K 97 x 151 mm', 'PRC 32K', 970, 1510, DMPAPER_P32K);
Add('PRC 32K(Big) 97 x 151 mm', 'PRC 32K(Big)', 970, 1510, DMPAPER_P32KBIG);
Add('PRC Envelope #1 102 x 165 mm', 'PRC Envelope #1', 1020, 1650, DMPAPER_PENV_1);
Add('PRC Envelope #2 102 x 176 mm', 'PRC Envelope #2', 1020, 1760, DMPAPER_PENV_2);
Add('PRC Envelope #3 125 x 176 mm', 'PRC Envelope #3', 1250, 1760, DMPAPER_PENV_3);
Add('PRC Envelope #4 110 x 208 mm', 'PRC Envelope #4', 1100, 2080, DMPAPER_PENV_4);
Add('PRC Envelope #5 110 x 220 mm', 'PRC Envelope #5', 2190, 2200, DMPAPER_PENV_5);
Add('PRC Envelope #6 120 x 230 mm', 'PRC Envelope #6', 1200, 2300, DMPAPER_PENV_6);
Add('PRC Envelope #7 160 x 230 mm', 'PRC Envelope #7', 1600, 2300, DMPAPER_PENV_7);
Add('PRC Envelope #8 120 x 309 mm', 'PRC Envelope #8', 1200, 3090, DMPAPER_PENV_8);
Add('PRC Envelope #9 229 x 324 mm', 'PRC Envelope #9', 2290, 3240, DMPAPER_PENV_9);
Add('PRC Envelope #10 324 x 458 mm', 'PRC Envelope #10', 3240, 4580, DMPAPER_PENV_10);
Add('PRC 16K Rotated 146 x 215 mm', 'PRC 16K Rotated', 1460, 2150, DMPAPER_P16K_ROTATED);
Add('PRC 32K Rotated 97 x 151 mm', 'PRC 32K Rotated', 970, 1510, DMPAPER_P32K_ROTATED);
Add('PRC 32K(Big) Rotated 97 x 151 mm', 'PRC 32K(Big) Rotated', 970, 1510, DMPAPER_P32KBIG_ROTATED);
Add('PRC Envelope #1 Rotated 165 x 102 mm', 'PRC Envelope #1 Rotated', 1650, 1020, DMPAPER_PENV_1_ROTATED);
Add('PRC Envelope #2 Rotated 176 x 102 mm', 'PRC Envelope #2 Rotated', 1760, 1020, DMPAPER_PENV_2_ROTATED);
Add('PRC Envelope #3 Rotated 176 x 125 mm', 'PRC Envelope #3 Rotated', 1760, 1250, DMPAPER_PENV_3_ROTATED);
Add('PRC Envelope #4 Rotated 208 x 110 mm', 'PRC Envelope #4 Rotated', 2080, 1100, DMPAPER_PENV_4_ROTATED);
Add('PRC Envelope #5 Rotated 220 x 110 mm', 'PRC Envelope #5 Rotated', 2200, 2190, DMPAPER_PENV_5_ROTATED);
Add('PRC Envelope #6 Rotated 230 x 120 mm', 'PRC Envelope #6 Rotated', 2300, 1200, DMPAPER_PENV_6_ROTATED);
Add('PRC Envelope #7 Rotated 230 x 160 mm', 'PRC Envelope #7 Rotated', 2300, 1600, DMPAPER_PENV_7_ROTATED);
Add('PRC Envelope #8 Rotated 309 x 120 mm', 'PRC Envelope #8 Rotated', 3090, 1200, DMPAPER_PENV_8_ROTATED);
Add('PRC Envelope #9 Rotated 324 x 229 mm', 'PRC Envelope #9 Rotated', 3240, 2290, DMPAPER_PENV_9_ROTATED);
Add('PRC Envelope #10 Rotated 458 x 324 mm', 'PRC Envelope #10 Rotated', 4580, 3240, DMPAPER_PENV_10_ROTATED);
end;
Add('Custom', 'Custom', 0, 0, DMPAPER_USER);
AddAdobe('10x11',254,279.4,DMPAPER_10X11);
AddAdobe('10x13',254,330.2);
AddAdobe('10x14',254,355.6,DMPAPER_10X14);
AddAdobe('12x11',304.8,279.4,DMPAPER_12X11);
AddAdobe('15x11',381,279.4,DMPAPER_15X11);
AddAdobe('7x9',177.8,228.6);
AddAdobe('8x10',203.2,254);
AddAdobe('9x11',228.6,279.4,DMPAPER_9X11);
AddAdobe('9x12',228.6,304.8);
AddAdobe('A0',841,1189);
AddAdobe('A1',594,841);
AddAdobe('A2',420,594,DMPAPER_A2);
AddAdobe('A3',297,420,DMPAPER_A3);
AddAdobe('A3.Transverse',297,420,DMPAPER_A3_TRANSVERSE);
AddAdobe('A3Extra',322,445,DMPAPER_A3_EXTRA);
AddAdobe('A3Extra.Transverse',322,445,DMPAPER_A3_EXTRA_TRANSVERSE);
AddAdobe('A3Rotated',420,297,DMPAPER_A3_ROTATED);
AddAdobe('A4',210,297,DMPAPER_A4);
AddAdobe('A4.Transverse',210,297,DMPAPER_A4_TRANSVERSE);
AddAdobe('A4Extra',235.5,322.3,DMPAPER_A4_EXTRA);
AddAdobe('A4Plus',210,330,DMPAPER_A4_PLUS);
AddAdobe('A4Rotated',297,210,DMPAPER_A4_ROTATED);
AddAdobe('A4Small',210,297,DMPAPER_A4SMALL);
AddAdobe('A5',148,210,DMPAPER_A5);
AddAdobe('A5.Transverse',148,210,DMPAPER_A5_TRANSVERSE);
AddAdobe('A5Extra',174,235,DMPAPER_A5_EXTRA);
AddAdobe('A5Rotated',210,148,DMPAPER_A5_ROTATED);
AddAdobe('A6',105,148,DMPAPER_A6);
AddAdobe('A6Rotated',148,105,DMPAPER_A6_ROTATED);
AddAdobe('A7',74,105);
AddAdobe('A8',52,74);
AddAdobe('A9',37,52);
AddAdobe('A10',26,37);
AddAdobe('AnsiC',431.8,558.8);
AddAdobe('AnsiD',558.8,863.6);
AddAdobe('AnsiE',863.6,1118);
AddAdobe('ARCHA',228.6,304.8);
AddAdobe('ARCHB',304.8,457.2);
AddAdobe('ARCHC',457.2,609.6,DMPAPER_CSHEET);
AddAdobe('ARCHD',609.6,914.4,DMPAPER_DSHEET);
AddAdobe('ARCHE',914.4,1219,DMPAPER_ESHEET);
AddAdobe('B0',1030,1456);
AddAdobe('B1',728,1030);
AddAdobe('B2',515,728);
AddAdobe('B3',364,515);
AddAdobe('B4',257,364,DMPAPER_B4);
AddAdobe('B4Rotated',364,257,DMPAPER_B4_JIS_ROTATED);
AddAdobe('B5',182,257,DMPAPER_B5);
AddAdobe('B5.Transverse',182,257,DMPAPER_B5_TRANSVERSE);
AddAdobe('B5Rotated',257,182,DMPAPER_B5_JIS_ROTATED);
AddAdobe('B6',128,182,DMPAPER_B6_JIS);
AddAdobe('B6Rotated',182,128,DMPAPER_B6_JIS_ROTATED);
AddAdobe('B7',91,128);
AddAdobe('B8',64,91);
AddAdobe('B9',45,64);
AddAdobe('B10',32,45);
AddAdobe('DoublePostcard',200,148,DMPAPER_DBL_JAPANESE_POSTCARD);
AddAdobe('DoublePostcardRotated',148,200,DMPAPER_DBL_JAPANESE_POSTCARD_ROTATED);
AddAdobe('Env9',98.4,225.4,DMPAPER_ENV_9);
AddAdobe('Env10',104.8,241.3,DMPAPER_ENV_10);
AddAdobe('Env11',114.3,263.5,DMPAPER_ENV_11);
AddAdobe('Env12',120.7,279.4,DMPAPER_ENV_12);
AddAdobe('Env14',127,292.1,DMPAPER_ENV_14);
AddAdobe('EnvC0',917,1297);
AddAdobe('EnvC1',648,917);
AddAdobe('EnvC2',458,648);
AddAdobe('EnvC3',324,458,DMPAPER_ENV_C3);
AddAdobe('EnvC4',229,324,DMPAPER_ENV_C4);
AddAdobe('EnvC5',162,229,DMPAPER_ENV_C5);
AddAdobe('EnvC6',114,162,DMPAPER_ENV_C6);
AddAdobe('EnvC65',114,229,DMPAPER_ENV_C65);
AddAdobe('EnvC7',81,114);
AddAdobe('EnvChou3',120,235,DMPAPER_JENV_CHOU3);
AddAdobe('EnvChou3Rotated',235,120,DMPAPER_JENV_CHOU3_ROTATED);
AddAdobe('EnvChou4',90,205,DMPAPER_JENV_CHOU4);
AddAdobe('EnvChou4Rotated',205,90,DMPAPER_JENV_CHOU4_ROTATED);
AddAdobe('EnvDL',110,220,DMPAPER_ENV_DL);
AddAdobe('EnvInvite',220,220,DMPAPER_ENV_INVITE);
AddAdobe('EnvISOB4',250,353,DMPAPER_ENV_B4);
AddAdobe('EnvISOB5',176,250,DMPAPER_ENV_B5);
AddAdobe('EnvISOB6',176,125,DMPAPER_ENV_B6);
AddAdobe('EnvItalian',110,230,DMPAPER_ENV_ITALY);
AddAdobe('EnvKaku2',240,332,DMPAPER_JENV_KAKU2);
AddAdobe('EnvKaku2Rotated',332,240,DMPAPER_JENV_KAKU2_ROTATED);
AddAdobe('EnvKaku3',216,277,DMPAPER_JENV_KAKU3);
AddAdobe('EnvKaku3Rotated',277,216,DMPAPER_JENV_KAKU3_ROTATED);
AddAdobe('EnvMonarch',98.43,190.5,DMPAPER_ENV_MONARCH);
AddAdobe('EnvPersonal',92.08,165.1,DMPAPER_ENV_PERSONAL);
AddAdobe('EnvPRC1',102,165,DMPAPER_PENV_1);
AddAdobe('EnvPRC1Rotated',165,102,DMPAPER_PENV_1_ROTATED);
AddAdobe('EnvPRC2',102,176,DMPAPER_PENV_2);
AddAdobe('EnvPRC2Rotated',176,102,DMPAPER_PENV_2_ROTATED);
AddAdobe('EnvPRC3',125,176,DMPAPER_PENV_3);
AddAdobe('EnvPRC3Rotated',176,125,DMPAPER_PENV_3_ROTATED);
AddAdobe('EnvPRC4',110,208,DMPAPER_PENV_4);
AddAdobe('EnvPRC4Rotated',208,110,DMPAPER_PENV_4_ROTATED);
AddAdobe('EnvPRC5',110,220,DMPAPER_PENV_5);
AddAdobe('EnvPRC5Rotated',220,110,DMPAPER_PENV_5_ROTATED);
AddAdobe('EnvPRC6',120,230,DMPAPER_PENV_6);
AddAdobe('EnvPRC6Rotated',230,120,DMPAPER_PENV_6_ROTATED);
AddAdobe('EnvPRC7',160,230,DMPAPER_PENV_7);
AddAdobe('EnvPRC7Rotated',230,160,DMPAPER_PENV_7_ROTATED);
AddAdobe('EnvPRC8',120,309,DMPAPER_PENV_8);
AddAdobe('EnvPRC8Rotated',309,120,DMPAPER_PENV_8_ROTATED);
AddAdobe('EnvPRC9',229,324,DMPAPER_PENV_9);
AddAdobe('EnvPRC9Rotated',324,229,DMPAPER_PENV_9_ROTATED);
AddAdobe('EnvPRC10',324,458,DMPAPER_PENV_10);
AddAdobe('EnvPRC10Rotated',458,324,DMPAPER_PENV_10_ROTATED);
AddAdobe('EnvYou4',105,235,DMPAPER_JENV_YOU4);
AddAdobe('EnvYou4Rotated',235,105,DMPAPER_JENV_YOU4_ROTATED);
AddAdobe('Executive',184.2,266.7,DMPAPER_EXECUTIVE);
AddAdobe('FanFoldUS',377.8,279.4,DMPAPER_FANFOLD_US);
AddAdobe('FanFoldGerman',215.9,304.8,DMPAPER_FANFOLD_STD_GERMAN);
AddAdobe('FanFoldGermanLegal',215.9,330,DMPAPER_FANFOLD_LGL_GERMAN);
AddAdobe('Folio',210,330,DMPAPER_FOLIO);
AddAdobe('ISOB0',1000,1414);
AddAdobe('ISOB1',707,1000);
AddAdobe('ISOB2',500,707);
AddAdobe('ISOB3',353,500);
AddAdobe('ISOB4',250,353,DMPAPER_ISO_B4);
AddAdobe('ISOB5',176,250);
AddAdobe('ISOB5Extra',201,276,DMPAPER_B5_EXTRA);
AddAdobe('ISOB6',125,176);
AddAdobe('ISOB7',88,125);
AddAdobe('ISOB8',62,88);
AddAdobe('ISOB9',44,62);
AddAdobe('ISOB10',31,44);
AddAdobe('Ledger',431.8,279.4,DMPAPER_LEDGER);
AddAdobe('Legal',215.9,355.6,DMPAPER_LEGAL);
AddAdobe('LegalExtra',241.3,381,DMPAPER_LEGAL_EXTRA);
AddAdobe('Letter',215.9,279.4,DMPAPER_LETTER);
AddAdobe('Letter.Transverse',215.9,279.4,DMPAPER_LETTER_TRANSVERSE);
AddAdobe('LetterExtra',241.3,304.8,DMPAPER_LETTER_EXTRA);
AddAdobe('LetterExtra.Transverse',241.3,304.8,DMPAPER_LETTER_EXTRA_TRANSVERSE);
AddAdobe('LetterPlus',215.9,322.3,DMPAPER_LETTER_PLUS);
AddAdobe('LetterRotated',279.4,215.9,DMPAPER_LETTER_ROTATED);
AddAdobe('LetterSmall',215.9,279.4,DMPAPER_LETTERSMALL);
AddAdobe('Note',215.9,279.4,DMPAPER_NOTE);
AddAdobe('Postcard',100,148,DMPAPER_JAPANESE_POSTCARD);
AddAdobe('PostcardRotated',148,100,DMPAPER_JAPANESE_POSTCARD_ROTATED);
AddAdobe('PRC16K',146,215,DMPAPER_P16K);
AddAdobe('PRC16KRotated',215,146,DMPAPER_P16K_ROTATED);
AddAdobe('PRC32K',97,151,DMPAPER_P32K);
AddAdobe('PRC32KBig',97,151,DMPAPER_P32KBIG);
AddAdobe('PRC32KBigRotated',151,97,DMPAPER_P32KBIG_ROTATED);
AddAdobe('PRC32KRotated',151,97,DMPAPER_P32K_ROTATED);
AddAdobe('Quarto',215.9,275.1,DMPAPER_QUARTO);
AddAdobe('Statement',139.7,215.9,DMPAPER_STATEMENT);
AddAdobe('SuperA',227,356,DMPAPER_A_PLUS);
AddAdobe('SuperB',305,487,DMPAPER_B_PLUS);
AddAdobe('Tabloid',279.4,431.8,DMPAPER_TABLOID);
AddAdobe('TabloidExtra',304.8,457.2,DMPAPER_TABLOID_EXTRA);
end;
function TPapers.GetCount: Integer;
begin
Result := FPapers.Count;
end;
function TPapers.GetPaper(Index: Integer): TPaper;
begin
Result := TPaper(FPapers[Index]);
end;
initialization
FPaperlist := TPapers.create;
_SourceNames[DMBIN_AUTO] := 'Auto';
_SourceNames[DMBIN_CASSETTE] := 'Cassette';
_SourceNames[DMBIN_ENVELOPE] := 'Envelope';
_SourceNames[DMBIN_ENVMANUAL] := 'EnvManual';
_SourceNames[DMBIN_FORMSOURCE] := 'FormSource';
_SourceNames[DMBIN_LARGECAPACITY] := 'LargeCapacity';
_SourceNames[DMBIN_LARGEFMT] := 'Largefmt';
_SourceNames[DMBIN_LOWER] := 'Lower';
_SourceNames[DMBIN_MANUAL] := 'Manual';
_SourceNames[DMBIN_MIDDLE] := 'Middle';
_SourceNames[DMBIN_ONLYONE] := 'Onlyone';
_SourceNames[DMBIN_SMALLFMT] := 'SmallFmt';
_SourceNames[DMBIN_TRACTOR] := 'Tractor';
_SourceNames[DMBIN_UPPER] := 'Upper';
_SourceNames[DMBIN_USER] := 'User';
_SourceConsts[DMBIN_AUTO] := 'DMBIN_AUTO';
_SourceConsts[DMBIN_CASSETTE] := 'DMBIN_CASSETTE';
_SourceConsts[DMBIN_ENVELOPE] := 'DMBIN_ENVELOPE';
_SourceConsts[DMBIN_ENVMANUAL] := 'DMBIN_ENVMANUAL';
_SourceConsts[DMBIN_FORMSOURCE] := 'DMBIN_FORMSOURCE';
_SourceConsts[DMBIN_LARGECAPACITY] := 'DMBIN_LARGECAPACITY';
_SourceConsts[DMBIN_LARGEFMT] := 'DMBIN_LARGEFMT';
_SourceConsts[DMBIN_LOWER] := 'DMBIN_LOWER';
_SourceConsts[DMBIN_MANUAL] := 'DMBIN_MANUAL';
_SourceConsts[DMBIN_MIDDLE] := 'DMBIN_MIDDLE';
_SourceConsts[DMBIN_ONLYONE] := 'DMBIN_ONLYONE';
_SourceConsts[DMBIN_SMALLFMT] := 'DMBIN_SMALLFMT';
_SourceConsts[DMBIN_TRACTOR] := 'DMBIN_TRACTOR';
_SourceConsts[DMBIN_UPPER] := 'DMBIN_UPPER';
_SourceConsts[DMBIN_USER] := 'DMBIN_USER';
finalization
FreeAndNil(FPaperlist);
end.
|
unit IdGopherServer;
interface
uses
Classes,
IdGlobal,
IdTCPServer;
const
Id_TIdGopherServer_TruncateUserFriendly = True;
Id_TIdGopherServer_TruncateLength = 70;
type
TRequestEvent = procedure(AThread: TIdPeerThread; ARequest: string) of object;
TPlusRequestEvent = procedure(AThread: TIdPeerThread; ARequest: string;
APlusData: string) of object;
TIdGopherServer = class(TIdTCPServer)
private
fAdminEmail: string;
fOnRequest: TRequestEvent;
fOnPlusRequest: TPlusRequestEvent;
fTruncateUserFriendly: Boolean;
fTruncateLength: Integer;
protected
function DoExecute(Thread: TIdPeerThread): boolean; override;
public
constructor Create(AOwner: TComponent); override;
function ReturnGopherItem(ItemType: Char;
UserFriendlyName, RealResourceName: string;
HostServer: string; HostPort: Integer): string;
procedure SendDirectoryEntry(Thread: TIdPeerThread;
ItemType: Char; UserFriendlyName, RealResourceName: string;
HostServer: string; HostPort: Integer);
procedure SetTruncateUserFriendlyName(truncate: Boolean);
procedure SetTruncateLength(length: Integer);
published
property AdminEmail: string read fAdminEmail write fAdminEmail;
property OnRequest: TRequestEvent read fOnRequest write fOnRequest;
property OnPlusRequest: TPlusRequestEvent read fOnPlusRequest
write fOnPlusRequest;
property TruncateUserFriendlyName: Boolean read fTruncateUserFriendly
write SetTruncateUserFriendlyName default
Id_TIdGopherServer_TruncateUserFriendly;
property TruncateLength: Integer read fTruncateLength
write SetTruncateLength default Id_TIdGopherServer_TruncateLength;
property DefaultPort default IdPORT_GOPHER;
end;
implementation
uses
IdGopherConsts, IdResourceStrings,
SysUtils;
constructor TIdGopherServer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DefaultPort := IdPORT_GOPHER;
fAdminEmail := '<gopher@domain.example>';
FTruncateUserFriendly := Id_TIdGopherServer_TruncateUserFriendly;
FTruncateLength := Id_TIdGopherServer_TruncateLength;
end;
function TIdGopherServer.DoExecute(Thread: TIdPeerThread): boolean;
var
s: string;
i: Integer;
begin
result := true;
with Thread.Connection do
begin
while Connected do
begin
try
s := ReadLn;
i := Pos(TAB, s);
if i > 0 then
begin
if Assigned(OnPlusRequest) then
begin
OnPlusRequest(Thread, Copy(s, 1, i - 1), Copy(s, i + 1, length(s)));
end
else
if Assigned(OnRequest) then
begin
OnRequest(Thread, s);
end
else
begin
Thread.Connection.Write(IdGopherPlusData_ErrorBeginSign
+ IdGopherPlusError_NotAvailable
+ RSGopherServerNoProgramCode + EOL
+ IdGopherPlusData_EndSign);
end;
end
else
if Assigned(OnRequest) then
begin
OnRequest(Thread, s)
end
else
begin
Thread.Connection.Write(RSGopherServerNoProgramCode
+ EOL + IdGopherPlusData_EndSign);
end;
except
break;
end;
Thread.Connection.Disconnect;
end;
end;
end;
function TIdGopherServer.ReturnGopherItem(ItemType: Char;
UserFriendlyName, RealResourceName: string;
HostServer: string; HostPort: Integer): string;
begin
if fTruncateUserFriendly then
begin
if (Length(UserFriendlyName) > fTruncateLength)
and (fTruncateLength <> 0) then
begin
UserFriendlyName := Copy(UserFriendlyName, 1, fTruncateLength);
end;
end;
result := ItemType + UserFriendlyName +
TAB + RealResourceName + TAB + HostServer + TAB + IntToStr(HostPort);
end;
procedure TIdGopherServer.SendDirectoryEntry;
begin
Thread.Connection.WriteLn(ReturnGopherItem(ItemType, UserFriendlyName,
RealResourceName, HostServer, HostPort));
end;
procedure TIdGopherServer.SetTruncateUserFriendlyName;
begin
fTruncateUserFriendly := Truncate;
end;
procedure TIdGopherServer.SetTruncateLength;
begin
fTruncateLength := Length;
end;
end.
|
unit uAcessoUsuario;
interface
uses uUsuario, uEmpresa;
type
TAcessoUsuario = class
private
codigo: Integer;
empresa: TEmpresa;
usuario: TUsuario;
terminal: String;
public
// construtor
constructor TAcessoUsuarioCreate;
// destrutor
destructor TAcessoUsuarioDestroy;
// metodo "procedimento" set do Objeto
procedure setCodigo(param: Integer);
procedure setEmpresa(param: TEmpresa);
procedure setUsuario(param: TUsuario);
procedure setTerminal(param: String);
// metodos "funcoes" get do Objeto
function getCodigo: Integer;
function getEmpresa: TEmpresa;
function getUsuario: TUsuario;
function getTerminal: String;
end;
var
acessoUsuario : TAcessoUsuario;
implementation
{ TAcessoUsuario get e set dos objetos }
function TAcessoUsuario.getCodigo: Integer;
begin
result := codigo;
end;
function TAcessoUsuario.getEmpresa: TEmpresa;
begin
result := empresa;
end;
function TAcessoUsuario.getTerminal: String;
begin
result := terminal;
end;
function TAcessoUsuario.getUsuario: TUsuario;
begin
result := usuario;
end;
procedure TAcessoUsuario.setCodigo(param: Integer);
begin
codigo := param;
end;
procedure TAcessoUsuario.setEmpresa(param: TEmpresa);
begin
empresa := param;
end;
procedure TAcessoUsuario.setTerminal(param: String);
begin
terminal := param;
end;
procedure TAcessoUsuario.setUsuario(param: TUsuario);
begin
usuario := param;
end;
constructor TAcessoUsuario.TAcessoUsuarioCreate;
begin
codigo := 0;
empresa.TEmpresaCreate;
usuario.TUsuarioCreate;
terminal := '';
end;
destructor TAcessoUsuario.TAcessoUsuarioDestroy;
begin
empresa.TEmpresaDestroy;
usuario.TUsuarioDestroy;
FreeInstance;
end;
end.
|
unit uFuncionario;
interface
uses uDependente, System.Generics.Collections;
type
TFuncionario = class
private
FID: Integer;
FCPF: String;
FSalario: Real;
FNome: String;
FListaDependentes: TList<TDependente>;
public
constructor Create; overload;
destructor Destroy;
property Id_Funcionario: Integer read FID write FID;
property Nome: String read FNome write FNome;
property CPF: String read FCPF write FCPF;
property Salario: Real read FSalario write FSalario;
property Dependentes: TList<TDependente> read FListaDependentes
write FListaDependentes;
end;
implementation
{ TFuncionario }
constructor TFuncionario.Create;
begin
FListaDependentes := TList<TDependente>.Create();
end;
destructor TFuncionario.Destroy;
var
oDependente: TDependente;
begin
for oDependente in FListaDependentes do
begin
oDependente.Free;
end;
FListaDependentes.Free;
FListaDependentes := nil;
end;
end.
|
program ExampleAuthenticate;
{$ifdef MSWINDOWS}{$apptype CONSOLE}{$endif}
{$ifdef FPC}{$mode OBJFPC}{$H+}{$endif}
uses
SysUtils, IPConnection, Device;
type
TExample = class
private
ipcon: TIPConnection;
public
procedure ConnectedCB(sender: TIPConnection; const connectReason: byte);
procedure EnumerateCB(sender: TIPConnection;
const uid: string; const connectedUid: string; const position: char;
const hardwareVersion: TVersionNumber; const firmwareVersion: TVersionNumber;
const deviceIdentifier: word; const enumerationType: byte);
procedure Execute;
end;
const
HOST = 'localhost';
PORT = 4223;
SECRET = 'My Authentication Secret!';
var
e: TExample;
{ Authenticate each time the connection got (re-)established }
procedure TExample.ConnectedCB(sender: TIPConnection; const connectReason: byte);
begin
case connectReason of
IPCON_CONNECT_REASON_REQUEST:
begin
WriteLn('Connected by request');
end;
IPCON_CONNECT_REASON_AUTO_RECONNECT:
begin
WriteLn('Auto-Reconnect');
end;
end;
{ Authenticate first... }
try
sender.Authenticate(SECRET);
WriteLn('Authentication succeeded');
except
WriteLn('Could not authenticate');
exit;
end;
{ ...reenable auto reconnect mechanism, as described below... }
sender.SetAutoReconnect(true);
{ ...then trigger enumerate }
sender.Enumerate;
end;
{ Print incoming enumeration }
procedure TExample.EnumerateCB(sender: TIPConnection;
const uid: string; const connectedUid: string; const position: char;
const hardwareVersion: TVersionNumber; const firmwareVersion: TVersionNumber;
const deviceIdentifier: word; const enumerationType: byte);
begin
WriteLn('UID: ' + uid + ', Enumerate Type: ' + IntToStr(enumerationType));
end;
procedure TExample.Execute;
begin
{ Create IP Connection }
ipcon := TIPConnection.Create;
{ Disable auto reconnect mechanism, in case we have the wrong secret.
If the authentication is successful, reenable it. }
ipcon.SetAutoReconnect(false);
{ Register connected callback to "ConnectedCB" }
ipcon.OnConnected := {$ifdef FPC}@{$endif}ConnectedCB;
{ Register enumerate callback to "EnumerateCB" }
ipcon.OnEnumerate := {$ifdef FPC}@{$endif}EnumerateCB;
{ Connect to brickd }
ipcon.Connect(HOST, PORT);
WriteLn('Press key to exit');
ReadLn;
ipcon.Destroy; { Calls ipcon.Disconnect internally }
end;
begin
e := TExample.Create;
e.Execute;
e.Destroy;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC Data Adapter Layer implementation }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.DApt;
interface
implementation
uses
System.SysUtils, System.Classes, Data.DB, System.Generics.Collections, System.Types,
FireDAC.DatS,
FireDAC.Stan.Intf, FireDAC.Stan.Param, FireDAC.Stan.Factory, FireDAC.Stan.Util,
FireDAC.Stan.Error, FireDAC.Stan.Consts, FireDAC.Stan.ResStrs, FireDAC.Stan.Option,
FireDAC.UI.Intf,
FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.DApt.Column;
type
TFDDAptTableAdapter = class;
TFDDAptTableAdapters = class;
TFDDAptSchemaAdapter = class;
TFDDAptUpdatesJournalProcessor = class(TObject)
private
FJournal: TFDDatSUpdatesJournal;
FAdapters: TFDDAptTableAdapters;
FAdapter: TFDDAptTableAdapter;
FUpdateHandler: IFDDAptUpdateHandler;
FOptions: IFDStanOptions;
{$IFDEF FireDAC_MONITOR}
FMonitor: IFDMoniClient;
function IsTracing: Boolean;
procedure Trace(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep;
const AMsg: String; const AArgs: array of const);
{$ENDIF}
function GetLimitToTable: TFDDatSTable;
function LookupTableAdapter(ATable: TFDDatSTable): IFDDAptTableAdapter;
public
constructor CreateForTableAdapter(ATableAdapter: TFDDAptTableAdapter);
constructor CreateForSchemaAdapter(ASchemaAdapter: TFDDAptSchemaAdapter);
destructor Destroy; override;
function Process(AMaxErrors: Integer = -1): Integer;
function Reconcile: Boolean;
property LimitToTable: TFDDatSTable read GetLimitToTable;
{$IFDEF FireDAC_MONITOR}
property Monitor: IFDMoniClient read FMonitor write FMonitor;
{$ENDIF}
property Journal: TFDDatSUpdatesJournal read FJournal write FJournal;
property UpdateHandler: IFDDAptUpdateHandler read FUpdateHandler
write FUpdateHandler;
end;
TFDDAptUpdateCommandReason = (urSetSelect, urSetErrorHandler,
urReset, urSetTransaction, urSetUpdateTransaction);
TFDDAptTableAdapter = class(TFDObject, IUnknown, IFDStanObject,
IFDStanErrorHandler, IFDPhysMappingHandler, IFDDAptTableAdapter)
private
FDatSTable: TFDDatSTable;
FDatSTableName: String;
FSourceRecordSetID: Integer;
FSourceRecordSetName: String;
FUpdateTableName: String;
FColMappings: TFDDAptColumnMappings;
FMetaInfoMergeMode: TFDPhysMetaInfoMergeMode;
FMappings: TFDDAptTableAdapters;
FDatSManager: TFDDatSManager;
FGeneratedCommands: TFDActionRequests;
FCommands: array of IFDPhysCommand;
FBuffer: TFDBuffer;
FErrorHandler: IFDStanErrorHandler;
FUpdateHandler: IFDDAptUpdateHandler;
FInUpdateRowHandler: Boolean;
FTransaction: IFDPhysTransaction;
FUpdateTransaction: IFDPhysTransaction;
procedure ProcessUpdate(ARow: TFDDatSRow; var AAction: TFDErrorAction;
ARequest: TFDUpdateRequest; AUpdRowOptions: TFDUpdateRowOptions;
AFillRowOptions: TFDPhysFillRowOptions; AColumn: Integer);
function GetUpdateRowCommand(ARow: TFDDatSRow;
AUpdRowOptions: TFDUpdateRowOptions; AUpdateRequest: TFDUpdateRequest;
AFillRowOptions: TFDPhysFillRowOptions; AColumn: Integer; ACacheCommand: Boolean;
var AFlags: TFDPhysCommandGeneratorFlags): IFDPhysCommand;
procedure MergeRowFromParams(const ACommand: IFDPhysCommand;
ABaseRow: TFDDatSRow; AFetchedParams: TFDParams; AClearRow: Boolean);
procedure MergeRows(const ACommand: IFDPhysCommand;
ABaseRow, AFetchedRow: TFDDatSRow; AClearRow: Boolean);
procedure ParName2Col(ABaseRow: TFDDatSRow; const AName: String;
var ACol: TFDDatSColumn; var ARow: TFDDatSRow; var AVersion: Integer);
procedure ProcessRequest(const ACommand: IFDPhysCommand; ARow: TFDDatSRow;
ARequest: TFDUpdateRequest; AUpdRowOptions: TFDUpdateRowOptions;
AFillRowOptions: TFDPhysFillRowOptions; AWrapByTX: Boolean);
procedure SetParamsFromRow(AParams: TFDParams; ARow: TFDDatSRow);
{$IFDEF FireDAC_MONITOR}
function IsTracing: Boolean;
procedure Trace(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep;
const AMsg: String; const AArgs: array of const);
function GetUpdateRequestName(ARequest: TFDUpdateRequest): String;
{$ENDIF}
function SetCommand(AReq: TFDActionRequest; const ACmd: IFDPhysCommand): Boolean;
procedure GetCommand(AReq: TFDActionRequest; out ACmd: IFDPhysCommand);
procedure UpdateCommands(AReason: TFDDAptUpdateCommandReason);
procedure CheckSelectCommand;
function GetSchemaAdapter: TFDDAptSchemaAdapter;
procedure InternalSetCommand(AReq: TFDActionRequest; const ACmd: IFDPhysCommand);
procedure ReleaseDatSTable;
procedure DetachDatSTable;
procedure AcquireDatSTable(ATable: TFDDatSTable);
procedure AttachDatSTable;
function MatchRecordSet(const ATable: TFDPhysMappingName): Boolean;
procedure GetConn(out AConn: IFDPhysConnection);
procedure GetUpdTx(out ATx: IFDPhysTransaction);
protected
// IUnknown
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
// IFDStanObject
function GetName: TComponentName;
function GetParent: IFDStanObject;
procedure BeforeReuse;
procedure AfterReuse;
procedure SetOwner(const AOwner: TObject; const ARole: TComponentName);
// IFDStanErrorHandler
procedure HandleException(const AInitiator: IFDStanObject;
var AException: Exception);
// IFDPhysMappingHandler
function MapRecordSet(const ATable: TFDPhysMappingName;
var ASourceID: Integer; var ASourceName, ADatSName, AUpdateName: String;
var ADatSTable: TFDDatSTable): TFDPhysMappingResult;
function MapRecordSetColumn(const ATable, AColumn: TFDPhysMappingName;
var ASourceID: Integer; var ASourceName, ADatSName, AUpdateName: String;
var ADatSColumn: TFDDatSColumn): TFDPhysMappingResult;
// IFDDAptTableAdapter
function GetSourceRecordSetID: Integer;
procedure SetSourceRecordSetID(const AValue: Integer);
function GetSourceRecordSetName: String;
procedure SetSourceRecordSetName(const AValue: String);
function GetUpdateTableName: String;
procedure SetUpdateTableName(const AValue: String);
function GetDatSTableName: String;
procedure SetDatSTableName(const AValue: String);
function GetDatSTable: TFDDatSTable;
procedure SetDatSTable(AValue: TFDDatSTable);
function GetColumnMappings: TFDDAptColumnMappings;
function GetMetaInfoMergeMode: TFDPhysMetaInfoMergeMode;
procedure SetMetaInfoMergeMode(const AValue: TFDPhysMetaInfoMergeMode);
function GetTableMappings: IFDDAptTableAdapters;
function GetDatSManager: TFDDatSManager;
procedure SetDatSManager(AValue: TFDDatSManager);
function GetSelectCommand: IFDPhysCommand;
procedure SetSelectCommand(const ACmd: IFDPhysCommand);
function GetInsertCommand: IFDPhysCommand;
procedure SetInsertCommand(const ACmd: IFDPhysCommand);
function GetUpdateCommand: IFDPhysCommand;
procedure SetUpdateCommand(const ACmd: IFDPhysCommand);
function GetDeleteCommand: IFDPhysCommand;
procedure SetDeleteCommand(const ACmd: IFDPhysCommand);
function GetLockCommand: IFDPhysCommand;
procedure SetLockCommand(const ACmd: IFDPhysCommand);
function GetUnLockCommand: IFDPhysCommand;
procedure SetUnLockCommand(const ACmd: IFDPhysCommand);
function GetFetchRowCommand: IFDPhysCommand;
procedure SetFetchRowCommand(const ACmd: IFDPhysCommand);
function GetTransaction: IFDPhysTransaction;
procedure SetTransaction(const AValue: IFDPhysTransaction);
function GetUpdateTransaction: IFDPhysTransaction;
procedure SetUpdateTransaction(const AValue: IFDPhysTransaction);
function GetOptions: IFDStanOptions;
function GetErrorHandler: IFDStanErrorHandler;
procedure SetErrorHandler(const AValue: IFDStanErrorHandler);
function GetUpdateHandler: IFDDAptUpdateHandler;
procedure SetUpdateHandler(const AValue: IFDDAptUpdateHandler);
function GetObj: TObject;
function Define: TFDDatSTable;
procedure Fetch(AAll: Boolean = False; ABlocked: Boolean = False); overload;
function Update(AMaxErrors: Integer = -1): Integer; overload;
function Reconcile: Boolean;
procedure Reset;
procedure Fetch(ARow: TFDDatSRow; var AAction: TFDErrorAction;
AColumn: Integer; AFillRowOptions: TFDPhysFillRowOptions); overload;
procedure Update(ARow: TFDDatSRow; var AAction: TFDErrorAction;
AUpdRowOptions: TFDUpdateRowOptions = []; AForceRequest: TFDActionRequest = arFromRow); overload;
procedure Lock(ARow: TFDDatSRow; var AAction: TFDErrorAction;
AUpdRowOptions: TFDUpdateRowOptions = []);
procedure UnLock(ARow: TFDDatSRow; var AAction: TFDErrorAction;
AUpdRowOptions: TFDUpdateRowOptions = []);
procedure FetchGenerators(ARow: TFDDatSRow; var AAction: TFDErrorAction;
AUpdRowOptions: TFDUpdateRowOptions = []);
public
constructor CreateForSchema(AMappings: TFDDAptTableAdapters);
procedure Initialize; override;
destructor Destroy; override;
end;
TFDDAptTableAdapters = class(TInterfacedObject, IUnknown,
IFDDAptTableAdapters)
private
FItems: TFDObjList;
[weak] FSchemaAdapter: TFDDAptSchemaAdapter;
procedure Clear;
function Find(const ATable: TFDPhysMappingName): Integer;
procedure DatSManagerDetaching;
procedure DatSManagerAttached;
protected
// IUnknown
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
// IFDDAptTableAdapters
function GetCount: Integer;
function GetItems(AIndex: Integer): IFDDAptTableAdapter;
function Lookup(const ATable: TFDPhysMappingName): IFDDAptTableAdapter;
function Add(const ASourceRecordSetName: String = '';
const ADatSTableName: String = '';
const AUpdateTableName: String = ''): IFDDAptTableAdapter; overload;
procedure Add(const AAdapter: IFDDAptTableAdapter); overload;
procedure Remove(const ATable: TFDPhysMappingName); overload;
procedure Remove(const AAdapter: IFDDAptTableAdapter); overload;
public
constructor Create(ASchemaAdapter: TFDDAptSchemaAdapter);
destructor Destroy; override;
end;
TFDDAptSchemaAdapter = class(TFDObject, IFDStanObject,
IFDPhysMappingHandler, IFDDAptSchemaAdapter)
private
FDatSManager: TFDDatSManager;
FAdapters: TFDDAptTableAdapters;
FUpdateHandler: IFDDAptUpdateHandler;
FErrorHandler: IFDStanErrorHandler;
FTransaction: IFDPhysTransaction;
FUpdateTransaction: IFDPhysTransaction;
FOptions: IFDStanOptions;
procedure AttachDatSManager(AManager: TFDDatSManager);
procedure ReleaseDatSManager;
procedure GetParentOptions(var AOpts: IFDStanOptions);
protected
// IFDStanObject
function GetName: TComponentName;
function GetParent: IFDStanObject;
procedure BeforeReuse;
procedure AfterReuse;
procedure SetOwner(const AOwner: TObject; const ARole: TComponentName);
// IFDPhysMappingHandler
function MapRecordSet(const ATable: TFDPhysMappingName;
var ASourceID: Integer; var ASourceName, ADatSName, AUpdateName: String;
var ADatSTable: TFDDatSTable): TFDPhysMappingResult;
function MapRecordSetColumn(const ATable, AColumn: TFDPhysMappingName;
var ASourceID: Integer; var ASourceName, ADatSName, AUpdateName: String;
var ADatSColumn: TFDDatSColumn): TFDPhysMappingResult;
// IFDDAptSchemaAdapter
function GetErrorHandler: IFDStanErrorHandler;
procedure SetErrorHandler(const AValue: IFDStanErrorHandler);
function GetUpdateHandler: IFDDAptUpdateHandler;
procedure SetUpdateHandler(const AValue: IFDDAptUpdateHandler);
function GetDatSManager: TFDDatSManager;
procedure SetDatSManager(AValue: TFDDatSManager);
function GetTableAdapters: IFDDAptTableAdapters;
function GetTransaction: IFDPhysTransaction;
procedure SetTransaction(const AValue: IFDPhysTransaction);
function GetUpdateTransaction: IFDPhysTransaction;
procedure SetUpdateTransaction(const AValue: IFDPhysTransaction);
function GetOptions: IFDStanOptions;
function Reconcile: Boolean;
function Update(AMaxErrors: Integer = -1): Integer;
public
procedure Initialize; override;
destructor Destroy; override;
end;
{-------------------------------------------------------------------------------}
{ TFDDAptUpdatesJournalProcessor }
{-------------------------------------------------------------------------------}
constructor TFDDAptUpdatesJournalProcessor.CreateForSchemaAdapter(
ASchemaAdapter: TFDDAptSchemaAdapter);
{$IFDEF FireDAC_MONITOR}
var
i: Integer;
oAdapt: TFDDAptTableAdapter;
{$ENDIF}
begin
inherited Create;
FAdapters := ASchemaAdapter.FAdapters;
FJournal := ASchemaAdapter.GetDatSManager.Updates;
ASSERT(FJournal <> nil);
{$IFDEF FireDAC_MONITOR}
for i := 0 to FAdapters.GetCount - 1 do begin
oAdapt := TFDDAptTableAdapter(FAdapters.FItems.Items[i]);
if (oAdapt.GetSelectCommand <> nil) and (oAdapt.GetSelectCommand.Connection <> nil) then begin
FMonitor := oAdapt.GetSelectCommand.Connection.Monitor;
if FMonitor <> nil then
Break;
end;
end;
{$ENDIF}
FUpdateHandler := ASchemaAdapter.GetUpdateHandler;
FOptions := ASchemaAdapter.GetOptions;
end;
{-------------------------------------------------------------------------------}
constructor TFDDAptUpdatesJournalProcessor.CreateForTableAdapter(
ATableAdapter: TFDDAptTableAdapter);
var
oTab: TFDDatSTable;
{$IFDEF FireDAC_MONITOR}
oConn: IFDPhysConnection;
{$ENDIF}
oCmd: IFDPhysCommand;
begin
inherited Create;
FAdapter := ATableAdapter;
oTab := ATableAdapter.GetDatSTable;
if oTab <> nil then
if oTab.UpdatesRegistry then
FJournal := oTab.Updates
else if (oTab.Manager <> nil) and oTab.Manager.UpdatesRegistry then
FJournal := oTab.Manager.Updates;
ASSERT(FJournal <> nil);
{$IFDEF FireDAC_MONITOR}
ATableAdapter.GetConn(oConn);
if oConn <> nil then
FMonitor := oConn.Monitor;
{$ENDIF}
FUpdateHandler := ATableAdapter.GetUpdateHandler;
ATableAdapter.GetCommand(arSelect, oCmd);
if oCmd <> nil then
FOptions := oCmd.Options;
end;
{-------------------------------------------------------------------------------}
destructor TFDDAptUpdatesJournalProcessor.Destroy;
begin
FOptions := nil;
FAdapter := nil;
FAdapters := nil;
FJournal := nil;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDDAptUpdatesJournalProcessor.GetLimitToTable: TFDDatSTable;
begin
if FAdapter <> nil then
Result := FAdapter.GetDatSTable
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDDAptUpdatesJournalProcessor.LookupTableAdapter(ATable: TFDDatSTable): IFDDAptTableAdapter;
begin
if FAdapter <> nil then begin
ASSERT(FAdapter.GetDatSTable = ATable);
Result := FAdapter as IFDDAptTableAdapter;
end
else if FAdapters <> nil then
Result := FAdapters.Lookup(TFDPhysMappingName.Create(ATable.Name, nkDatS))
else
Result := nil;
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
function TFDDAptUpdatesJournalProcessor.IsTracing: Boolean;
begin
Result := (FMonitor <> nil) and FMonitor.Tracing;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptUpdatesJournalProcessor.Trace(AKind: TFDMoniEventKind;
AStep: TFDMoniEventStep; const AMsg: String; const AArgs: array of const);
begin
if IsTracing then
FMonitor.Notify(AKind, AStep, Self, AMsg, AArgs);
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
function TFDDAptUpdatesJournalProcessor.Process(AMaxErrors: Integer): Integer;
var
eAction: TFDErrorAction;
oRow, oNextRow: TFDDatSRow;
oTabAdapter: IFDDAptTableAdapter;
oWait: IFDGUIxWaitCursor;
lShowCrs: Boolean;
function UpdateNoLocking(AUpdOpts: TFDUpdateRowOptions): TFDErrorAction;
begin
try
Result := eaApplied;
oTabAdapter.Update(oRow, Result, AUpdOpts);
except
Result := eaFail;
end;
end;
function UpdateLocking(AUpdOpts, ALockOpts, AUnlockOpts: TFDUpdateRowOptions): TFDErrorAction;
var
eTmpAction, ePrevAction: TFDErrorAction;
begin
ePrevAction := eaRetry; // impossible output value
try
Result := eaApplied;
oTabAdapter.Lock(oRow, Result, ALockOpts);
try
if Result = eaApplied then begin
oTabAdapter.Update(oRow, Result, AUpdOpts);
ePrevAction := Result;
end;
finally
if Result <> eaApplied then begin
AUnlockOpts := AUnlockOpts + [uoCancelUnlock];
if oRow.RowState = rsDeleted then
AUnlockOpts := AUnlockOpts - [uoNoSrvRecord];
eTmpAction := eaApplied;
oTabAdapter.UnLock(oRow, eTmpAction, AUnlockOpts);
end
else
oTabAdapter.UnLock(oRow, Result, AUnlockOpts);
if ePrevAction <> eaRetry then
Result := ePrevAction;
end;
except
Result := eaFail;
end;
end;
begin
{$IFDEF FireDAC_MONITOR}
if IsTracing then
if LimitToTable <> nil then
Trace(ekAdaptUpdate, esStart, 'Process',
['LimitToTable', LimitToTable.SourceName])
else
Trace(ekAdaptUpdate, esStart, 'Process', []);
try
{$ENDIF}
lShowCrs := (FOptions <> nil) and not FOptions.ResourceOptions.ActualSilentMode;
if lShowCrs then begin
FDCreateInterface(IFDGUIxWaitCursor, oWait);
oWait.StartWait;
end;
Journal.Lock;
try
Result := 0;
oRow := Journal.FirstChange(LimitToTable);
while oRow <> nil do begin
oNextRow := Journal.NextChange(oRow, LimitToTable);
oTabAdapter := LookupTableAdapter(oRow.Table);
if oTabAdapter <> nil then begin
try
case oRow.RowState of
rsInserted: eAction := UpdateNoLocking([uoNoSrvRecord]);
rsDeleted: eAction := UpdateLocking([], [uoDeferredLock], [uoNoSrvRecord]);
rsModified: eAction := UpdateLocking([], [uoDeferredLock], []);
else eAction := eaSkip;
end;
except
eAction := eaFail;
end;
if eAction = eaFail then begin
Inc(Result);
if (AMaxErrors <> -1) and (Result > AMaxErrors) then
Exit;
end;
end;
oRow := oNextRow;
end;
finally
Journal.Unlock;
if lShowCrs then
oWait.StopWait;
end;
{$IFDEF FireDAC_MONITOR}
finally
if IsTracing then
if LimitToTable <> nil then
Trace(ekAdaptUpdate, esEnd, 'Process',
['LimitToTable', LimitToTable.SourceName])
else
Trace(ekAdaptUpdate, esEnd, 'Process', []);
end;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
function TFDDAptUpdatesJournalProcessor.Reconcile: Boolean;
var
oRow, oNextRow: TFDDatSRow;
eAction: TFDDAptReconcileAction;
oTabAdapter: IFDDAptTableAdapter;
eErrAction: TFDErrorAction;
oWait: IFDGUIxWaitCursor;
lShowCrs: Boolean;
lAutoCommit: Boolean;
begin
{$IFDEF FireDAC_MONITOR}
if IsTracing then
if LimitToTable <> nil then
Trace(ekAdaptUpdate, esStart, 'Reconcile',
['LimitToTable', LimitToTable.SourceName])
else
Trace(ekAdaptUpdate, esStart, 'Reconcile', []);
try
{$ENDIF}
lShowCrs := (FOptions <> nil) and not FOptions.ResourceOptions.ActualSilentMode;
lAutoCommit := (FOptions <> nil) and FOptions.UpdateOptions.AutoCommitUpdates;
if lShowCrs then begin
FDCreateInterface(IFDGUIxWaitCursor, oWait);
oWait.StartWait;
end;
if Journal <> nil then
Journal.Lock;
try
if (Journal = nil) or not Assigned(FUpdateHandler) then begin
if lAutoCommit and (Journal <> nil) then
Journal.AcceptChanges(LimitToTable);
Result := True;
Exit;
end;
oRow := Journal.FirstChange(LimitToTable);
while oRow <> nil do begin
oNextRow := Journal.NextChange(oRow, LimitToTable);
oTabAdapter := LookupTableAdapter(oRow.Table);
if (oTabAdapter <> nil) and oRow.HasErrors then begin
if lShowCrs then
oWait.PushWait;
try
eAction := raSkip;
FUpdateHandler.ReconcileRow(oRow, eAction);
finally
if lShowCrs then
oWait.PopWait;
end;
case eAction of
raSkip:
;
raAbort:
Break;
raMerge:
begin
oRow.ClearErrors;
oRow.AcceptChanges;
end;
raCorrect:
oRow.ClearErrors;
raCancel:
begin
oRow.ClearErrors;
oRow.RejectChanges;
end;
raRefresh:
begin
oRow.ClearErrors;
eErrAction := eaApplied;
oTabAdapter.Fetch(oRow, eErrAction, -1,
[foClear] + FDGetFillRowOptions(oTabAdapter.Options.FetchOptions));
end;
end;
end
else if lAutoCommit then
oRow.AcceptChanges;
oRow := oNextRow;
end;
Result := not Journal.HasChanges(LimitToTable);
finally
if Journal <> nil then
Journal.Unlock;
if lShowCrs then
oWait.StopWait;
end;
{$IFDEF FireDAC_MONITOR}
finally
if IsTracing then
if LimitToTable <> nil then
Trace(ekAdaptUpdate, esEnd, 'Reconcile',
['LimitToTable', LimitToTable.SourceName])
else
Trace(ekAdaptUpdate, esEnd, 'Reconcile', []);
end;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
{ TFDDAptTableAdapterMappingHandler }
{-------------------------------------------------------------------------------}
type
TFDDAptTableAdapterMappingHandler = class(TInterfacedObject, IFDPhysMappingHandler)
private
FTableAdapter: TFDDAptTableAdapter;
protected
// IFDPhysMappingHandler
function MapRecordSet(const ATable: TFDPhysMappingName;
var ASourceID: Integer; var ASourceName, ADatSName, AUpdateName: String;
var ADatSTable: TFDDatSTable): TFDPhysMappingResult;
function MapRecordSetColumn(const ATable, AColumn: TFDPhysMappingName;
var ASourceID: Integer; var ASourceName, ADatSName, AUpdateName: String;
var ADatSColumn: TFDDatSColumn): TFDPhysMappingResult;
public
constructor Create(ATableAdapter: TFDDAptTableAdapter);
end;
{-------------------------------------------------------------------------------}
constructor TFDDAptTableAdapterMappingHandler.Create(ATableAdapter: TFDDAptTableAdapter);
begin
inherited Create;
FTableAdapter := ATableAdapter;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapterMappingHandler.MapRecordSet(const ATable: TFDPhysMappingName;
var ASourceID: Integer; var ASourceName, ADatSName, AUpdateName: String;
var ADatSTable: TFDDatSTable): TFDPhysMappingResult;
begin
Result := FTableAdapter.MapRecordSet(ATable, ASourceID, ASourceName, ADatSName,
AUpdateName, ADatSTable);
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapterMappingHandler.MapRecordSetColumn(const ATable, AColumn: TFDPhysMappingName;
var ASourceID: Integer; var ASourceName, ADatSName, AUpdateName: String;
var ADatSColumn: TFDDatSColumn): TFDPhysMappingResult;
begin
Result := FTableAdapter.MapRecordSetColumn(ATable, AColumn, ASourceID, ASourceName, ADatSName,
AUpdateName, ADatSColumn);
end;
{-------------------------------------------------------------------------------}
{ TFDDAptTableAdapter }
{-------------------------------------------------------------------------------}
constructor TFDDAptTableAdapter.CreateForSchema(AMappings: TFDDAptTableAdapters);
begin
inherited Create;
FMappings := AMappings;
if FMappings <> nil then
FMappings.FItems.Add(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.Initialize;
begin
inherited Initialize;
FBuffer := TFDBuffer.Create;
FColMappings := TFDDAptColumnMappings.Create(nil);
SetLength(FCommands, Integer(arFetchGenerators) - Integer(arSelect) + 1);
FSourceRecordSetID := -1;
FMappings := nil;
end;
{-------------------------------------------------------------------------------}
destructor TFDDAptTableAdapter.Destroy;
begin
ReleaseDatSTable;
SetDatSManager(nil);
FDFreeAndNil(FBuffer);
SetLength(FCommands, 0);
FDFreeAndNil(FColMappings);
FErrorHandler := nil;
FUpdateHandler := nil;
if FMappings <> nil then begin
FMappings.FItems.Remove(Self);
FMappings := nil;
end;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter._AddRef: Integer;
begin
Result := FDAddRef;
if FMappings <> nil then
FMappings._AddRef;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter._Release: Integer;
begin
Result := FDDecRef;
if FMappings <> nil then
Result := FMappings._Release
else if Result = 0 then
FDFree(Self);
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetObj: TObject;
begin
Result := Self;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetSchemaAdapter: TFDDAptSchemaAdapter;
begin
if FMappings <> nil then
Result := FMappings.FSchemaAdapter
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetTableMappings: IFDDAptTableAdapters;
begin
if FMappings <> nil then
Result := FMappings as IFDDAptTableAdapters
else
Result := nil;
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
// Tracing
function TFDDAptTableAdapter.IsTracing: Boolean;
var
oConn: IFDPhysConnection;
begin
GetConn(oConn);
Result := (oConn <> nil) and oConn.Tracing;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.Trace(AKind: TFDMoniEventKind;
AStep: TFDMoniEventStep; const AMsg: String; const AArgs: array of const);
var
oConn: IFDPhysConnection;
begin
GetConn(oConn);
if (oConn <> nil) and oConn.Tracing then
oConn.Monitor.Notify(AKind, AStep, Self, AMsg, AArgs);
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetName: TComponentName;
begin
Result := GetSourceRecordSetName + ': ' + ClassName + '($' +
IntToHex(Integer(Self), 8) + ')';
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetParent: IFDStanObject;
begin
if (FMappings = nil) or (FMappings.FSchemaAdapter = nil) then
Result := nil
else
Result := FMappings.FSchemaAdapter as IFDStanObject;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.AfterReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.BeforeReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetOwner(const AOwner: TObject;
const ARole: TComponentName);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
// Get/Set props
function TFDDAptTableAdapter.GetOptions: IFDStanOptions;
var
oCmd: IFDPhysCommand;
begin
oCmd := GetSelectCommand;
if oCmd = nil then
Result := nil
else
Result := oCmd.Options;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetColumnMappings: TFDDAptColumnMappings;
begin
Result := FColMappings;
Result.DatSTable := GetDatSTable;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetSourceRecordSetID: Integer;
begin
Result := FSourceRecordSetID;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetSourceRecordSetID(const AValue: Integer);
begin
if FSourceRecordSetID <> AValue then begin
FSourceRecordSetID := AValue;
if AValue >= 0 then
FSourceRecordSetName := '';
end;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetSourceRecordSetName: String;
var
oCmd: IFDPhysCommand;
begin
Result := FSourceRecordSetName;
oCmd := GetSelectCommand;
if (Result = '') and (oCmd <> nil) then
Result := oCmd.SourceObjectName;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetSourceRecordSetName(const AValue: String);
begin
if FSourceRecordSetName <> AValue then begin
FSourceRecordSetName := AValue;
if AValue <> '' then
FSourceRecordSetID := -1;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetUpdateTableName: String;
var
oCmd: IFDPhysCommand;
begin
Result := FUpdateTableName;
oCmd := GetSelectCommand;
if (Result = '') and (oCmd <> nil) then
Result := (GetSelectCommand.Options.UpdateOptions as TFDBottomUpdateOptions).UpdateTableName;
if (Result = '') and (FDatSTable <> nil) then
Result := FDatSTable.ActualOriginName;
if Result = '' then
Result := GetSourceRecordSetName;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetUpdateTableName(const AValue: String);
begin
FUpdateTableName := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetDatSTableName: String;
begin
Result := FDatSTableName;
if (Result = '') and (FDatSTable <> nil) then
Result := FDatSTable.Name;
if Result = '' then
Result := GetSourceRecordSetName;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.ReleaseDatSTable;
begin
if FDatSTable <> nil then begin
FDatSTable.RemRef;
FDatSTable := nil;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.DetachDatSTable;
var
oTab: TFDDatSTable;
begin
// Here was call the GetDatSTable, but it leads to TFDDatSTable leak
// in case, when (FDatSTable = nil) and (GetDatSTableName <> '').
// Because table will be removed from oTab.Manager.Tables, but
// TFDDAptTableAdapter ReleaseDatSTable releases only FDatSTable.
oTab := FDatSTable;
if (oTab <> nil) and (oTab.Manager <> nil) and
(oTab.Manager = FMappings.FSchemaAdapter.GetDatSManager) then
oTab.Manager.Tables.Remove(oTab, True);
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.AcquireDatSTable(ATable: TFDDatSTable);
begin
if FDatSTable <> ATable then begin
ReleaseDatSTable;
if ATable <> nil then
ATable.AddRef;
FDatSTable := ATable;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.AttachDatSTable;
var
oTab: TFDDatSTable;
oMan: TFDDatSManager;
begin
oTab := GetDatSTable;
oMan := FMappings.FSchemaAdapter.GetDatSManager;
if (oTab <> nil) and (oTab.Manager <> oMan) then begin
if oTab.Manager <> nil then
oTab.Manager.Tables.Remove(oTab, True);
if oMan <> nil then
oMan.Tables.Add(oTab);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetDatSTableName(const AValue: String);
begin
if FDatSTableName <> AValue then begin
FDatSTableName := AValue;
ReleaseDatSTable;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetDatSTable: TFDDatSTable;
var
i: Integer;
oTabs: TFDDatSTableList;
sName: String;
begin
if FDatSTable <> nil then
Result := FDatSTable
else begin
Result := nil;
if GetSchemaAdapter <> nil then begin
sName := GetDatSTableName;
if sName <> '' then begin
oTabs := GetSchemaAdapter.GetDatSManager.Tables;
i := oTabs.IndexOfName(sName);
if i <> -1 then
Result := oTabs.ItemsI[i];
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetDatSTable(AValue: TFDDatSTable);
begin
if FDatSTable <> AValue then begin
AcquireDatSTable(AValue);
FDatSTableName := '';
end;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetMetaInfoMergeMode: TFDPhysMetaInfoMergeMode;
begin
Result := FMetaInfoMergeMode;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetMetaInfoMergeMode(const AValue: TFDPhysMetaInfoMergeMode);
begin
FMetaInfoMergeMode := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetDatSManager: TFDDatSManager;
begin
if GetSchemaAdapter <> nil then
Result := GetSchemaAdapter.GetDatSManager
else
Result := FDatSManager;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetDatSManager(AValue: TFDDatSManager);
begin
if FDatSManager <> AValue then begin
SetDatSTable(nil);
if FDatSManager <> nil then
FDatSManager.RemRef;
FDatSManager := AValue;
if FDatSManager <> nil then
FDatSManager.AddRef;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.GetCommand(AReq: TFDActionRequest; out ACmd: IFDPhysCommand);
begin
ACmd := FCommands[Integer(AReq) - Integer(arSelect)];
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetSelectCommand: IFDPhysCommand;
begin
GetCommand(arSelect, Result);
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetDeleteCommand: IFDPhysCommand;
begin
GetCommand(arDelete, Result);
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetFetchRowCommand: IFDPhysCommand;
begin
GetCommand(arFetchRow, Result);
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetInsertCommand: IFDPhysCommand;
begin
GetCommand(arInsert, Result);
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetLockCommand: IFDPhysCommand;
begin
GetCommand(arLock, Result);
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetUnlockCommand: IFDPhysCommand;
begin
GetCommand(arUnlock, Result);
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetUpdateCommand: IFDPhysCommand;
begin
GetCommand(arUpdate, Result);
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.UpdateCommands(AReason: TFDDAptUpdateCommandReason);
var
i: Integer;
oCmd: IFDPhysCommand;
begin
if (FGeneratedCommands = []) and (AReason = urSetSelect) then
Exit;
for i := 0 to Length(FCommands) - 1 do begin
oCmd := FCommands[i];
if TFDActionRequest(i + Integer(arSelect)) in FGeneratedCommands then begin
Exclude(FGeneratedCommands, TFDActionRequest(i + Integer(arSelect)));
if oCmd <> nil then
FCommands[i] := nil;
end
else if oCmd <> nil then
case AReason of
urSetSelect:
;
urSetErrorHandler:
begin
oCmd.ErrorHandler := GetErrorHandler;
oCmd.MappingHandler := TFDDAptTableAdapterMappingHandler.Create(Self) as
IFDPhysMappingHandler;
end;
urReset:
oCmd.Disconnect;
urSetTransaction:
if (TFDActionRequest(i + Integer(arSelect)) = arSelect) and
(oCmd.Transaction <> GetTransaction) then begin
oCmd.Disconnect;
oCmd.Transaction := GetTransaction;
end;
urSetUpdateTransaction:
if (TFDActionRequest(i + Integer(arSelect)) <> arSelect) and
(oCmd.Transaction <> GetUpdateTransaction) then begin
oCmd.Disconnect;
oCmd.Transaction := GetUpdateTransaction;
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.InternalSetCommand(AReq: TFDActionRequest; const ACmd: IFDPhysCommand);
begin
if Length(FCommands) <> 0 then
FCommands[Integer(AReq) - Integer(arSelect)] := ACmd;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.SetCommand(AReq: TFDActionRequest; const ACmd: IFDPhysCommand): Boolean;
var
oCmd: IFDPhysCommand;
begin
Result := False;
GetCommand(AReq, oCmd);
if oCmd <> ACmd then begin
if oCmd <> nil then begin
oCmd.ErrorHandler := nil;
oCmd.MappingHandler := nil;
end;
InternalSetCommand(AReq, ACmd);
if ACmd <> nil then begin
ACmd.ErrorHandler := GetErrorHandler;
ACmd.MappingHandler := TFDDAptTableAdapterMappingHandler.Create(Self) as
IFDPhysMappingHandler;
Exclude(FGeneratedCommands, AReq);
end
else
Include(FGeneratedCommands, AReq);
Result := True;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.GetConn(out AConn: IFDPhysConnection);
var
oCmd: IFDPhysCommand;
begin
oCmd := GetSelectCommand;
if oCmd <> nil then
AConn := oCmd.Connection
else
AConn := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.GetUpdTx(out ATx: IFDPhysTransaction);
var
oCmd: IFDPhysCommand;
oConn: IFDPhysConnection;
begin
ATx := GetUpdateTransaction;
if ATx = nil then begin
ATx := GetTransaction;
if ATx = nil then begin
oCmd := GetSelectCommand;
if oCmd <> nil then begin
ATx := oCmd.Transaction;
if ATx = nil then begin
oConn := oCmd.Connection;
if oConn <> nil then
ATx := oConn.Transaction;
end;
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetSelectCommand(const ACmd: IFDPhysCommand);
begin
if SetCommand(arSelect, ACmd) then
UpdateCommands(urSetSelect);
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetDeleteCommand(const ACmd: IFDPhysCommand);
begin
SetCommand(arDelete, ACmd);
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetFetchRowCommand(const ACmd: IFDPhysCommand);
begin
SetCommand(arFetchRow, ACmd);
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetInsertCommand(const ACmd: IFDPhysCommand);
begin
SetCommand(arInsert, ACmd);
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetLockCommand(const ACmd: IFDPhysCommand);
begin
SetCommand(arLock, ACmd);
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetUnlockCommand(const ACmd: IFDPhysCommand);
begin
SetCommand(arUnlock, ACmd);
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetUpdateCommand(const ACmd: IFDPhysCommand);
begin
SetCommand(arUpdate, ACmd);
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.CheckSelectCommand;
begin
if GetSelectCommand = nil then
FDException(Self, [S_FD_LDApt], er_FD_DAptNoSelectCmd, []);
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetTransaction: IFDPhysTransaction;
var
oManAdapt: TFDDAptSchemaAdapter;
begin
if FTransaction <> nil then
Result := FTransaction
else begin
oManAdapt := GetSchemaAdapter;
if oManAdapt <> nil then
Result := oManAdapt.GetTransaction
else
Result := nil;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetTransaction(const AValue: IFDPhysTransaction);
begin
if FTransaction <> AValue then begin
FTransaction := AValue;
UpdateCommands(urSetTransaction);
end;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetUpdateTransaction: IFDPhysTransaction;
var
oManAdapt: TFDDAptSchemaAdapter;
begin
if FUpdateTransaction <> nil then
Result := FUpdateTransaction
else begin
oManAdapt := GetSchemaAdapter;
if oManAdapt <> nil then
Result := oManAdapt.GetUpdateTransaction
else
Result := nil;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetUpdateTransaction(const AValue: IFDPhysTransaction);
begin
if FUpdateTransaction <> AValue then begin
FUpdateTransaction := AValue;
UpdateCommands(urSetUpdateTransaction);
end;
end;
{-------------------------------------------------------------------------------}
// Exception handling
procedure TFDDAptTableAdapter.HandleException(const AInitiator: IFDStanObject;
var AException: Exception);
begin
{$IFDEF FireDAC_MONITOR}
if not (AException is EFDDBEngineException) and IsTracing then
Trace(ekError, esProgress, AException.Message, []);
{$ENDIF}
if Assigned(GetErrorHandler()) then
GetErrorHandler().HandleException(AInitiator, AException);
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetErrorHandler: IFDStanErrorHandler;
var
oManAdapt: TFDDAptSchemaAdapter;
begin
if FErrorHandler <> nil then
Result := FErrorHandler
else begin
oManAdapt := GetSchemaAdapter;
if oManAdapt <> nil then
Result := oManAdapt.GetErrorHandler
else
Result := nil;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetErrorHandler(const AValue: IFDStanErrorHandler);
begin
FErrorHandler := AValue;
UpdateCommands(urSetErrorHandler);
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetUpdateHandler: IFDDAptUpdateHandler;
var
oManAdapt: TFDDAptSchemaAdapter;
begin
if FUpdateHandler <> nil then
Result := FUpdateHandler
else begin
oManAdapt := GetSchemaAdapter;
if oManAdapt <> nil then
Result := oManAdapt.GetUpdateHandler
else
Result := nil;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetUpdateHandler(const AValue: IFDDAptUpdateHandler);
begin
FUpdateHandler := AValue;
end;
{-------------------------------------------------------------------------------}
// Mapping handling
function TFDDAptTableAdapter.MatchRecordSet(const ATable: TFDPhysMappingName): Boolean;
var
oTab: TFDDatSTable;
begin
case ATable.FKind of
nkID:
Result := GetSourceRecordSetID = ATable.FID;
nkSource:
Result := {$IFDEF FireDAC_NOLOCALE_META} CompareText {$ELSE} AnsiCompareText {$ENDIF}
(ATable.FName, GetSourceRecordSetName) = 0;
nkDatS:
Result := {$IFDEF FireDAC_NOLOCALE_META} CompareText {$ELSE} AnsiCompareText {$ENDIF}
(ATable.FName, GetDatSTableName) = 0;
nkObj:
begin
oTab := TFDDatSTable(ATable.FObj);
Result :=
(GetDatSTable <> nil) and (GetDatSTable = oTab) or
(GetSourceRecordSetID <> -1) and (GetSourceRecordSetID = oTab.SourceID) or
(GetSourceRecordSetName <> '') and (
{$IFDEF FireDAC_NOLOCALE_META} CompareText {$ELSE} AnsiCompareText {$ENDIF}
(GetSourceRecordSetName, oTab.SourceName) = 0) or
(GetDatSTableName <> '') and (
{$IFDEF FireDAC_NOLOCALE_META} CompareText {$ELSE} AnsiCompareText {$ENDIF}
(GetDatSTableName, oTab.Name) = 0);
end;
nkDefault:
Result := True;
else
Result := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure FDGetRecordSetInfo(const AAdapter: IFDDAptTableAdapter;
var ASourceID: Integer; var ASourceName, ADatSName, AUpdateName: String;
var ADatSTable: TFDDatSTable);
var
oTab: TFDDatSTable;
sName: String;
begin
if AAdapter.SourceRecordSetID <> -1 then
ASourceID := AAdapter.SourceRecordSetID;
sName := AAdapter.SourceRecordSetName;
if sName <> '' then
ASourceName := sName;
sName := AAdapter.DatSTableName;
if sName <> '' then
ADatSName := sName;
sName := AAdapter.UpdateTableName;
if sName <> '' then
AUpdateName := sName;
oTab := AAdapter.DatSTable;
if oTab <> nil then
ADatSTable := oTab;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.MapRecordSet(const ATable: TFDPhysMappingName;
var ASourceID: Integer; var ASourceName, ADatSName, AUpdateName: String;
var ADatSTable: TFDDatSTable): TFDPhysMappingResult;
begin
if MatchRecordSet(ATable) then begin
Result := mrMapped;
FDGetRecordSetInfo(Self as IFDDAptTableAdapter, ASourceID,
ASourceName, ADatSName, AUpdateName, ADatSTable);
end
else if (GetSchemaAdapter <> nil) and (ATable.FKind <> nkDefault) then
Result := GetSchemaAdapter.MapRecordSet(ATable, ASourceID,
ASourceName, ADatSName, AUpdateName, ADatSTable)
else
Result := mrNotMapped;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.MapRecordSetColumn(const ATable, AColumn: TFDPhysMappingName;
var ASourceID: Integer; var ASourceName, ADatSName, AUpdateName: String;
var ADatSColumn: TFDDatSColumn): TFDPhysMappingResult;
var
oColMap: TFDDAptColumnMapping;
begin
Result := mrNotMapped;
if MatchRecordSet(ATable) then
if (GetColumnMappings = nil) or (GetColumnMappings.Count = 0) then
Result := mrDefault
else begin
oColMap := GetColumnMappings.Lookup(AColumn);
if oColMap <> nil then begin
Result := mrMapped;
FDGetRecordSetColumnInfo(oColMap, ASourceID, ASourceName, ADatSName,
AUpdateName, ADatSColumn);
end;
end
else if GetSchemaAdapter <> nil then
Result := GetSchemaAdapter.MapRecordSetColumn(ATable, AColumn,
ASourceID, ASourceName, ADatSName, AUpdateName, ADatSColumn);
end;
{-------------------------------------------------------------------------------}
// Command generation
procedure TFDDAptTableAdapter.ParName2Col(ABaseRow: TFDDatSRow; const AName: String;
var ACol: TFDDatSColumn; var ARow: TFDDatSRow; var AVersion: Integer);
var
i, i1, iCol, iKind, iUCNameLen: Integer;
sUCName: String;
begin
sUCName := UpperCase(AName);
iUCNameLen := Length(sUCName);
if StrLIComp(PChar(sUCName), PChar('NEW_P$_'), 7) = 0 then begin
iKind := 1;
AVersion := 1;
i := 6;
end
else if StrLComp(PChar(sUCName), PChar('OLD_P$_'), 7) = 0 then begin
iKind := 1;
AVersion := -1;
i := 6;
end
else if StrLComp(PChar(sUCName), PChar('NEW_'), 4) = 0 then begin
iKind := 2;
AVersion := 1;
i := 6;
end
else if StrLComp(PChar(sUCName), PChar('OLD_'), 4) = 0 then begin
iKind := 2;
AVersion := -1;
i := 6;
end
else begin
iKind := 0;
AVersion := 0;
i := 1;
end;
ACol := nil;
ARow := nil;
if iKind = 1 then begin
while (i + 2 <= iUCNameLen) and (sUCName[i] <> '#') and (sUCName[i] = '$') and (sUCName[i + 1] = '_') do begin
Inc(i, 2);
i1 := i;
while (i <= iUCNameLen) and (sUCName[i] >= '0') and (sUCName[i] <= '9') do
Inc(i);
iCol := StrToInt(Copy(sUCName, i1, i - i1));
if (ACol = nil) and (ARow = nil) then begin
ARow := ABaseRow;
ACol := ARow.Table.Columns[iCol];
end
else begin
if ARow <> nil then
ARow := ARow.NestedRow[ACol.Index];
ACol := ACol.NestedTable.Columns[iCol];
end;
end;
end
else if iKind = 2 then begin
ARow := ABaseRow;
// See comment in TFDPhysCommandGenerator.AddColumnParam
i := Pos('$#', sUCName);
if i = 0 then
i := MAXINT;
ACol := ARow.Table.Columns.ColumnByName(Copy(sUCName, 5, i - 5));
end
else if iKind = 0 then begin
ARow := ABaseRow;
i := ARow.Table.Columns.IndexOfName(sUCName);
if i <> -1 then
ACol := ARow.Table.Columns[i];
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.SetParamsFromRow(AParams: TFDParams; ARow: TFDDatSRow);
var
i, j, iVersion: Integer;
eRowVersion: TFDDatSRowVersion;
oPar: TFDParam;
oCol, oRefCol: TFDDatSColumn;
oRow: TFDDatSRow;
pBuff: Pointer;
iLen, iFldSize: LongWord;
iFldPrec, iFldScale: Integer;
eFldType: TFieldType;
oFmtOpts: TFDFormatOptions;
begin
oFmtOpts := GetOptions.FormatOptions;
for i := 0 to AParams.Count - 1 do begin
oPar := AParams[I];
if oPar.ParamType in [ptUnknown, ptInput, ptInputOutput] then begin
ParName2Col(ARow, oPar.Name, oCol, oRow, iVersion);
if oCol <> nil then begin
if oCol.DataType = dtArrayRef then
oRefCol := oCol.NestedTable.Columns[0]
else
oRefCol := oCol;
oFmtOpts.ColumnDef2FieldDef(oRefCol.DataType, oRefCol.Size,
oRefCol.Precision, oRefCol.Scale, oRefCol.Attributes, eFldType,
iFldSize, iFldPrec, iFldScale);
if (oPar.DataType = ftUnknown) or (oPar.DataType <> eFldType) then begin
oPar.DataType := eFldType;
if oPar.FDDataType = dtUnknown then
oPar.FDDataType := oRefCol.DataType;
oPar.Precision := iFldPrec;
oPar.NumericScale := iFldScale;
oPar.Size := iFldSize;
end;
case iVersion of
-1: eRowVersion := rvOriginal;
1: eRowVersion := rvCurrent;
else eRowVersion := rvDefault;
end;
if oRow = nil then
oPar.SetData(nil, 0, -1)
else if oCol.DataType = dtArrayRef then begin
oRow := oRow.NestedRow[oCol.Index];
oPar.ArrayType := atTable;
oPar.ArraySize := oRow.Table.Columns.Count - 1;
oPar.DataTypeName := oCol.SourceDataTypeName;
for j := 0 to oPar.ArraySize - 1 do begin
oRow.GetData(j, eRowVersion, pBuff, 0, iLen, False);
oPar.SetData(pBuff, iLen, j);
end;
end
else begin
oRow.GetData(oCol.Index, eRowVersion, pBuff, 0, iLen, False);
oPar.SetData(pBuff, iLen, -1);
end;
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.MergeRows(const ACommand: IFDPhysCommand;
ABaseRow, AFetchedRow: TFDDatSRow; AClearRow: Boolean);
var
i, iBaseCol: Integer;
oBaseCols, oFetchedCols: TFDDatSColumnList;
pBuff: Pointer;
iLen: LongWord;
lRefreshing, lLoadingData, lCtrlEditing: Boolean;
rState: TFDDatSLoadState;
begin
lRefreshing := (ABaseRow.RowState = rsUnchanged);
lLoadingData := False;
lCtrlEditing := not (ABaseRow.RowState in [rsDetached, rsForceWrite]) or AClearRow;
ABaseRow.Table.BeginLoadData(rState, lmRefreshing);
try
try
oBaseCols := ABaseRow.Table.Columns;
oFetchedCols := AFetchedRow.Table.Columns;
for i := 0 to oFetchedCols.Count - 1 do begin
iBaseCol := oBaseCols.IndexOfSourceName(oFetchedCols[i].SourceName);
if iBaseCol <> -1 then begin
if not lLoadingData then begin
lLoadingData := True;
if lCtrlEditing then begin
ABaseRow.BeginEdit;
if AClearRow then
ABaseRow.Erase;
end;
end;
if oBaseCols.ItemsI[iBaseCol].DataType = oFetchedCols.ItemsI[i].DataType then begin
pBuff := nil;
iLen := 0;
AFetchedRow.GetData(i, rvDefault, pBuff, 0, iLen, False);
ABaseRow.SetData(iBaseCol, pBuff, iLen);
end
else
ABaseRow.SetData(iBaseCol, AFetchedRow.GetData(i, rvDefault));
if caAutoInc in oBaseCols.ItemsI[iBaseCol].ActualAttributes then
ACommand.Connection.SaveLastAutoGenValue(AFetchedRow.GetData(i, rvDefault));
end;
end;
if lLoadingData and lCtrlEditing then begin
ABaseRow.EndEdit;
if lRefreshing then
ABaseRow.AcceptChanges(False);
end;
except
if lLoadingData and lCtrlEditing then
ABaseRow.CancelEdit;
raise;
end;
finally
ABaseRow.Table.EndLoadData(rState);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.MergeRowFromParams(const ACommand: IFDPhysCommand;
ABaseRow: TFDDatSRow; AFetchedParams: TFDParams; AClearRow: Boolean);
var
i: Integer;
oCol: TFDDatSColumn;
oRow: TFDDatSRow;
iVersion: Integer;
lRefreshing, lLoadingData, lCtrlEditing: Boolean;
rState: TFDDatSLoadState;
begin
lRefreshing := (ABaseRow.RowState = rsUnchanged);
lLoadingData := False;
lCtrlEditing := not (ABaseRow.RowState in [rsDetached, rsForceWrite]) or AClearRow;
ABaseRow.Table.BeginLoadData(rState, lmRefreshing);
try
try
for i := 0 to AFetchedParams.Count - 1 do
if AFetchedParams[i].ParamType in [ptOutput, ptInputOutput] then begin
oCol := nil;
oRow := nil;
iVersion := -1;
ParName2Col(ABaseRow, AFetchedParams[i].Name, oCol, oRow, iVersion);
if (oRow <> nil) and (oCol <> nil) and (iVersion = 1) then begin
if not lLoadingData then begin
lLoadingData := True;
if lCtrlEditing then begin
ABaseRow.BeginEdit;
if AClearRow then
ABaseRow.Erase;
end;
end;
oRow.SetData(oCol.Index, AFetchedParams[i].Value);
if caAutoInc in oCol.ActualAttributes then
ACommand.Connection.SaveLastAutoGenValue(AFetchedParams[i].Value);
end;
end;
if lLoadingData and lCtrlEditing then begin
ABaseRow.EndEdit;
if lRefreshing then
ABaseRow.AcceptChanges(False);
end;
except
if lLoadingData and lCtrlEditing then
ABaseRow.CancelEdit;
raise;
end;
finally
ABaseRow.Table.EndLoadData(rState);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.ProcessRequest(const ACommand: IFDPhysCommand;
ARow: TFDDatSRow; ARequest: TFDUpdateRequest; AUpdRowOptions: TFDUpdateRowOptions;
AFillRowOptions: TFDPhysFillRowOptions; AWrapByTX: Boolean);
var
oRes: TFDResourceOptions;
oFtch: TFDFetchOptions;
oUpd: TFDUpdateOptions;
oConn: IFDPhysConnection;
oConnMeta: IFDPhysConnectionMetadata;
oTab: TFDDatSTable;
lOpen, lClearErrorHandler: Boolean;
procedure ErrorRecordIsDeleted(ARowsCount: Integer);
const
SOper: array[TFDUpdateRequest] of String = ('Insert', 'Update',
'Delete', 'Lock', 'Unlock', 'Fetch', 'UpdateHBlobs', 'DeleteAll',
'FetchGenerators');
var
s, sReasons: String;
begin
s := LowerCase(SOper[ARequest]);
if s[Length(s)] = 'e' then
s := s + 'd'
else
s := s + 'ed';
if ACommand.Connection.Messages <> nil then
sReasons := ACommand.Connection.Messages.Errors[0].Message
else
sReasons := S_FD_DAptRecordIsDeletedReasons;
FDException(Self, [S_FD_LDApt], er_FD_DAptRecordIsDeleted,
[SOper[ARequest], s, ARowsCount, sReasons]);
end;
begin
{$IFDEF FireDAC_MONITOR}
if IsTracing then
if ARow <> nil then
Trace(ekAdaptUpdate, esStart, 'ProcessRequest',
['ARow.Table.Name', ARow.Table.SourceName])
else
Trace(ekAdaptUpdate, esStart, 'ProcessRequest', []);
try
{$ENDIF}
oRes := ACommand.Options.ResourceOptions;
if oRes.CmdExecMode = amAsync then
oRes.CmdExecMode := amBlocking;
if ARequest = arLock then begin
oUpd := ACommand.Options.UpdateOptions;
if (oUpd.LockMode = lmPessimistic) and not oUpd.LockWait then begin
GetConn(oConn);
oConn.CreateMetadata(oConnMeta);
if not oConnMeta.LockNoWait and oConnMeta.AsyncAbortSupported then
oRes.CmdExecTimeout := 1000
else
oRes.CmdExecTimeout := $FFFFFFFF;
end;
end;
if ARequest = arFetchRow then begin
oFtch := ACommand.Options.FetchOptions;
if foBlobs in AFillRowOptions then
oFtch.Items := oFtch.Items + [fiBlobs];
if foDetails in AFillRowOptions then
oFtch.Items := oFtch.Items + [fiDetails];
end;
if ACommand.ErrorHandler = nil then begin
lClearErrorHandler := True;
ACommand.ErrorHandler := Self as IFDStanErrorHandler;
end
else
lClearErrorHandler := False;
try
try
ACommand.CloseAll;
if ACommand.CommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs] then begin
if ACommand.State = csInactive then
ACommand.Prepare;
SetParamsFromRow(ACommand.Params, ARow);
end
else begin
SetParamsFromRow(ACommand.Params, ARow);
if ACommand.State = csInactive then
ACommand.Prepare;
end;
if GetSelectCommand <> nil then
ACommand.SourceRecordSetName := GetSelectCommand.SourceRecordSetName;
lOpen := (ACommand.CommandKind in [skSelect, skSelectForLock, skSelectForUnLock,
skStoredProcWithCrs]);
while ACommand.State <> csInactive do begin
if lOpen then begin
ACommand.Open;
if ACommand.State <> csOpen then
Break;
oTab := TFDDatSTable.Create;
try
ACommand.Define(oTab, mmReset);
ACommand.Fetch(oTab, True);
if ARequest = arLock then begin
// Dont compare server side SELECT item values with client
// columns values - there may be precision lost related errors.
// Instead use correct UpdateMode to build limited WHERE and
// lets server perform a comparison.
if oTab.Rows.Count <> 1 then
if ACommand.Options.UpdateOptions.CountUpdatedRecords then
ErrorRecordIsDeleted(oTab.Rows.Count);
end
else if ARequest in [arFetchRow, arInsert, arUpdate, arFetchGenerators] then begin
if oTab.Rows.Count <> 1 then
if ACommand.Options.UpdateOptions.CountUpdatedRecords then
ErrorRecordIsDeleted(oTab.Rows.Count);
if oTab.Rows.Count > 0 then
MergeRows(ACommand, ARow, oTab.Rows[0], foClear in AFillRowOptions);
end;
finally
FDFree(oTab);
end;
end
else begin
ACommand.Execute;
if ACommand.RowsAffectedReal and (ACommand.RowsAffected <> 1) and
ACommand.Options.UpdateOptions.CountUpdatedRecords then
ErrorRecordIsDeleted(ACommand.RowsAffected);
if ARequest in [arInsert, arUpdate, arFetchRow, arUpdateHBlobs] then
MergeRowFromParams(ACommand, ARow, ACommand.Params, foClear in AFillRowOptions);
end;
ACommand.NextRecordSet := True;
lOpen := True;
end;
except
on E: EFDDBEngineException do begin
if (ARequest in [arInsert, arUpdate, arDelete, arLock, arUnlock,
arUpdateHBlobs, arFetchGenerators]) and
(E.Kind <> ekServerGone) then
ARow.RowError := E;
if E.Kind in [ekNoDataFound, ekTooManyRows] then begin
if ACommand.Options.UpdateOptions.CountUpdatedRecords then
ErrorRecordIsDeleted(ACommand.RowsAffected);
end
else
raise;
end;
on E: EFDException do begin
if ARequest in [arInsert, arUpdate, arDelete, arLock, arUnlock,
arUpdateHBlobs, arFetchGenerators] then
ARow.RowError := E;
raise;
end;
end;
finally
ACommand.CloseAll;
if lClearErrorHandler then
ACommand.ErrorHandler := nil;
end;
{$IFDEF FireDAC_MONITOR}
finally
if IsTracing then
if ARow <> nil then
Trace(ekAdaptUpdate, esEnd, 'ProcessRequest',
['ARow.Table.Name', ARow.Table.SourceName])
else
Trace(ekAdaptUpdate, esEnd, 'ProcessRequest', []);
end;
{$ENDIF}
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetUpdateRequestName(ARequest: TFDUpdateRequest): String;
begin
case ARequest of
arLock: Result := 'Lock';
arUnLock: Result := 'UnLock';
arInsert: Result := 'Insert';
arDelete: Result := 'Delete';
arUpdate: Result := 'Update';
arUpdateHBlobs: Result := 'UpdateHBlobs';
arFetchRow: Result := 'FetchRow';
arFetchGenerators: Result := 'FetchGenerators';
end;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.GetUpdateRowCommand(ARow: TFDDatSRow;
AUpdRowOptions: TFDUpdateRowOptions; AUpdateRequest: TFDUpdateRequest;
AFillRowOptions: TFDPhysFillRowOptions; AColumn: Integer; ACacheCommand: Boolean;
var AFlags: TFDPhysCommandGeneratorFlags): IFDPhysCommand;
var
oConn: IFDPhysConnection;
oTx: IFDPhysTransaction;
{$IFDEF FireDAC_MONITOR}
oObjIntf: IFDStanObject;
{$ENDIF}
eCommandKind: TFDPhysCommandKind;
oCmdGen: IFDPhysCommandGenerator;
oMeta: IFDPhysConnectionMetadata;
oRes: TFDResourceOptions;
oFtch: TFDFetchOptions;
oUpd: TFDUpdateOptions;
oFmt: TFDFormatOptions;
oTmpParams, oResParams: TFDParams;
i: Integer;
oPar: TFDParam;
begin
GetConn(oConn);
if AUpdateRequest = arUnlock then begin
oConn.CreateMetadata(oMeta);
if not oMeta.IsFileBased then
Exit;
end;
GetUpdTx(oTx);
oConn.CreateCommand(Result);
Result.Transaction := oTx;
{$IFDEF FireDAC_MONITOR}
Supports(Result, IFDStanObject, oObjIntf);
oObjIntf.SetOwner(Self, GetUpdateRequestName(AUpdateRequest));
{$ENDIF}
oRes := Result.Options.ResourceOptions;
oFtch := Result.Options.FetchOptions;
oUpd := Result.Options.UpdateOptions;
oFmt := Result.Options.FormatOptions;
oRes.ParamCreate := False;
oRes.MacroCreate := False;
Result.Params.BindMode := pbByNumber;
oConn.CreateCommandGenerator(oCmdGen, GetSelectCommand);
oCmdGen.Options := GetOptions;
oCmdGen.Table := ARow.Table;
oCmdGen.Row := ARow;
oCmdGen.Params := Result.Params;
oCmdGen.MappingHandler := TFDDAptTableAdapterMappingHandler.Create(Self) as
IFDPhysMappingHandler;
if AColumn <> -1 then
oCmdGen.Column := ARow.Table.Columns[AColumn]
else
oCmdGen.Column := nil;
oCmdGen.UpdateRowOptions := AUpdRowOptions;
oCmdGen.FillRowOptions := AFillRowOptions;
case AUpdateRequest of
arInsert: Result.CommandText := oCmdGen.GenerateInsert;
arUpdate: Result.CommandText := oCmdGen.GenerateUpdate;
arDelete: Result.CommandText := oCmdGen.GenerateDelete;
arLock: Result.CommandText := oCmdGen.GenerateLock;
arUnlock: Result.CommandText := oCmdGen.GenerateUnLock;
arUpdateHBlobs: Result.CommandText := oCmdGen.GenerateUpdateHBlobs;
arFetchRow: Result.CommandText := oCmdGen.GenerateSelect([foAfterIns, foAfterUpd] * AFillRowOptions = []);
arFetchGenerators: Result.CommandText := oCmdGen.GenerateFetchGenerators;
end;
eCommandKind := oCmdGen.CommandKind;
AFlags := oCmdGen.Flags;
if Result.CommandText = '' then begin
Result := nil;
Exit;
end;
if (gfInlineView in AFlags) and (GetSelectCommand.Params.Count > 0) then begin
oTmpParams := TFDParams.Create;
try
oResParams := Result.Params;
oTmpParams.Assign(oResParams);
oResParams.Assign(GetSelectCommand.Params);
for i := 0 to oTmpParams.Count - 1 do begin
oPar := oResParams.Add;
oPar.Assign(oTmpParams[i]);
end;
for i := 0 to oResParams.Count - 1 do
oResParams[i].Position := i + 1;
finally
FDFree(oTmpParams);
end;
end;
Result.CommandKind := eCommandKind;
oFmt.Assign(GetOptions.FormatOptions);
oFtch.Assign(GetOptions.FetchOptions);
oUpd.Assign(GetOptions.UpdateOptions);
oRes.Assign(GetOptions.ResourceOptions);
oRes.PreprocessCmdText := False;
oRes.ParamExpand := True;
if not ACacheCommand then
oRes.DirectExecute := True;
oFtch.Mode := fmExactRecsMax;
oFtch.RecsMax := 1;
oFtch.Items := oFtch.Items - [fiMeta];
oFtch.Cache := [];
oFtch.AutoClose := True;
oFtch.AutoFetchAll := afAll;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.ProcessUpdate(ARow: TFDDatSRow; var AAction: TFDErrorAction;
ARequest: TFDUpdateRequest; AUpdRowOptions: TFDUpdateRowOptions;
AFillRowOptions: TFDPhysFillRowOptions; AColumn: Integer);
var
oConn: IFDPhysConnection;
oTx: IFDPhysTransaction;
iLockID: LongWord;
lEndTX, lSavepoint: Boolean;
oCmd: IFDPhysCommand;
oMeta: IFDPhysConnectionMetadata;
eFillOpts: TFDPhysFillRowOptions;
lCacheUpdateCommand: Boolean;
eCmdFlags: TFDPhysCommandGeneratorFlags;
oUpdOpts: TFDUpdateOptions;
oExc: Exception;
{$IFDEF FireDAC_MONITOR}
sCaller, sTabName: String;
{$ENDIF}
lCustomFetchRow: Boolean;
lFailed: Boolean;
begin
try
CheckSelectCommand;
except
AAction := eaExitFailure;
raise;
end;
AAction := eaApplied;
oUpdOpts := GetOptions.UpdateOptions;
if not oUpdOpts.CheckRequest(ARequest, AUpdRowOptions, False) then
Exit;
eCmdFlags := [];
lCacheUpdateCommand := False;
oCmd := nil;
iLockID := $FFFFFFFF;
GetConn(oConn);
GetUpdTx(oTx);
oConn.CreateMetadata(oMeta);
AAction := eaDefault;
lFailed := False;
{$IFDEF FireDAC_MONITOR}
sCaller := GetUpdateRequestName(ARequest);
sTabName := '';
if IsTracing then
if ARow <> nil then begin
sTabName := ARow.Table.SourceName;
Trace(ekAdaptUpdate, esStart, sCaller, ['ARow.Table.Name', sTabName]);
end
else
Trace(ekAdaptUpdate, esStart, sCaller, []);
{$ENDIF}
if ARequest <> arFetchRow then
oTX.LockAutoStop;
try
try
// get existing command
if not (ARequest in FGeneratedCommands) then
GetCommand(ARequest, oCmd);
if oCmd = nil then begin
lCacheUpdateCommand :=
(ARequest = arFetchGenerators) or
(oUpdOpts.LockMode = lmNone) and not oUpdOpts.UpdateChangedFields and (
(ARequest = arInsert) or
(ARequest = arUpdate) and (oUpdOpts.UpdateMode = upWhereKeyOnly) or
(ARequest = arDelete) and (oUpdOpts.UpdateMode = upWhereKeyOnly));
if lCacheUpdateCommand then
GetCommand(ARequest, oCmd)
else begin
InternalSetCommand(ARequest, nil);
oCmd := nil;
end;
end;
repeat
try
if not FInUpdateRowHandler and (GetUpdateHandler <> nil) then begin
FInUpdateRowHandler := True;
try
GetUpdateHandler.UpdateRow(ARow, ARequest, AUpdRowOptions, AAction);
if AAction <> eaDefault then
lCacheUpdateCommand := False;
finally
FInUpdateRowHandler := False;
end;
end;
if AAction in [eaRetry, eaDefault] then begin
AAction := eaDefault;
// build command if required
if oCmd = nil then
case ARequest of
arLock:
begin
if (oUpdOpts.LockMode <> lmNone) and
not ((uoNoSrvRecord in AUpdRowOptions) or (ARow.RowState = rsInserted)) and
(ARow.DBLockID = 0) then begin
if (oUpdOpts.LockMode = lmPessimistic) and oMeta.TxSupported and not oTx.Active then
iLockID := oTx.StartTransaction;
oCmd := GetUpdateRowCommand(ARow, AUpdRowOptions, arLock,
[foData, foBlobs, foDetails, foUpdatable], -1, lCacheUpdateCommand,
eCmdFlags);
end;
end;
arUnLock:
begin
if (oUpdOpts.LockMode <> lmNone) and
not ((uoNoSrvRecord in AUpdRowOptions) or (ARow.RowState = rsInserted)) and
(ARow.DBLockID <> 0) then
oCmd := GetUpdateRowCommand(ARow, AUpdRowOptions, arUnLock,
[foData, foBlobs, foDetails, foUpdatable, foAfterUpd], -1, lCacheUpdateCommand,
eCmdFlags);
end;
arInsert:
begin
if not oUpdOpts.EnableInsert then
FDException(Self, [S_FD_LDApt], er_FD_DAptCantInsert, []);
oCmd := GetUpdateRowCommand(ARow, AUpdRowOptions, arInsert,
[], -1, lCacheUpdateCommand, eCmdFlags);
if gfFetchGenerator in eCmdFlags then begin
ProcessUpdate(ARow, AAction, arFetchGenerators,
AUpdRowOptions + [uoDeferredGenGet], [], -1);
if not (AAction in [eaApplied, eaDefault]) then
oCmd := nil;
end;
end;
arDelete:
begin
if not oUpdOpts.EnableDelete then
FDException(Self, [S_FD_LDApt], er_FD_DAptCantDelete, []);
oCmd := GetUpdateRowCommand(ARow, AUpdRowOptions, arDelete,
[], -1, lCacheUpdateCommand, eCmdFlags);
end;
arUpdate:
begin
if not oUpdOpts.EnableUpdate then
FDException(Self, [S_FD_LDApt], er_FD_DAptCantEdit, []);
oCmd := GetUpdateRowCommand(ARow, AUpdRowOptions, arUpdate,
[], -1, lCacheUpdateCommand, eCmdFlags);
end;
arUpdateHBlobs:
begin
if not oUpdOpts.EnableInsert then
FDException(Self, [S_FD_LDApt], er_FD_DAptCantInsert, []);
oCmd := GetUpdateRowCommand(ARow, AUpdRowOptions, arUpdateHBlobs,
[], -1, lCacheUpdateCommand, eCmdFlags);
end;
arFetchRow:
begin
if ARow.RowState in [rsInserted, rsDeleted, rsModified, rsUnchanged] then
oCmd := GetUpdateRowCommand(ARow, AUpdRowOptions, arFetchRow,
AFillRowOptions, AColumn, lCacheUpdateCommand, eCmdFlags);
end;
arFetchGenerators:
begin
if not oMeta.GeneratorSupported then
oCmd := nil
else
oCmd := GetUpdateRowCommand(ARow, AUpdRowOptions, arFetchGenerators,
[], -1, lCacheUpdateCommand, eCmdFlags);
end;
end;
if (oCmd = nil) and (AAction = eaDefault) then
if ARequest in [arDelete, arInsert] then
AAction := eaFail
else
AAction := eaApplied;
// process command if required
if oCmd <> nil then begin
// When transaction is active, DBMS has atomic transactions (PostgreSQL) and
// a command fails, then full transaction is marked as "invalid" and no
// more actions are possible - only Rollback. With pessimistic locking, if
// Post has failed, then user cannot change a data and do another Post. To
// unify behaviour with other DBMS's, FireDAC surrounds editing commands into
// savepoints.
lSavepoint := oTx.Active and oMeta.TxAtomic and
(oMeta.TxNested or oMeta.TxSavepoints);
if lSavepoint then
oTx.StartTransaction;
try
ProcessRequest(oCmd, ARow, ARequest, AUpdRowOptions, AFillRowOptions,
(ARequest in [arUpdate, arDelete]) and (oUpdOpts.LockMode <> lmNone));
if lSavepoint then
oTx.Commit;
except
if lSavepoint or (iLockID <> $FFFFFFFF) then
oTx.Rollback;
raise;
end;
end;
end;
// post process
if ARequest = arLock then begin
if ((AAction = eaApplied) and (oCmd = nil) or
(AAction = eaDefault) and (oCmd <> nil)) and
(oUpdOpts.LockMode <> lmNone) and (ARow.DBLockID = 0) then
ARow.DBLock(iLockID);
AAction := eaApplied;
end
else if ARequest = arUnLock then begin
lEndTX := False;
if (AAction = eaApplied) and (oCmd = nil) or
(AAction = eaDefault) and (oCmd <> nil) then begin
if (oUpdOpts.LockMode <> lmNone) and (ARow.DBLockID <> 0) then begin
lEndTX := (oTx.SerialID = ARow.DBLockID);
ARow.DBUnlock;
end;
if uoImmediateUpd in AUpdRowOptions then
if uoCancelUnlock in AUpdRowOptions then
ARow.RejectChanges
else
ARow.AcceptChanges;
end;
if (oUpdOpts.LockMode = lmPessimistic) and oTx.Active and lEndTX then
if uoCancelUnlock in AUpdRowOptions then
oTx.Rollback
else
oTx.Commit;
AAction := eaApplied;
end
else if (ARequest in [arInsert, arUpdate]) then begin
if oCmd <> nil then begin
lCustomFetchRow := not (arFetchRow in FGeneratedCommands) and (GetFetchRowCommand <> nil);
if not lCustomFetchRow and not oMeta.InlineRefresh and (oUpdOpts.RefreshMode <> rmManual) or
lCustomFetchRow and (oUpdOpts.RefreshMode = rmAll) then begin
eFillOpts := FDGetFillRowOptions(GetOptions.FetchOptions);
if ARequest = arInsert then
Include(eFillOpts, foAfterIns)
else if ARequest = arUpdate then
Include(eFillOpts, foAfterUpd);
if gfIdentityInsert in eCmdFlags then
Include(eFillOpts, foNoIdentity);
Fetch(ARow, AAction, -1, eFillOpts);
end;
if (ARequest = arInsert) and (gfHasHBlob in eCmdFlags) and
(oMeta.InsertHBlobMode = hmUpdateAfterInsert) then
ProcessUpdate(ARow, AAction, arUpdateHBlobs,
AUpdRowOptions - [uoNoSrvRecord], [], -1)
else
AAction := eaApplied;
if (ARequest = arInsert) and
((AAction = eaApplied) or (AAction = eaDefault)) then
if uoImmediateUpd in AUpdRowOptions then
ARow.AcceptChanges;
end;
end
else
AAction := eaApplied;
except
// handle exception
on E: EFDException do begin
if Assigned(GetErrorHandler()) then begin
oExc := EFDDAptRowUpdateException.Create(ARequest, ARow, AAction, E);
try
GetErrorHandler().HandleException(nil, oExc);
if oExc <> nil then
AAction := EFDDAptRowUpdateException(oExc).Action;
finally
FDFree(oExc);
end;
end
else
AAction := eaDefault;
// if refreshing record is not found, then remove it
if (ARequest = arFetchRow) and (AAction = eaDefault) and
([foClear, foData] * AFillRowOptions = [foClear, foData]) and
(E.FDCode = er_FD_DAptRecordIsDeleted) and oUpdOpts.RefreshDelete then begin
FDFreeAndNil(ARow);
AAction := eaExitFailure;
end;
// if retrying, then reset error and regenerate command, because
// field values may be changed in OnUpdateError event handler
if AAction = eaRetry then begin
ARow.ClearErrors;
if not lCacheUpdateCommand then
oCmd := nil;
end
else if AAction = eaDefault then
AAction := eaFail;
if AAction = eaFail then
raise;
end;
end;
until AAction <> eaRetry;
if AAction = eaFail then
FDException(Self, [S_FD_LDApt], er_FD_DAptApplyUpdateFailed, []);
if lCacheUpdateCommand then begin
InternalSetCommand(ARequest, oCmd);
if oCmd <> nil then
Include(FGeneratedCommands, ARequest)
else
Exclude(FGeneratedCommands, ARequest);
end;
except
lFailed := True;
raise;
end;
finally
if ARequest <> arFetchRow then
oTX.UnlockAutoStop(
not ((ARequest = arUnlock) and (uoCancelUnlock in AUpdRowOptions)) and
(AAction in [eaSkip, eaApplied, eaDefault, eaExitSuccess]) and not lFailed,
not ((ARequest = arLock) and (oUpdOpts.LockMode = lmPessimistic)));
{$IFDEF FireDAC_MONITOR}
if IsTracing then
if ARow <> nil then
Trace(ekAdaptUpdate, esEnd, sCaller, ['ARow.Table.Name', sTabName])
else
Trace(ekAdaptUpdate, esEnd, sCaller, []);
{$ENDIF}
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.Update(ARow: TFDDatSRow; var AAction: TFDErrorAction;
AUpdRowOptions: TFDUpdateRowOptions; AForceRequest: TFDActionRequest);
var
iKind: TFDUpdateRequest;
begin
ASSERT(ARow <> nil);
case AForceRequest of
arNone:
Exit;
arFromRow:
case ARow.RowState of
rsInserted: iKind := arInsert;
rsDeleted: iKind := arDelete;
rsModified: iKind := arUpdate;
else Exit;
end;
else
iKind := AForceRequest;
end;
ProcessUpdate(ARow, AAction, iKind, AUpdRowOptions, [], -1);
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.Lock(ARow: TFDDatSRow; var AAction: TFDErrorAction;
AUpdRowOptions: TFDUpdateRowOptions);
begin
ASSERT(ARow <> nil);
ProcessUpdate(ARow, AAction, arLock, AUpdRowOptions, [], -1);
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.UnLock(ARow: TFDDatSRow; var AAction: TFDErrorAction;
AUpdRowOptions: TFDUpdateRowOptions);
begin
ASSERT(ARow <> nil);
ProcessUpdate(ARow, AAction, arUnlock, AUpdRowOptions, [], -1);
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.FetchGenerators(ARow: TFDDatSRow;
var AAction: TFDErrorAction; AUpdRowOptions: TFDUpdateRowOptions);
begin
ASSERT(ARow <> nil);
ProcessUpdate(ARow, AAction, arFetchGenerators, AUpdRowOptions, [], -1);
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.Fetch(ARow: TFDDatSRow; var AAction: TFDErrorAction;
AColumn: Integer; AFillRowOptions: TFDPhysFillRowOptions);
begin
ASSERT(ARow <> nil);
ProcessUpdate(ARow, AAction, arFetchRow, [], AFillRowOptions, AColumn);
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.Define: TFDDatSTable;
var
lCreated: Boolean;
begin
CheckSelectCommand;
if GetDatSManager = nil then
Result := GetSelectCommand.Define(GetDatSTable, GetMetaInfoMergeMode)
else
Result := GetSelectCommand.Define(GetDatSManager, GetDatSTable, GetMetaInfoMergeMode);
lCreated := (Result <> nil) and (GetDatSTable = nil);
if lCreated then
AcquireDatSTable(Result);
try
if GetSelectCommand.State = csPrepared then
GetSelectCommand.Open;
except
if lCreated then
ReleaseDatSTable;
raise;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.Fetch(AAll: Boolean = False; ABlocked: Boolean = False);
begin
CheckSelectCommand;
GetSelectCommand.Fetch(GetDatSTable, AAll, ABlocked);
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.Reconcile: Boolean;
var
oPrc: TFDDAptUpdatesJournalProcessor;
begin
CheckSelectCommand;
oPrc := TFDDAptUpdatesJournalProcessor.CreateForTableAdapter(Self);
try
Result := oPrc.Reconcile;
finally
FDFree(oPrc);
end;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapter.Update(AMaxErrors: Integer = -1): Integer;
var
oTX: IFDPhysTransaction;
oPrc: TFDDAptUpdatesJournalProcessor;
lFailed: Boolean;
begin
Result := 0;
lFailed := False;
CheckSelectCommand;
GetUpdTx(oTX);
oTX.LockAutoStop;
oPrc := TFDDAptUpdatesJournalProcessor.CreateForTableAdapter(Self);
try
try
Result := oPrc.Process(AMaxErrors);
except
lFailed := True;
raise;
end;
finally
FDFree(oPrc);
oTX.UnlockAutoStop(
((AMaxErrors = -1) or (Result <= AMaxErrors)) and not lFailed,
True);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapter.Reset;
begin
UpdateCommands(urReset);
FBuffer.Release;
end;
{-------------------------------------------------------------------------------}
{ TFDDAptTableAdapters }
{-------------------------------------------------------------------------------}
constructor TFDDAptTableAdapters.Create(ASchemaAdapter: TFDDAptSchemaAdapter);
begin
inherited Create;
FSchemaAdapter := ASchemaAdapter;
FItems := TFDObjList.Create;
end;
{-------------------------------------------------------------------------------}
destructor TFDDAptTableAdapters.Destroy;
begin
Clear;
FDFreeAndNil(FItems);
FSchemaAdapter := nil;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapters._AddRef: Integer;
begin
if FSchemaAdapter <> nil then
Result := FSchemaAdapter._AddRef
else
Result := -1;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapters._Release: Integer;
begin
if FSchemaAdapter <> nil then
Result := FSchemaAdapter._Release
else
Result := -1;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapters.Clear;
var
i: Integer;
begin
for i := FItems.Count - 1 downto 0 do
FDFree(TFDDAptTableAdapter(FItems.Items[i]));
FItems.Clear;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapters.GetCount: Integer;
begin
Result := FItems.Count;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapters.Find(const ATable: TFDPhysMappingName): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to FItems.Count - 1 do
if TFDDAptTableAdapter(FItems.Items[i]).MatchRecordSet(ATable) then begin
Result := i;
Exit;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapters.GetItems(AIndex: Integer): IFDDAptTableAdapter;
begin
Result := TFDDAptTableAdapter(FItems.Items[AIndex]) as IFDDAptTableAdapter;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapters.Add(const ASourceRecordSetName: String = '';
const ADatSTableName: String = ''; const AUpdateTableName: String = ''): IFDDAptTableAdapter;
begin
Result := TFDDAptTableAdapter.CreateForSchema(Self) as IFDDAptTableAdapter;
Result.SourceRecordSetName := ASourceRecordSetName;
Result.DatSTableName := ADatSTableName;
Result.UpdateTableName := AUpdateTableName;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapters.Add(const AAdapter: IFDDAptTableAdapter);
var
oAdapt: TFDDAptTableAdapter;
begin
if AAdapter.TableMappings <> nil then
AAdapter.TableMappings.Remove(AAdapter);
oAdapt := AAdapter.GetObj as TFDDAptTableAdapter;
FItems.Add(oAdapt);
oAdapt.FMappings := Self;
oAdapt.AttachDatSTable;
FSchemaAdapter.FDAddRef(oAdapt.RefCount);
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapters.DatSManagerDetaching;
var
i: Integer;
oAdapt: TFDDAptTableAdapter;
begin
for i := 0 to FItems.Count - 1 do begin
oAdapt := TFDDAptTableAdapter(FItems.Items[i]);
oAdapt.DetachDatSTable;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapters.DatSManagerAttached;
var
i: Integer;
oAdapt: TFDDAptTableAdapter;
begin
for i := 0 to FItems.Count - 1 do begin
oAdapt := TFDDAptTableAdapter(FItems.Items[i]);
oAdapt.AttachDatSTable;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapters.Remove(const ATable: TFDPhysMappingName);
var
i: Integer;
begin
i := Find(ATable);
if i <> -1 then
Remove(GetItems(i));
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptTableAdapters.Remove(const AAdapter: IFDDAptTableAdapter);
var
i: Integer;
oAdapt: TFDDAptTableAdapter;
begin
oAdapt := AAdapter.GetObj as TFDDAptTableAdapter;
i := FItems.Remove(oAdapt);
if i >= 0 then begin
oAdapt.DetachDatSTable;
FSchemaAdapter.FDDecRef(oAdapt.RefCount);
oAdapt.FMappings := nil;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDAptTableAdapters.Lookup(const ATable: TFDPhysMappingName): IFDDAptTableAdapter;
var
i: Integer;
begin
i := Find(ATable);
if i <> -1 then
Result := GetItems(i)
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
{ TFDDAptSchemaAdapter }
{-------------------------------------------------------------------------------}
procedure TFDDAptSchemaAdapter.Initialize;
begin
inherited Initialize;
FAdapters := TFDDAptTableAdapters.Create(Self);
end;
{-------------------------------------------------------------------------------}
destructor TFDDAptSchemaAdapter.Destroy;
begin
ReleaseDatSManager;
FDFreeAndNil(FAdapters);
FErrorHandler := nil;
FUpdateHandler := nil;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDDAptSchemaAdapter.GetName: TComponentName;
begin
Result := ClassName + '($' + IntToHex(Integer(Self), 8) + ')';
if FDatSManager <> nil then
Result := FDatSManager.Name + ': ' + Result;
end;
{-------------------------------------------------------------------------------}
function TFDDAptSchemaAdapter.GetParent: IFDStanObject;
begin
Result := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptSchemaAdapter.AfterReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptSchemaAdapter.BeforeReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptSchemaAdapter.SetOwner(const AOwner: TObject;
const ARole: TComponentName);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TFDDAptSchemaAdapter.GetErrorHandler: IFDStanErrorHandler;
begin
Result := FErrorHandler;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptSchemaAdapter.SetErrorHandler(const AValue: IFDStanErrorHandler);
var
i: Integer;
begin
if FErrorHandler <> AValue then begin
FErrorHandler := AValue;
for i := 0 to FAdapters.GetCount - 1 do
TFDDAptTableAdapter(FAdapters.FItems.Items[i]).UpdateCommands(urSetErrorHandler);
end;
end;
{-------------------------------------------------------------------------------}
function TFDDAptSchemaAdapter.GetUpdateHandler: IFDDAptUpdateHandler;
begin
Result := FUpdateHandler;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptSchemaAdapter.SetUpdateHandler(const AValue: IFDDAptUpdateHandler);
begin
FUpdateHandler := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDDAptSchemaAdapter.GetTransaction: IFDPhysTransaction;
begin
Result := FTransaction;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptSchemaAdapter.SetTransaction(const AValue: IFDPhysTransaction);
var
i: Integer;
begin
if FTransaction <> AValue then begin
FTransaction := AValue;
for i := 0 to FAdapters.GetCount - 1 do
TFDDAptTableAdapter(FAdapters.FItems.Items[i]).UpdateCommands(urSetTransaction);
end;
end;
{-------------------------------------------------------------------------------}
function TFDDAptSchemaAdapter.GetUpdateTransaction: IFDPhysTransaction;
begin
Result := FUpdateTransaction;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptSchemaAdapter.SetUpdateTransaction(const AValue: IFDPhysTransaction);
var
i: Integer;
begin
if FUpdateTransaction <> AValue then begin
FUpdateTransaction := AValue;
for i := 0 to FAdapters.GetCount - 1 do
TFDDAptTableAdapter(FAdapters.FItems.Items[i]).UpdateCommands(urSetUpdateTransaction);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptSchemaAdapter.GetParentOptions(var AOpts: IFDStanOptions);
begin
AOpts := FDPhysManager.Options;
end;
{-------------------------------------------------------------------------------}
function TFDDAptSchemaAdapter.GetOptions: IFDStanOptions;
begin
if FOptions = nil then
FOptions := TFDOptionsContainer.Create(nil, TFDFetchOptions,
TFDBottomUpdateOptions, TFDBottomResourceOptions, GetParentOptions);
Result := FOptions;
end;
{-------------------------------------------------------------------------------}
function TFDDAptSchemaAdapter.MapRecordSet(const ATable: TFDPhysMappingName;
var ASourceID: Integer; var ASourceName, ADatSName, AUpdateName: String;
var ADatSTable: TFDDatSTable): TFDPhysMappingResult;
var
oTabAdapt: IFDDAptTableAdapter;
begin
oTabAdapt := GetTableAdapters.Lookup(ATable);
if oTabAdapt = nil then
Result := mrNotMapped
else begin
Result := mrMapped;
FDGetRecordSetInfo(oTabAdapt, ASourceID, ASourceName, ADatSName,
AUpdateName, ADatSTable);
end;
end;
{-------------------------------------------------------------------------------}
function TFDDAptSchemaAdapter.MapRecordSetColumn(const ATable, AColumn: TFDPhysMappingName;
var ASourceID: Integer; var ASourceName, ADatSName, AUpdateName: String;
var ADatSColumn: TFDDatSColumn): TFDPhysMappingResult;
var
oTabAdapt: IFDDAptTableAdapter;
oColMap: TFDDAptColumnMapping;
begin
Result := mrNotMapped;
oTabAdapt := GetTableAdapters.Lookup(ATable);
if oTabAdapt <> nil then
if (oTabAdapt.ColumnMappings = nil) or (oTabAdapt.ColumnMappings.Count = 0) then
Result := mrDefault
else begin
oColMap := oTabAdapt.ColumnMappings.Lookup(AColumn);
if oColMap <> nil then begin
Result := mrMapped;
FDGetRecordSetColumnInfo(oColMap, ASourceID, ASourceName, ADatSName,
AUpdateName, ADatSColumn);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptSchemaAdapter.ReleaseDatSManager;
begin
if FDatSManager <> nil then begin
FAdapters.DatSManagerDetaching;
FDatSManager.RemRef;
FDatSManager := nil;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptSchemaAdapter.AttachDatSManager(AManager: TFDDatSManager);
begin
if FDatSManager <> AManager then begin
ReleaseDatSManager;
FDatSManager := AManager;
if AManager <> nil then begin
AManager.AddRef;
FAdapters.DatSManagerAttached;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDAptSchemaAdapter.GetDatSManager: TFDDatSManager;
var
oMgr: TFDDatSManager;
begin
if FDatSManager = nil then begin
oMgr := TFDDatSManager.Create;
oMgr.CountRef(0);
oMgr.UpdatesRegistry := True;
AttachDatSManager(oMgr);
end;
Result := FDatSManager;
end;
{-------------------------------------------------------------------------------}
procedure TFDDAptSchemaAdapter.SetDatSManager(AValue: TFDDatSManager);
begin
if FDatSManager <> AValue then
AttachDatSManager(AValue);
end;
{-------------------------------------------------------------------------------}
function TFDDAptSchemaAdapter.GetTableAdapters: IFDDAptTableAdapters;
begin
Result := FAdapters as IFDDAptTableAdapters;
end;
{-------------------------------------------------------------------------------}
function TFDDAptSchemaAdapter.Reconcile: Boolean;
var
oPrc: TFDDAptUpdatesJournalProcessor;
begin
oPrc := TFDDAptUpdatesJournalProcessor.CreateForSchemaAdapter(Self);
try
Result := oPrc.Reconcile;
finally
FDFree(oPrc);
end;
end;
{-------------------------------------------------------------------------------}
function TFDDAptSchemaAdapter.Update(AMaxErrors: Integer = -1): Integer;
var
oTX: IFDPhysTransaction;
oPrc: TFDDAptUpdatesJournalProcessor;
i: Integer;
oTabAdapt: TFDDAptTableAdapter;
oList: TInterfaceList;
lFailed: Boolean;
begin
Result := 0;
lFailed := False;
oList := TInterfaceList.Create;
try
for i := 0 to GetTableAdapters.Count - 1 do begin
oTabAdapt := GetTableAdapters.Items[i] as TFDDAptTableAdapter;
oTabAdapt.CheckSelectCommand;
oTabAdapt.GetUpdTx(oTX);
if oList.IndexOf(oTX) = -1 then begin
oList.Add(oTX);
oTX.LockAutoStop;
end;
end;
oPrc := TFDDAptUpdatesJournalProcessor.CreateForSchemaAdapter(Self);
try
try
Result := oPrc.Process(AMaxErrors);
except
lFailed := True;
raise;
end;
finally
FDFree(oPrc);
end;
finally
for i := 0 to oList.Count - 1 do begin
oTX := IFDPhysTransaction(oList[i]);
oTX.UnlockAutoStop(
((AMaxErrors = -1) or (Result <= AMaxErrors)) and not lFailed,
True);
end;
FDFree(oList);
end;
end;
{-------------------------------------------------------------------------------}
var
oFact1,
oFact2: TFDFactory;
initialization
oFact1 := TFDMultyInstanceFactory.Create(TFDDAptTableAdapter, IFDDAptTableAdapter);
oFact2 := TFDMultyInstanceFactory.Create(TFDDAptSchemaAdapter, IFDDAptSchemaAdapter);
finalization
FDReleaseFactory(oFact1);
FDReleaseFactory(oFact2);
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: FileB3D<p>
File streaming class for the B3D loader<p>
<b>History :</b><font size=-1><ul>
<li>24/07/09 - DaStr - Got rid of compiler hints
<li>29/05/08 - DaStr - Added $I GLScene.inc
<li>22/12/05 - Mathx - Added to the GLScene Project.
</ul></font>
}
unit FileB3D;
interface
{$I GLScene.inc}
{$R-}
uses
Classes, TypesB3D, GLVectorGeometry, GLVectorTypes, GLVectorLists;
type
TB3DMaterial = class
public
MaterialData: TBRUSChunk;
constructor Create;
destructor Destroy; override;
function GetMaterialName: string;
end;
TB3DTexture = class
public
TextureData: TTEXSChunk;
constructor Create;
destructor Destroy; override;
function GetTextureName: string;
end;
TB3DNode = class
public
NodeData: PNODEChunk;
constructor Create;
destructor Destroy; override;
function GetNodeName: string;
procedure DestroyNodeData(Node: PNODEChunk);
end;
// TFileB3D
//
TFileB3D = class
private
fTextures: TStringList;
fMaterials: TStringList;
fNodes: TB3DNode;
procedure FreeLists;
function GetChunkType(aChunk: TB3DChunk): TB3DChunkType;
function SkipChunk(aStream: TStream; aChunk: TB3DChunk): Integer;
function ReadTextureChunk(aStream: TStream; aChunk: TB3DChunk): Integer;
function ReadMaterialChunk(aStream: TStream; aChunk: TB3DChunk): Integer;
function ReadNodeChunk(aStream: TStream; aChunk: TB3DChunk; Node: PNODEChunk; level: Integer): Integer;
function ReadMeshChunk(aStream: TStream; aChunk: TB3DChunk; Mesh: PMESHChunk): Integer;
function ReadVerticesChunk(aStream: TStream; aChunk: TB3DChunk; Vertices: PVRTSChunk): Integer;
function ReadTrianglesChunk(aStream: TStream; aChunk: TB3DChunk; Triangle: PTRISChunk): Integer;
public
constructor Create; virtual;
destructor Destroy; override;
procedure LoadFromStream(aStream : TStream);
//for test only
procedure Check;
property Textures: TStringList read fTextures;
property Materials: TStringList read fMaterials;
property Nodes: TB3DNode read fNodes;
end;
implementation
uses
SysUtils{, Windows};
constructor TB3DMaterial.Create;
begin
inherited Create;
fillChar(MaterialData, sizeof(TBRUSChunk), 0);
end;
destructor TB3DMaterial.Destroy;
begin
SetLength(MaterialData.texture_id, 0);
inherited Destroy;
end;
function TB3DMaterial.GetMaterialName: string;
begin
SetString(Result, MaterialData.name, strlen(MaterialData.name));
end;
constructor TB3DTexture.Create;
begin
inherited Create;
fillChar(TextureData, sizeof(TTEXSChunk), 0);
end;
destructor TB3DTexture.Destroy;
begin
inherited Destroy;
end;
function TB3DTexture.GetTextureName: string;
begin
SetString(Result, TextureData.fileName, strlen(TextureData.fileName));
end;
constructor TB3DNode.Create;
begin
inherited Create;
NodeData := nil;
end;
destructor TB3DNode.Destroy;
begin
DestroyNodeData(NodeData);
inherited Destroy;
end;
function TB3DNode.GetNodeName: string;
begin
SetString(Result, NodeData^.name, strlen(NodeData^.name));
end;
procedure DeleteVertices(var aVertex: PVertexData);
var
V: PVertexData;
begin
while aVertex<>nil do
begin
SetLength(aVertex^.tex_coords, 0);
V := aVertex^.next;
freeMem(aVertex);
aVertex := nil;
DeleteVertices(V);
end;
end;
procedure DeleteTriangles(var aTriangle: PTRISChunk);
var
T: PTRISChunk;
begin
while aTriangle<>nil do
begin
SetLength(aTriangle^.vertex_id, 0);
T := aTriangle^.next;
freeMem(aTriangle);
aTriangle := nil;
DeleteTriangles(T);
end;
end;
procedure TB3DNode.DestroyNodeData(Node: PNODEChunk);
var
oldNode, PNode: PNODEChunk;
begin
PNode := Node;
while PNode<>nil do
begin
if PNode^.meshes<>nil then
begin
DeleteTriangles(PNode^.meshes^.triangles);
DeleteVertices(PNode^.meshes^.vertices.vertices);
freeMem(PNode^.meshes);
PNode^.meshes := nil;
end;
if PNode^.keys<>nil then
freeMem(PNode^.keys);
DestroyNodeData(PNode^.nodes);
oldNode := PNode;
PNode := PNode^.next;
freeMem(oldNode);
end;
end;
//------------------------------------------------------------------------------
constructor TFileB3D.Create;
begin
inherited Create;
fTextures := TStringList.Create;
fMaterials := TStringList.Create;
fNodes := TB3DNode.Create;
end;
destructor TFileB3D.Destroy;
begin
FreeLists;
fTextures.free;
fMaterials.free;
fNodes.free;
inherited Destroy;
end;
function TFileB3D.GetChunkType(aChunk: TB3DChunk): TB3DChunkType;
begin
Result := bctUnKnown;
if StrLIComp(aChunk.chunk, 'BB3D', 4)=0 then
Result := bctHeader;
if StrLIComp(aChunk.chunk, 'TEXS', 4)=0 then
Result := bctTexture;
if StrLIComp(aChunk.chunk, 'BRUS', 4)=0 then
Result := bctBrush;
if StrLIComp(aChunk.chunk, 'NODE', 4)=0 then
Result := bctNode;
if StrLIComp(aChunk.chunk, 'VRTS', 4)=0 then
Result := bctVertex;
if StrLIComp(aChunk.chunk, 'BONE', 4)=0 then
Result := bctBone;
if StrLIComp(aChunk.chunk, 'KEYS', 4)=0 then
Result := bctKeyFrame;
if StrLIComp(aChunk.chunk, 'ANIM', 4)=0 then
Result := bctAnimation;
if StrLIComp(aChunk.chunk, 'MESH', 4)=0 then
Result := bctMesh;
if StrLIComp(aChunk.chunk, 'TRIS', 4)=0 then
Result := bctTriangle;
end;
function TFileB3D.SkipChunk(aStream: TStream; aChunk: TB3DChunk): Integer;
begin
aStream.Seek(aChunk.length, soFromCurrent);
Result := aChunk.length;
end;
function ReadString(aStream: TStream; buffer: PChar; MaxCount: Integer): Integer;
begin
Result := 0;
while Result<MaxCount do
begin
aStream.Read(buffer[Result], sizeof(char));
Inc(result);
if buffer[result-1]=#0 then
break;
end;
end;
function TFileB3D.ReadTextureChunk(aStream: TStream; aChunk: TB3DChunk): Integer;
var
Texture: TB3DTexture;
Count: Integer;
begin
Result := 0;
if aChunk.length<5 then
exit;
Count := 0;
while Count<aChunk.length do
begin
Texture := TB3DTexture.Create;
Inc(Count, ReadString(aStream, Texture.TextureData.fileName, 255));
Inc(Count, aStream.Read(Texture.TextureData.flags, sizeof(integer)));
Inc(Count, aStream.Read(Texture.TextureData.blend, sizeof(integer)));
Inc(Count, aStream.Read(Texture.TextureData.x_pos, sizeof(single)));
Inc(Count, aStream.Read(Texture.TextureData.y_pos, sizeof(single)));
Inc(Count, aStream.Read(Texture.TextureData.x_scale, sizeof(single)));
Inc(Count, aStream.Read(Texture.TextureData.y_scale, sizeof(single)));
Inc(Count, aStream.Read(Texture.TextureData.rotation, sizeof(single)));
fTextures.AddObject(Texture.GetTextureName, Texture);
end;
Result := fTextures.Count;
end;
function TFileB3D.ReadMaterialChunk(aStream: TStream; aChunk: TB3DChunk): Integer;
var
Material: TB3DMaterial;
Count, I: Integer;
TextureCount: Integer;
begin
Result := 0;
if aChunk.length<5 then
exit;
Count := 0;
TextureCount := 0;
while Count<aChunk.length do
begin
Material := TB3DMaterial.Create;
if Count=0 then
begin
Inc(Count, aStream.Read(Material.MaterialData.n_texs, sizeof(integer)));
TextureCount := Material.MaterialData.n_texs;
end else
Material.MaterialData.n_texs := TextureCount;
Inc(Count, ReadString(aStream, Material.MaterialData.name, 255));
Inc(Count, aStream.Read(Material.MaterialData.red, sizeof(single)));
Inc(Count, aStream.Read(Material.MaterialData.green, sizeof(single)));
Inc(Count, aStream.Read(Material.MaterialData.blue, sizeof(single)));
Inc(Count, aStream.Read(Material.MaterialData.alpha, sizeof(single)));
Inc(Count, aStream.Read(Material.MaterialData.shininess, sizeof(single)));
Inc(Count, aStream.Read(Material.MaterialData.blend, sizeof(integer)));
Inc(Count, aStream.Read(Material.MaterialData.fx, sizeof(integer)));
SetLength(Material.MaterialData.texture_id, TextureCount);
for I:=0 to TextureCount-1 do
Inc(Count, aStream.Read(Material.MaterialData.texture_id[I], sizeof(Integer)));
fMaterials.AddObject(Material.GetMaterialName, Material);
end;
Result := fMaterials.Count;
end;
function TFileB3D.ReadMeshChunk(aStream: TStream; aChunk: TB3DChunk; Mesh: PMESHChunk): Integer;
var
C: TB3DChunk;
T: PTRISChunk;
begin
Result := 0;
fillChar(Mesh^, sizeof(TMESHChunk), 0);
Mesh^.brush_id := -1;
Inc(Result, aStream.Read(Mesh^.brush_id, sizeof(Integer)));
T := nil;
while Result<aChunk.length do
begin
Inc(Result, aStream.Read(C, sizeof(TB3DChunk)));
case GetChunkType(C) of
bctVertex:
begin
Inc(Result, ReadVerticesChunk(aStream, C, @(Mesh^.vertices)));
end;
bctTriangle:
begin
if Mesh^.triangles=nil then
begin
GetMem(Mesh^.triangles, sizeof(TTRISChunk));
fillChar(Mesh^.triangles^, sizeof(TTRISChunk), 0);
Inc(Result, ReadTrianglesChunk(aStream, C, Mesh^.triangles));
end else
begin
if T=nil then
begin
GetMem(T, sizeof(TTRISChunk));
fillChar(T^, sizeof(TTRISChunk), 0);
Inc(Result, ReadTrianglesChunk(aStream, C, T));
Mesh^.triangles^.next := T;
end else
begin
GetMem(T^.next, sizeof(TTRISChunk));
fillChar(T^.next^, sizeof(TTRISChunk), 0);
Inc(Result, ReadTrianglesChunk(aStream, C, T^.next));
T := T^.next;
end;
end;
end;
else
inc(Result, SkipChunk(aStream, C));
end;
end;
end;
function TFileB3D.ReadVerticesChunk(aStream: TStream; aChunk: TB3DChunk; Vertices: PVRTSChunk): Integer;
var
v: PVertexData;
v1: PVertexData;
size: Integer;
begin
Result := 0;
fillChar(Vertices^, sizeof(TVRTSChunk), 0);
Inc(Result, aStream.Read(Vertices^.flags, sizeof(Integer)));
Inc(Result, aStream.Read(Vertices^.tex_coord_sets, sizeof(Integer)));
Inc(Result, aStream.Read(Vertices^.tex_coord_set_size, sizeof(Integer)));
size := Vertices^.tex_coord_set_size*Vertices^.tex_coord_sets;
v := nil;
while Result<aChunk.length do
begin
if Vertices^.vertices=nil then
begin
GetMem(Vertices^.vertices, sizeof(TVertexData));
fillChar(vertices^.vertices^, sizeof(TVertexData), 0);
end else
begin
if v=nil then
begin
GetMem(v, sizeof(TVertexData));
fillChar(v^, sizeof(TVertexData), 0);
vertices^.vertices^.next := v;
end else
begin
GetMem(v^.next, sizeof(TVertexData));
fillChar(v^.next^, sizeof(TVertexData), 0);
v := v^.next;
end;
end;
if v=nil then
v1 := vertices^.vertices
else
v1 := v;
Inc(Result, aStream.Read(v1^.x, sizeof(single)));
Inc(Result, aStream.Read(v1^.y, sizeof(single)));
Inc(Result, aStream.Read(v1^.z, sizeof(single)));
//W3D Begin
if (Vertices^.flags and 1)>0 then begin
Inc(Result, aStream.Read(v1^.nx, sizeof(single)));
Inc(Result, aStream.Read(v1^.ny, sizeof(single)));
Inc(Result, aStream.Read(v1^.nz, sizeof(single)));
end;
if (Vertices^.flags and 2)>0 then begin
Inc(Result, aStream.Read(v1^.red, sizeof(single)));
Inc(Result, aStream.Read(v1^.green, sizeof(single)));
Inc(Result, aStream.Read(v1^.blue, sizeof(single)));
Inc(Result, aStream.Read(v1^.alpha, sizeof(single)));
end;
//W3D END
SetLength(v1^.tex_coords, size);
Inc(Result, aStream.Read(v1^.tex_coords[0], size*sizeof(single)));
end;
end;
function TFileB3D.ReadTrianglesChunk(aStream: TStream; aChunk: TB3DChunk; Triangle: PTRISChunk): Integer;
begin
Result := 0;
if Triangle=nil then
begin
GetMem(Triangle, sizeof(TTRISChunk));
fillChar(Triangle^, sizeof(TTRISChunk), 0);
Triangle^.brush_id := -1;
end;
Inc(Result, aStream.Read(Triangle^.brush_id, sizeof(Integer)));
SetLength(Triangle^.vertex_id, (aChunk.length-Result) div sizeof(Integer));
Inc(Result, aStream.Read(Triangle^.vertex_id[0], (aChunk.length-Result)));
end;
//read in only the mesh data, the keyframes and animation had been dropped
function TFileB3D.ReadNodeChunk(aStream: TStream; aChunk: TB3DChunk; Node: PNODEChunk; level: Integer): Integer;
var
Count: Integer;
C: TB3DChunk;
N: PNODEChunk;
begin
N := nil;
fillChar(Node^, sizeof(TNODEChunk), 0);
Node^.level := level;
Count := 0;
Inc(Count, ReadString(aStream, Node^.name, 255));
Inc(Count, aStream.Read(Node^.position.V[0], sizeof(TAffineVector)));
Inc(Count, aStream.Read(Node^.scale.V[0], sizeof(TAffineVector)));
Inc(Count, aStream.Read(Node^.rotation.V[0], sizeof(TVector)));
while Count<aChunk.length do
begin
Inc(Count, aStream.Read(C, sizeof(TB3DChunk)));
case GetChunkType(C) of
bctMesh:
begin
GetMem(Node^.meshes, sizeof(TMESHChunk));
Inc(Count, ReadMeshChunk(aStream, C, Node^.meshes));
end;
bctKeyframe:
begin
Inc(Count, SkipChunk(aStream, C));
end;
bctNode:
begin
if N=nil then
begin
GetMem(N, sizeof(TNODEChunk));
fillChar(N^, sizeof(TNODEChunk), 0);
Inc(Count, ReadNodeChunk(aStream, C, N, level + 1));
Node^.next := N;
end else
begin
GetMem(N^.next, sizeof(TNODEChunk));
fillChar(N^.next^, sizeof(TNODEChunk), 0);
Inc(Count, ReadNodeChunk(aStream, C, N^.next, level + 1));
N := N^.next;
end;
end;
bctAnimation:
begin
Inc(Count, SkipChunk(aStream, C));
end;
else
Inc(Count, SkipChunk(aStream, C));
end;
end;
Result := Count;
end;
procedure TFileB3D.LoadFromStream(aStream : TStream);
var
aChunk: TB3DChunk;
FileSize: Integer;
begin
FileSize := aStream.Size;
while aStream.Position<FileSize do
begin
aStream.Read(aChunk, sizeof(TB3DChunk));
case GetChunkType(aChunk) of
bctHeader:
begin
FileSize := aChunk.length - sizeof(TB3DChunk) - sizeof(TBB3DChunk);
aStream.Seek(sizeof(TBB3DChunk), soFromCurrent);
end;
bctTexture:
begin
ReadTextureChunk(aStream, aChunk);
end;
bctBrush:
begin
ReadMaterialChunk(aStream, aChunk);
end;
bctNode:
begin
if fNodes.NodeData=nil then
begin
GetMem(fNodes.NodeData, sizeof(TNODEChunk));
ReadNodeChunk(aStream, aChunk, fNodes.NodeData, 0);
end;
end;
else
SkipChunk(aStream, aChunk);
end;
end;
end;
procedure TFileB3D.FreeLists;
begin
while fTextures.Count>0 do
begin
fTextures.Objects[0].free;
ftextures.Delete(0);
end;
while fMaterials.Count>0 do
begin
fMaterials.Objects[0].free;
fMaterials.Delete(0);
end;
end;
//for test only
procedure TFileB3D.Check;
var
NodeLevel: Integer;
// NodeCount: Integer;
Node: PNODEChunk;
// VerticesCount: Integer;
// FaceCount: Integer;
Face: PTRISChunk;
Vertex: PVertexData;
begin
NodeLevel := 0;
// NodeCount := 0;
// VerticesCount := 0;
// FaceCount := 0;
Node := fNodes.NodeData;
while Node<>nil do
begin
if Node^.meshes<>nil then
// Inc(NodeCount);
if Node^.level>NodeLevel then
NodeLevel := Node^.level;
if Node^.meshes<>nil then
begin
Vertex := Node^.meshes.vertices.vertices;
while Vertex<>nil do
begin
// Inc(VerticesCount);
Vertex := Vertex.next;
end;
Face := Node^.meshes.triangles;
while Face<>nil do
begin
// Inc(FaceCount);
Face := Face.next;
end;
end;
Node := Node^.next;
end;
//MessageBeep(FaceCount);
//MessageBeep(VerticesCount);
//MessageBeep(NodeLevel);
//MessageBeep(NodeCount);
end;
end.
|
unit udmNFe;
interface
uses
System.SysUtils, System.Classes, System.IniFiles, spdNFCe, System.Contnrs,
spdNFCeDataSets, Data.DB, nxdb, nxllComponent, nxsdServerEngine,
nxreRemoteServerEngine, nxllTransport, nxptBasePooledTransport,
nxtwWinsockTransport, madTools, Vcl.ExtCtrls, Windows, Messages,
spdNFCeType, ncDMServ, ActiveX, DateUtils;
type
TdmNFe = class(TDataModule)
nfceDS: TspdNFCeDataSets;
nfceComp: TspdNFCe;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
_NumeroLote : String;
_Dir : String;
serie : String;
slXML : TStrings;
slRet : TStrings;
vTotImp : Currency;
DM : TDM;
sErroValid : String;
function Contingencia: Boolean;
function CalcImp: Currency;
function ProxNumNFCe: Cardinal;
procedure ValidaXML;
{ Private declarations }
procedure nfce_gerarxml;
procedure nfce_criar;
public
procedure GerarNFE;
procedure Init(aDM : TDM);
function GetCertificados: TStrings;
{ Public declarations }
end;
function getXMLValue(aXML, aCampo: String; aCaminho: string = ''): String;
var
dmNFe: TdmNFe;
gProcessNFEWindow : Cardinal = 0;
TerminarProcNFE : Boolean = False;
gContingencia : Byte = 0;
const
cont_null = 0;
cont_off = 1;
cont_on = 2;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses ncServBD, ncDebug, ncClassesBase, udmNFe_trans, ncMsgCom, math;
{$R *.dfm}
function RetiraBrancosExcedentes(Texto: string): string;
begin
while Pos(' ', Texto) > 0 do
Texto := StringReplace(Texto, ' ', ' ', [rfReplaceAll]);
Result := Texto;
end;
function LimpaXML(S: String): String;
begin
S := RetiraBrancosExcedentes(S); // deixa apenas 1 espaço
S := StringReplace(S, '> <', '><', [rfIgnoreCase, rfReplaceAll]);
S := StringReplace(S, ' </', '</', [rfIgnoreCase, rfReplaceAll]);
S := StringReplace(S, '> ', '>', [rfIgnoreCase, rfReplaceAll]);
S := StringReplace(S, #$D#$A, '', [rfIgnoreCase, rfReplaceAll]);
S := StringReplace(S, #$D, '', [rfIgnoreCase, rfReplaceAll]);
Result := S;
end;
function getXMLValue(aXML, aCampo: String; aCaminho: string = ''): String;
var
sCaminho: String;
P : Integer;
function GetProxCaminho: Boolean;
begin
aCaminho := Trim(aCaminho);
P := Pos(',', aCaminho);
if P>0 then begin
sCaminho := Copy(aCaminho, 1, P-1);
Delete(aCaminho, 1, P);
end else begin
sCaminho := aCaminho;
aCaminho := '';
end;
Result := (sCaminho>'');
end;
begin
Result := '';
while GetProxCaminho do begin
P := Pos('<'+sCaminho+'>', aXML);
if P=0 then P := Pos('<'+sCaminho+' ', aXML);
if P>0 then
Delete(aXML, 1, P + 1 + Length(sCaminho));
end;
P := Pos('<'+aCampo+'>', aXML);
if P > 0 then begin
Delete(aXML, 1, P + 1 + Length(aCampo));
P := Pos('</'+aCampo+'>', aXML);
if P>0 then
Result := Trim(Copy(aXML, 1, P-1)) else
Result := aXML;
end;
end;
procedure ProcessMessages;
var Msg : TMsg;
begin
while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
function getImp(aValor, aImp: Currency): Currency;
begin
Result := aValor * aImp / 100;
end;
function TdmNFe.CalcImp: Currency;
var V: Currency;
begin
with DM do begin
V := tMovEstTotal.Value - tMovEstDesconto.Value;
if tBRTribOrigem.Value in [1, 2, 6, 7] then
Result := getImp(V, tNCMImpostoFed_Imp.Value) else
Result := getImp(V, tNCMImpostoFed_Nac.Value);
Result := Result + getImp(V, tNCMImpostoEst.Value) + getImp(V, tNCMImpostoMun.Value);
end;
end;
function CSOSN_ST(aCod: Word): Boolean;
begin
Result := (aCod=201) and (aCod=202) and (aCod=203);
end;
function CST_ST(aCod: Word): Boolean;
begin
Result := (aCod=30) and (aCod=60) and (aCod=70);
end;
function TdmNFe.Contingencia: Boolean;
begin
with DM do begin
tAuxNFE.IndexName := 'ItpAmbStatus';
if gContingencia=cont_null then
if tAuxNFE.FindKey([tNFConfigtpAmb.Value, nfestatus_contingencia]) then
gContingencia := cont_on else
gContingencia := cont_off;
end;
Result := (gContingencia=cont_on);
end;
procedure TdmNFe.DataModuleCreate(Sender: TObject);
begin
slXML := TStringList.Create;
slRet := TStringList.Create;
end;
procedure TdmNFe.DataModuleDestroy(Sender: TObject);
begin
slXML.Free;
slRet.Free;
end;
procedure TdmNFe.GerarNFE;
var
Save1, Save2: String;
P : PmsgNFEUpdated;
begin
Save1 := DM.tMovEst.IndexName;
Save2 := DM.tPagEsp.IndexName;
with DM do
try
tNFE.Append;
nfce_criar;
nfce_gerarxml;
ValidaXML;
if sErroValid>'' then begin
tNFEStatus.Value := nfetran_erro;
tNFEStatusNF.Value := 9999;
tNFENumero.Clear;
tNFExMotivo.Value := sErroValid;
end;
tNFE.Post;
tTran.Edit;
tTranTipoNFE.Value := tiponfe_nfce;
tTranStatusNFE.Value := tNFEStatus.Value;
tTranChaveNFE.Value := tNFEChave.Value;
tTranAmbNFe.Value := tNFEtpAmb.Value;
tTran.Post;
case tNFEStatus.Value of
nfestatus_transmitir : {TncTransmiteNFe.Create(tTranUID.AsGuid)};
nfestatus_erro, nfestatus_contingencia : begin
New(P);
P^.msgTran := tTranUID.AsGuid;
PostMessage(CliNotifyHandle, wm_nfeupdated, NativeUInt(P), 0);
end;
end;
finally
tMovEst.IndexName := Save1;
tPagEsp.IndexName := Save2;
end;
end;
function TdmNFe.GetCertificados: TStrings;
begin
Result := TStringList.Create;
nfceComp.ListarCertificados(Result);
end;
procedure TdmNFe.Init(aDM: TDM);
var S: String;
begin
DM := aDM;
with DM do begin
nfceComp.UF := tNFConfigEnd_UF.Value;
nfceComp.CNPJ := tNFConfigCNPJ.Value;
S := ExtractFilePath(ParamStr(0));
nfceComp.DiretorioEsquemas := S+'NFCE\Esquemas\';
nfceComp.DiretorioTemplates := S+'NFCE\Templates\';
nfceComp.DiretorioLog := S+'NFCE\Log';
nfceComp.ArquivoServidoresHom := S+'NFCE\nfceServidoresHom.ini';
nfceComp.ArquivoServidoresProd := S+'NFCE\nfceServidoresProd.ini';
nfceComp.DiretorioXmlDestinatario := S+'NFCE\XmlDestinatario\';
nfceComp.DiretorioLogErro := S+'NFCE\Erros\';
nfceComp.DiretorioTemporario := S+'NFCE\Temp\';
nfceComp.VersaoManual := vm50a;
nfceComp.ConexaoSegura := True;
nfceComp.ValidarEsquemaAntesEnvio := True;
DebugMsg('TdmNFe.Init - S: '+S);
S := ExtractFilePath(ParamStr(0))+'NFCE\Templates\vm50a\Conversor\NFCeDataSets.xml';
nfceDS.XMLDicionario := S;
if tNFConfigTipoCert.Value=tipocert_a1 then
nfceComp.TipoCertificado := ckFile
else begin
nfceComp.TipoCertificado := ckSmartCard;
nfceComp.PinCode := tNFConfigPinCert.Value;
end;
if tNFConfigtpAmb.Value=2 then
nfceComp.Ambiente := akHomologacao else
nfceComp.Ambiente := akProducao;
nfceComp.NomeCertificado.Text := tNFConfigCertificadoDig.Value;
end;
end;
procedure TdmNFe.nfce_criar;
begin
with DM do begin
tNFEModelo.Value := '65';
tNFESerie.Value := tNFConfigSerieNFCe.Value;
tNFEtpAmb.Value := tNFConfigtpAmb.Value;
tNFENumero.Value := ProxNumNFCe;
tNFEEntrada.Value := False;
tNFETipoDoc.Value := tiponfe_nfce;
tNFEDataHora.Value := Now; //tTranDataHora.Value;
tNFETran.Value := tTranUID.Value;
tNFEStatus.Value := nfestatus_transmitir;
tNFEValor.Value := tTranTotLiq.Value;
end;
end;
function FormatValor(aValor: Extended; aDecimais: Integer): String;
begin
Str(aValor:0:aDecimais, Result);
end;
function ZeroPad(S: String; T: Integer): String;
begin
Result := S;
while Length(Result)<T do Result := '0'+Result;
end;
procedure TdmNFe.nfce_gerarxml;
var
S: String;
sl : TStrings;
FExtraEmail : Boolean;
FExtraCPF : Boolean;
aChaveNormal, aChaveCont : String;
sXML : String;
procedure DadosDoNFCe;
var
_NRNota : String;
begin
with DM do begin
nfceDS.campo('versao_A02').Value := '3.10'; //Versão do leiaute
nfceDS.Campo('cUF_B02').Value := tNFConfigEnd_CodUF.AsString;
nfceDS.Campo('cNF_B03').Value := IntToStr(Random(99999999)); //Código Numérico que compõe a Chave de Acesso
nfceDS.Campo('natOp_B04').Value := 'VENDA MERC.ADQ.REC.TERC'; //Descrição da Natureza da Operação
nfceDS.Campo('indPag_B05').Value := '0'; //Indicador da forma de pagamento: 0 – pagamento à vista; 1 – pagamento à prazo; 2 - outros.
nfceDS.Campo('mod_B06').Value := '65'; //Modelo do Documento Fiscal
nfceDS.Campo('serie_B07').Value := '1';//tNFESerie.Value;
nfceDS.Campo('nNF_B08').Value := tNFENumero.AsString;
nfceDS.Campo('dhEmi_B09').Value := FormatDateTime('YYYY-mm-dd"T"HH:mm:ss', tNFEDataHora.Value) + TimeZoneStr; //Data e Hora de emissão do Documento Fiscal
nfceDS.Campo('tpNF_B11').Value := '1'; //Tipo de Operação: 0-entrada / 1-saída.
nfceDS.Campo('idDest_B11a').Value := '1'; //Identificador de local de destino da operação: 1- Operação interna; 2- Operação interestadual; 3- Operação com exterior.
nfceDS.Campo('cMunFG_B12').Value := tNFConfigEnd_CodMun.Value;
nfceDS.Campo('tpImp_B21').Value := '4';
nfceDS.Campo('tpEmis_B22').Value := '1';
nfceDS.Campo('cDV_B23').Value := ''; //Dígito Verificador da Chave de Acesso
nfceDS.Campo('tpAmb_B24').Value := tNFConfigtpAmb.AsString;
nfceDS.Campo('finNFe_B25').Value := '1'; //Finalidade de emissão da NF-e: 1- NF-e normal/ 2-NF-e complementar / 3 – NF-e de ajuste.
nfceDS.Campo('indFinal_B25a').Value := '1'; //Indica operação com Consumidor final: 0- Não; 1- Consumidor final;
nfceDS.Campo('indPres_B25b').Value := '1';
nfceDS.Campo('procEmi_B26').Value := '0';
nfceDS.Campo('verProc_B27').Value := '000'; //Versão do Processo de emissão da NF-e
end;
end;
procedure DadosDoEmitente;
begin
with DM do begin
nfceDS.Campo('CNPJ_C02').Value := tNFConfigCNPJ.Value;
nfceDS.Campo('xNome_C03').Value := tNFConfigRazaoSocial.Value;
nfceDS.Campo('xFant_C04').Value := tNFConfigNomeFantasia.Value;
nfceDS.Campo('xLgr_C06').Value := tNFConfigEnd_Logradouro.Value;
nfceDS.Campo('xCpl_C08').Value := tNFConfigEnd_Complemento.Value;
nfceDS.Campo('nro_C07').Value := tNFConfigEnd_Numero.Value;
nfceDS.Campo('xBairro_C09').Value := tNFConfigEnd_Bairro.Value;
nfceDS.Campo('cMun_C10').Value := tNFConfigEnd_CodMun.Value;
nfceDS.Campo('xMun_C11').Value := tNFConfigEnd_Municipio.Value;
nfceDS.Campo('UF_C12').Value := tNFConfigEnd_UF.Value;
nfceDS.Campo('CEP_C13').Value := tNFConfigEnd_CEP.Value;
nfceDS.Campo('cPais_C14').Value := '1058'; //Código do País
nfceDS.Campo('xPais_C15').Value := 'BRASIL'; //Nome do País
nfceDS.Campo('fone_C16').Value := tNFConfigTelefone.Value;
nfceDS.Campo('IE_C17').Value := tNFConfigIE.Value;
nfceDS.Campo('CRT_C21').Value := tNFConfigCRT.AsString;
end;
end;
function SoDig(S: String): String;
var I : Integer;
begin
Result := '';
for I := 1 to Length(S) do
if S[I] in ['0'..'9'] then
Result := Result + S[I];
end;
procedure AddNomeEmail;
begin
with DM do begin
if tNFConfigtpAmb.Value=2 then
nfceDS.Campo('xNome_E04').Value := ''
else begin
if (Length(SoDig(tCliCPF.Value))=11) or (Length(sl.Values['cpfnf'])=11) then
nfceDS.Campo('xNome_E04').Value := tCliNome.Value else
nfceDS.Campo('xNome_E04').Value := '';
end;
if (not FExtraEmail) and EmailValido(tCliEmail.Value) then begin
nfceDS.Campo('email_E19').Value := tCliEmail.Value;
DM.tNFEEmail.Value := tCliEmail.Value;
end else begin
if Trim(DM.tCliEmail.Value)='' then begin
DM.tCli.Edit;
DM.tCliEmail.Value := sl.Values['emailnf'];
DM.tCli.Post;
end;
end;
end;
end;
procedure AddExtraEmail;
var S: String;
begin
S := sl.Values['emailnf'];
if (trim(S)>'') then begin
nfceDS.Campo('email_E19').Value := S;
DM.tNFEEmail.Value := S;
FExtraEmail := True;
end else
FExtraEmail := False;
end;
procedure AddExtraCPF;
var S: String;
begin
S := sl.Values['cpfnf'];
if (trim(S)>'') then begin
nfceDS.Campo('CPF_E03').Value := SoDig(S);
DM.tNFECPF.Value := S;
FExtraCPF := True;
end else
FExtraCPF := False;
end;
procedure DadosDoDestinatario;
begin
nfceDS.Campo('CPF_E03').Value := '';
nfceDS.Campo('email_E19').Value := '';
nfceDS.Campo('xNome_E04').Value := '';
nfceDS.Campo('xLgr_E06').Value := '';
nfceDS.Campo('nro_E07').Value := '';
nfceDS.Campo('xBairro_E09').Value := '';
nfceDS.Campo('cMun_E10').Value := '';
nfceDS.Campo('xMun_E11').Value := '';
nfceDS.Campo('UF_E12').Value := '';
nfceDS.Campo('CEP_E13').Value := '';
nfceDS.Campo('cPais_E14').Value := '';
nfceDS.Campo('xPais_E15').Value := '';
nfceDS.Campo('indIEDest_E16a').Value := '9';
nfceDS.Campo('fone_E16').Value := '';
AddExtraEmail;
AddExtraCPF;
with DM do
if (tTranCliente.Value>0) and (tCliID.Value=tTranCliente.Value) then begin
if tCliPJuridica.Value and (Length(SoDig(tCliCPF.Value))>12) then begin
nfceDS.Campo('CNPJ_E02').Value := SoDig(tCliCPF.Value);
tNFECPF.Value := SoDig(tCliCPF.Value);
AddNomeEmail;
end else begin
if not FExtraCPF then begin
nfceDS.Campo('CPF_E03').Value := SoDig(tCliCPF.Value);
tNFECPF.Value := SoDig(tCliCPF.Value);
end else
if SoDig(tCliCPF.Value)<>SoDig(sl.Values['cpfnf']) then
begin
tCli.Edit;
tCliCPF.Value := sl.Values['cpfnf'];
tCli.Post;
end;
AddNomeEmail;
end;
end;
end;
function EAN13(S: String ): integer;
var i: integer;
begin
Result := 0;
S := copy(S, 1, 12);
{ Soma todos Números e Multiplica os Pares por 3 }
for i := 0 to Length( S ) -1 do
Result := Result + StrToInt( S[ i +1 ] ) * (( i mod 2 ) * 2 + 1);
{ 10 menos o Resto da divisão da soma por 10 }
Result := ( ( Ceil (Result / 10) * 10 ) - Result );
end;
function EAN_OK(S: String): Boolean;
begin
Result := (IntToStr(EAN13(S)) = Copy(S, 13, 1));
end;
procedure AdicionaItens;
var
aItem: Integer;
vImp : currency;
Q : Extended;
begin
aItem := 0;
vTotImp := 0;
DM.tMovEst.IndexName := 'ITranItem';
DM.tMovEst.SetRange([DM.tTranID.Value], [DM.tTranID.Value]);
with DM do
try
tNCM.IndexName := 'INCM';
tMovEst.First;
while not tMovEst.Eof do begin
tProduto.FindKey([tMovEstProduto.Value]);
if tProdutobrtrib.IsNull then
tBRTrib.FindKey([dm.tNFConfigTrib_Padrao.Value]) else
tBRTrib.FindKey([tProdutoBRTrib.Value]);
if tProdutoNCM.IsNull then
tNCM.FindKey([tNFConfigNCM_Padrao.Value{, tNFConfigNCMEx_Padrao}]) else
tNCM.FindKey([tProdutoNCM.Value, tProdutoNCM_Ex.Value]);
nfceDS.IncluirItem;
Inc(aItem);
nfceDS.Campo('cProd_I02').Value := tProdutoID.AsString;
nfceDS.Campo('nItem_H02').Value := IntToStr(aItem);
if (Length(tProdutoCodigo.Value)=13) and EAN_OK(tProdutoCodigo.Value) then begin
nfceDS.Campo('cEAN_I03').Value := tProdutoCodigo.Value;
nfceDS.Campo('cEANTrib_I12').Value := tProdutoCodigo.Value;
end;
nfceDS.Campo('xProd_I04').Value := Trim(tProdutoDescricao.Value);
nfceDS.Campo('NCM_I05').Value := tNCMNCM.Value;
nfceDS.Campo('CFOP_I08').Value := tBRTribCFOP_nfce.AsString;
nfceDS.Campo('uCom_I09').Value := tProdutoUnid.Value;
if (tMovEstTotal.Value>0) and (Frac(tMovEstQuant.Value)>0.00001) then
Q := tMovEstTotal.Value/tMovEstUnitario.Value else
Q := tMovEstQuant.Value;
nfceDS.Campo('qCom_I10').Value := FormatValor(Q, 4);
nfceDS.Campo('vUnCom_I10a').Value := FormatValor(tMovEstUnitario.Value, 4);
nfceDS.Campo('vProd_I11').Value := FormatValor(tMovEstTotal.Value, 2);
nfceDS.Campo('uTrib_I13').Value := tProdutoUnid.Value;
nfceDS.Campo('qTrib_I14').Value := FormatValor(Q, 4);
nfceDS.Campo('vUnTrib_I14a').Value := FormatValor(tMovEstUnitario.Value, 4);
if tMovEstDesconto.Value>=0.01 then
nfceDS.Campo('vDesc_I17').Value := FormatValor(tMovEstDesconto.Value, 2);
nfceDS.Campo('indTot_I17b').Value := '1'; //Indica se valor do Item (vProd) entra no valor total da NF-e (vProd)
//0 – o valor do item (vProd) não compõe o valor total da NF-e (vProd) 1 – o valor do item (vProd) compõe o valor total da NF-e (vProd)
vImp := CalcImp;
vTotImp := vTotImp + vImp;
nfceDS.Campo('vTotTrib_M02').Value := FormatValor(vImp, 2);
nfceDS.Campo('orig_N11').Value := tBRTribOrigem.AsString;
if tNFConfigCRT.Value=3 then
nfceDS.Campo('CST_N12').Value := ZeroPad(tBRTribCST.AsString, 2) else
nfceDS.Campo('CSOSN_N12a').Value := tBRTribCSOSN.AsString;
nfceDS.SalvarItem;
tMovEst.Next;
end;
finally
tMovEst.CancelRange;
end;
end;
Procedure DadosTotalizadores;
begin
with DM do begin
nfceDS.Campo('vBC_W03').Value := '0.00';
nfceDS.Campo('vICMS_W04').Value := '0.00';
nfceDS.Campo('vICMSDeson_W04a').Value := '0.00';
nfceDS.Campo('vBCST_W05').Value := '0.00'; //Base de Cálculo do ICMS ST
nfceDS.Campo('vST_W06').Value := '0.00'; //Valor Total do ICMS ST
nfceDS.Campo('vProd_W07').Value := FormatValor(tTranTotal.Value, 2);
nfceDS.Campo('vFrete_W08').Value := '0.00'; //Valor Total do Frete
nfceDS.Campo('vSeg_W09').Value := '0.00'; //Valor Total do Seguro
if tTranDesconto.Value>=0.01 then
nfceDS.Campo('vDesc_W10').Value := FormatValor(tTranDesconto.Value, 2) else
nfceDS.Campo('vDesc_W10').Value := '0.00';
nfceDS.Campo('vII_W11').Value := '0.00'; //Valor Total do II
nfceDS.Campo('vIPI_W12').Value := '0.00'; //Valor Total do IPI
nfceDS.Campo('vPIS_W13').Value := '0.00'; //Valor do PIS
nfceDS.Campo('vCOFINS_W14').Value := '0.00'; //Valor do COFINS
nfceDS.Campo('vOutro_W15').Value := '0.00'; //Outras Despesas acessórias
nfceDS.Campo('vNF_W16').Value := FormatValor(tTranTotLiq.Value, 2);
nfceDS.Campo('vTotTrib_W16a').Value := FormatValor(vTotImp, 2);
nfceDS.Campo('modFrete_X02').Value := '9'; //Modalidade do frete: 0- Por conta do emitente; 1- Por conta do destinatário/remetente; 2- Por conta de terceiros; 9- Sem frete.
end;
end;
procedure DadosPagamento;
var
V, Cred : Currency;
TotEsp : Array[1..99] of Currency;
T : Byte;
begin
DM.tPagEsp.IndexName := 'ITranID';
DM.tPagEsp.SetRange([DM.tTranID.Value], [DM.tTranID.Value]);
with DM do
try
Fillchar(TotEsp, SizeOf(TotEsp), 0);
Cred := tTranCredito.Value;
tPagEsp.First;
while not tPagEsp.Eof do begin
if tEspecie.FindKey([tPagEspEspecie.Value]) and (tEspecieTipoPagNFE.Value in [1..99]) then
T := tEspecieTipoPagNFE.Value else
T := 1;
V := tPagEspValor.Value-tPagEspTroco.Value;
if Cred>0 then begin
if Cred>=V then begin
Cred := Cred - V;
V := 0;
end else begin
V := V - Cred;
Cred := 0;
end;
end;
TotEsp[T] := TotEsp[T] + V;
tPagEsp.Next;
end;
TotEsp[5] := tTranDebito.Value + tTranCreditoUsado.Value;
for T := 1 to 99 do
if TotEsp[T]>0.009 then begin
nfceDS.IncluirPart('YA');
nfceDS.Campo('tPag_YA02').Value := ZeroPad(IntToStr(T), 2);
nfceDS.Campo('vPag_YA03').Value := FormatValor(TotEsp[T], 2);
nfceDS.SalvarPart('YA');
end;
finally
tPagEsp.CancelRange;
end;
end;
procedure Gera(aCont: Boolean);
begin
nfceDS.LoteNFCe.Clear;
nfceDS.Incluir;
DadosDoNFCe;
DadosDoEmitente;
DadosDoDestinatario;
AdicionaItens;
DadosTotalizadores;
DadosPagamento;
if aCont then begin
nfceDS.Campo('dhCont_B28').Value := FormatDateTime('YYYY-mm-dd"T"HH:mm:ss',now) + TimeZoneStr;
nfceDS.Campo('xJust_B29').Value := 'Sem internet ou sem comunicacao com SEFAZ';
nfceDS.Campo('tpEmis_B22').Value := '9';
end;
nfceDS.Salvar;
if aCont then begin
aChaveCont := Copy(nfceDS.Campo('Id_A03').AsString,4,44);
DM.tNFEXMLtransCont.Value := nfceComp.AssinarNota(nfceDS.LoteNFCe.GetText);
end else begin
aChaveNormal := Copy(nfceDS.Campo('Id_A03').AsString,4,44);
DM.tNFEXMLtrans.Value := nfceComp.AssinarNota(nfceDS.LoteNFCe.GetText)
end;
end;
begin
sl := TStringList.Create;
try
sl.Text := DM.tTranExtra.Value;
_Dir := ExtractFilePath(ParamStr(0))+'NFCe\Templates\vm50a\Conversor\NFCeDataSets.xml';
nfceDS.VersaoEsquema := pl_008d;
nfceDS.XMLDicionario := _Dir;
nfceDS.LoteNFCe.Clear;
Gera(False);
Gera(True);
if Contingencia then begin
DM.tNFEContingencia.Value := True;
DM.tNFEStatus.Value := nfestatus_contingencia;
DM.tNFEChave.Value := aChaveCont;
end else begin
DM.tNFEStatus.Value := nfestatus_transmitir;
DM.tNFEContingencia.Value := False;
DM.tNFEChave.Value := aChaveNormal;
end;
finally
sl.Free;
end;
end;
function TdmNFe.ProxNumNFCe: Cardinal;
var
C: Cardinal;
aSerie: String;
begin
with DM do begin
tAuxNFE.Active := True;
tAuxNFE.IndexName := 'ItpAmbModeloSerieNumero';
aSerie := tNFConfigSerieNFCe.Value;
tAuxNFE.SetRange([tNFConfigtpAmb.Value, '65', aSerie], [tNFConfigtpAmb.Value, '65', aSerie]);
if tAuxNFE.IsEmpty then
C := 0
else begin
tAuxNFE.Last;
C := tAuxNFENumero.Value;
end;
if (C<tNFConfigInicioNFCe.Value) then
Result := tNFConfigInicioNFCe.Value
else begin
tAuxNFE.Last;
C := tAuxNFENumero.Value;
Result := C + 1;
end;
end;
end;
procedure TdmNFe.ValidaXML;
var S: String;
begin
sErroValid := '';
if Contingencia then
S := DM.tNFEXMLtransCont.Value else
S := DM.tNFEXMLtrans.Value;
try
nfceComp.ValidarLoteParaEnvio('0001', S);
except
on E: Exception do sErroValid := E.Message;
end;
end;
end.
|
unit BodyKindsQuery;
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, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.StdCtrls, OrderQuery, DSWrap;
type
TBodyKindW = class(TOrderW)
private
FBodyKind: TFieldWrap;
FID: TFieldWrap;
FColor: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
procedure AddNewValue(const AValue: string);
procedure ApplyColor(AIDArr: TArray<Integer>; AColor: TColor);
procedure LocateOrAppend(AValue: string);
property BodyKind: TFieldWrap read FBodyKind;
property ID: TFieldWrap read FID;
property Color: TFieldWrap read FColor;
end;
TQueryBodyKinds = class(TQueryOrder)
private
FShowDuplicate: Boolean;
FW: TBodyKindW;
procedure SetShowDuplicate(const Value: Boolean);
{ Private declarations }
protected
function CreateDSWrap: TDSWrap; override;
public
constructor Create(AOwner: TComponent); override;
property ShowDuplicate: Boolean read FShowDuplicate write SetShowDuplicate;
property W: TBodyKindW read FW;
{ Public declarations }
end;
implementation
uses NotifyEvents, StrHelper;
{$R *.dfm}
constructor TQueryBodyKinds.Create(AOwner: TComponent);
begin
inherited;
FW := FDSWrap as TBodyKindW;
AutoTransaction := False;
// Не проверять необходимость заполнения полей на клиенте
FDQuery.UpdateOptions.CheckRequired := False;
end;
function TQueryBodyKinds.CreateDSWrap: TDSWrap;
begin
Result := TBodyKindW.Create(FDQuery);
end;
procedure TQueryBodyKinds.SetShowDuplicate(const Value: Boolean);
var
ASQL: String;
begin
if FShowDuplicate = Value then
Exit;
FShowDuplicate := Value;
// Получаем первоначальный запрос
ASQL := SQL;
if FShowDuplicate then
begin
ASQL := ASQL.Replace('/* ShowDuplicate', '', [rfReplaceAll]);
ASQL := ASQL.Replace('ShowDuplicate */', '', [rfReplaceAll]);
end;
FDQuery.Close;
FDQuery.SQL.Text := ASQL;
FDQuery.Open;
end;
constructor TBodyKindW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FOrd := TFieldWrap.Create(Self, 'Ord');
FBodyKind := TFieldWrap.Create(Self, 'BodyKind');
FColor := TFieldWrap.Create(Self, 'Color');
end;
procedure TBodyKindW.AddNewValue(const AValue: string);
begin
TryAppend;
BodyKind.F.AsString := AValue;
TryPost;
end;
procedure TBodyKindW.ApplyColor(AIDArr: TArray<Integer>; AColor: TColor);
var
AID: Integer;
begin
Assert(Length(AIDArr) > 0);
SaveBookmark;
for AID in AIDArr do
begin
ID.Locate(AID, [], True);
TryEdit;
Color.F.AsInteger := AColor;
TryPost;
end;
RestoreBookmark;
end;
procedure TBodyKindW.LocateOrAppend(AValue: string);
begin
if not FDDataSet.LocateEx(BodyKind.FieldName, AValue, [lxoCaseInsensitive])
then
AddNewValue(AValue);
end;
end.
|
Program NinetyNine;
Uses sysutils;
Var
i: Integer;
Begin
For i := 99 downto 1 do
begin
WriteLn(IntToStr(i) + ' bottles of beer on the wall, ' + IntToStr(i) + ' bottles of beer');
WriteLn('Take one down and pass it around, ' + IntToStr(i-1) + ' bottles of beer on the wall');
end;
ReadLn;
End. |
(*****************************************************************************
* Pascal Solution to "It Makes No Difference in the End" from the *
* *
* Seventh Annual UCF ACM UPE High School Programming Tournament *
* May 15, 1993 *
* *
*****************************************************************************)
program subtract;
var
f: text;
num: array[1..5] of integer;
(** This function determines whether **)
(** the four numbers are all zeroes. **)
function all_zeroes: boolean;
var
zero: boolean;
i: integer;
begin
zero := true;
for i := 1 to 4 do
begin
if ( num[i] <> 0 ) then
begin
zero := false;
end;
end;
all_zeroes := zero;
end;
(** This procedure writes out the sequence **)
(** and updates it using the differences. **)
procedure write_and_update;
var
i: integer;
begin
num[5] := num[1]; (* This makes finding differences easier *)
for i := 1 to 4 do
begin
write( num[i]:5 );
num[i] := abs( num[i] - num[i+1] );
end;
writeln;
end;
(*** Main program ***)
begin
assign( f, 'subtract.in' );
reset( f );
while not eof( f ) do
begin
readln( f, num[1], num[2], num[3], num[4] );
repeat
write_and_update;
until all_zeroes;
writeln;
end;
close( f );
end.
|
unit FIToolkit.Config.Defaults;
interface
uses
System.SysUtils, System.Rtti, System.Generics.Collections,
FIToolkit.Config.Types;
type
TDefaultValueAttributeClass = class of TDefaultValueAttribute;
TDefaultValueAttribute = class abstract (TCustomAttribute)
strict private
FValueKind : TDefaultValueKind;
private
function GetClassType : TDefaultValueAttributeClass;
function GetValue : TValue;
strict protected
FValue : TValue;
constructor Create(AValueKind : TDefaultValueKind);
protected
function CalculateValue : TValue; virtual;
public
property Value : TValue read GetValue;
property ValueKind : TDefaultValueKind read FValueKind;
end;
TDefaultValueAttribute<T> = class abstract (TDefaultValueAttribute)
protected
function MakeValue(const AValue : T) : TValue; virtual;
public
constructor Create(const AValue : T); overload;
constructor Create; overload;
end;
TDefaultsMap = class sealed
strict private
type
TInternalMap = class (TDictionary<TDefaultValueAttributeClass, TValue>);
strict private
class var
FInternalMap : TInternalMap;
FStaticInstance : TDefaultsMap;
private
class constructor Create;
class destructor Destroy;
protected
class property StaticInstance : TDefaultsMap read FStaticInstance;
public
class procedure AddValue(DefValAttribClass : TDefaultValueAttributeClass; Value : TValue);
class function GetValue(DefValAttribClass : TDefaultValueAttributeClass) : TValue;
class function HasValue(DefValAttribClass : TDefaultValueAttributeClass) : Boolean;
end;
procedure RegisterDefaultValue(DefValAttribClass : TDefaultValueAttributeClass; Value : TValue); overload;
procedure RegisterDefaultValue(DefValAttribClass : TDefaultValueAttributeClass;
const Evaluator : TFunc<TValue>); overload;
implementation
{ Utils }
procedure RegisterDefaultValue(DefValAttribClass : TDefaultValueAttributeClass; Value : TValue);
begin
TDefaultsMap.StaticInstance.AddValue(DefValAttribClass, Value);
end;
procedure RegisterDefaultValue(DefValAttribClass : TDefaultValueAttributeClass; const Evaluator : TFunc<TValue>);
begin
RegisterDefaultValue(DefValAttribClass, Evaluator());
end;
{ TDefaultValueAttribute }
constructor TDefaultValueAttribute.Create(AValueKind : TDefaultValueKind);
begin
inherited Create;
FValue := TValue.Empty;
FValueKind := AValueKind;
end;
function TDefaultValueAttribute.CalculateValue : TValue;
begin
with TDefaultsMap.StaticInstance do
if HasValue(Self.GetClassType) then
Result := GetValue(Self.GetClassType)
else
Result := TValue.Empty;
end;
function TDefaultValueAttribute.GetClassType : TDefaultValueAttributeClass;
begin
Result := TDefaultValueAttributeClass(ClassType);
end;
function TDefaultValueAttribute.GetValue : TValue;
begin
Result := TValue.Empty;
case FValueKind of
dvkData:
Result := FValue;
dvkCalculated:
Result := CalculateValue;
else
Assert(False, 'Unhandled default value kind while getting value.');
end;
end;
{ TDefaultValueAttribute<T> }
constructor TDefaultValueAttribute<T>.Create(const AValue : T);
begin
inherited Create(dvkData);
FValue := MakeValue(AValue);
end;
constructor TDefaultValueAttribute<T>.Create;
begin
inherited Create(dvkCalculated);
end;
function TDefaultValueAttribute<T>.MakeValue(const AValue : T) : TValue;
begin
Result := TValue.From<T>(AValue);
end;
{ TDefaultsMap }
class procedure TDefaultsMap.AddValue(DefValAttribClass : TDefaultValueAttributeClass; Value : TValue);
begin
StaticInstance.FInternalMap.Add(DefValAttribClass, Value);
end;
class constructor TDefaultsMap.Create;
begin
FInternalMap := TInternalMap.Create;
FStaticInstance := TDefaultsMap.Create;
end;
class destructor TDefaultsMap.Destroy;
begin
FreeAndNil(FInternalMap);
FreeAndNil(FStaticInstance);
end;
class function TDefaultsMap.GetValue(DefValAttribClass : TDefaultValueAttributeClass) : TValue;
begin
Result := StaticInstance.FInternalMap.Items[DefValAttribClass];
end;
class function TDefaultsMap.HasValue(DefValAttribClass : TDefaultValueAttributeClass) : Boolean;
begin
Result := StaticInstance.FInternalMap.ContainsKey(DefValAttribClass);
end;
end.
|
unit adot.Collections.Heap;
interface
{
TBHeap<TKey, TValue> Binary heap functions
TBinaryHeapClass<TKey,TValue> Binary heap implementation for pairs <TKey,TValues>
TBinaryHeapClass<TKey> Binary heap implementation for <TKey>
}
uses
adot.Types,
adot.Collections.Types,
adot.Collections.Vectors,
System.Generics.Collections,
System.Generics.Defaults,
System.SysUtils;
type
{ Low level heap operations on array.}
TBHeap<TKey, TValue> = class
class function GetLeft(ParentIdx: integer): integer; static;
class function GetRight(ParentIdx: integer): integer; static;
class function GetParent(ChildIdx: integer): integer; static;
class procedure MoveUp(var Items: TArray<TPair<TKey,TValue>>; ItemIndex: integer; Comparer: IComparer<TKey>); static;
class procedure Delete(var Items: TArray<TPair<TKey,TValue>>; ItemIndex,Count: integer; Comparer: IComparer<TKey>); static;
class function ExtractMin(var Items: TArray<TPair<TKey,TValue>>; Count: integer; Comparer: IComparer<TKey>):TPair<TKey,TValue>; static;
class procedure Build(var Items: TArray<TPair<TKey,TValue>>; Count: integer; Comparer: IComparer<TKey>); static;
class procedure Sort(var Items: TArray<TPair<TKey,TValue>>; Count: integer; Comparer: IComparer<TKey>); static;
class procedure Replace(var Items: TArray<TPair<TKey,TValue>>; ItemIndex,Count: integer;
Comparer: IComparer<TKey>; const Pair:TPair<TKey,TValue>); static;
end;
{ Binary heap of pairs [Key;Value]. }
TBinaryHeapClass<TKey,TValue> = class(TEnumerableExt<TPair<TKey,TValue>>)
public
type
TPairsEnumerator = TVector<TPair<TKey,TValue>>.TEnumerator;
{# Enumerator for heap (we have to inherit from TEnumerator to be comatible with TEnumerable) }
TBinaryHeapEnumerator = class(TEnumerator<TPair<TKey, TValue>>)
protected
PairEnumerator: TPairsEnumerator;
function DoGetCurrent: TPair<TKey, TValue>; override;
function DoMoveNext: Boolean; override;
public
constructor Create(const PairEnumerator: TPairsEnumerator);
end;
{# Enumerator of keys }
TKeyEnumerator = record
private
PairEnumerator: TPairsEnumerator;
function GetCurrent: TKey;
public
procedure Init(const APairEnumerator: TPairsEnumerator);
function MoveNext: Boolean;
property Current: TKey read GetCurrent;
end;
{# Collection of keys }
TKeyCollection = record
private
PairEnumerator: TPairsEnumerator;
public
procedure Init(const APairEnumerator: TPairsEnumerator);
function GetEnumerator: TKeyEnumerator;
end;
protected
FItems: TVector<TPair<TKey,TValue>>;
FComparer: IComparer<TKey>;
FOwnerships: TDictionaryOwnerships;
function GetCapacity: integer;
function GetCount: integer;
procedure SetCapacity(ACapacity: integer);
procedure SetValue(n: integer; const Value: TPair<TKey, TValue>);
function GetValue(Index: integer): TPair<TKey,TValue>;
function GetKeyCollection: TKeyCollection;
function DoGetEnumerator: TEnumerator<TPair<TKey, TValue>>; override;
function GetOwnsKeys: boolean;
function GetOwnsValues: boolean;
procedure SetOwnsKeys(const Value: boolean);
procedure SetOwnsValues(const Value: boolean);
procedure DisposeItem(n: integer);
procedure DisposeAll;
{ this function is O(N), avoid of use it }
function Find(const Key: TKey): integer;
public
constructor Create(ACapacity: integer = 0); overload;
constructor Create(ACapacity: integer; AComparer: IComparer<TKey>); overload;
constructor Create(ACapacity: integer; AComparison: TComparison<TKey>); overload;
constructor Create(const ACollection: TEnumerable<TPair<TKey,TValue>>; ACapacity: integer = 0; AComparison: TComparison<TKey> = nil); overload;
destructor Destroy; override;
function Add(const Key: TKey; const Value: TValue): integer; overload;
function Add(const Pair: TPair<TKey,TValue>): integer; overload;
procedure Add(const Values: TArray<TPair<TKey,TValue>>); overload;
procedure Add(const Values: TEnumerable<TPair<TKey,TValue>>); overload;
function MinValue: TPair<TKey,TValue>; { O(1) }
function ExtractMin: TPair<TKey,TValue>; { O(Log(n)) }
procedure DeleteMin;
procedure Delete(n: integer);
procedure Clear;
procedure TrimExcess;
function Empty: boolean;
property Count: integer read GetCount;
property Capacity: integer read GetCapacity write SetCapacity;
property Values[n: integer]: TPair<TKey,TValue> read GetValue write SetValue; default;
property Keys: TKeyCollection read GetKeyCollection;
property Comparer: IComparer<TKey> read FComparer;
property OwnsKeys: boolean read GetOwnsKeys write SetOwnsKeys;
property OwnsValues: boolean read GetOwnsValues write SetOwnsValues;
end;
{ Binary heap with key only. }
TBinaryHeapClass<TKey> = class(TEnumerableExt<TKey>)
protected
type
{# Enumerator for heap (we have to inherit from TEnumerator to be comatible with TEnumerable) }
TBinaryHeapEnumerator = class(TEnumerator<TKey>)
protected
FPairEnumerator: TEnumerator<TPair<TKey, TEmptyRec>>;
function DoGetCurrent: TKey; override;
function DoMoveNext: Boolean; override;
public
constructor Create(const PairEnumerator: TEnumerator<TPair<TKey, TEmptyRec>>);
destructor Destroy; override;
end;
var
FHeap: TBinaryHeapClass<TKey,TEmptyRec>;
function DoGetEnumerator: TEnumerator<TKey>; override;
function GetCapacity: integer;
function GetCount: integer;
function GetValue(n: integer): TKey;
procedure SetCapacity(const Value: integer);
procedure SetValue(n: integer; const Value: TKey);
{ this function is O(N), avoid of use it }
function Find(const Key: TKey): integer;
public
constructor Create(ACapacity: integer = 0); overload;
constructor Create(ACapacity: integer; AComparer: IComparer<TKey>); overload;
constructor Create(ACapacity: integer; AComparison: TComparison<TKey>); overload;
constructor Create(const ACollection: TEnumerable<TKey>; ACapacity: integer = 0; AComparison: TComparison<TKey> = nil); overload;
destructor Destroy; override;
function Add(const Value: TKey): integer; overload;
procedure Add(const Values: TArray<TKey>); overload;
procedure Add(const Values: TEnumerable<TKey>); overload;
function MinValue: TKey; { O(1) }
function ExtractMin: TKey; { O(Log(n)) }
procedure DeleteMin;
procedure Delete(n: integer);
procedure Clear;
procedure TrimExcess;
function Empty: boolean;
property Count: integer read GetCount;
property Capacity: integer read GetCapacity write SetCapacity;
property Values[n: integer]: TKey read GetValue write SetValue; default;
end;
implementation
uses
adot.Tools,
adot.Collections,
adot.Tools.RTTI;
{ TBHeap<TKey, TValue> }
class function TBHeap<TKey, TValue>.GetLeft(ParentIdx: integer): integer;
begin
result := (ParentIdx shl 1) + 1;
end;
class function TBHeap<TKey, TValue>.GetRight(ParentIdx: integer): integer;
begin
result := (ParentIdx shl 1) + 2;
end;
class function TBHeap<TKey, TValue>.GetParent(ChildIdx: integer): integer;
begin
result := (ChildIdx - 1) shr 1;
end;
class procedure TBHeap<TKey, TValue>.MoveUp(var Items: TArray<TPair<TKey, TValue>>;
ItemIndex: integer; Comparer: IComparer<TKey>);
var
ParentIndex: Integer;
Value: TPair<TKey, TValue>;
begin
while ItemIndex > 0 do
begin
ParentIndex := GetParent(ItemIndex);
if Comparer.Compare(Items[ParentIndex].Key, Items[ItemIndex].Key)<=0 then
Break;
Value := Items[ParentIndex];
Items[ParentIndex] := Items[ItemIndex];
Items[ItemIndex] := Value;
ItemIndex := ParentIndex;
end;
end;
class procedure TBHeap<TKey, TValue>.Replace(var Items: TArray<TPair<TKey, TValue>>; ItemIndex, Count: integer;
Comparer: IComparer<TKey>; const Pair: TPair<TKey, TValue>);
begin
Delete(Items, ItemIndex,Count, Comparer);
Items[Count-1] := Pair;
MoveUp(Items, Count-1, Comparer);
end;
class procedure TBHeap<TKey, TValue>.Delete(var Items: TArray<TPair<TKey, TValue>>;
ItemIndex,Count: integer; Comparer: IComparer<TKey>);
var
L,R: integer;
begin
repeat
L := GetLeft(ItemIndex);
if L >= Count then
Break;
R := GetRight(ItemIndex);
if R >= Count then
begin
Items[ItemIndex] := Items[L];
ItemIndex := L;
Break;
end;
if Comparer.Compare(Items[L].Key, Items[R].Key) < 0 then
begin
Items[ItemIndex] := Items[L];
ItemIndex := L;
end
else
begin
Items[ItemIndex] := Items[R];
ItemIndex := R;
end;
until False;
if ItemIndex < Count-1 then
begin
Items[ItemIndex] := Items[Count-1];
MoveUp(Items, ItemIndex, Comparer);
end;
end;
class function TBHeap<TKey, TValue>.ExtractMin(var Items: TArray<TPair<TKey, TValue>>;
Count: integer; Comparer: IComparer<TKey>): TPair<TKey, TValue>;
begin
result := Items[0];
Delete(Items, 0, Count, Comparer);
end;
class procedure TBHeap<TKey, TValue>.Build(var Items: TArray<TPair<TKey, TValue>>;
Count: integer; Comparer: IComparer<TKey>);
var
I: Integer;
begin
for I := Low(Items)+1 to Count-1 do
MoveUp(Items, I, Comparer);
end;
class procedure TBHeap<TKey, TValue>.Sort(var Items: TArray<TPair<TKey, TValue>>;
Count: integer; Comparer: IComparer<TKey>);
var
I: Integer;
begin
Build(Items, Count, Comparer);
for I := Length(Items)-1 downto 0 do
Items[I] := ExtractMin(Items, I+1, Comparer);
TArrayUtils.Inverse<TPair<TKey, TValue>>(Items);
end;
{ TBinaryHeapClass<TKey, TValue>.TEnumerator }
constructor TBinaryHeapClass<TKey, TValue>.TBinaryHeapEnumerator.Create(const PairEnumerator: TPairsEnumerator);
begin
inherited Create;
Self.PairEnumerator := PairEnumerator;
end;
function TBinaryHeapClass<TKey, TValue>.TBinaryHeapEnumerator.DoGetCurrent: TPair<TKey, TValue>;
begin
result := PairEnumerator.Current;
end;
function TBinaryHeapClass<TKey, TValue>.TBinaryHeapEnumerator.DoMoveNext: Boolean;
begin
result := PairEnumerator.MoveNext;
end;
{ TBinaryHeapClass<TKey, TValue>.TKeyEnumerator }
procedure TBinaryHeapClass<TKey, TValue>.TKeyEnumerator.Init(const APairEnumerator: TPairsEnumerator);
begin
Self := Default(TKeyEnumerator);
PairEnumerator := APairEnumerator;
end;
function TBinaryHeapClass<TKey, TValue>.TKeyEnumerator.GetCurrent: TKey;
begin
result := PairEnumerator.Current.Key;
end;
function TBinaryHeapClass<TKey, TValue>.TKeyEnumerator.MoveNext: Boolean;
begin
result := PairEnumerator.MoveNext;
end;
{ TBinaryHeapClass<TKey, TValue>.TKeyCollection }
procedure TBinaryHeapClass<TKey, TValue>.TKeyCollection.Init(const APairEnumerator: TPairsEnumerator);
begin
Self := Default(TKeyCollection);
PairEnumerator := APairEnumerator;
end;
function TBinaryHeapClass<TKey, TValue>.TKeyCollection.GetEnumerator: TKeyEnumerator;
begin
result.Init(PairEnumerator);
end;
{ TBinaryHeapClass<TKey, TValue> }
constructor TBinaryHeapClass<TKey, TValue>.Create(ACapacity: integer);
begin
inherited Create;
Capacity := ACapacity;
FComparer := TComparerUtils.DefaultComparer<TKey>;
end;
constructor TBinaryHeapClass<TKey, TValue>.Create(ACapacity: integer; AComparer: IComparer<TKey>);
begin
inherited Create;
Capacity := ACapacity;
if AComparer=nil
then FComparer := TComparerUtils.DefaultComparer<TKey>
else FComparer := AComparer;
end;
constructor TBinaryHeapClass<TKey, TValue>.Create(ACapacity: integer; AComparison: TComparison<TKey>);
var
C: IComparer<TKey>;
begin
if Assigned(AComparison)
then C := TDelegatedComparer<TKey>.Create(AComparison)
else C := nil;
Create(ACapacity, C);
end;
constructor TBinaryHeapClass<TKey, TValue>.Create(const ACollection: TEnumerable<TPair<TKey, TValue>>;
ACapacity: integer; AComparison: TComparison<TKey>);
begin
Create(ACapacity, AComparison);
Add(ACollection);
end;
destructor TBinaryHeapClass<TKey, TValue>.Destroy;
begin
Clear;
FComparer := nil;
inherited;
end;
procedure TBinaryHeapClass<TKey, TValue>.Clear;
begin
DisposeAll;
FItems.Clear;
end;
procedure TBinaryHeapClass<TKey, TValue>.DeleteMin;
begin
Delete(0);
end;
procedure TBinaryHeapClass<TKey, TValue>.Delete(n: integer);
begin
DisposeItem(n);
TBHeap<TKey, TValue>.Delete(FItems.Items, n, Count, FComparer);
FItems.Delete(Count-1);
end;
function TBinaryHeapClass<TKey, TValue>.Empty: boolean;
begin
result := FItems.Count=0;
end;
function TBinaryHeapClass<TKey, TValue>.Find(const Key: TKey): integer;
var
I: Integer;
begin
for I := 0 to Count-1 do
if FComparer.Compare(FItems.Items[I].Key, Key)=0 then
Exit(I);
result := -1;
end;
function TBinaryHeapClass<TKey, TValue>.GetCapacity: integer;
begin
result := FItems.Capacity;
end;
function TBinaryHeapClass<TKey, TValue>.GetCount: integer;
begin
result := FItems.Count;
end;
function TBinaryHeapClass<TKey, TValue>.DoGetEnumerator: TEnumerator<TPair<TKey, TValue>>;
begin
result := TBinaryHeapEnumerator.Create(FItems.GetEnumerator);
end;
function TBinaryHeapClass<TKey, TValue>.GetKeyCollection: TKeyCollection;
begin
result.Init( FItems.GetEnumerator );
end;
function TBinaryHeapClass<TKey, TValue>.GetOwnsKeys: boolean;
begin
result := doOwnsKeys in FOwnerships;
end;
function TBinaryHeapClass<TKey, TValue>.GetOwnsValues: boolean;
begin
result := doOwnsValues in FOwnerships;
end;
procedure TBinaryHeapClass<TKey, TValue>.SetOwnsKeys(const Value: boolean);
begin
if Value and not TRttiUtils.IsInstance<TKey> then
raise Exception.Create('Generic type is not a class.');
if Value
then include(FOwnerships, doOwnsKeys)
else exclude(FOwnerships, doOwnsKeys);
end;
procedure TBinaryHeapClass<TKey, TValue>.SetOwnsValues(const Value: boolean);
begin
if Value and not TRttiUtils.IsInstance<TValue> then
raise Exception.Create('Generic type is not a class.');
if Value
then include(FOwnerships, doOwnsValues)
else exclude(FOwnerships, doOwnsValues);
end;
function TBinaryHeapClass<TKey, TValue>.GetValue(Index: integer): TPair<TKey, TValue>;
begin
result := FItems.Items[Index];
end;
procedure TBinaryHeapClass<TKey, TValue>.SetCapacity(ACapacity: integer);
begin
FItems.Capacity := ACapacity;
end;
procedure TBinaryHeapClass<TKey, TValue>.DisposeAll;
var
I: Integer;
begin
if FOwnerships<>[] then
for I := 0 to FItems.Count-1 do
begin
if doOwnsKeys in FOwnerships then
PObject(@FItems.Items[I].Key)^.DisposeOf;
if doOwnsValues in FOwnerships then
PObject(@FItems.Items[I].Value)^.DisposeOf;
end;
end;
procedure TBinaryHeapClass<TKey, TValue>.DisposeItem(n: integer);
begin
if FOwnerships<>[] then
begin
if doOwnsKeys in FOwnerships then
PObject(@FItems.Items[n].Key)^.DisposeOf;
if doOwnsValues in FOwnerships then
PObject(@FItems.Items[n].Value)^.DisposeOf;
end;
end;
procedure TBinaryHeapClass<TKey, TValue>.SetValue(n: integer; const Value: TPair<TKey, TValue>);
begin
DisposeItem(n);
TBHeap<TKey, TValue>.Replace(FItems.Items, n, Count, FComparer, Value);
end;
procedure TBinaryHeapClass<TKey, TValue>.TrimExcess;
begin
FItems.TrimExcess;
end;
function TBinaryHeapClass<TKey, TValue>.Add(const Pair: TPair<TKey, TValue>): integer;
begin
result := FItems.Add(Pair);
TBHeap<TKey, TValue>.MoveUp(FItems.Items, result, FComparer);
end;
function TBinaryHeapClass<TKey, TValue>.Add(const Key: TKey; const Value: TValue): integer;
var
P: TPair<TKey,TValue>;
begin
P.Key := Key;
P.Value := Value;
result := FItems.Add(P);
TBHeap<TKey, TValue>.MoveUp(FItems.Items, result, FComparer);
end;
procedure TBinaryHeapClass<TKey, TValue>.Add(const Values: TEnumerable<TPair<TKey, TValue>>);
var
Pair: TPair<TKey, TValue>;
I: Integer;
begin
for Pair in Values do
begin
I := FItems.Add(Pair);
TBHeap<TKey, TValue>.MoveUp(FItems.Items, I, FComparer);
end;
end;
procedure TBinaryHeapClass<TKey, TValue>.Add(const Values: TArray<TPair<TKey, TValue>>);
var
I,J: Integer;
begin
for I := Low(Values) to High(Values) do
begin
J := FItems.Add(Values[I]);
TBHeap<TKey, TValue>.MoveUp(FItems.Items, J, FComparer);
end;
end;
function TBinaryHeapClass<TKey, TValue>.ExtractMin: TPair<TKey, TValue>;
begin
result := FItems.Items[0];
DeleteMin;
end;
function TBinaryHeapClass<TKey, TValue>.MinValue: TPair<TKey, TValue>;
begin
result := FItems.Items[0];
end;
{ TBinaryHeapClass<TKey>.TEnumerator }
constructor TBinaryHeapClass<TKey>.TBinaryHeapEnumerator.Create(const PairEnumerator: TEnumerator<TPair<TKey, TEmptyRec>>);
begin
inherited Create;
FPairEnumerator := PairEnumerator;
end;
destructor TBinaryHeapClass<TKey>.TBinaryHeapEnumerator.Destroy;
begin
FreeAndNil(FPairEnumerator);
inherited;
end;
function TBinaryHeapClass<TKey>.TBinaryHeapEnumerator.DoGetCurrent: TKey;
begin
result := FPairEnumerator.Current.Key;
end;
function TBinaryHeapClass<TKey>.TBinaryHeapEnumerator.DoMoveNext: Boolean;
begin
result := FPairEnumerator.MoveNext;
end;
{ TBinaryHeapClass<TKey> }
constructor TBinaryHeapClass<TKey>.Create(ACapacity: integer);
begin
inherited Create;
FHeap := TBinaryHeapClass<TKey,TEmptyRec>.Create(ACapacity);
end;
constructor TBinaryHeapClass<TKey>.Create(ACapacity: integer; AComparer: IComparer<TKey>);
begin
inherited Create;
FHeap := TBinaryHeapClass<TKey,TEmptyRec>.Create(ACapacity, AComparer);
end;
constructor TBinaryHeapClass<TKey>.Create(ACapacity: integer; AComparison: TComparison<TKey>);
var
C: IComparer<TKey>;
begin
if Assigned(AComparison)
then C := TDelegatedComparer<TKey>.Create(AComparison)
else C := nil;
Create(ACapacity, C);
end;
constructor TBinaryHeapClass<TKey>.Create(const ACollection: TEnumerable<TKey>; ACapacity: integer; AComparison: TComparison<TKey>);
begin
Create(ACapacity, AComparison);
Add(ACollection);
end;
procedure TBinaryHeapClass<TKey>.Clear;
begin
FHeap.Clear;
end;
procedure TBinaryHeapClass<TKey>.Delete(n: integer);
begin
FHeap.Delete(n);
end;
procedure TBinaryHeapClass<TKey>.DeleteMin;
begin
FHeap.DeleteMin;
end;
destructor TBinaryHeapClass<TKey>.Destroy;
begin
FreeAndNil(FHeap);
inherited;
end;
function TBinaryHeapClass<TKey>.DoGetEnumerator: TEnumerator<TKey>;
begin
result := TBinaryHeapEnumerator.Create(FHeap.GetEnumerator);
end;
function TBinaryHeapClass<TKey>.Add(const Value: TKey): integer;
var
P: TPair<TKey,TEmptyRec>;
begin
P.Key := Value;
result := FHeap.Add(P);
end;
procedure TBinaryHeapClass<TKey>.Add(const Values: TArray<TKey>);
var
P: TPair<TKey, TEmptyRec>;
I: Integer;
begin
I := Count + Length(Values);
if I > Capacity then
Capacity := I;
for I := Low(Values) to High(Values) do
begin
P.Key := Values[I];
FHeap.Add(P);
end;
end;
procedure TBinaryHeapClass<TKey>.Add(const Values: TEnumerable<TKey>);
var
P: TPair<TKey, TEmptyRec>;
K: TKey;
begin
for K in Values do
begin
P.Key := K;
FHeap.Add(P);
end;
end;
function TBinaryHeapClass<TKey>.MinValue: TKey;
begin
result := FHeap.MinValue.Key;
end;
function TBinaryHeapClass<TKey>.Empty: boolean;
begin
result := FHeap.Empty;
end;
procedure TBinaryHeapClass<TKey>.SetCapacity(const Value: integer);
begin
FHeap.Capacity := Value;
end;
procedure TBinaryHeapClass<TKey>.SetValue(n: integer; const Value: TKey);
var
p: TPair<TKey, TEmptyRec>;
begin
p.Key := Value;
FHeap.Values[n] := p;
end;
procedure TBinaryHeapClass<TKey>.TrimExcess;
begin
FHeap.TrimExcess;
end;
function TBinaryHeapClass<TKey>.ExtractMin: TKey;
begin
result := FHeap.ExtractMin.Key;
end;
function TBinaryHeapClass<TKey>.Find(const Key: TKey): integer;
begin
result := FHeap.Find(Key);
end;
function TBinaryHeapClass<TKey>.GetCapacity: integer;
begin
result := FHeap.Capacity;
end;
function TBinaryHeapClass<TKey>.GetCount: integer;
begin
result := FHeap.Count;
end;
function TBinaryHeapClass<TKey>.GetValue(n: integer): TKey;
begin
result := FHeap.Values[n].Key;
end;
end.
|
{$MODE OBJFPC} { -*- delphi -*- }
{$INCLUDE settings.inc}
unit players;
interface
uses
hashfunctions, hashtable, genericutils;
type
TPlayerID = String[10];
TPlayer = class
protected
FName: UTF8String;
FID: TPlayerID;
public
constructor Create(const Name: UTF8String; const ID: TPlayerID);
property Name: UTF8String read FName;
property ID: TPlayerID read FID;
end;
type
TPlayerIDUtils = specialize DefaultUtils <TPlayerID>;
TPlayerIDHashTable = class (specialize THashTable <TPlayerID, TPlayer, TPlayerIDUtils>)
constructor Create(PredictedCount: THashTableSizeInt = 2);
end;
generic TPlayerHashTable <T> = class (specialize THashTable <TPlayer, T, TObjectUtils>) // TPlayer => T
constructor Create(PredictedCount: THashTableSizeInt = 1);
end;
function TPlayerHash32(const Key: TPlayer): DWord;
implementation
constructor TPlayer.Create(const Name: UTF8String; const ID: TPlayerID);
begin
FName := Name;
FID := ID;
end;
function TPlayerIDHash32(const Key: TPlayerID): DWord;
var
Index: Cardinal;
begin
{$PUSH}
{$RANGECHECKS OFF}
{$OVERFLOWCHECKS OFF}
{$HINTS OFF}
// djb2 from http://www.cse.yorku.ca/~oz/hash.html:
Result := 5381;
if (Length(Key) > 0) then
for Index := 1 to Length(Key) do
Result := Result shl 5 + Result + Ord(Key[Index]);
{$POP}
end;
constructor TPlayerIDHashTable.Create(PredictedCount: THashTableSizeInt = 2);
begin
inherited Create(@TPlayerIDHash32, PredictedCount);
end;
function TPlayerHash32(const Key: TPlayer): DWord;
begin
Result := ObjectHash32(Key);
end;
constructor TPlayerHashTable.Create(PredictedCount: THashTableSizeInt = 1);
begin
inherited Create(@TPlayerHash32, PredictedCount);
end;
end. |
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//
//主要功能:
// 流解压缩、文件夹解压缩
//------------------------------------------------------------------------------}
unit untEasyUtilCompression;
interface
uses
Windows, Messages, SysUtils, Classes, ShellAPI, ZLib;
const
cBufferSize = $1000;
cIdent = 'eas';
cVersion = $02;
type
TDirectoryDecompressionProgress = function( // 解压进度
mFileCount: Integer; // 文件总个数
mFileIndex: Integer; // 当前解压文件序号
mPackSize: Integer; // 文件压缩大小
mFileName: string; // 当前解压文件名
mFileSize: Integer; // 当前解压文件大小
mParam: Integer // 附加参数
): Boolean; // 返回是否继续解压
TFileHead = packed record
rIdent: array[0..2] of Char; //标识
rVersion: Byte; //版本
end;
//解压缩流
procedure UnCompressionStream(var ASrcStream:TMemoryStream);
//压缩流
procedure CompressionStream(var ASrcStream:TMemoryStream;ACompressionLevel:Integer = 2);
// 获得目录的大小、文件个数、目录个数
//mDirectory 目录名
//nFileSize 总大小
//nFileCount 文件个数
//nDirectoryCount 目录个数
function DirectoryInfo(mDirectory: string; var nFileSize: Integer;
var nFileCount: Integer; var nDirectoryCount: Integer): Boolean;
// 将文件压缩到流中
//mFileName 文件名
// mStream 目标
//返回解压后的大小
function FileCompression(mFileName: string; mStream: TStream): Integer;
// 从流中解压文件
// mFileName 目标文件名
// mStream 来源
// 返回解压后的大小
function FileDecompression(mFileName: string; mStream: TStream): Integer;
// 将目录压缩成文件
// mDirectory 目录名
// mFileName 压缩后的文件名
// 返回压缩后的大小 //如果为负数则标识错误
function DirectoryCompression(mDirectory: string; mFileName: string): Integer; overload;
// 将目录压缩成流
//mDirectory 目录名
//mStream 压缩后的流
//返回压缩后的大小 //如果为负数则标识错误
function DirectoryCompression(mDirectory: string; mStream: TStream): Integer; overload;
// 从文件中解压目录
//mDirectory 目录名
//mFileName 压缩文件名
//mProgress 进度处理
//mParam 附加参数
//返回解压后的个数
function DirectoryDecompression(mDirectory: string; mFileName: string;
mProgress: TDirectoryDecompressionProgress = nil; mParam: Integer = 0): Integer; overload;
// 从流中解压目录
//mDirectory 指定目录名
//mStream 压缩流
//mProgress 进度处理
//mParam 附加参数
//返回解压的文件个数
function DirectoryDecompression(mDirectory: string; mStream: TStream;
mProgress: TDirectoryDecompressionProgress = nil; mParam: Integer = 0): Integer; overload;
implementation
//取左边的字符串
//mStr 原字符串
//mDelimiter 分隔符
//mIgnoreCase 是否忽略大小写
//返回第一个分隔符左边的字符串
function StrLeft(mStr: string; mDelimiter: string; mIgnoreCase: Boolean = False): string;
begin
if mIgnoreCase then
Result := Copy(mStr, 1, Pos(UpperCase(mDelimiter), UpperCase(mStr)) - 1)
else Result := Copy(mStr, 1, Pos(mDelimiter, mStr) - 1);
end; { StrLeft }
//取右边的字符串
//mStr 原字符串
//mDelimiter 分隔符
//mIgnoreCase 是否忽略大小写
//返回第一个分隔符右边的字符串
function StrRight(mStr: string; mDelimiter: string; mIgnoreCase: Boolean = False): string;
begin
if mIgnoreCase then
begin
if Pos(UpperCase(mDelimiter), UpperCase(mStr)) > 0 then
Result := Copy(mStr, Pos(UpperCase(mDelimiter), UpperCase(mStr)) +
Length(mDelimiter), MaxInt)
else Result := '';
end else
begin
if Pos(mDelimiter, mStr) > 0 then
Result := Copy(mStr, Pos(mDelimiter, mStr) + Length(mDelimiter), MaxInt)
else Result := '';
end;
end; { StrRight }
function DirectoryInfo(mDirectory: string; var nFileSize: Integer;
var nFileCount: Integer; var nDirectoryCount: Integer): Boolean;
var
vSearchRec: TSearchRec;
vFileSize: Integer; // 总大小
vFileCount: Integer; // 文件个数
vDirectoryCount: Integer; // 目录个数
begin
Result := False;
if not DirectoryExists(mDirectory) then Exit; // 目录不存在
nFileSize := 0;
nFileCount := 0;
nDirectoryCount := 0;
mDirectory := IncludeTrailingPathDelimiter(mDirectory);
if FindFirst(mDirectory + '*.*',
faAnyFile and not faHidden, vSearchRec) = NO_ERROR then
begin
repeat
if vSearchRec.Attr and faDirectory = faDirectory then
begin
if Pos('.', vSearchRec.Name) <> 1 then
begin
Inc(nDirectoryCount);
DirectoryInfo(mDirectory + vSearchRec.Name,
vFileSize, vFileCount, vDirectoryCount);
Inc(nFileSize, vFileSize);
Inc(nFileCount, vFileCount);
Inc(nDirectoryCount, vDirectoryCount);
end;
end else
begin
Inc(nFileCount);
Inc(nFileSize, vSearchRec.Size);
end;
until FindNext(vSearchRec) <> NO_ERROR;
FindClose(vSearchRec);
end;
Result := True;
end;
function FileCompression(mFileName: string; mStream: TStream): Integer;
var
vFileStream: TFileStream;
vBuffer: array[0..cBufferSize]of Char;
vPosition: Integer;
I: Integer;
begin
Result := -1;
if not FileExists(mFileName) then Exit;
if not Assigned(mStream) then Exit;
vPosition := mStream.Position;
vFileStream := TFileStream.Create(mFileName, fmOpenRead or fmShareDenyNone);
with TCompressionStream.Create(clMax, mStream) do
try
for I := 1 to vFileStream.Size div cBufferSize do
begin
vFileStream.Read(vBuffer, cBufferSize);
Write(vBuffer, cBufferSize);
end;
I := vFileStream.Size mod cBufferSize;
if I > 0 then
begin
vFileStream.Read(vBuffer, I);
Write(vBuffer, I);
end;
finally
Free;
vFileStream.Free;
end;
Result := mStream.Size - vPosition; //增量
end;
function FileDecompression(mFileName: string; mStream: TStream): Integer;
var
vFileStream: TFileStream;
vFileHandle: THandle;
vBuffer: array[0..cBufferSize]of Char;
I: Integer;
begin
Result := -1;
if not Assigned(mStream) then Exit;
ForceDirectories(ExtractFilePath(mFileName)); //创建目录
{ TODO : 判断文件是否可以创建 }
vFileHandle := FileCreate(mFileName); //2006-09-25 ZswangY37 No.1
if Integer(vFileHandle) <= 0 then Exit;
vFileStream := TFileStream.Create(vFileHandle);
with TDecompressionStream.Create(mStream) do
try
repeat
I := Read(vBuffer, cBufferSize);
vFileStream.Write(vBuffer, I);
until I = 0;
Result := vFileStream.Size;
finally
Free;
vFileStream.Free;
end;
end;
function DirectoryCompression(mDirectory: string; mFileName: string): Integer; overload;
var
vFileStream: TFileStream;
begin
vFileStream := TFileStream.Create(mFileName, fmCreate or fmShareDenyWrite);
try
Result := DirectoryCompression(mDirectory, vFileStream);
finally
vFileStream.Free;
end;
end; { DirectoryCompression }
function DirectoryCompression(mDirectory: string; mStream: TStream): Integer; overload;
var
vFileInfo: TStrings;
vFileInfoSize: Integer;
vFileInfoBuffer: PChar;
vFileHead: TFileHead;
vMemoryStream: TMemoryStream;
procedure pAppendFile(mSubFile: string);
begin
vFileInfo.Append(Format('%s|%d',
[StringReplace(mSubFile, mDirectory + '\', '', [rfReplaceAll, rfIgnoreCase]),
FileCompression(mSubFile, vMemoryStream)]));
Inc(Result);
end; { pAppendFile }
procedure pSearchFile(mPath: string);
var
vSearchRec: TSearchRec;
K: Integer;
begin
K := FindFirst(mPath + '\*.*', faAnyFile and not faHidden, vSearchRec);
while K = 0 do
begin
if (vSearchRec.Attr and faDirectory > 0) and
(Pos(vSearchRec.Name, '..') = 0) then
pSearchFile(mPath + '\' + vSearchRec.Name)
else if Pos(vSearchRec.Name, '..') = 0 then
pAppendFile(mPath + '\' + vSearchRec.Name);
K := FindNext(vSearchRec);
end;
FindClose(vSearchRec);
end; { pSearchFile }
begin
Result := 0;
if not Assigned(mStream) then Exit;
if not DirectoryExists(mDirectory) then Exit;
vFileInfo := TStringList.Create;
vMemoryStream := TMemoryStream.Create;
mDirectory := ExcludeTrailingPathDelimiter(mDirectory);
try
pSearchFile(mDirectory);
vFileInfoBuffer := vFileInfo.GetText;
vFileInfoSize := StrLen(vFileInfoBuffer);
{ DONE -oZswang -c添加 : 写入头文件信息 }
vFileHead.rIdent := cIdent;
vFileHead.rVersion := cVersion;
mStream.Write(vFileHead, SizeOf(vFileHead));
mStream.Write(vFileInfoSize, SizeOf(vFileInfoSize));
mStream.Write(vFileInfoBuffer^, vFileInfoSize);
vMemoryStream.Position := 0;
mStream.CopyFrom(vMemoryStream, vMemoryStream.Size);
finally
vFileInfo.Free;
vMemoryStream.Free;
end;
end;
function DirectoryDecompression(mDirectory: string; mFileName: string;
mProgress: TDirectoryDecompressionProgress = nil; mParam: Integer = 0): Integer; overload;
var
vFileStream: TFileStream;
begin
vFileStream := TFileStream.Create(mFileName, fmOpenRead or fmShareDenyNone);
try
Result := DirectoryDecompression(
mDirectory, vFileStream, mProgress, mParam);
finally
vFileStream.Free;
end;
end; { DirectoryDeompression }
function DirectoryDecompression(mDirectory: string; mStream: TStream;
mProgress: TDirectoryDecompressionProgress = nil; mParam: Integer = 0): Integer; overload;
var
vFileInfo: TStrings;
vFileInfoSize: Integer;
vFileHead: TFileHead;
vFileCount: Integer;
vFileName: string;
vFileSize: Integer;
vPackSize: Integer;
vMemoryStream: TMemoryStream;
I: Integer;
begin
Result := 0;
if not Assigned(mStream) then Exit;
vFileInfo := TStringList.Create;
vMemoryStream := TMemoryStream.Create;
mDirectory := ExcludeTrailingPathDelimiter(mDirectory);
try
mStream.Position := 0;
if mStream.Size < SizeOf(vFileHead) then Exit;
{ DONE -oZswang -c添加 : 读取头文件信息 }
mStream.Read(vFileHead, SizeOf(vFileHead));
if vFileHead.rIdent <> cIdent then Result := -1;
if vFileHead.rVersion <> cVersion then Result := -2;
if Result <> 0 then Exit;
mStream.Read(vFileInfoSize, SizeOf(vFileInfoSize));
vMemoryStream.CopyFrom(mStream, vFileInfoSize);
vMemoryStream.Position := 0;
vFileInfo.LoadFromStream(vMemoryStream);
vFileCount := vFileInfo.Count;
for I := 0 to vFileCount - 1 do
begin
vFileName := mDirectory + '\' + StrLeft(vFileInfo[I], '|');
vPackSize := StrToIntDef(StrRight(vFileInfo[I], '|'), 0);
vMemoryStream.Clear;
vMemoryStream.CopyFrom(mStream, vPackSize);
vMemoryStream.Position := 0;
vFileSize := FileDecompression(vFileName, vMemoryStream);
if Assigned(mProgress) then
if not mProgress(vFileCount, I,
vPackSize, vFileName, vFileSize, mParam) then Break;
end;
Result := vFileInfo.Count;
finally
vFileInfo.Free;
vMemoryStream.Free;
end;
end;
//解压缩
procedure UnCompressionStream(var ASrcStream:TMemoryStream);
var
nTmpStream:TDecompressionStream;
nDestStream:TMemoryStream;
nBuf: array[1..512] of Byte;
nSrcCount: integer;
begin
ASrcStream.Position := 0;
nDestStream := TMemoryStream.Create;
nTmpStream := TDecompressionStream.Create(ASrcStream);
try
repeat
//读入实际大小
nSrcCount := nTmpStream.Read(nBuf, SizeOf(nBuf));
if nSrcCount > 0 then
nDestStream.Write(nBuf, nSrcCount);
until (nSrcCount = 0);
ASrcStream.Clear;
ASrcStream.LoadFromStream(nDestStream);
ASrcStream.Position := 0;
finally
nDestStream.Clear;
nDestStream.Free;
nTmpStream.Free;
end;
end;
//压缩流
procedure CompressionStream(var ASrcStream:TMemoryStream;ACompressionLevel:Integer = 2);
var
nDestStream:TMemoryStream;
nTmpStream:TCompressionStream;
nCompressionLevel:TCompressionLevel;
begin
ASrcStream.Position := 0;
nDestStream := TMemoryStream.Create;
try
//级别
case ACompressionLevel of
0:nCompressionLevel := clNone;
1:nCompressionLevel := clFastest;
2:nCompressionLevel := clDefault;
3:nCompressionLevel := clMax;
else
nCompressionLevel := clMax;
end;
//开始压缩
nTmpStream := TCompressionStream.Create(nCompressionLevel,nDestStream);
try
ASrcStream.SaveToStream(nTmpStream);
finally
nTmpStream.Free;//释放后nDestStream才会有数据
end;
ASrcStream.Clear;
ASrcStream.LoadFromStream(nDestStream);
ASrcStream.Position := 0;
finally
nDestStream.Clear;
nDestStream.Free;
end;
end;
end.
|
unit MainView;
interface
uses
System.Classes,
System.Actions,
FMX.Graphics,
FMX.ActnList,
FMX.Forms,
FMX.Edit,
FMX.EditBox,
FMX.NumberBox,
FMX.StdCtrls,
FMX.Controls,
FMX.ListBox,
FMX.Layouts,
FMX.Controls.Presentation,
FMX.MultiView,
FMX.Types,
FMX.StdActns,
FMX.MediaLibrary.Actions,
FMX.ImageLayout;
type
TForm1 = class(TForm)
MultiView1: TMultiView;
btnDrawerView: TButton;
ToolBar1: TToolBar;
ListBox1: TListBox;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
ListBoxItem3: TListBoxItem;
swBounceAnimation: TSwitch;
swAutoHideScrollbars: TSwitch;
swAnimateDecelerationRate: TSwitch;
ListBoxItem4: TListBoxItem;
swMouseWheelZoom: TSwitch;
ListBoxItem5: TListBoxItem;
edBounceElasticity: TNumberBox;
ListBoxItem6: TListBoxItem;
edImageScale: TNumberBox;
ImageLayout1: TImageLayout;
ActionList1: TActionList;
OpenImageAction: TAction;
btnClearImage: TSpeedButton;
ClearImageAction: TAction;
TakePhotoFromLibraryAction: TTakePhotoFromLibraryAction;
TakePhotoFromCameraAction: TTakePhotoFromCameraAction;
btnPictureFromMediaCamera: TButton;
btnPictureFromMediaLibrary: TButton;
WhenImageChanged: TListBoxItem;
cbImageChangeAction: TComboBox;
procedure FormCreate(Sender: TObject);
procedure edBounceElasticityChange(Sender: TObject);
procedure swBounceAnimationSwitch(Sender: TObject);
procedure swAutoHideScrollbarsSwitch(Sender: TObject);
procedure swAnimateDecelerationRateSwitch(Sender: TObject);
procedure swMouseWheelZoomSwitch(Sender: TObject);
procedure edImageScaleChange(Sender: TObject);
procedure OpenImageActionExecute(Sender: TObject);
procedure ClearImageActionExecute(Sender: TObject);
procedure TakePhotoFromLibraryActionDidFinishTaking(Image: TBitmap);
procedure TakePhotoFromCameraActionDidFinishTaking(Image: TBitmap);
procedure ImageLayout1ImageChanged(Sender: TObject; const Reason: TImageChangeReason; var Action: TImageChangeAction);
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses
{$IFNDEF NEXTGEN}
System.UITypes,
FMX.Dialogs,
{$ENDIF}
System.SysUtils;
procedure TForm1.FormCreate(Sender: TObject);
begin
{$IFDEF MSWINDOWS}
ReportMemoryLeaksOnShutdown := True;
{$ENDIF}
{$IFNDEF NEXTGEN}
btnPictureFromMediaLibrary.Action := OpenImageAction;
{$ENDIF NEXTGEN}
MultiView1.Mode := TMultiViewMode.Drawer;
end;
procedure TForm1.ImageLayout1ImageChanged(Sender: TObject; const Reason: TImageChangeReason; var Action: TImageChangeAction);
begin
edImageScale.OnChange := nil;
try
edImageScale.Value := ImageLayout1.ImageScale;
if Reason = TImageChangeReason.LayoutResized then
Action := TImageChangeAction.RecalcBestFit
else
Action := TImageChangeAction(cbImageChangeAction.ItemIndex);
finally
edImageScale.OnChange := edImageScaleChange;
end;
end;
procedure TForm1.edImageScaleChange(Sender: TObject);
begin
ImageLayout1.ImageScale := edImageScale.Value;
end;
procedure TForm1.OpenImageActionExecute(Sender: TObject);
{$IFNDEF NEXTGEN}
var
OpenDialog: TOpenDialog;
{$ENDIF NEXTGEN}
begin
{$IFNDEF NEXTGEN}
OpenDialog := TOpenDialog.Create(nil);
try
OpenDialog.Filter := TBitmapCodecManager.GetFilterString;
OpenDialog.Options := [TOpenOption.ofPathMustExist, TOpenOption.ofFileMustExist, TOpenOption.ofReadOnly];
if OpenDialog.Execute then
ImageLayout1.Image.LoadFromFile(OpenDialog.FileName);
finally
OpenDialog.Free;
end;
{$ENDIF NEXTGEN}
end;
procedure TForm1.ClearImageActionExecute(Sender: TObject);
begin
ImageLayout1.ClearImage;
end;
procedure TForm1.edBounceElasticityChange(Sender: TObject);
begin
ImageLayout1.BounceElasticity := edBounceElasticity.Value;
end;
procedure TForm1.swBounceAnimationSwitch(Sender: TObject);
begin
ImageLayout1.BounceAnimation := swBounceAnimation.IsChecked;
end;
procedure TForm1.swAutoHideScrollbarsSwitch(Sender: TObject);
begin
ImageLayout1.AutoHideScrollbars := swAutoHideScrollbars.IsChecked;
end;
procedure TForm1.swAnimateDecelerationRateSwitch(Sender: TObject);
begin
ImageLayout1.AnimateDecelerationRate := swAnimateDecelerationRate.IsChecked;
end;
procedure TForm1.swMouseWheelZoomSwitch(Sender: TObject);
begin
ImageLayout1.MouseWheelZoom := swMouseWheelZoom.IsChecked;
end;
procedure TForm1.TakePhotoFromCameraActionDidFinishTaking(Image: TBitmap);
begin
ImageLayout1.Image := Image;
end;
procedure TForm1.TakePhotoFromLibraryActionDidFinishTaking(Image: TBitmap);
begin
ImageLayout1.Image := Image;
end;
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------
//单元说明:
// EasyPlate程序的服务端单元
//主要实现:
//-----------------------------------------------------------------------------}
unit untEasyPlateServerMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, untEasyToolBar, untEasyToolBarStylers, untEasyNavBar,
ExtCtrls, Grids, untEasyBaseGrid, untEasyGrid, untEasyStatusBar, Registry,
untEasyStatusBarStylers, untEasyGroupBox, Menus, untEasyMenus, IniFiles,
untEasyMenuStylers, untEasyTrayIcon, SvcMgr, ScktComp, ScktCnst, ActnList,
untEasyEdit, ComCtrls, ImgList, untEasyPageControl, DB, DBClient,
untEasyMemo, untEasyNavBarExt;
const
EApplicationName = 'EasyPlate服务程序';
EAlreadyRunning = '系统中已存在运行的服务程序实例,请不要重复运行!';
ESQueryDisconnect = '断开客户端连接,将导致客户端异常退出,是否现在断开?';
ESErrClose = '有客户端正在连接, 是否继续退出服务?';
type
TfrmEasyPlateServerMain = class(TForm)
dkpMain: TEasyDockPanel;
tlbMain: TEasyToolBar;
EasyToolBarOfficeStyler1: TEasyToolBarOfficeStyler;
stbMain: TEasyStatusBar;
EasyStatusBarOfficeStyler1: TEasyStatusBarOfficeStyler;
EasyPanel1: TEasyPanel;
Splitter1: TSplitter;
mmMain: TEasyMainMenu;
EasyMenuOfficeStyler1: TEasyMenuOfficeStyler;
N1: TMenuItem;
pmMain: TEasyPopupMenu;
N2: TMenuItem;
N3: TMenuItem;
N4: TMenuItem;
ServerTrayIcon: TEasyTrayIcon;
N5: TMenuItem;
SN1: TMenuItem;
N7: TMenuItem;
XML1: TMenuItem;
N8: TMenuItem;
N9: TMenuItem;
ActionList1: TActionList;
ApplyAction: TAction;
DisconnectAction: TAction;
ShowHostAction: TAction;
RemovePortAction: TAction;
RegisteredAction: TAction;
AllowXML: TAction;
EasyNavBarExt1: TEasyNavBarExt;
nbpPort: TEasyNavBarExtPanel;
PortList: TListBox;
nbpSocketSet: TEasyNavBarExtPanel;
PortNo: TEasyLabelEdit;
ThreadSize: TEasyLabelEdit;
Timeout: TEasyLabelEdit;
InterceptGUID: TEasyLabelEdit;
PortUpDown: TUpDown;
ThreadUpDown: TUpDown;
TimeoutUpDown: TUpDown;
imgServer: TImageList;
EasyToolBarButton1: TEasyToolBarButton;
EasyToolBarButton2: TEasyToolBarButton;
pgcServerMain: TEasyPageControl;
tbsConnHost: TEasyTabSheet;
tbsExecLog: TEasyTabSheet;
ConnectionList: TListView;
tbsErrorLog: TEasyTabSheet;
mmExecLog: TEasyMemo;
mmErrorLog: TEasyMemo;
EasyToolBarButton3: TEasyToolBarButton;
EasyToolBarSeparator1: TEasyToolBarSeparator;
EasyToolBarSeparator2: TEasyToolBarSeparator;
btnExit: TEasyToolBarButton;
N6: TMenuItem;
H1: TMenuItem;
R1: TMenuItem;
N10: TMenuItem;
mmAutoRun: TMenuItem;
N12: TMenuItem;
N13: TMenuItem;
mmDetailLog: TMenuItem;
N14: TMenuItem;
N15: TMenuItem;
N16: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure N5Click(Sender: TObject);
procedure ApplyActionExecute(Sender: TObject);
procedure DisconnectActionExecute(Sender: TObject);
procedure RemovePortActionExecute(Sender: TObject);
procedure RegisteredActionExecute(Sender: TObject);
procedure AllowXMLExecute(Sender: TObject);
procedure ShowHostActionExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure PortListClick(Sender: TObject);
procedure ApplyActionUpdate(Sender: TObject);
procedure DisconnectActionUpdate(Sender: TObject);
procedure RemovePortActionUpdate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure mmErrorLogChange(Sender: TObject);
procedure mmExecLogChange(Sender: TObject);
procedure EasyToolBarButton3Click(Sender: TObject);
procedure btnExitClick(Sender: TObject);
procedure N12Click(Sender: TObject);
procedure N13Click(Sender: TObject);
procedure mmDetailLogClick(Sender: TObject);
procedure N14Click(Sender: TObject);
procedure N16Click(Sender: TObject);
procedure mmAutoRunClick(Sender: TObject);
private
{ Private declarations }
FMaxClientCount: Integer;
FFromService: Boolean;
NT351: Boolean;
FClosing: Boolean;
FCurItem: Integer;
FSortCol: Integer;
function GetItemIndex: Integer;
procedure SetItemIndex(Value: Integer);
function GetSelectedSocket: TServerSocket; //保存端口列表
procedure CheckValues;
procedure UpdateStatus;
//输出日志
//App\log 运行日志App\log\ExecLog 错误日志 App\log\ErrorLog
// procedure SaveLogMemo(ALogFile: string);
procedure RefreshTableCache;
//开机自动启动 注册与反注册
procedure RegAutoRun(Key, AppPath: string);
procedure UnRegAutoRun(Key: string);
function FindRegAutoRun(Key: string): Boolean;
public
{ Public declarations }
procedure Initialize(FromService: Boolean);
property ItemIndex: Integer read GetItemIndex write SetItemIndex;
property SelectedSocket: TServerSocket read GetSelectedSocket;
function GetLocalTime: string;
function GetLocalDate: string;
protected
procedure ReadSettings;
procedure WriteSettings;
procedure AddClient(Thread: TServerClientThread);
procedure RemoveClient(Thread: TServerClientThread);
procedure ClearModifications;
//创建数据模块
procedure RDMServerCreated(var msg: TMessage); message WM_USER + 99;
//释放数据模块
procedure RDMServerDestroy(var msg: TMessage); message WM_USER + 100;
procedure RDMServerPoolerCreate(var msg: TMessage); message WM_USER + 101;
end;
TSocketService = class(TService)
protected
procedure Start(Sender: TService; var Started: Boolean);
procedure Stop(Sender: TService; var Stopped: Boolean);
public
function GetServiceController: TServiceController; override;
constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
end;
var
frmEasyPlateServerMain: TfrmEasyPlateServerMain;
SocketService: TSocketService;
implementation
uses
untRDMEasyPlateServer, SConnect, ActiveX, MidConst, untEasyLocalDM,
untEasyUtilMethod, EasyPlateServer_TLB;
{$R *.dfm}
var
AppServerPath, ExecLogPath, ErrorLogPath: string;
const
mmLogLineCount = 20000;
{ TSocketDispatcherThread }
type
TSocketDispatcherThread = class(TServerClientThread, ISendDataBlock)
private
FRefCount: Integer;
FInterpreter: TDataBlockInterpreter;
FTransport: ITransport;
FInterceptGUID: string;
FLastActivity: TDateTime;
FTimeout: TDateTime;
FRegisteredOnly: Boolean;
FAllowXML: Boolean;
protected
function CreateServerTransport: ITransport; virtual;
procedure AddClient;
procedure RemoveClient;
{ IUnknown }
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
{ ISendDataBlock }
function Send(const Data: IDataBlock; WaitForResult: Boolean): IDataBlock; stdcall;
public
constructor Create(CreateSuspended: Boolean; ASocket: TServerClientWinSocket;
const InterceptGUID: string; Timeout: Integer; RegisteredOnly, AllowXML: Boolean);
procedure ClientExecute; override;
property LastActivity: TDateTime read FLastActivity;
end;
{ TSocketDispatcher }
type
//套接字分配器
TSocketDispatcher = class(TServerSocket)
private
FScktIniFile: TIniFile;
FInterceptGUID: string;
FTimeout: Integer;
//获取套接字线程
procedure GetThread(Sender: TObject; ClientSocket: TServerClientWinSocket;
var SocketThread: TServerClientThread);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ReadSettings(PortNo: Integer{; Reg: TRegINIFile});
procedure WriteSettings({Reg: TRegINIFile});
property InterceptGUID: string read FInterceptGUID write FInterceptGUID;
property Timeout: Integer read FTimeout write FTimeout;
end;
procedure TfrmEasyPlateServerMain.AddClient(Thread: TServerClientThread);
var
Item: TListItem;
begin
Item := ConnectionList.Items.Add;
Item.Caption := IntToStr(Thread.ClientSocket.LocalPort);
Item.SubItems.Add(Thread.ClientSocket.RemoteAddress);
if ShowHostAction.Checked then
begin
Item.SubItems.Add(Thread.ClientSocket.RemoteHost);
if Item.SubItems[1] = '' then Item.SubItems[1] := SHostUnknown;
end
else
Item.SubItems.Add(SNotShown);
if Thread is TSocketDispatcherThread then
Item.SubItems.Add(DateTimeToStr(TSocketDispatcherThread(Thread).LastActivity));
Item.Data := Pointer(Thread);
//增加客户端时输出日志信息
frmEasyPlateServerMain.mmExecLog.Lines.Add(Format('%s 客户端 %s IP:%s:%s 连接成功!', [
DateTimeToStr(TSocketDispatcherThread(Thread).LastActivity),
Thread.ClientSocket.RemoteHost,
Thread.ClientSocket.RemoteAddress, IntToStr(Thread.ClientSocket.LocalPort)]));
UpdateStatus;
end;
procedure TfrmEasyPlateServerMain.FormCreate(Sender: TObject);
begin
//判断是否安装WinSock2
if not LoadWinSock2 then
raise Exception.CreateRes(@SNoWinSock2);
FClosing := False;
FCurItem := -1;
FSortCol := -1;
end;
{ TSocketService }
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
SocketService.Controller(CtrlCode);
end;
constructor TSocketService.CreateNew(AOwner: TComponent; Dummy: Integer);
begin
inherited CreateNew(AOwner, Dummy);
AllowPause := False;
Interactive := True;
DisplayName := EApplicationName;
Name := SServiceName;
OnStart := Start;
OnStop := Stop;
end;
function TSocketService.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
procedure TSocketService.Start(Sender: TService; var Started: Boolean);
begin
Started := True;
end;
procedure TSocketService.Stop(Sender: TService; var Stopped: Boolean);
begin
Stopped := True;
end;
procedure TfrmEasyPlateServerMain.ReadSettings;
var
// Reg: TRegINIFile;
Reg: TIniFile;
procedure CreateItem(ID: Integer);
var
SH: TSocketDispatcher;
begin
SH := TSocketDispatcher.Create(nil);
SH.ReadSettings(ID{, Reg});
PortList.Items.AddObject(IntToStr(SH.Port), SH);
try
SH.Open;
except
on E: Exception do
raise Exception.CreateResFmt(@SOpenError, [SH.Port, E.Message]);
end;
end;
var
Sections: TStringList;
pCount, //已创建端口计数,只允许创建一个
i: Integer;
begin
// Reg := TRegINIFile.Create('');
pCount := 0;
Reg := TIniFile.Create(ExtractFilePath(Forms.Application.ExeName) + '\ScktIni.ini');
try
// Reg.RootKey := HKEY_LOCAL_MACHINE;
// Reg.OpenKey(KEY_SOCKETSERVER, True);
Sections := TStringList.Create;
try
Reg.ReadSections(Sections);
if Sections.Count > 1 then
begin
for i := 0 to Sections.Count - 1 do
begin
//只有配置文件的第一个端口节设置有效
if (CompareText(Sections[i], csSettings) <> 0) and (pCount = 0) then
begin
CreateItem(StrToInt(Sections[i]));
pCount := 1;
end;
end;
end
else
CreateItem(-1);
ItemIndex := 0;
ShowHostAction.Checked := Reg.ReadBool(csSettings, ckShowHost, False);
RegisteredAction.Checked := Reg.ReadBool(csSettings, ckRegistered, True);
finally
Sections.Free;
end;
finally
Reg.Free;
end;
end;
procedure TfrmEasyPlateServerMain.RemoveClient(
Thread: TServerClientThread);
var
Item: TListItem;
begin
Item := ConnectionList.FindData(0, Thread, True, False);
if Assigned(Item) then
begin
//增加客户端时输出日志信息
frmEasyPlateServerMain.mmExecLog.Lines.Add(Format('%s 客户端 %s IP:%s:%s 断开连接!', [
DateTimeToStr(Now()), Item.SubItems[1],
Item.SubItems[0], Item.Caption]));
Item.Free;
end;
UpdateStatus;
end;
procedure TfrmEasyPlateServerMain.WriteSettings;
var
// Reg: TRegINIFile;
Reg: TIniFile;
Sections: TStringList;
i: Integer;
begin
// Reg := TRegINIFile.Create('');
Reg := TIniFile.Create(ExtractFilePath(Forms.Application.ExeName) + '\ScktIni.ini');
try
// Reg.RootKey := HKEY_LOCAL_MACHINE;
// Reg.OpenKey(KEY_SOCKETSERVER, True);
Sections := TStringList.Create;
try
Reg.ReadSections(Sections);
// for i := 0 to Sections.Count - 1 do
// TRegistry(Reg).DeleteKey(Sections[i]);
finally
Sections.Free;
end;
for i := 0 to PortList.Items.Count - 1 do
TSocketDispatcher(PortList.Items.Objects[i]).WriteSettings({Reg});
Reg.WriteBool(csSettings, ckShowHost, ShowHostAction.Checked);
Reg.WriteBool(csSettings, ckRegistered, RegisteredAction.Checked);
finally
Reg.Free;
end;
end;
{ TSocketDispatcher }
constructor TSocketDispatcher.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//
FScktIniFile := TIniFile.Create(ExtractFilePath(Forms.Application.ExeName) + '\ScktIni.ini');
//阻塞模式线程开启
ServerType := stThreadBlocking;
//获取线程事件绑定
OnGetThread := GetThread;
frmEasyPlateServerMain.mmExecLog.Lines.Add('SocketDispatcher创建完成!');
end;
destructor TSocketDispatcher.Destroy;
begin
FScktIniFile.Free;
inherited Destroy;
end;
procedure TSocketDispatcher.GetThread(Sender: TObject;
ClientSocket: TServerClientWinSocket;
var SocketThread: TServerClientThread);
begin
SocketThread := TSocketDispatcherThread.Create(False, ClientSocket,
InterceptGUID, Timeout, frmEasyPlateServerMain.RegisteredAction.Checked,
frmEasyPlateServerMain.AllowXML.Checked);
//输出获取套接字线程信息
//增加客户端时输出日志信息
frmEasyPlateServerMain.mmExecLog.Lines.Add(Format('%s 客户端 %s IP:%s:%s 获取Socket Thread, ThreadID:%d!', [
DateTimeToStr(TSocketDispatcherThread(SocketThread).LastActivity),
SocketThread.ClientSocket.RemoteHost,
SocketThread.ClientSocket.RemoteAddress, IntToStr(SocketThread.ClientSocket.LocalPort),
SocketThread.ThreadID]));
end;
procedure TSocketDispatcher.ReadSettings(PortNo: Integer{;
Reg: TRegINIFile});
var
Section: string;
begin
if PortNo = -1 then
begin
Section := csSettings;
//2011-01-05将默认端口调成9090
// Port := Reg.ReadInteger(Section, ckPort, 9090);
end
else
begin
Section := IntToStr(PortNo);
// Port := PortNo;
end;
Port := FScktIniFile.ReadInteger(Section, ckPort, 9090);
ThreadCacheSize := FScktIniFile.ReadInteger(Section, ckThreadCacheSize, 0);
FInterceptGUID := FScktIniFile.ReadString(Section, ckInterceptGUID, '');
FTimeout := FScktIniFile.ReadInteger(Section, ckTimeout, 0);
end;
procedure TSocketDispatcher.WriteSettings({Reg: TRegINIFile});
var
Section: string;
begin
Section := IntToStr(Port);
// Reg.WriteInteger(Section, ckPort, Port);
// Reg.WriteInteger(Section, ckThreadCacheSize, ThreadCacheSize);
// Reg.WriteString(Section, ckInterceptGUID, InterceptGUID);
// Reg.WriteInteger(Section, ckTimeout, Timeout);
FScktIniFile.WriteInteger(Section, ckPort, Port);
FScktIniFile.WriteInteger(Section, ckThreadCacheSize, ThreadCacheSize);
FScktIniFile.WriteString(Section, ckInterceptGUID, InterceptGUID);
FScktIniFile.WriteInteger(Section, ckTimeout, Timeout);
end;
{ TSocketDispatcherThread }
function TSocketDispatcherThread._AddRef: Integer;
begin
Inc(FRefCount);
Result := FRefCount;
end;
function TSocketDispatcherThread._Release: Integer;
begin
Dec(FRefCount);
Result := FRefCount;
end;
procedure TSocketDispatcherThread.AddClient;
begin
frmEasyPlateServerMain.AddClient(Self);
frmEasyPlateServerMain.FMaxClientCount := 5;
if frmEasyPlateServerMain.ConnectionList.Items.Count > frmEasyPlateServerMain.FMaxClientCount then
begin
frmEasyPlateServerMain.mmExecLog.Lines.Add('已超出最大有效客户端连接数!');
//要存在开打的端口
with TServerSocket(frmEasyPlateServerMain.PortList.Items.Objects[0]).Socket do
begin
Lock;
try
with frmEasyPlateServerMain.ConnectionList.Items[frmEasyPlateServerMain.ConnectionList.Items.Count - 1] do
TServerClientThread(Data).ClientSocket.Close;
finally
Unlock;
end;
end;
frmEasyPlateServerMain.RemoveClient(Self);
end;
end;
procedure TSocketDispatcherThread.ClientExecute;
var
Data: IDataBlock;
msg: TMsg;
Obj: ISendDataBlock;
Event: THandle;
WaitTime: DWord;
begin
CoInitialize(nil);
try
Synchronize(AddClient);
FTransport := CreateServerTransport;
try
Event := FTransport.GetWaitEvent;
PeekMessage(msg, 0, WM_USER, WM_USER, PM_NOREMOVE);
GetInterface(ISendDataBlock, Obj);
if FRegisteredOnly then
FInterpreter := TDataBlockInterpreter.Create(Obj, SSockets)
else
FInterpreter := TDataBlockInterpreter.Create(Obj, '');
try
Obj := nil;
if FTimeout = 0 then
WaitTime := INFINITE
else
WaitTime := 60000;
while not Terminated and FTransport.Connected do
try
case MsgWaitForMultipleObjects(1, Event, False, WaitTime, QS_ALLEVENTS) of
WAIT_OBJECT_0:
begin
WSAResetEvent(Event);
Data := FTransport.Receive(False, 0);
if Assigned(Data) then
begin
FLastActivity := Now;
FInterpreter.InterpretData(Data);
Data := nil;
FLastActivity := Now;
end;
end;
WAIT_OBJECT_0 + 1:
while PeekMessage(msg, 0, 0, 0, PM_REMOVE) do
DispatchMessage(msg);
WAIT_TIMEOUT:
//过期自动退出
if (FTimeout > 0) and ((Now - FLastActivity) > FTimeout) then
FTransport.Connected := False;
end;
except
FTransport.Connected := False;
end;
finally
FInterpreter.Free;
FInterpreter := nil;
end;
finally
FTransport := nil;
end;
finally
CoUninitialize;
Synchronize(RemoveClient);
end;
end;
constructor TSocketDispatcherThread.Create(CreateSuspended: Boolean;
ASocket: TServerClientWinSocket; const InterceptGUID: string;
Timeout: Integer; RegisteredOnly, AllowXML: Boolean);
begin
FInterceptGUID := InterceptGUID;
FTimeout := EncodeTime(Timeout div 60, Timeout mod 60, 0, 0);
FLastActivity := Now;
FRegisteredOnly := RegisteredOnly;
FAllowXML := AllowXML;
inherited Create(CreateSuspended, ASocket);
end;
function TSocketDispatcherThread.CreateServerTransport: ITransport;
var
SocketTransport: TSocketTransport;
begin
SocketTransport := TSocketTransport.Create;
SocketTransport.Socket := ClientSocket;
SocketTransport.InterceptGUID := FInterceptGUID;
Result := SocketTransport as ITransport;
end;
function TSocketDispatcherThread.QueryInterface(const IID: TGUID;
out Obj): HResult;
begin
if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE;
end;
procedure TSocketDispatcherThread.RemoveClient;
begin
frmEasyPlateServerMain.RemoveClient(Self);
end;
function TSocketDispatcherThread.Send(const Data: IDataBlock;
WaitForResult: Boolean): IDataBlock;
begin
FTransport.Send(Data);
if WaitForResult then
begin
while True do
begin
Result := FTransport.Receive(True, 0);
if Result = nil then break;
if (Result.Signature and ResultSig) = ResultSig then
break
else
FInterpreter.InterpretData(Result);
end;
end;
end;
function TfrmEasyPlateServerMain.GetItemIndex: Integer;
begin
Result := FCurItem;
end;
procedure TfrmEasyPlateServerMain.SetItemIndex(Value: Integer);
var
Selected: Boolean;
begin
if (FCurItem <> Value) then
try
if ApplyAction.Enabled then
ApplyAction.Execute;
except
PortList.ItemIndex := FCurItem;
raise;
end
else
Exit;
if Value = -1 then
Value := 0;
PortList.ItemIndex := Value;
FCurItem := PortList.ItemIndex;
Selected := FCurItem <> -1;
if Selected then
with TSocketDispatcher(PortList.Items.Objects[FCurItem]) do
begin
PortUpDown.Position := Port;
ThreadUpDown.Position := ThreadCacheSize;
Self.InterceptGUID.Text := FInterceptGUID;
TimeoutUpDown.Position := Timeout;
ClearModifications;
end;
PortNo.Enabled := Selected;
ThreadSize.Enabled := Selected;
Timeout.Enabled := Selected;
InterceptGUID.Enabled := Selected;
end;
procedure TfrmEasyPlateServerMain.N5Click(Sender: TObject);
begin
ServerTrayIcon.ShowMainForm;
end;
procedure TfrmEasyPlateServerMain.Initialize(FromService: Boolean);
// function IE4Installed: Boolean;
// var
// RegKey: HKEY;
// begin
// Result := False;
// if RegOpenKey(HKEY_LOCAL_MACHINE, KEY_IE, RegKey) = ERROR_SUCCESS then
// try
// Result := RegQueryValueEx(RegKey, 'Version', nil, nil, nil, nil) = ERROR_SUCCESS;
// finally
// RegCloseKey(RegKey);
// end;
// end;
//
begin
FFromService := FromService;
NT351 := (Win32MajorVersion <= 3) and (Win32Platform = VER_PLATFORM_WIN32_NT);
if NT351 then
begin
if not FromService then
raise Exception.CreateRes(@SServiceOnly);
end;
ReadSettings;
// if FromService then
// begin
// miClose.Visible := False;
// N1.Visible := False;
// end;
// if IE4Installed then
// FTaskMessage := RegisterWindowMessage('TaskbarCreated')
// else
end;
procedure TfrmEasyPlateServerMain.ApplyActionExecute(Sender: TObject);
begin
with TSocketDispatcher(SelectedSocket) do
begin
if Socket.ActiveConnections > 0 then
if Forms.Application.MessageBox(PChar(SErrChangeSettings), PChar('提示'), MB_OKCANCEL +
MB_ICONQUESTION) = IDCANCEL then
// if MessageDlg(SErrChangeSettings, mtConfirmation, [mbYes, mbNo], 0) = idNo then
Exit;
Close;
Port := StrToInt(PortNo.Text);
PortList.Items[ItemIndex] := PortNo.Text;
ThreadCacheSize := StrToInt(ThreadSize.Text);
InterceptGUID := Self.InterceptGUID.Text;
Timeout := StrToInt(Self.Timeout.Text);
Open;
end;
ClearModifications;
end;
function TfrmEasyPlateServerMain.GetSelectedSocket: TServerSocket;
begin
Result := TServerSocket(PortList.Items.Objects[ItemIndex]);
end;
procedure TfrmEasyPlateServerMain.ClearModifications;
begin
PortNo.Modified := False;
ThreadSize.Modified := False;
Timeout.Modified := False;
InterceptGUID.Modified := False;
end;
procedure TfrmEasyPlateServerMain.DisconnectActionExecute(Sender: TObject);
var
i: Integer;
begin
if Forms.Application.MessageBox(PChar(ESQueryDisconnect), PChar('提示'), MB_OKCANCEL +
MB_ICONQUESTION) = IDCANCEL then
// if MessageDlg(ESQueryDisconnect, mtConfirmation, [mbYes, mbNo], 0) = mrNo then
Exit;
with SelectedSocket.Socket do
begin
Lock;
try
for i := 0 to ConnectionList.Items.Count - 1 do
with ConnectionList.Items[i] do
if Selected then
TServerClientThread(Data).ClientSocket.Close;
finally
Unlock;
end;
end;
end;
procedure TfrmEasyPlateServerMain.RemovePortActionExecute(Sender: TObject);
begin
CheckValues;
PortList.Items.Objects[ItemIndex].Free;
PortList.Items.Delete(ItemIndex);
FCurItem := -1;
ItemIndex := 0;
end;
procedure TfrmEasyPlateServerMain.CheckValues;
begin
StrToInt(PortNo.Text);
StrToInt(ThreadSize.Text);
StrToInt(Timeout.Text);
end;
procedure TfrmEasyPlateServerMain.RegisteredActionExecute(Sender: TObject);
begin
RegisteredAction.Checked := not RegisteredAction.Checked;
ShowMessage('重启服务程序更改生效!');
// ShowMessage(SNotUntilRestart);
end;
procedure TfrmEasyPlateServerMain.AllowXMLExecute(Sender: TObject);
begin
AllowXML.Checked := not AllowXML.Checked;
end;
procedure TfrmEasyPlateServerMain.ShowHostActionExecute(Sender: TObject);
var
i: Integer;
Item: TListItem;
begin
ShowHostAction.Checked := not ShowHostAction.Checked;
ConnectionList.Items.BeginUpdate;
try
for i := 0 to ConnectionList.Items.Count - 1 do
begin
Item := ConnectionList.Items[i];
if ShowHostAction.Checked then
begin
Item.SubItems[1] := TServerClientThread(Item.Data).ClientSocket.RemoteHost;
if Item.SubItems[1] = '' then Item.SubItems[1] := SHostUnknown;
end
else
Item.SubItems[1] := SNotShown;
end;
finally
ConnectionList.Items.EndUpdate;
end;
end;
procedure TfrmEasyPlateServerMain.UpdateStatus;
begin
stbMain.Panels[0].Text := Format('在线客户: %d ', [ConnectionList.Items.Count]);
end;
procedure TfrmEasyPlateServerMain.FormDestroy(Sender: TObject);
var
i: Integer;
begin
for i := 0 to PortList.Items.Count - 1 do
PortList.Items.Objects[i].Free;
if not DirectoryExists(ExecLogPath + GetLocalDate) then
try
CreateDir(ExecLogPath + GetLocalDate);
except on e:Exception do
ShowMessage(e.Message);
end;
while not FileExists(ExecLogPath + GetLocalDate + '\' + GetLocalTime + '.log') do
mmExecLog.Lines.SaveToFile(ExecLogPath + GetLocalDate + '\' + GetLocalTime + '.log');
if not DirectoryExists(ErrorLogPath + GetLocalDate) then
try
CreateDir(ErrorLogPath + GetLocalDate);
except on e:Exception do
ShowMessage(e.Message);
end;
while not FileExists(ErrorLogPath + GetLocalDate + '\' + GetLocalTime + '.log') do
mmErrorLog.Lines.SaveToFile(ErrorLogPath + GetLocalDate + '\' + GetLocalTime + '.log');
end;
procedure TfrmEasyPlateServerMain.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
var
Factory: IClassFactory;
begin
try
CanClose := False;
//EXE应用程序退出
if ConnectionList.Items.Count > 0 then
begin
if Forms.Application.MessageBox(PChar(ESErrClose), PChar('提示'), MB_OKCANCEL +
MB_ICONQUESTION) = IDCANCEL then
begin
end else
begin
//关闭服务时不提示COM警告信息
CoGetClassObject(Class_RDMEasyPlateServer, CLSCTX_SERVER, nil, IClassFactory, Factory);
Factory.LockServer(False);
if ApplyAction.Enabled then
ApplyAction.Execute;
WriteSettings;
CanClose := True;
end;
end else
CanClose := True;
finally
end;
end;
procedure TfrmEasyPlateServerMain.PortListClick(Sender: TObject);
begin
ItemIndex := PortList.ItemIndex;
end;
procedure TfrmEasyPlateServerMain.ApplyActionUpdate(Sender: TObject);
begin
ApplyAction.Enabled := PortNo.Modified or ThreadSize.Modified or
Timeout.Modified or InterceptGUID.Modified;
end;
procedure TfrmEasyPlateServerMain.DisconnectActionUpdate(Sender: TObject);
begin
DisconnectAction.Enabled := ConnectionList.SelCount > 0;
end;
procedure TfrmEasyPlateServerMain.RemovePortActionUpdate(Sender: TObject);
begin
RemovePortAction.Enabled := (PortList.Items.Count > 1) and (ItemIndex <> -1);
end;
procedure TfrmEasyPlateServerMain.FormShow(Sender: TObject);
begin
pgcServerMain.ActivePageIndex := 0;
mmExecLog.ReadOnly := True;
mmErrorLog.ReadOnly := True;
//服务程序目录 处理日志目录
AppServerPath := ExtractFilePath(Forms.Application.ExeName);
ExecLogPath := AppServerPath + 'log\ExecLog\';
ErrorLogPath := AppServerPath + 'log\ErrorLog\';
if not DirectoryExists(AppServerPath + 'log') then
begin
try
if CreateDir(AppServerPath + 'log') then
begin
if not DirectoryExists(ExecLogPath) then
begin
try
CreateDir(ExecLogPath);
except on e:Exception do
ShowMessage('运行日志目录检查出错, 原因:' + e.Message);
end;
end;
if not DirectoryExists(ErrorLogPath) then
begin
try
CreateDir(ErrorLogPath);
except on e:Exception do
ShowMessage('错误日志目录检查出错, 原因:' + e.Message);
end;
end;
end;
except on e:Exception do
ShowMessage('日志目录检查出错, 原因:' + e.Message);
end;
end;
if FindRegAutoRun('EasyPlateServer') then
mmAutoRun.Checked := True;
end;
function TfrmEasyPlateServerMain.GetLocalDate: string;
begin
Result := FormatDateTime('YYYY-MM-DD', Now());
end;
function TfrmEasyPlateServerMain.GetLocalTime: string;
begin
Result := FormatDateTime('YYYY-MM-DD HHNNSS', Now());
end;
procedure TfrmEasyPlateServerMain.mmErrorLogChange(Sender: TObject);
begin
if TEasyMemo(Sender).Lines.Count > mmLogLineCount then
begin
if not DirectoryExists(ErrorLogPath + GetLocalDate) then
try
CreateDir(ErrorLogPath + GetLocalDate);
except on e:Exception do
ShowMessage(e.Message);
end;
while not FileExists(ErrorLogPath + GetLocalDate + '\' + GetLocalTime + '.log') do
mmErrorLog.Lines.SaveToFile(ErrorLogPath + GetLocalDate + '\' + GetLocalTime + '.log');
end;
end;
procedure TfrmEasyPlateServerMain.mmExecLogChange(Sender: TObject);
begin
if TEasyMemo(Sender).Lines.Count > mmLogLineCount then
begin
if not DirectoryExists(ExecLogPath + GetLocalDate) then
try
CreateDir(ExecLogPath + GetLocalDate);
except on e:Exception do
ShowMessage(e.Message);
end;
while not FileExists(ExecLogPath + GetLocalDate + '\' + GetLocalTime + '.log') do
mmExecLog.Lines.SaveToFile(ExecLogPath + GetLocalDate + '\' + GetLocalTime + '.log');
end;
end;
procedure TfrmEasyPlateServerMain.RDMServerCreated(var msg: TMessage);
begin
mmExecLog.Lines.Add('RDM创建成功!');
//
end;
procedure TfrmEasyPlateServerMain.RefreshTableCache;
var
I: Integer;
ASQL: string;
ACds : TClientDataSet;
begin
if not DirectoryExists(AppServerPath + 'Cache\Table\') then
CreateDir_H(AppServerPath + 'Cache\Table\');
ASQL := 'SELECT [name] FROM sys.all_objects WHERE type = ' + QuotedStr('U');
with DMLocal.EasyLocalCds do
begin
Close;
CommandText := ASQL;
Open;
if RecordCount > 0 then
begin
ACds := TClientDataSet.Create(nil);
ACds.Data := Data;
try
Screen.Cursor := crHourGlass;
for I := 0 to ACds.RecordCount - 1 do
begin
{with DMLocal.EasyLocalCds do
begin
Close;
CommandText := 'SELECT * FROM ' + ACds.fieldbyname('name').AsString
+ ' WHERE 1 = 2';
Open;
if not DirectoryExists(AppServerPath + 'Cache\Table\') then
begin
if CreateDir_H(AppServerPath + 'Cache\Table\') then
end;
// SaveToFile(AppServerPath + 'Cache\Table\'
// + ACds.fieldbyname('name').AsString + '.xml', dfXMLUTF8);
end; }
with DMLocal.EasyLocalQry do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + ACds.fieldbyname('name').AsString
+ ' WHERE 1 = 2');
Open;
DMLocal.EasyLocalQry.SaveToFile(AppServerPath + 'Cache\Table\'
+ ACds.fieldbyname('name').AsString + '.xml');
end;
ACds.Next;
end;
Forms.Application.MessageBox('表缓存更新成功!', '', MB_OK + MB_ICONINFORMATION);
finally
ACds.Free;
Screen.Cursor := crDefault;
end;
end;
end;
end;
procedure TfrmEasyPlateServerMain.EasyToolBarButton3Click(Sender: TObject);
begin
RefreshTableCache;
end;
procedure TfrmEasyPlateServerMain.btnExitClick(Sender: TObject);
begin
Close;
end;
procedure TfrmEasyPlateServerMain.RDMServerDestroy(var msg: TMessage);
begin
mmExecLog.Lines.Add('RDM销毁完成!');
end;
procedure TfrmEasyPlateServerMain.RDMServerPoolerCreate(var msg: TMessage);
begin
mmExecLog.Lines.Add('IRDM New完成!');
end;
procedure TfrmEasyPlateServerMain.N12Click(Sender: TObject);
begin
ServerTrayIcon.HideMainForm;
end;
procedure TfrmEasyPlateServerMain.N13Click(Sender: TObject);
begin
Close;
end;
procedure TfrmEasyPlateServerMain.mmDetailLogClick(Sender: TObject);
begin
mmDetailLog.Checked := not mmDetailLog.Checked;
end;
procedure TfrmEasyPlateServerMain.N14Click(Sender: TObject);
begin
btnExitClick(Sender);
end;
procedure TfrmEasyPlateServerMain.N16Click(Sender: TObject);
begin
N12Click(Sender);
end;
procedure TfrmEasyPlateServerMain.RegAutoRun(Key, AppPath: string);
//开机自动启动
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.OpenKey( '\SOFTWARE\Microsoft\windows\CurrentVersion\Run', False);
Reg.writeString(Key, AppPath);
Reg.CloseKey;
end;
procedure TfrmEasyPlateServerMain.UnRegAutoRun(Key: string);
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.OpenKey( '\SOFTWARE\Microsoft\windows\CurrentVersion\Run', False);
Reg.DeleteValue(Key);
Reg.CloseKey;
end;
procedure TfrmEasyPlateServerMain.mmAutoRunClick(Sender: TObject);
begin
mmAutoRun.Checked := not mmAutoRun.Checked;
if mmAutoRun.Checked then
RegAutoRun('EasyPlateServer', Forms.Application.ExeName)
else
UnRegAutoRun('EasyPlateServer');
end;
function TfrmEasyPlateServerMain.FindRegAutoRun(Key: string): Boolean;
var
Reg: TRegistry;
AFilePath: string;
begin
Reg := TRegistry.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.OpenKey( '\SOFTWARE\Microsoft\windows\CurrentVersion\Run', False);
AFilePath := Reg.ReadString(Key);
if FileExists(AFilePath) then
Result := True
else
Result := False;
Reg.CloseKey;
end;
end.
|
unit StoreHouseListInterface;
interface
type
IStorehouseList = interface(IInterface)
function GetStoreHouseCount: Integer;
function GetStoreHouseTitle: string;
property StoreHouseCount: Integer read GetStoreHouseCount;
property StoreHouseTitle: string read GetStoreHouseTitle;
end;
implementation
end.
|
unit MediaStream.Framer.H264;
interface
uses Windows,SysUtils,Classes, BufferedStream, MediaProcessing.Definitions,
MediaStream.Framer,H264Parser,H264Def;
type
TStreamFramerH264 = class (TStreamFramer)
private
FStream: TStream;
FReader: TBufferedStream;
FBuffer: TMemoryStream;
FParser : TH264Parser;
FProcessedFrameCount: int64;
function GetUpToNextNAL: boolean;
public
constructor Create; override;
destructor Destroy; override;
procedure OpenStream(aStream: TStream); override;
function GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal):boolean; overload; override;
function GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal; out aNal: TNalUnitType): boolean; reintroduce; overload;
function VideoStreamType: TStreamType; override;
function AudioStreamType: TStreamType; override;
function StreamInfo: TBytes; override;
property Parser: TH264Parser read FParser;
end;
implementation
{ TStreamFramerH264 }
constructor TStreamFramerH264.Create;
begin
inherited;
FBuffer:=TMemoryStream.Create;
FParser:=TH264Parser.Create;
end;
destructor TStreamFramerH264.Destroy;
begin
inherited;
FreeAndNil(FBuffer);
FreeAndNil(FReader);
FreeAndNil(FParser);
FStream:=nil;
end;
function TStreamFramerH264.GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal; out aNal: TNalUnitType): boolean;
var
aPayload: byte;
aTmp: integer;
aFrameRate: double;
begin
result:=GetUpToNextNAL;
if result then
begin
//
//|0|1|2|3|4|5|6|7|
//+-+-+-+-+-+-+-+-+
//|F|NRI| Type |
//+---------------+
aTmp:=(PByte(FBuffer.Memory)+4)^;
Assert(aTmp shr 7=0);
aPayload:=aTmp and $1F;
Assert(aPayload in [1..23]);
aNal:=TNalUnitType(aPayload);
//SEQ Param
if aNal = NAL_UT_SEQ_PARAM then
FParser.Parse(PByte(FBuffer.Memory)+4,FBuffer.Size-4);
aOutData:=FBuffer.Memory;
aOutDataSize:=FBuffer.Position;
Assert(PCardinal(aOutData)^=NAL_START_MARKER);
Assert(aOutDataSize>4);
Assert(PCardinal((PByte(aOutData)+aOutDataSize-4))^<>NAL_START_MARKER);
aOutInfo:=nil;
aOutInfoSize:=0;
aOutFormat.Clear;
aOutFormat.biMediaType:=mtVideo;
aOutFormat.biStreamType:=VideoStreamType;
aOutFormat.VideoWidth:=FParser.LastParams.PictureWidth;
aOutFormat.VideoHeight:=FParser.LastParams.PictureHeight;
//aOutFormat.biBitCount:=24; //TODO ??
//aOutFormat.DataSize:=aOutDataSize;
if aNal in [NAL_UT_SLICE_IDR,NAL_UT_SEQ_PARAM, NAL_UT_PIC_PARAM] then
Include(aOutFormat.biFrameFlags,ffKeyFrame);
if aNal in [NAL_UT_SEQ_PARAM,NAL_UT_PIC_PARAM] then
Include(aOutFormat.biFrameFlags,ffInitParamsFrame);
aFrameRate:=25;
if FParser.LastParams.frame_rate<>0 then
aFrameRate:=FParser.LastParams.frame_rate;
if aFrameRate>0 then
aOutFormat.TimeStamp:=Trunc(FProcessedFrameCount*1000/aFrameRate);
inc(FProcessedFrameCount);
end;
end;
function TStreamFramerH264.GetNextFrame(out aOutFormat: TMediaStreamDataHeader;
out aOutData: pointer; out aOutDataSize: cardinal;
out aOutInfo: pointer;
out aOutInfoSize: cardinal): boolean;
var
aNal: TNalUnitType;
begin
result:=GetNextFrame(aOutFormat,aOutData,aOutDataSize,aOutInfo,aOutInfoSize,aNal);
end;
function TStreamFramerH264.GetUpToNextNAL: boolean;
var
i: byte;
aMarker: cardinal;
aPtr: PCardinal;
begin
FBuffer.Position:=0;
aMarker:=NAL_START_MARKER;
FBuffer.Write(aMarker,4);
result:=false;
while true do
begin
if FReader.Read(i,1)<>1 then
break;
FBuffer.Write(i,1);
if FBuffer.Position>=8 then
begin
aPtr:=PCardinal(PByte(FBuffer.Memory)+(FBuffer.Position-4));
if aPtr^=NAL_START_MARKER then
begin
FBuffer.Position:=FBuffer.Position-4;
result:=true;
break;
end;
end;
end;
end;
procedure TStreamFramerH264.OpenStream(aStream: TStream);
begin
FreeAndNil(FReader);
FStream:=aStream;
FReader:=TBufferedStream.Create(aStream);
FReader.BufferSize:=65*1024;
FProcessedFrameCount:=0;
GetUpToNextNAL;
end;
function TStreamFramerH264.StreamInfo: TBytes;
begin
result:=nil;
end;
function TStreamFramerH264.VideoStreamType: TStreamType;
begin
result:=stH264;
end;
function TStreamFramerH264.AudioStreamType: TStreamType;
begin
result:=0;
end;
end.
|
unit MediaStream.Filer.H264;
interface
uses SysUtils,Classes, Windows, SyncObjs, MediaStream.Filer, MediaProcessing.Definitions,H264Parser;
type
TStreamFilerH264 = class (TStreamFiler)
private
FParser: TH264Parser;
protected
procedure DoWriteData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); override;
public
constructor Create; override;
destructor Destroy; override;
class function DefaultExt: string; override;
end;
implementation
{ TStreamFilerH264 }
constructor TStreamFilerH264.Create;
begin
inherited;
FParser:=TH264Parser.Create;
end;
class function TStreamFilerH264.DefaultExt: string;
begin
result:='.h264';
end;
destructor TStreamFilerH264.Destroy;
begin
FreeAndNil(FParser);
inherited;
end;
procedure TStreamFilerH264.DoWriteData(const aFormat: TMediaStreamDataHeader;
aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal);
begin
inherited;
Assert(PDWORD(aData)^=$1000000); //NAL_START_MARKER
FParser.Parse(aData,aDataSize);
if FParser.LastParams.PictureWidth<>0 then
FStream.WriteBuffer(aData^,aDataSize);
end;
end.
|
unit ugraphicsform;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs,
ComCtrls, StdCtrls, ExtCtrls, Grids, Buttons, ValEdit, Menus, Windows,
strutils, uregistermachine, umanualform;
type
{ TReMEditForm }
TReMEditForm = class(TForm)
openWriteBtn: TButton;
CloseBtn: TBitBtn;
Editor: TMemo;
fillIndicesPop: TPopupMenu;
fillIndices: TMenuItem;
ErrorOutput: TMemo;
HeadingError: TPanel;
HeadingStart: TPanel;
openManualBtn: TButton;
saveMenu: TMenuItem;
SpeedContainer: TPanel;
SaveRegister: TSaveDialog;
SaveFile: TButton;
CancelExecuteBtn: TBitBtn;
CreateBtnWrite: TButton;
ExecuteBtn: TBitBtn;
InfoLabel: TLabel;
SpeedLabel: TLabel;
LoadFile: TButton;
OpenRegister: TOpenDialog;
Pages: TPageControl;
HeadingLeft: TPanel;
RegisterSG: TStringGrid;
ExecuteSG: TStringGrid;
TabSetUp: TTabSheet;
TabError: TTabSheet;
TabStart: TTabSheet;
TabWrite: TTabSheet;
SpeedTrackBar: TTrackBar;
procedure openManualBtnClick(Sender: TObject);
procedure openWriteBtnClick(Sender: TObject);
procedure save(fileSource: string);
procedure CancelExecuteBtnClick(Sender: TObject);
procedure fillIndicesClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
procedure SaveFileClick(Sender: TObject);
procedure CloseBtnClick(Sender: TObject);
procedure CreateMachine(Sender: TObject);
procedure ExecuteBtnClick(Sender: TObject);
procedure ExecuteSGDrawCell(Sender: TObject; aCol, aRow: integer;
aRect: TRect; aState: TGridDrawState);
procedure FormCreate(Sender: TObject);
procedure LoadFileClick(Sender: TObject);
procedure initializeExecuteSG(registerAmount: integer);
procedure Delay;
procedure goToLine(X, Y: integer);
procedure saveMenuClick(Sender: TObject);
procedure updateCaption;
private
{ private declarations }
public
{ public declarations }
end;
var
ReMEditForm: TReMEditForm;
loadedList: TStringList;
regM: RegisterMachine;
markedCells: array of array[0..1] of integer;
cancelExecute: boolean;
actualFile: string;
implementation
{$R *.lfm}
{DELAY FUNCTION}
{ TReMEditForm }
procedure TReMEditForm.LoadFileClick(Sender: TObject);
begin
if (Editor.Lines.Count <> 0) and
(MessageDlg('', 'Alle nicht gespeicherten Fortschritte gehen verloren. Fortfahren?',
mtConfirmation, mbYesNo, -1) = mrYes) then
begin
if OpenRegister.Execute then
begin
Editor.Clear;
actualFile := OpenRegister.FileName;
Editor.Lines.LoadFromFile(actualFile);
updateCaption;
end
else
ShowMessage('Kein File ausgewählt');
end;
end;
procedure TReMEditForm.initializeExecuteSG(registerAmount: integer);
var
i: integer;
begin
RegisterSG.Enabled := False;
ExecuteBtn.Enabled := False;
CancelExecuteBtn.Enabled := True;
with ExecuteSG do
begin
Enabled := True;
Visible := True;
ColCount := 4 + registerAmount;
RowCount := 1;
Cells[0, 0] := 'i';
Cells[1, 0] := 'b';
Cells[2, 0] := 'Zeile';
Cells[3, 0] := 'Effekt';
end;
for i := 0 to registerAmount - 1 do
begin
ExecuteSG.Cells[i + 4, 0] := 'c(' + IntToStr(i) + ')';
end;
end;
procedure TReMEditForm.Delay;
var
tc: DWORD;
begin
tc := GetTickCount;
while (GetTickCount < tc + ((SpeedTrackBar.Max + SpeedTrackBar.Min) -
SpeedTrackBar.Position)) and (not Application.Terminated) do
Application.ProcessMessages;
end;
procedure TReMEditForm.goToLine(X, Y: integer);
var
s: string;
actLineNumber, i, cPos: integer;
begin
actLineNumber := 0;
s := Editor.Text;
cPos := 0;
for i := 0 to Length(s) do
begin
cPos := cPos + 1;
if Copy(s, i, 1) = #10 then
actLineNumber := actLineNumber + 1;
if actLineNumber = Y then
begin
Editor.SetFocus;
Editor.SelStart := cPos + X;
Break;
end;
end;
end;
procedure TReMEditForm.saveMenuClick(Sender: TObject);
begin
if actualFile <> '' then
save(actualFile)
else
SaveFileClick(nil);
end;
procedure TReMEditForm.updateCaption;
begin
Caption := 'ReMEdit 1.0 ' + ExtractFileName(actualFile);
end;
procedure TReMEditForm.CloseBtnClick(Sender: TObject);
begin
Close;
end;
procedure TReMEditForm.SaveFileClick(Sender: TObject);
begin
if SaveRegister.Execute then
begin
save(SaveRegister.FileName);
end;
end;
procedure TReMEditForm.fillIndicesClick(Sender: TObject);
var
i, j, b, oldLineLength: integer;
pos: TPOINT;
line, refLine, referrer: string;
forwardC, backwardC : array of array[0..1] of String;
procedure fillVerifiedCommands; //firstly changes all commands to legal commands
var
k : Integer;
begin
for k := 0 to Editor.Lines.Count - 1 do
begin
line := trim(Editor.Lines[k]);
if RegisterMachine.verifyCommand('0 ' + line) = '' then //else it adds an artificial index to check if the user hasn't written any
Editor.Lines[k] := '0 ' + line;
end;
end;
procedure findIndexChanges; //finds lines which need a value change
var
l, m, refIndex, referrerIndex: Integer;
begin
for l:= 0 to Editor.Lines.Count - 1 do
begin
if (AnsiMatchText(ExtractDelimited(2, Editor.Lines[l], [' ']), ['GOTO', 'JZERO', 'JNZERO'])) AND (RegisterMachine.verifyCommand(Editor.Lines[l]) = '') then
//if command is GOTO, JZERO or JNZERO
begin
//find referred line
referrerIndex := StrToInt(ExtractDelimited(3, Editor.Lines[l], [' ']));
for m := 0 to Editor.Lines.Count - 1 do
begin
if RegisterMachine.verifyCommand(Editor.Lines[m]) = '' then
begin
refIndex:= StrToInt(ExtractDelimited(1, Editor.Lines[m], [' ']));
//if the referred line's index is bigger than the referrer line it's a forward Index Change otherwise it's backward
if referrerIndex = refIndex then
begin
if l < m then
begin
SetLength(forwardC, Length(forwardC) + 1);
forwardC[High(forwardC)][0] := Editor.Lines[l];
forwardC[High(forwardC)][1] := Editor.Lines[m];
end
else
begin
SetLength(backwardC, Length(backwardC) + 1);
backwardC[High(backwardC)][0] := Editor.Lines[l];
backwardC[High(backwardC)][1] := Editor.Lines[m];
end;
break;
end;
end;
end;
end;
end;
end;
begin
pos := editor.CaretPos;
oldLineLength:= Length(Editor.Lines[pos.y]); //necessary for recalculation of cursor position in memo
b := 0;
fillVerifiedCommands;
findIndexChanges;
for i := 0 to Editor.Lines.Count - 1 do
begin
if RegisterMachine.verifyCommand(Editor.Lines[i]) = '' then //if command legal
begin
line := Editor.Lines[i];
line := UpperCase(IntToStr(b) + ' ' + ExtractDelimited(2, line, [' ']) + ' ' + ExtractDelimited(3, line, [' '])); //updates index
//implementation of forward Index Changes
for j := 0 to High(forwardC) do
begin
if forwardC[j][0] = Editor.Lines[i] then //if the actual line will be changed, the string in forwardC will be too
begin
forwardC[j][0] := line;
end;
if forwardC[j][1] = Editor.Lines[i] then
begin
referrer := forwardC[j][0];
Editor.Lines[Editor.Lines.IndexOf(referrer)] := ExtractDelimited(1, referrer, [' ']) + ' ' + ExtractDelimited(2, referrer, [' ']) + ' ' + IntToStr(b) ;
end;
end;
//implementation of backward Index Changes
for j := 0 to High(backwardC) do
begin
if backwardC[j][1] = Editor.Lines[i] then
begin
backwardC[j][1] := line;
end;
if backwardC[j][0] = Editor.Lines[i] then
begin
refLine:= backwardC[j][1];
line := ExtractDelimited(1, line, [' ']) + ' ' + ExtractDelimited(2, line, [' ']) + ' ' + ExtractDelimited(1, refLine, [' ']) ;
end;
end;
b := b + 1;
Editor.Lines[i] := line;
end;
end;
goToLine(pos.x + Length(Editor.Lines[pos.y]) - oldLineLength, pos.y); //recalculation of cursor position
end;
procedure TReMEditForm.FormCloseQuery(Sender: TObject; var CanClose: boolean);
var
i: integer;
fileSaved: boolean;
oldFile, newFile: TStringList;
begin
fileSaved := True;
oldFile := TStringList.Create;
newFile := TStringList.Create;
newFile.AddStrings(Editor.Lines);
//Determines, if file has changed
try
oldFile.LoadFromFile(actualFile);
for i := 0 to newFile.Count - 1 do
begin
try
if trim(newFile.Strings[i]) <> trim(oldFile.Strings[i]) then
begin
fileSaved := False;
break;
end;
except
fileSaved := False;
break;
end;
end;
except
fileSaved := False;
end;
if not fileSaved then
begin
if MessageDlg('Warnung', 'Sie haben ungespeicherte Änderungen. Wollen Sie die Anwendung wirklich schließen?',
mtWarning, mbYesNo, 0) = mrYes then
CanClose := True
else
CanClose := False;
end;
end;
procedure TReMEditForm.save(fileSource: string);
begin
actualFile := fileSource;
Editor.Lines.SaveToFile(fileSource);
updateCaption;
end;
procedure TReMEditForm.openWriteBtnClick(Sender: TObject);
begin
TabWrite.TabVisible:= true;
Pages.ActivePage := TabWrite;
end;
procedure TReMEditForm.openManualBtnClick(Sender: TObject);
begin
manualform.Show;
end;
procedure TReMEditForm.CancelExecuteBtnClick(Sender: TObject);
begin
cancelExecute := True;
CancelExecuteBtn.Enabled := False;
ExecuteBtn.Enabled := True;
RegisterSG.Enabled := True;
end;
//CREATE
procedure TReMEditForm.CreateMachine(Sender: TObject);
var
i: integer;
begin
fillIndicesClick(nil);
loadedList := TStringList.Create;
loadedList.AddStrings(Editor.Lines);
regM := RegisterMachine.Create(loadedList);
if regM.GetErrorMessage <> '' then
begin
//ERROR HANDLING
TabError.TabVisible := True;
Pages.ActivePage := TabError;
ErrorOutput.Clear;
ErrorOutput.Lines.Add(regM.GetErrorMessage);
end
else
begin
//INITIALIZATION for TabExecute
if actualFile <> '' then
Editor.Lines.SaveToFile(actualFile);
TabError.TabVisible := False;
with RegisterSG do
begin
RowCount := 2;
FixedRows := 1;
ColCount := High(regM.GetRegisterData);
end;
for i := 0 to High(regM.GetRegisterData) - 1 do
begin
RegisterSG.Cells[i, 0] := 'c(' + IntToStr(i + 1) + ')';
RegisterSG.Cells[i, 1] := '0';
end;
ExecuteSG.Visible := False;
TabSetUp.TabVisible := True;
Pages.ActivePage := TabSetUp;
end;
end;
//EXECUTE
procedure TReMEditForm.ExecuteBtnClick(Sender: TObject);
var
values: registerArray;
i, j, colorRegister: integer;
h: commandLine;
begin
cancelExecute := False;
SetLength(values, RegisterSG.ColCount);
for i := 0 to RegisterSG.ColCount - 1 do
begin
values[i] := StrToInt(RegisterSG.Cells[i, 1]);
end;
if not regM.Execute(values) then
begin
if MessageDlg('Warnung',
'Möglicherweise wird die Registermaschine nie beendet. Ein manueller Abbruch ist bei Fortfahren eventuell erforderlich.',
mtWarning, mbOKCancel, 0) = mrCancel then
exit;
end;
initializeExecuteSG(Length(regM.GetRegisterData));
for i := 1 to Length(regM.GetExecuteLog) do
begin
if cancelExecute then //Cancel button is pressed stop procedure
exit;
with ExecuteSG do
begin
//Adds new line in ExecuteSG
RowCount := RowCount + 1;
Row := RowCount;
Cells[0, i] := IntToStr(i);
Cells[1, i] := regM.GetExecuteLog[i - 1].b;
h := regM.GetExecuteLog[i - 1].command;
case h.command of
'END': Cells[2, i] := h.command;
'': Cells[2, i] := '';
else
Cells[2, i] := h.command + ' ' + IntToStr(h.Value);
end;
Cells[3, i] := regM.GetExecuteLog[i - 1].sysOutput;
end;
for j := 0 to High(regM.GetExecuteLog[i - 1].registers) do
begin
ExecuteSG.Cells[4 + j, i] := IntToStr(regM.GetExecuteLog[i - 1].registers[j]);
end;
//colors Registers
colorRegister := -1;
if AnsiMatchText(regM.GetExecuteLog[i - 1].command.command,
['LOAD', 'CLOAD', 'CADD', 'CSUB', 'CMULT', 'CDIV', 'MULT',
'ADD', 'SUB', 'DIV']) then
colorRegister := 0
else if regM.GetExecuteLog[i - 1].command.command = 'STORE' then
colorRegister := regM.GetExecuteLog[i - 1].command.Value;
if colorRegister <> -1 then
begin
SetLength(markedCells, Length(markedCells) + 1);
markedCells[High(markedCells)][0] := 4 + colorRegister;
markedCells[High(markedCells)][1] := i;
end;
Delay;
end;
CancelExecuteBtnClick(nil);
end;
procedure TReMEditForm.ExecuteSGDrawCell(Sender: TObject; aCol, aRow: integer;
aRect: TRect; aState: TGridDrawState);
var
i: integer;
procedure colorCell(aRect: TRect; cellText: string; brushColor: TColor);
begin
with ExecuteSG do
begin
Canvas.Brush.Color := brushColor;
Canvas.FillRect(aRect);
Canvas.TextOut(aRect.Left + 2, aRect.Top + 2, cellText);
end;
end;
begin
//changes color of ExecuteSG cells
//grey cells
for i := 0 to High(markedCells) do
begin
if (ACol = markedCells[i][0]) and (ARow = markedCells[i][1]) then
begin
colorCell(aRect, ExecuteSG.Cells[ACol, ARow], clSilver);
end;
end;
//green cells
if ARow = Length(regM.GetExecuteLog) then
begin
colorCell(aRect, ExecuteSG.Cells[ACol, ARow], clGreen);
end;
end;
procedure TReMEditForm.FormCreate(Sender: TObject);
begin
//VARIABLE INITIALIZATION
actualFile := 'Beispiele/Zahlenvergleich.txt';
cancelExecute := False;
SetLength(markedCells, 0);
Editor.Lines.LoadFromFile(actualFile);
//LAYOUT INITIALIZATION
Pages.ActivePage := TabStart;
TabWrite.TabVisible:= false;
TabSetUp.TabVisible := False;
TabError.TabVisible := False;
Pages.Color := clGray;
updateCaption;
end;
end.
|
unit PascalCoin.FMX.Frame.Send;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
PascalCoin.FMX.Frame.Base, FMX.EditBox, FMX.NumberBox, FMX.Edit, FMX.ListBox,
FMX.Controls.Presentation, FMX.Layouts, PascalCoin.RPC.Interfaces,
PascalCoin.Wallet.Interfaces;
type
TSendFrame = class(TBaseFrame)
MainLayout: TLayout;
AccountLayout: TLayout;
AccountLabel: TLabel;
AccountNumber: TComboBox;
PayloadLayout: TLayout;
PayloadLabel: TLabel;
Payload: TEdit;
AmountLayout: TLayout;
AmountLabel: TLabel;
Amount: TNumberBox;
PascLabel: TLabel;
PayloadAdvanced: TLayout;
PayloadEncodeLayout: TLayout;
PayloadEncodeLabel: TLabel;
PayloadEncode: TComboBox;
PayloadEncryptLayout: TLayout;
PayloadEncryptLabel: TLabel;
PayloadEncrypt: TComboBox;
PayloadPasswordLayout: TLayout;
PasswordLabel: TLabel;
PayloadPassword: TEdit;
SendTolayout: TLayout;
SendToLabel: TLabel;
SendTo: TEdit;
FooterLayout: TLayout;
SendButton: TButton;
FeeLayout: TLayout;
FeeLabel: TLabel;
Fee: TNumberBox;
Label2: TLabel;
procedure AccountNumberChange(Sender: TObject);
procedure AmountChange(Sender: TObject);
procedure SendButtonClick(Sender: TObject);
procedure SendToChange(Sender: TObject);
private
{ Private declarations }
FSendFromValid: Boolean;
FSendToValid: Boolean;
FAmountValid: Boolean;
FSenderAccount: Cardinal;
FSenderCheckSum: Integer;
FRecipientAccountNumber: Cardinal;
FRecipientCheckSum: Integer;
FRecipientAccount: IPascalCoinAccount;
FAvaliableBalance: Currency;
procedure DataChanged;
function CheckEnoughPasc: Boolean;
function CheckSendToValid: Boolean;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
end;
var
SendFrame: TSendFrame;
implementation
{$R *.fmx}
uses System.Rtti, PascalCoin.FMX.DataModule, PascalCoin.FMX.Wallet.Shared,
PascalCoin.Utils.Interfaces, PascalCoin.FMX.Strings,
PascalCoin.RawOp.Interfaces;
{ TSendFrame }
function TSendFrame.CheckEnoughPasc: Boolean;
begin
if (Amount.Value > 0) and (Amount.Value > FAvaliableBalance) then
begin
ShowMessage
('The selected account doesn''t have enough PASC for this transaction');
result := False;
end
else
result := True;
end;
function TSendFrame.CheckSendToValid: Boolean;
var
lAccount: Cardinal;
lChkSum: Integer;
begin
FRecipientAccountNumber := 0;
FRecipientCheckSum := 0;
result := MainDataModule.Utils.ValidAccountNumber(SendTo.Text);
if not result then
begin
ShowMessage(STheAccountNumberIsInvalid);
Exit;
end;
MainDataModule.Utils.SplitAccount(SendTo.Text, lAccount, lChkSum);
try
FRecipientAccount := MainDataModule.API.getaccount(lAccount);
result := True;
FRecipientAccountNumber := lAccount;
FRecipientCheckSum := lChkSum;
except
ShowMessage('Cannot find this account in the SafeBox');
end;
end;
constructor TSendFrame.Create(AOwner: TComponent);
var
lPE: TPayloadEncryption;
lPT: TPayloadEncode;
lAccount, tAccount: string;
sAccount: Integer;
begin
inherited;
PascLabel.Text := FormatSettings.CurrencyString;
// FURI := MainDataModule.Config.Container.Resolve<IPascalCoinURI>;
for lPE := Low(TPayloadEncryption) to High(TPayloadEncryption) do
PayloadEncrypt.Items.Add(_PayloadEncryptText[lPE]);
PayloadEncrypt.ItemIndex := 2;
for lPT := Low(TPayloadEncode) to High(TPayloadEncode) do
PayloadEncode.Items.Add(_PayloadEncodeText[lPT]);
PayloadEncode.ItemIndex := 0;
PayloadAdvanced.Visible := MainDataModule.Settings.AdvancedOptions;
PayloadPasswordLayout.Visible := False;
FeeLayout.Visible := MainDataModule.Settings.AdvancedOptions;
sAccount := MainDataModule.AccountsDataAccountNumber.Value;
tAccount := '';
MainDataModule.DisableAccountData;
try
MainDataModule.AccountsData.First;
while not MainDataModule.AccountsData.Eof do
begin
if MainDataModule.AccountsDataBalance.Value > 0 then
begin
lAccount := MainDataModule.AccountsDataAccountNumChkSum.Value;
if MainDataModule.AccountsDataAccountName.Value <> '' then
lAccount := lAccount + ' | ' +
MainDataModule.AccountsDataAccountName.Value;
lAccount := lAccount + ' | ' +
CurrToStrF(MainDataModule.AccountsDataBalance.Value, ffCurrency, 4);
AccountNumber.Items.Add(lAccount);
if MainDataModule.AccountsDataAccountNumber.Value = sAccount then
tAccount := lAccount;
end;
MainDataModule.AccountsData.Next;
end;
finally
MainDataModule.EnableAccountData;
end;
if tAccount <> '' then
AccountNumber.ItemIndex := AccountNumber.Items.IndexOf(tAccount)
else
AccountNumber.ItemIndex := 0;
end;
procedure TSendFrame.AccountNumberChange(Sender: TObject);
var
lAccount: TArray<string>;
lBalance: string;
begin
FSendFromValid := (AccountNumber.ItemIndex > -1);
if FSendFromValid then
begin
lAccount := AccountNumber.Selected.Text.Split(['|']);
MainDataModule.Utils.SplitAccount(lAccount[0].Trim, FSenderAccount,
FSenderCheckSum);
lBalance := lAccount[length(lAccount) - 1];
lBalance := lBalance.Substring
(lBalance.IndexOf(FormatSettings.CurrencyString) +
length(FormatSettings.CurrencyString)).Trim;
FAvaliableBalance := StrToCurr(lBalance);
FSendFromValid := CheckEnoughPasc;
end;
DataChanged;
end;
procedure TSendFrame.AmountChange(Sender: TObject);
begin
FAmountValid := Amount.Value > 0;
if FAmountValid then
FSendFromValid := CheckEnoughPasc;
DataChanged;
end;
procedure TSendFrame.DataChanged;
begin
SendButton.Enabled := FSendFromValid and FAmountValid and FSendToValid;
end;
procedure TSendFrame.SendButtonClick(Sender: TObject);
var
Ops: IRawOperations;
Tx: IRawTransactionOp;
Retval: IPascalCoinOperation;
sAccount: IPascalCoinAccount;
lWalletKey: IWalletKey;
lPayload, lHexPayload: string;
lEncrypt: TPayloadEncryption;
begin
sAccount := MainDataModule.API.getaccount(FSenderAccount);
if sAccount.balance < Amount.Value then
begin
ShowMessage('Not enough PASC for this');
Exit;
end;
lHexPayload := MainDataModule.Utils.StrToHex(Payload.Text);
lEncrypt := TPayloadEncryption(PayloadEncrypt.ItemIndex);
case lEncrypt of
TPayloadEncryption.None:
lPayload := lHexPayload;
TPayloadEncryption.SendersKey:
begin
lWalletKey := MainDataModule.Wallet.FindKey(sAccount.enc_pubkey);
lPayload := MainDataModule.KeyTools.EncryptPayloadWithPublicKey
(lWalletKey.KeyType, lWalletKey.PublicKey.AsBase58, lHexPayload);
end;
TPayloadEncryption.RecipientsKey:
lPayload := MainDataModule.API.payloadEncryptWithPublicKey(lHexPayload,
FRecipientAccount.enc_pubkey, TKeyStyle.ksEncKey);
TPayloadEncryption.Password:
lPayload := MainDataModule.KeyTools.EncryptPayloadWithPassword
(PayloadPassword.Text, Payload.Text);
end;
Ops := MainDataModule.Config.Container.Resolve<IRawOperations>;
{ TODO :
if MainDataModule.Settings.AutoMultiAccountTransactions then
Add a trawl through accounts and create multiple transactions to create
until the amount is reached
}
Tx := MainDataModule.Config.Container.Resolve<IRawTransactionOp>;
Tx.SendFrom := FSenderAccount;
Tx.SendTo := FRecipientAccountNumber;
Tx.NOp := sAccount.n_operation + 1;
Tx.Amount := Amount.Value;
Tx.Fee := Fee.Value;
Tx.Key := MainDataModule.Wallet.FindKey(sAccount.enc_pubkey).PrivateKey;
Tx.Payload := lPayload;
Ops.AddRawOperation(Tx);
MainDataModule.UpdatesPause;
try
Retval := MainDataModule.API.executeoperation(Ops.RawData);
finally
MainDataModule.UpdatesRestart;
end;
end;
procedure TSendFrame.SendToChange(Sender: TObject);
begin
FSendToValid := SendTo.Text <> '';
if FSendToValid then
FSendToValid := CheckSendToValid;
DataChanged;
end;
end.
|
unit amqp.time;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
{$INCLUDE config.inc}
uses {$IFNDEF FPC}
{$IFDEF _WIN32}
Net.Winsock2,
{$ELSE}
Net.SocketAPI,
{$ENDIF}
Winapi.Windows,
{$ELSE}
Windows, winsock2, //WS2tcpip,
{$ENDIF} AMQP.Types;
function amqp_time_from_now(var Atime : Tamqp_time;const Atimeout: Ptimeval):integer;
function amqp_time_s_from_now(var Atime : Tamqp_time; Aseconds : integer):integer;
function amqp_time_ms_until( Atime : Tamqp_time):integer;
function amqp_time_tv_until( Atime : Tamqp_time; Ain: Ptimeval; Aout: PPtimeval):integer;
function amqp_time_has_past( Atime : Tamqp_time):integer;
function amqp_time_first( l, r : Tamqp_time):Tamqp_time;
const
//要指定 uint64_t,否则会引发计算错误
AMQP_MS_PER_S: uint32_t =1000;
AMQP_US_PER_MS: uint32_t =1000;
AMQP_NS_PER_S: uint64_t =1000*1000*1000; //每秒=多少纳秒
AMQP_NS_PER_MS: uint64_t =1000*1000; //每毫秒=多少纳秒
AMQP_NS_PER_US: uint32_t =1000; //每微秒=多少纳秒
var
NS_PER_COUNT: double ;
implementation
function amqp_get_monotonic_timestamp:uint64;
var
perf_count,
perf_frequency : Int64;//LARGE_INTEGER;
begin
//static double NS_PER_COUNT = 0;
if 0 = NS_PER_COUNT then
begin
if not QueryPerformanceFrequency(perf_frequency) then
Exit(0);
//NS_PER_COUNT := double(AMQP_NS_PER_S / perf_frequency);
NS_PER_COUNT := (AMQP_NS_PER_S / perf_frequency);
end;
if not QueryPerformanceCounter(perf_count) then
Exit(0);
Result := uint64_t(Round(perf_count * NS_PER_COUNT));
end;
function amqp_time_from_now(var Atime : Tamqp_time;const Atimeout: Ptimeval):integer;
var
now_ns,
delta_ns : Uint64;
LValue: int;
Lns: Int64;
begin
//assert(nil <> Atime);
if nil = Atimeout then
begin
Atime := Tamqp_time.infinite;
LValue := Integer(AMQP_STATUS_OK);
Exit(LValue);
end;
if (Atimeout.tv_sec < 0) or
(Atimeout.tv_usec < 0) then
begin
LValue := Integer(AMQP_STATUS_INVALID_PARAMETER);
Exit(LValue);
end;
Lns := Atimeout.tv_sec * AMQP_NS_PER_S;
delta_ns := Lns +
Atimeout.tv_usec * AMQP_NS_PER_US;
now_ns := amqp_get_monotonic_timestamp();
if 0 = now_ns then
begin
Exit(Integer(AMQP_STATUS_TIMER_FAILURE));
end;
Atime.time_point_ns := now_ns + delta_ns;
if (now_ns > Atime.time_point_ns) or
(delta_ns > Atime.time_point_ns) then
begin
Exit(Integer(AMQP_STATUS_INVALID_PARAMETER));
end;
Result := Integer(AMQP_STATUS_OK);
end;
function amqp_time_s_from_now(var Atime : Tamqp_time; Aseconds : integer):integer;
var
now_ns,
delta_ns : uint64;
begin
//assert(nil <> Atime);
if 0 >= Aseconds then
begin
Atime := Tamqp_time.infinite;
Exit(Integer(AMQP_STATUS_OK));
end;
now_ns := amqp_get_monotonic_timestamp();
if 0 = now_ns then
begin
Exit(Integer(AMQP_STATUS_TIMER_FAILURE));
end;
delta_ns := uint64_t(Aseconds * AMQP_NS_PER_S);
Atime.time_point_ns := now_ns + delta_ns;
if (now_ns > Atime.time_point_ns) or
(delta_ns > Atime.time_point_ns) then
begin
Exit(Integer(AMQP_STATUS_INVALID_PARAMETER));
end;
Result := Integer(AMQP_STATUS_OK);
end;
function amqp_time_ms_until( Atime : Tamqp_time):integer;
var
now_ns,
delta_ns : uint64;
left_ms : integer;
begin
if UINT64_MAX = Atime.time_point_ns then
begin
Exit(-1);
end;
if 0 = Atime.time_point_ns then
begin
Exit(0);
end;
now_ns := amqp_get_monotonic_timestamp();
if 0 = now_ns then
begin
Exit(Integer(AMQP_STATUS_TIMER_FAILURE));
end;
if now_ns >= Atime.time_point_ns then
begin
Exit(0);
end;
delta_ns := Atime.time_point_ns - now_ns;
left_ms := delta_ns div AMQP_NS_PER_MS;
Result := left_ms;
end;
function amqp_time_tv_until( Atime : Tamqp_time; Ain: Ptimeval; Aout: PPtimeval):integer;
var
now_ns,
delta_ns : uint64;
begin
assert(Ain <> nil);
if UINT64_MAX = Atime.time_point_ns then
begin
Aout^ := nil;
Exit(Integer(AMQP_STATUS_OK));
end;
if 0 = Atime.time_point_ns then
begin
Ain.tv_sec := 0;
Ain.tv_usec := 0;
Aout^ := Ain;
Exit(Integer(AMQP_STATUS_OK));
end;
now_ns := amqp_get_monotonic_timestamp();
if 0 = now_ns then
begin
Exit(Integer(AMQP_STATUS_TIMER_FAILURE));
end;
if now_ns >= Atime.time_point_ns then
begin
Ain.tv_sec := 0;
Ain.tv_usec := 0;
Aout^ := Ain;
Exit(Integer(AMQP_STATUS_OK));
end;
delta_ns := Atime.time_point_ns - now_ns;
Ain.tv_sec := delta_ns div AMQP_NS_PER_S;
Ain.tv_usec :=(delta_ns mod AMQP_NS_PER_S) div AMQP_NS_PER_US;
Aout^ := Ain;
Result := Integer(AMQP_STATUS_OK);
end;
function amqp_time_has_past( Atime : Tamqp_time):integer;
var
now_ns : uint64;
begin
if UINT64_MAX = Atime.time_point_ns then
begin
Exit(Integer(AMQP_STATUS_OK));
end;
now_ns := amqp_get_monotonic_timestamp();
if 0 = now_ns then
begin
Exit(Integer(AMQP_STATUS_TIMER_FAILURE));
end;
if now_ns > Atime.time_point_ns then
begin
Exit(Integer(AMQP_STATUS_TIMEOUT));
end;
Result := Integer(AMQP_STATUS_OK);
end;
function amqp_time_first( l, r : Tamqp_time):Tamqp_time;
begin
if l.time_point_ns < r.time_point_ns then
Exit(l);
Result := r;
end;
initialization
NS_PER_COUNT := 0;
end.
|
unit Main;
interface //####################################################################
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
System.Math.Vectors,
FMX.Types3D, FMX.Objects3D, FMX.Controls.Presentation,
FMX.ScrollBox, FMX.Memo, FMX.Controls3D, FMX.Viewport3D, FMX.TabControl,
LUX, LUX.D3, LUX.FMX, LUX.FMX.Context.DX11,
LIB.Material;
type
TForm1 = class(TForm)
TabControl1: TTabControl;
TabItemV: TTabItem;
Viewport3D1: TViewport3D;
Dummy1: TDummy;
Dummy2: TDummy;
Camera1: TCamera;
Light1: TLight;
Grid3D1: TGrid3D;
StrokeCube1: TStrokeCube;
TabItemS: TTabItem;
TabControlS: TTabControl;
TabItemSV: TTabItem;
TabControlSV: TTabControl;
TabItemSVC: TTabItem;
MemoSVC: TMemo;
TabItemSVE: TTabItem;
MemoSVE: TMemo;
TabItemSP: TTabItem;
TabControlSP: TTabControl;
TabItemSPC: TTabItem;
MemoSPC: TMemo;
TabItemSPE: TTabItem;
MemoSPE: TMemo;
procedure FormCreate(Sender: TObject);
procedure Viewport3D1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
procedure Viewport3D1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single);
procedure Viewport3D1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
private
{ private 宣言 }
_MouseS :TShiftState;
_MouseP :TPointF;
///// メソッド
function VoxToPos( const V_:TSingle3D ) :TSingle3D;
function PosToVox( const P_:TSingle3D ) :TSingle3D;
public
{ public 宣言 }
_VolumeCube :TVolumeCube;
///// メソッド
procedure DrawSphere( const Center_:TSingle3D; const Radius_:Single; const Color_:TAlphaColorF );
procedure MakeTexture3D;
end;
var
Form1: TForm1;
implementation //###############################################################
{$R *.fmx}
uses System.Math,
LUX.FMX.Types3D;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
/////////////////////////////////////////////////////////////////////// メソッド
function TForm1.VoxToPos( const V_:TSingle3D ) :TSingle3D;
begin
with _VolumeCube.Material.Texture3D do
begin
Result.X := V_.X / Width ;
Result.Y := V_.Y / Height;
Result.Z := V_.Z / Depth ;
end;
end;
function TForm1.PosToVox( const P_:TSingle3D ) :TSingle3D;
begin
with _VolumeCube.Material.Texture3D do
begin
Result.X := P_.X * Width ;
Result.Y := P_.Y * Height;
Result.Z := P_.Z * Depth ;
end;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
/////////////////////////////////////////////////////////////////////// メソッド
procedure TForm1.DrawSphere( const Center_:TSingle3D; const Radius_:Single; const Color_:TAlphaColorF );
var
P0, P1, V0, V1, V, P :TSingle3D;
X0, X1, X,
Y0, Y1, Y,
Z0, Z1, Z :Integer;
begin
P0.X := Center_.X - Radius_; P1.X := Center_.X + Radius_;
P0.Y := Center_.Y - Radius_; P1.Y := Center_.Y + Radius_;
P0.Z := Center_.Z - Radius_; P1.Z := Center_.Z + Radius_;
V0 := PosToVox( P0 );
V1 := PosToVox( P1 );
with _VolumeCube.Material.Texture3D do
begin
X0 := Max( 0, Floor( V0.X ) ); X1 := Min( Ceil( V1.X ), Width -1 );
Y0 := Max( 0, Floor( V0.Y ) ); Y1 := Min( Ceil( V1.Y ), Height-1 );
Z0 := Max( 0, Floor( V0.Z ) ); Z1 := Min( Ceil( V1.Z ), Depth -1 );
for Z := Z0 to Z1 do
begin
V.Z := Z + 0.5;
for Y := Y0 to Y1 do
begin
V.Y := Y + 0.5;
for X := X0 to X1 do
begin
V.X := X + 0.5;
P := VoxToPos( V );
if Distance( Center_, P ) < Radius_ then Pixels[ X, Y, Z ] := Color_;
end;
end;
end;
end;
end;
procedure TForm1.MakeTexture3D;
var
N, I :Integer;
P :TSingle3D;
R :Single;
C :TAlphaColorF;
begin
N := 512;
with _VolumeCube.Material.Texture3D do
begin
Width := 64;
Height := 64;
Depth := 64;
for I := 1 to N do
begin
P := TSingle3D.Create( Random, Random, Random );
R := Roo2( 2 ) / Roo3( N ) * Pow2( Random );
C := TAlphaColorF.Create( Random( 5 ) / 4,
Random( 5 ) / 4,
Random( 5 ) / 4,
Random( 5 ) / 4 );
DrawSphere( P, R, C );
end;
UpdateTexture;
end;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
procedure TForm1.FormCreate(Sender: TObject);
var
T :String;
begin
Assert( Viewport3D1.Context.ClassName = 'TLuxDX11Context', 'TLuxDX11Context class is not applied!' );
//////////
MemoSVC.Lines.LoadFromFile( '..\..\_DATA\ShaderV.hlsl' );
MemoSPC.Lines.LoadFromFile( '..\..\_DATA\ShaderP.hlsl' );
_VolumeCube := TVolumeCube.Create( Viewport3D1 );
with _VolumeCube do
begin
Parent := Viewport3D1;
Width := 10;
Height := 10;
Depth := 10;
with Material do
begin
with ShaderV do
begin
Source.Text := MemoSVC.Text;
for T in Errors.Keys do
begin
with MemoSVE.Lines do
begin
Add( '▼ ' + T );
Add( Errors[ T ] );
end;
end;
end;
with ShaderP do
begin
Source.Text := MemoSPC.Text;
for T in Errors.Keys do
begin
with MemoSPE.Lines do
begin
Add( '▼ ' + T );
Add( Errors[ T ] );
end;
end;
end;
end;
end;
MakeTexture3D;
end;
//------------------------------------------------------------------------------
procedure TForm1.Viewport3D1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
_MouseS := Shift;
_MouseP := TPointF.Create( X, Y );
end;
procedure TForm1.Viewport3D1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single);
var
P :TPointF;
begin
if ssLeft in _MouseS then
begin
P := TPointF.Create( X, Y );
with Dummy1.RotationAngle do Y := Y + ( P.X - _MouseP.X ) / 2;
with Dummy2.RotationAngle do X := X - ( P.Y - _MouseP.Y ) / 2;
_MouseP := P;
end;
end;
procedure TForm1.Viewport3D1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
Viewport3D1MouseMove( Sender, Shift, X, Y );
_MouseS := [];
end;
end. //#########################################################################
|
unit View.Usuario;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, View.BaseGrid, DB, ActnList, ImgList, ComCtrls, StdCtrls,
Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, ExtCtrls, Mask, JvExMask,
JvToolEdit, Model.Usuario.Entidade;
type
TfrmView_Usuario = class(TfrmBaseGrid)
GroupBox2: TGroupBox;
Label1: TLabel;
Label2: TLabel;
edtNOME: TEdit;
edtEMAIL: TEdit;
Label3: TLabel;
edtSENHA: TEdit;
Label4: TLabel;
edtLOGIN: TEdit;
rdgSTATUS: TRadioGroup;
edtDATA_NASCIMENTO: TJvDateEdit;
Label5: TLabel;
procedure FormShow(Sender: TObject);
procedure acSalvarExecute(Sender: TObject);
procedure acAlterarExecute(Sender: TObject);
procedure acVisualizarExecute(Sender: TObject);
procedure acNovoExecute(Sender: TObject);
procedure acExcluirExecute(Sender: TObject);
private
FId: Integer;
{ Private declarations }
procedure _BindObjetctToForm(AObject: TUSUARIO);
procedure _BindFormToObjetct(AObject: TUSUARIO);
procedure _ClearForm;
public
{ Public declarations }
end;
var
frmView_Usuario: TfrmBaseGrid;
implementation
{$R *.dfm}
procedure TfrmView_Usuario.FormShow(Sender: TObject);
begin
inherited;
FParent.USUARIOS.DAO.DataSource(DataSource1);
FParent.USUARIOS.DAO.Find;
end;
procedure TfrmView_Usuario.acSalvarExecute(Sender: TObject);
begin
case Status of
stEditar: begin
_BindFormToObjetct(FParent.USUARIOS.DAO._This);
FParent.USUARIOS.DAO.Update();
end;
stNovo: begin
_BindFormToObjetct(FParent.USUARIOS.DAO._This);
FParent.USUARIOS.DAO.Insert();
end;
stExcluir: begin
_BindFormToObjetct(FParent.USUARIOS.DAO._NewThis);
FParent.USUARIOS.DAO.Delete(FId);
end;
else
raise Exception.Create('Não é necessário salvar os dados');
end;
FParent.USUARIOS.DAO.Find();
inherited;
end;
procedure TfrmView_Usuario.acAlterarExecute(Sender: TObject);
begin
_BindObjetctToForm(FParent.USUARIOS.DAO._This);
inherited;
end;
procedure TfrmView_Usuario._BindObjetctToForm(AObject: TUSUARIO);
begin
FId := AObject.CODIGO;
edtNOME.Text := AObject.NOME;
edtLOGIN.Text := AObject.LOGIN;
edtSENHA.Text := AObject.SENHA;
rdgSTATUS.ItemIndex := AObject.STATUS;
edtEMAIL.Text := AObject.EMAIL;
edtDATA_NASCIMENTO.Date := AObject.DATA_NASCIMENTO;
end;
procedure TfrmView_Usuario.acVisualizarExecute(Sender: TObject);
begin
_BindObjetctToForm(FParent.USUARIOS.DAO._This);
inherited;
end;
procedure TfrmView_Usuario._BindFormToObjetct(AObject: TUSUARIO);
begin
AObject.CODIGO := FId;
AObject.NOME := edtNOME.Text;
AObject.LOGIN := edtLOGIN.Text;
AObject.SENHA := edtSENHA.Text;
AObject.STATUS := rdgSTATUS.ItemIndex;
AObject.EMAIL := edtEMAIL.Text;
AObject.DATA_NASCIMENTO := edtDATA_NASCIMENTO.Date;
end;
procedure TfrmView_Usuario._ClearForm;
begin
FId := -1;
edtNOME.Clear;
edtLOGIN.Clear;
edtSENHA.Clear;
rdgSTATUS.ItemIndex := 0;
edtEMAIL.Clear;
edtDATA_NASCIMENTO.Clear;
end;
procedure TfrmView_Usuario.acNovoExecute(Sender: TObject);
begin
_ClearForm;
inherited;
end;
procedure TfrmView_Usuario.acExcluirExecute(Sender: TObject);
begin
_BindObjetctToForm(FParent.USUARIOS.DAO._This);
inherited;
end;
end.
|
unit MovimentoDeContaCorrenteAplicacao;
interface
uses Classes,
{ Fluente }
DataUtil, UnModelo, Componentes, UnAplicacao,
UnMovimentoDeContaCorrenteListaRegistrosModelo,
UnMovimentoDeContaCorrenteListaRegistrosView,
UnMovimentoDeContaCorrenteRegistroView,
UnMovimentoDeContaCorrenteImpressaoView;
type
TMovimentoDeContaCorrenteAplicacao = class(TAplicacao, IResposta)
private
FMovimentoDeContaCorrenteListaRegistrosView: ITela;
public
function AtivarAplicacao: TAplicacao; override;
procedure Responder(const Chamada: TChamada);
function Descarregar: TAplicacao; override;
function Preparar(const ConfiguracaoAplicacao: TConfiguracaoAplicacao = nil):
TAplicacao; override;
end;
implementation
{ TMovimentoDeContaCorrenteAplicacao }
function TMovimentoDeContaCorrenteAplicacao.AtivarAplicacao: TAplicacao;
begin
Self.FMovimentoDeContaCorrenteListaRegistrosView :=
TMovimentoDeContaCorrenteListaRegistrosView.Create(nil)
.Modelo(Self.FFabricaDeModelos
.ObterModelo('MovimentoDeContaCorrenteListaRegistrosModelo'))
.Controlador(Self)
.Preparar;
Self.FMovimentoDeContaCorrenteListaRegistrosView.ExibirTela;
Result := Self;
end;
function TMovimentoDeContaCorrenteAplicacao.Descarregar: TAplicacao;
begin
Result := Self;
end;
function TMovimentoDeContaCorrenteAplicacao.Preparar(
const ConfiguracaoAplicacao: TConfiguracaoAplicacao = nil): TAplicacao;
begin
Result := Self;
end;
procedure TMovimentoDeContaCorrenteAplicacao.Responder(const Chamada: TChamada);
var
_OidRegistro: string;
_acao: AcaoDeRegistro;
_modelo: TModelo;
_registroView: ITela;
begin
_modelo := Self.FFabricaDeModelos
.ObterModelo('MovimentoDeContaCorrenteRegistroModelo');
_acao := RetornarAcaoDeRegistro(
Chamada.ObterParametros.Ler('acao').ComoInteiro);
if _acao in [adrIncluir, adrCarregar] then
begin
if _acao = adrIncluir then
_modelo.Incluir
else
begin
_OidRegistro := Chamada.ObterParametros.Ler('oid').ComoTexto;
_modelo.CarregarPor(
Criterio.Campo('ccormv_oid').igual(_OidRegistro).obter);
end;
_registroView := TMovimentoDeContaCorrenteRegistroView.Create(nil)
.Modelo(_modelo)
.Controlador(Self)
.Preparar;
try
_registroView.ExibirTela;
finally
_registroView.Descarregar;
end;
end
else
if _acao = adrOutra then
begin
_modelo := (Chamada.ObterParametros.Ler('modelo').ComoObjeto
as TModelo);
_registroView := TMovimentoDeContaCorrenteImpressaoView.Create(nil)
.Controlador(Self)
.Modelo(_modelo)
.Preparar;
try
_registroView.ExibirTela;
finally
_registroView.Descarregar;
end;
end
end;
initialization
RegisterClass(TMovimentoDeContaCorrenteAplicacao);
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
//GLS
GLScene, GLTeapot, GLObjects, GLWin32Viewer,
GLVectorGeometry, GLTexture, GLCadencer, GLImposter, GLSkydome,
GLCrossPlatform, GLCoordinates, GLBaseClasses, GLRenderContextInfo;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLCamera1: TGLCamera;
GLTeapot1: TGLTeapot;
GLLightSource1: TGLLightSource;
GLDirectOpenGL1: TGLDirectOpenGL;
GLCadencer1: TGLCadencer;
Timer1: TTimer;
GLSkyDome1: TGLSkyDome;
GLDummyCube1: TGLDummyCube;
Panel1: TPanel;
LabelTexSize: TLabel;
CBShowTeapot: TCheckBox;
CBShowImposter: TCheckBox;
CBSampleSize: TComboBox;
Label2: TLabel;
LabelFPS: TLabel;
procedure GLDirectOpenGL1Render(Sender: TObject;
var rci: TRenderContextInfo);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure CBSampleSizeChange(Sender: TObject);
procedure CBShowImposterClick(Sender: TObject);
procedure CBShowTeapotClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
impBuilder : TGLStaticImposterBuilder;
renderPoint : TGLRenderPoint;
mx, my : Integer;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
//var
// x, y : Integer;
begin
renderPoint:=TGLRenderPoint(GLDummyCube1.AddNewChild(TGLRenderPoint));
impBuilder:=TGLStaticImposterBuilder.Create(Self);
impBuilder.SampleSize:=64;
impBuilder.SamplingRatioBias:=1.3;
impBuilder.Coronas.Items[0].Samples:=32;
impBuilder.Coronas.Add(15, 24);
impBuilder.Coronas.Add(30, 24);
impBuilder.Coronas.Add(45, 16);
impBuilder.Coronas.Add(60, 16);
impBuilder.Coronas.Add(85, 16);
impBuilder.RenderPoint:=renderPoint;
impBuilder.RequestImposterFor(GLTeapot1);
end;
procedure TForm1.GLDirectOpenGL1Render(Sender: TObject;
var rci: TRenderContextInfo);
var
camPos, pos : TVector;
imp : TImposter;
x, y : Integer;
begin
imp:=impBuilder.ImposterFor(GLTeapot1);
if (imp=nil) or (imp.Texture.Handle=0) then Exit;
imp.BeginRender(rci);
for x:=-30 to 30 do for y:=-30 to 30 do begin
MakePoint(pos, x*5, 0, y*4);
camPos:=VectorSubtract(rci.cameraPosition, pos);
imp.Render(rci, pos, camPos, 1);
end;
imp.EndRender(rci);
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
GLSceneViewer1.Invalidate;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
LabelFPS.Caption:=GLSceneViewer1.FramesPerSecondText;
if CBShowImposter.Checked then
LabelFPS.Caption:=LabelFPS.Caption+' - 3721 imposters';
GLSceneViewer1.ResetPerformanceMonitor;
LabelTexSize.Caption:=Format('%d x %d - %.1f%%',
[impBuilder.TextureSize.X, impBuilder.TextureSize.Y,
impBuilder.TextureFillRatio*100]);
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if ssLeft in Shift then begin
GLCamera1.MoveAroundTarget(my-y, mx-x);
end;
mx:=x; my:=y;
end;
procedure TForm1.CBSampleSizeChange(Sender: TObject);
var
s : Integer;
begin
s:=StrToInt(CBSampleSize.Text);
if (GLSceneViewer1.Width>=s) and (GLSceneViewer1.Height>=s) then
impBuilder.SampleSize:=s
else begin
ShowMessage('Viewer is too small to allow rendering the imposter samples');
end;
end;
procedure TForm1.CBShowImposterClick(Sender: TObject);
begin
GLDirectOpenGL1.Visible:=CBShowImposter.Checked;
end;
procedure TForm1.CBShowTeapotClick(Sender: TObject);
begin
GLTeapot1.Visible:=CBShowTeapot.Checked;
end;
end.
|
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2013-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit uWait;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes,
System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs,
FMX.StdCtrls, FMX.Objects, FMX.Controls.Presentation;
type
/// <summary>
/// TWait is a simple TForm based that can be used to visualize, that the application is currently busy executing
/// some code.
/// </summary>
/// <remarks>
/// TWait implements a singleton pattern.
/// </remarks>
/// <example>
/// TWait.Start;<br />try<br /> // do your time consuming stuff here<br />finally<br /> TWait.Done;<br />end;
/// </example>
TWait = class(TForm)
LabelStatus: TLabel;
Image1: TImage;
private
class var
FInstance: TWait;
FWaitEnabled: Integer;
class function Instance: TWait; static;
class function WaitEnabled: Boolean; static;
class constructor Create;
public
/// <summary>
/// Call Start to bring up the Wait form on top and centered above your main form.
/// </summary>
/// <param name="AMessage">
/// <para>
/// An optional short message to present to the user. Default is "Working ..."
/// </para>
/// <para>
/// Can be called multiple times, to update its message.
/// </para>
/// <para>
/// Calls Application.ProcessMessages
/// </para>
/// </param>
class procedure Start(const AMessage: string = '');
/// <summary>
/// Call Done to close the Wait form. If there is currently no Wait form, then this call will just be ignored.
/// </summary>
class procedure Done;
end;
implementation
{$R *.fmx}
class constructor TWait.Create;
begin
FWaitEnabled := -1;
end;
class function TWait.WaitEnabled: Boolean;
begin
if FWaitEnabled < 0 then
if not FindCmdLineSwitch('nw') and (DebugHook = 0) then
FWaitEnabled := 1
else
FWaitEnabled := 0;
Result := FWaitEnabled = 1;
end;
// Simplistic Singleton/Lazyloader
class procedure TWait.Done;
begin
if not WaitEnabled then
Exit;
if assigned(FInstance) then
begin
FInstance.Release;
FInstance := nil;
end;
end;
class function TWait.Instance: TWait;
begin
if not assigned(FInstance) then begin
FInstance := TWait.create(Application.MainForm);
//center manually, as poOwnerFormCenter appears to be broken in XE4
FInstance.Top := Application.MainForm.Top + Trunc(Application.MainForm.Height / 2 ) - Trunc(FInstance.Height /2);
FInstance.Left := Application.MainForm.Left + Trunc(Application.MainForm.Width / 2 ) - Trunc(FInstance.Width /2);
end;
Result := FInstance;
end;
class procedure TWait.Start(const AMessage: string = '');
begin
if not WaitEnabled then
Exit;
if AMessage <> '' then
Instance.LabelStatus.Text := AMessage;
Instance.Show;
Application.ProcessMessages;
end;
end.
|
unit ColorGridImpl1;
interface
uses
Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls,
ComServ, StdVCL, AXCtrls, DelCtrls_TLB, ColorGrd;
type
TColorGridX = class(TActiveXControl, IColorGridX)
private
{ Private declarations }
FDelphiControl: TColorGrid;
FEvents: IColorGridXEvents;
procedure ChangeEvent(Sender: TObject);
procedure ClickEvent(Sender: TObject);
procedure KeyPressEvent(Sender: TObject; var Key: Char);
protected
{ Protected declarations }
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure InitializeControl; override;
function ClassNameIs(const Name: WideString): WordBool; safecall;
function ColorToIndex(AColor: OLE_COLOR): Integer; safecall;
function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall;
function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall;
function Get_BackgroundColor: OLE_COLOR; safecall;
function Get_BackgroundEnabled: WordBool; safecall;
function Get_BackgroundIndex: Integer; safecall;
function Get_BiDiMode: TxBiDiMode; safecall;
function Get_ClickEnablesColor: WordBool; safecall;
function Get_Ctl3D: WordBool; safecall;
function Get_Cursor: Smallint; safecall;
function Get_DoubleBuffered: WordBool; safecall;
function Get_DragCursor: Smallint; safecall;
function Get_DragMode: TxDragMode; safecall;
function Get_Enabled: WordBool; safecall;
function Get_Font: IFontDisp; safecall;
function Get_ForegroundColor: OLE_COLOR; safecall;
function Get_ForegroundEnabled: WordBool; safecall;
function Get_ForegroundIndex: Integer; safecall;
function Get_GridOrdering: TxGridOrdering; safecall;
function Get_ParentCtl3D: WordBool; safecall;
function Get_ParentFont: WordBool; safecall;
function Get_Selection: Integer; safecall;
function Get_Visible: WordBool; safecall;
function GetControlsAlignment: TxAlignment; safecall;
function IsRightToLeft: WordBool; safecall;
function UseRightToLeftAlignment: WordBool; safecall;
function UseRightToLeftReading: WordBool; safecall;
function UseRightToLeftScrollBar: WordBool; safecall;
procedure _Set_Font(const Value: IFontDisp); safecall;
procedure AboutBox; safecall;
procedure FlipChildren(AllLevels: WordBool); safecall;
procedure InitiateAction; safecall;
procedure Set_BackgroundEnabled(Value: WordBool); safecall;
procedure Set_BackgroundIndex(Value: Integer); safecall;
procedure Set_BiDiMode(Value: TxBiDiMode); safecall;
procedure Set_ClickEnablesColor(Value: WordBool); safecall;
procedure Set_Ctl3D(Value: WordBool); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_DoubleBuffered(Value: WordBool); safecall;
procedure Set_DragCursor(Value: Smallint); safecall;
procedure Set_DragMode(Value: TxDragMode); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_Font(const Value: IFontDisp); safecall;
procedure Set_ForegroundEnabled(Value: WordBool); safecall;
procedure Set_ForegroundIndex(Value: Integer); safecall;
procedure Set_GridOrdering(Value: TxGridOrdering); safecall;
procedure Set_ParentCtl3D(Value: WordBool); safecall;
procedure Set_ParentFont(Value: WordBool); safecall;
procedure Set_Selection(Value: Integer); safecall;
procedure Set_Visible(Value: WordBool); safecall;
end;
implementation
uses ComObj, About6;
{ TColorGridX }
procedure TColorGridX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling
DefinePropertyPage with the class id of the page. For example,
DefinePropertyPage(Class_ColorGridXPage); }
end;
procedure TColorGridX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as IColorGridXEvents;
end;
procedure TColorGridX.InitializeControl;
begin
FDelphiControl := Control as TColorGrid;
FDelphiControl.OnChange := ChangeEvent;
FDelphiControl.OnClick := ClickEvent;
FDelphiControl.OnKeyPress := KeyPressEvent;
end;
function TColorGridX.ClassNameIs(const Name: WideString): WordBool;
begin
Result := FDelphiControl.ClassNameIs(Name);
end;
function TColorGridX.ColorToIndex(AColor: OLE_COLOR): Integer;
begin
end;
function TColorGridX.DrawTextBiDiModeFlags(Flags: Integer): Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlags(Flags);
end;
function TColorGridX.DrawTextBiDiModeFlagsReadingOnly: Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly;
end;
function TColorGridX.Get_BackgroundColor: OLE_COLOR;
begin
Result := OLE_COLOR(FDelphiControl.BackgroundColor);
end;
function TColorGridX.Get_BackgroundEnabled: WordBool;
begin
Result := FDelphiControl.BackgroundEnabled;
end;
function TColorGridX.Get_BackgroundIndex: Integer;
begin
Result := FDelphiControl.BackgroundIndex;
end;
function TColorGridX.Get_BiDiMode: TxBiDiMode;
begin
Result := Ord(FDelphiControl.BiDiMode);
end;
function TColorGridX.Get_ClickEnablesColor: WordBool;
begin
Result := FDelphiControl.ClickEnablesColor;
end;
function TColorGridX.Get_Ctl3D: WordBool;
begin
Result := FDelphiControl.Ctl3D;
end;
function TColorGridX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
function TColorGridX.Get_DoubleBuffered: WordBool;
begin
Result := FDelphiControl.DoubleBuffered;
end;
function TColorGridX.Get_DragCursor: Smallint;
begin
Result := Smallint(FDelphiControl.DragCursor);
end;
function TColorGridX.Get_DragMode: TxDragMode;
begin
Result := Ord(FDelphiControl.DragMode);
end;
function TColorGridX.Get_Enabled: WordBool;
begin
Result := FDelphiControl.Enabled;
end;
function TColorGridX.Get_Font: IFontDisp;
begin
GetOleFont(FDelphiControl.Font, Result);
end;
function TColorGridX.Get_ForegroundColor: OLE_COLOR;
begin
Result := OLE_COLOR(FDelphiControl.ForegroundColor);
end;
function TColorGridX.Get_ForegroundEnabled: WordBool;
begin
Result := FDelphiControl.ForegroundEnabled;
end;
function TColorGridX.Get_ForegroundIndex: Integer;
begin
Result := FDelphiControl.ForegroundIndex;
end;
function TColorGridX.Get_GridOrdering: TxGridOrdering;
begin
Result := Ord(FDelphiControl.GridOrdering);
end;
function TColorGridX.Get_ParentCtl3D: WordBool;
begin
Result := FDelphiControl.ParentCtl3D;
end;
function TColorGridX.Get_ParentFont: WordBool;
begin
Result := FDelphiControl.ParentFont;
end;
function TColorGridX.Get_Selection: Integer;
begin
Result := FDelphiControl.Selection;
end;
function TColorGridX.Get_Visible: WordBool;
begin
Result := FDelphiControl.Visible;
end;
function TColorGridX.GetControlsAlignment: TxAlignment;
begin
Result := TxAlignment(FDelphiControl.GetControlsAlignment);
end;
function TColorGridX.IsRightToLeft: WordBool;
begin
Result := FDelphiControl.IsRightToLeft;
end;
function TColorGridX.UseRightToLeftAlignment: WordBool;
begin
Result := FDelphiControl.UseRightToLeftAlignment;
end;
function TColorGridX.UseRightToLeftReading: WordBool;
begin
Result := FDelphiControl.UseRightToLeftReading;
end;
function TColorGridX.UseRightToLeftScrollBar: WordBool;
begin
Result := FDelphiControl.UseRightToLeftScrollBar;
end;
procedure TColorGridX._Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TColorGridX.AboutBox;
begin
ShowColorGridXAbout;
end;
procedure TColorGridX.FlipChildren(AllLevels: WordBool);
begin
FDelphiControl.FlipChildren(AllLevels);
end;
procedure TColorGridX.InitiateAction;
begin
FDelphiControl.InitiateAction;
end;
procedure TColorGridX.Set_BackgroundEnabled(Value: WordBool);
begin
FDelphiControl.BackgroundEnabled := Value;
end;
procedure TColorGridX.Set_BackgroundIndex(Value: Integer);
begin
FDelphiControl.BackgroundIndex := Value;
end;
procedure TColorGridX.Set_BiDiMode(Value: TxBiDiMode);
begin
FDelphiControl.BiDiMode := TBiDiMode(Value);
end;
procedure TColorGridX.Set_ClickEnablesColor(Value: WordBool);
begin
FDelphiControl.ClickEnablesColor := Value;
end;
procedure TColorGridX.Set_Ctl3D(Value: WordBool);
begin
FDelphiControl.Ctl3D := Value;
end;
procedure TColorGridX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
procedure TColorGridX.Set_DoubleBuffered(Value: WordBool);
begin
FDelphiControl.DoubleBuffered := Value;
end;
procedure TColorGridX.Set_DragCursor(Value: Smallint);
begin
FDelphiControl.DragCursor := TCursor(Value);
end;
procedure TColorGridX.Set_DragMode(Value: TxDragMode);
begin
FDelphiControl.DragMode := TDragMode(Value);
end;
procedure TColorGridX.Set_Enabled(Value: WordBool);
begin
FDelphiControl.Enabled := Value;
end;
procedure TColorGridX.Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TColorGridX.Set_ForegroundEnabled(Value: WordBool);
begin
FDelphiControl.ForegroundEnabled := Value;
end;
procedure TColorGridX.Set_ForegroundIndex(Value: Integer);
begin
FDelphiControl.ForegroundIndex := Value;
end;
procedure TColorGridX.Set_GridOrdering(Value: TxGridOrdering);
begin
FDelphiControl.GridOrdering := TGridOrdering(Value);
end;
procedure TColorGridX.Set_ParentCtl3D(Value: WordBool);
begin
FDelphiControl.ParentCtl3D := Value;
end;
procedure TColorGridX.Set_ParentFont(Value: WordBool);
begin
FDelphiControl.ParentFont := Value;
end;
procedure TColorGridX.Set_Selection(Value: Integer);
begin
FDelphiControl.Selection := Value;
end;
procedure TColorGridX.Set_Visible(Value: WordBool);
begin
FDelphiControl.Visible := Value;
end;
procedure TColorGridX.ChangeEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnChange;
end;
procedure TColorGridX.ClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnClick;
end;
procedure TColorGridX.KeyPressEvent(Sender: TObject; var Key: Char);
var
TempKey: Smallint;
begin
TempKey := Smallint(Key);
if FEvents <> nil then FEvents.OnKeyPress(TempKey);
Key := Char(TempKey);
end;
initialization
TActiveXControlFactory.Create(
ComServer,
TColorGridX,
TColorGrid,
Class_ColorGridX,
6,
'{695CDAFE-02E5-11D2-B20D-00C04FA368D4}',
0,
tmApartment);
end.
|
unit uRAMForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Buttons, ExtCtrls, Grids, uResourceStrings, uView, uProcessor,
StdCtrls, Menus, Registry, uMisc;
type
TRAMRefreshRequestEvent = procedure(Listener: IRAM) of object;
TRAMUpdateRequestEvent = procedure(Address: Word; Value: Byte) of object;
TRAMForm = class(TForm, ILanguage, IRadixView, IRAM, IRegistry)
sgRAM: TStringGrid;
pBottom: TPanel;
sbPage: TScrollBar;
LblPage: TLabel;
LblPageIndex: TLabel;
PopupMenu: TPopupMenu;
miClose: TMenuItem;
N1: TMenuItem;
miStayOnTop: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure sgRAMDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure sbPageChange(Sender: TObject);
procedure miCloseClick(Sender: TObject);
procedure miStayOnTopClick(Sender: TObject);
procedure sgRAMKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure sgRAMDblClick(Sender: TObject);
procedure sgRAMSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure FormCanResize(Sender: TObject; var NewWidth,
NewHeight: Integer; var Resize: Boolean);
private
_Block: Boolean;
_Width: Integer;
_Radix: TRadix;
_View: TView;
_ARow: Integer;
_ACol: Integer;
_OnRAMRefreshRequest: TRAMRefreshRequestEvent;
_OnRAMUpdateRequest: TRAMUpdateRequestEvent;
procedure RefreshObject(Sender: TObject);
procedure Reset(Sender: TObject);
procedure RAMUpdate(Sender: TObject; Address: Word; Value: Byte);
procedure LoadData(RegistryList: TRegistryList);
procedure SaveData(RegistryList: TRegistryList);
public
procedure LoadLanguage;
procedure RadixChange(Radix: TRadix; View: TView);
function Show(ATop: Integer): Integer; overload;
property OnRAMRefreshRequest: TRAMRefreshRequestEvent read _OnRAMRefreshRequest write _OnRAMRefreshRequest;
property OnRAMUpdateRequest: TRAMUpdateRequestEvent read _OnRAMUpdateRequest write _OnRAMUpdateRequest;
end;
var
RAMForm: TRAMForm;
implementation
uses uEditForm;
{$R *.dfm}
procedure TRAMForm.FormCreate(Sender: TObject);
begin
_Block:= true;
_Radix:= rOctal;
_View:= vShort;
sbPage.Position:= 0;
sgRAM.RowCount:= 257;
LblPageIndex.Caption:= IntToStr(sbPage.Position);
sgRAM.ColCount:= 2;
{ -one- RAM Page }
sgRAM.ColWidths[0]:= 100;
sgRAM.ColWidths[1]:= 100;
ClientWidth:= 220;
ClientHeight:= sgRAM.RowHeights[0] * 10 + pBottom.Height;
_Width:= Width;
_ARow:= -1;
_ACol:= -1;
LoadLanguage;
_Block:= false;
end;
procedure TRAMForm.FormCanResize(Sender: TObject; var NewWidth,
NewHeight: Integer; var Resize: Boolean);
begin
if not _Block then
NewWidth:= _Width;
end;
procedure TRAMForm.sgRAMDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
begin
if (ARow = 0) or (ACol = 0) then
sgRAM.Canvas.Brush.Color:= sgRAM.FixedColor
else
sgRAM.Canvas.Brush.Color:= sgRAM.Color;
sgRAM.Canvas.FillRect(Rect);
Rect.Top:= Rect.Top + ((sgRAM.RowHeights[ARow] -
sgRAM.Canvas.TextHeight(sgRAM.Cells[ACol,ARow]))) div 2;
if ARow = 0 then
Rect.Left:= Rect.Left + (sgRAM.ColWidths[ACol] -
sgRAM.Canvas.TextWidth(sgRAM.Cells[ACol,ARow])) div 2
else
Rect.Left:= Rect.Right - 4 - sgRAM.Canvas.TextWidth(sgRAM.Cells[ACol,ARow]);
sgRAM.Canvas.TextOut(Rect.Left,Rect.Top,sgRAM.Cells[ACol,ARow]);
end;
procedure TRAMForm.sbPageChange(Sender: TObject);
begin
LblPageIndex.Caption:= IntToStr(sbPage.Position);
if Assigned(OnRAMRefreshRequest) then
OnRAMRefreshRequest(Self);
end;
procedure TRAMForm.miCloseClick(Sender: TObject);
begin
Close;
end;
procedure TRAMForm.miStayOnTopClick(Sender: TObject);
begin
if miStayOnTop.Checked then
FormStyle:= fsNormal
else
FormStyle:= fsStayOnTop;
miStayOnTop.Checked:= not miStayOnTop.Checked;
end;
procedure TRAMForm.sgRAMSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
begin
_ARow:= ARow;
_ACol:= ACol;
end;
procedure TRAMForm.sgRAMDblClick(Sender: TObject);
var
C: Boolean;
P: TPoint;
begin
if (_ARow > 0) and (_ACol = 1) then
begin
P.X:= Mouse.CursorPos.X;
P.Y:= Mouse.CursorPos.Y;
EditForm.Value:= RadixToWord(sgRAM.Cells[_ACol,_ARow],_Radix,vLong,C);
if (EditForm.ShowModal(_Radix,vLong,8,P) = mrOk) and Assigned(OnRAMUpdateRequest) then
OnRAMUpdateRequest(sbPage.Position*256+(_ARow-1),EditForm.Value);
end;
end;
procedure TRAMForm.sgRAMKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
sgRAMDblClick(Sender);
end;
procedure TRAMForm.RefreshObject(Sender: TObject);
var
i, iOffset: Integer;
begin
if Sender is Ti8008RAM then
begin
iOffset:= sbPage.Position shl 8;
iOffset:= iOffset - 1;
for i:= 1 to sgRAM.RowCount do
begin
if _Radix = rDecimalNeg then sgRAM.Cells[0,i]:= WordToRadix(i+iOffset,rDecimal,_View,14)
else sgRAM.Cells[0,i]:= WordToRadix(i+iOffset,_Radix,_View,14);
sgRAM.Cells[1,i]:= WordToRadix((Sender as Ti8008RAM).RAM[i+iOffset],
_Radix,vLong,8);
end;
end;
sgRAM.Invalidate;
end;
procedure TRAMForm.Reset(Sender: TObject);
begin
if Assigned(OnRAMRefreshRequest) then
OnRAMRefreshRequest(Self);
end;
procedure TRAMForm.RAMUpdate(Sender: TObject; Address: Word; Value: Byte);
begin
// RAM - Page ('High')
if (Address shr 8) = sbPage.Position then
begin
// 'Low'
Address:= Address and 255;
sgRAM.Cells[1,Address+1]:= WordToRadix(Value,_Radix,vLong,8);
end;
end;
procedure TRAMForm.LoadData(RegistryList: TRegistryList);
begin
if RegistryList.Registry.OpenKey(APPLICATION_MAIN_KEY,false) then
RegistryList.LoadFormSettings(Self,true)
end;
procedure TRAMForm.SaveData(RegistryList: TRegistryList);
begin
if RegistryList.Registry.OpenKey(APPLICATION_MAIN_KEY,true) then
RegistryList.SaveFormSettings(Self,true);
end;
procedure TRAMForm.LoadLanguage;
begin
sgRAM.Cells[0,0]:= getString(rsAddress);
sgRAM.Cells[1,0]:= getString(rsValue);
LblPage.Caption:= getString(rsPage);
miClose.Caption:= getString(rsClose);
miStayOnTop.Caption:= getString(rsStayOnTop);
end;
procedure TRAMForm.RadixChange(Radix: TRadix; View: TView);
begin
_Radix:= Radix;
_View:= View;
end;
function TRAMForm.Show(ATop: Integer): Integer;
begin
Top:= ATop;
Left:= 0;
Show;
result:= Width;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ Copyright(c) 2012-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXSqliteMetaDataReader;
interface
uses
Data.DbxCommon, Data.DBXCommonTable, Data.DBXMetaDataReader, Data.DBXPlatform;
type
TDBXSqliteCustomMetaDataReader = class(TDBXBaseMetaDataReader)
protected
function GetDataTypeDescriptions: TDBXDataTypeDescriptionArray; override;
function GetProductName: string; override;
function GetReservedWords: TDBXStringArray; override;
function GetSqlForIndexes: string; override;
function GetSqlForTables: string; override;
function GetSqlForViews: string; override;
function IsLowerCaseIdentifiersSupported: Boolean; override;
function IsNestedTransactionsSupported: Boolean; override;
public
function FetchCatalogs: TDBXTable; override;
function FetchColumnConstraints(const Catalog: string; const Schema: string; const Table: string): TDBXTable; override;
function FetchColumns(const Catalog: string; const Schema: string; const Table: string): TDBXTable; override;
function FetchForeignKeyColumns(const Catalog: string; const Schema: string; const Table: string; const ForeignKeyName: string; const PrimaryCatalog: string; const PrimarySchema: string; const PrimaryTable: string; const PrimaryKeyName: string): TDBXTable; override;
function FetchForeignKeys(const Catalog: string; const Schema: string; const Table: string): TDBXTable; override;
function FetchIndexColumns(const Catalog: string; const Schema: string; const Table: string; const Index: string): TDBXTable; override;
function FetchPackageProcedureParameters(const Catalog: string; const Schema: string; const PackageName: string; const ProcedureName: string; const ParameterName: string): TDBXTable; override;
function FetchPackageProcedures(const Catalog: string; const Schema: string; const PackageName: string; const ProcedureName: string; const ProcedureType: string): TDBXTable; override;
function FetchPackages(const Catalog: string; const Schema: string; const PackageName: string): TDBXTable; override;
function FetchPackageSources(const Catalog: string; const Schema: string; const PackageName: string): TDBXTable; override;
function FetchProcedureParameters(const Catalog: string; const Schema: string; const Proc: string; const Parameter: string): TDBXTable; override;
function FetchProcedures(const Catalog: string; const Schema: string; const ProcedureName: string; const ProcedureType: string): TDBXTable; override;
function FetchProcedureSources(const Catalog: string; const Schema: string; const Proc: string): TDBXTable; override;
function FetchRoles: TDBXTable; override;
function FetchSchemas(const Catalog: string): TDBXTable; override;
function FetchSynonyms(const Catalog: string; const Schema: string; const Synonym: string): TDBXTable; override;
function FetchUsers: TDBXTable; override;
end;
TDBXSqliteMetaDataReader = class(TDBXSqliteCustomMetaDataReader)
end;
TDBXSqliteColumnsTableCursor = class(TDBXColumnsTableCursor)
private
FDataTypesRow: TDBXSingleValueRow;
protected
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
public
constructor Create(const Reader: TDBXBaseMetaDataReader; const CheckBase: Boolean; const Cursor: TDBXTable);
destructor Destroy; override;
function Next: Boolean; override;
end;
implementation
uses
Data.DbxCommonResStrs, Data.DBXDBReaders, Data.DBXMetaDataCommandFactory,
Data.DbxMetaDataNames, Data.DbxSqlite, Data.DBXSqlScanner, System.Sqlite, System.SysUtils;
const
RefIndex = 20;
ForeignIndex = 21;
OnIndex = 22;
CollateIndex = 23;
AscIndex = 24;
DescIndex = 25;
IndexToken = 26;
TableToken = 27;
PrimaryToken = 28;
ConstraintToken = 29;
function TDBXSqliteCustomMetaDataReader.GetDataTypeDescriptions: TDBXDataTypeDescriptionArray;
var
Types: TDBXDataTypeDescriptionArray;
begin
SetLength(Types, 4);
Types[0] := TDBXDataTypeDescription.Create('INTEGER', TDBXDataTypes.Int64Type, 10, 'INTEGER', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[1] := TDBXDataTypeDescription.Create('REAL', TDBXDataTypes.DoubleType, 53, 'REAL', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[2] := TDBXDataTypeDescription.Create('TEXT', TDBXDataTypes.BlobType, 2147483647, 'TEXT', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.LongOption or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.Unicode or TDBXTypeFlag.StringOption);
Types[3] := TDBXDataTypeDescription.Create('BLOB', TDBXDataTypes.BlobType, 2147483647, 'BLOB', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.SearchableWithLike);
Result := Types;
end;
function TDBXSqliteCustomMetaDataReader.GetProductName: string;
begin
Result := 'Sqlite';
end;
function TDBXSqliteCustomMetaDataReader.GetReservedWords: TDBXStringArray;
var
Words: TDBXStringArray;
begin
SetLength(Words, 121);
Words[0] := 'ABORT';
Words[1] := 'ACTION';
Words[2] := 'ADD';
Words[3] := 'AFTER';
Words[4] := 'ALL';
Words[5] := 'ALTER';
Words[6] := 'ANALYZE';
Words[7] := 'AND';
Words[8] := 'AS';
Words[9] := 'ASC';
Words[10] := 'ATTACH';
Words[11] := 'AUTOINCREMENT';
Words[12] := 'BEFORE';
Words[13] := 'BEGIN';
Words[14] := 'BETWEEN';
Words[15] := 'BY';
Words[16] := 'CASCADE';
Words[17] := 'CASE';
Words[18] := 'CAST';
Words[19] := 'CHECK';
Words[20] := 'COLLATE';
Words[21] := 'COLUMN';
Words[22] := 'COMMIT';
Words[23] := 'CONFLICT';
Words[24] := 'CONSTRAINT';
Words[25] := 'CREATE';
Words[26] := 'CROSS';
Words[27] := 'CURRENT_DATE';
Words[28] := 'CURRENT_TIME';
Words[29] := 'CURRENT_TIMESTAMP';
Words[30] := 'DATABASE';
Words[31] := 'DEFAULT';
Words[32] := 'DEFERRABLE';
Words[33] := 'DEFERRED';
Words[34] := 'DELETE';
Words[35] := 'DESC';
Words[36] := 'DETACH';
Words[37] := 'DISTINCT';
Words[38] := 'DROP';
Words[39] := 'EACH';
Words[40] := 'ELSE';
Words[41] := 'END';
Words[42] := 'ESCAPE';
Words[43] := 'EXCEPT';
Words[44] := 'EXCLUSIVE';
Words[45] := 'EXISTS';
Words[46] := 'EXPLAIN';
Words[47] := 'FAIL';
Words[48] := 'FOR';
Words[49] := 'FOREIGN';
Words[50] := 'FROM';
Words[51] := 'FULL';
Words[52] := 'GLOB';
Words[53] := 'GROUP';
Words[54] := 'HAVING';
Words[55] := 'IF';
Words[56] := 'IGNORE';
Words[57] := 'IMMEDIATE';
Words[58] := 'IN';
Words[59] := 'INDEX';
Words[60] := 'INDEXED';
Words[61] := 'INITIALLY';
Words[62] := 'INNER';
Words[63] := 'INSERT';
Words[64] := 'INSTEAD';
Words[65] := 'INTERSECT';
Words[66] := 'INTO';
Words[67] := 'IS';
Words[68] := 'ISNULL';
Words[69] := 'JOIN';
Words[70] := 'KEY';
Words[71] := 'LEFT';
Words[72] := 'LIKE';
Words[73] := 'LIMIT';
Words[74] := 'MATCH';
Words[75] := 'NATURAL';
Words[76] := 'NO';
Words[77] := 'NOT';
Words[78] := 'NOTNULL';
Words[79] := 'NULL';
Words[80] := 'OF';
Words[81] := 'OFFSET';
Words[82] := 'ON';
Words[83] := 'OR';
Words[84] := 'ORDER';
Words[85] := 'OUTER';
Words[86] := 'PLAN';
Words[87] := 'PRAGMA';
Words[88] := 'PRIMARY';
Words[89] := 'QUERY';
Words[90] := 'RAISE';
Words[91] := 'REFERENCES';
Words[92] := 'REGEXP';
Words[93] := 'REINDEX';
Words[94] := 'RELEASE';
Words[95] := 'RENAME';
Words[96] := 'REPLACE';
Words[97] := 'RESTRICT';
Words[98] := 'RIGHT';
Words[99] := 'ROLLBACK';
Words[100] := 'ROW';
Words[101] := 'SAVEPOINT';
Words[102] := 'SELECT';
Words[103] := 'SET';
Words[104] := 'TABLE';
Words[105] := 'TEMP';
Words[106] := 'TEMPORARY';
Words[107] := 'THEN';
Words[108] := 'TO';
Words[109] := 'TRANSACTION';
Words[110] := 'TRIGGER';
Words[111] := 'UNION';
Words[112] := 'UNIQUE';
Words[113] := 'UPDATE';
Words[114] := 'USING';
Words[115] := 'VACUUM';
Words[116] := 'VALUES';
Words[117] := 'VIEW';
Words[118] := 'VIRTUAL';
Words[119] := 'WHEN';
Words[120] := 'WHERE';
Result := Words;
end;
function TDBXSqliteCustomMetaDataReader.GetSqlForIndexes: string;
begin
Result := 'select NULL, NULL, tbl_name, name, NULL, NULL, NULL from sqlite_master where type = ''index'' and (tbl_name = :TABLE_NAME OR (:TABLE_NAME IS NULL))';
end;
function TDBXSqliteCustomMetaDataReader.GetSqlForTables: string;
begin
Result := 'select NULL, NULL, name, NULL from sqlite_master where ((type = ''table'' and :TABLES = ''TABLE'') OR (type = ''view'' and :VIEWS = ''VIEW'')) and (name = :TABLE_NAME OR (:TABLE_NAME IS NULL))';
end;
function TDBXSqliteCustomMetaDataReader.GetSqlForViews: string;
begin
Result := 'select NULL, NULL, name, sql from sqlite_master where type = ''view'' and (name = :VIEW_NAME OR (:VIEW_NAME IS NULL))';
end;
function TDBXSqliteCustomMetaDataReader.IsLowerCaseIdentifiersSupported: Boolean;
begin
Result := True;
end;
function TDBXSqliteCustomMetaDataReader.IsNestedTransactionsSupported: Boolean;
begin
Result := True;
end;
function TDBXSqliteCustomMetaDataReader.FetchCatalogs: TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateCatalogsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Catalogs, Columns);
end;
function TDBXSqliteCustomMetaDataReader.FetchColumnConstraints(const Catalog: string; const Schema: string; const Table: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateColumnConstraintsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.ColumnConstraints, Columns);
end;
function TDBXSqliteCustomMetaDataReader.FetchColumns(const Catalog: string; const Schema: string; const Table: string): TDBXTable;
function GetPrecision(DataType: Integer; DataTypeName: string): Integer;
var
Pos1, Pos2: Integer;
begin
case DataType of
SQLITE_INTEGER: Result := SizeOf(Int64);
SQLITE_FLOAT: Result := SizeOf(Double);
SQLITE_BLOB: Result := 0;
SQLITE_TEXT:
begin
Pos1 := DataTypeName.IndexOf('(');
if Pos1 > -1 then
begin
Pos2 := DataTypeName.IndexOf(')');
Result := StrToInt(DataTypeName.Substring(Pos1+1, Pos2-Pos1-1));
end
else
Result := 1;
end
else
Result := 1;
end;
end;
function GetDbxDataType(DataType: Integer): Integer;
begin
case DataType of
SQLITE_INTEGER: Result := TDBXDataTypes.Int64Type;
SQLITE_FLOAT: Result := TDBXDataTypes.DoubleType;
else
Result := TDBXDataTypes.BlobType;
end;
end;
var
LConnection: TDBXSqliteConnection;
LCommand: TDBXSqliteCommand;
LReader: TDBXSqliteReader;
Columns, TableColumns: TDBXValueTypeArray;
ColType, I, NumCols: Integer;
MemTable: TDBXMemoryTable;
DBXContext: TDBXContext;
Cursor: TDBXTable;
DataTypePtrUni: MarshaledString;
ColumnName: string;
{$IF not (DEFINED(CPUARM) and DEFINED(IOS))}
DbName, TableName: string;
Autoinc, ErrorCode, NotNull, PrimaryKey: Integer;
CollationSeqPtr, DataTypePtr: MarshaledAString;
{$ENDIF not (CPUARM and IOS)}
begin
Result := nil;
Columns := TDBXMetaDataCollectionColumns.CreateColumnsColumns;
if Table = '' then
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Columns, Columns)
else
begin
if Assigned(Context) then
begin
LConnection := TDBXSqliteConnection(TDBXDataExpressProviderContext(Context).Connection);
if Assigned(LConnection) then
begin
DBXContext := TDBXContext.Create;
try
LCommand := TDBXSqliteCommand.Create(DBXContext, LConnection);
try
LCommand.Text := 'select * from ' + Table + ' LIMIT 1';
LReader := TDBXSqliteReader(LCommand.ExecuteQuery);
LReader.Next;
try
MemTable := TDBXMemoryTable.Create;
try
TableColumns := TDBXMetaDataCollectionColumns.CreateColumnsColumns;
MemTable.Columns := TableColumns;
NumCols := sqlite3_column_count(LCommand.StatementHandle);
MemTable.Insert; //Dummy Row
for I := 0 to NumCols - 1 do
begin
MemTable.Insert;
{$IF not (DEFINED(CPUARM) and DEFINED(IOS))}
if LConnection.GetVendorProperty('ColumnMetaDataSupported') = 'True' then
begin
DbName := sqlite3_column_database_name16(LCommand.StatementHandle, I);
TableName := sqlite3_column_table_name16(LCommand.StatementHandle, I);
ColumnName := sqlite3_column_origin_name16(LCommand.StatementHandle, I);
ColType := sqlite3_column_type(LCommand.StatementHandle, I);
ErrorCode := sqlite3_table_column_metadata(LConnection.ConnectionHandle,
MarshaledAString(Utf8Encode(DbName)),
MarshaledAString(Utf8Encode(TableName)),
MarshaledAString(Utf8Encode(ColumnName)),
DataTypePtr,
CollationSeqPtr,
NotNull,
PrimaryKey,
Autoinc);
CheckError(ErrorCode, LConnection.ConnectionHandle, DBXContext);
MemTable.Value[2].AsString := TableName;
MemTable.Value[3].AsString := ColumnName;
MemTable.Value[4].AsString := string(DataTypePtr);
MemTable.Value[5].AsInt32 := GetPrecision(ColType, string(DataTypePtr));
MemTable.Value[7].AsInt32 := I;
MemTable.Value[9].AsBoolean := NotNull = 0;
MemTable.Value[10].AsBoolean := Autoinc <> 0;
MemTable.Value[12].AsInt32 := GetDbxDataType(ColType);
end
else
{$ENDIF not (CPUARM and IOS)}
begin
ColumnName := sqlite3_column_name16(LCommand.StatementHandle, I);
DataTypePtrUni := sqlite3_column_decltype16(LCommand.StatementHandle, I);
ColType := sqlite3_column_type(LCommand.StatementHandle, I);
MemTable.Value[2].AsString := Table;
MemTable.Value[3].AsString := ColumnName;
MemTable.Value[4].AsString := DataTypePtrUni;
MemTable.Value[5].AsInt32 := GetPrecision(ColType, DataTypePtrUni);
MemTable.Value[7].AsInt32 := I;
MemTable.Value[9].AsBoolean := True;
MemTable.Value[10].AsBoolean := False;
MemTable.Value[12].AsInt32 := GetDbxDataType(ColType);
end;
end;
MemTable.First;
Cursor := TDBXStringTrimTable.CreateTrimTableIfNeeded(MemTable);
Cursor := TDBXCustomMetaDataTable.Create(GetContext, TDBXMetaDataCollectionName.Columns, Columns, Cursor);
Result := TDBXSqliteColumnsTableCursor.Create(Self, False, Cursor);
except
MemTable.Free;
raise;
end;
finally
LReader.Free;
end;
finally
LCommand.Free;
end;
finally
DBXContext.Free;
end;
end;
end;
end;
end;
function TDBXSqliteCustomMetaDataReader.FetchForeignKeyColumns(const Catalog: string; const Schema: string; const Table: string; const ForeignKeyName: string; const PrimaryCatalog: string; const PrimarySchema: string; const PrimaryTable: string; const PrimaryKeyName: string): TDBXTable;
procedure Scan(Scanner: TDBXSqlScanner; MemTable: TDBXMemoryTable);
var
FKNum, I, LookAheadToken, NumCols, SavedIndex, Token: Integer;
ColumnNames: array of string;
ParentTableName: string;
begin
Token := 0;
SavedIndex := 0;
FKNum := 1;
NumCols := 0;
while Token <> TDBXSqlScanner.TokenEos do
begin
Token := Scanner.NextToken;
if Token = RefIndex then
begin
MemTable.Insert;
MemTable.Value[2].AsString := Table;
MemTable.Value[3].AsString := 'FK' + IntToStr(FKNum);
Inc(FKNum);
Scanner.Init(Scanner.SqlQuery, SavedIndex);
Scanner.NextToken;
MemTable.Value[4].AsString := Scanner.Id;
Scanner.NextToken;
Scanner.NextToken;
MemTable.Value[7].AsString := Scanner.Id;
Scanner.NextToken;
Scanner.NextToken;
MemTable.Value[9].AsString := Scanner.Id;
end
else if Token = ForeignIndex then
begin
Scanner.NextToken;
Scanner.NextToken;
SavedIndex := Scanner.NextIndex;
Token := Scanner.NextToken;
//Get a count of columns in the composite key
while Token <> TDBXSqlScanner.TokenCloseParen do
begin
if Token <> TDBXSqlScanner.TokenComma then
Inc(NumCols);
Token := Scanner.NextToken;
end;
SetLength(ColumnNames, NumCols);
Scanner.Init(Scanner.SqlQuery, SavedIndex);
//Columns that make up foreign key
for I := 0 to NumCols - 1 do
begin
Scanner.NextToken;
ColumnNames[I] := Scanner.Id;
Scanner.NextToken;
end;
Scanner.NextToken;
Scanner.NextToken;
ParentTableName := Scanner.Id;
Scanner.NextToken;
for I := 0 to NumCols - 1 do
begin
MemTable.Insert;
MemTable.Value[2].AsString := Table;
MemTable.Value[3].AsString := 'FK' + IntToStr(FKNum);
MemTable.Value[4].AsString := ColumnNames[I];
MemTable.Value[7].AsString := ParentTableName;
Scanner.NextToken;
MemTable.Value[9].AsString := Scanner.Id;
Scanner.NextToken;
end;
Inc(FKNum);
NumCols := 0;
end;
LookAheadToken := Scanner.LookAtNextToken;
if LookAheadToken <> 20 then
SavedIndex := Scanner.NextIndex;
end;
end;
const
Ref = 'REFERENCES';
Foreign = 'FOREIGN';
var
Columns, TableColumns: TDBXValueTypeArray;
DBXContext: TDBXContext;
LConnection: TDBXSqliteConnection;
LCommand: TDBXSqliteCommand;
LReader: TDBXSqliteReader;
MemTable: TDBXMemoryTable;
Scanner: TDBXSqlScanner;
Cursor: TDBXTable;
begin
Result := nil;
Columns := TDBXMetaDataCollectionColumns.CreateForeignKeyColumnsColumns;
if Table = '' then
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.ForeignKeyColumns, Columns)
else
begin
if Assigned(Context) then
begin
LConnection := TDBXSqliteConnection(TDBXDataExpressProviderContext(Context).Connection);
if Assigned(LConnection) then
begin
DBXContext := TDBXContext.Create;
try
LCommand := TDBXSqliteCommand.Create(DBXContext, LConnection);
try
LCommand.Text := 'select sql from sqlite_master where name = ''' + Table + '''';
LReader := TDBXSqliteReader(LCommand.ExecuteQuery);
try
MemTable := TDBXMemoryTable.Create;
try
TableColumns := TDBXMetaDataCollectionColumns.CreateForeignKeyColumnsColumns;
MemTable.Columns := TableColumns;
Scanner := TDBXSqlScanner.Create(GetSqlIdentifierQuoteChar, GetSqlIdentifierQuotePrefix, GetSqlIdentifierQuoteSuffix);
try
Scanner.RegisterId(Ref, RefIndex);
Scanner.RegisterId(Foreign, ForeignIndex);
LReader.Next;
Scanner.Init(LReader.Value[0].AsString);
MemTable.Insert; //Dummy Row
Scan(Scanner, MemTable);
finally
Scanner.Free;
end;
MemTable.First;
Cursor := TDBXStringTrimTable.CreateTrimTableIfNeeded(MemTable);
Cursor := TDBXCustomMetaDataTable.Create(GetContext, TDBXMetaDataCollectionName.ForeignKeyColumns, Columns, Cursor);
Result := TDBXSqliteColumnsTableCursor.Create(Self, False, Cursor);
except
MemTable.Free;
raise;
end;
finally
LReader.Free;
end;
finally
LCommand.Free;
end;
finally
DBXContext.Free;
end;
end;
end;
end;
end;
function TDBXSqliteCustomMetaDataReader.FetchForeignKeys(const Catalog: string; const Schema: string; const Table: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateForeignKeysColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.ForeignKeys, Columns);
end;
function TDBXSqliteCustomMetaDataReader.FetchIndexColumns(const Catalog: string; const Schema: string; const Table: string; const Index: string): TDBXTable;
procedure Scan(Scanner: TDBXSqlScanner; MemTable: TDBXMemoryTable);
var
Token, Ordinal: Integer;
TableName, ColumnName, IndexName: string;
IsAscending, IsDescending: Boolean;
begin
Ordinal := 0;
Scanner.NextToken;
Token := Scanner.NextToken;
while Token <> TDBXSqlScanner.TokenEos do
begin
if Token = IndexToken then
begin
while Token <> OnIndex do
Token := Scanner.NextToken;
Scanner.NextToken;
TableName := Scanner.Id;
Token := Scanner.NextToken;
while (Token <> TDBXSqlScanner.TokenEos) and (Token <> TDBXSqlScanner.TokenCloseParen) do
begin
MemTable.Insert;
Scanner.NextToken;
MemTable.Value[2].AsString := TableName;
MemTable.Value[3].AsString := Table;
MemTable.Value[4].AsString := Scanner.Id;
MemTable.Value[5].AsInt32 := Ordinal;
Inc(Ordinal);
Token := Scanner.NextToken;
if Token = CollateIndex then
begin
Scanner.NextToken;
MemTable.Value[8].AsString := Scanner.Id;
Token := Scanner.NextToken;
end;
if Token = AscIndex then
begin
MemTable.Value[6].AsBoolean := True;
MemTable.Value[7].AsBoolean := False;
Token := Scanner.NextToken;
end
else if Token = DescIndex then
begin
MemTable.Value[6].AsBoolean := False;
MemTable.Value[7].AsBoolean := True;
Token := Scanner.NextToken;
end
else
begin
MemTable.Value[6].AsBoolean := False;
MemTable.Value[7].AsBoolean := False;
end;
end;
end
else if Token = TableToken then
begin
Token := Scanner.LookAtNextToken;
while Token <> TDBXSqlScanner.TokenOpenParen do
begin
Scanner.NextToken;
TableName := Scanner.Id;
Token := Scanner.LookAtNextToken;
end;
Token := Scanner.NextToken;
while (Token <> TDBXSqlScanner.TokenCloseParen) and (Token <> TDBXSqlScanner.TokenEos) do
begin
Scanner.NextToken;
ColumnName := Scanner.Id;
IndexName := '';
IsAscending := False;
IsDescending := False;
Token := Scanner.NextToken;
while (Token <> TDBXSqlScanner.TokenComma) and (Token <> TDBXSqlScanner.TokenCloseParen) and (Token <> TDBXSqlScanner.TokenEos) do
begin
if Token = ConstraintToken then
begin
Scanner.NextToken;
IndexName := Scanner.Id;
Token := Scanner.NextToken;
end
else if Token = PrimaryToken then
begin
Scanner.NextToken;
Token := Scanner.NextToken;
if Token = AscIndex then
IsAscending := True
else if Token = DescIndex then
IsDescending := True;
MemTable.Insert;
MemTable.Value[2].AsString := TableName;
MemTable.Value[3].AsString := IndexName;
MemTable.Value[4].AsString := ColumnName;
MemTable.Value[5].AsInt32 := Ordinal;
Inc(Ordinal);
MemTable.Value[6].AsBoolean := IsAscending;
MemTable.Value[7].AsBoolean := IsDescending;
end
else
Token := Scanner.NextToken;
end;
end;
end;
Token := Scanner.NextToken;
end;
end;
const
OnConst = 'ON';
Collate = 'COLLATE';
Asc = 'ASC';
Desc = 'DESC';
IndexConst = 'INDEX';
TableConst = 'TABLE';
PrimaryConst = 'PRIMARY';
ConstraintConst = 'CONSTRAINT';
var
Columns, TableColumns: TDBXValueTypeArray;
DBXContext: TDBXContext;
LConnection: TDBXSqliteConnection;
LCommand: TDBXSqliteCommand;
LReader: TDBXSqliteReader;
MemTable: TDBXMemoryTable;
I: Integer;
Scanner: TDBXSqlScanner;
Cursor: TDBXTable;
begin
Result := nil;
if Table = '' then
begin
Columns := TDBXMetaDataCollectionColumns.CreateIndexColumnsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.IndexColumns, Columns);
end
else
begin
if Assigned(Context) then
begin
LConnection := TDBXSqliteConnection(TDBXDataExpressProviderContext(Context).Connection);
if Assigned(LConnection) then
begin
DBXContext := TDBXContext.Create;
try
LCommand := TDBXSqliteCommand.Create(DBXContext, LConnection);
try
LCommand.Text := 'select sql from sqlite_master where name = ''' + Table + ''' collate nocase';
LReader := TDBXSqliteReader(LCommand.ExecuteQuery);
try
SetLength(Columns, 9);
Columns[0] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexColumnsColumns.CatalogName, SCatalogName, TDBXDataTypes.WideStringType);
Columns[1] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexColumnsColumns.SchemaName, SSchemaName, TDBXDataTypes.WideStringType);
Columns[2] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexColumnsColumns.TableName, STableName, TDBXDataTypes.WideStringType);
Columns[3] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexColumnsColumns.IndexName, SIndexName, TDBXDataTypes.WideStringType);
Columns[4] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexColumnsColumns.ColumnName, SColumnName, TDBXDataTypes.WideStringType);
Columns[5] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexColumnsColumns.Ordinal, SOrdinal, TDBXDataTypes.Int32Type);
Columns[6] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexColumnsColumns.IsAscending, SIsAscending, TDBXDataTypes.BooleanType);
Columns[7] := TDBXMetaDataCollectionColumns.CreateValueType('IsDescending', 'Descending', TDBXDataTypes.BooleanType, True);
Columns[8] := TDBXMetaDataCollectionColumns.CreateValueType('CollationName', 'Collation Name', TDBXDataTypes.WideStringType, True);
MemTable := TDBXMemoryTable.Create;
try
SetLength(TableColumns, Length(Columns));
for I := 0 to Length(Columns) - 1 do
TableColumns[I] := Columns[I].Clone;
MemTable.Columns := TableColumns;
Scanner := TDBXSqlScanner.Create(GetSqlIdentifierQuoteChar, GetSqlIdentifierQuotePrefix, GetSqlIdentifierQuoteSuffix);
try
Scanner.RegisterId(OnConst, OnIndex);
Scanner.RegisterId(Collate, CollateIndex);
Scanner.RegisterId(Asc, AscIndex);
Scanner.RegisterId(Desc, DescIndex);
Scanner.RegisterId(IndexConst, IndexToken);
Scanner.RegisterId(TableConst, TableToken);
Scanner.RegisterId(PrimaryConst, PrimaryToken);
Scanner.RegisterId(ConstraintConst, ConstraintToken);
LReader.Next;
Scanner.Init(LReader.Value[0].AsString);
MemTable.Insert; //Dummy Row
Scan(Scanner, MemTable);
finally
Scanner.Free;
end;
MemTable.First;
Cursor := TDBXStringTrimTable.CreateTrimTableIfNeeded(MemTable);
Cursor := TDBXCustomMetaDataTable.Create(GetContext, TDBXMetaDataCollectionName.IndexColumns, Columns, Cursor);
Result := TDBXSqliteColumnsTableCursor.Create(Self, False, Cursor);
except
MemTable.Free;
raise;
end;
finally
LReader.Free;
end;
finally
LCommand.Free;
end;
finally
DBXContext.Free;
end;
end;
end;
end;
end;
function TDBXSqliteCustomMetaDataReader.FetchPackageProcedureParameters(const Catalog: string; const Schema: string; const PackageName: string; const ProcedureName: string; const ParameterName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageProcedureParametersColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedureParameters, Columns);
end;
function TDBXSqliteCustomMetaDataReader.FetchPackageProcedures(const Catalog: string; const Schema: string; const PackageName: string; const ProcedureName: string; const ProcedureType: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageProceduresColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedures, Columns);
end;
function TDBXSqliteCustomMetaDataReader.FetchPackages(const Catalog: string; const Schema: string; const PackageName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackagesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Packages, Columns);
end;
function TDBXSqliteCustomMetaDataReader.FetchPackageSources(const Catalog: string; const Schema: string; const PackageName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageSourcesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageSources, Columns);
end;
function TDBXSqliteCustomMetaDataReader.FetchProcedureParameters(const Catalog: string; const Schema: string; const Proc: string; const Parameter: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateProcedureParametersColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.ProcedureParameters, Columns);
end;
function TDBXSqliteCustomMetaDataReader.FetchProcedures(const Catalog: string; const Schema: string; const ProcedureName: string; const ProcedureType: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateProceduresColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Procedures, Columns);
end;
function TDBXSqliteCustomMetaDataReader.FetchProcedureSources(const Catalog: string; const Schema: string; const Proc: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateProcedureSourcesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.ProcedureSources, Columns);
end;
function TDBXSqliteCustomMetaDataReader.FetchRoles: TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateRolesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Roles, Columns);
end;
function TDBXSqliteCustomMetaDataReader.FetchSchemas(const Catalog: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateSchemasColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Schemas, Columns);
end;
function TDBXSqliteCustomMetaDataReader.FetchSynonyms(const Catalog: string; const Schema: string; const Synonym: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateSynonymsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Synonyms, Columns);
end;
function TDBXSqliteCustomMetaDataReader.FetchUsers: TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateUsersColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Users, Columns);
end;
{ TDBXSqliteColumnsTableCursor }
function TDBXSqliteColumnsTableCursor.GetWritableValue(
const Ordinal: Integer): TDBXWritableValue;
begin
Result := FTable.Value[Ordinal];
end;
constructor TDBXSqliteColumnsTableCursor.Create(const Reader: TDBXBaseMetaDataReader;
const CheckBase: Boolean; const Cursor: TDBXTable);
const
DbxDataTypeIndex = 7;
var
DataTypeColumns: TDBXValueTypeArray;
Ordinal: Integer;
begin
inherited Create;
Table := Cursor;
FDataTypeHash := Reader.DataTypeHash;
FReader := Reader;
FCheckBase := CheckBase;
if DBXTableName = TDBXMetaDataCollectionName.Columns then
begin
FOrdinalOffset := 0;
FOrdinalTypeName := 2;
SetLength(DataTypeColumns, 1);
for Ordinal := 0 to Length(DataTypeColumns) - 1 do
DataTypeColumns[Ordinal] := TDBXValueType(Cursor.Columns[Ordinal + DbxDataTypeIndex].Clone);
FDataTypesRow := TDBXSingleValueRow.Create;
FDataTypesRow.Columns := DataTypeColumns;
end;
end;
destructor TDBXSqliteColumnsTableCursor.Destroy;
begin
if DBXTableName = TDBXMetaDataCollectionName.Columns then
FDataTypesRow.Free;
inherited Destroy;
end;
function TDBXSqliteColumnsTableCursor.Next: Boolean;
var
ReturnValue: Boolean;
begin
ReturnValue := FTable.Next;
if ReturnValue and (DBXTableName = TDBXMetaDataCollectionName.Columns) then
FDataType := TDBXDataTypeDescription(FDataTypeHash[FTable.Value[FOrdinalTypeName].AsString]);
Result := ReturnValue;
end;
end.
|
//*********************************************************************************//
//Unit: osUtilsBD //
//Classes: //
// -TAlteradorBD //
//*********************************************************************************//
unit osUtilsBD;
interface
uses
Classes, osSQLDataSet, IdGlobal, SysUtils, variants, DB;
const
//definição das constantes de erro
E_CAMPO_EXISTENTE = 'O campo já existe';
E_CAMPO_INEXISTENTE = 'Campo inexistente';
E_IMPOSSIVEL_INSERIR_CAMPO = 'Impossível inserir campo';
E_SEM_CAMPOS = 'Não existem campos';
E_TABELA_NAO_DEFINIDA = 'A tabela não está definida';
E_CHAVE_SEM_VALOR = 'Existe uma chave sem um valor definido';
type
//tipo utilizado para definir as propriedades de um campo
TPropsCampo = class
public
Tipo: TFieldType;
SubTipo: TFieldType;
Chave: Boolean;
Valor: Variant;
end;
//definição da classe TAlteradorBD
TAlteradorBD = class
private
FnomesCampos: TStringList; //os nomes de todos os campos envolvidos
FNomeTabela: string; //o nome da tabela que está sendo atualizada
property nomesCampos: TStringList read FnomesCampos write FnomesCampos;
function getSelect: string;
function getFrom: string;
function getWhere: string;
function getInsert: string;
function getUpdate: string;
procedure preencheParams(query: TosSQLDataSet);
procedure inserirRegistro;
procedure atualizarRegistro;
public
property nomeTabela: string read FNomeTabela write FNomeTabela; //o nome da tabela publicado
constructor create;
destructor destroy; override;
function existeRegistro: boolean;
procedure inserir(sobreescrever: boolean = false);
procedure adicionarCampo(PNome: string; PTipo: TFieldType; chave: boolean = false);
procedure adicionarCampoValor(PNome: string; PTipo: TFieldType; PValor: variant;
PChave: boolean = false);
procedure setarSubTipo(PNome: string; PSubTipo: TBlobType);
procedure setarValor(PNome: string; PValor: variant);
end;
implementation
uses SQLMainData, SqlExpr;
{ TAlteradorBD }
//**********************************************************************************//
//Classe: TAlteradorBD //
//Descrição: A idéia geral desta classe é evitar que se escreva muitas sentenças //
// SQL simples. Assim, baseando-se em três listas a classe deve controlar inserções//
// e atualizações no banco de dados. Esta classe depende do SQLMainData para //
// funcionar. Existem três listas: //
// 1) nomesCampos: lista de nomes de todos os campos de uma tabela que //
// interessam para a atualização que está sendo feita //
// 2) nomesChaves: lista de nomes de todos os campos da lista de campos que //
// deverão ser tratados como chave //
// 3) valoresCampos: lista paralela à lista de nomes de campos que diz respeito//
// aos valores correspondentes aos campos //
// Além das listas, existe uma propriedade (nomeTabela) que representa o nome da //
// tabela que está sendo atualizada pelo objeto. //
// Existem 3 métodos públicos além do construtor e do destrutor: //
// 1) existeRegistro: baseado nas informações contidas nas listas, verifica se //
// já existe um registro correspondente (no que diz respeito//
// às chaves) no BD. //
// 2) inserir: insere o registro no BD. Caso o registro já exista no BD e a //
// propriedade sobreescrever esteja setada para true, gera um //
// update para a tabela. //
// 3) adicionarCampo: é o meio com que os campos são adicionados ao objeto //
//**********************************************************************************//
//*********************************************************************************//
//Método: adicionarCampo //
//Descrição: Serve para adicionar um campo à lista de campos. O usuário da classe //
// não terá acesso à lista de nomes dos campos, ficando a cargo deste //
// procedimento controlar a liata //
//*********************************************************************************//
procedure TAlteradorBD.adicionarCampo(PNome: string; PTipo: TFieldType; chave: boolean);
begin
adicionarCampoValor(PNome, PTipo, NULL, chave);
end;
procedure TAlteradorBD.adicionarCampoValor(PNome: string; PTipo: TFieldType; PValor:variant;
PChave: boolean);
var
indiceCampo: integer;
begin
//se o campo já existe, retorna um erro
if (nomesCampos.IndexOf(PNome)<>-1) then
raise exception.create(E_CAMPO_EXISTENTE);
//insere o nome do campo na lista de nomes
indiceCampo := nomesCampos.Add(PNome);
//criar um objeto setar as propriedades do campo
nomesCampos.Objects[indiceCampo] := TPropsCampo.Create;
with TPropsCampo(nomesCampos.Objects[indiceCampo]) do
begin
Chave := PChave;
Valor := PValor;
Tipo := PTipo;
SubTipo := ftUnknown;
end;
end;
//*********************************************************************************//
//Método: atualizarRegistro //
//Descrição: Envia a sentença de update para o BDi //
//*********************************************************************************//
procedure TAlteradorBD.atualizarRegistro;
var
query: TosSQLDataSet;
begin
query := TosSQLDataSet.Create(nil);
try
query.SQLConnection := MainData.SQLConnection;
query.CommandText := getUpdate + getWhere;
preencheParams(query);
query.ExecSQL;
finally
freeAndNil(query);
end;
end;
//*********************************************************************************//
//Método: constructor //
//Descrição: Construtora da classe. Cria as listas que devem ser criadas. //
//*********************************************************************************//
constructor TAlteradorBD.create;
begin
nomesCampos := TStringList.Create;
end;
//*********************************************************************************//
//Método: destroy //
//Descrição: Destrutora da classe. Libera as listas que foram criadas na //
// construtora. //
//*********************************************************************************//
destructor TAlteradorBD.destroy;
begin
nomesCampos.Free;
end;
//*********************************************************************************//
//Método: existeRegistro //
//Descrição: Verifica a existência do registro no BD. //
//*********************************************************************************//
function TAlteradorBD.existeRegistro: boolean;
var
query: TosSQLDataSet;
begin
query := TosSQLDataSet.Create(nil);
try
query.SQLConnection := MainData.SQLConnection;
query.CommandText := 'Select count(1) ' + getFrom + getWhere;
preencheParams(query);
query.Open;
result := query.fields[0].Value>0;
finally
freeAndNil(query);
end;
end;
//*********************************************************************************//
//Método: getFrom //
//Descrição: Gera uma parte de código SQL referente ao FROM. //
//*********************************************************************************//
function TAlteradorBD.getFrom: string;
begin
if nomeTabela='' then
raise Exception.Create(E_TABELA_NAO_DEFINIDA);
result := ' FROM ' + FNomeTabela + ' ';
end;
//*********************************************************************************//
//Método: getInsert //
//Descrição: Gera a parte do insert do código SQL já com o INTO e values. Os //
// valores são parametrizados. //
//*********************************************************************************//
function TAlteradorBD.getInsert: string;
var
sent: string;
i: integer;
begin
if nomeTabela='' then
raise Exception.Create(E_TABELA_NAO_DEFINIDA);
sent := 'INSERT INTO ' + FNomeTabela + ' ';
sent := sent + '(';
for i := 0 to nomesCampos.Count-1 do
begin
sent := sent + nomesCampos[i];
if i<nomesCampos.Count-1 then
sent := sent + ', ';
end;
sent := sent + ') values (';
for i := 0 to nomesCampos.Count-1 do
begin
sent := sent + ':'+nomesCampos[i];
if i<nomesCampos.Count-1 then
sent := sent + ', ';
end;
Result := sent + ') ';
end;
//*********************************************************************************//
//Método: getSelect //
//Descrição: Gera a parte de código SQL referente a um SELECT //
//*********************************************************************************//
function TAlteradorBD.getSelect: string;
var
sent: string;
i: integer;
begin
sent := 'SELECT ';
for i := 0 to nomesCampos.Count-1 do
begin
sent := sent + nomesCampos[i];
if i<nomesCampos.Count-1 then
sent := sent + ', ';
end;
result := sent + ' ';
end;
//*********************************************************************************//
//Método: getUpdate //
//Descrição: Gera a parte de código SQL referente a um UPDATE já com SET. Os //
// valores vão parametrizados. //
//*********************************************************************************//
function TAlteradorBD.getUpdate: string;
var
sent: string;
i: integer;
begin
if nomeTabela='' then
raise Exception.Create(E_TABELA_NAO_DEFINIDA);
sent := 'UPDATE ' + FNomeTabela + ' SET ';
for i := 0 to nomesCampos.Count-1 do
begin
sent := sent + nomesCampos[i] + '= :' + nomesCampos[i];
if i<nomesCampos.Count-1 then
sent := sent + ', ';
end;
Result := sent + ' ';
end;
//*********************************************************************************//
//Método: getUpdate //
//Descrição: Gera a parte de código SQL referente a um WHERE já com ANDs. Os //
// valores vão parametrizados. Somente campos chave são inseridos //
//*********************************************************************************//
function TAlteradorBD.getWhere: string;
var
sent: string;
i: integer;
begin
sent := ' WHERE ';
for i := 0 to nomesCampos.Count-1 do
begin
if TPropsCampo(nomesCampos.Objects[i]).Chave then
sent := sent + nomesCampos[i] + '= :' + nomesCampos[i];
end;
result := Copy(sent, 0, length(sent)-4);
end;
//*********************************************************************************//
//Método: inserir //
//Descrição: Já descrito. //
//*********************************************************************************//
procedure TAlteradorBD.inserir(sobreescrever: boolean);
begin
if (existeRegistro AND (not(sobreescrever))) then
exit;
if existeRegistro then
atualizarRegistro
else
inserirRegistro;
end;
//*********************************************************************************//
//Método: inserirRegistro //
//Descrição: Manda ao BD a sentença de inserção com os parâmetros preenchidos. //
//*********************************************************************************//
procedure TAlteradorBD.inserirRegistro;
var
query: TosSQLDataSet;
begin
query := TosSQLDataSet.Create(nil);
try
query.SQLConnection := MainData.SQLConnection;
query.CommandText := getInsert;
preencheParams(query);
query.ExecSQL;
finally
freeAndNil(query);
end;
end;
//*********************************************************************************//
//Método: preencheParams //
//Descrição: Baseando-se nos parâmetros da query, preenche seus valores conforme //
// a lista de valores //
//*********************************************************************************//
procedure TAlteradorBD.preencheParams(query: TosSQLDataSet);
var
i, indiceCampo: integer;
nomeParam: string;
begin
for i := 0 to query.Params.Count-1 do
begin
nomeParam := query.Params[i].Name;
indiceCampo := nomesCampos.IndexOf(nomeParam);
if indiceCampo=-1 then
raise exception.Create(E_CHAVE_SEM_VALOR);
query.Params[i].Value := TPropsCampo(nomesCampos.Objects[indiceCampo]).Valor;
query.Params[i].DataType := TPropsCampo(nomesCampos.Objects[indiceCampo]).Tipo;
if (query.Params[i].DataType=ftBlob) then
TBlobField(query.Params[i]).BlobType := TPropsCampo(nomesCampos.Objects[indiceCampo]).SubTipo;
end;
end;
//*********************************************************************************//
//Método: setarValor //
//Descrição: Altera o valor de um campo //
//*********************************************************************************//
procedure TAlteradorBD.setarSubTipo(PNome: string; PSubTipo: TBlobType);
var
indiceCampo: integer;
begin
indiceCampo := nomesCampos.IndexOf(PNome);
if indiceCampo=-1 then
raise exception.Create(E_CAMPO_INEXISTENTE);
TPropsCampo(nomesCampos.Objects[indiceCampo]).SubTipo := PSubTipo;
end;
procedure TAlteradorBD.setarValor(PNome: string; PValor: variant);
var
indiceCampo: integer;
begin
indiceCampo := nomesCampos.IndexOf(PNome);
if indiceCampo=-1 then
raise exception.Create(E_CAMPO_INEXISTENTE);
TPropsCampo(nomesCampos.Objects[indiceCampo]).Valor := PValor;
end;
end.
|
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit ResponseStreamIntf;
interface
{$MODE OBJFPC}
{$H+}
type
(*!----------------------------------------------
* interface for any class having capability as
* HTTP response body
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*-----------------------------------------------*)
IResponseStream = interface
['{14394487-875D-4C4E-B4AE-9176B7393CAC}']
(*!------------------------------------
* read stream to buffer from current
* seek position
*-------------------------------------
* @param buffer pointer to buffer to store
* @param sizeToRead number of bytes to read
* @return number of bytes actually read
*-------------------------------------
* After read, implementation must advance its
* internal pointer position to actual number
* of bytes read
*-------------------------------------*)
function read(var buffer; const sizeToRead : longint) : longint;
(*!------------------------------------
* write buffer to stream
*-------------------------------------
* @param buffer pointer to buffer to write
* @param sizeToWrite number of bytes to write
* @return number of bytes actually written
*-------------------------------------*)
function write(const buffer; const sizeToWrite : longint) : longint;
(*!------------------------------------
* write string to stream
*-------------------------------------
* @param buffer string to write
* @return number of bytes actually written
*-------------------------------------*)
function write(const buffer : string) : longint;
(*!------------------------------------
* get stream size
*-------------------------------------
* @return size of stream in bytes
*-------------------------------------*)
function size() : int64;
(*!------------------------------------
* seek
*-------------------------------------
* @param offset in bytes to seek start from beginning
* @return actual offset
*-------------------------------------
* if offset >= stream size then it is capped
* to stream size-1
*-------------------------------------*)
function seek(const offset : longint) : int64;
end;
implementation
end.
|
unit fmVDLogger;
interface
uses VCL.Forms, System.Classes, System.SysUtils, VCL.ComCtrls, VCL.StdCtrls, VCL.Controls;
type
tgLogger = Class(TCustomForm)
private
FStatusBar: TStatusBar;
FMemo: TMemo;
procedure SetStatusBar(const Value: TStatusBar);
procedure SetMemo(const Value: TMemo);
property Memo: TMemo read FMemo write SetMemo;
property StatusBar: TStatusBar read FStatusBar write SetStatusBar;
procedure OnCloseEvent(Sender: TObject; var Action: TCloseAction);
protected
public
class function CreateLog(AOwner: TComponent; ALogFileName: TFileName): tgLogger;
End;
implementation
uses
System.Types, Winapi.Windows;
{ tgLogger }
class function tgLogger.CreateLog(AOwner: TComponent; ALogFileName: TFileName): tgLogger;
var
LScreen: TRect;
LLogger: tgLogger;
LLogFile: TFileStream; // Log File Access
begin
LLogger := tgLogger.CreateNew(AOwner); // create the form without .dfm
{ Establish all components at run time }
with LLogger do
begin
// SystemParametersInfo(SPI_GETWORKAREA, 0, @LScreen, 0);
OnClose := OnCloseEvent; // set the on close event
SetBounds(30, 30, 700, 700); // X, Y, Width, Height
Caption := 'Log File Display'; // form caption
StatusBar := TStatusBar.Create(LLogger); // simple status bar
StatusBar.Parent := LLogger; // parent required for display
StatusBar.SimplePanel := True; // simple panel has one panel
StatusBar.SimpleText := ALogFileName; // show the log file name in status bar
StatusBar.AlignWithMargins := True; // leave a smidge at the border
Memo := TMemo.Create(LLogger); // create the memo to show the log file
Memo.Parent := LLogger; // parent rquired for display
Memo.Align := TAlign.alClient; // take all the space
Memo.ScrollBars := ssBoth; // allow for really wide content
Memo.ReadOnly := True; // there's no modifying provided
Memo.WordWrap := False; // turn off word wrap (see scroll bars)
Memo.AlignWithMargins := True; // more space for the memo
LLogFile := TFileStream.Create(ALogFileName, fmOpenRead); // open the inpus
try
Memo.Lines.LoadFromStream(LLogFile, TEncoding.UTF8); // load the memo lines
finally
LLogFile.Free; // free the file resource
end;
end;
Result := LLogger; // return the form object to caller
end;
procedure tgLogger.OnCloseEvent(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree; // free the form resource
ModalResult := mrCancel; // return cancel
end;
procedure tgLogger.SetMemo(const Value: TMemo);
begin
FMemo := Value;
end;
procedure tgLogger.SetStatusBar(const Value: TStatusBar);
begin
FStatusBar := Value;
end;
end.
|
unit BillContentViewModel;
interface
uses
BaseProductsViewModel, ProductsBaseQuery0, BillContentInterface, BillInterface,
BillContentQry, StoreHouseListQuery;
type
TBillContentViewModel = class(TBaseProductsViewModel)
private
FBill: IBill;
FqStoreHouseList: TQueryStoreHouseList;
function GetqBillContent: TQueryBillContent;
function GetqStoreHouseList: TQueryStoreHouseList;
protected
function CreateProductsQuery: TQryProductsBase0; override;
function GetExportFileName: string; override;
public
procedure CloseContent;
procedure LoadContent(ABillID: Integer; ABill: IBill);
property qBillContent: TQueryBillContent read GetqBillContent;
property qStoreHouseList: TQueryStoreHouseList read GetqStoreHouseList;
end;
implementation
uses
System.SysUtils;
procedure TBillContentViewModel.CloseContent;
begin
FBill := nil;
end;
function TBillContentViewModel.CreateProductsQuery: TQryProductsBase0;
begin
Result := TQueryBillContent.Create(Self);
end;
function TBillContentViewModel.GetExportFileName: string;
begin
Assert(FBill <> nil);
Assert(FBill.BillNumber > 0);
Result := Format('Ñ÷¸ò ¹%s îò %s.xlsx', [FBill.BillNumberStr,
FormatDateTime('dd.mm.yyyy', FBill.BillDate)]);
Assert(not Result.IsEmpty);
end;
function TBillContentViewModel.GetqBillContent: TQueryBillContent;
begin
Result := qProductsBase0 as TQueryBillContent;
end;
function TBillContentViewModel.GetqStoreHouseList: TQueryStoreHouseList;
begin
if FqStoreHouseList = nil then
begin
FqStoreHouseList := TQueryStoreHouseList.Create(Self);
FqStoreHouseList.FDQuery.Open;
end;
Result := FqStoreHouseList;
end;
procedure TBillContentViewModel.LoadContent(ABillID: Integer; ABill: IBill);
begin
Assert(ABill <> nil);
FBill := ABill;
qBillContent.LoadContent(ABillID);
end;
end.
|
unit RootForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, SettingsController, FormsHelper;
type
TfrmRoot = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FAutoSaveFormSize: Boolean;
procedure SetAutoSaveFormSize(const Value: Boolean);
{ Private declarations }
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure DoOnCaptionClick;
procedure ClearSelection(AComponent: TComponent);
procedure WMSysCommand(var Message: TWMSysCommand); message WM_SYSCOMMAND;
public
constructor Create(AOwner: TComponent); override;
procedure AfterConstruction; override;
property AutoSaveFormSize: Boolean read FAutoSaveFormSize
write SetAutoSaveFormSize;
{ Public declarations }
end;
var
frmRoot: TfrmRoot;
implementation
uses
System.Generics.Collections, SelectionInt, ProjectConst;
{$R *.dfm}
constructor TfrmRoot.Create(AOwner: TComponent);
begin
inherited;
FAutoSaveFormSize := True;
end;
procedure TfrmRoot.AfterConstruction;
begin
inherited;
// Scaled := True;
end;
{ —делать форму независимой от основного окна программы }
procedure TfrmRoot.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.ExStyle := Params.ExStyle or WS_EX_APPWINDOW;
Params.WndParent := GetDesktopWindow;
end;
procedure TfrmRoot.DoOnCaptionClick;
begin
ClearSelection(Self);
end;
procedure TfrmRoot.FormCreate(Sender: TObject);
begin
if FAutoSaveFormSize then
TFormsHelper.StringToFormStats(TSettings.Create.GetValue('Forms',
Name), Self);
TFormsHelper.SetFont(Self, BaseFontSize);
end;
procedure TfrmRoot.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if FAutoSaveFormSize then
TSettings.Create.SetValue('Forms', Name,
TFormsHelper.FormStatsToString(Self));
end;
procedure TfrmRoot.ClearSelection(AComponent: TComponent);
var
i: Integer;
ISel: ISelection;
begin
for i := 0 to AComponent.ComponentCount - 1 do
begin
// if AComponent.Components[i] is TfrmGrid then
// (AComponent.Components[i] as TfrmGrid).ClearSelection;
if AComponent.Components[i].GetInterface(ISelection, ISel) then
if ISel.HaveFocus then
ISel.ClearSelection;
// »щем среди дочерних компонентов
ClearSelection(AComponent.Components[i]);
end;
end;
procedure TfrmRoot.SetAutoSaveFormSize(const Value: Boolean);
begin
FAutoSaveFormSize := Value;
end;
procedure TfrmRoot.WMSysCommand(var Message: TWMSysCommand);
begin
if Message.CmdType = $F012 then // если клик по заголовку
begin
DoOnCaptionClick;
Application.ProcessMessages;
end;
inherited; // вызвать стандартное действие
end;
end.
|
unit UnitJournal;
interface
type
TJournalRecord = record
public
Time: TDateTime;
Level: byte;
Ok: boolean;
Text: string;
class function Deserialize(var p: Pointer)
: TArray<TJournalRecord>; static;
end;
implementation
uses myutils, System.sysutils;
function PointerToByteArray( Value: Pointer; SizeInBytes: Cardinal): TBytes;
var Address, i: integer;
begin
Address := Integer(Value);
SetLength(Result, SizeInBytes);
for i := 0 to SizeInBytes do
Result[i] := PByte(Ptr(Address + i))^;
end;
class function TJournalRecord.Deserialize(var p: Pointer): TArray<TJournalRecord>;
var
I: Integer;
recsCount: int64;
strBytes: TBytes;
strLen: Cardinal;
begin
recsCount := PInt64(p)^;
Inc(PByte(p), 8);
SetLength(Result, recsCount);
if recsCount = 0 then
exit;
for I := 0 to recsCount - 1 do
begin
Result[i].Time := unixMillisToDateTime(PInt64(p)^);
Inc(PByte(p), 8);
Result[i].Level := PByte(p)^;
Inc(PByte(p), 1);
Result[i].Ok := PByte(p)^ <> 0;
Inc(PByte(p), 1);
strLen := PInt64(p)^;
Inc(PByte(p), 8);
strBytes := PointerToByteArray( PByte(p), strLen);
Inc(PByte(p), strLen);
Result[i].Text := TEncoding.UTF8.GetString(strBytes);
end;
end;
end.
|
{**********************************************************}
{ }
{ Cipher 1.0 }
{ ---- Sample for Using TinyDB }
{ }
{ Author: DayDream Studio }
{ Email: webmaster@tinydb.com }
{ URL: http://www.TinyDB.com }
{ }
{**********************************************************}
unit MainFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics,
Controls, Forms, Dialogs, ComCtrls, ToolWin,
Menus, Db, ActnList, ImgList, ExtCtrls,
PwdDataFrm, TinyDB;
type
TMainForm = class(TForm)
MainMenu: TMainMenu;
FileMenu: TMenuItem;
ToolBar: TToolBar;
ListView: TListView;
StatusBar: TStatusBar;
ToolButton1: TToolButton;
HelpMenu: TMenuItem;
HelpAboutItem: TMenuItem;
FileExitItem: TMenuItem;
TinyDatabase: TTinyDatabase;
TinyTable: TTinyTable;
ActionList: TActionList;
NewAction: TAction;
DeleteAction: TAction;
ModifyAction: TAction;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ImageList: TImageList;
FileN1Item: TMenuItem;
FileNewItem: TMenuItem;
FileDeleteItem: TMenuItem;
FileModifyItem: TMenuItem;
Panel1: TPanel;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
ChgPwdAction: TAction;
FileChgPwdItem: TMenuItem;
FileN2Item: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure NewActionExecute(Sender: TObject);
procedure DeleteActionExecute(Sender: TObject);
procedure ModifyActionExecute(Sender: TObject);
procedure ChgPwdActionExecute(Sender: TObject);
procedure FileExitItemClick(Sender: TObject);
procedure HelpAboutItemClick(Sender: TObject);
private
{ Private declarations }
function GetDBFileName: string;
function CreateDatabase(Password: string): Boolean;
procedure SavePwdData(Data: TPwdDataFormData);
procedure FillListView;
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
uses StrRes, SetPwdFrm, InputFrm, AboutFrm;
function TMainForm.GetDBFileName: string;
begin
Result := ExtractFilePath(Application.ExeName) + 'Cipher.dat';
end;
function TMainForm.CreateDatabase(Password: string): Boolean;
var
DBFileName: string;
begin
Result := True;
DBFileName := GetDBFileName;
try
TinyDatabase.CreateDatabase(DBFileName, False, clNormal, 'ZLIB', True, 'Blowfish', Password, True);
TinyDatabase.DatabaseName := DBFileName;
TinyDatabase.Password := Password;
TinyDatabase.CreateTable('Cipher', [
FieldItem('ID', ftAutoInc),
FieldItem('Password', ftString, 64),
FieldItem('Note', ftMemo)
] );
TinyDatabase.CreateIndex('Cipher', 'ByPassword', [], ['Password']);
except
DeleteFile(DBFileName);
Result := False;
end;
end;
procedure TMainForm.SavePwdData(Data: TPwdDataFormData);
begin
TinyTable.AppendRecord([0, Data.Password, Data.Note]);
end;
procedure TMainForm.FillListView;
var
I: Integer;
ListItem: TListItem;
begin
ListView.Items.BeginUpdate;
ListView.Items.Clear;
TinyTable.First;
for I := 0 to TinyTable.RecordCount - 1 do
begin
ListItem := ListView.Items.Add;
ListItem.Caption := TinyTable.FieldByName('Password').AsString;
ListItem.SubItems.Add(TinyTable.FieldByName('Note').AsString);
ListItem.ImageIndex := 4;
ListItem.Data := Pointer(TinyTable.FieldByName('ID').AsInteger);
TinyTable.Next;
end;
ListView.Items.EndUpdate;
end;
procedure TMainForm.FormCreate(Sender: TObject);
var
DBFileName: string;
Password: string;
Tip: string;
begin
DBFileName := GetDBFileName;
if not FileExists(DBFileName) then
begin
Tip := SStartupTip;
if not ShowSetPwdForm(Password, Tip, SInputPassword) then
begin
Position := poDesigned;
Left := -1000;
Application.Terminate;
Exit;
end;
if not CreateDatabase(Password) then
begin
MessageBox(Application.Handle, PChar(SFailToCreateDb), PChar(Application.Title), 16);
Application.Terminate;
end;
end else
begin
TinyDatabase.Close;
TinyDatabase.DatabaseName := DBFileName;
TinyDatabase.Open;
if ShowInputForm(Password, Self.Caption, SInputPassword, True) then
begin
TinyDatabase.Password := Password;
if not TinyDatabase.CanAccess then
begin
Application.MessageBox(PChar(SPasswordWrong), PChar(Application.Title), 48);
Application.Terminate;
end;
end else
begin
Application.Terminate;
Exit;
end;
end;
TinyTable.DatabaseName := DBFileName;
TinyTable.TableName := 'Cipher';
TinyTable.Password := Password;
TinyTable.Open;
FillListView;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
TinyTable.Close;
end;
procedure TMainForm.NewActionExecute(Sender: TObject);
var
Data: TPwdDataFormData;
begin
if ShowPwdDataForm(Data) then
begin
SavePwdData(Data);
FillListView;
end;
end;
procedure TMainForm.DeleteActionExecute(Sender: TObject);
var
ID, R: Integer;
begin
if ListView.Selected = nil then Exit;
R := MessageBox(Application.Handle, PChar(SQueryDeletePassword), PChar(Application.Title), 36);
if R = ID_NO then Exit;
ID := Integer(ListView.Selected.Data);
if TinyTable.FindKey([ID]) then
begin
TinyTable.Delete;
ListView.Selected.Delete;
end;
end;
procedure TMainForm.ModifyActionExecute(Sender: TObject);
var
ID: Integer;
Data: TPwdDataFormData;
ListItem: TListItem;
begin
if ListView.Selected = nil then Exit;
ListItem := ListView.Selected;
ID := Integer(ListItem.Data);
if TinyTable.FindKey([ID]) then
begin
Data.Password := TinyTable.FieldByName('Password').AsString;
Data.Note := TinyTable.FieldByName('Note').AsString;
if ShowPwdDataForm(Data) then
begin
TinyTable.Edit;
TinyTable.FieldByName('Password').AsString := Data.Password;
TinyTable.FieldByName('Note').AsString := Data.Note;
TinyTable.Post;
ListItem.Caption := Data.Password;
ListItem.SubItems[0] := Data.Note;
end;
end;
end;
procedure TMainForm.ChgPwdActionExecute(Sender: TObject);
var
Password, Tip: string;
begin
Tip := SChangePwdTip;
if ShowSetPwdForm(Password, Tip, SChangePassord) then
begin
TinyTable.Close;
if TinyDatabase.ChangePassword(Password, True) then
begin
MessageBox(Handle, PChar(SChgPwdSucc), PChar(Application.Title), 48);
TinyTable.Password := Password;
end;
TinyTable.Open;
end;
end;
procedure TMainForm.FileExitItemClick(Sender: TObject);
begin
Close;
end;
procedure TMainForm.HelpAboutItemClick(Sender: TObject);
begin
ShowAboutForm;
end;
end.
|
unit PRFWK_DAO;
interface
uses PRFWK_Classe, Classes, PRFWK_Atributo, PRFWK_Modelo, TypInfo, DBClient, SqlExpr,
Provider, PRFWK_Conexao, DB, SysUtils, PRFWK_Utilidades, Variants, PRFWK_ClientDataSet,
PRFWK_DataSetProvider, PRFWK_SqlDataSet, AdoDB, PRFWK_AdoDataSet;
type
TPRFWK_DAO = class(TPRFWK_Classe)
private
protected
aMapeamentoAtributos : TList;
aClasse : TPRFWK_Modelo;
aClientDataSet : TPRFWK_ClientDataSet;
aSqlDataSet : TPRFWK_SQLDataSet;
aAdoDataSet : TPRFWK_ADODataSet;
aDataSetProvider : TPRFWK_DataSetProvider;
aConexao : TPRFWK_Conexao;
aNomeTabela : String;
procedure ProviderBeforeUpdateRecord(Sender: TObject; SourceDS: TDataSet; DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind; var Applied: Boolean);
procedure montarObjetos();
procedure montarEntidade(entidade: TPRFWK_Modelo);
procedure definirValoresAtributos(entidade: TPRFWK_Modelo; zeraChavePrimaria: Boolean = true);
function posicionarChavePrimaria(entidade: TPRFWK_Modelo):Boolean;
public
property nomeTabela:String read aNomeTabela write aNomeTabela;
property mapeamentoAtributos:TList read aMapeamentoAtributos write aMapeamentoAtributos;
property classe:TPRFWK_Modelo read aClasse write aClasse;
property conexao:TPRFWK_Conexao read aConexao write aConexao;
property clientDataSet:TPRFWK_ClientDataSet read aClientDataSet write aClientDataSet;
property sqlDataSet:TPRFWK_SQLDataSet read aSqlDataSet write aSqlDataSet;
property adoDataSet:TPRFWK_ADODataSet read aAdoDataSet write aAdoDataSet;
property dataSetProvider:TPRFWK_DataSetProvider read aDataSetProvider write aDataSetProvider;
constructor Create; override;
destructor Destroy; override;
procedure adicionarMapeamento(nome: String; sqlIndice: Boolean = False; sqlUpdate: Boolean = True; sqlWhere: Boolean = True);
procedure inserir(entidade: TPRFWK_Modelo); virtual;
procedure alterar(entidade: TPRFWK_Modelo); virtual;
procedure excluir(entidade: TPRFWK_Modelo); virtual;
function obter(entidade: TPRFWK_Modelo):TPRFWK_Modelo; virtual;
function obterTodos(entidade: TPRFWK_Modelo):TList; virtual;
function obterQuantidade():Integer; virtual;
procedure defineSql(sql: WideString; montaObjetos: Boolean = true);
procedure fechaDataSet(incluiClientDataSet: Boolean = true);
procedure abreDataSet(incluiClientDataSet: Boolean = true);
published
end;
implementation
{ TGerente }
{**
* Adiciona mapeamento de atributo da classe
*}
procedure TPRFWK_DAO.adicionarMapeamento(nome: String; sqlIndice: Boolean = False; sqlUpdate: Boolean = True; sqlWhere: Boolean = True);
var
lAtributo : TPRFWK_Atributo;
begin
aMapeamentoAtributos.Add( TPRFWK_Atributo.Create );
lAtributo := aMapeamentoAtributos[ aMapeamentoAtributos.Count-1 ];
lAtributo.nome := nome;
lAtributo.sqlIndice := sqlIndice;
lAtributo.sqlUpdate := sqlUpdate;
lAtributo.sqlWhere := sqlWhere;
end;
{**
* Construtor
*}
constructor TPRFWK_DAO.Create;
begin
inherited;
//verifica se definido o nome da entidade
if (aNomeTabela = '') then
begin
TPRFWK_Utilidades.obterInstancia().msgCrit('[' + ClassName + ']: O nome da entidade não foi definido.');
end
else
begin
//cria lista de mapeamento
aMapeamentoAtributos := TList.Create;
//adiciona chave primária - toda tabela precisa ter este campo
adicionarMapeamento('ID', True, True , True);
//cria objetos de conexão
aClientDataSet := TPRFWK_ClientDataSet.Create(nil);
aDataSetProvider := TPRFWK_DataSetProvider.Create(nil);
//verifica que tipo de conexão é para criar o dataSet correto
if aConexao.driver <> 'ADO' then
aSqlDataSet := TPRFWK_SQLDataSet.Create(nil)
else
aAdoDataSet := TPRFWK_ADODataSet.Create(nil);
//define nomes
aClientDataSet.Name := 'CDS';
if aConexao.driver <> 'ADO' then
aSqlDataSet.Name := 'SDS'
else
aAdoDataSet.Name := 'ADS';
aDataSetProvider.Name := 'DSP';
//define atributos do SDS
if aConexao.driver <> 'ADO' then
begin
aSqlDataSet.DbxCommandType := 'Dbx.SQL';
aSqlDataSet.CommandType := ctQuery;
aSqlDataSet.SQLConnection := TSQLConnection(aConexao.conexaoSql);
aSqlDataSet.CommandText := '';
end
else
begin
aAdoDataSet.CommandType := cmdText;
aAdoDataSet.Connection := TADOConnection(aConexao.conexaoSql);
aAdoDataSet.CommandText := '';
end;
//define atributos do DSP
if aConexao.driver <> 'ADO' then
aDataSetProvider.DataSet := aSqlDataSet
else
aDataSetProvider.DataSet := aAdoDataSet;
aDataSetProvider.UpdateMode := upWhereKeyOnly;
aDataSetProvider.Options := [poAllowCommandText,poUseQuoteChar,poPropogateChanges,poCascadeDeletes,poCascadeUpdates];
aDataSetProvider.Exported := true;
aDataSetProvider.BeforeUpdateRecord := ProviderBeforeUpdateRecord;
//define atributos do CDS
aClientDataSet.ProviderName := aDataSetProvider.Name;
aClientDataSet.StoreDefs := True;
aClientDataSet.SetProvider(aDataSetProvider);
end;
end;
{**
* Destrutor
*}
destructor TPRFWK_DAO.Destroy;
begin
inherited;
//desconecta os dataSets
fechaDataSet();
//destrói objetos
aMapeamentoAtributos.Free;
if aConexao.driver <> 'ADO' then
aSqlDataSet.Free
else
aAdoDataSet.Free;
aClientDataSet.Free;
aDataSetProvider.Free;
end;
{**
* Insere objeto no banco
*}
procedure TPRFWK_DAO.inserir(entidade: TPRFWK_Modelo);
begin
//monta dataSets
montarObjetos();
//abre dataSets
abreDataSet();
//adiciona novo registro
aClientDataSet.Append;
//define valores do dataSet baseado no mapeamento
definirValoresAtributos(entidade);
//confirma inclusão
aClientDataSet.Post;
aClientDataSet.ApplyUpdates(-1);
//atualiza para liberar o dataSet
aClientDataSet.Refresh;
end;
{**
* Obtém objeto do banco
*}
function TPRFWK_DAO.obter(entidade: TPRFWK_Modelo):TPRFWK_Modelo;
begin
//monta dataSets
montarObjetos();
//abre dataSets
abreDataSet();
//posiciona na chave primária
if posicionarChavePrimaria(entidade) = true then
begin
//monta entidade apartir do dataSet
montarEntidade(entidade);
//retorna entidade montada
Result := entidade;
end
else
begin
Result := nil;
end;
end;
{**
* Exclui objeto do banco
*}
procedure TPRFWK_DAO.excluir(entidade: TPRFWK_Modelo);
begin
//monta dataSets
montarObjetos();
//abre dataSets
abreDataSet();
//posiciona na chave primária
if posicionarChavePrimaria(entidade) = true then
begin
//exclui registro
aClientDataSet.Delete;
aClientDataSet.ApplyUpdates(-1);
end;
end;
{**
* Altera objeto no banco
*}
procedure TPRFWK_DAO.alterar(entidade: TPRFWK_Modelo);
begin
//monta dataSets
montarObjetos();
//abre dataSets
abreDataSet();
//posiciona na chave primária
if posicionarChavePrimaria(entidade) = true then
begin
//define novos valores e altera
aClientDataSet.Edit;
definirValoresAtributos(entidade, false);
aClientDataSet.ApplyUpdates(-1);
end;
end;
{**
* Obtém todos os objetos do banco
*}
function TPRFWK_DAO.obterTodos(entidade: TPRFWK_Modelo):TList;
begin
//monta dataSets
montarObjetos();
//fecha dataSets
fechaDataSet();
aClientDataSet.SetProvider(aDataSetProvider);
//cria query
if aConexao.driver <> 'ADO' then
aSqlDataSet.CommandText := 'SELECT * FROM ' + nomeTabela
else
aAdoDataSet.CommandText := 'SELECT * FROM ' + nomeTabela;
//abre dataSets
abreDataSet();
//posiciona no primeiro registro
aClientDataSet.First;
//percorre o dataSet
if aClientDataSet.RecordCount > 0 then
begin
//cria lista de resultados
Result := TList.Create;
while not aClientDataSet.Eof do
begin
//monta entidade adicionando na lista
Result.Add( entidade.NewInstance );
//monta entidade apartir do dataSet
montarEntidade( Result[Result.Count-1] );
//próximo registro
aClientDataSet.Next;
end;
end
else
Result := nil;
end;
{**
* Obtém a quantidade de registros de uma entidade do banco
*}
function TPRFWK_DAO.obterQuantidade():Integer;
var
lTemp : String;
begin
//monta dataSets
montarObjetos();
//fecha dataSets
fechaDataSet();
aClientDataSet.SetProvider(aDataSetProvider);
//cria query
if aConexao.driver <> 'ADO' then
begin
lTemp := aSqlDataSet.CommandText;
aSqlDataSet.CommandText := 'SELECT COUNT(ID) FROM ' + nomeTabela;
end
else
begin
lTemp := aAdoDataSet.CommandText;
aAdoDataSet.CommandText := 'SELECT COUNT(ID) FROM ' + nomeTabela;
end;
//abre dataSets
abreDataSet();
//retorna resultado
Result := aClientDataSet.Fields[0].AsInteger;
//fecha dataSets
fechaDataSet();
aClientDataSet.SetProvider(aDataSetProvider);
if aConexao.driver <> 'ADO' then
aSqlDataSet.CommandText := lTemp
else
aAdoDataSet.CommandText := lTemp;
//abre dataSets
abreDataSet();
end;
{**
* Monta objetos de conexão
*}
procedure TPRFWK_DAO.montarObjetos();
begin
//verifica se já foi montado
if aClientDataSet.FieldCount = 0 then
begin
//fecha dataSets
fechaDataSet();
aClientDataSet.SetProvider(aDataSetProvider);
//define tabela e abre dataSet
if aConexao.driver <> 'ADO' then
begin
aSqlDataSet.CommandText := 'SELECT * FROM ' + nomeTabela;
end
else
begin
aAdoDataSet.CommandText := 'SELECT * FROM ' + nomeTabela;
end;
//abre dataSet
abreDataSet();
end;
end;
{**
* Adiciona valor dos atributos nos datasets
*}
procedure TPRFWK_DAO.definirValoresAtributos(entidade: TPRFWK_Modelo; zeraChavePrimaria: Boolean = true);
var
lListaPropriedades : PPropList;
lContPropriedades : Integer;
x : Integer;
y : Integer;
PropInfo : TPropInfo;
PropValue : Variant;
nomeAtributo : String;
nomePropriedade : String;
begin
//define valor da chave primária
if zeraChavePrimaria = true then
if aClientDataSet.FieldByName( 'ID' ).CanModify then
aClientDataSet.FieldByName( 'ID' ).AsVariant := 0;
//obtém informações dos atributos que são Publisheds
lContPropriedades := GetPropList(entidade.ClassInfo, tkAny, nil);
GetMem( lListaPropriedades, lContPropriedades * SizeOf(TPropInfo) );
try
GetPropList(entidade, lListaPropriedades);
for x := 0 to Pred(lContPropriedades) do
begin
//obtém informações da propriedade
PropInfo := TPropInfo(lListaPropriedades^[x]^);
PropValue := GetPropValue(entidade, PropInfo.Name);
//varre mapeamento
for y := 0 to aMapeamentoAtributos.Count - 1 do
begin
nomeAtributo := TPRFWK_Atributo(aMapeamentoAtributos[y]).nome;
nomePropriedade := PropInfo.Name;
if (UpperCase(nomeAtributo) = UpperCase(nomePropriedade)) and (UpperCase(nomeAtributo) <> 'ID') then
begin
try
aClientDataSet.FindField( nomeAtributo ).AsVariant := PropValue;
except
//não faz nada
end;
end;
end;
end;
finally
FreeMem(lListaPropriedades);
end;
end;
{**
* Monta entidade apartir de dataSet
*}
procedure TPRFWK_DAO.montarEntidade(entidade: TPRFWK_Modelo);
var
x : Integer;
nomeAtributo : String;
lListaPropriedades : PPropList;
lContPropriedades : Integer;
PropInfo : TPropInfo;
lListaNomeAtributos : TStringList;
begin
//verifica se já foi montado
if aClientDataSet.FieldCount > 0 then
begin
//obtém informações dos atributos que são Publisheds
lContPropriedades := GetPropList(entidade.ClassInfo, tkAny, nil);
GetMem( lListaPropriedades, lContPropriedades * SizeOf(TPropInfo) );
try
lListaNomeAtributos := TStringList.Create;
GetPropList(entidade, lListaPropriedades);
//varre os atributos da classe para verificar se existe um atributo na classe com o mesmo nome
for x := 0 to Pred(lContPropriedades) do
begin
//obtém informações da propriedade
PropInfo := TPropInfo(lListaPropriedades^[x]^);
lListaNomeAtributos.Add( PropInfo.Name );
end;
finally
FreeMem(lListaPropriedades);
end;
//varre mapeamento
for x := 0 to aMapeamentoAtributos.Count - 1 do
begin
nomeAtributo := TPRFWK_Atributo(aMapeamentoAtributos[x]).nome;
try
if lListaNomeAtributos.IndexOf(nomeAtributo) > -1 then
if aClientDataSet.FieldByName(nomeAtributo).IsNull = false then
SetPropValue(entidade, nomeAtributo, aClientDataSet.FieldByName(nomeAtributo).AsVariant);
except
//não faz nada
end;
end;
//libera objetos da memória
lListaNomeAtributos.Free;
end;
end;
{**
* Posiciona dataSet na chave primária
*}
function TPRFWK_DAO.posicionarChavePrimaria(entidade: TPRFWK_Modelo):Boolean;
begin
Result := aClientDataSet.Locate('ID', entidade.ID , [loPartialKey]);
end;
{**
* Método chamada antes do update
*}
procedure TPRFWK_DAO.ProviderBeforeUpdateRecord(Sender: TObject; SourceDS: TDataSet; DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind; var Applied: Boolean);
var
x : Integer;
lProviderFlags : TProviderFlags;
begin
//define atributos dos campos dos dataSets
for x := 0 to aMapeamentoAtributos.Count - 1 do
begin
//cria ProviderFlags
lProviderFlags := [];
if TPRFWK_Atributo(aMapeamentoAtributos[x]).sqlIndice = true then
lProviderFlags := lProviderFlags + [pfInKey];
if TPRFWK_Atributo(aMapeamentoAtributos[x]).sqlUpdate = true then
lProviderFlags := lProviderFlags + [pfInUpdate];
if TPRFWK_Atributo(aMapeamentoAtributos[x]).sqlWhere = true then
lProviderFlags := lProviderFlags + [pfInWhere];
//define atributos
DeltaDS.FieldByName( TPRFWK_Atributo(aMapeamentoAtributos[x]).nome ).Required := TPRFWK_Atributo(aMapeamentoAtributos[x]).requerido;
DeltaDS.FieldByName( TPRFWK_Atributo(aMapeamentoAtributos[x]).nome ).ProviderFlags := lProviderFlags;
end;
end;
{**
* Método que define uma query sql executando os processos básicos
*}
procedure TPRFWK_DAO.defineSql(sql: WideString; montaObjetos: Boolean = true);
begin
//monta dataSets
if (montaObjetos = true) then
montarObjetos();
//fecha dataSets
fechaDataSet();
//define provider
aClientDataSet.SetProvider(aDataSetProvider);
//define query sql
if aConexao.driver <> 'ADO' then
aSqlDataSet.CommandText := sql
else
aAdoDataSet.CommandText := sql;
//abre dataSets
abreDataSet();
//posiciona no primeiro registro
aClientDataSet.First;
end;
{**
* Método que fecha o dataSet correto
*}
procedure TPRFWK_DAO.fechaDataSet(incluiClientDataSet: Boolean = true);
begin
//fecha dataSets
if aConexao.driver <> 'ADO' then
aSqlDataSet.Close
else
aAdoDataSet.Close;
if incluiClientDataSet = true then
aClientDataSet.Close;
end;
{**
* Método que abre o dataSet correto
*}
procedure TPRFWK_DAO.abreDataSet(incluiClientDataSet: Boolean = true);
begin
//fecha dataSets
if aConexao.driver <> 'ADO' then
aSqlDataSet.Open
else
aAdoDataSet.Open;
if incluiClientDataSet = true then
aClientDataSet.Open;
end;
end.
|
unit UCtrlCidade;
interface
uses uController, DB, UDaoCidade;
type CtrlCidade = class(Controller)
private
protected
umaDaoCidade : DaoCidade;
public
Constructor CrieObjeto;
Destructor Destrua_se;
function Salvar(obj:TObject): string; override;
function GetDS : TDataSource; override;
function Carrega(obj:TObject): TObject; override;
function Buscar(obj : TObject) : Boolean; override;
function Excluir(obj : TObject) : string ; override;
end;
implementation
{ CtrlCidade }
function CtrlCidade.Buscar(obj: TObject): Boolean;
begin
result := umaDaoCidade.Buscar(obj);
end;
function CtrlCidade.Carrega(obj: TObject): TObject;
begin
result := umaDaoCidade.Carrega(obj);
end;
constructor CtrlCidade.CrieObjeto;
begin
umaDaoCidade := DaoCidade.CrieObjeto;
end;
destructor CtrlCidade.Destrua_se;
begin
umaDaoCidade.Destrua_se;
end;
function CtrlCidade.Excluir(obj: TObject): string;
begin
result := umaDaoCidade.Excluir(obj);
end;
function CtrlCidade.GetDS: TDataSource;
begin
result := umaDaoCidade.GetDS;
end;
function CtrlCidade.Salvar(obj: TObject): string;
begin
result := umaDaoCidade.Salvar(obj);
end;
end.
|
unit SudokuMain;
{
***************************************************************************
* Copyright (C) 2006 Matthijs Willemstein *
* *
* Note: the original code by Matthijs was checked in as revision 7217 *
* in Lazarus-CCR subversion repository *
* *
* This source is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This code is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License for more details. *
* *
* A copy of the GNU General Public License is available on the World *
* Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also *
* obtain it by writing to the Free Software Foundation, *
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
***************************************************************************
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, Grids,
Buttons, StdCtrls, SudokuType, ScratchPad;
type
{ TForm1 }
TForm1 = class(TForm)
btnClear: TButton;
btnLoad: TButton;
btnSave: TButton;
btnSolve: TButton;
btnEdit: TButton;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
SGrid: TStringGrid;
procedure btnClearClick(Sender: TObject);
procedure btnEditClick(Sender: TObject);
procedure btnLoadClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnSolveClick(Sender: TObject);
procedure EditorKeyPress(Sender: TObject; var Key: char);
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure SGridPrepareCanvas(sender: TObject; aCol, aRow: Integer;
{%H-}aState: TGridDrawState);
procedure SGridSelectEditor(Sender: TObject; {%H-}aCol, {%H-}aRow: Integer;
var Editor: TWinControl);
private
{ private declarations }
const
MaxSteps = 50;
private
//theValues: TValues;
FSolveUsesRawData: Boolean;
FRawData: TRawGrid;
procedure OnCopyBackValues(Sender: TObject; Values: TValues);
procedure OnCopyBackRawData(Sender: TObject; RawData: TRawGrid);
procedure SetSolveUsesRawData(AValue: Boolean);
function SolveSudoku(out Values: TValues; out RawData: TRawGrid; out Steps: Integer): Boolean;
function SolveSudoku(var RawData: TRawGrid; out Values: TValues; out Steps: Integer): Boolean;
procedure GridToValues(out Values: TValues);
procedure ValuesToGrid(const Values: TValues);
procedure RawDataToGrid(const RawData: TRawGrid);
procedure ShowScratchPad(RawData: TRawGrid);
procedure LoadSudokuFromFile(const Fn: String);
procedure SaveSudokuToFile(const Fn: String);
function IsValidSudokuFile(Lines: TStrings): Boolean;
procedure LinesToGrid(Lines: TStrings);
procedure GridToLines(Lines: TStrings);
procedure EnableEdit;
procedure DisableEdit;
public
{ public declarations }
property SolveUsesRawData: Boolean read FSolveUsesRawData write SetSolveUsesRawData default False;
end;
ESudokuFile = Class(Exception);
var
Form1: TForm1;
implementation
{$R *.lfm }
const
FileEmptyChar = '-';
VisualEmptyChar = #32;
AllFilesMask = {$ifdef windows}'*.*'{$else}'*'{$endif}; //Window users are used to see '*.*', so I redefined this constant
SudokuFileFilter = 'Sudoku files|*.sudoku|All files|' + AllFilesMask;
{ TForm1 }
procedure TForm1.btnEditClick(Sender: TObject);
begin
EnableEdit;
SGrid.SetFocus;
end;
procedure TForm1.btnLoadClick(Sender: TObject);
begin
if OpenDialog.Execute then
try
LoadSudokuFromFile(OpenDialog.Filename);
SolveUsesRawData := False;
except
on E: Exception do ShowMessage(E.Message);
end;
end;
procedure TForm1.btnSaveClick(Sender: TObject);
begin
if SaveDialog.Execute then
try
SaveSudokuToFile(SaveDialog.Filename);
except
on E: Exception do ShowMessage(E.Message);
end;
end;
procedure TForm1.btnClearClick(Sender: TObject);
begin
SGrid.Clean;
end;
procedure TForm1.btnSolveClick(Sender: TObject);
var
Res: Boolean;
Values: TValues;
Steps: Integer;
begin
DisableEdit;
try
if not FSolveUsesRawData then
Res := SolveSudoku(Values, FRawData, Steps)
else
Res := SolveSudoku(FRawData, Values, Steps);
ValuesToGrid(Values);
if Res then
ShowMessage(Format('Sudoku solved in %d steps.', [Steps]))
else
begin
if (Steps < MaxSteps) then
ShowMessage(Format('Unable to solve sudoku (no progress after step %d).',[Steps-1]))
else
ShowMessage(Format('Unable to completely solve sudoku (tried %d steps).',[Steps]));
ShowScratchPad(FRawData);
end;
except
on E: ESudoku do ShowMessage(E.Message);
end;
end;
procedure TForm1.EditorKeyPress(Sender: TObject; var Key: char);
var
Ed: TStringCellEditor;
begin
if (Sender is TStringCellEditor) then
begin
Ed := TStringCellEditor(Sender);
Ed.SelectAll; //Key will now overwrite selection, in effect allowing to enter only 1 key
if not (Key in [#8, '1'..'9']) then Key := #0;
end;
end;
procedure TForm1.FormActivate(Sender: TObject);
begin
Self.OnActivate := nil;
SGrid.ClientWidth := 9 * SGrid.DefaultColWidth;
SGrid.ClientHeight := 9 * SGrid.DefaultRowHeight;
ClientWidth := 2 * SGrid.Left + SGrid.Width;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
SolveUsesRawData := False;
OpenDialog.Filter := SudokuFileFilter;
SaveDialog.Filter := SudokuFileFilter;
end;
procedure TForm1.SGridPrepareCanvas(sender: TObject; aCol, aRow: Integer;
aState: TGridDrawState);
var
NeedsColor: Boolean;
GridTextStyle: TTextStyle;
begin
GridTextStyle := (Sender as TStringGrid).Canvas.TextStyle;
GridTextStyle.Alignment := taCenter;
GridTextStyle.Layout := tlCenter;
(Sender as TStringGrid).Canvas.TextStyle := GridTextStyle;
NeedsColor := False;
if aCol in [0..2, 6..8] then
begin
if aRow in [0..2, 6..8] then
NeedsColor := True;
end
else
begin
if aRow in [3..5] then
NeedsColor := True;
end;
if NeedsColor then
(Sender as TStringGrid).Canvas.Brush.Color := $00EEEEEE;
end;
procedure TForm1.SGridSelectEditor(Sender: TObject; aCol, aRow: Integer;
var Editor: TWinControl);
var
Ed: TStringCellEditor;
begin
if Editor is TStringCellEditor then
begin
Ed := TStringCellEditor(Editor);
Ed.OnKeyPress := @EditorKeyPress;
end;
end;
function TForm1.SolveSudoku(out Values: TValues; out RawData: TRawGrid; out Steps: Integer): Boolean;
var
aSudoku: TSudoku;
begin
GridToValues(Values);
RawData := Default(TRawGrid);
aSudoku := TSudoku.Create;
try
Result := aSudoku.GiveSolution(Values, RawData, Steps);
finally
aSudoku.Free;
end;
end;
function TForm1.SolveSudoku(var RawData: TRawGrid; out Values: TValues; out Steps: Integer): Boolean;
var
aSudoku: TSudoku;
begin
aSudoku := TSudoku.Create;
try
Result := aSudoku.GiveSolution(RawData, Values, Steps);
finally
aSudoku.Free;
end;
end;
procedure TForm1.GridToValues(out Values: TValues);
var
Col, Row: Integer;
S: String;
AValue: Longint;
begin
Values := Default(TValues); //initialize all to zero
for Col := 0 to 8 do
begin
for Row := 0 to 8 do
begin
S := Trim(SGrid.Cells[Col, Row]);
if Length(S) = 1 then
begin
if TryStrToInt(S, AValue) then
Values[Col + 1, Row + 1] := AValue;
end;
end;
end;
end;
procedure TForm1.OnCopyBackValues(Sender: TObject; Values: TValues);
begin
ValuesToGrid(Values);
SolveUsesRawData := False;
end;
procedure TForm1.OnCopyBackRawData(Sender: TObject; RawData: TRawGrid);
begin
FRawData := RawData;
RawDataToGrid(RawData);
SolveUsesRawData := True;
end;
procedure TForm1.SetSolveUsesRawData(AValue: Boolean);
begin
if FSolveUsesRawData = AValue then Exit;
FSolveUsesRawData := AValue;
if FSolveUsesRawData then
DisableEdit
else
EnableEdit;
btnEdit.Enabled := not FSolveUsesRawData;
btnClear.Enabled := not FSolveUsesRawData;
end;
procedure TForm1.ValuesToGrid(const Values: TValues);
var
Col, Row: Integer;
Ch: Char;
begin
for Col := 0 to 8 do
begin
for Row := 0 to 8 do
begin
Ch := IntToStr(Values[Col + 1, Row + 1])[1];
if Ch = '0' then
Ch := VisualEmptyChar;
SGrid.Cells[Col, Row] := Ch;
end;
end;
end;
procedure TForm1.RawDataToGrid(const RawData: TRawGrid);
var
Col, Row: Integer;
Ch: Char;
begin
for Col := 0 to 8 do
begin
for Row := 0 to 8 do
begin
Ch := IntToStr(RawData[Col + 1, Row + 1].Value)[1];
if Ch = '0' then
Ch := VisualEmptyChar;
SGrid.Cells[Col, Row] := Ch;
end;
end;
end;
procedure TForm1.ShowScratchPad(RawData: TRawGrid);
begin
ScratchForm.OnCopyValues := @OnCopyBackValues;
ScratchForm.OnCopyRawData := @OnCopyBackRawData;
ScratchForm.RawData := RawData;
ScratchForm.ScratchGrid.Options := SGrid.Options - [goEditing];
ScratchForm.Left := Left + Width + 10;
if (ScratchForm.ShowModal <> mrOK) then
SolveUsesRawData := False;
end;
procedure TForm1.LoadSudokuFromFile(const Fn: String);
var
SL: TStringList;
begin
SL := TStringList.Create;
try
SL.LoadFromFile(Fn);
SL.Text := AdjustLineBreaks(SL.Text);
if not IsValidSudokuFile(SL) then
Raise ESudokuFile.Create(Format('File does not seem to be a valid Sudoku file:'^m'"%s"',[Fn]));
LinesToGrid(SL);
finally
SL.Free
end;
end;
procedure TForm1.SaveSudokuToFile(const Fn: String);
var
SL: TStringList;
begin
SL := TStringList.Create;
try
SL.SkipLastLineBreak := True;
GridToLines(SL);
{$if fpc_fullversion >= 30200}
SL.WriteBom := False;
{$endif}
SL.SaveToFile(Fn);
finally
SL.Free;
end;
end;
{
A valid SudokuFile consists of 9 lines, each line consists of 9 characters.
Only the characters '1'to '9' and spaces and FileEmptyChar ('-') are allowed.
Empty lines and lines starting with '#' (comments) are discarded
Future implementations may allow for adding a comment when saving the file
}
function TForm1.IsValidSudokuFile(Lines: TStrings): Boolean;
var
i: Integer;
S: String;
Ch: Char;
begin
Result := False;
for i := Lines.Count - 1 downto 0 do
begin
S := Lines[i];
if (S = '') or (S[1] = '#') then Lines.Delete(i);
end;
if (Lines.Count <> 9) then Exit;
for i := 0 to Lines.Count - 1 do
begin
S := Lines[i];
if (Length(S) <> 9) then Exit;
for Ch in S do
begin
if not (Ch in [FileEmptyChar, '1'..'9',VisualEmptyChar]) then Exit;
end;
end;
Result := True;
end;
{
Since this should only be called if IsValidSudokuFile retruns True,
We know that all lines consist of 9 chactres exactly and that there are exactly 9 lines in Lines
}
procedure TForm1.LinesToGrid(Lines: TStrings);
var
Row, Col: Integer;
S: String;
Ch: Char;
begin
for Row := 0 to Lines.Count - 1 do
begin
S := Lines[Row];
for Col := 0 to Length(S) - 1 do
begin
Ch := S[Col+1];
if (Ch = FileEmptyChar) then
Ch := VisualEmptyChar;
SGrid.Cells[Col, Row] := Ch;
end;
end;
end;
procedure TForm1.GridToLines(Lines: TStrings);
var
ALine, S: String;
Ch: Char;
Row, Col: Integer;
begin
Lines.Clear;
for Row := 0 to SGrid.RowCount - 1 do
begin
ALine := StringOfChar(FileEmptyChar,9);
for Col := 0 to SGrid.ColCount - 1 do
begin
S := SGrid.Cells[Col, Row];
if (Length(S) >= 1) then
begin
Ch := S[1];
if (Ch = VisualEmptyChar) then
Ch := FileEmptyChar;
ALine[Col+1] := Ch;
end;
end;
Lines.Add(ALine);
end;
end;
procedure TForm1.EnableEdit;
begin
SGrid.Options := SGrid.Options + [goEditing];
end;
procedure TForm1.DisableEdit;
begin
SGrid.Options := SGrid.Options - [goEditing];
end;
end.
|
unit Getter.TrimBasics;
interface
uses
SysUtils, Windows,
OSFile, OSFile.IoControl, OSFile.Handle, OS.Handle,
Partition, Getter.PartitionExtent, Getter.Filesystem.Name;
type
TTrimBasicsToInitialize = record
PaddingLBA: Integer;
LBAPerCluster: Cardinal;
StartLBA: UInt64;
end;
EUnknownPartition = class(Exception);
TTrimBasicsGetter = class abstract(TIoControlFile)
private
Handle: THandle;
FFileSystemName: String;
function GetStartLBA: UInt64;
protected
function GetFileSystemName: String;
function GetMinimumPrivilege: TCreateFileDesiredAccess; override;
const
BytePerLBA = 512;
public
constructor Create(const FileToGetAccess: String); override;
function IsPartitionMyResponsibility: Boolean; virtual; abstract;
function GetTrimBasicsToInitialize: TTrimBasicsToInitialize;
virtual;
procedure SetHandle(const Handle: THandle);
procedure SetFileSystemName(const FileSystemName: String);
end;
implementation
{ TTrimBasicsGetter }
constructor TTrimBasicsGetter.Create(const FileToGetAccess: String);
begin
inherited;
try
CreateHandle(FileToGetAccess, DesiredReadOnly);
except
on E: EOSError do;
else raise;
end;
end;
function TTrimBasicsGetter.GetFileSystemName: String;
var
FileSystemNameGetter: TFileSystemNameGetter;
begin
if FFileSystemName <> '' then
exit(FFileSystemName);
FileSystemNameGetter := TFileSystemNameGetter.Create(GetPathOfFileAccessing);
try
result := FileSystemNameGetter.GetFileSystemName;
finally
FreeAndNil(FileSystemNameGetter);
end;
end;
function TTrimBasicsGetter.GetMinimumPrivilege: TCreateFileDesiredAccess;
begin
result := TCreateFileDesiredAccess.DesiredReadOnly;
end;
function TTrimBasicsGetter.GetStartLBA: UInt64;
var
PartitionExtentGetter: TPartitionExtentGetter;
PartitionExtentList: TPartitionExtentList;
begin
PartitionExtentGetter :=
TPartitionExtentGetter.Create(GetPathOfFileAccessing);
try
PartitionExtentList := PartitionExtentGetter.GetPartitionExtentList;
result := PartitionExtentList[0].StartingOffset div BytePerLBA;
FreeAndNil(PartitionExtentList);
finally
FreeAndNil(PartitionExtentGetter);
end;
end;
function TTrimBasicsGetter.GetTrimBasicsToInitialize: TTrimBasicsToInitialize;
begin
result.StartLBA := GetStartLBA;
end;
procedure TTrimBasicsGetter.SetFileSystemName(const FileSystemName: String);
begin
FFileSystemName := FileSystemName;
end;
procedure TTrimBasicsGetter.SetHandle(const Handle: THandle);
begin
self.Handle := Handle;
end;
end.
|
unit Script;
interface
uses
Classes, Data;
type
TDBScript = class(TObject)
private
FLines: TStringList;
public
procedure Clear;
procedure SetHeader;
procedure AddInsert(Values: TValuesRec);
procedure SetFooter;
function GetText: AnsiString;
end;
implementation
//---------------------------------------------------------------------------
{ TDBScript }
procedure TDBScript.AddInsert(Values: TValuesRec);
var
ValuesLine, SQLLine: AnsiString;
begin
ValuesLine := Format('',
[Values.F1, Values.F2, Values.F3, Values.F4, Values.F5, Values.F6,
Values.F7, Values.F8, Values.F9, Values.F10, Values.F11, Values.F12,
Values.F13, Values.F14, Values.F15, Values.F16, Values.F17, Values.F18,
Values.F19, Values.F20, Values.F21, Values.F22, Values.F23, Values.F24,
Values.F25, Values.F26, Values.F27, Values.F28, Values.F29, Values.F30,
Values.F31, Values.F32, Values.F33, Values.F34, Values.F35, Values.F36,
Values.F37, Values.F38, Values.F39, Values.F40, Values.F41, Values.F42,
Values.F43, Values.F44, Values.F45, Values.F46, Values.F47, Values.F48,
Values.F49, Values.F50, Values.F51, Values.F52, Values.F53, Values.F54,
Values.F55, Values.F56, Values.F57, Values.F58, Values.F59, Values.F60,
Values.F61, Values.F62, Values.F63, Values.F64, Values.F65, Values.F66,
Values.F67, Values.F68]);
SQLLine := Format('insert into Table (id, value) values (%s);', [ValuesLine]);
FLines.Append(SQLLine);
end;
//---------------------------------------------------------------------------
procedure TDBScript.Clear;
begin
FLines.Clear();
end;
//---------------------------------------------------------------------------
function TDBScript.GetText: AnsiString;
var
I: Integer;
begin
Result := '';
for I := 0 to FLines.Count - 1 do
begin
Result := Result + #13#10 + FLines[I];
end;
end;
//---------------------------------------------------------------------------
procedure TDBScript.SetFooter;
begin
FLines.Append(S_SCRIPT_FOOTER);
end;
//---------------------------------------------------------------------------
procedure TDBScript.SetHeader;
begin
FLines.Insert(0, S_SCRIPT_HEADER);
end;
end.
|
unit DlgParamsRandom;
{$mode objfpc}{$H+}
interface
uses
Forms, ButtonPanel, StdCtrls,
SpectrumTypes, FrmRange, FrmRangePoints;
type
TRandomParamsDlg = class(TForm)
ButtonPanel1: TButtonPanel;
GroupBoxY: TGroupBox;
GroupBoxX: TGroupBox;
RangeX: TRangeFrm;
RangeY: TRangeFrm;
PointsX: TRangePointsFrm;
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormCreate(Sender: TObject);
private
FParams: PRandomSampleParams;
public
constructor Create(out AParams: TRandomSampleParams); reintroduce;
end;
implementation
uses
Controls,
OriMath, OriIniFile, OriUtils_Gui,
SpectrumStrings, SpectrumSettings;
{$R *.lfm}
var
StateLoaded: Boolean = False;
State: TRandomSampleParams;
procedure SaveState(Ini: TOriIniFile);
begin
with Ini, State do
begin
Section := 'PARAMS_RANDOM_SAMPLE';
WriteFloat('MinY', MinY);
WriteFloat('MaxY', MaxY);
SpectrumTypes.Save(X, 'X', Ini);
end;
end;
procedure LoadState;
var
Ini: TOriIniFile;
begin
Ini := TOriIniFile.Create;
with Ini, State do
try
Section := 'PARAMS_RANDOM_SAMPLE';
MinY := ReadFloat('MinY', 0);
MaxY := ReadFloat('MaxY', 100);
SpectrumTypes.Load(X, 'X', Ini);
finally
Free;
end;
end;
constructor TRandomParamsDlg.Create(out AParams: TRandomSampleParams);
begin
inherited Create(Application.MainForm);
FParams := @AParams;
end;
procedure TRandomParamsDlg.FormCreate(Sender: TObject);
begin
SetDefaultColor(Self);
ScaleDPI(Self, 96);
if not StateLoaded then LoadState;
RangeX.Min := State.X.Min;
RangeX.Max := State.X.Max;
PointsX.Step := State.X.Step;
PointsX.Points := State.X.Points;
PointsX.UseStep := State.X.UseStep;
RangeY.Min := State.MinY;
RangeY.Max := State.MaxY;
ActiveControl := RangeX.ActiveControl;
end;
procedure TRandomParamsDlg.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var
MinValue, MaxValue, Value: TValue;
begin
if ModalResult = mrOk then
begin
CanClose := False;
MinValue := RangeX.Min;
MaxValue := RangeX.Max;
if MinValue > MaxValue then
begin
RangeX.Max := MinValue;
RangeX.Min := MaxValue;
Swap(MinValue, MaxValue);
end
else if MinValue = MaxValue then
begin
ErrorDlg(ParamErr_ZeroRange);
Exit;
end;
if PointsX.UseStep then
begin
Value := PointsX.Step;
if Value < 0 then
begin
Value := -Value;
PointsX.Step := Value;
end;
if (Value = 0) or (Value >= MaxValue - MinValue) then
begin
ErrorDlg(ParamErr_WrongStep, [Value, MaxValue-MinValue]);
Exit;
end;
end;
CanClose := True;
end;
end;
procedure TRandomParamsDlg.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
State.X.Min := RangeX.Min;
State.X.Max := RangeX.Max;
State.X.Step := PointsX.Step;
State.X.Points := PointsX.Points;
State.X.UseStep := PointsX.UseStep;
State.MinY := RangeY.Min;
State.MaxY := RangeY.Max;
if (ModalResult = mrOk) and not StateLoaded then
begin
StateLoaded := True;
RegisterSaveStateProc(@SaveState);
end;
FParams^ := State;
CloseAction := caFree;
end;
end.
|
Unit DM;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DB, DBTables;
type
TDM1 = class(TDataModule)
Customer: TTable;
CustomerSource: TDataSource;
SQLCustomer: TQuery;
SQLOrders: TQuery;
OrdersSource: TDataSource;
SQLOrdersOrderNo: TFloatField;
SQLOrdersCustno: TFloatField;
SQLOrdersSaleDate: TDateTimeField;
SQLOrdersShipDate: TDateTimeField;
SQLOrdersEmpNo: TIntegerField;
SQLOrdersAmountPaid: TCurrencyField;
procedure DM1Create(Sender: TObject);
procedure SQLOrdersFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
public
{ The variable below will be accessible to to CustView (because it is
public and this unit is in its uses). It is used in
SQLOrdersFilterRecord to set the Filter amount for the Orders Query. }
OrdersFilterAmount: Extended;
end;
var
DM1: TDM1;
implementation
{$R *.DFM}
procedure TDM1.DM1Create(Sender: TObject);
begin
try
Screen.Cursor := crHourGlass;
SQLCustomer.Open;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TDM1.SQLOrdersFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
begin
{ This is only called if the Filtered property is True, set
dynamically by the CheckBox on the CustView form. }
Accept := SQLOrdersAmountPaid.Value >= OrdersFilterAmount;
end;
end.
|
unit GlobalVars;
interface
const
MenuState = 1; //Состояние меню
HelpState = 2; //Состояние вывода справки
ChooseMapState = 3; //Состояние выбора карты
InputNamesState = 4; //Состояние ввода ников
MainGameState = 5; //Состояние самой игры (бомбермена)
EditorState = 7; //Состояние редактора
HighscoreState = 10; //Состояние вывода рекордов
EndHighState = 11; //Состояние вывода результатов
DelayInput = 180; //Задержка между нажатиями клавиш
SlowEnemy = 1; //Тип монстра - обычный
FastEnemy = 2; //Тип монстра - быстрый
BlowupEnemy = 3; //Тип монстра - взрывающийся
TopOffset = 64; //Смещение отрисовки относительно вверха
MaxPlayers = 2; //Максимальное число игроков
type
plNames = array[1..MaxPlayers] of string;
plScores = array[1..MaxPlayers] of integer;
var
inputKeys : array[0..255] of boolean; //Состояние клавиш
LastChar : integer; //Последний нажатый символ
IsQuit : boolean; //Конец программы или нет
LastChange : longint; //Время последнего нажатия клавиши
_CurrentState : byte; //Текущее состояние
_CurrentMap : string; //Текущее имя карты
PlayerNames : plNames; //Имена игроков
PlayerScores : plScores; //Счет игроков
{Процедура смены текущего состояния }
{Параметры: toState - на какое состояние менять }
procedure ChangeState(toState : byte);
{Процедура очищающая данные состояния }
{Параметры: startPos - состояние }
procedure DisposeState(state : byte);
{Процедура инициализирующая данные состояния }
{Параметры: startPos - состояние }
procedure InitState(state : byte);
implementation
uses
Menu, Help, Highscore, MapMenu, InputNames, MainGame, Editor;
procedure DisposeState;
begin
case state of
MainGameState :
begin
DisposeMainGame();
end;
EndHighState :
begin
DisposeNewHighscore();
end;
end;
end;
procedure InitState;
begin
case state of
MenuState :
begin
InitMenu();
end;
HelpState:
begin
InitHelp();
end;
HighscoreState :
begin
InitHighscore();
end;
ChooseMapState :
begin
InitMapMenu();
end;
InputNamesState :
begin
InitInputNames();
end;
MainGameState :
begin
InitMainGame();
end;
EndHighState :
begin
InitNewHighscore();
end;
EditorState :
begin
InitEditor();
end;
end;
end;
procedure ChangeState;
begin
DisposeState(_CurrentState);
InitState(toState);
_CurrentState := toState;
end;
begin
end. |
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLObjectManager<p>
The object manager is used for registering classes together with a category,
description + icon, so that they can be displayed visually. This can then
be used by run-time or design-time scene editors for choosing which
scene objects to place into a scene.<p>
TODO: add some notification code, so that when a scene object is registered/
unregistered, any editor that is using the object manager can be notified.
<b>History : </b><font size=-1><ul>
<li>11/11/09 - DaStr - Improved FPC compatibility
(thanks Predator) (BugtrackerID = 2893580)
<li>25/07/09 - DaStr - Added $I GLScene.inc
<li>26/03/09 - DanB - Added PopulateMenuWithRegisteredSceneObjects procedure.
<li>14/03/09 - DanB - Created by moving TObjectManager in from GLSceneRegister.pas,
made some slight adjustments to allow resources being loaded
from separate packages.
</ul></font>
}
unit GLObjectManager;
interface
{$I GLScene.inc}
uses
System.Classes,
System.SysUtils,
VCL.Graphics,
VCL.Controls,
VCL.Menus,
//GLS
GLCrossPlatform,
GLScene;
type
PSceneObjectEntry = ^TGLSceneObjectEntry;
// holds a relation between an scene object class, its global identification,
// its location in the object stock and its icon reference
TGLSceneObjectEntry = record
ObjectClass: TGLSceneObjectClass;
Name: string; // type name of the object
Category: string; // category of object
Index, // index into "FSceneObjectList"
ImageIndex: Integer; // index into "FObjectIcons"
end;
// TObjectManager
//
TObjectManager = class(TComponent)
private
{ Private Declarations }
FSceneObjectList: TList;
FObjectIcons: TImageList; // a list of icons for scene objects
{$IFDEF MSWINDOWS}
FOverlayIndex, // indices into the object icon list
{$ENDIF}
FSceneRootIndex,
FCameraRootIndex,
FLightsourceRootIndex,
FObjectRootIndex: Integer;
protected
{ Protected Declarations }
procedure DestroySceneObjectList;
function FindSceneObjectClass(AObjectClass: TGLSceneObjectClass;
const ASceneObject: string = ''): PSceneObjectEntry;
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CreateDefaultObjectIcons(ResourceModule: Cardinal);
function GetClassFromIndex(Index: Integer): TGLSceneObjectClass;
function GetImageIndex(ASceneObject: TGLSceneObjectClass): Integer;
function GetCategory(ASceneObject: TGLSceneObjectClass): string;
procedure GetRegisteredSceneObjects(ObjectList: TStringList);
procedure PopulateMenuWithRegisteredSceneObjects(AMenuItem: TMenuItem; aClickEvent: TNotifyEvent);
//: Registers a stock object and adds it to the stock object list
procedure RegisterSceneObject(ASceneObject: TGLSceneObjectClass; const aName, aCategory: string); overload;
procedure RegisterSceneObject(ASceneObject: TGLSceneObjectClass; const aName, aCategory: string; aBitmap: TBitmap); overload;
procedure RegisterSceneObject(ASceneObject: TGLSceneObjectClass; const aName, aCategory: string; ResourceModule: Cardinal; ResourceName: string = ''); overload;
//: Unregisters a stock object and removes it from the stock object list
procedure UnRegisterSceneObject(ASceneObject: TGLSceneObjectClass);
property ObjectIcons: TImageList read FObjectIcons;
property SceneRootIndex: Integer read FSceneRootIndex;
property LightsourceRootIndex: Integer read FLightsourceRootIndex;
property CameraRootIndex: Integer read FCameraRootIndex;
property ObjectRootIndex: Integer read FObjectRootIndex;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
//----------------- TObjectManager ---------------------------------------------
// Create
//
constructor TObjectManager.Create(AOwner: TComponent);
begin
inherited;
FSceneObjectList := TList.Create;
// FObjectIcons Width + Height are set when you add the first bitmap
FObjectIcons := TImageList.CreateSize(16, 16);
end;
// Destroy
//
destructor TObjectManager.Destroy;
begin
DestroySceneObjectList;
FObjectIcons.Free;
inherited Destroy;
end;
// FindSceneObjectClass
//
function TObjectManager.FindSceneObjectClass(AObjectClass: TGLSceneObjectClass;
const aSceneObject: string = ''): PSceneObjectEntry;
var
I: Integer;
Found: Boolean;
begin
Result := nil;
Found := False;
with FSceneObjectList do
begin
for I := 0 to Count - 1 do
with TGLSceneObjectEntry(Items[I]^) do
if (ObjectClass = AObjectClass) and (Length(ASceneObject) = 0)
or (CompareText(Name, ASceneObject) = 0) then
begin
Found := True;
Break;
end;
if Found then
Result := Items[I];
end;
end;
// GetClassFromIndex
//
function TObjectManager.GetClassFromIndex(Index: Integer): TGLSceneObjectClass;
begin
if Index < 0 then
Index := 0;
if Index > FSceneObjectList.Count - 1 then
Index := FSceneObjectList.Count - 1;
Result := TGLSceneObjectEntry(FSceneObjectList.Items[Index + 1]^).ObjectClass;
end;
// GetImageIndex
//
function TObjectManager.GetImageIndex(ASceneObject: TGLSceneObjectClass): Integer;
var
classEntry: PSceneObjectEntry;
begin
classEntry := FindSceneObjectClass(ASceneObject);
if Assigned(classEntry) then
Result := classEntry^.ImageIndex
else
Result := 0;
end;
// GetCategory
//
function TObjectManager.GetCategory(ASceneObject: TGLSceneObjectClass): string;
var
classEntry: PSceneObjectEntry;
begin
classEntry := FindSceneObjectClass(ASceneObject);
if Assigned(classEntry) then
Result := classEntry^.Category
else
Result := '';
end;
// GetRegisteredSceneObjects
//
procedure TObjectManager.GetRegisteredSceneObjects(objectList: TStringList);
var
i: Integer;
begin
if Assigned(objectList) then
with objectList do
begin
Clear;
for i := 0 to FSceneObjectList.Count - 1 do
with TGLSceneObjectEntry(FSceneObjectList.Items[I]^) do
AddObject(Name, Pointer(ObjectClass));
end;
end;
procedure TObjectManager.PopulateMenuWithRegisteredSceneObjects(AMenuItem: TMenuItem;
AClickEvent: TNotifyEvent);
var
ObjectList: TStringList;
i, j: Integer;
Item, CurrentParent: TMenuItem;
CurrentCategory: string;
Soc: TGLSceneObjectClass;
begin
ObjectList := TStringList.Create;
try
GetRegisteredSceneObjects(ObjectList);
for i := 0 to ObjectList.Count - 1 do
if ObjectList[i] <> '' then
begin
CurrentCategory := GetCategory(TGLSceneObjectClass(ObjectList.Objects[i]));
if CurrentCategory = '' then
CurrentParent := AMenuItem
else
begin
CurrentParent := NewItem(CurrentCategory, 0, False, True, nil, 0, '');
AMenuItem.Add(CurrentParent);
end;
for j := i to ObjectList.Count - 1 do
if ObjectList[j] <> '' then
begin
Soc := TGLSceneObjectClass(ObjectList.Objects[j]);
if CurrentCategory = GetCategory(Soc) then
begin
Item := NewItem(objectList[j], 0, False, True, AClickEvent, 0, '');
Item.ImageIndex := GetImageIndex(Soc);
CurrentParent.Add(Item);
ObjectList[j] := '';
if CurrentCategory = '' then
Break;
end;
end;
end;
finally
ObjectList.Free;
end;
end;
// RegisterSceneObject
//
procedure TObjectManager.RegisterSceneObject(ASceneObject: TGLSceneObjectClass;
const aName, aCategory: string);
var
resBitmapName: string;
bmp: TBitmap;
begin
// Since no resource name was provided, assume it's the same as class name
resBitmapName := ASceneObject.ClassName;
bmp := TBitmap.Create;
try
// Try loading bitmap from module that class is in
GLLoadBitmapFromInstance(FindClassHInstance(ASceneObject), bmp, resBitmapName);
if bmp.Width = 0 then
GLLoadBitmapFromInstance(HInstance, bmp, resBitmapName);
// If resource was found, register scene object with bitmap
if bmp.Width <> 0 then
begin
RegisterSceneObject(ASceneObject, aName, aCategory, bmp);
end
else
// Resource not found, so register without bitmap
RegisterSceneObject(ASceneObject, aName, aCategory, nil);
finally
bmp.Free;
end;
end;
// RegisterSceneObject
//
procedure TObjectManager.RegisterSceneObject(ASceneObject: TGLSceneObjectClass; const aName, aCategory: string; aBitmap: TBitmap);
var
newEntry: PSceneObjectEntry;
bmp: TBitmap;
begin
if Assigned(RegisterNoIconProc) then
RegisterNoIcon([aSceneObject]);
with FSceneObjectList do
begin
// make sure no class is registered twice
if Assigned(FindSceneObjectClass(ASceneObject, AName)) then
Exit;
New(NewEntry);
try
with NewEntry^ do
begin
// object stock stuff
// registered objects list stuff
ObjectClass := ASceneObject;
NewEntry^.Name := aName;
NewEntry^.Category := aCategory;
Index := FSceneObjectList.Count;
if Assigned(aBitmap) then
begin
bmp := TBitmap.Create;
try
// If we just add the bitmap, and it has different dimensions, then
// all icons will be cleared, so ensure this doesn't happen
bmp.PixelFormat := glpf24bit;
bmp.Width := FObjectIcons.Width;
bmp.Height := FObjectIcons.Height;
bmp.Canvas.Draw(0, 0, ABitmap);
FObjectIcons.AddMasked(bmp, bmp.Canvas.Pixels[0, 0]);
ImageIndex := FObjectIcons.Count - 1;
finally
bmp.free;
end;
end
else
ImageIndex := 0;
end;
Add(NewEntry);
finally
//
end;
end;
end;
// RegisterSceneObject
//
procedure TObjectManager.RegisterSceneObject(ASceneObject: TGLSceneObjectClass; const aName, aCategory: string; ResourceModule: Cardinal; ResourceName: string = '');
var
bmp: TBitmap;
resBitmapName: string;
begin
if ResourceName = '' then
resBitmapName := ASceneObject.ClassName
else
resBitmapName := ResourceName;
bmp := TBitmap.Create;
try
// Load resource
if (ResourceModule <> 0) then
GLLoadBitmapFromInstance(ResourceModule, bmp, resBitmapName);
// If the resource was found, then register scene object using the bitmap
if bmp.Width > 0 then
RegisterSceneObject(ASceneObject, aName, aCategory, bmp)
else
// Register the scene object with no icon
RegisterSceneObject(ASceneObject, aName, aCategory, nil);
finally
bmp.Free;
end;
end;
// UnRegisterSceneObject
//
procedure TObjectManager.UnRegisterSceneObject(ASceneObject: TGLSceneObjectClass);
var
oldEntry: PSceneObjectEntry;
begin
// find the class in the scene object list
OldEntry := FindSceneObjectClass(ASceneObject);
// found?
if assigned(OldEntry) then
begin
// remove its entry from the list of registered objects
FSceneObjectList.Remove(OldEntry);
// finally free the memory for the entry
Dispose(OldEntry);
end;
end;
// CreateDefaultObjectIcons
//
procedure TObjectManager.CreateDefaultObjectIcons(ResourceModule: Cardinal);
var
bmp: TBitmap;
begin
bmp := TBitmap.Create;
with FObjectIcons, bmp.Canvas do
begin
try
// There's a more direct way for loading images into the image list, but
// the image quality suffers too much
{$IFDEF WIN32}
GLLoadBitmapFromInstance(ResourceModule, bmp, 'gls_cross');
FOverlayIndex := AddMasked(bmp, Pixels[0, 0]);
Overlay(FOverlayIndex, 0); // used as indicator for disabled objects
{$ENDIF}
GLLoadBitmapFromInstance(ResourceModule, bmp, 'gls_root');
FSceneRootIndex := AddMasked(bmp, Pixels[0, 0]);
GLLoadBitmapFromInstance(ResourceModule, bmp, 'gls_camera');
FCameraRootIndex := AddMasked(bmp, Pixels[0, 0]);
GLLoadBitmapFromInstance(ResourceModule, bmp, 'gls_lights');
FLightsourceRootIndex := AddMasked(bmp, Pixels[0, 0]);
GLLoadBitmapFromInstance(ResourceModule, bmp, 'gls_objects');
FObjectRootIndex := AddMasked(bmp, Pixels[0, 0]);
finally
bmp.Free;
end;
end;
end;
// DestroySceneObjectList
//
procedure TObjectManager.DestroySceneObjectList;
var
i: Integer;
begin
with FSceneObjectList do
begin
for i := 0 to Count - 1 do
Dispose(PSceneObjectEntry(Items[I]));
Free;
end;
end;
initialization
end.
|
unit u_xml_events;
{$mode objfpc}{$H+}
interface
uses Classes, SysUtils, DOM, u_xml;
type
{ TXMLTimerType }
TXMLTimerMode = (tmUp, tmDown, tmRecurrent);
TXMLTimerType = class(TDOMElement)
private
function Get_Estimated_End_Time: TDateTime;
function Get_Frequency: cardinal;
function Get_Mode: TXMLTimerMode;
function Get_Range: string;
function Get_Remaining: cardinal;
function Get_start_time: TDateTime;
function Get_Status: string;
function Get_Tag: AnsiString;
function Get_Target: string;
procedure Set_Estimated_End_Time(const AValue: TDateTime);
procedure Set_Frequency(const AValue: cardinal);
procedure Set_Mode(const AValue: TXMLTimerMode);
procedure Set_Remaining(const AValue: cardinal);
procedure Set_start_time(const AValue: TDateTime);
procedure Set_Status(const AValue: string);
procedure Set_Tag(const AValue: AnsiString);
procedure Set_Target(const AValue: string);
public
property Target : string read Get_Target write Set_Target;
property start_time : TDateTime read Get_start_time write Set_start_time;
property Remaining : cardinal read Get_Remaining write Set_Remaining;
property Status : string read Get_Status write Set_Status;
property Mode : TXMLTimerMode read Get_Mode write Set_Mode;
function ModeAsString : string;
property Frequency : cardinal read Get_Frequency write Set_Frequency;
property Estimated_End_Time : TDateTime read Get_Estimated_End_Time write Set_Estimated_End_Time;
property Range : string read Get_Range;
property Name : AnsiString read Get_Tag write Set_Tag;
end;
TXMLTimersType = specialize TXMLElementList<TXMLTimerType>;
{ TXMLEventType }
TXMLEventType = class(TDOMElement)
private
function Get_dow: AnsiString;
function Get_End_Time: AnsiString;
function Get_EventDateTime: ansistring;
function Get_EventRunTime: ansistring;
function Get_Init: ansistring;
function Get_interval: ansistring;
function Get_Param: ansistring;
function Get_randomtime: ansistring;
function Get_recurring: boolean;
function Get_runsub: ansistring;
function Get_Start_Time: AnsiString;
function Get_Tag: AnsiString;
protected
public
property tag : AnsiString read Get_Tag;
property start_time : AnsiString read Get_Start_Time;
property end_time : AnsiString read Get_End_Time;
property dow : AnsiString read Get_dow;
property randomtime : ansistring read Get_randomtime;
property recurring : boolean read Get_recurring;
property interval : ansistring read Get_interval;
property runsub : ansistring read Get_runsub;
property param : ansistring read Get_Param;
property eventdatetime : ansistring read Get_EventDateTime;
property eventruntime : ansistring read Get_EventRunTime;
property init : ansistring read Get_Init;
end;
TXMLEventsType = specialize TXMLElementList<TXMLEventType>;
var Eventsfile : TXMLeventsType;
implementation //=========================================================================
uses XMLRead, XMLWrite,uxPLConst;
var document : TXMLDocument;
//========================================================================================
function TXMLEventType.Get_dow: AnsiString;
begin Result := GetAttribute(K_XML_STR_Dow); end;
function TXMLEventType.Get_End_Time: AnsiString;
begin Result := GetAttribute(K_XML_STR_Endtime); end;
function TXMLEventType.Get_EventDateTime: ansistring;
begin Result := GetAttribute(K_XML_STR_Eventdatetim); end;
function TXMLEventType.Get_EventRunTime: ansistring;
begin Result := GetAttribute(K_XML_STR_Eventruntime); end;
function TXMLEventType.Get_Init: ansistring;
begin Result := GetAttribute(K_XML_STR_Init); end;
function TXMLEventType.Get_interval: ansistring;
begin Result := GetAttribute(K_XML_STR_Interval); end;
function TXMLEventType.Get_Param: ansistring;
begin Result := GetAttribute(K_XML_STR_Param); end;
function TXMLEventType.Get_randomtime: ansistring;
begin Result := GetAttribute(K_XML_STR_Randomtime); end;
function TXMLEventType.Get_recurring: boolean;
begin Result := GetAttribute(K_XML_STR_Recurring)=K_STR_TRUE; end;
function TXMLEventType.Get_runsub: ansistring;
begin Result := GetAttribute(K_XML_STR_Runsub); end;
function TXMLEventType.Get_Start_Time: AnsiString;
begin Result := GetAttribute(K_XML_STR_Starttime); end;
function TXMLEventType.Get_Tag: AnsiString;
begin Result := GetAttribute(K_XML_STR_Tag); end;
// Unit initialization ===================================================================
{ TXMLTimerType }
function TXMLTimerType.Get_Estimated_End_Time: TDateTime;
begin Result := StrToDateTime(GetAttribute(K_XML_STR_ESTIMATED_END_TIME)); end;
function TXMLTimerType.Get_Frequency: cardinal;
begin Result := StrToInt(GetAttribute(K_XML_STR_FREQUENCY)); end;
function TXMLTimerType.Get_Mode: TXMLTimerMode;
begin Result := TXMLTimerMode(GetAttribute(K_XML_STR_MODE)); end;
function TXMLTimerType.Get_Range: string;
begin if Target = '*' then result := 'global' else result := 'local'; end;
function TXMLTimerType.Get_Remaining: cardinal;
begin Result := StrToInt(GetAttribute(K_XML_STR_REMAINING)); end;
function TXMLTimerType.Get_start_time: TDateTime;
begin Result := StrToDateTime(GetAttribute(K_XML_STR_Starttime)); end;
function TXMLTimerType.Get_Status: string;
begin Result := GetAttribute(K_XML_STR_Status); end;
function TXMLTimerType.Get_Tag: AnsiString;
begin Result := GetAttribute(K_XML_STR_Tag); end;
function TXMLTimerType.Get_Target: string;
begin Result := GetAttribute(K_XML_STR_Msg_target); end;
procedure TXMLTimerType.Set_Estimated_End_Time(const AValue: TDateTime);
begin SetAttribute(K_XML_STR_ESTIMATED_END_TIME, DateTimeToStr(aValue)); end;
procedure TXMLTimerType.Set_Frequency(const AValue: cardinal);
begin SetAttribute(K_XML_STR_FREQUENCY, IntToStr(aValue)); end;
procedure TXMLTimerType.Set_Mode(const AValue: TXMLTimerMode);
begin SetAttribute(K_XML_STR_MODE, IntToStr(Ord(aValue))); end;
procedure TXMLTimerType.Set_Remaining(const AValue: cardinal);
begin SetAttribute(K_XML_STR_REMAINING, IntToStr(aValue)); end;
procedure TXMLTimerType.Set_start_time(const AValue: TDateTime);
begin SetAttribute(K_XML_STR_Starttime, DateTimeToStr(aValue)); end;
procedure TXMLTimerType.Set_Status(const AValue: string);
begin SetAttribute(K_XML_STR_Status, aValue); end;
procedure TXMLTimerType.Set_Tag(const AValue: AnsiString);
begin SetAttribute(K_XML_STR_TAG, aValue); end;
procedure TXMLTimerType.Set_Target(const AValue: string);
begin SetAttribute(K_XML_STR_Msg_target, aValue); end;
function TXMLTimerType.ModeAsString: string;
begin
case Mode of
tmUp : result := 'ascending';
tmDown : result := 'descending';
tmRecurrent : result := 'recurrent';
end;
end;
//initialization
// document := TXMLDocument.Create;
// ReadXMLFile(document,'C:\Program Files\xPL\xPLHal 2.0 for Windows\data\xplhal_events.xml');
// eventsfile := TXMLeventsType.Create(document, K_XML_STR_Global);
//
//finalization
// WriteXMLFile(document,'C:\Program Files\xPL\xPLHal 2.0 for Windows\data\xplhal_events.xml');
// eventsfile.destroy;
// document.destroy;
end.
|
unit ThreadToView.Trim;
interface
uses
SysUtils, Classes, Windows,
Global.LanguageString;
type
TTrimProgress = record
CurrentPartition: Integer;
PartitionCount: Integer;
end;
TTrimSynchronization = record
IsUIInteractionNeeded: Boolean;
ThreadToSynchronize: TThread;
Progress: TTrimProgress;
end;
TTrimThreadToView = class
public
constructor Create(TrimSynchronizationToApply: TTrimSynchronization);
procedure ApplyOriginalUI;
procedure ApplyProgressToUI(ProgressToApply: Integer);
procedure ApplyNextDriveStartToUI(ProgressToApply: Integer);
private
Progress: Integer;
TrimSynchronization: TTrimSynchronization;
procedure SynchronizedApplyProgressToUI;
procedure SynchronizedApplyOriginalUI;
procedure SynchronizedApplyNextDriveStartToUI;
function IsTrimInProgress: Boolean;
procedure SynchronizedApplyProgressToLabel;
end;
implementation
uses
Form.Main;
constructor TTrimThreadToView.Create(
TrimSynchronizationToApply: TTrimSynchronization);
begin
TrimSynchronization := TrimSynchronizationToApply;
end;
procedure TTrimThreadToView.ApplyProgressToUI(ProgressToApply: Integer);
begin
if TrimSynchronization.IsUIInteractionNeeded then
begin
Progress := ProgressToApply;
TThread.Queue(
TrimSynchronization.ThreadToSynchronize,
SynchronizedApplyProgressToUI);
end;
end;
procedure TTrimThreadToView.ApplyNextDriveStartToUI(ProgressToApply: Integer);
begin
if TrimSynchronization.IsUIInteractionNeeded then
begin
Progress := ProgressToApply;
TThread.Queue(
TrimSynchronization.ThreadToSynchronize,
SynchronizedApplyNextDriveStartToUI);
end;
end;
procedure TTrimThreadToView.ApplyOriginalUI;
begin
if TrimSynchronization.IsUIInteractionNeeded then
begin
TThread.Synchronize(
TrimSynchronization.ThreadToSynchronize,
SynchronizedApplyOriginalUI);
end;
end;
procedure TTrimThreadToView.SynchronizedApplyProgressToUI;
begin
fMain.pDownload.Position := Progress;
end;
function TTrimThreadToView.IsTrimInProgress: Boolean;
begin
result := TrimSynchronization.Progress.CurrentPartition <=
TrimSynchronization.Progress.PartitionCount;
end;
procedure TTrimThreadToView.SynchronizedApplyProgressToLabel;
begin
fMain.lProgress.Caption :=
CapProg1[CurrLang] +
IntToStr(TrimSynchronization.Progress.CurrentPartition) + ' / ' +
IntToStr(TrimSynchronization.Progress.PartitionCount);
end;
procedure TTrimThreadToView.SynchronizedApplyOriginalUI;
begin
fMain.pDownload.Position := 0;
fMain.gTrim.Visible := true;
end;
procedure TTrimThreadToView.SynchronizedApplyNextDriveStartToUI;
begin
SynchronizedApplyProgressToUI;
if TrimSynchronization.Progress.CurrentPartition < 0 then
exit;
if IsTrimInProgress then
SynchronizedApplyProgressToLabel;
end;
end.
|
program Sample;
begin
WriteLn(1);
WriteLn(2);
end.
|
unit amqp.api;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses {$IFDEF FPC}SysUtils,{$Else} System.SysUtils, {$ENDIF} amqp.framing, AMQP.Types;
function amqp_basic_publish( state : Pamqp_connection_state; channel : amqp_channel_t;
exchange, routing_key : Tamqp_bytes;
mandatory, immediate : amqp_boolean_t;
properties: Pamqp_basic_properties;
body : Tamqp_bytes):integer;
function amqp_channel_close( state : Pamqp_connection_state; channel : amqp_channel_t; code : integer): Tamqp_rpc_reply;
function amqp_connection_close( state : Pamqp_connection_state; code : integer):Tamqp_rpc_reply;
implementation
uses amqp.socket, amqp.connection, amqp.privt, amqp.time;
function amqp_connection_close( state : Pamqp_connection_state; code : integer):Tamqp_rpc_reply;
var
codestr : array[0..12] of AMQPChar;
replies : Tamqp_methods;
req : Tamqp_channel_close;
s: Ansistring;
i, Size: Integer;
begin
SetLength(replies,2);
replies[0] := AMQP_CONNECTION_CLOSE_OK_METHOD;
replies[1] := 0;
if (code < 0) or (code > UINT16_MAX) then
Exit(amqp_rpc_reply_error(AMQP_STATUS_INVALID_PARAMETER));
req.reply_code := uint16_t(code);
req.reply_text.bytes := @codestr;
s := Format('%d', [code]);
size:=Length(S);
For i:=1 To size Do
Begin
codestr[i-1]:=S[i];
If (i = size) Then Break;
End;
req.reply_text.len := size;
req.class_id := 0;
req.method_id := 0;
Result := amqp_simple_rpc(state, 0, AMQP_CONNECTION_CLOSE_METHOD, replies, @req);
SetLength(replies,0);
end;
function amqp_channel_close( state : Pamqp_connection_state; channel : amqp_channel_t; code : integer): Tamqp_rpc_reply;
var
codestr : array[0..12] of AMQPChar;
replies : Tamqp_methods;
req : Tamqp_channel_close;
s: Ansistring;
i, Size: Integer;
begin
SetLength(replies,2);
replies[0] := AMQP_CHANNEL_CLOSE_OK_METHOD;
replies[1] := 0;
if (code < 0) or (code > UINT16_MAX) then
Exit(amqp_rpc_reply_error(AMQP_STATUS_INVALID_PARAMETER));
req.reply_code := uint16_t(code);
req.reply_text.bytes := @codestr;
s := Format('%d', [code]);
size:=Length(S);
For i:=1 To size Do
Begin
codestr[i-1]:=S[i];
If (i = size) Then Break;
End;
req.reply_text.len := size;
req.class_id := 0;
req.method_id := 0;
Result := amqp_simple_rpc(state, channel, AMQP_CHANNEL_CLOSE_METHOD, replies, @req);
SetLength(replies,0);
end;
function amqp_basic_publish( state : Pamqp_connection_state; channel : amqp_channel_t;
exchange, routing_key : Tamqp_bytes;
mandatory, immediate : amqp_boolean_t;
properties: Pamqp_basic_properties;
body : Tamqp_bytes):integer;
var
f : Tamqp_frame;
body_offset,
usable_body_payload_size : size_t;
res,
flagz : integer;
m : Tamqp_basic_publish;
default_properties : Tamqp_basic_properties;
remaining : size_t;
begin
usable_body_payload_size := state.frame_max - (HEADER_SIZE + FOOTER_SIZE);
m.exchange := exchange;
m.routing_key := routing_key;
m.mandatory := mandatory;
m.immediate := immediate;
m.ticket := 0;
{ TODO(alanxz): this heartbeat check is happening in the wrong place, it
* should really be done in amqp_try_send/writev }
res := amqp_time_has_past(state.next_recv_heartbeat);
if Int(AMQP_STATUS_TIMER_FAILURE) = res then
Exit(res)
else
if (Int(AMQP_STATUS_TIMEOUT) = res) then
begin
res := amqp_try_recv(state);
if Int(AMQP_STATUS_TIMEOUT) = res then
Exit(Int(AMQP_STATUS_HEARTBEAT_TIMEOUT))
else if int(AMQP_STATUS_OK) <> res then
Exit(res);
end;
res := amqp_send_method_inner(state, channel, AMQP_BASIC_PUBLISH_METHOD, @m,
Int(AMQP_SF_MORE), Tamqp_time.infinite());
if res < 0 then
Exit(res);
if properties = nil then
begin
memset(default_properties, 0, sizeof(default_properties));
properties := @default_properties;
end;
f.frame_type := AMQP_FRAME_HEADER;
f.channel := channel;
f.payload.properties.class_id := AMQP_BASIC_CLASS;
f.payload.properties.body_size := body.len;
f.payload.properties.decoded := Pointer(properties);
if body.len > 0 then
flagz := Int(AMQP_SF_MORE)
else
flagz := Int(AMQP_SF_NONE);
res := amqp_send_frame_inner(state, f, flagz, Tamqp_time.infinite);
if res < 0 then
Exit(res);
body_offset := 0;
while body_offset < body.len do
begin
remaining := body.len - body_offset;
if remaining = 0 then
break;
f.frame_type := AMQP_FRAME_BODY;
f.channel := channel;
f.payload.body_fragment.bytes := amqp_offset(body.bytes, body_offset);
if remaining >= usable_body_payload_size then
begin
f.payload.body_fragment.len := usable_body_payload_size;
flagz := Int(AMQP_SF_MORE);
end
else
begin
f.payload.body_fragment.len := remaining;
flagz := Int(AMQP_SF_NONE);
end;
body_offset := body_offset + f.payload.body_fragment.len;
res := amqp_send_frame_inner(state, f, flagz, Tamqp_time.infinite());
if res < 0 then
Exit(res);
end;
Result := Int(AMQP_STATUS_OK);
end;
initialization
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit InetDesignResStrs;
interface
resourcestring
// Ports wizard page
sPortsPageInfo = 'Click a field for more information';
sPortsPageTitle = 'Port Number';
sPortsPageDescription = 'Specify the port that will be used by the web application to listen for client requests. ' +
'Use "Test" button to make sure the port is not already in use on this computer.';
sHTTPPortInfo = 'HTTP port. Port 80 is the well known HTTP port number used by web servers such as IIS.';
sHTTPSInfo = 'The HTTPS checkbox enables use of the HTTP(Secure) protocol. Port 443 is the well known HTTPS port number used by IIS.';
sPEMFileFilter = 'PEM File(*.pem;*.crt;*.cer)|*.pem|Any file (*.*)|*.*';
sPEMKeyFileFilter = 'PEM File(*.pem;*.crt;*.cer;*.key)|*.pem;*.crt;*.cer;*.key|Any file (*.*)|*.*';
sPEMFileNotFound = 'File "%s" not found';
SPEMOpenFileTitle = 'Open';
// CertFilesPage
sCertFilesPageInfo = 'Click a field for more information';
sCertFilesPageTitle = 'X.509 Certificates';
sCertFilesPageDescription = 'Specify the X.509 certificate and key files that will be used to secure an HTTPS connection. ' +
'After specifying a certificate and key file, use the "Test" button to validate.';
sCertFileInfo = 'Certificate file. This is the public key of your certificate.';
sRootCertFileINfo = 'Root Certificate file. Certificate file identifying a Root Certificate Authority.';
sKeyFileInfo = 'Certificate key file. This is the private key of your certificate.';
sKeyFilePasswordInfo = 'Certficate key password. This is the password used to encrypt the private key.';
sTestCertFilesOK = 'Test succeeded';
sCertFilesTestInfo = 'Click the "Test" button to create a temporary server and client, using the specified certificate and key files.';
sISAPIInfo = 'An ISAPI library integrates with IIS. IIS has support for HTTP and HTTPS.';
sCGIInfo = 'A CGI executable integrates with web server. ' +
'Note that CGI is typically slower and more difficult to debug than ISAPI or Apache module.';
sIndyFormInfo = 'A stand-alone WebBroker application is a web server that displays a form. It Supports HTTP using an Indy HTTP server component.';
sIndyConsoleInfo = 'A stand-alone WebBroker console application is a web server that has a text-only user interface. It Supports HTTP using an Indy HTTP server component.';
sWebAppDebugExeInfo = 'A Web App Debugger executable integrate with the Web App Debugger, and support HTTP';
sWebServerPageTitle = 'WebBroker Project Type';
sWebServerPageDescription = 'Select the type of WebBroker project';
sCoClassNameInfo = 'The class name is an identifier that will be used in the URL to connect to a particular Web App Debugger executable.';
// Apache Page
sApacheInfo = 'An Apache module. Apache has support for HTTP and HTTPS. Only Apache version 2.4 is supported on Linux.';
sApachePageTitle = 'Apache Module Options';
sApachePageDescription = 'Provide data to create the Apache module';
sVersionInfo = 'Apache server version';
sModuleInfo = 'Apache module and handler name';
sUnitInfo = 'Apache unit aded to the Apache project';
sLibraryInfo = 'TODO LibraryInfo';
sInvalidModule = '"%s" is not a valid Module Name';
sApacheVersion20 = 'Apache version 2.0';
sApacheVersion22 = 'Apache version 2.2';
sApacheVersion24 = 'Apache version 2.4';
//FramWork Page
sFrameWorkInfo = 'Specify the type of application that will be created';
sFrameWorkPageTitle = 'Application Type';
sFrameWorkPageDescription = 'Select the type of application to be created';
sVCLInfo = 'Creates a VCL application';
sFMInfo = 'Creates a FireMonkey application';
//Platform Page
sPlatformWorkInfo = 'Specify the type of platform for the application';
sPlatformPageTitle = 'Platform';
sPlatformPageDescription = 'Select the platform for the application to be created';
sWindowsInfo = 'Creates a Windows application';
sLinuxInfo = 'Creates a Linux application';
const
sDefaultModule = 'webbroker_module'; //Do not localize
sDefaultFileName = 'mod_webbroker'; //Do not localize
sApacheUnit20 = 'Web.HTTPD20Impl'; //Do not localize
sApacheUnit22 = 'Web.HTTPD22Impl'; //Do not localize
sApacheUnit24 = 'Web.HTTPD24Impl'; //Do not localize
ApacheDefaultVersion = 2;
ApacheVersionCount = 2;
ApacheLinuxMinVersionIndex = 2;
sApacheVersion : Array[0 .. ApacheVersionCount] of string = (sApacheVersion20, sApacheVersion22, sApacheVersion24);
sApacheImpl : Array[0 .. ApacheVersionCount] of string = (sApacheUnit20, sApacheUnit22, sApacheUnit24);
implementation
end.
|
unit SolidLongInput;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls, FMX.Graphics,
FMX.Effects, System.UITypes, LongInput, ColorClass;
type
TSolidLongInput = class(TLongInput)
private
{ Private declarations }
protected
{ Protected declarations }
FShadow: TShadowEffect;
FStrokeGradientDefocus: TGradient;
FFocusEffect: TGlowEffect;
{ Events settings }
procedure OnEditEnter(Sender: TObject); override;
procedure OnEditExit(Sender: TObject); override;
procedure SetFText(const Value: String); override;
function GetFSelectedColor: TAlphaColor;
procedure SetFSelectedColor(const Value: TAlphaColor);
procedure HideEffectValidation();
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ValidateText(): Boolean;
procedure Clear; override;
procedure Select();
procedure Deselect();
published
{ Published declarations }
property SelectedColor: TAlphaColor read GetFSelectedColor write SetFSelectedColor;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Componentes Customizados', [TSolidLongInput]);
end;
{ TSolidAppleEdit }
constructor TSolidLongInput.Create(AOwner: TComponent);
begin
inherited;
FDarkTheme := TAlphaColor($FF424242);
FLightTheme := TAlphaColor($FFFFFFFF);
FSelectedTheme := TAlphaColor($FF006CD0);
FFocusEffect := TGlowEffect.Create(Self);
Self.AddObject(FFocusEffect);
FFocusEffect.Enabled := true;
FFocusEffect.GlowColor := FSelectedTheme;
FFocusEffect.Opacity := 0;
FFocusEffect.Softness := 0.1;
FFocusEffect.SetSubComponent(true);
FFocusEffect.Stored := false;
FBackground.Stroke.Kind := TBrushKind.Gradient;
FBackground.Stroke.Thickness := 1;
FBackground.Fill.Color := TAlphaColor($FFFFFFFF);
FStrokeGradientDefocus := TGradient.Create;
with FStrokeGradientDefocus do
begin
Color := $FFD2D2D2;
Color1 := $FFBABABA;
end;
FBackground.Stroke.Gradient := FStrokeGradientDefocus;
{ Shadow }
FShadow := TShadowEffect.Create(Self);
FBackground.AddObject(FShadow);
FShadow.Direction := 90;
FShadow.Distance := 0.7;
FShadow.Opacity := 0.1;
FShadow.Softness := 0.1;
FShadow.Enabled := true;
end;
procedure TSolidLongInput.Select;
begin
FFocusEffect.GlowColor := FSelectedTheme;
FFocusEffect.AnimateFloat('Opacity', 1, 0.2);
end;
procedure TSolidLongInput.Deselect;
begin
FFocusEffect.AnimateFloat('Opacity', 0, 0.2);
if FInvalid then
ValidateText();
end;
destructor TSolidLongInput.Destroy;
begin
if Assigned(FStrokeGradientDefocus) then
FStrokeGradientDefocus.Free;
if Assigned(FShadow) then
FShadow.Free;
if Assigned(FFocusEffect) then
FFocusEffect.Free;
inherited;
end;
procedure TSolidLongInput.OnEditEnter(Sender: TObject);
begin
Select;
inherited;
end;
procedure TSolidLongInput.OnEditExit(Sender: TObject);
begin
Deselect;
inherited;
end;
function TSolidLongInput.GetFSelectedColor: TAlphaColor;
begin
Result := FSelectedTheme;
end;
procedure TSolidLongInput.SetFSelectedColor(const Value: TAlphaColor);
begin
FSelectedTheme := Value;
end;
procedure TSolidLongInput.SetFText(const Value: String);
begin
inherited;
if not Self.Text.Equals('') then
HideEffectValidation();
end;
procedure TSolidLongInput.Clear;
begin
inherited;
HideEffectValidation();
end;
function TSolidLongInput.ValidateText: Boolean;
begin
if not Self.Validate then
begin
if FTextPromptAnimation then
FLabel.AnimateColor('TextSettings.FontColor', SOLID_ERROR_COLOR, 0.25, TAnimationType.InOut,
TInterpolationType.Circular);
FFocusEffect.GlowColor := SOLID_ERROR_COLOR;
FFocusEffect.AnimateFloat('Opacity', 1, 0.2);
end;
FInvalid := not Self.Validate;
Result := Self.Validate;
end;
procedure TSolidLongInput.HideEffectValidation;
begin
if FFocusEffect.GlowColor = SOLID_ERROR_COLOR then
begin
if FTextPromptAnimation then
FLabel.AnimateColor('TextSettings.FontColor', TAlphaColor($FF999999), 0, TAnimationType.InOut,
TInterpolationType.Circular);
FFocusEffect.GlowColor := FSelectedTheme;
FFocusEffect.AnimateFloat('Opacity', 0, 0.2);
end;
end;
end.
|
// ==============================================================
//
// This unit contains the routine for displaying the player stats
// Note: It requires TALProgressBar.
// Can be found at:
// http://store77.googlecode.com/svn/trunk/GOLD/LUX-source/ALProgressBar.pas
//
// Esta unit contém a rotina para mostrar o status do jogador
// Nota: Requer o componente TALProgressBar.
// Que pode ser encontrado em:
// http://store77.googlecode.com/svn/trunk/GOLD/LUX-source/ALProgressBar.pas
//
// ==============================================================
unit uFrameStatusPlayer;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ALProgressBar, ExtCtrls, Menus, uWarrior;
type
TFrameStatusPlayer = class(TFrame)
// Some display stuff
// Componentes para exibição
MainPanel: TPanel;
StatusImage: TImage;
PlayerNameLabel: TLabel;
GetPlayerStatsTimer: TTimer;
HPProgressBar: TALProgressBar;
StaminaProgressBar: TALProgressBar;
SLLabel: TLabel;
VitLabel: TLabel;
AttLabel: TLabel;
EndLabel: TLabel;
StrLabel: TLabel;
DexLabel: TLabel;
ResLabel: TLabel;
IntLabel: TLabel;
FaiLabel: TLabel;
DefaultPopupMenu: TPopupMenu;
ShowSL: TMenuItem;
CurseIt: TMenuItem; //TODO: implement (if possible) / Implementar (se possível)
// TODO: Implement the time menu (in ms)
// TODO: Implementar menu de tempo (em ms)
// Timer for update
// Timer para atualização
CheckStatus: TTimer;
CheckPlayerHealth: TTimer;
procedure GetPlayerStatsTimerTimer(Sender: TObject);
// Procedure for showing/hidding the Stats (just show SL)
// Procedure para esconder/mostrar o stats (apenas mostra SL)
procedure ShowSLClick(Sender: TObject);
// Timer for CheckPlayerHealth.OnTimer
// Timer para evento CheckPlayerHealth.OnTimer
procedure CheckPlayerHealthTimer(Sender: TObject);
// Proceudre for CheckStatus.OnTimer
// Procedure para CheckStatus.OnTimer
procedure CheckStatusTimer(Sender: TObject);
private
FWarrior: TWarrior;
function GetFrameWarrior: TWarrior;
procedure SetFrameWarrior(AWarrior: TWarrior);
protected
procedure PaintWindow(DC: HDC); override;
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
procedure HideStats;
procedure ShowStats;
procedure HideShowStats(const AValue: Boolean);
procedure UpdatePlayerStats;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
property Warrior: TWarrior read GetFrameWarrior write SetFrameWarrior;
end;
implementation
uses
uDefaultPlayer, uRedPhantom, uBluePhantom, uWhitePhantom;
{$R *.dfm}
procedure TFrameStatusPlayer.CheckPlayerHealthTimer(Sender: TObject);
begin
HPProgressBar.Max := Warrior.MaxHP;
StaminaProgressBar.Max := Warrior.MaxStamina;
HPProgressBar.Position := Warrior.HP;
StaminaProgressBar.Position := Warrior.ActualStamina;
end;
procedure TFrameStatusPlayer.CheckStatusTimer(Sender: TObject);
begin
UpdatePlayerStats;
end;
constructor TFrameStatusPlayer.Create(AOwner: TComponent);
begin
inherited;
Self.DoubleBuffered := True;
end;
destructor TFrameStatusPlayer.Destroy;
begin
inherited;
end;
function TFrameStatusPlayer.GetFrameWarrior: TWarrior;
begin
Result := FWarrior;
end;
procedure TFrameStatusPlayer.GetPlayerStatsTimerTimer(Sender: TObject);
begin
if Warrior = nil then
if Warrior.ClassType = TDefaultPlayer then
Warrior := TDefaultPlayer.Create
else
if Warrior.ClassType = TRedPhantom then
Warrior := TRedPhantom.Create
else
if Warrior.ClassType = TBluePhantom then
Warrior := TBluePhantom.Create
else
if Warrior.ClassType = TWhitePhantom then
Warrior := TWhitePhantom.Create
else
Exit;
end;
procedure TFrameStatusPlayer.HideShowStats(const AValue: Boolean);
begin
VitLabel.Visible := AValue;
AttLabel.Visible := AValue;
EndLabel.Visible := AValue;
StrLabel.Visible := AValue;
DexLabel.Visible := AValue;
ResLabel.Visible := AValue;
IntLabel.Visible := AValue;
FaiLabel.Visible := AValue;
end;
procedure TFrameStatusPlayer.HideStats;
begin
HideShowStats(False);
end;
procedure TFrameStatusPlayer.PaintWindow(DC: HDC);
begin
inherited;
end;
procedure TFrameStatusPlayer.SetFrameWarrior(AWarrior: TWarrior);
begin
FWarrior := AWarrior;
end;
procedure TFrameStatusPlayer.ShowSLClick(Sender: TObject);
begin
if ShowSL.Checked then
begin
ShowSL.Checked := False;
ShowStats;
end
else
begin
ShowSL.Checked := True;
HideStats;
end;
end;
procedure TFrameStatusPlayer.ShowStats;
begin
HideShowStats(True)
end;
procedure TFrameStatusPlayer.UpdatePlayerStats;
begin
Warrior.UpdateStatus;
PlayerNameLabel.Caption := Warrior.Name + ' - ' + Warrior.WarriorClassName;
SLLabel.Caption := IntToStr(Warrior.Level);
VitLabel.Caption := IntToStr(Warrior.Vitality);
AttLabel.Caption := IntToStr(Warrior.Attunement);
EndLabel.Caption := IntToStr(Warrior.Endurance);
StrLabel.Caption := IntToStr(Warrior.Strength);
DexLabel.Caption := IntToStr(Warrior.Dexterity);
ResLabel.Caption := IntToStr(Warrior.Resistance);
IntLabel.Caption := IntToStr(Warrior.Intelligence);
FaiLabel.Caption := IntToStr(Warrior.Faith);
end;
procedure TFrameStatusPlayer.WMPaint(var Message: TWMPaint);
begin
inherited;
end;
end.
|
unit UThreadTestConnectMongo;
interface
uses
Classes, UDMMongo, UIMainController;
type
TThreadTestConnectMongo = class(TThread)
private
FController: IMainController;
protected
procedure Execute; override;
public
constructor Create(MainController : IMainController);
end;
implementation
{ TThreadTestConnectMongo }
constructor TThreadTestConnectMongo.Create(MainController : IMainController);
begin
inherited Create(True);
FController := MainController;
FreeOnTerminate := true;
Resume;
end;
procedure TThreadTestConnectMongo.Execute;
var
DmMongo : TDMMongo;
begin
Self.NameThreadForDebugging(Self.ClassName);
FController.SetMongoConnecting;
DmMongo := TDMMongo.Create(nil);
if DmMongo.TestConnection then
FController.SetMongoConnected
else
FController.SetMongoNotConnected;
DmMongo.Free;
Self.Terminate;
end;
end.
|
unit PizzaStore;
interface
uses
Pizza, System.SysUtils;
type
TTipoDePizzas = class of TPizza;
TPizzaStore = class
private
class var CardapioPizzas: TArray<TTipoDePizzas>;
public
class procedure RegistrarPizza(Pizza: TTipoDePizzas); virtual;
class function PedirPizza(Pizzas: string): TPizza;
end;
TPedido = class
class var FPizzas: TArray<TPizza>;
class procedure Pedir(Qtde: Integer; const Tipo: string);
class procedure MostrarPedido;
public
destructor Destroy; override;
end;
implementation
{ TPizzaStore }
class function TPizzaStore.PedirPizza(Pizzas: string): TPizza;
var
ClasseDaPizza: TTipoDePizzas;
begin
Result := nil;
for ClasseDaPizza in CardapioPizzas do
if ClasseDaPizza.ClassName = Pizzas then
Result := (ClasseDaPizza.Create);
if Result = nil then
raise Exception.Create('Pizza não cadastrada.');
end;
class procedure TPizzaStore.RegistrarPizza(Pizza: TTipoDePizzas);
begin
CardapioPizzas := CardapioPizzas + [Pizza];
end;
{ TPedido }
destructor TPedido.Destroy;
var
P: TPizza;
begin
for P in FPizzas do
P.Free;
inherited;
end;
class procedure TPedido.MostrarPedido;
var
P: TPizza;
begin
for P in FPizzas do
WriteLn(P.PrepararPizza);
end;
class procedure TPedido.Pedir(Qtde: Integer; const Tipo: string);
var
I: Integer;
begin
for I := 0 to Qtde - 1 do
FPizzas := FPizzas + [TPizzaStore.PedirPizza(Tipo)];
end;
end.
|
unit nexPopUpBase;
interface
uses
SysUtils, Classes, Controls, cxControls, cxContainer, cxEdit,
SpTBXFormPopupMenu, SpTBXItem, SpTBXControls, cxTextEdit, Menus,
Forms, SpTBXSkins;
type
TnexPopUpBase = class(TcxTextEdit)
private
FOnChange: TMenuChangeEvent;
FOnPopup: TNotifyEvent;
FOnClosePopup: TSpTBXRollUpEvent;
FOnBeforeClosePopup: TSpTBXRollUpEvent;
FOnBeforePopup: TSpTBXRollDownEvent;
FOnGetPopupFormClass: TSpTBXGetFormClassEvent;
procedure SetPopupForm(Value: TCustomForm);
procedure doPopup(Sender: TObject);
procedure doGetPopupFormClass(Sender: TObject; var AFormClass: TCustomFormClass);
procedure doClosePopup(Sender: TObject; Selected: Boolean);
procedure doBeforeClosePopup(Sender: TObject; Selected: Boolean);
procedure doBeforePopup(Sender: TObject; var FormWidth, FormHeight: Integer);
{ Private declarations }
protected
fFormPopupMenu: TSpTBXFormPopupMenu;
fPopupForm: TCustomForm;
procedure DoPopupChange(Sender: TObject; Source: TMenuItem; Rebuild: Boolean);
{ Protected declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property PopupForm: TCustomForm read FPopupForm write SetPopupForm;
{ Public declarations }
published
property OnChange: TMenuChangeEvent read FOnChange write FOnChange;
property OnPopup: TNotifyEvent read FOnPopup write FOnPopup;
property OnClosePopup: TSpTBXRollUpEvent read FOnClosePopup write FOnClosePopup;
property OnBeforeClosePopup: TSpTBXRollUpEvent read FOnBeforeClosePopup write FOnBeforeClosePopup;
property OnBeforePopup: TSpTBXRollDownEvent read FOnBeforePopup write FOnBeforePopup;
property OnGetPopupFormClass: TSpTBXGetFormClassEvent read FOnGetPopupFormClass write FOnGetPopupFormClass;
{ Published declarations }
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('NexCafe', [TnexPopUpBase]);
end;
constructor TnexPopUpBase.Create(AOwner: TComponent);
begin
inherited;
fFormPopupMenu := TSpTBXFormPopupMenu.Create(nil);
fFormPopupMenu.SkinType := sknNone;
fFormPopupMenu.OnChange := DoPopupChange;
fFormPopupMenu.OnPopup := doPopup;
fFormPopupMenu.OnGetPopupFormClass := doGetPopupFormClass;
fFormPopupMenu.OnClosePopup := doClosePopup;
fFormPopupMenu.OnBeforeClosePopup := doBeforeClosePopup;
fFormPopupMenu.OnBeforePopup := doBeforePopup;
PopupMenu := fFormPopupMenu;
end;
destructor TnexPopUpBase.Destroy;
begin
fFormPopupMenu.Free;
inherited;
end;
procedure TnexPopUpBase.doBeforeClosePopup(Sender: TObject; Selected: Boolean);
begin
if assigned(fOnBeforeClosePopup) then
fOnBeforeClosePopup(self, Selected);
end;
procedure TnexPopUpBase.doBeforePopup(Sender: TObject; var FormWidth,
FormHeight: Integer);
begin
if assigned(fOnBeforePopup) then
fOnBeforePopup(self, FormWidth, FormHeight);
end;
procedure TnexPopUpBase.DoPopupChange(Sender: TObject; Source: TMenuItem; Rebuild: Boolean);
begin
if assigned(fOnChange) then
fOnChange(self, Source, Rebuild);
end;
procedure TnexPopUpBase.doClosePopup(Sender: TObject; Selected: Boolean);
begin
if assigned(fOnClosePopup) then
fOnClosePopup(self, Selected);
end;
procedure TnexPopUpBase.doGetPopupFormClass(Sender: TObject;
var AFormClass: TCustomFormClass);
begin
if assigned(fOnGetPopupFormClass) then
fOnGetPopupFormClass(self, AFormClass);
end;
procedure TnexPopUpBase.doPopup(Sender: TObject);
begin
if assigned(fOnPopup) then
fOnPopup(self);
end;
procedure TnexPopUpBase.SetPopupForm(Value: TCustomForm);
begin
if FPopupForm <> Value then begin
FPopupForm := Value;
fFormPopupMenu.PopupForm := Value;
end;
end;
end.
|
{ This, Folks, is the 2nd BackDoor program. Enjoy it, it's made for you! }
{ Idea: C. Olliwood. Distortions by Chip-sy-King (Hahaha!) }
PROGRAM Funny_Message_V1_0; { From Feb. the 26, 1995 }
USES Crt;
VAR Zuffi_Zahl : Integer;
Spruch : String;
PROCEDURE Waehle_Spruch;
BEGIN
Zuffi_Zahl := RANDOM (6);
CASE Zuffi_Zahl OF
0 : Spruch := 'Hi, nice to see you. Hope you got a good f*#+ tonight !?';
1 : Spruch := 'Yes, touch my keys, you stut muffin. It is so good when you do it!';
2 : Spruch := 'No joke today, I`m busy!';
3 : Spruch := 'Hi, chummer, doin` alright? I hope so! Now let`s start...';
4 : Spruch := 'Eat shit and bark at the moon! (No offence)';
5 : Spruch := 'WARNING!!! There is a corrupt DOS-System on your HD. Your PC will explode in 20 seconds!';
END;
END;
BEGIN
RANDOMIZE;
WRITELN;
TextAttr := RANDOM (16);
Waehle_Spruch;
WRITELN (Spruch);
TEXTCOLOR (8);
WRITELN ('The ultimate Joke-Processor. (c)1995 by BackDoor');
WRITELN;
TEXTCOLOR (7);
END. |
{$i deltics.unicode.inc}
unit Deltics.Unicode.Transcode.Utf8ToUtf16;
interface
uses
Deltics.Unicode.Types;
procedure _Utf8ToUtf16Be(var aUtf8: PUtf8Char; var aUtf8Count: Integer; var aUtf16: PWideChar; var aUtf16Count: Integer);
procedure _Utf8ToUtf16Le(var aUtf8: PUtf8Char; var aUtf8Count: Integer; var aUtf16: PWideChar; var aUtf16Count: Integer);
implementation
uses
Deltics.Unicode;
procedure _Utf8ToUtf16Be(var aUtf8: PUtf8Char;
var aUtf8Count: Integer;
var aUtf16: PWideChar;
var aUtf16Count: Integer);
var
code: Codepoint;
hi, lo: WideChar;
begin
while (aUtf8Count > 0) and (aUtf16Count > 0) do
begin
code := Unicode.Utf8ToCodepoint(aUtf8, aUtf8Count);
if code > $ffff then
begin
if aUtf16Count = 1 then
raise EMoreData.Create('%s requires a surrogate pair but only 1 widechar remains available in the destination buffer', [Unicode.Ref(code)]);
Unicode.CodepointToSurrogates(code, hi, lo);
aUtf16^ := WideChar(((Word(hi) and $ff00) shr 8) or ((Word(hi) and $00ff) shl 8));
Inc(aUtf16);
aUtf16^ := WideChar(((Word(lo) and $ff00) shr 8) or ((Word(lo) and $00ff) shl 8));
Inc(aUtf16);
Dec(aUtf16Count, 2);
end
else
begin
aUtf16^ := WideChar(((Word(code) and $ff00) shr 8) or ((Word(code) and $00ff) shl 8));
Inc(aUtf16);
Dec(aUtf16Count);
end;
end;
end;
procedure _Utf8ToUtf16Le(var aUtf8: PUtf8Char;
var aUtf8Count: Integer;
var aUtf16: PWideChar;
var aUtf16Count: Integer);
var
code: Codepoint;
hi, lo: WideChar;
begin
while (aUtf8Count > 0) and (aUtf16Count > 0) do
begin
code := Unicode.Utf8ToCodepoint(aUtf8, aUtf8Count);
if code > $ffff then
begin
if aUtf16Count = 1 then
raise EMoreData.Create('%s requires a surrogate pair but only 1 widechar remains available in the destination buffer', [Unicode.Ref(code)]);
Unicode.CodepointToSurrogates(code, hi, lo);
aUtf16^ := hi;
Inc(aUtf16);
aUtf16^ := lo;
Inc(aUtf16);
Dec(aUtf16Count, 2);
end
else
begin
aUtf16^ := WideChar(code);
Inc(aUtf16);
Dec(aUtf16Count);
end;
end;
end;
end.
|
unit BrickCamp.Common.Mapping;
//as per a stack entry by Sir Rufo. Its as per as I have done it c# and ruby
interface
uses
System.Generics.Collections,
System.Rtti,
System.SysUtils,
System.TypInfo;
type
TMapKey = record
Source: PTypeInfo;
Target: PTypeInfo;
class function Create<TSource, TTarget>( ): TMapKey; static;
end;
TMapper = class
private
FMappings: TDictionary<TMapKey, TFunc<TValue, TValue>>;
public
procedure Add<TSource, TTarget>( Converter: TFunc<TSource, TTarget> ); overload;
procedure Add<TSource, TTarget>( Converter: TFunc<TSource, TTarget>; Reverter: TFunc<TTarget, TSource> ); overload;
public
constructor Create;
destructor Destroy; override;
function MapCollection<TSource, TTarget>( const Collection: TEnumerable<TSource> ): TArray<TTarget>; overload;
function MapCollection<TSource, TTarget>( const Collection: array of TSource ): TArray<TTarget>; overload;
function Map<TSource, TTarget>( const Source: TSource ): TTarget; overload;
procedure Map<TSource, TTarget>( const Source: TSource; out Target: TTarget ); overload;
end;
implementation
{ TMapper }
procedure TMapper.Add<TSource, TTarget>( Converter: TFunc<TSource, TTarget> );
var
lKey: TMapKey;
begin
lKey := TMapKey.Create<TSource, TTarget>( );
FMappings.Add( lKey,
function( Source: TValue ): TValue
begin
Result := TValue.From<TTarget>( Converter( Source.AsType<TSource>( ) ) );
end );
end;
procedure TMapper.Add<TSource, TTarget>(
Converter: TFunc<TSource, TTarget>;
Reverter : TFunc<TTarget, TSource> );
begin
Add<TSource, TTarget>( Converter );
Add<TTarget, TSource>( Reverter );
end;
constructor TMapper.Create;
begin
inherited;
FMappings := TDictionary < TMapKey, TFunc < TValue, TValue >>.Create;
end;
destructor TMapper.Destroy;
begin
FMappings.Free;
inherited;
end;
function TMapper.Map<TSource, TTarget>( const Source: TSource ): TTarget;
var
Key: TMapKey;
Value : TValue;
begin
Key := TMapKey.Create<TSource, TTarget>( );
Value := TValue.From<TSource>( Source );
Result := FMappings[ Key ]( Value ).AsType<TTarget>( );
end;
procedure TMapper.Map<TSource, TTarget>(
const Source: TSource;
out Target : TTarget );
begin
Target := Map<TSource, TTarget>( Source );
end;
function TMapper.MapCollection<TSource, TTarget>( const Collection: array of TSource ): TArray<TTarget>;
var
TempCollection: TList<TSource>;
begin
TempCollection := TList<TSource>.Create( );
try
TempCollection.AddRange( Collection );
Result := MapCollection<TSource, TTarget>( TempCollection );
finally
TempCollection.Free;
end;
end;
function TMapper.MapCollection<TSource, TTarget>( const Collection: TEnumerable<TSource> ): TArray<TTarget>;
var
Key : TMapKey;
MapHandler: TFunc<TValue, TValue>;
ListOfTarget : TList<TTarget>;
SourceItem: TSource;
begin
Key := TMapKey.Create<TSource, TTarget>( );
MapHandler := FMappings[ Key ];
ListOfTarget := TList<TTarget>.Create;
try
for SourceItem in Collection do
begin
ListOfTarget.Add( MapHandler( TValue.From<TSource>( SourceItem ) ).AsType<TTarget>( ) );
end;
Result := ListOfTarget.ToArray( );
finally
ListOfTarget.Free;
end;
end;
{ TMapKey }
class function TMapKey.Create<TSource, TTarget>: TMapKey;
begin
Result.Source := TypeInfo( TSource );
Result.Target := TypeInfo( TTarget );
end;
end.
|
unit Unit_GlobalFunctions;
interface
uses ActiveX, Windows, Sysutils;
type
SingleArray = array of single;
TRowData = class
private
fComObj : IUnknown;
public
constructor Create(ComObj : IUnknown); overload;
property ComObj : IUnknown read fComObj write fComObj;
end;
function SingleArrayToSafeArray(Value : SingleArray) : PSafeArray;
procedure SafeArrayToSingleArray(Value : PSafeArray ;var Return : SingleArray; DestroyArray : Boolean = true);
implementation
constructor TRowData.Create(ComObj : IUnknown);
begin
fComObj := ComObj;
end;
function SingleArrayToSafeArray(Value : SingleArray) : PSafeArray;
var
ArrayData : Pointer;
begin
Result := SafeArrayCreateVector( VT_R4, 0, Length(Value));
if SafeArrayAccessData( Result , ArrayData ) = S_OK then begin
CopyMemory(ArrayData,Value,Length(Value) * SizeOf(Value));
SafeArrayUnAccessData(Result);
end else begin
SafeArrayDestroy(Result);
raise exception.Create('SAFEARRAY CREATE FAILURE');
end;
end;
procedure SafeArrayToSingleArray(Value : PSafeArray ;var Return : SingleArray; DestroyArray : Boolean = true);
var
Result : HResult;
ArrayBounds : TSafeArrayBound;
ArrayData : Pointer;
begin
Result := SafeArrayAccessData(Value, ArrayData);
case Result of
S_OK : begin
ArrayBounds := Value.rgsabound[0];
SetLength(Return,ArrayBounds.cElements);
CopyMemory(Return,ArrayData,ArrayBounds.cElements * Value.cbElements);
SafeArrayUnAccessData(Value);
if DestroyArray then SafeArrayDestroy(Value);
end;
else raise exception.Create('SAFEARRAY READ FAILURE ' + inttostr(Result));
end;
end;
end.
|
unit JcfIdeRegister;
{ AFS 7 Jan 2K
JEDI Code Format IDE plugin registration }
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is JcfIdeRegister, released May 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele, Juergen Kehrel
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/NPL/
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.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses
{ rtl }
SysUtils, Classes,
{ lcl }
LCLType;
procedure Register;
implementation
uses
{ lazarus }
MenuIntf, IdeCommands,
{ local }
JcfIdeMain;
const
FORMAT_MENU_NAME = 'jcfJEDICodeFormat';
FORMAT_CURRENT_NAME = 'jcfCurrentEditorWindow';
FORMAT_PROJECT_NAME = 'jcfAllFilesinProject';
FORMAT_OPEN_NAME = 'jcfAllOpenWindows';
FORMAT_REG_SETTINGS_MENU_NAME = 'jcfRegistrySettings';
FORMAT_SETTINGS_MENU_NAME = 'jcfFormatSettings';
FORMAT_ABOUT_MENU_NAME = 'jcfAbout';
FORMAT_CATEGORY_NAME = 'jcfFormat';
FORMAT_MENU_SECTION1 = 'jcfSection1';
FORMAT_MENU_SECTION2 = 'jcfSection2';
resourcestring
FORMAT_MENU = 'JEDI Code &Format';
FORMAT_CURRENT = '&Current Editor Window';
FORMAT_PROJECT = '&All Files in Project';
FORMAT_OPEN = 'All &Open Windows';
FORMAT_REG_SETTINGS_MENU = '&Registry Settings';
FORMAT_SETTINGS_MENU = '&Format Settings';
FORMAT_ABOUT_MENU = '&About';
FORMAT_CATEGORY = 'JEDI Code Format';
var
lcJCFIDE: TJcfIdeMain;
procedure Register;
var
Cat: TIDECommandCategory;
Key: TIDEShortCut;
fcMainMenu, SubSection: TIDEMenuSection;
CmdFormatFile: TIDECommand;
begin
Cat := IDECommandList.CreateCategory(nil, FORMAT_CATEGORY_NAME,
FORMAT_CATEGORY, IDECmdScopeSrcEditOnly);
// Ctrl + D ?
Key := IDEShortCut(VK_D, [SSctrl], VK_UNKNOWN, []);
CmdFormatFile := RegisterIDECommand(Cat, FORMAT_CURRENT_NAME, FORMAT_CURRENT, Key,
lcJCFIDE.DoFormatCurrentIDEWindow);
fcMainMenu := RegisterIDESubMenu(itmSecondaryTools, FORMAT_MENU_NAME, FORMAT_MENU);
RegisterIDEMenuCommand(fcMainMenu, FORMAT_CURRENT_NAME, FORMAT_CURRENT,
lcJCFIDE.DoFormatCurrentIDEWindow, nil, CmdFormatFile);
RegisterIDEMenuCommand(fcMainMenu, FORMAT_PROJECT_NAME, FORMAT_PROJECT,
lcJCFIDE.DoFormatProject);
RegisterIDEMenuCommand(fcMainMenu, FORMAT_OPEN_NAME, FORMAT_OPEN,
lcJCFIDE.DoFormatOpen);
// settings
SubSection := RegisterIDEMenuSection(fcMainMenu, FORMAT_MENU_SECTION1);
RegisterIDEMenuCommand(SubSection, FORMAT_REG_SETTINGS_MENU_NAME, FORMAT_REG_SETTINGS_MENU,
lcJCFIDE.DoRegistrySettings);
RegisterIDEMenuCommand(SubSection, FORMAT_SETTINGS_MENU_NAME, FORMAT_SETTINGS_MENU,
lcJCFIDE.DoFormatSettings);
// about
SubSection := RegisterIDEMenuSection(fcMainMenu, FORMAT_MENU_SECTION2);
RegisterIDEMenuCommand(fcMainMenu, FORMAT_ABOUT_MENU_NAME, FORMAT_ABOUT_MENU,
lcJCFIDE.DoAbout);
end;
initialization
lcJCFIDE := TJcfIdeMain.Create;
finalization
FreeAndNil(lcJCFIDE);
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1997,99 Inprise Corporation }
{ }
{*******************************************************}
unit MXREG;
interface
uses
DesignIntf, DesignEditors, CHARTREG, CHART;
type
TDSSChartCompEditor = class(TChartCompEditor)
public
procedure Edit; override;
end;
procedure Register;
implementation
uses
SysUtils, Classes, MXGRID, MXPIVSRC, MXDB, MXDCONST,
Forms, Graphics, StdCtrls, ComCtrls, Mxstore, Controls,
DBTables, MXGRAPH, bdeconst, MXBUTTON, MXTABLES, MXDSSQRY, MXDIMEDT, MXDCUBE,
EDITCHAR;
{ TQueryEditor }
type
TDQueryEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
procedure TDQueryEditor.ExecuteVerb(Index: Integer);
var
Query: TQuery;
begin
Query := Component as TQuery;
case Index of
0: ShowDSSQueryEditor(Designer, Query);
end;
end;
function TDQueryEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := sQueryVerb1;
end;
end;
function TDQueryEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
{ TSourceEditor }
type
TSourceEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
procedure TSourceEditor.ExecuteVerb(Index: Integer);
var
Source: TDecisionSource;
begin
Source := Component as TDecisionSource;
case Index of
0:
begin
Source.SparseRows := not Source.SparseRows;
Source.SparseCols := Source.SparseRows;
end;
end;
end;
function TSourceEditor.GetVerb(Index: Integer): string;
var
Source: TDecisionSource;
begin
Source := Component as TDecisionSource;
case Index of
0:
begin
if Source.SparseRows then
Result := sSourceVerb0
else
Result := sSourceVerb1;
end;
end;
end;
function TSourceEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
{ TCubeEditor }
type
TCubeEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
procedure TCubeEditor.ExecuteVerb(Index: Integer);
var
Cube: TDecisionCube;
begin
Cube := Component as TDecisionCube;
case Index of
0: ShowDSSCubeEditor(Cube);
1:
begin
if (Cube.DataSet is TQuery) then
ShowDssQueryEditor(Designer,TQuery(Cube.DataSet));
end;
end;
end;
function TCubeEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := SCubeVerb0;
1: Result := SCubeVerb1;
end;
end;
function TCubeEditor.GetVerbCount: Integer;
var
Cube: TDecisionCube;
begin
Cube := Component as TDecisionCube;
if (Cube.DataSet is TQuery) and not (Cube.DataSet is TDecisionQuery) then
Result := 2
else
Result := 1;
end;
{ TDSSChartCompEditor }
procedure TDSSChartCompEditor.Edit;
begin
EditDSSChart(nil, TCustomChart(Component));
end;
{ TGridEditor }
type
TGridEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
procedure TGridEditor.ExecuteVerb(Index: Integer);
var
Grid: TDecisionGrid;
begin
Grid := Component as TDecisionGrid;
case Index of
0: Grid.Totals := not Grid.Totals;
end;
end;
function TGridEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := sGridVerb0;
end;
end;
function TGridEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
{ TDecisionGridDimsProperty }
type
TDecisionGridDimsProperty = class(TPropertyEditor)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
end;
function TDecisionGridDimsProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog];
end;
function TDecisionGridDimsProperty.GetValue: String;
begin
Result := '(' + TDisplayDims.ClassName + ')';
end;
procedure TDecisionGridDimsProperty.Edit;
begin
ShowDisplayDimEditor(Designer, GetComponent(0) as TDecisionGrid);
end;
{ TDimensionMapProperty }
type
TDimensionMapProperty = class(TPropertyEditor)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
end;
function TDimensionMapProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog];
end;
function TDimensionMapProperty.GetValue: String;
begin
Result := 'TDimensionMaps';
end;
procedure TDimensionMapProperty.Edit;
begin
ShowDSSCubeEditor(GetComponent(0)as TDecisionCube);
end;
{ TSummaryMapProperty }
type
TSummaryMapProperty = class(TPropertyEditor)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
end;
function TSummaryMapProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog];
end;
function TSummaryMapProperty.GetValue: String;
begin
Result := 'TSummaryMaps';
end;
procedure TSummaryMapProperty.Edit;
begin
ShowDSSQueryEditor(Designer, GetComponent(0) as TDecisionQuery);
end;
{ Registration }
procedure Register;
begin
RegisterComponents(sComponentTabName, [TDecisionCube, TDecisionQuery,
TDecisionSource, TDecisionPivot, TDecisionGrid, TDecisionGraph]);
RegisterNonActiveX([TDecisionCube, TDecisionQuery, TDecisionSource,
TDecisionPivot, TDecisionPivot, TDecisionGrid, TDecisionGraph,
TCustomDecisionGrid, TCustomDecisionGraph], axrIncludeDescendants);
RegisterComponentEditor(TDecisionQuery, TDQueryEditor);
RegisterComponentEditor(TDecisionCube, TCubeEditor);
RegisterComponentEditor(TDecisionSource, TSourceEditor);
RegisterComponentEditor(TDecisionGrid, TGridEditor);
RegisterComponentEditor(TDecisionGraph,TDSSChartCompEditor);
RegisterPropertyEditor(TypeInfo(TCollection), TDecisionGrid, 'Dimensions', TDecisionGridDimsProperty);
RegisterPropertyEditor(TypeInfo(TCollection), TDecisionCube, 'DimensionMap', TDimensionMapProperty);
RegisterPropertyEditor(TypeInfo(TCollection), TDecisionQuery, 'SummaryMap', TSummaryMapProperty);
RegisterPropertyEditor(TypeInfo(TDate), nil, '', TDateProperty);
end;
end.
|
{ }
{ Log unit v3.02 }
{ }
{ This unit is copyright © 2002-2004 by David J Butler }
{ }
{ This unit is part of Delphi Fundamentals. }
{ Its original file name is cLog.pas }
{ The latest version is available from the Fundamentals home page }
{ http://fundementals.sourceforge.net/ }
{ }
{ I invite you to use this unit, free of charge. }
{ I invite you to distibute this unit, but it must be for free. }
{ I also invite you to contribute to its development, }
{ but do not distribute a modified copy of this file. }
{ }
{ A forum is available on SourceForge for general discussion }
{ http://sourceforge.net/forum/forum.php?forum_id=2117 }
{ }
{ }
{ Revision history: }
{ 2002/02/07 2.01 Added TLog component from cDebug to cSysUtils. }
{ 2002/09/04 3.02 Moved TLog component to cLog unit. }
{ }
{$INCLUDE ..\cDefines.inc}
unit cLog;
interface
uses
{ Delphi }
SysUtils,
Classes;
{ }
{ Log Component }
{ }
{$TYPEINFO ON}
type
TLogClass = (lcInfo, lcError, lcWarning, lcDebug, lcEndRepeat,
lcUserEventBegin, lcUserEventEnd, lcInit);
TLogEvent = procedure (Sender: TObject; LogClass: TLogClass;
LogMsg: String) of object;
TLogEditMessageEvent = procedure (Sender: TObject; LogClass: TLogClass;
var LogMsg: String) of object;
TLogFileEvent = procedure (Sender: TObject; LogClass: TLogClass;
var LogMsg: String; var LogToFile: Boolean) of object;
TLogOptions = Set of (loLogToFile, // Output log to a file
loKeepFileOpen, // Keep log file open between messages
loLogToDebugLog, // Log to system debug log (IDE)
loNoLogEvent, // Don't generate log event
loLogDate, // Include date in log message
loLogTime, // Include time in log message
loLogMilliSecDiff, // Include milliseconds since last log in message
loIgnoreLogFailure, // Ignore log failures
loCheckRepeats, // Log first and last of repeated messages
loIgnoreClassDebug, // Ignore messages of class Debug
loIgnoreClassError, // Ignore messages of class Error
loIgnoreClassWarning, // Ignore messages of class Warning
loIgnoreClassInfo); // Ignore messages of class Info
TLog = class(TComponent)
protected
FOnLog : TLogEvent;
FOnEditMessage : TLogEditMessageEvent;
FOnLogFile : TLogFileEvent;
FLogFile : TFileStream;
FLogFileName : String;
FLogOptions : TLogOptions;
FLastLog : Cardinal;
FLastLogMsg : String;
FLogRepeatCount : Integer;
FLogTo : TLog;
FLevels : TStringList;
FMaxLogLevel : Integer;
procedure SetLogFileName(const LogFileName: String);
procedure SetLogOptions(const LogOptions: TLogOptions);
procedure SetLogTo(const LogTo: TLog);
procedure Init; virtual;
procedure RaiseError(const Msg: String);
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetLogLevel: Integer;
procedure TriggerLogMsg(const Sender: TObject; const LogClass: TLogClass;
const LogMsg: String); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property LogFileName: String read FLogFileName write SetLogFileName;
property LogOptions: TLogOptions read FLogOptions write SetLogOptions default [];
property LogTo: TLog read FLogTo write SetLogTo;
property LogLevel: Integer read GetLogLevel;
property Levels: TStringList read FLevels;
procedure Enter(const Level: String = '');
procedure Leave;
property MaxLogLevel: Integer read FMaxLogLevel write FMaxLogLevel default -1;
procedure Log(const Sender: TObject; const LogClass: TLogClass;
const LogMsg: String); overload; virtual;
procedure Log(const LogClass: TLogClass; const LogMsg: String); overload;
procedure Log(const LogMsg: String); overload;
procedure LogDebug(const LogMsg: String);
procedure LogError(const LogMsg: String);
procedure LogWarning(const LogMsg: String);
procedure DeleteLogFile;
procedure LoadLogFileInto(const Destination: TStrings; const Size: Integer = -1);
property OnLog: TLogEvent read FOnLog write FOnLog;
property OnEditMessage: TLogEditMessageEvent read FOnEditMessage write FOnEditMessage;
property OnLogFile: TLogFileEvent read FOnLogFile write FOnLogFile;
end;
ELog = class(Exception);
{ TfndLog }
TfndLog = class(TLog)
published
property LogFileName;
property LogOptions;
property LogTo;
property MaxLogLevel;
property OnLog;
property OnEditMessage;
property OnLogFile;
end;
{ }
{ Application Log }
{ }
function AppLog: TLog;
implementation
uses
{ Delphi }
Windows,
{ Fundamentals }
cUtils,
cStrings;
{ }
{ Log Component }
{ }
constructor TLog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FLevels := TStringList.Create;
Init;
end;
destructor TLog.Destroy;
begin
FreeAndNil(FLogFile);
FreeAndNil(FLevels);
inherited Destroy;
end;
procedure TLog.Init;
begin
FLogFileName := StrExclPrefix(ObjectClassName(self) + '.log', 'T');
FMaxLogLevel := -1;
FLogOptions := [{$IFDEF DEBUG}loLogToDebugLog{$ENDIF}];
{$IFDEF OS_WIN32}
FLastLog := GetTickCount;
{$ENDIF}
end;
procedure TLog.RaiseError(const Msg: String);
begin
raise ELog.Create(Msg);
end;
procedure TLog.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then
if AComponent = FLogTo then
FLogTo := nil;
end;
procedure TLog.SetLogFileName(const LogFileName: String);
begin
if LogFileName = FLogFileName then
exit;
FreeAndNil(FLogFile);
FLogFileName := LogFileName;
end;
procedure TLog.SetLogOptions(const LogOptions: TLogOptions);
begin
if LogOptions = FLogOptions then
exit;
FLogOptions := LogOptions;
if not (loLogToFile in LogOptions) or not (loKeepFileOpen in LogOptions) then
FreeAndNil(FLogFile);
end;
procedure TLog.SetLogTo(const LogTo: TLog);
var L : TLog;
begin
if LogTo = FLogTo then
exit;
if LogTo = nil then
begin
FLogTo := nil;
exit;
end;
L := LogTo;
Repeat
if L = self then
RaiseError('Circular LogTo reference');
L := L.FLogTo;
Until not Assigned(L);
FLogTo := LogTo;
end;
procedure TLog.TriggerLogMsg(const Sender: TObject; const LogClass: TLogClass; const LogMsg: String);
begin
end;
procedure TLog.Log(const Sender: TObject; const LogClass: TLogClass; const LogMsg: String);
var S : String;
N : TDateTime;
I : Integer;
T : Cardinal;
R, F : Boolean;
begin
if [csDesigning, csLoading] * ComponentState <> [] then
exit;
if (FMaxLogLevel >= 0) and (FLevels.Count > FMaxLogLevel) then
exit;
if Assigned(FLogTo) then
try
FLogTo.Log(Sender, LogClass, LogMsg);
except
if not (loIgnoreLogFailure in FLogOptions) then
raise;
end;
Case LogClass of
lcDebug : if loIgnoreClassDebug in FLogOptions then exit;
lcInfo : if loIgnoreClassInfo in FLogOptions then exit;
lcError : if loIgnoreClassError in FLogOptions then exit;
lcWarning : if loIgnoreClassWarning in FLogOptions then exit;
end;
try
if loCheckRepeats in FLogOptions then
begin
if LogMsg = FLastLogMsg then
begin
Inc(FLogRepeatCount);
exit;
end;
if FLogRepeatCount > 0 then
begin
I := FLogRepeatCount + 1;
FLogRepeatCount := 0;
Log(self, lcEndRepeat, IntToStr(I) + ' times');
end;
FLastLogMsg := LogMsg;
end;
S := LogMsg;
if Assigned(FOnEditMessage) then
FOnEditMessage(Sender, LogClass, S);
if not (loNoLogEvent in FLogOptions) and Assigned(FOnLog) then
FOnLog(Sender, LogClass, S);
{$IFDEF OS_WIN32}
if loLogMilliSecDiff in FLogOptions then
begin
T := GetTickCount;
S := PadLeft(IntToStr(T - FLastLog), ' ', 4, False) + ' ' + S;
FLastLog := T;
end;
{$ENDIF}
if [loLogDate, loLogTime] * FLogOptions <> [] then
begin
N := Now;
if loLogTime in FLogOptions then
S := FormatDateTime('hhnnss', N) + ' ' + S;
if loLogDate in FLogOptions then
S := FormatDateTime('yymmdd', N) + ' ' + S;
end;
TriggerLogMsg(Sender, LogClass, S);
{$IFDEF OS_WIN32}
if loLogToDebugLog in FLogOptions then
OutputDebugString(PChar(S));
{$ENDIF}
if loLogToFile in FLogOptions then
begin
if FLogFileName = '' then
exit;
F := True;
if Assigned(FOnLogFile) then
FOnLogFile(Sender, LogClass, S, F);
if not F then
exit;
R := False;
if not Assigned(FLogFile) then
try
FLogFile := TFileStream.Create(FLogFileName, fmOpenReadWrite);
R := True;
except
FLogFile := TFileStream.Create(FLogFileName, fmCreate);
end;
if R then
FLogFile.Seek(0, soFromEnd);
try
if S <> '' then
FLogFile.Write(Pointer(S)^, Length(S));
FLogFile.Write(CRLF, Length(CRLF));
finally
if not (loKeepFileOpen in FLogOptions) then
FreeAndNil(FLogFile);
end;
end;
except
if not (loIgnoreLogFailure in FLogOptions) then
raise;
end;
end;
procedure TLog.Log(const LogClass: TLogClass; const LogMsg: String);
begin
Log(self, LogClass, LogMsg);
end;
procedure TLog.Log(const LogMsg: String);
begin
Log(lcInfo, LogMsg);
end;
procedure TLog.LogDebug(const LogMsg: String);
begin
Log(lcDebug, LogMsg);
end;
procedure TLog.LogError(const LogMsg: String);
begin
Log(lcError, LogMsg);
end;
procedure TLog.LogWarning(const LogMsg: String);
begin
Log(lcWarning, LogMsg);
end;
procedure TLog.DeleteLogFile;
begin
if FLogFileName = '' then
exit;
FreeAndNil(FLogFile);
SysUtils.DeleteFile(FLogFileName);
end;
procedure TLog.LoadLogFileInto(const Destination: TStrings; const Size: Integer);
var S : Int64;
C : Integer;
L : String;
begin
Destination.Clear;
if Size = 0 then
exit;
// Open file
FreeAndNil(FLogFile);
try
FLogFile := TFileStream.Create(FLogFileName, fmOpenReadWrite);
except
exit;
end;
S := FLogFile.Size;
if S = 0 then
exit;
// Read
if Size < 0 then
C := S else
C := MinI(Size, S);
FLogFile.Position := S - C;
SetLength(L, C);
FLogFile.Read(Pointer(L)^, C);
// Remove incomplete first line
TrimLeftInPlace(L, csComplete - [#13, #10]);
TrimLeftInPlace(L, [#13, #10]);
// Set text
Destination.Text := L;
end;
function TLog.GetLogLevel: Integer;
begin
Result := FLevels.Count;
end;
procedure TLog.Enter(const Level: String);
begin
if Assigned(FLogTo) then
FLogTo.Enter(Level);
FLevels.Add(Level);
end;
procedure TLog.Leave;
var I: Integer;
begin
if Assigned(FLogTo) then
FLogTo.Leave;
I := FLevels.Count;
if I <= 0 then
exit;
FLevels.Delete(I - 1);
end;
{ }
{ Application Log }
{ }
var
FAppLog: TLog = nil;
function AppLog: TLog;
begin
if not Assigned(FAppLog) then
begin
FAppLog := TLog.Create(nil);
FAppLog.LogFileName := ChangeFileExt(ParamStr(0), '.log');
FAppLog.LogOptions := [
loLogToFile,
loLogDate, loLogTime
{$IFNDEF DEBUG}, loIgnoreLogFailure, loIgnoreClassDebug{$ENDIF}
];
end;
Result := FAppLog;
end;
initialization
finalization
FreeAndNil(FAppLog);
end.
|
unit FIToolkit.CommandLine.Exceptions;
interface
uses
FIToolkit.Commons.Exceptions;
type
ECommandLineException = class abstract (ECustomException);
{ Command-line option exceptions }
ECLIOptionException = class abstract (ECommandLineException);
ECLIOptionParseError = class abstract (ECLIOptionException);
ECLIOptionIsEmpty = class (ECLIOptionParseError);
ECLIOptionHasNoName = class (ECLIOptionParseError);
implementation
uses
FIToolkit.CommandLine.Consts;
initialization
RegisterExceptionMessage(ECLIOptionIsEmpty, RSCLIOptionIsEmpty);
RegisterExceptionMessage(ECLIOptionHasNoName, RSCLIOptionHasNoName);
end.
|
unit UDaoVenda;
interface
uses uDao, DB, SysUtils, Messages, UVenda, UDaoCliente, UDaoProduto,
UDaoCondicaoPagamento, UDaoFuncionario, UDaoContasReceber, UContasReceber,
UDaoUsuario, Dialogs;
type DaoVenda = class(Dao)
private
protected
umVenda : Venda;
umaDaoCliente : DaoCliente;
umaDaoProduto : DaoProduto;
umaDaoCondicaoPagamento : DaoCondicaoPagamento;
umaDaoFuncionario : DaoFuncionario;
UmaDaoUsuario : DaoUsuario;
umaDaoContasReceber : DaoContasReceber;
umaContaReceber : ContasReceber;
public
Constructor CrieObjeto;
Destructor Destrua_se;
function Salvar(obj:TObject): string; override;
function GetDS : TDataSource; override;
function Carrega(obj:TObject): TObject; override;
function Buscar(obj : TObject) : Boolean; override;
function Excluir(obj : TObject) : string ; override;
function VerificarVenda (obj : TObject) : Boolean;
function VerificarNota (obj : TObject) : Boolean;
procedure AtualizaGrid;
procedure Ordena(campo: string);
end;
implementation
{ DaoVenda }
function DaoVenda.Buscar(obj: TObject): Boolean;
var
prim: Boolean;
sql, e, onde: string;
umaVenda: Venda;
begin
e := ' and ';
onde := ' where';
prim := true;
umaVenda := Venda(obj);
sql := 'select * from venda v';
if umaVenda.getUmCliente.getNome_RazaoSoCial <> '' then
begin
//Buscar a descricao do cliente na tabela cliente
sql := sql+' INNER JOIN cliente c ON v.idcliente = c.idcliente and c.nome_razaosocial like '+quotedstr('%'+umaVenda.getUmCliente.getNome_RazaoSoCial+'%');
if (prim) and (umaVenda.getStatus <> '')then
begin
prim := false;
sql := sql+onde;
end
end;
if umaVenda.getStatus <> '' then
begin
if prim then
begin
prim := false;
sql := sql+onde;
end;
sql := sql+' v.status like '+quotedstr('%'+umaVenda.getStatus+'%'); //COLOCA CONDIÇAO NO SQL
end;
if (DateToStr(umaVenda.getDataEmissao) <> '30/12/1899') and (datetostr(umaVenda.getDataVenda) <> '30/12/1899') then
begin
if prim then
begin
prim := false;
sql := sql+onde;
end
else
sql := sql+e;
sql := sql+' v.dataemissao between '+QuotedStr(DateToStr(umaVenda.getDataEmissao))+' and '+QuotedStr(DateToStr(umaVenda.getDataVenda));
end;
with umDM do
begin
QVenda.Close;
QVenda.sql.Text := sql+' order by numnota';
QVenda.Open;
if QVenda.RecordCount > 0 then
result := True
else
result := false;
end;
end;
function DaoVenda.VerificarVenda (obj : TObject) : Boolean;
var sql : string;
umaVenda : Venda;
begin
umaVenda := Venda(obj);
sql := 'select * from venda where idordemservico = '+IntToStr(umaVenda.getIdOrdemServico)+' and status = '''+umaVenda.getStatus+'''';
with umDM do
begin
QVenda.Close;
QVenda.sql.Text := sql;
QVenda.Open;
if QVenda.RecordCount > 0 then
result := True
else
result := false;
end;
Self.AtualizaGrid;
end;
function DaoVenda.VerificarNota (obj : TObject) : Boolean;
var sql : string;
umaVenda : Venda;
begin
umaVenda := Venda(obj);
sql := 'select * from venda where numnota = '+IntToStr(umaVenda.getNumNota)+' and serienota = '''+umaVenda.getSerieNota+'''';
with umDM do
begin
QVenda.Close;
QVenda.sql.Text := sql;
QVenda.Open;
if QVenda.RecordCount > 0 then
result := True
else
result := false;
end;
Self.AtualizaGrid;
end;
procedure DaoVenda.AtualizaGrid;
begin
with umDM do
begin
QVenda.Close;
QVenda.sql.Text := 'select * from venda order by numnota';
QVenda.Open;
end;
end;
function DaoVenda.Carrega(obj: TObject): TObject;
var
umaVenda: Venda;
I : Integer;
begin
umaVenda := Venda(obj);
with umDM do
begin
if not QVenda.Active then
QVenda.Open;
if umaVenda.getNumNota <> 0 then
begin
QVenda.Close;
QVenda.SQL.Text := 'select * from venda where numnota = '+IntToStr(umaVenda.getNumNota);
QVenda.Open;
end;
umaVenda.setNumNota(QVendanumnota.AsInteger);
umaVenda.setSerieNota(QVendaserienota.AsString);
umaVenda.setObservacao(QVendaobservacao.AsString);
umaVenda.setStatus(QVendastatus.AsString);
umaVenda.setDataCadastro(QVendadatacadastro.AsDateTime);
umaVenda.setDataAlteracao(QVendadataalteracao.AsDateTime);
umaVenda.setDataEmissao(QVendadataemissao.AsDateTime);
umaVenda.setDataVenda(QVendadatavenda.AsDateTime);
// Busca o Cliente referente a Venda
umaVenda.getUmCliente.setId(QVendaidcliente.AsInteger);
umaDaoCliente.Carrega(umaVenda.getumCliente);
//Busca Funcioanrio referente a Venda
umaVenda.getUmUsuario.setIdUsuario(QVendaidusuario.AsInteger);
UmaDaoUsuario.Carrega(umaVenda.getUmUsuario);
//Busca Condicao de Pagamento referente a Venda
umaVenda.getUmaCondicaoPagamento.setId(QVendaidcondicaopagamento.AsInteger);
umaDaoCondicaoPagamento.Carrega(umaVenda.getUmaCondicaoPagamento);
//Carregar os Produtos
QProdutoVenda.Close;
QProdutoVenda.SQL.Text := 'select * from produto_venda where numnota = '+IntToStr(umaVenda.getNumNota);
QProdutoVenda.Open;
QProdutoVenda.First;
if umaVenda.CountProdutos <> 0 then
umaVenda.LimparListaProduto; //Limpar a lista caso a lista vim com itens carregados
if umaVenda.CountParcelas <> 0 then
umaVenda.LimparListaParcelas; //Limpar a lista caso a lista vim com itens carregados
while not QProdutoVenda.Eof do
begin
UmaVenda.CrieObejtoProduto;
umaVenda.addProdutoVenda(umaVenda.getUmProdutoVenda);
UmaVenda.getUmProdutoVenda.setId(QProdutoVendaidproduto.AsInteger);
umaDaoProduto.Carrega(UmaVenda.getUmProdutoVenda); //Buscar Descricao do Produto
UmaVenda.getUmProdutoVenda.setQtdProduto(QProdutoVendaquantidade.AsFloat);
UmaVenda.getUmProdutoVenda.setValorUnitario(QProdutoVendavalorunitario.AsFloat);
UmaVenda.getUmProdutoVenda.setDesconto(QProdutoVendadesconto.AsFloat);
QProdutoVenda.Next;
end;
end;
result := umVenda;
Self.AtualizaGrid;
end;
constructor DaoVenda.CrieObjeto;
begin
inherited;
umaDaoCliente := DaoCliente.CrieObjeto;
umaDaoProduto := DaoProduto.CrieObjeto;
umaDaoCondicaoPagamento := DaoCondicaoPagamento.CrieObjeto;
umaDaoFuncionario := DaoFuncionario.CrieObjeto;
umaDaoUsuario := DaoUsuario.CrieObjeto;
umaDaoContasReceber := DaoContasReceber.CrieObjeto;
umaContaReceber := ContasReceber.CrieObjeto;
end;
destructor DaoVenda.Destrua_se;
begin
inherited;
end;
function DaoVenda.Excluir(obj: TObject): string;
begin
end;
function DaoVenda.GetDS: TDataSource;
begin
//-----Formatar Grid-----//
umDM.QVenda.FieldByName('numnota').DisplayLabel := 'NN';
umDM.QVenda.FieldByName('serienota').DisplayLabel := 'SN';
umDM.QVenda.FieldByName('numnota').DisplayWidth := 5;
umDM.QVenda.FieldByName('serienota').DisplayWidth := 5;
//----------------------//
Self.AtualizaGrid;
result := umDM.DSVenda;
end;
procedure DaoVenda.Ordena(campo: string);
begin
umDM.QVenda.IndexFieldNames := campo;
end;
function DaoVenda.Salvar(obj: TObject): string;
var
umaVenda : Venda;
i, j, compareNumNota, NumParcelas, count : Integer;
cancelar, gerarContas : Boolean;
valor, numNotaAux,quantidade : Real;
CP_Status : String;
begin
umaVenda := Venda(obj);
NumParcelas := 0;
numNotaAux := 0;
count := 0;
gerarContas := False;
with umDM do
begin
try
beginTrans;
QVenda.Close;
umaContaReceber.setNumNota(umaVenda.getNumNota);
umaContaReceber.setSerieNota(umaVenda.getSerieNota);
umaContaReceber.setStatus('RECEBIDA');
if umaVenda.getNumNota = 0 then
QVenda.SQL := UpdateVenda.InsertSQL
else
begin
if (umaDaoContasReceber.VerificarContas(umaContaReceber)) then
begin
result := 'Essa Venda não pode ser Cancelada pois 1 ou mais das parcelas já foram recebidas!';
Self.AtualizaGrid;
Exit;
end;
QVenda.SQL := UpdateVenda.ModifySQL;
QVenda.Params.ParamByName('OLD_numnota').Value := umaVenda.getNumNota;
QVenda.Params.ParamByName('OLD_serienota').Value := umaVenda.getSerieNota;
end;
QVenda.Params.ParamByName('serienota').Value := umaVenda.getSerieNota;
if (umaVenda.getIdOrdemServico <> 0) then
QVenda.Params.ParamByName('idordemservico').Value := umaVenda.getIdOrdemServico;
QVenda.Params.ParamByName('idcliente').Value := umaVenda.getUmCliente.getId;
QVenda.Params.ParamByName('idusuario').Value := umaVenda.getUmUsuario.getIdUsuario;
QVenda.Params.ParamByName('idcondicaopagamento').Value := umaVenda.getUmaCondicaoPagamento.getId;
QVenda.Params.ParamByName('status').Value := umaVenda.getStatus;
QVenda.Params.ParamByName('observacao').Value := umaVenda.getObservacao;
QVenda.Params.ParamByName('datacadastro').Value := umaVenda.getDataCadastro;
QVenda.Params.ParamByName('dataalteracao').Value := umaVenda.getDataAlteracao;
QVenda.Params.ParamByName('dataemissao').Value := umaVenda.getDataEmissao;
QVenda.Params.ParamByName('datavenda').Value := umaVenda.getDataVenda;
QVenda.ExecSQL;
if umaVenda.getNumNota = 0 then
begin
QGenerica.Close;
QGenerica.SQL.Text := 'Select last_value as numNota from numnota_seq';
QGenerica.Open;
umaVenda.setNumNota(QGenerica.Fields.FieldByName('numNota').Value);
end;
numNotaAux := QProdutoVendanumnota.AsInteger; //Recupera o numNota da tabela relacional
//Faz Relacao com os Itens da Venda
for i := 1 to umaVenda.CountProdutos do
begin
if (umaVenda.getNumNota <> numNotaAux)then
begin
QProdutoVenda.SQL := UpdateProdutoVenda.InsertSQL;
cancelar := False;
end
else
begin
QProdutoVenda.SQL := UpdateProdutoVenda.ModifySQL;
if ((umaVenda.getStatus = 'FINALIZADA') ) then
cancelar := False
else
cancelar := True;
end;
QProdutoVenda.Params.ParamByName('numnota').Value := umaVenda.getNumNota;
QProdutoVenda.Params.ParamByName('serienota').Value := umaVenda.getSerieNota;
QProdutoVenda.Params.ParamByName('idproduto').Value := umaVenda.getProdutoVenda(i-1).getId;
QProdutoVenda.Params.ParamByName('valorunitario').Value := umaVenda.getProdutoVenda(i-1).getValorUnitario;
QProdutoVenda.Params.ParamByName('quantidade').Value := umaVenda.getProdutoVenda(i-1).getQtdProduto;
QProdutoVenda.Params.ParamByName('desconto').Value := umaVenda.getProdutoVenda(i-1).getDesconto;
umaContaReceber.setStatus('PENDENTE');
if (umaDaoContasReceber.VerificarContas(umaContaReceber)) or (umaVenda.getStatus <> 'CANCELADA') or (umaVenda.getTipo = False) then
begin
gerarContas := True;
if (count = 0) then
begin
for j := 1 to umaVenda.CountCalcProduto do
begin
quantidade := umaVenda.getProdutoVenda(j-1).getQuantidade;
if (cancelar) then //Aumenta o estoque do produto correspondente
umaVenda.getProdutoVenda(j-1).setQuantidade( quantidade + umaVenda.getCalcProduto(j-1).getTotalProduto)
else //Diminui o estoque do produto correspondente
umaVenda.getProdutoVenda(j-1).setQuantidade( quantidade - umaVenda.getCalcProduto(j-1).getTotalProduto);
umaDaoProduto.Salvar(umaVenda.getProdutoVenda(j-1));
count := count + 1;
end;
end;
end;
QProdutoVenda.ExecSQL;
end;
//Gera Contas a Receber
if (gerarContas) and (umaVenda.getTipo <> False) then
begin
umaContaReceber.setStatus('RECEBIDA');
for i := 1 to umaVenda.CountParcelas do
begin
if (umaVenda.getStatus <> 'FINALIZADA') and (not umaDaoContasReceber.VerificarContas(umaContaReceber)) then
begin
QContasReceber.SQL := UpdateContasReceber.ModifySQL;
QContasReceber.Params.ParamByName('OLD_numnota').Value := umaVenda.getNumNota;
QContasReceber.Params.ParamByName('OLD_serienota').Value := umaVenda.getSerieNota;
QContasReceber.Params.ParamByName('OLD_numparcela').Value := umaVenda.getParcelas(i-1).getNumParcela;
CP_Status := 'CANCELADA';
end
else
begin
QContasReceber.SQL := UpdateContasReceber.InsertSQL;
CP_Status := 'PENDENTE';
end;
QContasReceber.Params.ParamByName('numnota').Value := umaVenda.getNumNota;
QContasReceber.Params.ParamByName('serienota').Value := umaVenda.getSerieNota;
QContasReceber.Params.ParamByName('numparcela').Value := umaVenda.getParcelas(i-1).getNumParcela;
QContasReceber.Params.ParamByName('datavencimento').Value := DateToStr(Date + (umaVenda.getParcelas(i-1).getDias));
valor := StrToFloat(FormatFloat('#0.00',(umaVenda.getParcelas(i-1).getPorcentagem/100) * umaVenda.getTotalAux));
QContasReceber.Params.ParamByName('valor').Value := valor;
QContasReceber.Params.ParamByName('dataemissao').Value := DateToStr(Date);
// if umaVenda.CountParcelas = 1 then
// QContasReceber.Params.ParamByName('status').Value := 'RECEBIDA'
// else
QContasReceber.Params.ParamByName('status').Value := CP_Status;
QContasReceber.Params.ParamByName('idcliente').Value := umaVenda.getUmCliente.getId;
QContasReceber.Params.ParamByName('idusuario').Value := umaVenda.getUmUsuario.getIdUsuario;
QContasReceber.Params.ParamByName('idformapagamento').Value := umaVenda.getUmaCondicaoPagamento.getUmaFormaPagamento.getId;
QContasReceber.ExecSQL;
end;
end;
Commit;
if umaVenda.getStatus = 'CANCELADA' then
result := 'Venda Cancelada com sucesso!'
else
result := 'Venda salva com sucesso!';
except
on e: Exception do
begin
rollback;
if umaVenda.getStatus = 'CANCELADA' then
Result := 'Ocorreu um erro! Venda não foi cancelada. Erro: '+e.Message
else
Result := 'Ocorreu um erro! Venda não foi salva. Erro: '+e.Message;
end;
end;
end;
Self.AtualizaGrid;
end;
end.
|
unit HomeOrderItem;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Mask, DBCtrlsEh, ExtCtrls, DBLookupEh, Grids, DBGridEh,
DB, RpCon, RpConDS, RpBase, RpSystem, RpDefine, RpRave, ComCtrls, ToolWin;
type
THomeOrderItemForm = class(TForm)
Panel2: TPanel;
DBGridEh1: TDBGridEh;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
InsertButton: TToolButton;
EditButton: TToolButton;
DeleteButton: TToolButton;
ToolButton2: TToolButton;
Panel1: TPanel;
Label2: TLabel;
DBDateTimeEditEh1: TDBDateTimeEditEh;
Panel3: TPanel;
OKButton: TButton;
CancelButton: TButton;
Label1: TLabel;
DBEditEh1: TDBEditEh;
DBEditEh3: TDBEditEh;
Label3: TLabel;
Label4: TLabel;
DBEditEh4: TDBEditEh;
Label3a: TLabel;
Label4a: TLabel;
procedure EnabledButtons;
procedure HomeOrderPost;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure OKButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure InsertButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure DBEditEh3EditButtons0Click(Sender: TObject;
var Handled: Boolean);
procedure DBEditEh3KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure DBEditEh4EditButtons0Click(Sender: TObject;
var Handled: Boolean);
procedure DBEditEh4KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure DBGridEh1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure DBGridEh1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumnEh; State: TGridDrawState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
HomeOrderItemForm: THomeOrderItemForm;
implementation
uses StoreDM, HomeStructure, HomeTypeSelect, DivisionSelect;
{$R *.dfm}
procedure THomeOrderItemForm.EnabledButtons;
begin
// Если записей нету, то Деактивируем кнопки "Редактировать" и "Удалить",
// а если есть, Активируем.
if StoreDataModule.HomeStructureDataSet.IsEmpty then
begin
EditButton.Enabled := False;
EditButton.ShowHint := False;
DeleteButton.Enabled := False;
DeleteButton.ShowHint := False;
end
else
begin
EditButton.Enabled := True;
EditButton.ShowHint := True;
DeleteButton.Enabled := True;
DeleteButton.ShowHint := True;
end;
end;
procedure THomeOrderItemForm.HomeOrderPost;
begin
with StoreDataModule do
begin
if HomeOrderDataSet.Modified then
try
HomeOrderDataSet.Post;
HomeOrderDataSet.Close;
HomeOrderDataSet.Open
except
Application.MessageBox('Недопустимые значения данных',
'Ошибка ввода', mb_IconStop);
Abort;
end
else
HomeOrderDataSet.Cancel;
end;
end;
procedure THomeOrderItemForm.FormCreate(Sender: TObject);
begin
// OKButton.Visible := False;
// CancelButton.Caption := 'Exit';
EnabledButtons;
// Запоминаем положение Курсора, что бы вернуться на прежнее место
CurOrderID := StoreDataModule.HomeOrderDataSet['OrderID'];
StoreDataModule.TypePriceDataSet.Open;
Caption := 'Внутренняя накладная';
case StoreDataModule.HomeOrderDataSet['ProperID'] of
5:
begin
Caption := Caption + ' - Вввод остатков';
DBEditEh3.Visible := False;
Label3.Visible := False;
Label3a.Visible := False;
end;
6:
begin
Caption := Caption + ' - Излишки';
DBEditEh3.Visible := False;
Label3.Visible := False;
Label3a.Visible := False;
end;
7:
begin
Caption := Caption + ' - Списание';
DBEditEh4.Visible := False;
Label4.Visible := False;
Label4a.Visible := False;
end;
8:
begin
Caption := Caption + ' - Пересорт';
DBEditEh4.Visible := False;
Label4.Visible := False;
Label4a.Visible := False;
end;
9:
begin
Caption := Caption + ' - Перемещение';
Label3.Caption := 'Склад отправитель:';
Label3a.Left := 184;
Label4.Caption := 'Склад получатель:';
Label4a.Left := 184;
end;
end;
StoreDataModule.DivisionSelectQuery.Open;
if StoreDataModule.HomeOrderDataSet['OutDivisionID'] <> Null then
begin
StoreDataModule.DivisionSelectQuery.Locate('DivisionID', StoreDataModule.HomeOrderDataSet['OutDivisionID'], []);
Label3a.Caption := StoreDataModule.DivisionSelectQuery.FieldByName('DivisionName').AsString;
end;
if StoreDataModule.HomeOrderDataSet['InDivisionID'] <> Null then
begin
StoreDataModule.DivisionSelectQuery.Locate('DivisionID', StoreDataModule.HomeOrderDataSet['InDivisionID'], []);
Label4a.Caption := StoreDataModule.DivisionSelectQuery.FieldByName('DivisionName').AsString;
end;
StoreDataModule.DivisionSelectQuery.Close;
end;
procedure THomeOrderItemForm.FormShow(Sender: TObject);
begin
{ if StoreDataModule.HomeOrderDataSet.State = dsInsert then
begin
OKButton.Visible := True;
CancelButton.Caption := 'Cancel';
end;{}
end;
procedure THomeOrderItemForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
with StoreDataModule do
try
try
if ModalResult = mrOk then
begin
if HomeOrderDataSet.Modified then
HomeOrderDataSet.Post;
HomeTransaction.Commit;
end
else
HomeTransaction.Rollback;
except
Application.MessageBox('Недопустимые значения данных',
'Ошибка ввода', mb_IconStop);
Abort;
end; {try except}
finally
if TypePriceDataSet.Active = True then
TypePriceDataSet.Close;
// Открываем Таблицы "Документы", "Строки Документов" после Commit(Rollback)'а транзакции
HomeOrderDataSet.Open;
HomeStructureDataSet.Open;
// Возвращаемся на прежнее место
// HomeOrderDataSet.Locate('OrderID', CurOrderID, []);
end; {try finally}
Release;
end;
procedure THomeOrderItemForm.OKButtonClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure THomeOrderItemForm.CancelButtonClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure THomeOrderItemForm.InsertButtonClick(Sender: TObject);
begin
{ with StoreDataModule do
try
if HomeOrderDataSet.Modified then
HomeOrderDataSet.Post;
except
Application.MessageBox('Недопустимые значения данных',
'Ошибка ввода', mb_IconStop);
Abort;
end;{}
StoreDataModule.HomeStructureDataSet.Append;
StoreDataModule.HomeStructureDataSet['OrderID'] := StoreDataModule.HomeOrderDataSet['OrderID'];
if StoreDataModule.HomeOrderDataSet['ProperID'] = 6 then
begin
StoreDataModule.HomeStructureDataSet['Type'] := -1;
HomeStructureForm := THomeStructureForm.Create(Self);
HomeStructureForm.ShowModal;
end;
if StoreDataModule.HomeOrderDataSet['ProperID'] = 7 then
begin
StoreDataModule.HomeStructureDataSet['Type'] := 1;
HomeStructureForm := THomeStructureForm.Create(Self);
HomeStructureForm.ShowModal;
end;
if StoreDataModule.HomeOrderDataSet['ProperID'] = 8 then
begin
//Выбираем Вид Накладной
HomeTypeSelectForm := THomeTypeSelectForm.Create(Self);
HomeTypeSelectForm.ShowModal;
if HomeTypeSelectForm.ModalResult = mrOK then
begin
StoreDataModule.HomeStructureDataSet['Type'] := CurType;
HomeStructureForm := THomeStructureForm.Create(Self);
HomeStructureForm.ShowModal;
end
else
begin
StoreDataModule.HomeStructureDataSet.Cancel;
end;
end;
if StoreDataModule.HomeOrderDataSet['ProperID'] = 9 then
begin
StoreDataModule.HomeStructureDataSet['Type'] := 0;
HomeStructureForm := THomeStructureForm.Create(Self);
HomeStructureForm.ShowModal;
end;
end;
procedure THomeOrderItemForm.EditButtonClick(Sender: TObject);
begin
StoreDataModule.HomeStructureDataSet.Edit;
HomeStructureForm := THomeStructureForm.Create(Self);
HomeStructureForm.ShowModal;
end;
procedure THomeOrderItemForm.DeleteButtonClick(Sender: TObject);
var
HomeStrucStr : String;
begin
HomeStrucStr := StoreDataModule.HomeStructureDataSet.FieldByName('ProductFullName').AsString;
if Application.MessageBox(PChar('Вы действительно хотите удалить запись"' +
HomeStrucStr + '"?'),
'Удаление записи',
mb_YesNo + mb_IconQuestion + mb_DefButton2) = idYes then
try
StoreDataModule.HomeStructureDataSet.Delete;
except
Application.MessageBox(PChar('Запись "' + HomeStrucStr + '" удалять нельзя.'),
'Ошибка удаления', mb_IconStop);
end;
end;
procedure THomeOrderItemForm.DBEditEh3EditButtons0Click(Sender: TObject;
var Handled: Boolean);
begin
with StoreDataModule do
try
if HomeOrderDataSet.State = dsBrowse then
HomeOrderDataSet.Edit;
if HomeOrderDataSet['OutDivisionID'] <> Null then
CurDivisionID := HomeOrderDataSet['OutDivisionID'];
// перестраиваем запрос, что бы не видно было "Склад получатель"
if HomeOrderDataSet['InDivisionID'] <> null then
DivisionSelectQuery.SQL.Strings[3] := 'AND ("DivisionID" <> ' + HomeOrderDataSet.FieldByName('InDivisionID').AsString + ')';
DivisionSelectForm := TDivisionSelectForm.Create(Self);
DivisionSelectForm.ShowModal;
if DivisionSelectForm.ModalResult = mrOk then
begin
HomeOrderDataSet['OutDivisionID'] := CurDivisionID;
HomeOrderPost;
Label3a.Caption := CurDivisionName;
end
else
HomeOrderDataSet.Cancel;
finally
DivisionSelectQuery.SQL.Strings[3] := '';
end;
DBGridEh1.SetFocus;
end;
procedure THomeOrderItemForm.DBEditEh3KeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
var
h: Boolean;
begin
if Key = VK_F3 then
DBEditEh3EditButtons0Click(Self, h);
end;
procedure THomeOrderItemForm.DBEditEh4EditButtons0Click(Sender: TObject;
var Handled: Boolean);
begin
with StoreDataModule do
try
if HomeOrderDataSet.State = dsBrowse then
HomeOrderDataSet.Edit;
if HomeOrderDataSet['InDivisionID'] <> Null then
CurDivisionID := HomeOrderDataSet['InDivisionID'];
// перестраиваем запрос, что бы не видно было "Склад отправитель"
if HomeOrderDataSet['OutDivisionID'] <> null then
DivisionSelectQuery.SQL.Strings[3] := 'AND ("DivisionID" <> ' + HomeOrderDataSet.FieldByName('OutDivisionID').AsString + ')';
DivisionSelectForm := TDivisionSelectForm.Create(Self);
DivisionSelectForm.ShowModal;
if DivisionSelectForm.ModalResult = mrOk then
begin
HomeOrderDataSet['InDivisionID'] := CurDivisionID;
HomeOrderPost;
Label4a.Caption := CurDivisionName;
end
else
HomeOrderDataSet.Cancel;
finally
DivisionSelectQuery.SQL.Strings[3] := '';
end;
DBGridEh1.SetFocus;
end;
procedure THomeOrderItemForm.DBEditEh4KeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
var
h: Boolean;
begin
if Key = VK_F3 then
DBEditEh4EditButtons0Click(Self, h);
end;
procedure THomeOrderItemForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
OKButton.Click;
end;
procedure THomeOrderItemForm.DBGridEh1KeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
case Key of
VK_F2 : InsertButton.Click;
VK_F3 : EditButton.Click;
VK_F8 : DeleteButton.Click;
end;
end;
procedure THomeOrderItemForm.DBGridEh1DrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumnEh;
State: TGridDrawState);
var
ItemNo: String;
begin
//Проставляем номера по порядку в строках Документа
with DBGridEh1.Canvas do
begin
if StoreDataModule.HomeStructureDataSet.RecNo <> 0 then
ItemNo := IntToStr(StoreDataModule.HomeStructureDataSet.RecNo)
else
ItemNo := '';
if Column.Index = 0 then
begin
FillRect(Rect);
TextOut(Rect.Right - 3 - TextWidth(ItemNo), Rect.Top, ItemNo);
end
else
DBGridEh1.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
end;
end.
|
unit uFrmSendEmail;
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls,
ComCtrls, ACBrMail, types, ACBrBase, Menus, ExtCtrls,Windows, DB,
DBClient, Variants;
type
{ TForm1 }
TFrmSendMail = class(TForm)
ACBrMail1: TACBrMail;
MainMenu1: TMainMenu;
Opes1: TMenuItem;
Configuraes1: TMenuItem;
N1: TMenuItem;
Fechar1: TMenuItem;
Panel1: TPanel;
Panel2: TPanel;
listaCliente: TListBox;
Panel3: TPanel;
Label6: TLabel;
edtDe: TEdit;
Label2: TLabel;
edSubject: TEdit;
Panel4: TPanel;
ProgressBar1: TProgressBar;
Panel5: TPanel;
bEnviar: TButton;
pnlBody: TPanel;
Label3: TLabel;
mAltBody: TMemo;
Label5: TLabel;
mLog: TMemo;
listEmails: TListBox;
cdsListaEnviados: TClientDataSet;
cdsListaEnviadosemail: TStringField;
cdsListaEnviadosarquivo: TStringField;
Label1: TLabel;
lblEnviandoPara: TLabel;
procedure ACBrMail1AfterMailProcess(Sender: TObject);
procedure ACBrMail1BeforeMailProcess(Sender: TObject);
procedure ACBrMail1MailException(const AMail: TACBrMail;
const E: Exception; var ThrowIt: Boolean);
procedure ACBrMail1MailProcess(const AMail: TACBrMail;
const aStatus: TMailStatus);
procedure bEnviarClick(Sender: TObject);
procedure Fechar1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Configuraes1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
procedure AjustaParametrosDeEnvio;
Procedure CarregarListaClientes(aNomeFile : String);
Procedure CarregarListaEmails(aNomeFile : String);
Procedure CarregarDados();
Procedure AddRegistro(aEmail, aFile : String);
{ private declarations }
public
{ public declarations }
end;
var
FrmSendMail: TFrmSendMail;
implementation
Uses mimemess, uFrmConfigEmail, udmADM;
{$R *.dfm}
{ TForm1 }
procedure TFrmSendMail.bEnviarClick(Sender: TObject);
var
Dir, ArqXML, aEmail, aArquivo: String;
MS: TMemoryStream;
P, N, I, posicao, iTamanho : Integer;
begin
mLog.Lines.Clear;
ProgressBar1.Position := 1;
lblEnviandoPara.Caption := '';
Dir := ExtractFilePath(ParamStr(0))+'PDF\';
P := pos(' - ', edSubject.Text);
if P > 0 then
begin
N := StrToIntDef( copy(edSubject.Text, P+3, 5), 0) + 1;
edSubject.Text := copy(edSubject.Text, 1, P+2) + IntToStr(N);
end;
bEnviar.Enabled := False;
Try
// mensagem principal do e-mail. pode ser html ou texto puro
//if cbUsarTXT.Checked then
for i:= 0 to listEmails.Items.Count-1 do
begin
posicao := pos('::',listEmails.Items[i]);
iTamanho := Length(listEmails.Items[i]);
aEmail := Copy(listEmails.Items[i],1,posicao-1);
aArquivo := Copy(listEmails.Items[i],posicao+2, iTamanho) ;
if not (cdsListaEnviados.Locate('email;arquivo',
VarArrayOf([aEmail,aArquivo]),[])) then
begin
lblEnviandoPara.Caption := 'Enviando para: '+aEmail;
ACBrMail1.Clear;
ACBrMail1.IsHTML := False;
ACBrMail1.Subject := edSubject.Text;
AjustaParametrosDeEnvio;
ACBrMail1.AddAddress(aEmail,aEmail);
ACBrMail1.AltBody.Assign( mAltBody.Lines );
// Anexo
if FileExists(Dir+aArquivo) then
ACBrMail1.AddAttachment(Dir+aArquivo, 'Boleto');
ACBrMail1.Send( False );
Sleep(100);
// Add Email enviado
AddRegistro(aEmail, aArquivo);
mLog.Lines.Clear;
End;
End;
Application.MessageBox(PChar('Envio concluído.'), 'Concluído',MB_OK+MB_ICONINFORMATION);
Finally
bEnviar.Enabled := True;
lblEnviandoPara.Caption := 'Concluído';
End;
Application.ProcessMessages;
end;
procedure TFrmSendMail.ACBrMail1BeforeMailProcess(Sender: TObject);
begin
mLog.Lines.Add('Antes de Enviar o email: '+ TACBrMail(Sender).Subject);
end;
procedure TFrmSendMail.ACBrMail1MailException(const AMail: TACBrMail;
const E: Exception; var ThrowIt: Boolean);
begin
ShowMessage(E.Message);
ThrowIt := False;
mLog.Lines.Add('*** Erro ao Enviar o email: '+ AMail.Subject);
end;
procedure TFrmSendMail.ACBrMail1MailProcess(const AMail: TACBrMail;
const aStatus: TMailStatus);
begin
ProgressBar1.Position := Integer( aStatus );
case aStatus of
pmsStartProcess:
mLog.Lines.Add('Iniciando processo de envio.');
pmsConfigHeaders:
mLog.Lines.Add('Configurando o cabeçalho do e-mail.');
pmsLoginSMTP:
mLog.Lines.Add('Logando no servidor de e-mail.');
pmsStartSends:
mLog.Lines.Add('Iniciando os envios.');
pmsSendTo:
mLog.Lines.Add('Processando lista de destinatários.');
pmsSendCC:
mLog.Lines.Add('Processando lista CC.');
pmsSendBCC:
mLog.Lines.Add('Processando lista BCC.');
pmsSendReplyTo:
mLog.Lines.Add('Processando lista ReplyTo.');
pmsSendData:
mLog.Lines.Add('Enviando dados.');
pmsLogoutSMTP:
mLog.Lines.Add('Fazendo Logout no servidor de e-mail.');
pmsDone:
begin
mLog.Lines.Add('Terminando e limpando.');
ProgressBar1.Position := ProgressBar1.Max;
end;
end;
mLog.Lines.Add(' '+AMail.Subject);
Application.ProcessMessages;
end;
procedure TFrmSendMail.ACBrMail1AfterMailProcess(Sender: TObject);
begin
mLog.Lines.Add('Depois de Enviar o email: '+ TACBrMail(Sender).Subject);
end;
procedure TFrmSendMail.AjustaParametrosDeEnvio;
begin
ACBrMail1.From := dmADM.cdsConfigEmailLOGIN.AsString; // 'one.supersonic2@gmail.com';
ACBrMail1.FromName := dmADM.cdsConfigEmailLOGIN.AsString; // 'Fula do Tal';
ACBrMail1.Host := dmADM.cdsConfigEmailSMTP.AsString; // 'smtp.gmail.com'; // troque pelo seu servidor smtp
ACBrMail1.Username := dmADM.cdsConfigEmailLOGIN.AsString; // 'one.supersonic2@gmail.com';
ACBrMail1.Password := dmADM.cdsConfigEmailSENHA.AsString;
ACBrMail1.Port := dmADM.cdsConfigEmailPORTA.AsString; // troque pela porta do seu servidor smtp
ACBrMail1.SetTLS := False;
If (dmADM.cdsConfigEmailTSL.AsBoolean) then
ACBrMail1.SetTLS := True; // Verifique se o seu servidor necessita SSL
ACBrMail1.SetSSL := False;
If (dmADM.cdsConfigEmailSSL.AsBoolean) then
ACBrMail1.SetSSL := True;
//ACBrMail1.AddCC('roneyweb@ig.com.br'); // opcional
//ACBrMail1.AddReplyTo('um_email'); // opcional
//ACBrMail1.AddBCC('um_email'); // opcional
ACBrMail1.Priority := MP_normal;
ACBrMail1.ReadingConfirmation := False; // solicita confirmação de leitura
end;
procedure TFrmSendMail.Fechar1Click(Sender: TObject);
begin
Close;
end;
procedure TFrmSendMail.CarregarListaClientes(aNomeFile: String);
var
ArqTxt : TextFile;
linha : string;
begin
listaCliente.Clear;
AssignFile(ArqTxt,aNomeFile);
Try
Reset(ArqTxt);
while not eof(ArqTxt) do
begin
// 0000010::DROGATERPI
Readln(ArqTxt, Linha);
listaCliente.Items.Add(linha);
end;
Finally
Closefile(ArqTxt);
End;
end;
procedure TFrmSendMail.FormShow(Sender: TObject);
begin
CarregarListaClientes('listaclientes.txt');
CarregarListaEmails('listaemail.txt');
//
CarregarDados;
cdsListaEnviados.Close;
cdsListaEnviados.Open;
cdsListaEnviados.EmptyDataSet;
//
lblEnviandoPara.Caption := '';
end;
procedure TFrmSendMail.CarregarListaEmails(aNomeFile: String);
var
ArqTxt : TextFile;
linha : string;
iCont : Integer;
begin
listEmails.Clear;
iCont := 0;
AssignFile(ArqTxt,aNomeFile);
Try
Reset(ArqTxt);
while not eof(ArqTxt) do
begin
// roneyweb@ig.com.br::0000010_000321801_05062007.PDF
Readln(ArqTxt, Linha);
listEmails.Items.Add(linha);
iCont := iCont + 1;
end;
Finally
Closefile(ArqTxt);
End;
//
Label1.Caption := 'Registro(s): '+InttoStr(iCont);
end;
procedure TFrmSendMail.Configuraes1Click(Sender: TObject);
begin
Application.CreateForm(TFrmConfigEmail, FrmConfigEmail);
Try
FrmConfigEmail.ShowModal;
Finally
FrmConfigEmail.Free;
End;
CarregarDados;
end;
procedure TFrmSendMail.CarregarDados;
begin
edtDe.Text := dmADM.cdsConfigEmailNOME_DE.AsString;
edSubject.Text := dmADM.cdsConfigEmailASSUNTO.AsString;
mAltBody.Lines.Text := dmADM.cdsConfigEmailMENSAGEM.AsString;
//
end;
procedure TFrmSendMail.AddRegistro(aEmail, aFile: String);
begin
With cdsListaEnviados do
begin
Append;
FieldByname('email').AsString := aEmail;
FieldByname('arquivo').AsString := aFile;
Post;
End;
end;
procedure TFrmSendMail.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
cdsListaEnviados.EmptyDataSet;
cdsListaEnviados.Close;
end;
end.
|
unit FungsiLain;
interface
uses Windows, SysUtils, TlHelp32, Messages, Dialogs;
function GetVersion(ApplicationName: string) : string;
function GetProcessID(ProcessName: String):Integer;
function GetHWndByPID(const hPID: THandle): THandle;
procedure KillProcess(hWindowHandle: HWND);
implementation
procedure KillProcess(hWindowHandle: HWND);
var
hprocessID: INTEGER;
processHandle: THandle;
DWResult: DWORD;
begin
SendMessageTimeout(hWindowHandle, WM_CLOSE, 0, 0,
SMTO_ABORTIFHUNG or SMTO_NORMAL, 5000, DWResult);
if isWindow(hWindowHandle) then
begin
// PostMessage(hWindowHandle, WM_QUIT, 0, 0);
{ Get the process identifier for the window}
GetWindowThreadProcessID(hWindowHandle, @hprocessID);
if hprocessID <> 0 then
begin
{ Get the process handle }
processHandle := OpenProcess(PROCESS_TERMINATE or PROCESS_QUERY_INFORMATION, False, hprocessID);
if processHandle <> 0 then
begin
{ Terminate the process }
TerminateProcess(processHandle, 0);
CloseHandle(ProcessHandle);
end;
end;
end;
end;
function GetVersion(ApplicationName: string) : string;
CONST
VAR_FILE_INFO = '\VarFileInfo\Translation';
STRING_FILE_INFO = '\StringFileInfo\';
FILE_VERSION = 'FileVersion';
VAR
iVersionInfoSize: integer;
dwHandle: dWord;
strVersionInfoBuffer: string;
iVersionValueSize: cardinal;
pTranslationTable: pLongInt;
strVersionValue: string;
pVersionValue: pChar;
function QueryValue(ValueStr: String): String;
Begin
IF VerQueryValue(PChar(strVersionInfoBuffer),
PChar(strVersionValue + ValueStr),
Pointer(pVersionValue),
iVersionValueSize) THEN
Result := String(pVersionValue)
//ELSE
// Result := FCurrentVersion;
end;
begin
iVersionInfoSize := GetFileVersionInfoSize(PChar(ApplicationName), dwHandle);
IF iVersionInfoSize > 0 THEN
Begin
SetLength(strVersionInfoBuffer, iVersionInfoSize);
IF GetFileVersionInfo(PChar(ApplicationName),dwHandle,
iVersionInfoSize,
PChar(strVersionInfoBuffer))
THEN
IF VerQueryValue(PChar(strVersionInfoBuffer),
PChar(VAR_FILE_INFO),
Pointer(pTranslationTable),
iVersionValueSize)
THEN
strVersionValue := Format('%s%.4x%.4x%s',
[STRING_FILE_INFO,
LoWord(pTranslationTable^),
HiWord(pTranslationTable^),'\']);
End;
Result := QueryValue(FILE_VERSION);
end;
function GetProcessID(ProcessName: String):Integer;
var Handle: tHandle;
Process: tProcessEntry32;
GotProcess: Boolean;
begin
Handle:=CreateToolHelp32SnapShot(TH32CS_SNAPALL,0);
Process.dwSize:=SizeOf(Process);
GotProcess := Process32First(Handle,Process);
{$B-}
if GotProcess and (Process.szExeFile<>ProcessName) then
repeat
GotProcess := Process32Next(Handle,Process);
until (not GotProcess) or (Process.szExeFile=ProcessName);
{$B+}
if GotProcess then
Result:=Process.th32ProcessID
else
Result:=0;
CloseHandle(Handle);
end;
function GetHWndByPID(const hPID: THandle): THandle;
type
PEnumInfo = ^TEnumInfo;
TEnumInfo = record
ProcessID: DWORD;
HWND: THandle;
end;
function EnumWindowsProc(Wnd: DWORD; var EI: TEnumInfo): Bool; stdcall;
var
PID: DWORD;
begin
GetWindowThreadProcessID(Wnd, @PID);
Result := (PID <> EI.ProcessID) or (not IsWindowEnabled(WND)) or (not IsWindowVisible(WND));
if not Result then EI.HWND := WND; //break on return FALSE
end;
function FindMainWindow(PID: DWORD): DWORD;
var
EI: TEnumInfo;
begin
EI.ProcessID := PID;
EI.HWND := 0;
EnumWindows(@EnumWindowsProc, Integer(@EI));
Result := EI.HWND;
//showmessage(inttostr(result));
end;
begin
if hPID<>0 then
Result:=FindMainWindow(hPID)
else
Result:=0;
end;
end.
|
unit SearchComponentOrFamilyQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap;
type
TSearchComponentOrFamilyW = class(TDSWrap)
private
FParentProductID: TFieldWrap;
FID: TFieldWrap;
FFamilyID: TFieldWrap;
FFamilyValue: TFieldWrap;
FProducer: TFieldWrap;
FProducerParamSubParamID: TParamWrap;
FProducerParam: TParamWrap;
FValue: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
procedure ApplyFamilyFilter;
procedure ApplyComponentFilter;
property ParentProductID: TFieldWrap read FParentProductID;
property ID: TFieldWrap read FID;
property FamilyID: TFieldWrap read FFamilyID;
property FamilyValue: TFieldWrap read FFamilyValue;
property Producer: TFieldWrap read FProducer;
property ProducerParamSubParamID: TParamWrap read FProducerParamSubParamID;
property ProducerParam: TParamWrap read FProducerParam;
property Value: TFieldWrap read FValue;
end;
TQuerySearchComponentOrFamily = class(TQueryBase)
private
FW: TSearchComponentOrFamilyW;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
function SearchByValue(const AComponentName: string): Integer;
function SearchByValueLike(const AComponentNames: string): Integer;
function SearchByValues(const AComponentNames: string): Integer;
function SearchComponent(const AComponentName: string): Integer; overload;
function SearchComponent(AParentID: Integer; const AComponentName: string)
: Integer; overload;
function SearchComponentWithProducer(const AComponentName,
AProducer: string): Integer; overload;
function SearchComponentWithProducer(const AComponentName: string)
: Integer; overload;
function SearchFamily(const AFamilyName: string): Integer;
property W: TSearchComponentOrFamilyW read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses StrHelper, System.Strutils, DefaultParameters;
constructor TQuerySearchComponentOrFamily.Create(AOwner: TComponent);
begin
inherited;
FW := TSearchComponentOrFamilyW.Create(FDQuery);
end;
function TQuerySearchComponentOrFamily.SearchComponentWithProducer
(const AComponentName, AProducer: string): Integer;
var
AStipulation: string;
ASQL: string;
begin
Assert(not AComponentName.IsEmpty);
Assert(not AProducer.IsEmpty);
// Добавляем Производителя
ASQL := SQL;
ASQL := ASQL.Replace('/* Producer', '', [rfReplaceAll]);
ASQL := ASQL.Replace('Producer */', '', [rfReplaceAll]);
ASQL := ReplaceInSQL(ASQL, Format('pv.Value = :%s',
[W.ProducerParam.FieldName]), 2);
// условие
AStipulation := Format('upper(%s) = upper(:%s)',
[W.Value.FullName, W.Value.FieldName]);
FDQuery.SQL.Text := ReplaceInSQL(ASQL, AStipulation, 0);
SetParamType(W.Value.FieldName, ptInput, ftWideString);
SetParamType(W.ProducerParamSubParamID.FieldName);
SetParamType(W.ProducerParam.FieldName, ptInput, ftWideString);
// Ищем
Result := Search([W.Value.FieldName, W.ProducerParamSubParamID.FieldName,
W.ProducerParam.FieldName], [AComponentName,
TDefaultParameters.ProducerParamSubParamID, AProducer]);
end;
function TQuerySearchComponentOrFamily.SearchComponentWithProducer
(const AComponentName: string): Integer;
var
AStipulation: string;
ASQL: string;
begin
Assert(not AComponentName.IsEmpty);
// Добавляем Производителя
ASQL := SQL;
ASQL := ASQL.Replace('/* Producer', '', [rfReplaceAll]);
ASQL := ASQL.Replace('Producer */', '', [rfReplaceAll]);
// Меняем условие
AStipulation := Format('upper(%s) = upper(:%s)',
[W.Value.FullName, W.Value.FieldName]);
FDQuery.SQL.Text := ReplaceInSQL(ASQL, AStipulation, 0);
SetParamType(W.ProducerParamSubParamID.FieldName);
SetParamType(W.Value.FieldName, ptInput, ftWideString);
// Ищем
Result := Search([W.Value.FieldName, W.ProducerParamSubParamID.FieldName],
[AComponentName, TDefaultParameters.ProducerParamSubParamID]);
end;
function TQuerySearchComponentOrFamily.SearchByValueLike(const AComponentNames
: string): Integer;
var
AStipulation: string;
m: TArray<String>;
S: String;
begin
Assert(not AComponentNames.IsEmpty);
m := AComponentNames.Split([',']);
AStipulation := '';
// Формируем несколько условий
for S in m do
begin
AStipulation := IfThen(AStipulation.IsEmpty, '', ' or ');
AStipulation := AStipulation + Format('%s like %s',
[W.Value.FullName, QuotedStr(S + '%')]);
end;
// Делаем замену в первоначальном SQL запросе
FDQuery.SQL.Text := ReplaceInSQL(SQL, AStipulation, 0);
Result := Search([], []);
end;
function TQuerySearchComponentOrFamily.SearchByValues(const AComponentNames
: string): Integer;
var
AStipulation: string;
begin
Assert(not AComponentNames.IsEmpty);
AStipulation := Format('instr('',''||:%s||'','', '',''||%s||'','') > 0',
[W.Value.FieldName, W.Value.FullName]);
FDQuery.SQL.Text := ReplaceInSQL(SQL, AStipulation, 0);
SetParamType(W.Value.FieldName, ptInput, ftWideString);
Result := Search([W.Value.FieldName], [AComponentNames]);
end;
function TQuerySearchComponentOrFamily.SearchByValue(const AComponentName
: string): Integer;
begin
Assert(not AComponentName.IsEmpty);
Result := SearchEx([TParamRec.Create(W.Value.FullName, AComponentName,
ftWideString, True)]);
end;
function TQuerySearchComponentOrFamily.SearchFamily(const AFamilyName
: string): Integer;
var
ANewSQL: string;
begin
Assert(not AFamilyName.IsEmpty);
// Делаем замену в первоначальном SQL запросе
ANewSQL := ReplaceInSQL(SQL, Format('%s is null',
[W.ParentProductID.FullName]), 0);
FDQuery.SQL.Text := ReplaceInSQL(ANewSQL, Format('upper(%s) = upper(:%s)',
[W.Value.FullName, W.Value.FieldName]), 1);
SetParamType(W.Value.FieldName, ptInput, ftWideString);
// Ищем
Result := Search([W.Value.FieldName], [AFamilyName]);
end;
function TQuerySearchComponentOrFamily.SearchComponent(AParentID: Integer;
const AComponentName: string): Integer;
begin
Assert(AParentID > 0);
Assert(not AComponentName.IsEmpty);
Result := SearchEx([TParamRec.Create(W.Value.FullName, AComponentName,
ftWideString, True), TParamRec.Create(W.ParentProductID.FullName,
AParentID)]);
end;
function TQuerySearchComponentOrFamily.SearchComponent(const AComponentName
: string): Integer;
var
ANewSQL: string;
begin
Assert(not AComponentName.IsEmpty);
// Делаем замену в первоначальном SQL запросе
ANewSQL := ReplaceInSQL(SQL, Format('not (%s is null)',
[W.ParentProductID.FullName]), 0);
FDQuery.SQL.Text := ReplaceInSQL(ANewSQL, Format('upper(%s) = upper(:%s)',
[W.Value.FullName, W.Value.FieldName]), 1);
SetParamType(W.Value.FieldName, ptInput, ftWideString);
// Ищем
Result := Search([W.Value.FieldName], [AComponentName]);
end;
constructor TSearchComponentOrFamilyW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'p.ID', '', True);
FParentProductID := TFieldWrap.Create(Self, 'p.ParentProductID');
FProducer := TFieldWrap.Create(Self, 'Producer');
FValue := TFieldWrap.Create(Self, 'p.Value');
FFamilyID := TFieldWrap.Create(Self, 'FamilyID');
FFamilyValue := TFieldWrap.Create(Self, 'FamilyValue');
FProducerParamSubParamID := TParamWrap.Create(Self,
'ProducerParamSubParamID');
FProducerParam := TParamWrap.Create(Self, 'Producer');
end;
procedure TSearchComponentOrFamilyW.ApplyFamilyFilter;
begin
DataSet.Filter := Format('%s = NULL', [ParentProductID.FieldName]);
DataSet.Filtered := True;
end;
procedure TSearchComponentOrFamilyW.ApplyComponentFilter;
begin
DataSet.Filter := Format('%s <> NULL', [ParentProductID.FieldName]);
DataSet.Filtered := True;
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OpenGL;
const
ImageWidth = 64;
ImageHeight = 64;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
hrc: HGLRC;
Image : Array [0..ImageHeight-1, 0..ImageWidth - 1, 0..2] of GLUbyte;
procedure MakeImage;
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
{=======================================================================
Создание образа шахматной доски}
procedure TfrmGL.MakeImage;
var
i, j : Integer;
begin
For i := 0 to ImageHeight - 1 do
For j := 0 to ImageWidth - 1 do begin
If ((i and 8) = 0) xor ((j and 8) = 0)
then begin
Image[i][j][0] := 0;
Image[i][j][1] := 0;
Image[i][j][2] := 255;
end
else begin
Image[i][j][0] := 255;
Image[i][j][1] := 0;
Image[i][j][2] := 0;
end;
end;
end;
{=======================================================================
Рисование картинки}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
wglMakeCurrent(Canvas.Handle, hrc);
glViewPort (0, 0, ClientWidth, ClientHeight); // область вывода
glClearColor (0.5, 0.5, 0.75, 1.0);
glClear (GL_COLOR_BUFFER_BIT);
glRasterPos2f(-0.25, -0.25);
glDrawPixels(ImageWidth, ImageHeight, GL_RGB, GL_UNSIGNED_BYTE, @Image);
SwapBuffers(Canvas.Handle);
wglMakeCurrent(0, 0);
end;
{=======================================================================
Формат пикселя}
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
SetDCPixelFormat(Canvas.Handle);
hrc := wglCreateContext(Canvas.Handle);
MakeImage;
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglDeleteContext(hrc);
end;
end.
|
library tclsampleext;
{$mode objfpc}{$H+}
{$packrecords C}
{ Strings are UTF8 by default }
{$codepage utf8}
uses {$IFDEF UNIX} {$IFDEF UseCThreads}
cthreads, {$ENDIF} {$ENDIF}
Classes,
SysUtils,
ctypes,
tcl;
type
TMailingListRecord = record
FirstName: string;
end;
PMailingListRecord = ^TMailingListRecord;
procedure Square_Del_Cmd(clientData: ClientData); cdecl;
var
PML: PMailingListRecord;
begin
PML := PMailingListRecord(clientData);
WriteLn('Clearing Square clientData which had firstname: ' + PML^.FirstName);
Dispose(PML);
end;
function Square_Cmd(clientData: ClientData; interp: PTcl_Interp;
objc: cint; objv: PPTcl_Obj): cint; cdecl;
var
i: cint;
ml: TMailingListRecord;
begin
ml := PMailingListRecord(clientData)^;
WriteLn('FirstName in ClientData ' + ml.FirstName);
if objc <> 2 then
begin
Tcl_WrongNumArgs(interp, 1, objv, 'value');
Exit(TCL_ERROR);
end;
WriteLn('objv[1]:' + Tcl_GetString(objv[1]));
if Tcl_GetIntFromObj(interp, objv[1], @i) <> TCL_OK then
begin
Exit(TCL_ERROR);
end;
Tcl_SetObjResult(interp, Tcl_NewIntObj(i * i));
Result := TCL_OK;
end;
function Tclsampleext_Init(interp: PTcl_Interp): cint; cdecl;
var
clientData: PMailingListRecord;
VarValue: PChar;
VarString: string;
begin
New(clientData);
clientData^.FirstName := 'Mark';
Tcl_InitStubs(interp, '8.5', 0);
Tcl_PkgProvideEx(interp, 'test', '0.1', nil);
Tcl_CreateObjCommand(interp, 'square', @Square_Cmd, clientData, @Square_Del_Cmd);
Tcl_Eval(interp, 'set a "\u0e01\u0150\u0104" ; puts $a');
VarValue := Tcl_GetVar(interp, 'a', TCL_GLOBAL_ONLY);
Tcl_SetVar(interp, 'b', VarValue, TCL_GLOBAL_ONLY);
Tcl_Eval(interp, 'puts "Via Tcl: $b"');
VarString := StrPas(VarValue);
WriteLn(Concat('And via Pascal: ' , VarString));
Result := TCL_OK;
end;
exports Tclsampleext_Init;
end.
|
(***********************************************************)
(* xPLRFX *)
(* part of Digital Home Server project *)
(* http://www.digitalhomeserver.net *)
(* info@digitalhomeserver.net *)
(***********************************************************)
unit uxPLRFX_0x52;
interface
Uses uxPLRFXConst, u_xPL_Message, u_xpl_common, uxPLRFXMessages;
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
implementation
Uses SysUtils;
(*
Type $52 - Temperature/Humidity Sensors
Buffer[0] = packetlength = $0A;
Buffer[1] = packettype
Buffer[2] = subtype
Buffer[3] = seqnbr
Buffer[4] = id1
Buffer[5] = id2
Buffer[6] = temperaturehigh:7/temperaturesign:1
Buffer[7] = temperaturelow
Buffer[8] = humidity
Buffer[9] = humidity_status
Buffer[10] = battery_level:4/rssi:4
Test strings :
0A520211700200A72D0089
0A5205D42F000082590379
xPL Schema
sensor.basic
{
device=(th1-th10) 0x<hex sensor id>
type=temp
current=<degrees celsius>
units=c
}
sensor.basic
{
device=(th1-th10) 0x<hex sensor id>
type=humidity
current=(0-100)
description=normal|comfort|dry|wet
}
sensor.basic
{
device=(th1-th10) 0x<hex sensor id>
type=battery
current=0-100
}
*)
const
// Type
TEMPHUM = $52;
// Subtype
TH1 = $01; //
TH2 = $02;
TH3 = $03;
TH4 = $04;
TH5 = $05;
TH6 = $06;
TH7 = $07;
TH8 = $08;
TH9 = $09;
TH10 = $0A;
// Humidity status
HUM_NORMAL = $00;
HUM_COMFORT = $01;
HUM_DRY = $02;
HUM_WET = $03;
// Humidity status strings
HUM_NORMAL_STR = 'normal';
HUM_COMFORT_STR = 'comfort';
HUM_DRY_STR = 'dry';
HUM_WET_STR = 'wet';
var
SubTypeArray : array[1..10] of TRFXSubTypeRec =
((SubType : TH1; SubTypeString : 'th1'),
(SubType : TH2; SubTypeString : 'th2'),
(SubType : TH3; SubTypeString : 'th3'),
(SubType : TH4; SubTypeString : 'th4'),
(SubType : TH5; SubTypeString : 'th5'),
(SubType : TH6; SubTypeString : 'th6'),
(SubType : TH7; SubTypeString : 'th7'),
(SubType : TH8; SubTypeString : 'th8'),
(SubType : TH9; SubTypeString : 'th9'),
(SubType : TH10; SubTypeString : 'th10'));
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
var
DeviceID : String;
SubType : String;
Temperature : Extended;
TemperatureSign : String;
Humidity : Integer;
Status : String;
BatteryLevel : Integer;
xPLMessage : TxPLMessage;
begin
DeviceID := GetSubTypeString(Buffer[2],SubTypeArray)+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2);
if Buffer[6] and $80 > 0 then
TemperatureSign := '-'; // negative value
Buffer[6] := Buffer[6] and $7F; // zero out the temperature sign
Temperature := ((Buffer[6] shl 8) + Buffer[7]) / 10;
Humidity := Buffer[8];
case Buffer[9] of
HUM_NORMAL : Status := HUM_NORMAL_STR;
HUM_COMFORT : Status := HUM_COMFORT_STR;
HUM_DRY : Status := HUM_DRY_STR;
HUM_WET : Status := HUM_WET_STR;
end;
if (Buffer[10] and $0F) = 0 then // zero out rssi
BatteryLevel := 0
else
BatteryLevel := 100;
// Create sensor.basic message for the temperature
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+TemperatureSign+FloatToStr(Temperature));
xPLMessage.Body.AddKeyValue('units=c');
xPLMessage.Body.AddKeyValue('type=temperature');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+IntToStr(Humidity));
xPLMessage.Body.AddKeyValue('description='+Status);
xPLMessage.Body.AddKeyValue('type=humidity');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+IntToStr(BatteryLevel));
xPLMessage.Body.AddKeyValue('type=battery');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
end;
end.
|
unit caChart;
{$INCLUDE ca.inc}
interface
uses
// Standard Delphi units
Windows,
Classes,
SysUtils,
Controls,
ExtCtrls,
Graphics,
// ca units
caGraphics,
caClasses,
caControls;
type
TcaAxisType = (axX, axY);
//---------------------------------------------------------------------------
// Forward declarations
//---------------------------------------------------------------------------
TcaChart = class;
//---------------------------------------------------------------------------
// IcaChartObject
//---------------------------------------------------------------------------
IcaChartObject = interface
['{C92F24EE-1E71-4AF5-9334-44B3B2943348}']
// Public methods
procedure Paint;
end;
//---------------------------------------------------------------------------
// TcaChartObject
//---------------------------------------------------------------------------
TcaChartObject = class(TcaInterfacedPersistent, IcaChartObject)
private
FChart: TcaChart;
// Property methods
protected
// Virtual methods
procedure Paint; virtual;
public
constructor Create(AChart: TcaChart);
end;
//---------------------------------------------------------------------------
// IcaChartAxis
//---------------------------------------------------------------------------
IcaChartAxis = interface
['{8628D8B6-5229-41CB-BD85-881DC970D406}']
// Property methods
function GetAxisType: TcaAxisType;
function GetMajorInterval: Double;
function GetMaxValue: Double;
function GetMinorInterval: Double;
function GetMinValue: Double;
function GetOnChanged: TNotifyEvent;
procedure SetMajorInterval(const Value: Double);
procedure SetMaxValue(const Value: Double);
procedure SetMinorInterval(const Value: Double);
procedure SetMinValue(const Value: Double);
procedure SetOnChanged(const Value: TNotifyEvent);
// Protected methods
procedure Paint;
// Properties
property AxisType: TcaAxisType read GetAxisType;
property MajorInterval: Double read GetMajorInterval write SetMajorInterval;
property MaxValue: Double read GetMaxValue write SetMaxValue;
property MinorInterval: Double read GetMinorInterval write SetMinorInterval;
property MinValue: Double read GetMinValue write SetMinValue;
property OnChanged: TNotifyEvent read GetOnChanged write SetOnChanged;
end;
//---------------------------------------------------------------------------
// TcaChartAxis
//---------------------------------------------------------------------------
TcaChartAxis = class(TcaChartObject, IcaChartAxis)
private
FAxisType: TcaAxisType;
FMajorInterval: Double;
FMaxValue: Double;
FMinorInterval: Double;
FMinValue: Double;
FOnChanged: TNotifyEvent;
// Property methods
function GetAxisType: TcaAxisType;
function GetMajorInterval: Double;
function GetMaxValue: Double;
function GetMinorInterval: Double;
function GetMinValue: Double;
function GetOnChanged: TNotifyEvent;
procedure SetMajorInterval(const Value: Double);
procedure SetMaxValue(const Value: Double);
procedure SetMinorInterval(const Value: Double);
procedure SetMinValue(const Value: Double);
procedure SetOnChanged(const Value: TNotifyEvent);
// Private methods
procedure Changed;
protected
procedure DoChanged; virtual;
procedure Paint; override;
public
constructor Create(AChart: TcaChart; AAxisType: TcaAxisType);
// Public properties
property AxisType: TcaAxisType read GetAxisType;
property OnChanged: TNotifyEvent read GetOnChanged write SetOnChanged;
published
// Published properties
property MajorInterval: Double read GetMajorInterval write SetMajorInterval;
property MaxValue: Double read GetMaxValue write SetMaxValue;
property MinorInterval: Double read GetMinorInterval write SetMinorInterval;
property MinValue: Double read GetMinValue write SetMinValue;
end;
//---------------------------------------------------------------------------
// IcaChartGrid
//---------------------------------------------------------------------------
IcaChartGrid = interface
['{F3D16104-1E39-4983-868B-1F1E03B50E21}']
// Property methods
function GetHeight: Integer;
function GetWidth: Integer;
function GetXAxis: TcaChartAxis;
function GetYAxis: TcaChartAxis;
procedure SetXAxis(const Value: TcaChartAxis);
procedure SetYAxis(const Value: TcaChartAxis);
// Protected methods
procedure Paint;
// Properties
property Height: Integer read GetHeight;
property Width: Integer read GetWidth;
property XAxis: TcaChartAxis read GetXAxis write SetXAxis;
property YAxis: TcaChartAxis read GetYAxis write SetYAxis;
end;
//---------------------------------------------------------------------------
// TcaChartGrid
//---------------------------------------------------------------------------
TcaChartGrid = class(TcaChartObject, IcaChartGrid)
private
FHeight: Integer;
FWidth: Integer;
FXAxis: TcaChartAxis;
FYAxis: TcaChartAxis;
// Property methods
function GetHeight: Integer;
function GetWidth: Integer;
function GetXAxis: TcaChartAxis;
function GetYAxis: TcaChartAxis;
procedure SetXAxis(const Value: TcaChartAxis);
procedure SetYAxis(const Value: TcaChartAxis);
protected
procedure Paint; override;
public
// Properties
property Height: Integer read GetHeight;
property Width: Integer read GetWidth;
property XAxis: TcaChartAxis read GetXAxis write SetXAxis;
property YAxis: TcaChartAxis read GetYAxis write SetYAxis;
end;
//---------------------------------------------------------------------------
// IcaChart
//---------------------------------------------------------------------------
IcaChart = interface
['{D52D84AF-6EC7-43A8-A0A1-2C778FD9CE30}']
function GetMargin: TcaMargin;
function GetXAxis: TcaChartAxis;
function GetYAxis: TcaChartAxis;
procedure SetMargin(const Value: TcaMargin);
procedure SetXAxis(const Value: TcaChartAxis);
procedure SetYAxis(const Value: TcaChartAxis);
// Properties
property Margin: TcaMargin read GetMargin write SetMargin;
property XAxis: TcaChartAxis read GetXAxis write SetXAxis;
property YAxis: TcaChartAxis read GetYAxis write SetYAxis;
end;
//---------------------------------------------------------------------------
// TcaChart
//---------------------------------------------------------------------------
TcaChart = class(TcaPanel, IcaChart)
private
FMargin: TcaMargin;
FGrid: TcaChartGrid;
FXAxis: TcaChartAxis;
FYAxis: TcaChartAxis;
// Property methods
function GetGrid: TcaChartGrid;
function GetMargin: TcaMargin;
function GetXAxis: TcaChartAxis;
function GetYAxis: TcaChartAxis;
procedure SetMargin(const Value: TcaMargin);
procedure SetXAxis(const Value: TcaChartAxis);
procedure SetYAxis(const Value: TcaChartAxis);
// Event handlers
procedure MarginChangedEvent(Sender: TObject);
procedure AxisChangedEvent(Sender: TObject);
protected
procedure Paint; override;
property Grid: TcaChartGrid read GetGrid;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Margin: TcaMargin read GetMargin write SetMargin;
property XAxis: TcaChartAxis read GetXAxis write SetXAxis;
property YAxis: TcaChartAxis read GetYAxis write SetYAxis;
end;
implementation
//---------------------------------------------------------------------------
// TcaChartObject
//---------------------------------------------------------------------------
// Virtual methods
constructor TcaChartObject.Create(AChart: TcaChart);
begin
inherited Create;
FChart := AChart;
end;
procedure TcaChartObject.Paint;
begin
// Virtual
end;
//---------------------------------------------------------------------------
// TcaChartAxis
//---------------------------------------------------------------------------
constructor TcaChartAxis.Create(AChart: TcaChart; AAxisType: TcaAxisType);
begin
inherited Create(AChart);
FAxisType := AAxisType;
end;
// Protected methods
procedure TcaChartAxis.DoChanged;
begin
if Assigned(FOnChanged) then FOnChanged(Self);
end;
procedure TcaChartAxis.Paint;
var
M: TcaMargin;
C: TCanvas;
Grid: TcaChartGrid;
Range: Double;
XFrom: Integer;
XTo: Integer;
YFrom: Integer;
YTo: Integer;
LineValue: Double;
begin
M := FChart.Margin;
C := FChart.Canvas;
Grid := FChart.Grid;
Range := FMaxValue - FMinValue;
if (FMinorInterval > 0) and (Round(Range / FMinorInterval) >= 2) then
begin
LineValue := FMinorInterval;
while LineValue < Range do
begin
if FAxisType = axX then
begin
XFrom := M.Left + Round(Grid.Width * LineValue / Range);
XTo := XFrom;
YFrom := M.Top;
YTo := M.Top + Grid.Height;
end
else
begin
XFrom := M.Left;
XTo := M.Left + Grid.Width;
YFrom := M.Top + Grid.Height - Round(Grid.Height * LineValue / Range);
YTo := YFrom;
end;
C.Pen.Color := clGray;
C.Pen.Style := psSolid;
C.MoveTo(XFrom, YFrom);
C.LineTo(XTo, YTo);
LineValue := LineValue + FMinorInterval;
end;
end;
end;
// Private methods
procedure TcaChartAxis.Changed;
begin
DoChanged;
end;
// Property methods
function TcaChartAxis.GetAxisType: TcaAxisType;
begin
Result := FAxisType;
end;
function TcaChartAxis.GetMajorInterval: Double;
begin
Result := FMajorInterval;
end;
function TcaChartAxis.GetMaxValue: Double;
begin
Result := FMaxValue;
end;
function TcaChartAxis.GetMinorInterval: Double;
begin
Result := FMinorInterval;
end;
function TcaChartAxis.GetMinValue: Double;
begin
Result := FMinValue;
end;
function TcaChartAxis.GetOnChanged: TNotifyEvent;
begin
Result := FOnChanged;
end;
procedure TcaChartAxis.SetMajorInterval(const Value: Double);
begin
FMajorInterval := Value;
Changed;
end;
procedure TcaChartAxis.SetMaxValue(const Value: Double);
begin
FMaxValue := Value;
Changed;
end;
procedure TcaChartAxis.SetMinorInterval(const Value: Double);
begin
FMinorInterval := Value;
Changed;
end;
procedure TcaChartAxis.SetMinValue(const Value: Double);
begin
FMinValue := Value;
Changed;
end;
procedure TcaChartAxis.SetOnChanged(const Value: TNotifyEvent);
begin
FOnChanged := Value;
end;
//---------------------------------------------------------------------------
// TcaChartGrid
//---------------------------------------------------------------------------
// Protected methods
procedure TcaChartGrid.Paint;
var
M: TcaMargin;
C: TCanvas;
R: IcaRect;
begin
M := FChart.Margin;
C := FChart.Canvas;
R := TcaRect.Create(FChart.ClientRect);
R.Adjust(M.Left, M.Top, -M.Right, -M.Bottom);
FWidth := R.Right - R.Left;
FHeight := R.Bottom - R.Top;
C.Pen.Color := clGray;
C.Pen.Style := psSolid;
C.MoveTo(R.Left, R.Top);
C.LineTo(R.Right, R.Top);
C.LineTo(R.Right, R.Bottom);
C.LineTo(R.Left, R.Bottom);
C.LineTo(R.Left, R.Top);
end;
// Property methods
function TcaChartGrid.GetHeight: Integer;
begin
Result := FHeight;
end;
function TcaChartGrid.GetWidth: Integer;
begin
Result := FWidth;
end;
function TcaChartGrid.GetXAxis: TcaChartAxis;
begin
Result := FXAxis;
end;
function TcaChartGrid.GetYAxis: TcaChartAxis;
begin
Result := FYAxis;
end;
procedure TcaChartGrid.SetXAxis(const Value: TcaChartAxis);
begin
FXAxis := Value;
end;
procedure TcaChartGrid.SetYAxis(const Value: TcaChartAxis);
begin
FYAxis := Value;
end;
//---------------------------------------------------------------------------
// TcaChart
//---------------------------------------------------------------------------
constructor TcaChart.Create(AOwner: TComponent);
begin
inherited;
FMargin := TcaMargin.Create;
FMargin.OnChanged := MarginChangedEvent;
FGrid := TcaChartGrid.Create(Self);
FXAxis := TcaChartAxis.Create(Self, axX);
FXAxis.OnChanged := AxisChangedEvent;
FYAxis := TcaChartAxis.Create(Self, axY);
FYAxis.OnChanged := AxisChangedEvent;
end;
destructor TcaChart.Destroy;
begin
FMargin.Free;
FGrid.Free;
FXAxis.Free;
FYAxis.Free;
inherited;
end;
// Protected methods
procedure TcaChart.Paint;
begin
inherited;
FGrid.Paint;
FXAxis.Paint;
FYAxis.Paint;
end;
// Event handlers
procedure TcaChart.AxisChangedEvent(Sender: TObject);
begin
Invalidate;
end;
procedure TcaChart.MarginChangedEvent(Sender: TObject);
begin
Invalidate;
end;
// Property methods
function TcaChart.GetGrid: TcaChartGrid;
begin
Result := FGrid;
end;
function TcaChart.GetMargin: TcaMargin;
begin
Result := FMargin;
end;
function TcaChart.GetXAxis: TcaChartAxis;
begin
Result := FXAxis;
end;
function TcaChart.GetYAxis: TcaChartAxis;
begin
Result := FYAxis;
end;
procedure TcaChart.SetMargin(const Value: TcaMargin);
begin
FMargin := Value;
end;
procedure TcaChart.SetXAxis(const Value: TcaChartAxis);
begin
FXAxis := Value;
end;
procedure TcaChart.SetYAxis(const Value: TcaChartAxis);
begin
FYAxis := Value;
end;
end.
|
{-----------------------------------------------------------------------------
Author: Roman
Purpose: Пример реализации трейдера. Данный трейдер работает с
двумя индикаторами MACD и RSI на фреймах 60 и 15
History:
-----------------------------------------------------------------------------}
unit FC.Trade.Trader.Sample1;
{$I Compiler.inc}
interface
uses
Classes, Math,Graphics, Contnrs, Forms, Controls, SysUtils, BaseUtils, ActnList, Properties.Obj, Properties.Definitions,
StockChart.Definitions, StockChart.Definitions.Units, Properties.Controls, StockChart.Indicators,
Serialization, FC.Definitions, FC.Trade.Trader.Base,FC.Trade.Properties,FC.fmUIDataStorage;
type
//Интерфейс нашего трейдера
//Пока здесь объявлен. Потом как устоится, вынести в Definitions
IStockTraderSample1 = interface
['{D80D6DF8-2FF2-42A0-A5F6-9C306D046994}']
end;
//Собственно трейдер
TStockTraderSample1 = class (TStockTraderBase,IStockTraderSample1)
private
FMACD: ISCIndicatorMACD;
FRSI : ISCIndicatorRSI;
public
//Создание-удаление своих объектов
procedure OnCreateObjects; override;
procedure OnReleaseObjects; override;
//Посчитать
procedure UpdateStep2(const aTime: TDateTime); override;
constructor Create; override;
destructor Destroy; override;
procedure Dispose; override;
end;
implementation
uses Variants,Application.Definitions, FC.Trade.OrderCollection, FC.Trade.Trader.Message,
StockChart.Indicators.Properties.Dialog, FC.Trade.Trader.Factory,
FC.DataUtils;
{ TStockTraderSample1 }
constructor TStockTraderSample1.Create;
begin
inherited Create;
end;
destructor TStockTraderSample1.Destroy;
begin
inherited;
end;
procedure TStockTraderSample1.Dispose;
begin
inherited;
end;
procedure TStockTraderSample1.OnCreateObjects;
begin
inherited;
//Создаем MACD на 60
FMACD:=CreateOrFindIndicator(GetProject.GetStockChart(sti60),ISCIndicatorMACD,'60, MACD') as ISCIndicatorMACD;
//Создаем RSI На 15
FRSI:=CreateOrFindIndicator(GetProject.GetStockChart(sti15),ISCIndicatorRSI,'15, RSI') as ISCIndicatorRSI;
end;
procedure TStockTraderSample1.OnReleaseObjects;
begin
inherited;
if FMACD<>nil then
OnRemoveObject(FMACD);
FMACD:=nil;
if FRSI<>nil then
OnRemoveObject(FRSI);
FRSI:=nil;
end;
procedure TStockTraderSample1.UpdateStep2(const aTime: TDateTime);
var
j: integer;
aGuessOpen,aGuessClose : TStockExpertGuess;
aInputData : ISCInputDataCollection;
aChart : IStockChart;
begin
aGuessOpen:=0;
aGuessClose:=0;
//Брокер может закрыть ордера и без нас. У нас в списке они остануться,
//но будут уже закрыты. Если их не убрать, то открываться в этоу же сторону мы не
//сможем, пока не будет сигнала от эксперта. Если же их удалить, сигналы
//от эксперта в эту же сторону опять можно отрабатывать
RemoveClosedOrders;
//----- Анализируем экcпертные оценки ----
aChart:=GetProject.GetStockChart(sti60);
aInputData:=aChart.GetInputData;
j:=aChart.FindBar(aTime); //Получаем индекс бара по времени
if j<>-1 then
begin
//Здесь принимается решение об открытии/закрытии ордеров
//Анализ приведен только в качестве примера!!!
if (FMACD.GetValue(j)>0) and (FRSI.GetValue(j)<0) then
begin
aGuessClose:=egSellSurely;
aGuessOpen:=egBuySurely;
end
else if (FMACD.GetValue(j)<0) and (FRSI.GetValue(j)>0) then
begin
aGuessClose:=egBuySurely;
aGuessOpen:=egSellSurely;
end;
//Если есть команда к закрытию открытых ордеров
if aGuessClose<egSell70 then
begin
if LastOrderType = lotSell then
CloseLastOrder('Trader: time to close');
end
else if aGuessClose>egBuy70 then
begin
if LastOrderType=lotBuy then
CloseLastOrder('Trader: time to close');
end;
//Открываемся на продажу
if aGuessOpen<egSell70 then
begin
case LastOrderType of
lotBuy: begin
//Автоматически закрываем предыдущий противоположный ордер
CloseLastOrder('Trader: open opposite');
OpenOrder(okSell);
end;
lotSell:; //Мы уже и так открыты в эту же сторону. Второй раз открываться не будем
lotNone: OpenOrder(okSell);
end;
end
//Открываемся на покупку
else if aGuessOpen>egBuy70 then
begin
case LastOrderType of
lotSell: begin
//Автоматически закрываем предыдущий противоположный ордер
CloseLastOrder('Trader: open opposite');
OpenOrder(okBuy);
end;
lotBuy:; //Мы уже и так открыты в эту же сторону. Второй раз открываться не будем
lotNone: OpenOrder(okBuy);
end;
end
end;
end;
initialization
FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Samples','Sample1',TStockTraderSample1,IStockTraderSample1);
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ SOAP Support }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{*******************************************************}
unit SoapHTTPClient;
interface
uses Classes, RIO, WSDLNode, WSDLItems, OPConvert, OPToSoapDomConv, SOAPHTTPTrans, WebNode, XMLIntf;
type
THTTPRIO = class(TRIO)
private
FWSDLItems: TWSDLItems;
WSDLItemDoc: IXMLDocument;
FWSDLView: TWSDLView;
FWSDLLocation: string;
FDOMConverter: TOPToSoapDomConvert;
FHTTPWebNode: THTTPReqResp;
procedure ClearDependentWSDLView;
procedure SetWSDLLocation(Value: string);
function GetPort: string;
procedure SetPort(Value: string);
function GetService: string;
procedure SetService(Value: string);
procedure CheckWSDLView;
procedure SetURL(Value: string);
procedure SetDomConverter(Value: TOPToSoapDomConvert);
procedure SetHTTPWebNode(Value: THTTPReqResp);
function GetURL: string;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function QueryInterface(const IID: TGUID; out Obj): HResult; override; stdcall;
property WSDLItems: TWSDLItems read FWSDLItems;
published
property WSDLLocation: string read FWSDLLocation write SetWSDLLocation;
property Service: string read GetService write SetService;
property Port: string read GetPort write SetPort;
property URL: string read GetURL write SetURL;
property HTTPWebNode: THTTPReqResp read FHTTPWebNode write SetHTTPWebNode;
property Converter: TOPToSoapDomConvert read FDOMConverter write SetDOMConverter;
end;
implementation
uses SysUtils, InvokeRegistry, Controls;
constructor THTTPRIO.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDOMConverter := TOPToSoapDomConvert.Create(Self);
FDomConverter.Name := 'Converter1'; { do not localize }
FDomConverter.SetSubComponent(True);
FHTTPWebNode := THTTPReqResp.Create(Self);
FHTTPWebNode.Name := 'HTTPWebNode1'; { do not localize }
FHTTPWebNode.SetSubComponent(True);
FConverter := FDOMConverter as IOPConvert;
FWebNode := FHTTPWebNode as IWebNode;
end;
procedure THTTPRIO.ClearDependentWSDLView;
begin
if Assigned(FDomConverter) and Assigned(FDOMConverter.WSDLView) then
FDOMConverter.WSDLView := nil;
if Assigned(FHTTPWebNode) and Assigned(FHTTPWebNode.WSDLView) then
FHTTPWebNode.WSDLView := FWSDLView;
end;
procedure THTTPRIO.CheckWSDLView;
begin
if not Assigned(FWSDLItems) then
begin
if not Assigned(FWSDLItems) then
begin
FWSDLItems := TWSDLItems.Create(nil);
WSDLItemDoc := FWSDLItems;
end;
if not Assigned(FWSDLView) then
FWSDLView := TWSDLView.Create(nil);
FWSDLView.WSDL := FWSDLItems;
if Assigned(FDomConverter) then
FDOMConverter.WSDLView := FWSDLView;
if Assigned(FHTTPWebNode) then
FHTTPWebNode.WSDLView := FWSDLView;
end;
end;
destructor THTTPRIO.Destroy;
begin
if Assigned(FConverter) then
FConverter := nil;
if Assigned(FWebNode) then
FWebNode := nil;
if Assigned(FWSDLView) then
FWSDLView.Free;
if Assigned(FHTTPWebNode) and (FHTTPWebNode.Owner = Self) then
FHTTPWebNode.Free;
if Assigned(FDOMConverter) and (FDomConverter.Owner = Self) then
FDomConverter.Free;
inherited;
end;
function THTTPRIO.GetPort: string;
begin
if Assigned(FWSDLView) then
Result := FWSDLView.Port;
end;
function THTTPRIO.GetService: string;
begin
if Assigned(FWSDLView) then
Result := FWSDLView.Service;
end;
procedure THTTPRIO.SetPort(Value: string);
begin
if Assigned(FWSDLView) then
FWSDLView.Port := Value;
end;
procedure THTTPRIO.SetService(Value: string);
begin
if Assigned(FWSDLView) then
FWSDLView.Service := Value;
end;
procedure THTTPRIO.SetURL(Value: string);
begin
if Assigned(FHTTPWebNode) then
begin
FHTTPWebNode.URL := Value;
if Value <> '' then
begin
WSDLLocation := '';
ClearDependentWSDLView;
end;
end;
end;
procedure THTTPRIO.SetWSDLLocation(Value: string);
begin
if (Value <> '') and (URL <> '') then
FHTTPWebNode.URL := '';
CheckWSDLView;
if FWSDLItems.Active then
FWSDLItems.Active := False;
FWSDLLocation := Value;
FWSDLItems.FileName := Value;
FWSDLView.Port := '';
FWSDLView.Service := '';
end;
function THTTPRIO.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
Result := inherited QueryInterface(IID, Obj);
if Result = 0 then
FHTTPWebNode.SoapAction := InvRegistry.GetNamespaceByGUID(IID);
end;
procedure THTTPRIO.SetDomConverter(Value: TOPToSoapDomConvert);
begin
if Assigned(FDOMConverter) and (FDomConverter.Owner = Self) then
begin
FConverter := nil;
FDomConverter.Free;
end;
FDomConverter := Value;
if Value <> nil then
begin
FConverter := Value;
Value.FreeNotification(Self);
end;
end;
procedure THTTPRIO.SetHTTPWebNode(Value: THTTPReqResp);
begin
if Assigned(FHTTPWebNode) and (FHTTPWebNode.Owner = Self) then
begin
FWebNode := nil;
FHTTPWebNode.Free;
end;
FHTTPWebNode := Value;
if Value <> nil then
begin
FWebNode := Value;
Value.FreeNotification(Self);
end;
end;
function THTTPRIO.GetURL: string;
begin
if Assigned(FHTTPWebNode) then
Result := FHTTPWebNode.URL;
end;
procedure THTTPRIO.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FHTTPWebNode) then
begin
FWebNode := nil;
FHTTPWebNode := nil;
end;
if (Operation = opRemove) and (AComponent = FDomConverter) then
begin
FConverter := nil;
FDomConverter := nil;
end;
end;
initialization
GroupDescendentsWith(THTTPRIO, Controls.TControl);
end.
|
unit IdTimeServer;
interface
{
2000-3-May J. Peter Mugaas
-Added BaseDate to the date the calculations are based on can be
adjusted to work after the year 2035
2000-30-April J. Peter Mugaas
-Adjusted the formula for the integer so that the Time is now
always based on Universal Time (also known as Greenwhich Mean
-Time Replaced the old forumala used to calculate the time with
a new one suggested by Jim Gunkel. This forumala is more
accurate than the old one.
2000-24-April J. Peter Mugaaas
-This now uses the Internet Byte order functions
2000-22-Apr J Peter Mugass
-Ported to Indy
-Fixed a problem where the server was not returning anything
2000-13-Jan MTL
-Moved to new Palette Scheme (Winshoes Servers)
1999-13-Apr
-Final Version
Original Author: Ozz Nixon
-Based on RFC 868
}
uses
Classes,
IdAssignedNumbers,
IdTCPServer;
const
{This indicates that the default date is Jan 1, 1900 which was specified
by RFC 868.}
TIME_DEFBASEDATE = 2;
Type
TIdTimeServer = class(TIdTCPServer)
protected
FBaseDate : TDateTime;
//
function DoExecute(AThread: TIdPeerThread): Boolean; override;
public
constructor Create(AOwner: TComponent); override;
published
{This property is used to set the Date the Time server bases it's
calculations from. If both the server and client are based from the same
date which is higher than the original date, you can extend it beyond the
year 2035}
property BaseDate : TDateTime read FBaseDate write FBaseDate;
property DefaultPort default IdPORT_TIME;
end;
implementation
uses
IdGlobal,
IdStack, SysUtils;
constructor TIdTimeServer.Create(AOwner: TComponent);
begin
inherited;
DefaultPort := IdPORT_TIME;
{This indicates that the default date is Jan 1, 1900 which was specified
by RFC 868.}
FBaseDate := 2;
end;
function TIdTimeServer.DoExecute(AThread: TIdPeerThread): Boolean;
begin
Result := true;
with AThread.Connection do begin
WriteCardinal(Trunc(extended(Now + IdGlobal.TimeZoneBias - Int(FBaseDate)) * 24 * 60 * 60));
Disconnect;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.DBXMySqlMetaDataReader;
interface
uses
Data.DBXCommon,
Data.DBXCommonTable,
Data.DBXMetaDataNames,
Data.DBXMetaDataReader,
Data.DBXPlatform,
Data.DBXSqlScanner;
type
/// <summary> TDBXMySqlCustomMetaDataReader contains custom code for MySQL.
/// </summary>
/// <remarks> For MySQL version 4 and earlier the output of SHOW commands are filtered
/// into metadata schema table structures.
/// For MySQL version 5 and up the system views are filtered for MySQL specifics.
/// </remarks>
TDBXMySqlCustomMetaDataReader = class(TDBXBaseMetaDataReader)
public
type
/// <summary> TMySqlColumnType holds a data type definition.
/// </summary>
TMySqlColumnType = class
public
FDataType: UnicodeString;
FPrecision: Integer;
FScale: Integer;
FUnsigned: Boolean;
FUnicode: Boolean;
FNotnull: Boolean;
end;
TMySqlParameter = class(TDBXMySqlCustomMetaDataReader.TMySqlColumnType)
public
FName: UnicodeString;
FMode: UnicodeString;
FOrdinal: Integer;
end;
TMySqlForeignKey = class
public
constructor Create;
destructor Destroy; override;
procedure Reset; virtual;
public
FConstraintName: UnicodeString;
FKeyColumns: TDBXStringList;
FReferencedTableName: UnicodeString;
FReferencedColumns: TDBXStringList;
end;
/// <summary> TDBXMySql4TablesCursor is a filter for a cursor providing tables.
/// </summary>
/// <remarks> This filter takes the output from "SHOW TABLES" and transforms it into a Tables schema table.
/// </remarks>
TDBXMySql4TablesCursor = class(TDBXCustomMetaDataTable)
public
destructor Destroy; override;
protected
constructor Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Cursor: TDBXTable);
function FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer; override;
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
public
FTableValue: TDBXWritableValue;
FNullValue: TDBXWritableValue;
private
const ShowTablesTableNameOrdinal = 0;
end;
/// <summary> TDBXMySqlColumnsTableCursor provides IsUnicode based on the character
/// set of the column.
/// </summary>
TDBXMySqlColumnsTableCursor = class(TDBXColumnsTableCursor)
public
constructor Create(const Reader: TDBXMySqlCustomMetaDataReader; const Version5: Boolean; const Original: TDBXTable; const Sanitized: TDBXTable);
destructor Destroy; override;
function Next: Boolean; override;
protected
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
public
FRow: TDBXSingleValueRow;
private
FOriginal: TDBXTable;
FVersion5: Boolean;
private
const MysqlIsUnicode = TDBXColumnsIndex.DbxDataType;
const MysqlIsUnsigned = TDBXColumnsIndex.DbxDataType + 1;
end;
/// <summary> TDBXMySql4ColumnsCursor is a filter for a cursor providing table columns.
/// </summary>
/// <remarks> This filter takes the output from "SHOW COLUMNS FROM [tablename]" and transforms it into a Columns schema table.
/// </remarks>
TDBXMySql4ColumnsCursor = class(TDBXCustomMetaDataTable)
public
destructor Destroy; override;
procedure Close; override;
function Next: Boolean; override;
protected
constructor Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Sql: UnicodeString; const TableName: UnicodeString);
function FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer; override;
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
private
function InitNextCursor: Boolean;
function ComputeDefaultValue: UnicodeString;
function ComputeAutoIncrement: Boolean;
function ComputeNullable: Boolean;
private
FReader: TDBXMySqlCustomMetaDataReader;
FTables: TDBXStringList;
FTableIndex: Integer;
FSql: UnicodeString;
FTableName: UnicodeString;
FColumnNumber: Integer;
FColumnType: TDBXMySqlCustomMetaDataReader.TMySqlColumnType;
FRow: TDBXSingleValueRow;
private
const ShowColumnsFieldOrdinal = 0;
const ShowColumnsTypeOrdinal = 1;
const ShowColumnsNullOrdinal = 2;
const ShowColumnsKeyOrdinal = 3;
const ShowColumnsDefaultOrdinal = 4;
const ShowColumnsExtraOrdinal = 5;
end;
/// <summary> TDBXMySql4IndexesCursor is a filter for a cursor providing indexes.
/// </summary>
/// <remarks> This filter takes the output from "SHOW INDEX FROM [tablename]" and transforms it into a Indexes schema table.
/// </remarks>
TDBXMySql4IndexesCursor = class(TDBXCustomMetaDataTable)
public
destructor Destroy; override;
procedure Close; override;
function Next: Boolean; override;
protected
constructor Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Sql: UnicodeString; const TableName: UnicodeString);
function FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer; override;
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
private
function InitNextCursor: Boolean;
function ComputeConstraintName: UnicodeString;
private
FReader: TDBXMySqlCustomMetaDataReader;
FTables: TDBXStringList;
FTableIndex: Integer;
FSql: UnicodeString;
FTableName: UnicodeString;
FUniqueIndex: Boolean;
FIndexName: UnicodeString;
FPrevIndexName: UnicodeString;
FPrevTableName: UnicodeString;
FRow: TDBXSingleValueRow;
private
const ShowIndexTableOrdinal = 0;
const ShowIndexNonUniqueOrdinal = 1;
const ShowIndexKeyNameOrdinal = 2;
const ShowIndexSeqInIndexOrdinal = 3;
const ShowIndexColumnNameOrdinal = 4;
const ShowIndexCollationOrdinal = 5;
const ShowIndexCardinalityOrdinal = 6;
const ShowIndexSubPartOrdinal = 7;
const ShowIndexPackedOrdinal = 8;
const ShowIndexNullOrdinal = 9;
const ShowIndexIndexTypeOrdinal = 10;
const ShowIndexCommentOrdinal = 11;
end;
/// <summary> TDBXMySql4IndexColumnsCursor is a filter for a cursor providing index columns.
/// </summary>
/// <remarks> This filter takes the output from "SHOW INDEX FROM [tablename]" and transforms it into a IndexColumns schema table.
/// </remarks>
TDBXMySql4IndexColumnsCursor = class(TDBXCustomMetaDataTable)
public
destructor Destroy; override;
procedure Close; override;
function Next: Boolean; override;
protected
constructor Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Sql: UnicodeString; const TableName: UnicodeString; const IndexName: UnicodeString);
function FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer; override;
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
private
function InitNextCursor: Boolean;
private
FReader: TDBXMySqlCustomMetaDataReader;
FTables: TDBXStringList;
FTableIndex: Integer;
FSql: UnicodeString;
FWantedIndexName: UnicodeString;
FTableName: UnicodeString;
FIndexName: UnicodeString;
FRow: TDBXSingleValueRow;
private
const ShowIndexTableOrdinal = 0;
const ShowIndexNonUniqueOrdinal = 1;
const ShowIndexKeyNameOrdinal = 2;
const ShowIndexSeqInIndexOrdinal = 3;
const ShowIndexColumnNameOrdinal = 4;
const ShowIndexCollationOrdinal = 5;
const ShowIndexCardinalityOrdinal = 6;
const ShowIndexSubPartOrdinal = 7;
const ShowIndexPackedOrdinal = 8;
const ShowIndexNullOrdinal = 9;
const ShowIndexIndexTypeOrdinal = 10;
const ShowIndexCommentOrdinal = 11;
end;
/// <summary> TDBXMySql4ForeignKeyCursor is a filter for a cursor providing foreign keys.
/// </summary>
/// <remarks> This filter takes the output from "SHOW CREATE TABLE [tablename]" and transforms it into a ForeignKey schema table.
/// </remarks>
TDBXMySql4ForeignKeyCursor = class(TDBXCustomMetaDataTable)
public
destructor Destroy; override;
procedure Close; override;
function Next: Boolean; override;
protected
constructor Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Sql: UnicodeString; const TableName: UnicodeString);
function FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer; override;
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
private
function InitNextCursor: Boolean;
public
FKey: TDBXMySqlCustomMetaDataReader.TMySqlForeignKey;
FRow: TDBXSingleValueRow;
private
FReader: TDBXMySqlCustomMetaDataReader;
FTables: TDBXStringList;
FTableIndex: Integer;
FSql: UnicodeString;
FTableName: UnicodeString;
FSqlCreateTable: UnicodeString;
FParseIndex: Integer;
private
const ShowCreateTableSqlOrdinal = 1;
end;
/// <summary> TDBXMySql4ForeignKeyColumnsCursor is a filter for a cursor providing foreign key columns.
/// </summary>
/// <remarks> This filter takes the output from "SHOW CREATE TABLE [tablename]" and transforms it into a ForeignKeyColumns schema table.
/// </remarks>
TDBXMySql4ForeignKeyColumnsCursor = class(TDBXCustomMetaDataTable)
public
destructor Destroy; override;
procedure Close; override;
function Next: Boolean; override;
protected
constructor Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Sql: UnicodeString; const TableName: UnicodeString; const ForeignKeyName: UnicodeString; const PrimaryTableName: UnicodeString; const PrimaryKeyName: UnicodeString);
function FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer; override;
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
private
function InitNextCursor: Boolean;
procedure SetValues;
public
FKey: TDBXMySqlCustomMetaDataReader.TMySqlForeignKey;
private
FReader: TDBXMySqlCustomMetaDataReader;
FTables: TDBXStringList;
FTableIndex: Integer;
FSql: UnicodeString;
FTableName: UnicodeString;
FForeignKeyName: UnicodeString;
FPrimaryTableName: UnicodeString;
FPrimaryKeyName: UnicodeString;
FSqlCreateTable: UnicodeString;
FParseIndex: Integer;
FKeyIndex: Integer;
FRow: TDBXSingleValueRow;
private
const ShowCreateTableSqlOrdinal = 1;
end;
/// <summary> TDBXMySqlProcedureSourcesCursor is a filter for a cursor providing procedure sources.
/// </summary>
/// <remarks> This filter takes the output from "SHOW CREATE PROCEDURE <procname>" and transforms it into a ProcedureSources schema table.
/// </remarks>
TDBXMySqlProcedureSourcesCursor = class(TDBXCustomMetaDataTable)
public
destructor Destroy; override;
procedure Close; override;
function Next: Boolean; override;
protected
constructor Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Sql: UnicodeString; const SchemaName: UnicodeString; const ProcedureName: UnicodeString);
function FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer; override;
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
private
function InitNextCursor: Boolean;
function ComputeDefinition: UnicodeString;
function ComputeDefiner: UnicodeString;
private
FReader: TDBXMySqlCustomMetaDataReader;
FProcedures: TDBXStringList;
FProcedureTypes: TDBXStringList;
FProcedureIndex: Integer;
FSql: UnicodeString;
FProcedureName: UnicodeString;
FProcedureType: UnicodeString;
FDefiner: UnicodeString;
FRow: TDBXSingleValueRow;
private
const ShowCreateProcedureSqlOrdinal = 2;
const DefinerString = 'DEFINER=';
end;
TDBXMySqlProcedureParametersCursor = class(TDBXCustomMetaDataTable)
public
destructor Destroy; override;
procedure Close; override;
function Next: Boolean; override;
protected
constructor Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Sql: UnicodeString; const SchemaName: UnicodeString; const ProcedureName: UnicodeString; const ParameterName: UnicodeString);
function FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer; override;
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
private
function InitNextCursor: Boolean;
procedure SetValues;
procedure ComputeParams;
private
FReader: TDBXMySqlCustomMetaDataReader;
FProcedures: TDBXStringList;
FProcedureTypes: TDBXStringList;
FProcedureIndex: Integer;
FParameterIndex: Integer;
FSql: UnicodeString;
FProcedureName: UnicodeString;
FParameterName: UnicodeString;
FProcedureType: UnicodeString;
FDefiner: UnicodeString;
FParams: TDBXArrayList;
FParameter: TDBXMySqlCustomMetaDataReader.TMySqlParameter;
FRow: TDBXSingleValueRow;
private
const ShowCreateProcedureSqlOrdinal = 2;
const DefinerString = 'DEFINER=';
end;
public
destructor Destroy; override;
/// <summary> Overrides the implementation in TDBXBaseMetaDataReader.
/// </summary>
/// <remarks> Allthough MySQL does not support schemas, catalogs are reported as schemas
/// in MySQL version 5.
/// </remarks>
function FetchSchemas(const Catalog: UnicodeString): TDBXTable; override;
/// <summary> Overrides the implementation in TDBXBaseMetaDataReader.
/// </summary>
/// <remarks> Use a special filter for MySQL 4 to convert output from "SHOW TABLES".
/// </remarks>
function FetchTables(const Catalog: UnicodeString; const Schema: UnicodeString; const TableName: UnicodeString; const TableType: UnicodeString): TDBXTable; override;
/// <summary> Overrides the implementation in TDBXBaseMetaDataReader.
/// </summary>
/// <remarks> Note: views did not exist in MySQL prior to version 5.
/// </remarks>
function FetchViews(const Catalog: UnicodeString; const Schema: UnicodeString; const View: UnicodeString): TDBXTable; override;
/// <summary> Overrides the implementation in TDBXBaseMetaDataReader.
/// </summary>
/// <remarks> Use a special filter for MySQL 4 to convert output from "SHOW COLUMNS FROM [tablename]".
/// </remarks>
/// <seealso cref="TDBXMySql4ColumnsCursor"/>
function FetchColumns(const Catalog: UnicodeString; const Schema: UnicodeString; const Table: UnicodeString): TDBXTable; override;
/// <summary> Overrides the implementation in TDBXBaseMetaDataReader.
/// </summary>
/// <remarks> Use a special filter for MySQL 4 to convert output from "SHOW INDEX FROM [tablename]".
/// </remarks>
/// <seealso cref="TDBXMySql4IndexesCursor"/>
function FetchIndexes(const Catalog: UnicodeString; const Schema: UnicodeString; const Table: UnicodeString): TDBXTable; override;
/// <summary> Overrides the implementation in TDBXBaseMetaDataReader.
/// </summary>
/// <remarks> Use a special filter for MySQL 4 to convert output from "SHOW INDEX FROM [tablename]".
/// </remarks>
/// <seealso cref="TDBXMySql4IndexColumnsCursor"/>
function FetchIndexColumns(const Catalog: UnicodeString; const Schema: UnicodeString; const Table: UnicodeString; const Index: UnicodeString): TDBXTable; override;
function FetchForeignKeys(const Catalog: UnicodeString; const Schema: UnicodeString; const Table: UnicodeString): TDBXTable; override;
function FetchForeignKeyColumns(const Catalog: UnicodeString; const Schema: UnicodeString; const Table: UnicodeString; const ForeignKeyName: UnicodeString; const PrimaryCatalog: UnicodeString; const PrimarySchema: UnicodeString; const PrimaryTable: UnicodeString; const PrimaryKeyName: UnicodeString): TDBXTable; override;
function FetchProcedures(const Catalog: UnicodeString; const Schema: UnicodeString; const ProcedureName: UnicodeString; const ProcType: UnicodeString): TDBXTable; override;
function FetchProcedureSources(const Catalog: UnicodeString; const Schema: UnicodeString; const &Procedure: UnicodeString): TDBXTable; override;
function FetchProcedureParameters(const Catalog: UnicodeString; const Schema: UnicodeString; const &Procedure: UnicodeString; const Parameter: UnicodeString): TDBXTable; override;
function FetchUsers: TDBXTable; override;
protected
procedure SetContext(const Context: TDBXProviderContext); override;
function IsDefaultCharSetUnicode: Boolean; virtual;
procedure PopulateDataTypes(const Hash: TDBXObjectStore; const Types: TDBXArrayList; const Descr: TDBXDataTypeDescriptionArray); override;
function GetDataTypeDescriptions: TDBXDataTypeDescriptionArray; override;
function GetTables: TDBXStringList;
function FindDataType(const TypeName: UnicodeString): Integer; virtual;
private
procedure InitScanner;
procedure GetProcedures(const SchemaName: UnicodeString; const ProcedureName: UnicodeString; const Procedures: TDBXStringList; const ProcedureTypes: TDBXStringList);
function ParseProcedureDefiner(const Definition: UnicodeString): UnicodeString;
procedure ParseProcedure(const Definition: UnicodeString; const &Type: UnicodeString; const Params: TDBXArrayList);
function ParseType(const Definition: UnicodeString; const &Type: TDBXMySqlCustomMetaDataReader.TMySqlColumnType): Integer;
function ReplaceIdentifier(const Sql: UnicodeString; const ParameterName: UnicodeString; const ActualValue: UnicodeString; const MakeQuotes: Boolean): UnicodeString;
function ToInt(const Value: UnicodeString): Integer;
function ParseIdList(const Scanner: TDBXSqlScanner; const List: TDBXStringList): Boolean;
function ParseForeignKey(const Scanner: TDBXSqlScanner; const ForeignKey: TDBXMySqlCustomMetaDataReader.TMySqlForeignKey): Boolean;
function ParseCreateTableForNextForeignKey(const Sql: UnicodeString; const InStartIndex: Integer; const Key: TDBXMySqlCustomMetaDataReader.TMySqlForeignKey): Integer;
protected
FScanner: TDBXSqlScanner;
private
FDefaultCharSetIsUnicode: Boolean;
public
property DefaultCharSetUnicode: Boolean read IsDefaultCharSetUnicode;
private
property Tables: TDBXStringList read GetTables;
private
const DefaultCharsetIsUnicode = 'UnicodeEncoding';
const YForYes = 'Y';
const AForAscending = 'A';
const FAuto_increment = 'auto_increment';
const IntegerType = 'integer';
const IntType = 'int';
const DecimalType = 'decimal';
const DecType = 'dec';
const Table = 'TABLE';
const Constraint = 'CONSTRAINT';
const Foreign = 'FOREIGN';
const Key = 'KEY';
const References = 'REFERENCES';
const Quote = '''';
const FYear = 'year';
const CurrentTimestamp = 'CURRENT_TIMESTAMP';
const Primary = 'PRIMARY';
const &Procedure = 'PROCEDURE';
const &Function = 'FUNCTION';
const &Begin = 'BEGIN';
const &Create = 'CREATE';
const Definer = 'DEFINER';
const Returns = 'RETURNS';
const Character = 'CHARACTER';
const &Set = 'SET';
const Utf8 = 'utf8';
const &In = 'IN';
const Out = 'OUT';
const Inout = 'INOUT';
const Unsigned = 'UNSIGNED';
const &Not = 'NOT';
const NullSpec = 'NULL';
const Binary = 'BINARY';
const Varbinary = 'VARBINARY';
const DefaultVarcharPrecision = 128;
const TokenProcedure = 1;
const TokenFunction = 2;
const TokenReturns = 3;
const TokenBegin = 4;
const TokenIn = 5;
const TokenOut = 6;
const TokenInout = 7;
const TokenCharacter = 8;
const TokenSet = 9;
const TokenUtf8 = 10;
const TokenUnsigned = 11;
const TokenCreate = 12;
const TokenDefiner = 13;
const TokenNot = 14;
const TokenNull = 15;
const TokenBinary = 16;
end;
TDBXMySqlMetaDataReader = class(TDBXMySqlCustomMetaDataReader)
public
function FetchCatalogs: TDBXTable; override;
function FetchSchemas(const CatalogName: UnicodeString): TDBXTable; override;
function FetchColumnConstraints(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const TableName: UnicodeString): TDBXTable; override;
function FetchSynonyms(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const SynonymName: UnicodeString): TDBXTable; override;
function FetchPackages(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString): TDBXTable; override;
function FetchPackageProcedures(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString; const ProcedureName: UnicodeString; const ProcedureType: UnicodeString): TDBXTable; override;
function FetchPackageProcedureParameters(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString; const ProcedureName: UnicodeString; const ParameterName: UnicodeString): TDBXTable; override;
function FetchPackageSources(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString): TDBXTable; override;
function FetchRoles: TDBXTable; override;
protected
function GetProductName: UnicodeString; override;
function GetSqlIdentifierQuotePrefix: UnicodeString; override;
function GetSqlIdentifierQuoteSuffix: UnicodeString; override;
function GetSqlIdentifierQuoteChar: UnicodeString; override;
function GetTableType: UnicodeString; override;
function IsDescendingIndexColumnsSupported: Boolean; override;
function IsLowerCaseIdentifiersSupported: Boolean; override;
function IsUpperCaseIdentifiersSupported: Boolean; override;
function IsMultipleCommandsSupported: Boolean; override;
function GetSqlForTables: UnicodeString; override;
function GetSqlForViews: UnicodeString; override;
function GetSqlForColumns: UnicodeString; override;
function GetSqlForIndexes: UnicodeString; override;
function GetSqlForIndexColumns: UnicodeString; override;
function GetSqlForForeignKeys: UnicodeString; override;
function GetSqlForForeignKeyColumns: UnicodeString; override;
function GetSqlForProcedures: UnicodeString; override;
function GetSqlForProcedureSources: UnicodeString; override;
function GetSqlForProcedureParameters: UnicodeString; override;
function GetSqlForUsers: UnicodeString; override;
function GetReservedWords: TDBXStringArray; override;
end;
implementation
uses
Data.DBXMetaDataUtil,
System.SysUtils;
destructor TDBXMySqlCustomMetaDataReader.Destroy;
begin
FreeAndNil(FScanner);
inherited Destroy;
end;
procedure TDBXMySqlCustomMetaDataReader.SetContext(const Context: TDBXProviderContext);
begin
inherited SetContext(Context);
FDefaultCharSetIsUnicode := (Context.GetVendorProperty(DefaultCharsetIsUnicode) = 'true');
end;
function TDBXMySqlCustomMetaDataReader.IsDefaultCharSetUnicode: Boolean;
begin
Result := FDefaultCharSetIsUnicode;
end;
procedure TDBXMySqlCustomMetaDataReader.PopulateDataTypes(const Hash: TDBXObjectStore; const Types: TDBXArrayList; const Descr: TDBXDataTypeDescriptionArray);
var
Index: Integer;
DataType: TDBXDataTypeDescription;
begin
if FDefaultCharSetIsUnicode or (CompareVersion(TDBXVersion.FMySQL5) >= 0) then
for Index := 0 to Length(Descr) - 1 do
begin
DataType := Descr[Index];
if (DataType.DbxDataType = TDBXDataTypes.AnsiStringType) or (DataType.DbxDataType = TDBXDataTypes.WideStringType) then
DataType.UnicodeOptionSupported := True;
end;
inherited PopulateDataTypes(Hash, Types, Descr);
end;
function TDBXMySqlCustomMetaDataReader.GetDataTypeDescriptions: TDBXDataTypeDescriptionArray;
var
StringType: Integer;
Types: TDBXDataTypeDescriptionArray;
begin
StringType := TDBXDataTypes.AnsiStringType;
if FDefaultCharSetIsUnicode then
StringType := TDBXDataTypes.WideStringType;
SetLength(Types,32);
Types[0] := TDBXDataTypeDescription.Create('tinyint', TDBXDataTypes.Int8Type, 3, 'tinyint', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.UnsignedOption);
Types[1] := TDBXDataTypeDescription.Create('smallint', TDBXDataTypes.Int16Type, 5, 'smallint', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.UnsignedOption);
Types[2] := TDBXDataTypeDescription.Create('int', TDBXDataTypes.Int32Type, 10, 'int', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.UnsignedOption);
Types[3] := TDBXDataTypeDescription.Create('mediumint', TDBXDataTypes.Int64Type, 19, 'mediumint', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.UnsignedOption);
Types[4] := TDBXDataTypeDescription.Create('bigint', TDBXDataTypes.Int64Type, 19, 'bigint', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.UnsignedOption);
Types[5] := TDBXDataTypeDescription.Create('float', TDBXDataTypes.SingleType, 23, 'float', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[6] := TDBXDataTypeDescription.Create('double', TDBXDataTypes.DoubleType, 53, 'double', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[7] := TDBXDataTypeDescription.Create('decimal', TDBXDataTypes.BcdType, 64, 'decimal({0}, {1})', 'Precision, Scale', 64, 0, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[8] := TDBXDataTypeDescription.Create('numeric', TDBXDataTypes.BcdType, 64, 'numeric({0}, {1})', 'Precision, Scale', 64, 0, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[9] := TDBXDataTypeDescription.Create('timestamp', TDBXDataTypes.TimeStampType, 4, 'timestamp', NullString, -1, -1, '{ts ''', '''}', NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Searchable or TDBXTypeFlag.ConcurrencyType);
Types[10] := TDBXDataTypeDescription.Create('datetime', TDBXDataTypes.TimeStampType, 8, 'datetime', NullString, -1, -1, '{ts ''', '''}', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[11] := TDBXDataTypeDescription.Create('date', TDBXDataTypes.DateType, 3, 'date', NullString, -1, -1, '{ts ''', '''}', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[12] := TDBXDataTypeDescription.Create('time', TDBXDataTypes.TimeType, 3, 'time', NullString, -1, -1, '{ts ''', '''}', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[13] := TDBXDataTypeDescription.Create('year', TDBXDataTypes.Int32Type, 1, 'year', NullString, -1, -1, '{ts ''', '''}', NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[14] := TDBXDataTypeDescription.Create('binary', TDBXDataTypes.BytesType, 255, 'binary({0})', 'Precision', -1, -1, '0x', NullString, NullString, '05.00.0000', TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[15] := TDBXDataTypeDescription.Create('varbinary', TDBXDataTypes.VarBytesType, 254, 'varbinary({0})', 'Precision', -1, -1, '0x', NullString, '05.00.0002', NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[16] := TDBXDataTypeDescription.Create('varbinary', TDBXDataTypes.VarBytesType, 65533, 'varbinary({0})', 'Precision', -1, -1, '0x', NullString, NullString, '05.00.0003', TDBXTypeFlag.BestMatch or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[17] := TDBXDataTypeDescription.Create('char', StringType, 255, 'char({0})', 'Precision', -1, -1, '''', '''', NullString, '05.00.0000', TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[18] := TDBXDataTypeDescription.Create('varchar', StringType, 254, 'varchar({0})', 'Precision', -1, -1, '''', '''', '05.00.0002', NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[19] := TDBXDataTypeDescription.Create('varchar', StringType, 65533, 'varchar({0})', 'Precision', -1, -1, '''', '''', NullString, '05.00.0003', TDBXTypeFlag.BestMatch or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[20] := TDBXDataTypeDescription.Create('tinytext', StringType, 254, 'tinytext', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.SearchableWithLike);
Types[21] := TDBXDataTypeDescription.Create('text', StringType, 65533, 'text', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.SearchableWithLike);
Types[22] := TDBXDataTypeDescription.Create('mediumtext', StringType, 16777212, 'mediumtext', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.SearchableWithLike);
Types[23] := TDBXDataTypeDescription.Create('longtext', StringType, 4294967291, 'longtext', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.SearchableWithLike);
Types[24] := TDBXDataTypeDescription.Create('tinyblob', TDBXDataTypes.BlobType, 254, 'tinyblob', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Long or TDBXTypeFlag.Nullable);
Types[25] := TDBXDataTypeDescription.Create('blob', TDBXDataTypes.BlobType, 65533, 'blob', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Long or TDBXTypeFlag.Nullable);
Types[26] := TDBXDataTypeDescription.Create('mediumblob', TDBXDataTypes.BlobType, 16777212, 'mediumblob', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.Long or TDBXTypeFlag.Nullable);
Types[27] := TDBXDataTypeDescription.Create('longblob', TDBXDataTypes.BlobType, 4294967291, 'longblob', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Long or TDBXTypeFlag.Nullable);
Types[28] := TDBXDataTypeDescription.Create('bool', TDBXDataTypes.BooleanType, 1, 'bool', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Long or TDBXTypeFlag.Nullable);
Types[29] := TDBXDataTypeDescription.Create('enum', StringType, 65535, 'enum', NullString, -1, -1, '''', '''', NullString, '05.00.0003', TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[30] := TDBXDataTypeDescription.Create('set', StringType, 64, 'set', NullString, -1, -1, '''', '''', NullString, '05.00.0003', TDBXTypeFlag.CaseSensitive or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[31] := TDBXDataTypeDescription.Create('bit', TDBXDataTypes.VarBytesType, 8, 'bit({0})', 'Precision', -1, -1, NullString, NullString, NullString, '05.00.0003', TDBXTypeFlag.BestMatch or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Result := Types;
end;
function TDBXMySqlCustomMetaDataReader.FetchSchemas(const Catalog: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
if CompareVersion(TDBXVersion.FMySQL5) >= 0 then
Result := inherited FetchSchemas(Catalog)
else
begin
Columns := TDBXMetaDataCollectionColumns.CreateSchemasColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Schemas, Columns);
end;
end;
function TDBXMySqlCustomMetaDataReader.FetchTables(const Catalog: UnicodeString; const Schema: UnicodeString; const TableName: UnicodeString; const TableType: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
Sql: UnicodeString;
Cursor: TDBXTable;
begin
if CompareVersion(TDBXVersion.FMySQL5) >= 0 then
Exit(inherited FetchTables(Catalog, Schema, TableName, TableType));
Columns := TDBXMetaDataCollectionColumns.CreateTablesColumns;
if (not StringIsNil(TableType)) and (StringIndexOf(TableType,Table) < 0) then
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Tables, Columns)
else
begin
Sql := SqlForTables;
if not StringIsNil(TableName) then
Sql := Sql + ' like ''' + TableName + '''';
Cursor := Context.ExecuteQuery(Sql, nil, nil);
Result := TDBXMySqlCustomMetaDataReader.TDBXMySql4TablesCursor.Create(self, Columns, Cursor);
end;
end;
function TDBXMySqlCustomMetaDataReader.FetchViews(const Catalog: UnicodeString; const Schema: UnicodeString; const View: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
if CompareVersion(TDBXVersion.FMySQL5) >= 0 then
Result := inherited FetchViews(Catalog, Schema, View)
else
begin
Columns := TDBXMetaDataCollectionColumns.CreateViewsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Views, Columns);
end;
end;
function TDBXMySqlCustomMetaDataReader.FetchColumns(const Catalog: UnicodeString; const Schema: UnicodeString; const Table: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
ParameterNames: TDBXStringArray;
ParameterValues: TDBXStringArray;
Original: TDBXTable;
Sanitized: TDBXTable;
Original4: TDBXTable;
begin
Columns := TDBXMetaDataCollectionColumns.CreateColumnsColumns;
if CompareVersion(TDBXVersion.FMySQL5) >= 0 then
begin
SetLength(ParameterNames,3);
ParameterNames[0] := TDBXParameterName.CatalogName;
ParameterNames[1] := TDBXParameterName.SchemaName;
ParameterNames[2] := TDBXParameterName.TableName;
SetLength(ParameterValues,3);
ParameterValues[0] := Catalog;
ParameterValues[1] := Schema;
ParameterValues[2] := Table;
Original := Context.ExecuteQuery(SqlForColumns, ParameterNames, ParameterValues);
Sanitized := TDBXCustomMetaDataTable.Create(Context, TDBXMetaDataCollectionName.Columns, Columns, Original);
Result := TDBXMySqlCustomMetaDataReader.TDBXMySqlColumnsTableCursor.Create(self, True, Original, Sanitized);
end
else
begin
Original4 := TDBXMySqlCustomMetaDataReader.TDBXMySql4ColumnsCursor.Create(self, Columns, SqlForColumns, Table);
Result := TDBXMySqlCustomMetaDataReader.TDBXMySqlColumnsTableCursor.Create(self, False, Original4, Original4);
end;
end;
function TDBXMySqlCustomMetaDataReader.FetchIndexes(const Catalog: UnicodeString; const Schema: UnicodeString; const Table: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
if CompareVersion(TDBXVersion.FMySQL5) >= 0 then
Exit(inherited FetchIndexes(Catalog, Schema, Table));
Columns := TDBXMetaDataCollectionColumns.CreateIndexesColumns;
Result := TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexesCursor.Create(self, Columns, SqlForIndexes, Table);
end;
function TDBXMySqlCustomMetaDataReader.FetchIndexColumns(const Catalog: UnicodeString; const Schema: UnicodeString; const Table: UnicodeString; const Index: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
if CompareVersion(TDBXVersion.FMySQL5) >= 0 then
Exit(inherited FetchIndexColumns(Catalog, Schema, Table, Index));
Columns := TDBXMetaDataCollectionColumns.CreateIndexColumnsColumns;
Result := TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexColumnsCursor.Create(self, Columns, SqlForIndexColumns, Table, Index);
end;
function TDBXMySqlCustomMetaDataReader.FetchForeignKeys(const Catalog: UnicodeString; const Schema: UnicodeString; const Table: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
if CompareVersion(TDBXVersion.FMySQL5) >= 0 then
Exit(inherited FetchForeignKeys(Catalog, Schema, Table));
Columns := TDBXMetaDataCollectionColumns.CreateForeignKeysColumns;
Result := TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyCursor.Create(self, Columns, SqlForForeignKeys, Table);
end;
function TDBXMySqlCustomMetaDataReader.FetchForeignKeyColumns(const Catalog: UnicodeString; const Schema: UnicodeString; const Table: UnicodeString; const ForeignKeyName: UnicodeString; const PrimaryCatalog: UnicodeString; const PrimarySchema: UnicodeString; const PrimaryTable: UnicodeString; const PrimaryKeyName: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
if CompareVersion(TDBXVersion.FMySQL5_0_6) >= 0 then
Exit(inherited FetchForeignKeyColumns(Catalog, Schema, Table, ForeignKeyName, PrimaryCatalog, PrimarySchema, PrimaryTable, PrimaryKeyName));
Columns := TDBXMetaDataCollectionColumns.CreateForeignKeyColumnsColumns;
Result := TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyColumnsCursor.Create(self, Columns, SqlForForeignKeys, Table, ForeignKeyName, PrimaryTable, PrimaryKeyName);
end;
function TDBXMySqlCustomMetaDataReader.FetchProcedures(const Catalog: UnicodeString; const Schema: UnicodeString; const ProcedureName: UnicodeString; const ProcType: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
if CompareVersion(TDBXVersion.FMySQL5_0_6) >= 0 then
Result := inherited FetchProcedures(Catalog, Schema, ProcedureName, ProcType)
else
begin
Columns := TDBXMetaDataCollectionColumns.CreateProceduresColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Procedures, Columns);
end;
end;
function TDBXMySqlCustomMetaDataReader.FetchProcedureSources(const Catalog: UnicodeString; const Schema: UnicodeString; const &Procedure: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateProcedureSourcesColumns;
if CompareVersion(TDBXVersion.FMySQL5_0_6) >= 0 then
Result := TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureSourcesCursor.Create(self, Columns, SqlForProcedureSources, Schema, &Procedure)
else
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.ProcedureSources, Columns);
end;
function TDBXMySqlCustomMetaDataReader.FetchProcedureParameters(const Catalog: UnicodeString; const Schema: UnicodeString; const &Procedure: UnicodeString; const Parameter: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateProcedureParametersColumns;
if CompareVersion(TDBXVersion.FMySQL5_0_6) >= 0 then
Result := TDBXColumnsTableCursor.Create(self, True, TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureParametersCursor.Create(self, Columns, SqlForProcedureSources, Schema, &Procedure, Parameter))
else
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.ProcedureParameters, Columns);
end;
function TDBXMySqlCustomMetaDataReader.FetchUsers: TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
if CompareVersion(TDBXVersion.FMySQL5) >= 0 then
Result := inherited FetchUsers
else
begin
Columns := TDBXMetaDataCollectionColumns.CreateUsersColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Users, Columns);
end;
end;
procedure TDBXMySqlCustomMetaDataReader.InitScanner;
var
Scan: TDBXSqlScanner;
begin
if FScanner = nil then
begin
Scan := TDBXSqlScanner.Create(SqlIdentifierQuoteChar, SqlIdentifierQuotePrefix, SqlIdentifierQuoteSuffix);
Scan.RegisterId(&Procedure, TokenProcedure);
Scan.RegisterId(&Function, TokenFunction);
Scan.RegisterId(Returns, TokenReturns);
Scan.RegisterId(&Begin, TokenBegin);
Scan.RegisterId(&In, TokenIn);
Scan.RegisterId(Out, TokenOut);
Scan.RegisterId(Inout, TokenInout);
Scan.RegisterId(Character, TokenCharacter);
Scan.RegisterId(&Set, TokenSet);
Scan.RegisterId(Utf8, TokenUtf8);
Scan.RegisterId(Unsigned, TokenUnsigned);
Scan.RegisterId(&Create, TokenCreate);
Scan.RegisterId(Definer, TokenDefiner);
Scan.RegisterId(&Not, TokenNot);
Scan.RegisterId(NullSpec, TokenNull);
Scan.RegisterId(Binary, TokenBinary);
FScanner := Scan;
end;
end;
procedure TDBXMySqlCustomMetaDataReader.GetProcedures(const SchemaName: UnicodeString; const ProcedureName: UnicodeString; const Procedures: TDBXStringList; const ProcedureTypes: TDBXStringList);
var
Cursor: TDBXTable;
begin
Cursor := FetchProcedures(NullString, SchemaName, ProcedureName, NullString);
while Cursor.Next do
begin
Procedures.Add(Cursor.Value[TDBXProceduresIndex.ProcedureName].AsString);
ProcedureTypes.Add(Cursor.Value[TDBXProceduresIndex.ProcedureType].AsString);
end;
Cursor.Close;
Cursor.Free;
end;
// CREATE DEFINER=`barney`@`%` FUNCTION `f1`(param1 INT) RETURNS int(11) begin return param1+1; end
// CREATE DEFINER=`barney`@`%` PROCEDURE `simpleproc`(OUT param1 INT) begin select count(*) into param1 from joal_t1; end
function TDBXMySqlCustomMetaDataReader.ParseProcedureDefiner(const Definition: UnicodeString): UnicodeString;
var
Definer: UnicodeString;
Token: Integer;
begin
InitScanner;
FScanner.Init(Definition);
Definer := NullString;
Token := FScanner.NextToken;
if Token = TokenCreate then
begin
Token := FScanner.NextToken;
if Token = TokenDefiner then
begin
Token := FScanner.NextToken;
if (Token = TDBXSqlScanner.TokenSymbol) and (FScanner.Symbol = '=') then
begin
Token := FScanner.NextToken;
if Token = TDBXSqlScanner.TokenId then
Definer := FScanner.Id;
end;
end;
end;
Result := Definer;
end;
procedure TDBXMySqlCustomMetaDataReader.ParseProcedure(const Definition: UnicodeString; const &Type: UnicodeString; const Params: TDBXArrayList);
var
ReturnType: TDBXMySqlCustomMetaDataReader.TMySqlParameter;
Ordinal: Integer;
Token: Integer;
Param: TDBXMySqlCustomMetaDataReader.TMySqlParameter;
begin
Params.Clear;
ReturnType := nil;
if (&Type = &Function) then
begin
ReturnType := TDBXMySqlCustomMetaDataReader.TMySqlParameter.Create;
ReturnType.FName := 'RETURN_VALUE';
ReturnType.FMode := 'RESULT';
ReturnType.FOrdinal := 0;
Params.Add(ReturnType);
end;
InitScanner;
FScanner.Init(Definition);
Ordinal := 1;
Token := TDBXSqlScanner.TokenId;
while Token <> TDBXSqlScanner.TokenOpenParen do
Token := FScanner.NextToken;
Token := TDBXSqlScanner.TokenComma;
while Token = TDBXSqlScanner.TokenComma do
begin
Param := TDBXMySqlCustomMetaDataReader.TMySqlParameter.Create;
Param.FMode := &In;
Token := FScanner.NextToken;
if (Token = TokenIn) or (Token = TokenOut) or (Token = TokenInout) then
begin
Param.FMode := FScanner.Id;
FScanner.NextToken;
end;
;
Param.FName := FScanner.Id;
Param.FOrdinal := Ordinal;
Token := ParseType(NullString, Param);
Params.Add(Param);
IncrAfter(Ordinal);
end;
;
Token := FScanner.NextToken;
if (ReturnType <> nil) and (Token = TokenReturns) then
ParseType(NullString, ReturnType);
end;
function TDBXMySqlCustomMetaDataReader.ParseType(const Definition: UnicodeString; const &Type: TDBXMySqlCustomMetaDataReader.TMySqlColumnType): Integer;
var
Token: Integer;
begin
if not StringIsNil(Definition) then
begin
InitScanner;
FScanner.Init(Definition);
end;
FScanner.NextToken;
&Type.FDataType := WideLowerCase(FScanner.Id);
&Type.FPrecision := 0;
&Type.FScale := 0;
&Type.FUnsigned := False;
&Type.FUnicode := False;
&Type.FNotnull := False;
if (&Type.FDataType = IntegerType) then
&Type.FDataType := IntType;
if (&Type.FDataType = DecType) then
&Type.FDataType := DecimalType;
Token := FScanner.NextToken;
if Token = TDBXSqlScanner.TokenOpenParen then
begin
Token := FScanner.NextToken;
if Token = TDBXSqlScanner.TokenNumber then
begin
&Type.FPrecision := ToInt(FScanner.Id);
Token := FScanner.NextToken;
if Token = TDBXSqlScanner.TokenComma then
begin
Token := FScanner.NextToken;
if Token = TDBXSqlScanner.TokenNumber then
begin
&Type.FScale := ToInt(FScanner.Id);
Token := FScanner.NextToken;
end;
end;
end;
while Token <> TDBXSqlScanner.TokenCloseParen do
Token := FScanner.NextToken;
Token := FScanner.NextToken;
end;
while True do
begin
case Token of
TokenBegin,
TDBXSqlScanner.TokenEos,
TDBXSqlScanner.TokenComma:
Exit(Token);
TokenUnsigned:
&Type.FUnsigned := True;
TokenUtf8:
&Type.FUnicode := True;
TokenBinary:
if (&Type.FDataType = 'varchar') then
&Type.FDataType := WideLowerCase(Varbinary)
else if (&Type.FDataType = 'char') then
&Type.FDataType := WideLowerCase(Binary);
TokenNot:
begin
Token := FScanner.NextToken;
if Token = TokenNull then
&Type.FNotnull := False
else if (Token = TDBXSqlScanner.TokenComma) or (Token = TokenBegin) then
Exit(Token);
end;
end;
Token := FScanner.NextToken;
end;
end;
function TDBXMySqlCustomMetaDataReader.GetTables: TDBXStringList;
var
Cursor: TDBXTable;
Tables: TDBXStringList;
begin
Cursor := Context.ExecuteQuery(SqlForTables, nil, nil);
Tables := TDBXStringList.Create;
while Cursor.Next do
Tables.Add(Cursor.Value[0].AsString);
Cursor.Close;
Cursor.Free;
Result := Tables;
end;
function TDBXMySqlCustomMetaDataReader.FindDataType(const TypeName: UnicodeString): Integer;
var
Hash: TDBXObjectStore;
DataType: TDBXDataTypeDescription;
begin
Hash := DataTypeHash;
DataType := TDBXDataTypeDescription(Hash[TypeName]);
if DataType <> nil then
Result := DataType.DbxDataType
else
Result := TDBXDataTypes.UnknownType;
end;
function TDBXMySqlCustomMetaDataReader.ReplaceIdentifier(const Sql: UnicodeString; const ParameterName: UnicodeString; const ActualValue: UnicodeString; const MakeQuotes: Boolean): UnicodeString;
var
ParameterStart: Integer;
ParameterEnd: Integer;
Value: UnicodeString;
begin
ParameterStart := StringLastIndexOf(Sql,ParameterName);
ParameterEnd := ParameterStart + Length(ParameterName);
Value := Sql;
if (ParameterStart > 0) and (Sql[1+ParameterStart - 1] = SqlDefaultParameterMarker[1+0]) then
begin
Dec(ParameterStart);
Value := ActualValue;
if MakeQuotes then
Value := TDBXMetaDataUtil.QuoteIdentifier(Value, SqlIdentifierQuoteChar, SqlIdentifierQuotePrefix, SqlIdentifierQuoteSuffix);
Value := Copy(Sql,0+1,ParameterStart-(0)) + Value + Copy(Sql,ParameterEnd+1,Length(Sql)-(ParameterEnd));
end;
Result := Value;
end;
function TDBXMySqlCustomMetaDataReader.ToInt(const Value: UnicodeString): Integer;
begin
try
Result := StrToInt(Value);
except
on Ex: Exception do
Result := -1;
end;
end;
function TDBXMySqlCustomMetaDataReader.ParseIdList(const Scanner: TDBXSqlScanner; const List: TDBXStringList): Boolean;
var
Token: Integer;
begin
Token := Scanner.NextToken;
if Token <> TDBXSqlScanner.TokenOpenParen then
Exit(False);
Token := Scanner.NextToken;
if Token <> TDBXSqlScanner.TokenId then
Exit(False);
List.Add(Scanner.Id);
Token := Scanner.NextToken;
while Token = TDBXSqlScanner.TokenComma do
begin
Token := Scanner.NextToken;
if Token <> TDBXSqlScanner.TokenId then
Exit(False);
List.Add(Scanner.Id);
Token := Scanner.NextToken;
end;
if Token <> TDBXSqlScanner.TokenCloseParen then
Exit(False);
Result := True;
end;
function TDBXMySqlCustomMetaDataReader.ParseForeignKey(const Scanner: TDBXSqlScanner; const ForeignKey: TDBXMySqlCustomMetaDataReader.TMySqlForeignKey): Boolean;
var
Token: Integer;
begin
Scanner.NextToken;
if not Scanner.IsKeyword(Constraint) then
Exit(False);
Token := Scanner.NextToken;
if Token <> TDBXSqlScanner.TokenId then
Exit(False);
ForeignKey.FConstraintName := Scanner.Id;
Scanner.NextToken;
if not Scanner.IsKeyword(Foreign) then
Exit(False);
Scanner.NextToken;
if not Scanner.IsKeyword(Key) then
Exit(False);
if not ParseIdList(Scanner, ForeignKey.FKeyColumns) then
Exit(False);
Scanner.NextToken;
if not Scanner.IsKeyword(References) then
Exit(False);
Token := Scanner.NextToken;
if Token <> TDBXSqlScanner.TokenId then
Exit(False);
ForeignKey.FReferencedTableName := Scanner.Id;
Result := ParseIdList(Scanner, ForeignKey.FReferencedColumns);
end;
function TDBXMySqlCustomMetaDataReader.ParseCreateTableForNextForeignKey(const Sql: UnicodeString; const InStartIndex: Integer; const Key: TDBXMySqlCustomMetaDataReader.TMySqlForeignKey): Integer;
var
StartIndex: Integer;
Index: Integer;
begin
StartIndex := InStartIndex;
Index := StringIndexOf(Sql,Constraint,StartIndex);
InitScanner;
while Index > 0 do
begin
StartIndex := Index + Length(Constraint);
FScanner.Init(Sql, Index);
Key.Reset;
if ParseForeignKey(FScanner, Key) then
begin
FreeAndNil(FScanner);
Exit(StartIndex);
end;
Index := StringIndexOf(Sql,Constraint,StartIndex);
end;
FreeAndNil(FScanner);
Result := -1;
end;
constructor TDBXMySqlCustomMetaDataReader.TMySqlForeignKey.Create;
begin
inherited Create;
FKeyColumns := TDBXStringList.Create;
FReferencedColumns := TDBXStringList.Create;
end;
destructor TDBXMySqlCustomMetaDataReader.TMySqlForeignKey.Destroy;
begin
FreeAndNil(FKeyColumns);
FreeAndNil(FReferencedColumns);
inherited Destroy;
end;
procedure TDBXMySqlCustomMetaDataReader.TMySqlForeignKey.Reset;
begin
FConstraintName := NullString;
FKeyColumns.Clear;
FReferencedColumns.Clear;
end;
constructor TDBXMySqlCustomMetaDataReader.TDBXMySql4TablesCursor.Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Cursor: TDBXTable);
begin
inherited Create(Reader.Context, TDBXMetaDataCollectionName.Tables, Columns, Cursor);
FNullValue := TDBXWritableValue(TDBXValue.CreateValue(TDBXValueType(Columns[TDBXTablesIndex.TableType].Clone())));
FNullValue.SetNull;
FTableValue := TDBXWritableValue(TDBXValue.CreateValue(TDBXValueType(Columns[TDBXTablesIndex.TableType].Clone())));
FTableValue.AsString := Table;
end;
destructor TDBXMySqlCustomMetaDataReader.TDBXMySql4TablesCursor.Destroy;
begin
FreeAndNil(FTableValue);
FreeAndNil(FNullValue);
inherited Destroy;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4TablesCursor.FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer;
begin
case Ordinal of
TDBXTablesIndex.TableName:
Result := SourceColumns[ShowTablesTableNameOrdinal].Size;
else
Result := DefaultVarcharPrecision;
end;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4TablesCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue;
begin
if Ordinal = TDBXTablesIndex.TableName then
Exit(inherited GetWritableValue(ShowTablesTableNameOrdinal));
if Ordinal = TDBXTablesIndex.TableType then
Exit(FTableValue);
Result := FNullValue;
end;
constructor TDBXMySqlCustomMetaDataReader.TDBXMySqlColumnsTableCursor.Create(const Reader: TDBXMySqlCustomMetaDataReader; const Version5: Boolean; const Original: TDBXTable; const Sanitized: TDBXTable);
begin
inherited Create(Reader, False, Sanitized);
self.FOriginal := Original;
self.FVersion5 := Version5;
FRow := TDBXSingleValueRow.Create;
FRow.Columns := CopyColumns;
end;
destructor TDBXMySqlCustomMetaDataReader.TDBXMySqlColumnsTableCursor.Destroy;
begin
FreeAndNil(FRow);
inherited Destroy;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySqlColumnsTableCursor.Next: Boolean;
var
ReturnValue: Boolean;
Value: TDBXWritableValue;
IsUnsigned: Boolean;
DataType: Integer;
begin
ReturnValue := inherited Next;
if ReturnValue then
begin
Value := FRow.Value[TDBXColumnsIndex.IsUnicode];
if FVersion5 then
Value.SetBoolean((FOriginal.Value[MysqlIsUnicode].AsString = Utf8))
else
Value.AsBoolean := False;
Value := FRow.Value[TDBXColumnsIndex.IsUnsigned];
if FVersion5 then
IsUnsigned := FOriginal.Value[MysqlIsUnsigned].AsBoolean
else
IsUnsigned := FOriginal.Value[TDBXColumnsIndex.IsUnsigned].GetBoolean;
Value.AsBoolean := IsUnsigned;
DataType := inherited GetWritableValue(TDBXColumnsIndex.DbxDataType).AsInt32;
if IsUnsigned then
case DataType of
TDBXDataTypes.Int8Type:
DataType := TDBXDataTypes.UInt8Type;
TDBXDataTypes.Int16Type:
DataType := TDBXDataTypes.UInt16Type;
TDBXDataTypes.Int32Type:
DataType := TDBXDataTypes.UInt32Type;
TDBXDataTypes.Int64Type:
DataType := TDBXDataTypes.UInt64Type;
end;
FRow.Value[TDBXColumnsIndex.DbxDataType].AsInt32 := DataType;
end;
Result := ReturnValue;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySqlColumnsTableCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue;
begin
case Ordinal of
TDBXColumnsIndex.IsUnicode,
TDBXColumnsIndex.IsUnsigned,
TDBXColumnsIndex.DbxDataType:
Exit(FRow.Value[Ordinal]);
end;
Result := inherited GetWritableValue(Ordinal);
end;
constructor TDBXMySqlCustomMetaDataReader.TDBXMySql4ColumnsCursor.Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Sql: UnicodeString; const TableName: UnicodeString);
begin
inherited Create(Reader.Context, TDBXMetaDataCollectionName.Columns, Columns, nil);
self.FReader := Reader;
self.FSql := Sql;
self.FTableName := TableName;
if StringIsNil(TableName) then
begin
self.FTables := Reader.Tables;
self.FTableIndex := -1;
end;
self.FColumnType := TDBXMySqlCustomMetaDataReader.TMySqlColumnType.Create;
InitNextCursor;
FRow := TDBXSingleValueRow.Create;
FRow.Columns := CopyColumns;
end;
destructor TDBXMySqlCustomMetaDataReader.TDBXMySql4ColumnsCursor.Destroy;
begin
Close;
FreeAndNil(FRow);
inherited Destroy;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4ColumnsCursor.FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer;
begin
case Ordinal of
TDBXColumnsIndex.ColumnName:
Result := SourceColumns[ShowColumnsFieldOrdinal].Size;
TDBXColumnsIndex.DefaultValue:
Result := SourceColumns[ShowColumnsDefaultOrdinal].Size;
else
Result := DefaultVarcharPrecision;
end;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4ColumnsCursor.InitNextCursor: Boolean;
var
Query: UnicodeString;
begin
if FTables <> nil then
begin
IncrAfter(FTableIndex);
if FTableIndex >= FTables.Count then
Exit(False);
FTableName := UnicodeString(FTables[FTableIndex]);
end;
Query := FReader.ReplaceIdentifier(FSql, TDBXParameterName.TableName, FTableName, True);
try
FCursor := FReader.Context.ExecuteQuery(Query, nil, nil);
except
on Ex: Exception do
FCursor := nil;
end;
FColumnNumber := 0;
Result := (FCursor <> nil);
end;
procedure TDBXMySqlCustomMetaDataReader.TDBXMySql4ColumnsCursor.Close;
begin
if FCursor <> nil then
FCursor.Close;
FreeAndNil(FCursor);
FreeAndNil(FTables);
FreeAndNil(FColumnType);
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4ColumnsCursor.Next: Boolean;
begin
if FCursor = nil then
Exit(False);
while not FCursor.Next do
begin
FCursor.Close;
FCursor.Free;
FCursor := nil;
if (FTables = nil) or not InitNextCursor then
Exit(False);
end;
IncrAfter(FColumnNumber);
FReader.ParseType(FCursor.Value[ShowColumnsTypeOrdinal].AsString, FColumnType);
FRow.Value[TDBXColumnsIndex.CatalogName].SetNull;
FRow.Value[TDBXColumnsIndex.SchemaName].SetNull;
FRow.Value[TDBXColumnsIndex.TableName].AsString := FTableName;
FRow.Value[TDBXColumnsIndex.ColumnName].AsString := FCursor.Value[ShowColumnsFieldOrdinal].AsString;
FRow.Value[TDBXColumnsIndex.DefaultValue].AsString := ComputeDefaultValue;
FRow.Value[TDBXColumnsIndex.TypeName].AsString := FColumnType.FDataType;
FRow.Value[TDBXColumnsIndex.Ordinal].AsInt32 := FColumnNumber;
FRow.Value[TDBXColumnsIndex.Precision].AsInt32 := FColumnType.FPrecision;
FRow.Value[TDBXColumnsIndex.Scale].AsInt32 := FColumnType.FScale;
FRow.Value[TDBXColumnsIndex.IsAutoIncrement].AsBoolean := ComputeAutoIncrement;
FRow.Value[TDBXColumnsIndex.IsNullable].AsBoolean := ComputeNullable;
FRow.Value[TDBXColumnsIndex.IsUnsigned].AsBoolean := FColumnType.FUnsigned;
FRow.Value[TDBXColumnsIndex.IsUnicode].AsBoolean := False;
Result := True;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4ColumnsCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue;
begin
case Ordinal of
TDBXColumnsIndex.CatalogName,
TDBXColumnsIndex.SchemaName,
TDBXColumnsIndex.TableName,
TDBXColumnsIndex.ColumnName,
TDBXColumnsIndex.DefaultValue,
TDBXColumnsIndex.TypeName,
TDBXColumnsIndex.Ordinal,
TDBXColumnsIndex.Precision,
TDBXColumnsIndex.Scale,
TDBXColumnsIndex.IsAutoIncrement,
TDBXColumnsIndex.IsNullable,
TDBXColumnsIndex.IsUnsigned,
TDBXColumnsIndex.IsUnicode:
Exit(FRow.Value[Ordinal]);
end;
Result := inherited GetWritableValue(Ordinal);
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4ColumnsCursor.ComputeDefaultValue: UnicodeString;
var
DefaultValue: UnicodeString;
DataType: Integer;
begin
DefaultValue := NullString;
if not FCursor.Value[ShowColumnsDefaultOrdinal].IsNull then
DefaultValue := FCursor.Value[ShowColumnsDefaultOrdinal].AsString;
if (not StringIsNil(DefaultValue)) and not (DefaultValue = CurrentTimestamp) then
begin
if Length(DefaultValue) = 0 then
DefaultValue := NullString
else
begin
DataType := FReader.FindDataType(FColumnType.FDataType);
case DataType of
TDBXDataTypes.Int32Type:
if (FColumnType.FDataType = FYear) then
DefaultValue := Quote + DefaultValue + Quote;
TDBXDataTypes.WideStringType,
TDBXDataTypes.AnsiStringType,
TDBXDataTypes.TimeStampType,
TDBXDataTypes.TimeType,
TDBXDataTypes.DateType:
DefaultValue := Quote + DefaultValue + Quote;
end;
end;
end;
Result := DefaultValue;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4ColumnsCursor.ComputeAutoIncrement: Boolean;
begin
Result := not FCursor.Value[ShowColumnsExtraOrdinal].IsNull and (StringIndexOf(FCursor.Value[ShowColumnsExtraOrdinal].AsString,FAuto_increment) >= 0);
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4ColumnsCursor.ComputeNullable: Boolean;
begin
Result := not FCursor.Value[ShowColumnsNullOrdinal].IsNull and (YForYes = FCursor.Value[ShowColumnsNullOrdinal].AsString);
end;
constructor TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexesCursor.Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Sql: UnicodeString; const TableName: UnicodeString);
begin
inherited Create(Reader.Context, TDBXMetaDataCollectionName.Indexes, Columns, nil);
self.FReader := Reader;
self.FSql := Sql;
self.FTableName := TableName;
if StringIsNil(TableName) then
begin
self.FTables := Reader.Tables;
self.FTableIndex := -1;
end;
InitNextCursor;
FRow := TDBXSingleValueRow.Create;
FRow.Columns := CopyColumns;
end;
destructor TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexesCursor.Destroy;
begin
Close;
inherited Destroy;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexesCursor.FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer;
begin
case Ordinal of
TDBXIndexesIndex.IndexName,
TDBXIndexesIndex.ConstraintName:
Result := SourceColumns[ShowIndexKeyNameOrdinal].Size;
else
Result := DefaultVarcharPrecision;
end;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexesCursor.InitNextCursor: Boolean;
var
Query: UnicodeString;
begin
if FTables <> nil then
begin
IncrAfter(FTableIndex);
if FTableIndex >= FTables.Count then
Exit(False);
FTableName := UnicodeString(FTables[FTableIndex]);
end;
Query := FReader.ReplaceIdentifier(FSql, TDBXParameterName.TableName, FTableName, True);
try
FCursor := FReader.Context.ExecuteQuery(Query, nil, nil);
except
on Ex: Exception do
FCursor := nil;
end;
Result := (FCursor <> nil);
end;
procedure TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexesCursor.Close;
begin
if FCursor <> nil then
FCursor.Close;
FreeAndNil(FCursor);
FreeAndNil(FTables);
FreeAndNil(FRow);
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexesCursor.Next: Boolean;
begin
if FCursor = nil then
Exit(False);
FPrevTableName := FTableName;
FPrevIndexName := FIndexName;
repeat
while not FCursor.Next do
begin
FCursor.Close;
FCursor.Free;
FCursor := nil;
if (FTables = nil) or not InitNextCursor then
Exit(False);
end;
FUniqueIndex := not FCursor.Value[ShowIndexNonUniqueOrdinal].IsNull and not FCursor.Value[ShowIndexNonUniqueOrdinal].AsBoolean;
FIndexName := FCursor.Value[ShowIndexKeyNameOrdinal].AsString;
until not ((FTableName = FPrevTableName) and (FIndexName = FPrevIndexName));
FRow.Value[TDBXIndexesIndex.CatalogName].SetNull;
FRow.Value[TDBXIndexesIndex.SchemaName].SetNull;
if not FUniqueIndex then
FRow.Value[TDBXIndexesIndex.ConstraintName].SetNull
else
FRow.Value[TDBXIndexesIndex.ConstraintName].AsString := ComputeConstraintName;
FRow.Value[TDBXIndexesIndex.TableName].AsString := FTableName;
FRow.Value[TDBXIndexesIndex.IndexName].AsString := FIndexName;
FRow.Value[TDBXIndexesIndex.IsPrimary].AsBoolean := FUniqueIndex and (Primary = FIndexName);
FRow.Value[TDBXIndexesIndex.IsUnique].AsBoolean := FUniqueIndex;
FRow.Value[TDBXIndexesIndex.IsAscending].AsBoolean := True;
Result := True;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexesCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue;
begin
case Ordinal of
TDBXIndexesIndex.CatalogName,
TDBXIndexesIndex.SchemaName,
TDBXIndexesIndex.ConstraintName,
TDBXIndexesIndex.TableName,
TDBXIndexesIndex.IndexName,
TDBXIndexesIndex.IsPrimary,
TDBXIndexesIndex.IsUnique,
TDBXIndexesIndex.IsAscending:
Exit(FRow.Value[Ordinal]);
end;
Result := inherited GetWritableValue(Ordinal);
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexesCursor.ComputeConstraintName: UnicodeString;
var
ConstraintName: UnicodeString;
begin
ConstraintName := NullString;
if FUniqueIndex then
ConstraintName := FIndexName;
Result := ConstraintName;
end;
constructor TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexColumnsCursor.Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Sql: UnicodeString; const TableName: UnicodeString; const IndexName: UnicodeString);
begin
inherited Create(Reader.Context, TDBXMetaDataCollectionName.IndexColumns, Columns, nil);
self.FReader := Reader;
self.FSql := Sql;
self.FTableName := TableName;
self.FWantedIndexName := IndexName;
if StringIsNil(TableName) then
begin
self.FTables := Reader.Tables;
self.FTableIndex := -1;
end;
InitNextCursor;
FRow := TDBXSingleValueRow.Create;
FRow.Columns := CopyColumns;
end;
destructor TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexColumnsCursor.Destroy;
begin
Close;
FreeAndNil(FRow);
inherited Destroy;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexColumnsCursor.FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer;
begin
case Ordinal of
TDBXIndexColumnsIndex.IndexName:
Result := SourceColumns[ShowIndexKeyNameOrdinal].Size;
TDBXIndexColumnsIndex.ColumnName:
Result := SourceColumns[ShowIndexColumnNameOrdinal].Size;
else
Result := DefaultVarcharPrecision;
end;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexColumnsCursor.InitNextCursor: Boolean;
var
Query: UnicodeString;
begin
if FTables <> nil then
begin
IncrAfter(FTableIndex);
if FTableIndex >= FTables.Count then
Exit(False);
FTableName := UnicodeString(FTables[FTableIndex]);
end;
Query := FReader.ReplaceIdentifier(FSql, TDBXParameterName.TableName, FTableName, True);
try
FCursor := FReader.Context.ExecuteQuery(Query, nil, nil);
except
on Ex: Exception do
FCursor := nil;
end;
Result := (FCursor <> nil);
end;
procedure TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexColumnsCursor.Close;
begin
if FCursor <> nil then
FCursor.Close;
FreeAndNil(FCursor);
FreeAndNil(FTables);
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexColumnsCursor.Next: Boolean;
begin
if FCursor = nil then
Exit(False);
repeat
while not FCursor.Next do
begin
FCursor.Close;
FCursor.Free;
FCursor := nil;
if (FTables = nil) or not InitNextCursor then
Exit(False);
end;
FIndexName := FCursor.Value[ShowIndexKeyNameOrdinal].AsString;
until ((StringIsNil(FWantedIndexName)) or (FWantedIndexName = FIndexName));
FRow.Value[TDBXIndexColumnsIndex.CatalogName].SetNull;
FRow.Value[TDBXIndexColumnsIndex.SchemaName].SetNull;
FRow.Value[TDBXIndexColumnsIndex.TableName].AsString := FTableName;
FRow.Value[TDBXIndexColumnsIndex.IndexName].AsString := FIndexName;
FRow.Value[TDBXIndexColumnsIndex.ColumnName].AsString := FCursor.Value[ShowIndexColumnNameOrdinal].AsString;
FRow.Value[TDBXIndexColumnsIndex.Ordinal].AsInt32 := FCursor.Value[ShowIndexSeqInIndexOrdinal].AsInt32;
FRow.Value[TDBXIndexColumnsIndex.IsAscending].AsBoolean := True;
Result := True;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4IndexColumnsCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue;
begin
case Ordinal of
TDBXIndexColumnsIndex.CatalogName,
TDBXIndexColumnsIndex.SchemaName,
TDBXIndexColumnsIndex.TableName,
TDBXIndexColumnsIndex.IndexName,
TDBXIndexColumnsIndex.ColumnName,
TDBXIndexColumnsIndex.Ordinal,
TDBXIndexColumnsIndex.IsAscending:
Exit(FRow.Value[Ordinal]);
end;
Result := inherited GetWritableValue(Ordinal);
end;
constructor TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyCursor.Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Sql: UnicodeString; const TableName: UnicodeString);
begin
FKey := TDBXMySqlCustomMetaDataReader.TMySqlForeignKey.Create;
inherited Create(Reader.Context, TDBXMetaDataCollectionName.ForeignKeys, Columns, nil);
self.FReader := Reader;
self.FSql := Sql;
self.FTableName := TableName;
if StringIsNil(TableName) then
begin
self.FTables := Reader.Tables;
self.FTableIndex := -1;
end;
InitNextCursor;
FRow := TDBXSingleValueRow.Create;
FRow.Columns := CopyColumns;
end;
destructor TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyCursor.Destroy;
begin
Close;
FreeAndNil(FRow);
inherited Destroy;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyCursor.FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer;
begin
Result := DefaultVarcharPrecision;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyCursor.InitNextCursor: Boolean;
var
Query: UnicodeString;
begin
if FTables <> nil then
begin
IncrAfter(FTableIndex);
if FTableIndex >= FTables.Count then
Exit(False);
FTableName := UnicodeString(FTables[FTableIndex]);
end;
Query := FReader.ReplaceIdentifier(FSql, TDBXParameterName.TableName, FTableName, True);
try
FCursor := FReader.Context.ExecuteQuery(Query, nil, nil);
except
on Ex: Exception do
FCursor := nil;
end;
FParseIndex := -1;
Result := (FCursor <> nil);
end;
procedure TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyCursor.Close;
begin
if FCursor <> nil then
FCursor.Close;
FreeAndNil(FCursor);
FreeAndNil(FTables);
FreeAndNil(FKey);
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyCursor.Next: Boolean;
begin
if FCursor = nil then
Exit(False);
repeat
if FParseIndex < 0 then
begin
while not FCursor.Next do
begin
FCursor.Close;
FCursor.Free;
FCursor := nil;
if (FTables = nil) or not InitNextCursor then
Exit(False);
end;
FSqlCreateTable := FCursor.Value[ShowCreateTableSqlOrdinal].AsString;
FParseIndex := 0;
end;
FParseIndex := FReader.ParseCreateTableForNextForeignKey(FSqlCreateTable, FParseIndex, FKey);
until FParseIndex >= 0;
FRow.Value[TDBXForeignKeysIndex.CatalogName].SetNull;
FRow.Value[TDBXForeignKeysIndex.SchemaName].SetNull;
FRow.Value[TDBXForeignKeysIndex.TableName].AsString := FTableName;
FRow.Value[TDBXForeignKeysIndex.ForeignKeyName].AsString := FKey.FConstraintName;
Result := True;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue;
begin
case Ordinal of
TDBXForeignKeysIndex.CatalogName,
TDBXForeignKeysIndex.SchemaName,
TDBXForeignKeysIndex.TableName,
TDBXForeignKeysIndex.ForeignKeyName:
Exit(FRow.Value[Ordinal]);
end;
Result := inherited GetWritableValue(Ordinal);
end;
constructor TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyColumnsCursor.Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Sql: UnicodeString; const TableName: UnicodeString; const ForeignKeyName: UnicodeString; const PrimaryTableName: UnicodeString; const PrimaryKeyName: UnicodeString);
begin
FKey := TDBXMySqlCustomMetaDataReader.TMySqlForeignKey.Create;
inherited Create(Reader.Context, TDBXMetaDataCollectionName.ForeignKeyColumns, Columns, nil);
self.FReader := Reader;
self.FSql := Sql;
self.FTableName := TableName;
self.FForeignKeyName := ForeignKeyName;
self.FPrimaryTableName := PrimaryTableName;
self.FPrimaryKeyName := PrimaryKeyName;
if StringIsNil(TableName) then
begin
self.FTables := Reader.Tables;
self.FTableIndex := -1;
end;
InitNextCursor;
FRow := TDBXSingleValueRow.Create;
FRow.Columns := CopyColumns;
end;
destructor TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyColumnsCursor.Destroy;
begin
Close;
FreeAndNil(FRow);
inherited Destroy;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyColumnsCursor.FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer;
begin
Result := DefaultVarcharPrecision;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyColumnsCursor.InitNextCursor: Boolean;
var
Query: UnicodeString;
begin
if FTables <> nil then
begin
IncrAfter(FTableIndex);
if FTableIndex >= FTables.Count then
Exit(False);
FTableName := UnicodeString(FTables[FTableIndex]);
end;
Query := FReader.ReplaceIdentifier(FSql, TDBXParameterName.TableName, FTableName, True);
try
FCursor := FReader.Context.ExecuteQuery(Query, nil, nil);
except
on Ex: Exception do
FCursor := nil;
end;
FParseIndex := -1;
Result := (FCursor <> nil);
end;
procedure TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyColumnsCursor.Close;
begin
if FCursor <> nil then
FCursor.Close;
FreeAndNil(FCursor);
FreeAndNil(FTables);
FreeAndNil(FKey);
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyColumnsCursor.Next: Boolean;
begin
if FCursor = nil then
Exit(False);
IncrAfter(FKeyIndex);
if FKeyIndex < FKey.FKeyColumns.Count then
begin
SetValues;
Exit(True);
end;
repeat
if FParseIndex < 0 then
begin
while not FCursor.Next do
begin
FCursor.Close;
FCursor.Free;
FCursor := nil;
if (FTables = nil) or not InitNextCursor then
Exit(False);
end;
FSqlCreateTable := FCursor.Value[ShowCreateTableSqlOrdinal].AsString;
FParseIndex := 0;
end;
FParseIndex := FReader.ParseCreateTableForNextForeignKey(FSqlCreateTable, FParseIndex, FKey);
until ((FParseIndex >= 0) and (FKey.FKeyColumns.Count > 0) and ((StringIsNil(FForeignKeyName)) or (FForeignKeyName = FKey.FConstraintName)) and ((StringIsNil(FPrimaryTableName)) or (FPrimaryTableName = FKey.FReferencedTableName)));
FKeyIndex := 0;
SetValues;
Result := True;
end;
procedure TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyColumnsCursor.SetValues;
begin
FRow.Value[TDBXForeignKeyColumnsIndex.CatalogName].SetNull;
FRow.Value[TDBXForeignKeyColumnsIndex.SchemaName].SetNull;
FRow.Value[TDBXForeignKeyColumnsIndex.PrimaryCatalogName].SetNull;
FRow.Value[TDBXForeignKeyColumnsIndex.PrimarySchemaName].SetNull;
FRow.Value[TDBXForeignKeyColumnsIndex.PrimaryKeyName].SetNull;
FRow.Value[TDBXForeignKeyColumnsIndex.TableName].AsString := FTableName;
FRow.Value[TDBXForeignKeyColumnsIndex.ForeignKeyName].AsString := FKey.FConstraintName;
FRow.Value[TDBXForeignKeyColumnsIndex.PrimaryTableName].AsString := FKey.FReferencedTableName;
FRow.Value[TDBXForeignKeyColumnsIndex.ColumnName].AsString := UnicodeString(FKey.FKeyColumns[FKeyIndex]);
FRow.Value[TDBXForeignKeyColumnsIndex.PrimaryColumnName].AsString := UnicodeString(FKey.FReferencedColumns[FKeyIndex]);
FRow.Value[TDBXForeignKeyColumnsIndex.Ordinal].AsInt32 := FKeyIndex + 1;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySql4ForeignKeyColumnsCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue;
begin
case Ordinal of
TDBXForeignKeyColumnsIndex.CatalogName,
TDBXForeignKeyColumnsIndex.SchemaName,
TDBXForeignKeyColumnsIndex.PrimaryCatalogName,
TDBXForeignKeyColumnsIndex.PrimarySchemaName,
TDBXForeignKeyColumnsIndex.PrimaryKeyName,
TDBXForeignKeyColumnsIndex.TableName,
TDBXForeignKeyColumnsIndex.ForeignKeyName,
TDBXForeignKeyColumnsIndex.PrimaryTableName,
TDBXForeignKeyColumnsIndex.ColumnName,
TDBXForeignKeyColumnsIndex.PrimaryColumnName,
TDBXForeignKeyColumnsIndex.Ordinal:
Exit(FRow.Value[Ordinal]);
end;
Result := inherited GetWritableValue(Ordinal);
end;
constructor TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureSourcesCursor.Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Sql: UnicodeString; const SchemaName: UnicodeString; const ProcedureName: UnicodeString);
begin
inherited Create(Reader.Context, TDBXMetaDataCollectionName.ProcedureSources, Columns, nil);
self.FReader := Reader;
self.FSql := Sql;
self.FProcedureName := ProcedureName;
self.FProcedureType := &Procedure;
self.FProcedures := TDBXStringList.Create;
self.FProcedureTypes := TDBXStringList.Create;
self.FReader.GetProcedures(SchemaName, ProcedureName, FProcedures, FProcedureTypes);
self.FProcedureIndex := -1;
InitNextCursor;
FRow := TDBXSingleValueRow.Create;
FRow.Columns := CopyColumns;
end;
destructor TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureSourcesCursor.Destroy;
begin
Close;
FreeAndNil(FRow);
inherited Destroy;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureSourcesCursor.FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer;
begin
Result := DefaultVarcharPrecision;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureSourcesCursor.InitNextCursor: Boolean;
var
Query: UnicodeString;
begin
IncrAfter(FProcedureIndex);
if FProcedureIndex >= FProcedures.Count then
Exit(False);
FProcedureName := UnicodeString(FProcedures[FProcedureIndex]);
FProcedureType := UnicodeString(FProcedureTypes[FProcedureIndex]);
Query := FSql;
Query := FReader.ReplaceIdentifier(Query, TDBXParameterName.ProcedureName, FProcedureName, True);
Query := FReader.ReplaceIdentifier(Query, TDBXParameterName.ProcedureType, FProcedureType, False);
FCursor := FReader.Context.ExecuteQuery(Query, nil, nil);
Result := True;
end;
procedure TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureSourcesCursor.Close;
begin
if FCursor <> nil then
FCursor.Close;
FCursor.Free;
FCursor := nil;
FreeAndNil(FProcedures);
FreeAndNil(FProcedureTypes);
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureSourcesCursor.Next: Boolean;
begin
if FCursor = nil then
Exit(False);
while not FCursor.Next do
begin
FCursor.Close;
FCursor.Free;
FCursor := nil;
if not InitNextCursor then
Exit(False);
end;
FDefiner := ComputeDefiner;
FRow.Value[TDBXProcedureSourcesIndex.CatalogName].SetNull;
FRow.Value[TDBXProcedureSourcesIndex.ExternalDefinition].SetNull;
if StringIsNil(FDefiner) then
FRow.Value[TDBXProcedureSourcesIndex.SchemaName].SetNull
else
FRow.Value[TDBXProcedureSourcesIndex.SchemaName].AsString := FDefiner;
FRow.Value[TDBXProcedureSourcesIndex.ProcedureName].AsString := FProcedureName;
FRow.Value[TDBXProcedureSourcesIndex.ProcedureType].AsString := FProcedureType;
FRow.Value[TDBXProcedureSourcesIndex.Definition].AsString := ComputeDefinition;
Result := True;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureSourcesCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue;
begin
case Ordinal of
TDBXProcedureSourcesIndex.CatalogName,
TDBXProcedureSourcesIndex.ExternalDefinition,
TDBXProcedureSourcesIndex.SchemaName,
TDBXProcedureSourcesIndex.ProcedureName,
TDBXProcedureSourcesIndex.ProcedureType,
TDBXProcedureSourcesIndex.Definition:
Exit(FRow.Value[Ordinal]);
end;
Result := inherited GetWritableValue(Ordinal);
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureSourcesCursor.ComputeDefinition: UnicodeString;
var
SqlCreateProcedure: UnicodeString;
Index: Integer;
begin
SqlCreateProcedure := FCursor.Value[ShowCreateProcedureSqlOrdinal].AsString;
Index := StringIndexOf(SqlCreateProcedure,FProcedureType);
if Index >= 0 then
SqlCreateProcedure := &Create + '"' + Copy(SqlCreateProcedure,Index+1,Length(SqlCreateProcedure)-(Index));
Result := SqlCreateProcedure;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureSourcesCursor.ComputeDefiner: UnicodeString;
var
Definer: UnicodeString;
SqlCreateProcedure: UnicodeString;
Index: Integer;
EndIndex: Integer;
begin
Definer := NullString;
SqlCreateProcedure := FCursor.Value[ShowCreateProcedureSqlOrdinal].AsString;
Index := StringIndexOf(SqlCreateProcedure,DefinerString);
if Index >= 0 then
begin
Index := Index + Length(DefinerString) + 1;
EndIndex := StringIndexOf(SqlCreateProcedure,FReader.SqlIdentifierQuoteSuffix,Index);
if EndIndex > 0 then
Definer := Copy(SqlCreateProcedure,Index+1,EndIndex-(Index));
end;
Result := Definer;
end;
constructor TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureParametersCursor.Create(const Reader: TDBXMySqlCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Sql: UnicodeString; const SchemaName: UnicodeString; const ProcedureName: UnicodeString; const ParameterName: UnicodeString);
begin
inherited Create(Reader.Context, TDBXMetaDataCollectionName.ProcedureParameters, Columns, nil);
self.FReader := Reader;
self.FSql := Sql;
self.FProcedureName := ProcedureName;
self.FParameterName := ParameterName;
self.FProcedureType := &Procedure;
self.FProcedures := TDBXStringList.Create;
self.FProcedureTypes := TDBXStringList.Create;
self.FReader.GetProcedures(SchemaName, ProcedureName, FProcedures, FProcedureTypes);
self.FProcedureIndex := -1;
self.FParams := TDBXArrayList.Create;
InitNextCursor;
FRow := TDBXSingleValueRow.Create;
FRow.Columns := CopyColumns;
end;
destructor TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureParametersCursor.Destroy;
var
I: Integer;
begin
Close;
if FParams <> nil then
begin
for I := 0 to FParams.Count - 1 do
FParams[I].Free;
FParams.Clear;
end;
FreeAndNil(FParams);
FreeAndNil(FRow);
inherited Destroy;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureParametersCursor.FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer;
begin
Result := DefaultVarcharPrecision;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureParametersCursor.InitNextCursor: Boolean;
var
Query: UnicodeString;
begin
IncrAfter(FProcedureIndex);
if FProcedureIndex >= FProcedures.Count then
Exit(False);
FProcedureName := UnicodeString(FProcedures[FProcedureIndex]);
FProcedureType := UnicodeString(FProcedureTypes[FProcedureIndex]);
Query := FSql;
Query := FReader.ReplaceIdentifier(Query, TDBXParameterName.ProcedureName, FProcedureName, True);
Query := FReader.ReplaceIdentifier(Query, TDBXParameterName.ProcedureType, FProcedureType, False);
FCursor := FReader.Context.ExecuteQuery(Query, nil, nil);
Result := True;
end;
procedure TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureParametersCursor.Close;
begin
if FCursor <> nil then
FCursor.Close;
FreeAndNil(FCursor);
FreeAndNil(FProcedures);
FreeAndNil(FProcedureTypes);
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureParametersCursor.Next: Boolean;
begin
if FCursor = nil then
Exit(False);
IncrAfter(FParameterIndex);
while True do
begin
while FParameterIndex < FParams.Count do
begin
FParameter := TDBXMySqlCustomMetaDataReader.TMySqlParameter(FParams[FParameterIndex]);
if (StringIsNil(FParameterName)) or (FParameterName = FParameter.FName) then
begin
SetValues;
Exit(True);
end;
IncrAfter(FParameterIndex);
end;
while not FCursor.Next do
begin
FCursor.Close;
FreeAndNil(FCursor);
if not InitNextCursor then
Exit(False);
end;
ComputeParams;
end;
end;
procedure TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureParametersCursor.SetValues;
begin
FRow.Value[TDBXProcedureParametersIndex.SchemaName].SetNull;
FRow.Value[TDBXProcedureParametersIndex.DbxDataType].SetNull;
FRow.Value[TDBXProcedureParametersIndex.IsFixedLength].SetNull;
FRow.Value[TDBXProcedureParametersIndex.IsLong].SetNull;
if StringIsNil(FDefiner) then
FRow.Value[TDBXProcedureParametersIndex.CatalogName].SetNull
else
FRow.Value[TDBXProcedureParametersIndex.CatalogName].AsString := FDefiner;
FRow.Value[TDBXProcedureParametersIndex.ProcedureName].AsString := FProcedureName;
FRow.Value[TDBXProcedureParametersIndex.ParameterName].AsString := FParameter.FName;
FRow.Value[TDBXProcedureParametersIndex.ParameterMode].AsString := FParameter.FMode;
FRow.Value[TDBXProcedureParametersIndex.TypeName].AsString := FParameter.FDataType;
FRow.Value[TDBXProcedureParametersIndex.Precision].AsInt32 := FParameter.FPrecision;
FRow.Value[TDBXProcedureParametersIndex.Scale].AsInt32 := FParameter.FScale;
FRow.Value[TDBXProcedureParametersIndex.Ordinal].AsInt32 := FParameter.FOrdinal;
FRow.Value[TDBXProcedureParametersIndex.IsNullable].AsBoolean := not FParameter.FNotnull;
FRow.Value[TDBXProcedureParametersIndex.IsUnicode].AsBoolean := FParameter.FUnicode;
FRow.Value[TDBXProcedureParametersIndex.IsUnsigned].AsBoolean := FParameter.FUnsigned;
end;
function TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureParametersCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue;
begin
case Ordinal of
TDBXProcedureParametersIndex.CatalogName,
TDBXProcedureParametersIndex.SchemaName,
TDBXProcedureParametersIndex.DbxDataType,
TDBXProcedureParametersIndex.IsFixedLength,
TDBXProcedureParametersIndex.IsLong,
TDBXProcedureParametersIndex.ProcedureName,
TDBXProcedureParametersIndex.ParameterName,
TDBXProcedureParametersIndex.ParameterMode,
TDBXProcedureParametersIndex.TypeName,
TDBXProcedureParametersIndex.Precision,
TDBXProcedureParametersIndex.Scale,
TDBXProcedureParametersIndex.Ordinal,
TDBXProcedureParametersIndex.IsNullable,
TDBXProcedureParametersIndex.IsUnicode,
TDBXProcedureParametersIndex.IsUnsigned:
Exit(FRow.Value[Ordinal]);
end;
Result := inherited GetWritableValue(Ordinal);
end;
procedure TDBXMySqlCustomMetaDataReader.TDBXMySqlProcedureParametersCursor.ComputeParams;
var
SqlCreateProcedure: UnicodeString;
begin
SqlCreateProcedure := FCursor.Value[ShowCreateProcedureSqlOrdinal].AsString;
FDefiner := FReader.ParseProcedureDefiner(SqlCreateProcedure);
FReader.ParseProcedure(SqlCreateProcedure, FProcedureType, FParams);
FParameterIndex := 0;
end;
function TDBXMySqlMetaDataReader.GetProductName: UnicodeString;
begin
Result := 'MySQL';
end;
function TDBXMySqlMetaDataReader.GetSqlIdentifierQuotePrefix: UnicodeString;
begin
Result := '`';
end;
function TDBXMySqlMetaDataReader.GetSqlIdentifierQuoteSuffix: UnicodeString;
begin
Result := '`';
end;
function TDBXMySqlMetaDataReader.GetSqlIdentifierQuoteChar: UnicodeString;
begin
Result := '`';
end;
function TDBXMySqlMetaDataReader.GetTableType: UnicodeString;
begin
Result := 'BASE TABLE';
end;
function TDBXMySqlMetaDataReader.IsDescendingIndexColumnsSupported: Boolean;
begin
Result := False;
end;
function TDBXMySqlMetaDataReader.IsLowerCaseIdentifiersSupported: Boolean;
begin
Result := True;
end;
function TDBXMySqlMetaDataReader.IsUpperCaseIdentifiersSupported: Boolean;
begin
Result := False;
end;
function TDBXMySqlMetaDataReader.IsMultipleCommandsSupported: Boolean;
begin
Result := False;
end;
function TDBXMySqlMetaDataReader.FetchCatalogs: TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateCatalogsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Catalogs, Columns);
end;
function TDBXMySqlMetaDataReader.FetchSchemas(const CatalogName: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateSchemasColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Schemas, Columns);
end;
function TDBXMySqlMetaDataReader.GetSqlForTables: UnicodeString;
var
CurrentVersion: UnicodeString;
begin
CurrentVersion := Version;
if CurrentVersion >= '05.00.0000' then
Result := 'SELECT TABLE_SCHEMA, CAST(NULL AS CHAR(1)), TABLE_NAME, CASE TABLE_TYPE WHEN ''BASE TABLE'' THEN ''TABLE'' ELSE TABLE_TYPE END ' +
'FROM INFORMATION_SCHEMA.TABLES ' +
'WHERE (TABLE_SCHEMA = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (1=1 OR :SCHEMA_NAME IS NULL) AND (TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (TABLE_TYPE IN (:TABLES,:VIEWS,:SYSTEM_VIEWS,:SYSTEM_TABLES)) ' +
'ORDER BY 1,2,3'
else
Result := 'SHOW TABLES';
end;
function TDBXMySqlMetaDataReader.GetSqlForViews: UnicodeString;
var
CurrentVersion: UnicodeString;
begin
CurrentVersion := Version;
if CurrentVersion >= '05.00.0000' then
Result := 'SELECT TABLE_SCHEMA, CAST(NULL AS CHAR(1)), TABLE_NAME, VIEW_DEFINITION ' +
'FROM INFORMATION_SCHEMA.VIEWS ' +
'WHERE (TABLE_SCHEMA = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (1=1 OR :SCHEMA_NAME IS NULL) AND (TABLE_NAME = :VIEW_NAME OR (:VIEW_NAME IS NULL)) ' +
'ORDER BY 1,2,3'
else
Result := 'EmptyTable';
end;
function TDBXMySqlMetaDataReader.GetSqlForColumns: UnicodeString;
var
CurrentVersion: UnicodeString;
begin
CurrentVersion := Version;
if CurrentVersion >= '05.00.0000' then
Result := 'SELECT TABLE_SCHEMA, CAST(NULL AS CHAR(1)), TABLE_NAME, COLUMN_NAME, DATA_TYPE, COALESCE(NUMERIC_PRECISION,CHARACTER_MAXIMUM_LENGTH), NUMERIC_SCALE, ORDINAL_POSITION, CAST(CASE WHEN COLUMN_DEFAULT IS NOT NULL AND COLUMN_DEFAULT <> ''CURRENT_TIMESTAMP'' AND ' + 'DATA_TYPE IN (''char'',''varchar'',''timestamp'',''datetime'',''date'',''time'',''year'') THEN CONCAT("''",COLUMN_DEFAULT,"''") ELSE COLUMN_DEFAULT END AS CHAR(255)), IS_NULLABLE=''YES'', LOCATE(''auto_increment'',EXTRA) > 0, -1, CHARACTER_SET_NAME, (LOCATE(''unsigned'',COLUMN' + '_TYPE) > 0) ' +
'FROM INFORMATION_SCHEMA.COLUMNS ' +
'WHERE (TABLE_SCHEMA = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (1=1 OR :SCHEMA_NAME IS NULL) AND (TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'ORDER BY 1,2,3,ORDINAL_POSITION'
else
Result := 'SHOW COLUMNS FROM :TABLE_NAME';
end;
function TDBXMySqlMetaDataReader.FetchColumnConstraints(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const TableName: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateColumnConstraintsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.ColumnConstraints, Columns);
end;
function TDBXMySqlMetaDataReader.GetSqlForIndexes: UnicodeString;
var
CurrentVersion: UnicodeString;
begin
CurrentVersion := Version;
if CurrentVersion >= '05.00.0000' then
Result := 'SELECT TABLE_SCHEMA, CAST(NULL AS CHAR(1)), TABLE_NAME, INDEX_NAME, CASE WHEN NON_UNIQUE = 0 THEN INDEX_NAME ELSE NULL END, INDEX_NAME=''PRIMARY'', NON_UNIQUE=0, 1=1 ' +
'FROM INFORMATION_SCHEMA.STATISTICS ' +
'WHERE (TABLE_SCHEMA = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (1=1 OR :SCHEMA_NAME IS NULL) AND (TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'GROUP BY 1, 2, 3 ,4 ' +
'ORDER BY 1, 2, 3, 4'
else
Result := 'SHOW INDEX FROM :TABLE_NAME';
end;
function TDBXMySqlMetaDataReader.GetSqlForIndexColumns: UnicodeString;
var
CurrentVersion: UnicodeString;
begin
CurrentVersion := Version;
if CurrentVersion >= '05.00.0000' then
Result := 'SELECT TABLE_SCHEMA, CAST(NULL AS CHAR(1)), TABLE_NAME, INDEX_NAME, COLUMN_NAME, SEQ_IN_INDEX, COLLATION=''A'' ' +
'FROM INFORMATION_SCHEMA.STATISTICS ' +
'WHERE (TABLE_SCHEMA = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (1=1 OR :SCHEMA_NAME IS NULL) AND (TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (INDEX_NAME = :INDEX_NAME OR (:INDEX_NAME IS NULL)) ' +
'ORDER BY 1, 2, 3, 4, SEQ_IN_INDEX'
else
Result := 'SHOW INDEX FROM :TABLE_NAME';
end;
function TDBXMySqlMetaDataReader.GetSqlForForeignKeys: UnicodeString;
var
CurrentVersion: UnicodeString;
begin
CurrentVersion := Version;
if CurrentVersion >= '05.00.0000' then
Result := 'SELECT TABLE_SCHEMA, CAST(NULL AS CHAR(1)), TABLE_NAME, CONSTRAINT_NAME ' +
'FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE ' +
'WHERE POSITION_IN_UNIQUE_CONSTRAINT IS NOT NULL ' +
' AND (TABLE_SCHEMA = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (1=1 OR :SCHEMA_NAME IS NULL) AND (TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'GROUP BY 1,2,3,4 ' +
'ORDER BY 1,2,3,4'
else
Result := 'SHOW CREATE TABLE :TABLE_NAME';
end;
function TDBXMySqlMetaDataReader.GetSqlForForeignKeyColumns: UnicodeString;
var
CurrentVersion: UnicodeString;
begin
CurrentVersion := Version;
if CurrentVersion >= '05.00.0006' then
Result := 'SELECT TABLE_SCHEMA, CAST(NULL AS CHAR(1)), TABLE_NAME, CONSTRAINT_NAME, COLUMN_NAME, REFERENCED_TABLE_SCHEMA, CAST(NULL AS CHAR(1)), REFERENCED_TABLE_NAME, ''PRIMARY'', REFERENCED_COLUMN_NAME, ORDINAL_POSITION ' +
'FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE ' +
'WHERE POSITION_IN_UNIQUE_CONSTRAINT IS NOT NULL ' +
' AND (TABLE_SCHEMA = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (1=1 OR :SCHEMA_NAME IS NULL) AND (TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
' AND (REFERENCED_TABLE_SCHEMA = :PRIMARY_CATALOG_NAME OR (:PRIMARY_CATALOG_NAME IS NULL)) AND (1=1 OR (:PRIMARY_SCHEMA_NAME IS NULL)) AND (REFERENCED_TABLE_NAME = :PRIMARY_TABLE_NAME OR (:PRIMARY_TABLE_NAME IS NULL)) AND (''PRIMARY'' = :PRIMARY_KEY_NAME OR ' + '(:PRIMARY_KEY_NAME IS NULL)) ' +
'ORDER BY 1,2,3,4,ORDINAL_POSITION'
else
Result := 'SHOW CREATE TABLE :TABLE_NAME';
end;
function TDBXMySqlMetaDataReader.FetchSynonyms(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const SynonymName: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateSynonymsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Synonyms, Columns);
end;
function TDBXMySqlMetaDataReader.GetSqlForProcedures: UnicodeString;
var
CurrentVersion: UnicodeString;
begin
CurrentVersion := Version;
if CurrentVersion >= '05.00.0006' then
Result := 'SELECT ROUTINE_SCHEMA, NULL, ROUTINE_NAME, ROUTINE_TYPE ' +
'FROM INFORMATION_SCHEMA.ROUTINES ' +
'WHERE (ROUTINE_SCHEMA = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (1=1 OR (:SCHEMA_NAME IS NULL)) AND (ROUTINE_NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) AND (ROUTINE_TYPE = :PROCEDURE_TYPE OR (:PROCEDURE_TYPE IS NULL)) ' +
'ORDER BY 1, 2, 3'
else
Result := 'EmptyTable';
end;
function TDBXMySqlMetaDataReader.GetSqlForProcedureSources: UnicodeString;
begin
Result := 'SHOW CREATE :PROCEDURE_TYPE :PROCEDURE_NAME';
end;
function TDBXMySqlMetaDataReader.GetSqlForProcedureParameters: UnicodeString;
begin
Result := 'SHOW CREATE :PROCEDURE_TYPE :PROCEDURE_NAME';
end;
function TDBXMySqlMetaDataReader.FetchPackages(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackagesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Packages, Columns);
end;
function TDBXMySqlMetaDataReader.FetchPackageProcedures(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString; const ProcedureName: UnicodeString; const ProcedureType: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageProceduresColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedures, Columns);
end;
function TDBXMySqlMetaDataReader.FetchPackageProcedureParameters(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString; const ProcedureName: UnicodeString; const ParameterName: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageProcedureParametersColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedureParameters, Columns);
end;
function TDBXMySqlMetaDataReader.FetchPackageSources(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageSourcesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageSources, Columns);
end;
function TDBXMySqlMetaDataReader.GetSqlForUsers: UnicodeString;
var
CurrentVersion: UnicodeString;
begin
CurrentVersion := Version;
if CurrentVersion >= '05.00.0000' then
Result := 'SELECT USER FROM MYSQL.USER'
else
Result := 'EmptyTable';
end;
function TDBXMySqlMetaDataReader.FetchRoles: TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateRolesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Roles, Columns);
end;
function TDBXMySqlMetaDataReader.GetReservedWords: TDBXStringArray;
var
Words: TDBXStringArray;
begin
SetLength(Words,225);
Words[0] := 'ADD';
Words[1] := 'ALL';
Words[2] := 'ALTER';
Words[3] := 'ANALYZE';
Words[4] := 'AND';
Words[5] := 'AS';
Words[6] := 'ASC';
Words[7] := 'ASENSITIVE';
Words[8] := 'BEFORE';
Words[9] := 'BETWEEN';
Words[10] := 'BIGINT';
Words[11] := 'BINARY';
Words[12] := 'BLOB';
Words[13] := 'BOTH';
Words[14] := 'BY';
Words[15] := 'CALL';
Words[16] := 'CASCADE';
Words[17] := 'CASE';
Words[18] := 'CHANGE';
Words[19] := 'CHAR';
Words[20] := 'CHARACTER';
Words[21] := 'CHECK';
Words[22] := 'COLLATE';
Words[23] := 'COLUMN';
Words[24] := 'CONDITION';
Words[25] := 'CONNECTION';
Words[26] := 'CONSTRAINT';
Words[27] := 'CONTINUE';
Words[28] := 'CONVERT';
Words[29] := 'CREATE';
Words[30] := 'CROSS';
Words[31] := 'CURRENT_DATE';
Words[32] := 'CURRENT_TIME';
Words[33] := 'CURRENT_TIMESTAMP';
Words[34] := 'CURRENT_USER';
Words[35] := 'CURSOR';
Words[36] := 'DATABASE';
Words[37] := 'DATABASES';
Words[38] := 'DAY_HOUR';
Words[39] := 'DAY_MICROSECOND';
Words[40] := 'DAY_MINUTE';
Words[41] := 'DAY_SECOND';
Words[42] := 'DEC';
Words[43] := 'DECIMAL';
Words[44] := 'DECLARE';
Words[45] := 'DEFAULT';
Words[46] := 'DELAYED';
Words[47] := 'DELETE';
Words[48] := 'DESC';
Words[49] := 'DESCRIBE';
Words[50] := 'DETERMINISTIC';
Words[51] := 'DISTINCT';
Words[52] := 'DISTINCTROW';
Words[53] := 'DIV';
Words[54] := 'DOUBLE';
Words[55] := 'DROP';
Words[56] := 'DUAL';
Words[57] := 'EACH';
Words[58] := 'ELSE';
Words[59] := 'ELSEIF';
Words[60] := 'ENCLOSED';
Words[61] := 'ESCAPED';
Words[62] := 'EXISTS';
Words[63] := 'EXIT';
Words[64] := 'EXPLAIN';
Words[65] := 'FALSE';
Words[66] := 'FETCH';
Words[67] := 'FLOAT';
Words[68] := 'FLOAT4';
Words[69] := 'FLOAT8';
Words[70] := 'FOR';
Words[71] := 'FORCE';
Words[72] := 'FOREIGN';
Words[73] := 'FROM';
Words[74] := 'FULLTEXT';
Words[75] := 'GOTO';
Words[76] := 'GRANT';
Words[77] := 'GROUP';
Words[78] := 'HAVING';
Words[79] := 'HIGH_PRIORITY';
Words[80] := 'HOUR_MICROSECOND';
Words[81] := 'HOUR_MINUTE';
Words[82] := 'HOUR_SECOND';
Words[83] := 'IF';
Words[84] := 'IGNORE';
Words[85] := 'IN';
Words[86] := 'INDEX';
Words[87] := 'INFILE';
Words[88] := 'INNER';
Words[89] := 'INOUT';
Words[90] := 'INSENSITIVE';
Words[91] := 'INSERT';
Words[92] := 'INT';
Words[93] := 'INT1';
Words[94] := 'INT2';
Words[95] := 'INT3';
Words[96] := 'INT4';
Words[97] := 'INT8';
Words[98] := 'INTEGER';
Words[99] := 'INTERVAL';
Words[100] := 'INTO';
Words[101] := 'IS';
Words[102] := 'ITERATE';
Words[103] := 'JOIN';
Words[104] := 'KEY';
Words[105] := 'KEYS';
Words[106] := 'KILL';
Words[107] := 'LABEL';
Words[108] := 'LEADING';
Words[109] := 'LEAVE';
Words[110] := 'LEFT';
Words[111] := 'LIKE';
Words[112] := 'LIMIT';
Words[113] := 'LINES';
Words[114] := 'LOAD';
Words[115] := 'LOCALTIME';
Words[116] := 'LOCALTIMESTAMP';
Words[117] := 'LOCK';
Words[118] := 'LONG';
Words[119] := 'LONGBLOB';
Words[120] := 'LONGTEXT';
Words[121] := 'LOOP';
Words[122] := 'LOW_PRIORITY';
Words[123] := 'MATCH';
Words[124] := 'MEDIUMBLOB';
Words[125] := 'MEDIUMINT';
Words[126] := 'MEDIUMTEXT';
Words[127] := 'MIDDLEINT';
Words[128] := 'MINUTE_MICROSECOND';
Words[129] := 'MINUTE_SECOND';
Words[130] := 'MOD';
Words[131] := 'MODIFIES';
Words[132] := 'NATURAL';
Words[133] := 'NO_WRITE_TO_BINLOG';
Words[134] := 'NOT';
Words[135] := 'NULL';
Words[136] := 'NUMERIC';
Words[137] := 'ON';
Words[138] := 'OPTIMIZE';
Words[139] := 'OPTION';
Words[140] := 'OPTIONALLY';
Words[141] := 'OR';
Words[142] := 'ORDER';
Words[143] := 'OUT';
Words[144] := 'OUTER';
Words[145] := 'OUTFILE';
Words[146] := 'PRECISION';
Words[147] := 'PRIMARY';
Words[148] := 'PROCEDURE';
Words[149] := 'PURGE';
Words[150] := 'RAID0';
Words[151] := 'READ';
Words[152] := 'READS';
Words[153] := 'REAL';
Words[154] := 'REFERENCES';
Words[155] := 'REGEXP';
Words[156] := 'RELEASE';
Words[157] := 'RENAME';
Words[158] := 'REPEAT';
Words[159] := 'REPLACE';
Words[160] := 'REQUIRE';
Words[161] := 'RESTRICT';
Words[162] := 'RETURN';
Words[163] := 'REVOKE';
Words[164] := 'RIGHT';
Words[165] := 'RLIKE';
Words[166] := 'SCHEMA';
Words[167] := 'SCHEMAS';
Words[168] := 'SECOND_MICROSECOND';
Words[169] := 'SELECT';
Words[170] := 'SENSITIVE';
Words[171] := 'SEPARATOR';
Words[172] := 'SET';
Words[173] := 'SHOW';
Words[174] := 'SMALLINT';
Words[175] := 'SONAME';
Words[176] := 'SPATIAL';
Words[177] := 'SPECIFIC';
Words[178] := 'SQL';
Words[179] := 'SQL_BIG_RESULT';
Words[180] := 'SQL_CALC_FOUND_ROWS';
Words[181] := 'SQL_SMALL_RESULT';
Words[182] := 'SQLEXCEPTION';
Words[183] := 'SQLSTATE';
Words[184] := 'SQLWARNING';
Words[185] := 'SSL';
Words[186] := 'STARTING';
Words[187] := 'STRAIGHT_JOIN';
Words[188] := 'TABLE';
Words[189] := 'TERMINATED';
Words[190] := 'THEN';
Words[191] := 'TINYBLOB';
Words[192] := 'TINYINT';
Words[193] := 'TINYTEXT';
Words[194] := 'TO';
Words[195] := 'TRAILING';
Words[196] := 'TRIGGER';
Words[197] := 'TRUE';
Words[198] := 'UNDO';
Words[199] := 'UNION';
Words[200] := 'UNIQUE';
Words[201] := 'UNLOCK';
Words[202] := 'UNSIGNED';
Words[203] := 'UPDATE';
Words[204] := 'UPGRADE';
Words[205] := 'USAGE';
Words[206] := 'USE';
Words[207] := 'USING';
Words[208] := 'UTC_DATE';
Words[209] := 'UTC_TIME';
Words[210] := 'UTC_TIMESTAMP';
Words[211] := 'VALUES';
Words[212] := 'VARBINARY';
Words[213] := 'VARCHAR';
Words[214] := 'VARCHARACTER';
Words[215] := 'VARYING';
Words[216] := 'WHEN';
Words[217] := 'WHERE';
Words[218] := 'WHILE';
Words[219] := 'WITH';
Words[220] := 'WRITE';
Words[221] := 'X509';
Words[222] := 'XOR';
Words[223] := 'YEAR_MONTH';
Words[224] := 'ZEROFILL';
Result := Words;
end;
end.
|
unit Form.EditBook;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Form.BaseEditForm, cxGraphics,
cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore,
dxSkinMetropolis, cxClasses, dxSkinsForm, Vcl.StdCtrls, cxButtons,
Vcl.ExtCtrls, cxControls, cxContainer, cxEdit, cxMaskEdit, cxDropDownEdit,
cxTextEdit, cxLabel, Vcl.Buttons, ConnectionModule, Common.Utils,
System.ImageList, Vcl.ImgList, Data.DB, cxDBEdit, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox, DBAccess, Uni, MemDS, dxdbtrel;
type
TfrmEditBook = class(TfrmBaseEditor)
lblBookName: TcxLabel;
lblParentCategory: TcxLabel;
btnAddCategory: TcxButton;
lblFileLink: TcxLabel;
btnFileLink: TcxButton;
edtBookName: TcxDBTextEdit;
edtFileLink: TcxDBTextEdit;
qryCategories: TUniQuery;
dsCategories: TUniDataSource;
cbbCategory: TcxDBLookupComboBox;
edtFullCategory: TcxTextEdit;
procedure btnOKClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnFileLinkClick(Sender: TObject);
procedure btnAddCategoryClick(Sender: TObject);
procedure cbbParentCategoryPropertiesChange(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
function GetFullCategory: string;
public
class function Edit(AMode: TEditMode): Boolean;
end;
var
frmEditBook: TfrmEditBook;
implementation
uses
Form.EditCategory;
{$R *.dfm}
{ TfrmEditBook }
procedure TfrmEditBook.btnAddCategoryClick(Sender: TObject);
//var
// CategoryBookmark, Bookmark: TBookmark;
begin
// if DM.qryCategories.Active then
// CategoryBookmark := DM.qryCategories.GetBookmark;
// if DM.qryBooks.Active then
// Bookmark := DM.qryBooks.GetBookmark;
// qryCategories.Append;
// if TfrmEditCategory.Edit(emAppend) then begin
// qryCategories.Active := False;
// qryCategories.Active := True;
// end;
//qryCategories.GotoBookmark(CategoryBookmark);
// DM.qryBooks.GotoBookmark(Bookmark);
end;
procedure TfrmEditBook.btnCancelClick(Sender: TObject);
begin
DM.qryBooks.Cancel;
inherited;
end;
procedure TfrmEditBook.btnFileLinkClick(Sender: TObject);
begin
with TOpenDialog.Create(nil) do try
Filter := 'Файлы книг|*.pdf;*.djvu;*.epab;*.chm';
if Execute then
edtFileLink.Text := FileName;
finally
Free;
end;
end;
procedure TfrmEditBook.btnOKClick(Sender: TObject);
begin
try
DM.qryBooks.Post;
except on E: Exception do begin
ShowErrorFmt('Не удалось сохранить книгу "%s"'#10#13+'%s', [edtBookName.Text, E.Message]);
DM.qryBooks.Cancel;
ModalResult := mrCancel;
end;
end;
inherited;
end;
procedure TfrmEditBook.cbbParentCategoryPropertiesChange(Sender: TObject);
begin
edtFullCategory.Text := GetFullCategory;
end;
class function TfrmEditBook.Edit(AMode: TEditMode): Boolean;
var
Form: TfrmEditBook;
begin
Form := TfrmEditBook.Create(Application);
try
if AMode = emAppend then
Form.Header := 'Новая книга'
else
Form.Header := Format('Редактирование книги: %s', [DM.qryBooks.FieldValues['BookName']]);
Form.qryCategories.Open;
Result := Form.ShowModal = mrOk;
finally
Form.Free;
end;
end;
procedure TfrmEditBook.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = 13) and (ssCtrl in Shift) then
btnOKClick(nil);
inherited;
end;
function TfrmEditBook.GetFullCategory: string;
const
cSQL =
'with recursive m(path, id) as ( '#13#10 +
' select categoryname path, id from categories where parent_id is null '#13#10 +
' union all '#13#10 +
' select path || '' -> '' || t.categoryname, t.id '#13#10 +
' from categories t, m where t.parent_id = m.id '#13#10 +
') select * from m '#13#10 +
'where id = :id;';
begin
Result := '';
with TUniQuery.Create(nil) do try
Connection := DM.conn;
SQL.Text := cSQL;
ParamByName('ID').AsInteger := cbbCategory.EditValue;
Open;
if not IsEmpty then
Result := FieldValues['Path'];
finally
Free;
end;
end;
end.
|
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Реализация IStockDataSourceConnection для файлов формата MetaTrader 4
History:
-----------------------------------------------------------------------------}
unit FC.StockData.MT.StockDataConnection;
{$I Compiler.inc}
interface
uses SysUtils,Classes,DB, Serialization, FC.Definitions,FC.StockData.StockDataSource, FC.StockData.StockDataConnectionFile;
type
//MT$ File
TStockDataSourceConnection_MTFile = class (TStockDataSourceConnectionFile)
private
FStartLoadingFrom: TDateTime;
public
constructor Create(const aSymbol: string; aInterval: TStockTimeInterval; aConnectionString: string; const aStartLoadingFrom: TDateTime=0);
procedure OnDefineValues; override;
function CreateDataSource(aUseCacheIfPossible: boolean=true): IStockDataSource; override;
end;
implementation
uses FC.StockData.MT.StockDataSource;
{ TStockDataSourceConnection_MTFile }
constructor TStockDataSourceConnection_MTFile.Create(const aSymbol: string; aInterval: TStockTimeInterval; aConnectionString: string; const aStartLoadingFrom: TDateTime=0);
begin
inherited Create(aSymbol,aInterval,aConnectionString);
FStartLoadingFrom:=aStartLoadingFrom;
end;
function TStockDataSourceConnection_MTFile.CreateDataSource(aUseCacheIfPossible: boolean=true): IStockDataSource;
var
aStream: TFileStream;
aDS : TStockDataSource_B;
begin
aStream:=TFileStreamEx.CreateForRead(ConnectionString);
try
aDS:=TStockDataSource_MT.Create(self,Symbol,Interval,aStream,FStartLoadingFrom);
result:=aDS;
finally
aStream.Free;
end;
end;
procedure TStockDataSourceConnection_MTFile.OnDefineValues;
begin
inherited;
end;
initialization
Serialization.TClassFactory.RegisterClass(TStockDataSourceConnection_MTFile);
end.
|
{*******************************************************}
{ Unit Name: Stats.BaseMng }
{ Unit Description: Base management for traces }
{ Copyright: © 1994-2017 SIMCON s.r.o. }
{ ----------------------------------------------------- }
{ Maintainer: Michal Kocifaj / P. Jankovic }
{ Reviewer: Norbert Adamko }
{ Added to version: 6.33 }
{ Last Modification: 09.03.2017 }
{*******************************************************}
unit Stats.BaseMng;
interface
uses System.SysUtils, Generics.Collections, Stats.Constant;
type
ETrace = class(Exception);
TBasicTraceReplication = class;
TBasicReplicationsList = TObjectList<TBasicTraceReplication>;
//******************************************************************************
// Informacie o jednej stope nacitane zo suboru .pcf
// Stopa sa sklada z replikacii
//******************************************************************************
TBasicTrace = class
strict protected
FBasicTraceReplications: TObjectList<TBasicTraceReplication>;
{ Data o jednotlivych replikaciach }
FSelected: Boolean; { Ci je stopa vybrata uzivatelom }
FStoredData: Boolean; { Informacia o tom, ci su data z konfiguracie
v samostatnom adresari pri stope }
FCreated: TDateTime; { Cas kedy bola replikacia spustena }
FStart: TDateTime; { Cas zaciatku simulacie - sim. cas }
FSupposedStop: TDateTime; { Cas kedy ma koncit simulacie - sim. cas }
FReplicationsCount: Integer; { Pocet replikacii }
FRandSeed: Integer; { Hlavna nasada pre zaciatok simulovania }
{ Totozna s nasadou prvej replikacie }
FFileName: String; { Cast nazvu vsetkych datovych suborov - napr. Trace0, Trace1...}
FFolderName: String; { Meno adresara so stopami}
FTraceID: Integer;
FModelID: Integer;
FFormatOfSimProtocols: TSimProtocolsFormats;
procedure SetSelected(paSelected: Boolean);
function GetName: String; virtual;
public
constructor Create; virtual;
destructor Destroy; override;
procedure SelectAllReplications;
procedure DeselectAllReplications;
property Name: String read GetName;
property BasicTraceReplications: TObjectList<TBasicTraceReplication> read FBasicTraceReplications;
property Selected: Boolean read FSelected write SetSelected;
property StoredData: boolean read fStoredData;
property Created: TDateTime read FCreated;
property Start: TDateTime read FStart;
property SupposedStop: TDateTime read FSupposedStop;
property ReplicationCount: Integer read FReplicationsCount;
property RandSeed: Integer read FRandSeed;
property FileName: String read FFileName;
property FolderName: string read FFolderName;
property TraceID: Integer read FTraceID;
property ModelID: Integer read FModelID;
property FormatOfSimProtocols: TSimProtocolsFormats read FFormatOfSimProtocols;
end;
//******************************************************************************
// Informacie o jedinej replikacii
//******************************************************************************
TBasicTraceReplication = class
strict protected
FInterrupted: Boolean; { Ci bola replikacia prerusena }
FRandSeed: Integer; { Nasada pre tuto replikaciu }
FRealStop: TDateTime; { Cas ukoncenia repikacie }
FBasicTraceInformation: TBasicTrace; // materska stopa, ktorej patri
FFolderName: String; { Nazov adresara so stopou }
FReplicationNumber: Integer; { Poradove cislo replikacie 1, 2... }
FLoaded: Boolean; { Ci uz boli nacitane vseobecne data (elementy )
so stopy }
FSelected: Boolean; { Ci je vybrata pre zobrazenie statistik }
function GetFileName(): String;
strict protected
function GetTraceMinTime: TDateTime; virtual;
function GetTraceMaxTime: TDateTime; virtual;
function GetName: String;
public
constructor Create(const paBasicTraceInformation: TBasicTrace;
const paNumberOfReplication: Integer; paInterrupted: Boolean; paRandSeed: Integer;
paRealStop: TDateTime); virtual;
function LoadData(): boolean; virtual; abstract;
property Interrupted: Boolean read FInterrupted;
property RandSeed: Integer read FRandSeed;
property RealStop: TDateTime read FRealStop;
property Name: String read GetName;
property BasicTraceInformation: TBasicTrace read FBasicTraceInformation;
property FolderName: String read FFolderName;
property TraceFile: String read GetFileName; // vrati nazov suboru bez predpony s cislom replikacie a priponou. Napr. Trace_1.stf
property ReplicationNumber: Integer read FReplicationNumber;
property Loaded: Boolean read FLoaded;
property Selected: Boolean read FSelected write FSelected;
property TraceMinTime: TDateTime read GetTraceMinTime;
property TraceMaxTime: TDateTime read GetTraceMaxTime;
end;
implementation
uses Constant;
{ TBasicTraceInformation }
constructor TBasicTrace.Create;
begin
inherited Create;
FBasicTraceReplications := TObjectList<TBasicTraceReplication>.Create;
FFileName := pxTrace;
FFolderName := '';
FCreated := -1;
FStart := -1;
FSupposedStop := -1;
FReplicationsCount := 0;
FRandSeed := 0;
FStoredData := False;
FSelected := False;
end;
destructor TBasicTrace.Destroy;
begin
inherited;
FreeAndNil(FBasicTraceReplications);
end;
function TBasicTrace.GetName: String;
begin
Result := '';
end;
procedure TBasicTrace.SelectAllReplications;
var i: Integer;
begin
for i := 0 to FBasicTraceReplications.Count - 1 do
FBasicTraceReplications[i].Selected := True;
end;
procedure TBasicTrace.SetSelected(paSelected: Boolean);
begin
FSelected := paSelected;
if (FSelected) then
SelectAllReplications()
else
DeselectAllReplications();
end;
procedure TBasicTrace.DeselectAllReplications;
var i: Integer;
begin
for i := 0 to FBasicTraceReplications.Count - 1 do
FBasicTraceReplications[i].Selected := False;
end;
{ TBasicTraceReplication }
constructor TBasicTraceReplication.Create(
const paBasicTraceInformation: TBasicTrace;
const paNumberOfReplication: Integer;
paInterrupted: Boolean; paRandSeed: Integer; paRealStop: TDateTime);
begin
inherited Create;
FInterrupted := paInterrupted;
FRandSeed := paRandSeed;
FRealStop := paRealStop;
FBasicTraceInformation := paBasicTraceInformation;
FFolderName := paBasicTraceInformation.FolderName;
FReplicationNumber := paNumberOfReplication;
FLoaded := False;
FSelected := False;
end;
function TBasicTraceReplication.GetName: String;
begin
Result := BasicTraceInformation.Name + ' [replication ' + IntToStr(FReplicationNumber) + ']';
end;
function TBasicTraceReplication.GetFileName(): String;
begin
Result := FBasicTraceInformation.FileName + '_' + IntToStr(FReplicationNumber) + exStreamTraceFile;
end;
function TBasicTraceReplication.GetTraceMaxTime: TDateTime;
begin
Result := FRealStop;
end;
function TBasicTraceReplication.GetTraceMinTime: TDateTime;
begin
Result := FBasicTraceInformation.Start;
end;
end.
|
UNIT DT_Pokedex;
INTERFACE
USES
Utilidades, BaseDeDatos, DT_Especie, DT_TipoElemental, SysUtils;
TYPE
DatosPokedex= RECORD
especies: ListaEspecies;
tiposElementales: ListaTiposElementales;
indiceDeSeleccion: INTEGER;
end;
(*Carga desde la base de datos las listas de especies y tipos elementales. Se
establece además el índice de selección (selector) en 1*)
PROCEDURE IniciarPokedex(VAR p: DatosPokedex);
(*Devuelve la especie marcada por el selector.*)
FUNCTION EspecieSeleccionada(p: DatosPokedex): Especie;
(*Mueve el selector a la siguiente especie en la lista. Si ya está seleccionada
la última especie entonces no se hace nada.*)
PROCEDURE SiguienteEspecie(VAR p: DatosPokedex);
(*Mueve el selector a la especie anterior en la lista. Si ya está seleccionada
la primera especie entonces no se hace nada.*)
PROCEDURE AnteriorEspecie(VAR p: DatosPokedex);
(*Retorna la lista de especies.*)
FUNCTION ListaDeEspecies(p: DatosPokedex): ListaEspecies;
(*Retorna el índice de la especie seleccionada en la lista.*)
FUNCTION IndiceEspecieSeleccionada(p: DatosPokedex): INTEGER;
(*Retorna un TipoElemental a partir de su número ID. Si no existe un tipo con
el ID indicado se retorna el tipo NULL.*)
FUNCTION ObtenerTipoElemental(id: INTEGER; p: DatosPokedex): TipoElemental;
(*Busca una especie en la pokedex que tenga un número o un nombre igual al
argumento pasado como parámetro. Si la encuentra retorna su índice, sino la
encuentra retorna -1*)
FUNCTION BuscarEspecie(numeroONombre: String; p: DatosPokedex): INTEGER;
IMPLEMENTATION
(*Carga desde la base de datos las listas de especies y tipos elementales. Se
establece además el índice de selección (selector) en 1*)
PROCEDURE IniciarPokedex(VAR p: DatosPokedex); Begin
p.indiceDeSeleccion:=1;
CargarListaEspecies(p.especies);
CargarListaTiposElementales(p.tiposElementales);
end;
(*Devuelve la especie marcada por el selector.*)
FUNCTION EspecieSeleccionada(p: DatosPokedex): Especie;
Begin
EspecieSeleccionada := EspecieListaEspecies(p.indiceDeSeleccion, p.especies)
end;
(*Mueve el selector a la siguiente especie en la lista. Si ya está seleccionada
la última especie entonces no se hace nada.*)
PROCEDURE SiguienteEspecie(VAR p: DatosPokedex);
BEGIN
if EsIndiceValidoListaEspecies(p.indiceDeSeleccion + 1, p.especies)
then p.indiceDeSeleccion := p.indiceDeSeleccion + 1;
end;
(*Mueve el selector a la especie anterior en la lista. Si ya está seleccionada
la primera especie entonces no se hace nada.*)
PROCEDURE AnteriorEspecie(VAR p: DatosPokedex); BEGIN
if p.indiceDeSeleccion > 1
then p.indiceDeSeleccion := p.indiceDeSeleccion - 1;
end;
(*Retorna la lista de especies.*)
FUNCTION ListaDeEspecies(p: DatosPokedex): ListaEspecies;
BEGIN
ListaDeEspecies:= p.especies;
end;
(*Retorna el índice de la especie seleccionada en la lista.*)
FUNCTION IndiceEspecieSeleccionada(p: DatosPokedex): INTEGER; BEGIN
IndiceEspecieSeleccionada := p.indiceDeSeleccion;
(* IndiceEspecieSeleccionada := IdEspecie(especieListaEspecies(p.indiceDeSeleccion,
p.especies)); *)
end;
(*Retorna un TipoElemental a partir de su número ID. Si no existe un tipo con
el ID indicado se retorna el tipo NULL.*)
FUNCTION ObtenerTipoElemental(id: INTEGER; p: DatosPokedex): TipoElemental;
//VAR i: INTEGER; t: TipoElemental;
BEGIN
(* Comentario: 'NULL' tiene indice 19 definido en el sistema, lo devuelvo
Quizas podria ir el de los interrogantes, porque ya se usa el NULL en tipo secundario inexistente *)
if(NOT EsIndiceValidoListaTiposElementales(id,p.tiposElementales)) then
id := 19;
ObtenerTipoElemental := TipoListaTiposElementales(id,p.tiposElementales);
(*
i := 0;
if not esIndiceValidoListaTiposElementales(id, p.tiposElementales)then
begin
repeat
i := i + 1;
t := TipoListaTiposElementales(i, p.tiposElementales);
until upperCase(nombreTipoElemental(t)) = 'NULL';
ObtenerTipoElemental := t;
end
else
begin
repeat
i := i + 1;
t := TipoListaTiposElementales(i, p.tiposElementales);
until id = idTipoElemental(t);
ObtenerTipoElemental := t;
end; *)
end;
(*Busca una especie en la pokedex que tenga un número o un nombre igual al
argumento pasado como parámetro. Si la encuentra retorna su índice, sino la
encuentra retorna 0*)
FUNCTION BuscarEspecie(numeroONombre: String; p: DatosPokedex): INTEGER;
var i, indice: INTEGER;
numONom, compNum, compNom: STRING;
Begin
numONom := lowerCase(numeroONombre);
i := 1;
indice := 0;
while (indice = 0) and esIndiceValidoListaEspecies(i, p.especies) do
begin
compNum := lowerCase(nombreEspecie(especieListaEspecies(i, p.especies)));
compNom := lowerCase(numeroEspecie(especieListaEspecies(i, p.especies)));
if (numONom = compNum) or (numONom = compNom)
then indice := (idEspecie(especieListaEspecies(i, p.especies)));
i := i + 1;
end;
BuscarEspecie := indice;
end;
END.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, CRCunit, FileCtrl, ComCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Edit1: TEdit;
ProgressBar1: TProgressBar;
procedure UpdateList(StartDir: string; List: TStringList);
procedure Button1Click(Sender: TObject);
function CountFiles(ADirectory: String): Integer;
private
{ Private declarations }
public
end;
var
Form1: TForm1;
List: TStringList;
Dir: String;
implementation
{$R *.dfm}
function TForm1.CountFiles(ADirectory: String): Integer;
var
Rec: TSearchRec;
sts: Integer;
begin
Result := 0;
sts := FindFirst(ADirectory + '\*.*', faAnyFile, Rec);
if sts = 0 then
begin
repeat
if ((Rec.Attr and faDirectory) <> faDirectory) then
Inc(Result)
else if (Rec.Name <> '.') and (Rec.Name <> '..') then
Result := Result + CountFiles(ADirectory + '\' + Rec.Name);
until FindNext(Rec) <> 0;
SysUtils.FindClose(Rec);
end;
end;
procedure TForm1.UpdateList(StartDir: string; List: TStringList);
var
SearchRec: TSearchRec;
Fold: String;
begin
if StartDir[Length(StartDir)] <> '\' then
StartDir := StartDir + '\';
if FindFirst(StartDir + '*.*', faAnyFile, SearchRec) = 0 then
begin
repeat
Application.ProcessMessages;
if (SearchRec.Attr and faDirectory) <> faDirectory then
begin
Fold := StringReplace(StartDir, Dir, '', [rfReplaceAll, rfIgnoreCase]);
List.Add(Fold + SearchRec.Name + '=' +
IntToHex(GetFileCRC(StartDir + SearchRec.Name), 8));
ProgressBar1.Position := ProgressBar1.Position + 1;
end
else if (SearchRec.Name <> '..') and (SearchRec.Name <> '.') then
UpdateList(StartDir + SearchRec.Name + '\', List);
until FindNext(SearchRec) <> 0;
FindClose(SearchRec);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
Var
Folder: String;
begin
Memo1.Clear;
SelectDirectory('Выберите папку :', '', Folder, [sdNewFolder, sdNewUI]);
if Folder <> '' then
begin
Edit1.Text := Folder;
ProgressBar1.Max := CountFiles(Folder);
List := TStringList.Create;
Dir := Folder;
UpdateList(Dir, List);
List.SaveToFile('C:\UpdateList.dwn');
Memo1.Lines.LoadFromFile('C:\UpdateList.dwn');
Form1.Caption := 'Файл сохранен : "C:\UpdateList.dwn" ' +
IntToStr(List.Count)+' Файлов';
List.Free;
WinExec('EXPLORER /e, ' + '"c:\"', SW_SHOW);
ProgressBar1.Position := 0;
end;
end;
end.
|
unit uDisplayUtils;
interface
uses math, sysutils;
function showTime(t:TDatetime):string;
function showBytes(b:int64):string;
function showVel(v:double):string;
function SizeToStr(b:Int64):string;
implementation
function showTime(t:TDatetime):string;
var
AHour, AMinute, ASecond, AMilliSecond: Word;
begin
result := '';
DecodeTime( t, AHour, AMinute, ASecond, AMilliSecond);
if trunc(t)>1 then
result := result + ' ' + inttostr(trunc(t)) + ' dias'
else
if trunc(t)>0 then
result := result + ' ' + inttostr(trunc(t)) + ' dia';
if AHour>1 then
result := result + ' ' + inttostr(AHour) + ' horas'
else
if AHour>0 then
result := result + ' ' + inttostr(AHour) + ' hora';
if AMinute>1 then
result := result + ' ' + inttostr(AMinute) + ' minutos'
else
if AMinute>0 then
result := result + ' ' + inttostr(AMinute) + ' minuto';
if ASecond>1 then
result := result + ' ' + inttostr(ASecond) + ' segundos'
else
if ASecond>0 then
result := result + ' ' + inttostr(ASecond) + ' segundo';
end;
function showBytes(b:int64):string;
begin
if b> power(2,30) then
result := formatfloat('########.00', b / power(2,30)) + ' GB'
else
if b> power(2,20) then
result := formatfloat('########.00', b / power(2,20)) + ' MB'
else
if b> power(2,10) then
result := formatfloat('########.00', b / power(2,10)) + ' KB'
else
result := inttostr( b ) + ' B'
end;
function showVel(v:double):string;
begin
if v> power(2,30) then
result := formatfloat('########.00', v / power(2,30)) + ' GB/s.'
else
if v> power(2,20) then
result := formatfloat('########.00', v / power(2,20)) + ' MB/s.'
else
if v> power(2,10) then
result := formatfloat('########.00', v / power(2,10)) + ' KB/s.'
else
result := inttostr( trunc(v) ) + ' B/s.'
end;
function SizeToStr(b:Int64):string;
begin
if b<1024 then
result := inttostr(b) + ' B'
else if b<( power( 1024, 2)) then
result := FormatFloat('0.00', b / 1024) + ' KB'
else if b<( power( 1024, 3)) then
result := FormatFloat('0.00', b / power( 1024, 2)) + ' MB'
else if b<( power( 1024, 4)) then
result := FormatFloat('0.00', b / power( 1024, 3)) + ' GB'
else if b<( power( 1024, 5)) then
result := FormatFloat('0.00', b / power( 1024, 4)) + ' TB'
else if b<( power( 1024, 6)) then
result := FormatFloat('0.00', b / power( 1024, 4)) + ' EB';
end;
end.
|
/ *****************************************************************
// ** COMPANY NAME: HPA Systems
// *****************************************************************
// ** Application......:
// **
// ** Module Name......: RichFunctions1.pas
// ** Program Name.....:
// ** Program Description: Library of Procedures/Functions for various things.
// **
// **
// **
// **
// **
// **
// **
// ** Documentation....:
// ** Called By........:
// ** Sequence.........:
// ** Programs Called..:
// **
// ** Create Options...:
// ** Object Owner.....:
// ** CREATED By.......: RICHARD KNECHTEL
// ** Creation Date....: 02/07/2002
// **
// **
// *****************************************************************
// *
// * INPUT FILES:
// *
// * UPDATE FILES:
// *
// *****************************************************************
// *
// * PARAMETERS
// * ------------------------------------------------------------
// *
// * PARAMETERS PASSED TO THIS PROGRAM:
// *
// * NAME DESCRIPTION
// * ---------- -----------------------------------------------
// * NONE
// *
// *****************************************************************
// *
// * PROGRAMS CALLED
// * ------------------------------------------------------------
// * NO PROGRAMS CALLED
// *
// *****************************************************************
// *****************************************************************
// * License
// *****************************************************************
// *
// * This program is free software; you can redistribute it and/or modify
// * it under the terms of the GNU General Public License as published by
// * the Free Software Foundation; either version 2 of the License, or
// * (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
// *
// *****************************************************************
// * MODIFICATION LOG: *
// *===============================================================*
// *##|WHO |WHEN |WHAT & (CSR#) *
// *===============================================================*
// * | | | *
// * | | | *
// *---------------------------------------------------------------*
// *****************************************************************
// *****************************************************************
// **
// **
Unit RichFunctions;
Interface
//******************************************************************************
//** Functions/Procedures Prototypes
//******************************************************************************
Procedure GetFunctionNamesFromDLL(DLLName: string; List: TStrings);
Procedure CopyDos (FileIn, FileOut: PChar);
Function CvtUrlHex(strURL: String): String;
Function UnHex(strURL: String): Integer;
Function HexToDec(HexNumber: String): Integer;
Function DecToHex(DecNumber: Integer): String;
Function CelToFar(Cel: String): String;
Function FarToCel(Far: String): String;
Function BinToDec(BinNumber: String): Integer;
Function DecToBin(DecNumber: Integer): String;
Function AsciiToDec(Str: String): String;
Procedure DelTree(const RootDir : String);
Function FileThere (strFile: String): Boolean;
Procedure ClickStart;
Function IsEven (intEven: integer) : Boolean;
Function IsPos (intPos: integer) : Boolean;
Function InStr(nStart: Integer; const sData, sFind: string): Integer;
Function Mid(const sData: string; nStart: Integer; nLength: Integer): string; overload;
Function StrLeft(const sData: string; nLength: integer): string;
Function StrRight(const sData: string; nLength: integer): string;
Function LCase(const sData: string; nLength: Integer): String;
Function UCase(const sData: string; nLength: Integer): String;
Function GetCurSysDate(VAR intMonth: integer; VAR intDay: integer; VAR intYear: integer): string;
Function GoAgain(): Boolean;
Procedure MsgBox1(pc_Messg: PChar);
Function MsgBox2(pc_Messg: PChar): Int64;
Procedure GoAway;
Procedure WriteInstructions;
Function IsAlpha(chrChar: Char): Boolean;
Function ITOST(i_Num: Integer): String;
Function STOI( cNum: STRING ): LONGINT;
Function RTOI( RealNum: REAL ): LONGINT;
//******************************************************************************
//** Var goes above here
Implementation
//** User Defined Functions ****************************************************
//******************************************************************************
//** GetFunctionNamesFromDLL -
//** This code enables you to view all procedures and
//** functions what DLL,DAT,EXE,DRV file has.
//** It displays them to your screen
//** and later you can use this file with Delphi.
//** Parms = DLL Name, List
//** Returns = All procedures and functions what DLL,EXE,DAT,DRV file has.
//**
//** Function by: Priit Serk
//**
//******************************************************************************
Procedure GetFunctionNamesFromDLL(DLLName: string; List: TStrings);
Type chararr = array[0..$FFFFFF] of char;
Var
h: THandle;
i, fc: integer;
st: string;
arr: pointer;
ImageDebugInformation: PImageDebugInformation;
Begin
List.Clear;
DLLName := ExpandFileName(DLLName);
If Not FileExists(DLLName) Then Exit;
h := CreateFile(PChar(DLLName), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
If h = -1 Then Exit;
ImageDebugInformation := MapDebugInformation(h, PChar(DLLName), nil, 0);
If ImageDebugInformation = nil Then Exit;
arr := ImageDebugInformation^.ExportedNames;
fc := 0;
For i := 0 To ImageDebugInformation^.ExportedNamesSize - 1 Do
Begin
If chararr(arr^)[i] = #0 Then
Begin
st := PChar(@chararr(arr^)[fc]);
If length(st) > 0 Then List.Add(st);
If (i > 0) And (chararr(arr^)[i - 1] = #0) Then Break;
fc := i + 1; end;
End;
UnmapDebugInformation(ImageDebugInformation);
CloseHandle(h);
End;
End;
//******************************************************************************
//******************************************************************************
//** CopyDos - Like DOS Copy Command
//** (COMSPEC is necessary in case you are running DR DOS.)
//******************************************************************************
Procedure CopyDos (FileIn, FileOut: PChar);
Var
CommandLine: array[0..$FF] of Char;
Begin
StrCopy (CommandLine, GetEnvVar ('COMSPEC'));
StrCat (CommandLine, ' /c copy ');
StrCat (CommandLine, FileIn);
StrCat (CommandLine, ' ');
StrCat (CommandLine, FileOut);
WinExec (CommandLine, sw_Hide);
End;
//******************************************************************************
//******************************************************************************
//** CvtUrlHex - Takes all the Hex(%FF) code in a url and converts them
//** to it's character value.
//** Parm = String
//** Return = Decimal Number
//** Usage:
//** CvtUrlHex('http://hotbot.lycos.com/?MT=%26%5E%5E%25%25%24%27&SQ=1&TR=7111&AM1=MC');
//******************************************************************************
//** UnHex - used by CvtUrlHex
Function UnHex(strURL: String): Integer;
Var
b1 : String;
b2 : String;
i : Integer;
Begin
b1 := copy(strURL, 1,1);
b2 := copy(strURL, length(strURL),1);
For i := 0 To 5 do
Begin
If b1 = Chr(65 + i) Then
b1 := inttostr(10 + i)
Else
If b1 = Chr(97 + i) Then
b1 := inttostr(10 + i);
If b2 = Chr(65 + i) Then
Begin
b2 := inttostr(10 + i);
End
Else
If b2 = Chr(97 + i) Then
b2 := inttostr(10 + i);
End; //** Next
UnHex := (16 * strtoint(b1)) + strtoint(b2);
End;
Function CvtUrlHex(strURL: String): String;
Var
k : integer;
s : String;
Begin
k := 1;
While k <= Length(strURL) Do
Begin
If copy(strURL, k, 1) = '%' Then
Begin
s := s + Chr(UnHex(copy(strURL, k + 1, 2)));
k := k + 2
End
Else
Begin
s := s + copy(strURL, k, 1);
k := k + 1;
End;
End;
ConUrlHex := s;
End;
//******************************************************************************
//******************************************************************************
//** HexToDec - Convert a Hexidecimal String to a Deciumal #
//** Deicmal Number (0 ... 255)
//** Hexidecimal String (2 Digits)
//** Parm = Hexidecimal String
//** Return = Decimal Number
//******************************************************************************
Function HexToDec(HexNum: String): Integer;
Var
Strlength : Integer;
dech : Integer;
decl : Integer;
Begin
dech := 0;
//** Calculate length of hex string
Strlength := Length(HexNum);
//** Convert least significant digit
decl := Ord(HexNum[Strlength]) - Ord('0');
//** Digit > 9 subtract offset A...F
If decl > 9 Then
Begin
decl := decl - 7;
End;
//** Digit > 15 subtract offset A...F
If decl > 15 Then
Begin
decl := decl - 32;
End;
//** If second digit exist convert it
If Strlength = 2 Then
Begin
//** Convert most significant digit
dech := Ord(HexNum[1]) - Ord('0');
//** Digit > 9 subtract offset A...F
If dech > 9 Then
Begin
dech := dech - 7;
End;
//** Digit > 15 subtract offset A...F
If dech > 15 Then
Begin
dech := dech - 32;
End;
End;
//** Shift MSD 4 bit left & add to LSD
HexToDec := (dech SHL 4) + decl;
End;
//******************************************************************************
//******************************************************************************
//** DecToHex - Convert a Decimal # to a Hexadecimal String
//** Deicmal Number (0 ... 255)
//** Hexidecimal String (2 Digits)
//** Parm = Decimal Number
//** Return = Hexidecimal String
//******************************************************************************
Function DecToHex(DecNumber: Integer): String;
Type
String2 = String[2];
Var
hex1 : String2;
hex2 : String2;
VarChr : Variant;
Begin
//** MSD = dec. number / 16
hex1 := IntToStr(DecNumber DIV 16);
//** LSD = remainder dec number / 16
hex2 := IntToStr(DecNumber MOD 16);
//** If digit > 9 add offset for A...F
If StrToInt(hex1) > 9 Then
Begin
VarChr := Chr(StrToInt(hex1) + 55);
hex1 := VarChr;
End;
//** If digit > 9 add offset for A...F
If StrToInt(hex2) > 9 Then
Begin
VarChr := Chr(StrToInt(hex2)+ 55);
hex2 := VarChr;
End;
DecToHex := hex1 + hex2; //** Store Result
End;
//******************************************************************************
//******************************************************************************
//** CelToFar - Convert Celcius to Farenheit
//** Parm = Celcius Tempature
//** Return = Farenheit Tempature
//******************************************************************************
Function CelToFar(Cel: String): String;
Var
C : Real; //** Celcius Tempature
F : Real; //** Farenheit Tempature
S : string; //** Temp variable for conversion
Begin
C := StrtoFloat(Cel); //** Convert passed string to a Real Number
F := C*9/5+32; //** do the conversion
S := FloattoStrF(F, ffFixed, 5, 2); //** convert result of conversion to text
CelToFar := S; //** Return Farenheit Tempature
End;
//******************************************************************************
//******************************************************************************
//** FarToCel - Convert Farenheit To Celcius
//** Parm = Farenheit Tempature
//** Return = Celcius Tempature
//******************************************************************************
Function FarToCel(Far: String): String;
Var
C : Real; //** Celcius Tempature
F : Real; //** Farenheit Tempature
S : string; //** Temp variable for conversion
Begin
F := StrtoFloat(Far); //** Convert passed string to a Real Number
C := (F-32)*5/9; //** do the conversion
S := FloattoStrF(C, ffFixed, 5, 2); //** convert result of conversion to text
FarToCel := S; //** Return Celcius Tempature
End;
//******************************************************************************
//******************************************************************************
//** BinToDec - Converts an Binary # To Deciaml #
//** Binary number (Max 64 Bits)
//** Parm = Binary # (As String)
//** Returns = Decimal Number
//******************************************************************************
Function BinToDec(BinNumber: Tbinstring): Integer;
Var
i : Integer;
weight : Integer;
dec : Integer;
Begin
Weight := 1; //** Set weight factor at lowest bit
dec := 0; //** Reset decimal number
//** Convert all bits from bin. string
For i := Length(BinNumber) DownTo 1 Do
Begin
//** If bit=1 then add weigth factor
dec := dec + Ord(BinNumber[i] = '1') * Weight;
//** Multiply weight factor by 2
Weight := Weight SHL 1;
END;
//** Store result
BinToDec := dec;
End;
//******************************************************************************
//******************************************************************************
//** DecToBin - Converts an Decimal # To Binary #
//** Parm = Decimal #
//** Returns = Binary Number (Max 64 Bits) (As String)
//** NOTE: Requires Instr & Mid Functions
//******************************************************************************
Function DecToBin(DecNumber: Integer): Tbinstring;
Type
arBinNum = Array[1..64] of Integer;
Var
i : Integer;
bin : String;
Remain : Integer;
Quot : Integer;
WrkNum : Integer;
BinNum : arBinNum;
iPos : Integer;
Begin
Quot := DecNumber;
For i := 1 To 64 Do
BinNum[i] := 0;
i := 1;
Repeat
Begin
WrkNum := Quot DIV 2;
Remain := Quot MOD 2;
BinNum[i] := Remain;
i := i + 1;
Quot := WrkNum;
End
Until Quot = 0;
//** Store result
For i := 64 DownTo 1 Do
bin := bin + IntToStr(BinNum[i]);
//** Strip Excess Leading Zero's
iPos := Instr(1,bin,'1');
bin := Mid(bin, (iPos), (Length(bin) - (iPos - 1)));
//** Return Result
DecToBin := bin;
End;
//******************************************************************************
//******************************************************************************
//** AsciiToDec - Converts an ASCII To Decimal
//** Parm = ASCII String
//** Returns = Deicmal # (As String)
//******************************************************************************
Function AsciiToDec(Str: String): String;
Var
Temp : String;
J : Integer;
Begin
//** Initializations
Temp :='';
J := 0;
For J := 1 To Length(Str) Do
Begin
Temp := Temp + IntToStr(Ord(Str[J]));
End;
AsciiToDec := Temp;
End ;
//******************************************************************************
//******************************************************************************
//** DelTree - Like DOS Command DelTree
//** Parm = Directory Path
//******************************************************************************
Procedure DelTree(const RootDir : String);
Var
SearchRec : TSearchRec;
Begin
Try
ChDir(RootDir); //** Path to the directory given as parameter
FindFirst('*.*', faAnyFile, SearchRec);
Erc := 0;
While Erc = 0 Do
Begin
//** Ignore higher level markers
If ((SearchRec.Name <> '.' ) And (SearchRec.Name <> '..')) Then
Begin
If (SearchRec.Attr and faDirectory>0) Then
Begin
//** Have found a directory, not a file.
//** Recusively call ouselves to delete its files
DelTree(SearchRec.Name);
End
Else
Begin
//** Found a file.
//** Delete it or whatever you want to do here
End;
End;
Erc := FindNext(SearchRec);
//** Erc is zero if FindNext successful,
//** otherwise Erc = negative DOS error
//** Give someone else a chance to run
Application.ProcessMessages;
End;
finally
//** If we are not at the root of the disk, back up a level
if Length(RootDir) > 3 then
ChDir('..');
//** I guess you would remove directory RootDir here
End;
End;
//******************************************************************************
//******************************************************************************
//** FileThere
//******************************************************************************
Function FileThere (strFile: String): Boolean;
Begin
FileThere := FileExists(strFile);
End;
//******************************************************************************
//******************************************************************************
//** ClickStart - Simulates a click on the Windows start button
//******************************************************************************
Procedure ClickStart;
Begin
SendMessage(Self.Handle, WM_SYSCOMMAND, SC_TASKLIST, 0);
End;
//******************************************************************************
//******************************************************************************
//** Function IsEven - Tests if a given integer is Even
//******************************************************************************
Function IsEven (intEven: integer) : Boolean;
Begin
If intEven MOD 2 = 0 then
IsEven:= True //** Number is Even
Else
IsEven:= False; //** Number is Odd
End;
//******************************************************************************
//** Function IsPos - Tests if a given integer is Positive
//******************************************************************************
Function IsPos (intPos: integer) : Boolean;
Begin
If intPos < 0 Then
IsPos:= False //** Number is Negative
Else
IsPos:= True //** Number is Positive
End;
//******************************************************************************
//** Function Instr - Like the Visual Basic Function
//******************************************************************************
Function InStr(nStart: Integer; const sData, sFind: string): Integer;
Var
sTemp: String;
nFound: Integer;
Begin
sTemp := Copy(sData, nStart, (Length(sData) - (nStart - 1)));
nFound := Pos(sFind, sTemp);
If nFound = 0 then
Begin
Instr:= 0;
End
Else
Begin
Instr:= nFound + nStart - 1;
End
End;
//******************************************************************************
//** Function Mid - Like the Visual Basic Funciton
//******************************************************************************
Function Mid(const sData: string; nStart: Integer; nLength: Integer): string; overload;
Begin
Mid:= Copy(sData, nStart, nLength);
End;
//******************************************************************************
//** Function Left - Like the Visual Basic Funciton
//******************************************************************************
Function StrLeft(const sData: string; nLength: integer): string;
Begin
StrLeft:= Copy(sData, 1, nLength);
End;
//******************************************************************************
//** Function Right - Like the Visual Basic Funciton
//******************************************************************************
Function StrRight(const sData: string; nLength: integer): string;
Begin
StrRight:= Copy(sData, Length(sData) - (nLength - 1), nLength);
End;
//******************************************************************************
//** Function LCase - converts passed string to lower case
//******************************************************************************
Function LCase(const sData: string; nLength: Integer): String;
Var
x: Integer;
Begin
For x:= 1 to nLength Do
Begin
LCase:= LowerCase(sData[x]);
End;
End;
//******************************************************************************
//** Function UCase - converts passed string to upper case
//******************************************************************************
Function UCase(const sData: string; nLength: Integer): String;
Var
x: Integer;
Begin
For x:= 1 to nLength Do
Begin
UCase:= UpperCase(sData[x]);
End;
End;
//******************************************************************************
//** Get Curent Date MM/DD/YYYY
//******************************************************************************
Function GetCurSysDate(VAR intMonth: integer; VAR intDay: integer; VAR intYear: integer): string;
//** Returns date in mm/dd/yy format
//** Also returns MM , DD, YYYY By Reference. (need global variables to hold these in).
//** Call from program with:
//** Get the current system Date
//** strSysDate:= GetCurSysDate(intSysMonth, intSysDay, intSysYear);
Var
strDate: string; //** Holds Current date
intPos: integer; //** Holds 1st position of /
intPos2: integer; //** Holds 2nd position of /
intLen: integer; //** Holds length of Date string
endPos: integer; //** End position for Mid
startPos: integer; //** Start position for Mid
strWork: string; //** Work variable for String to Integer Conversion
Begin
strDate:= DateTimetoStr(Now); //** Get date in mm/dd/yy
strDate:= FormatDateTime('" " mm/dd/yyyy, " " hh:mm AM/PM', strtodatetime(strDate));
strDate:= mid(strDate,2,11);
intLen:= length(strDate);
intPos:= instr(1,strDate,'/');
endPos:= (intPos - 1);
If intPos > 0 Then
Begin
//** Get Month
strWork:= mid(strDate, 1, endPos); //** Get mm
intMonth:= StrtoInt(strWork);
//** Get Day
strWork:= mid(strDate, (endPos + 2), 2);
intDay:= StrtoInt(strWork);
End;
//** Get Year
intPos2:= instr((intPos + 1),strDate,'/');
startPos:= (intPos2 + 1);
If intPos2 > 0 Then
Begin
strWork:= mid(strDate, startPos, (intLen - intPos2));
intYear:= StrtoInt(strWork);
End;
End;
//******************************************************************************
//** Function GoAgain - Does user want to Continue?
//******************************************************************************
Function GoAgain(): Boolean;
//** Call from program with:
//** See if User Wants to Go Again
//** blnGoAgain:= GoAgain();
// If blnGoAgain = True Then
// Begin
// blnExit:= False
// End
// Else
// Begin
// blnExit:= True
// End
//***************************************************************
Var
strYN: String; //** For program exit or not
blnExit2: Boolean; //** Boolean to tell if We should exit a loop
strUpCase: String; //** Used to hold converted Upper case letter
Begin
//** Initializations
blnExit2:= False;
strUpCase:= ' ';
//** See if User Wants to Go Again
Repeat
Begin
Write('Do you wish to Continue? ');
Readln(strYN);
strUpCase:= UpperCase(strYN);
If strUpCase = 'Y' Then //** User wants to continue
Begin
blnExit2:= True;
GoAgain:= blnExit2;
End
Else If strUpCase = 'N' Then //** User wants to exit
Begin
blnExit2:= False;
GoAgain:= blnExit2;
blnExit2:= True; //** Force to exit loop
End
Else If (strUpCase <> 'N') Or (strUpCase <> 'Y') Then
Begin
writeln('Please enter Y or N');
blnExit2:= False;
End
End
Until blnExit2 = True;
End;
//** End of GoAgain ************************************************************
//******************************************************************************
//** MsgBox1 - Display an informational Message Box to User Ok Button
//******************************************************************************
Procedure MsgBox1(pc_Messg: PChar);
Begin
with Application Do
Begin
NormalizeTopMosts;
MessageBox(pc_Messg,'MyApplication',MB_OK);
RestoreTopMosts;
End;
End;
//** End of MsgBox *************************************************************
//******************************************************************************
//** MsgBox2 - Display an informational Message Box to User Ok/Cancel Buttons
//******************************************************************************
Function MsgBox2(pc_Messg: PChar): Int64;
Var
i_RtnCode : Int64;
Begin
with Application Do
Begin
NormalizeTopMosts;
i_RtnCode:= MessageBox(pc_Messg,'MyApplication',MB_OKCANCEL);
RestoreTopMosts;
End;
MsgBox2 := i_RtnCode;
End;
//** End of MsgBox ************************************************************
//******************************************************************************
//** GoAway - This Procedure will End the program (Console Mode)
//******************************************************************************
Procedure GoAway;
Begin
Writeln;
Writeln('Press <ENTER> to Exit');
Readln
End;
//** End of GoAway ************************************************************
//******************************************************************************
//** Write Instructions
//******************************************************************************
Procedure WriteInstructions;
//** Call from program with:
//** Give User instructions if wanted
//** WriteInstructions();
Var
chrInstr: Char; //** Charcter either Y or N to check if user wants instructions
Begin
//** Initializations
chrInstr:= ' ';
Repeat //** Instructions Loop
//** Does user need Instructions?
Write('Do you Need Instructions (Y/N)?');
readln(chrInstr);
If UpperCase(chrInstr) = 'Y' Then
Begin
//** Write out Instructions
writeln;
//******************************************
//** Insert writeln's with user instructions
//** Here
//******************************************
writeln;
Writeln('Press ENTER to continue');
writeln;
readln;
blnExit:= True; //** Set on loop exit trigger
writeln;
End
Else If (UpperCase(chrInstr) = 'N') Then
Begin
blnExit:= True;
writeln;
End
Else If (UpperCase(chrInstr) <> 'N') And (UpperCase(chrInstr) <> 'Y') Then
Begin
Writeln('Please enter either Y or N');
blnExit:= False; //** set off loop exit trigger
End
Until blnExit = True;
End;
//** End of WriteInstructions *****************************
//******************************************************************************
//** Function IsAlpha
//******************************************************************************
Function IsAlpha(chrChar: Char): Boolean;
//** Checks whether a passed character is one of the alpha letters or not
Var
blnAlpha: Boolean; //** Is Alpha switch
blnAlpha:= False; //** Initialize to False (not Alpha)
Begin
Case chrChar Of
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T', 'U','V','W','X','Y','Z': blnAlpha:= True;
End;
If blnAlpha = True Then
Begin
IsAlpha:= True;
End
Else
Begin
IsAlpha:= False;
End
End
//** End of IsAlpha ********************************************************
//******************************************************************************
//** ITOST - Convert an Integer to a String
//******************************************************************************
Function ITOST(i_Num: Integer): String;
Var
v_INum : Variant;
Begin
v_INum := I_Num;
ITOST := v_INum;
End;
//******************************************************************************
//******************************************************************************
//** STOI - Convert STRING to INTEGER
//** PARAMETER: cNum - String to convert to integer format
//** RETURNS: cNum as a numeric integer
//******************************************************************************
Function STOI( cNum: STRING ): LONGINT;
Var
c: INTEGER;
i: LONGINT;
Begin
VAL( cNum, i, c );
STOI := i;
End;
//************END OF STOI*******************************************************
//******************************************************************************
//** RTOI - convert a real to an integer
//** PARAMETER: RealNum - Real type number
//** RETURNS: The integer part of RealNum
//******************************************************************************
Function RTOI( RealNum: REAL ): LONGINT;
Var
s: String;
l: LongInt;
i: Integer;
Begin
STR( RealNum:17:2, s );
s := Left( s, LENGTH(s) - 3 );
VAL( s, l, i );
RTOI := l;
End;
//********END OF RTOI**********************************************************
//*****************************************************************************
End.
//** End of Code **************************************************************
|
{**********************************************}
{ TPenDialog }
{ Copyright (c) 1996-2004 by David Berneda }
{**********************************************}
unit TeePenDlg;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
Qt, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls,
Types,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
TeCanvas, TeeProcs;
type
TPenDialog = class(TForm)
CBVisible: TCheckBox;
SEWidth: TEdit;
LWidth: TLabel;
BOk: TButton;
BCancel: TButton;
UDWidth: TUpDown;
Label1: TLabel;
CBStyle: TComboFlat;
BColor: TButtonColor;
CBEndStyle: TComboFlat;
procedure FormShow(Sender: TObject);
procedure SEWidthChange(Sender: TObject);
procedure CBVisibleClick(Sender: TObject);
procedure BCancelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CBStyleChange(Sender: TObject);
{$IFDEF CLX}
procedure CBStyleDrawItem(Sender: TObject; Index: Integer;
Rect: TRect; State: TOwnerDrawState; var Handled:Boolean);
{$ELSE}
procedure CBStyleDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
{$ENDIF}
procedure BColorClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure CBEndStyleChange(Sender: TObject);
private
{ Private declarations }
BackupPen : TChartPen;
ModifiedPen : Boolean;
Procedure EnablePenStyle;
public
{ Public declarations }
ThePen : TPen;
end;
Function EditChartPen(AOwner:TComponent; ChartPen:TChartPen; HideColor:Boolean=False):Boolean;
{ Show / Hide controls in array }
Procedure ShowControls(Show:Boolean; Const AControls:Array of TControl);
{ Asks the user a question and returns Yes or No }
Function TeeYesNo(Const Message:String; Owner:TControl=nil):Boolean;
{ Same as above, but using predefined "Sure to Delete?" message }
Function TeeYesNoDelete(Const Message:String; Owner:TControl=nil):Boolean;
type
TButtonPen=class(TTeeButton)
protected
procedure DrawSymbol(ACanvas:TTeeCanvas); override;
public
HideColor : Boolean;
procedure Click; override;
procedure LinkPen(APen:TChartPen);
end;
{$IFDEF CLX}
Procedure TeeFixParentedForm(AForm:TForm);
{$ENDIF}
Procedure AddFormTo(AForm:TForm; AParent:TWinControl); overload;
Procedure AddFormTo(AForm:TForm; AParent:TWinControl; ATag:TPersistent); overload;
Procedure AddFormTo(AForm:TForm; AParent:TWinControl; ATag:Integer); overload;
Procedure AddDefaultValueFormats(AItems:TStrings);
Procedure TeeLoadArrowBitmaps(AUp,ADown:TBitmap);
{ Helper listbox items routines }
procedure MoveList(Source,Dest:TCustomListBox);
procedure MoveListAll(Source,Dest:TStrings);
// Adds all cursors and special "crTeeHand" cursor to ACombo.
// Sets combo ItemIndex to ACursor.
procedure TeeFillCursors(ACombo:TComboFlat; ACursor:TCursor);
Function TeeSetCursor(ACursor:TCursor; const S:String):TCursor;
Const TeeFormBorderStyle={$IFDEF CLX}fbsNone{$ELSE}bsNone{$ENDIF};
Function TeeCreateForm(FormClass:TFormClass; AOwner:TComponent):TForm;
Function TeeCursorToIdent(ACursor:Integer; Var AName:String):Boolean;
Function TeeIdentToCursor(Const AName:String; Var ACursor:Integer):Boolean;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses {$IFNDEF CLX}
ExtDlgs,
{$ENDIF}
{$IFDEF CLR}
Variants,
{$ENDIF}
Math, TypInfo, TeeConst;
{$IFDEF CLR}
{$R TeeArrowDown.bmp}
{$R TeeArrowUp.bmp}
{$ENDIF}
Function TeeCreateForm(FormClass:TFormClass; AOwner:TComponent):TForm;
Function TeeGetParentForm(AOwner:TComponent):TComponent;
begin
result:=AOwner;
if Assigned(result) and (result is TControl) then
begin
result:=GetParentForm(TControl(result));
if not Assigned(result) then result:=AOwner;
end;
end;
begin
result:=FormClass.Create(TeeGetParentForm(AOwner));
with result do
begin
Align:=alNone;
{$IFDEF D5}
if Assigned(Owner) then Position:=poOwnerFormCenter
else
{$ENDIF}
Position:=poScreenCenter;
BorderStyle:=TeeBorderStyle;
end;
end;
Function EditChartPen(AOwner:TComponent; ChartPen:TChartPen; HideColor:Boolean=False):Boolean;
Begin
With TeeCreateForm(TPenDialog,AOwner) as TPenDialog do
try
ThePen:=ChartPen;
if HideColor then BColor.Hide;
result:=ShowModal=mrOk;
finally
Free;
end;
end;
procedure TPenDialog.FormShow(Sender: TObject);
begin
BackupPen:=TChartPen.Create(nil);
if Assigned(ThePen) then
begin
BackupPen.Assign(ThePen);
if ThePen is TChartPen then
begin
CBVisible.Checked:=TChartPen(ThePen).Visible;
BackupPen.Visible:=CBVisible.Checked;
if IsWindowsNT then CBStyle.Items.Add(TeeMsg_SmallDotsPen);
if TChartPen(ThePen).SmallDots then
begin
CBStyle.ItemIndex:=CBStyle.Items.Count-1;
UDWidth.Enabled:=False;
SEWidth.Enabled:=False;
end
else
CBStyle.ItemIndex:=Ord(ThePen.Style);
if IsWindowsNT then
begin
CBEndStyle.ItemIndex:=Ord(TChartPen(ThePen).EndStyle);
{$IFDEF CLX}
CBEndStyle.OnSelect:=CBEndStyleChange;
{$ENDIF}
end
else CBEndStyle.Visible:=False;
end
else
begin
CBVisible.Visible:=False;
CBStyle.ItemIndex:=Ord(ThePen.Style);
end;
UDWidth.Position:=ThePen.Width;
EnablePenStyle;
BColor.LinkProperty(ThePen,'Color');
end;
TeeTranslateControl(Self);
ModifiedPen:=False;
end;
Procedure TPenDialog.EnablePenStyle;
begin
{$IFNDEF CLX}
if not IsWindowsNT then CBStyle.Enabled:=ThePen.Width=1;
{$ENDIF}
end;
procedure TPenDialog.SEWidthChange(Sender: TObject);
begin
if Showing then
begin
ThePen.Width:=UDWidth.Position;
EnablePenStyle;
ModifiedPen:=True;
end;
end;
procedure TPenDialog.CBEndStyleChange(Sender: TObject);
begin
TChartPen(ThePen).EndStyle:=TPenEndStyle(CBEndStyle.ItemIndex);
ModifiedPen:=True;
end;
procedure TPenDialog.CBVisibleClick(Sender: TObject);
begin
if Showing then
begin
TChartPen(ThePen).Visible:=CBVisible.Checked;
ModifiedPen:=True;
end;
end;
procedure TPenDialog.BCancelClick(Sender: TObject);
begin
if ModifiedPen then
begin
ThePen.Assign(BackupPen);
if ThePen is TChartPen then
begin
TChartPen(ThePen).Visible:=BackupPen.Visible;
if Assigned(ThePen.OnChange) then ThePen.OnChange(Self);
end;
end;
ModalResult:=mrCancel;
end;
procedure TPenDialog.FormClose(Sender: TObject; var Action: TCloseAction);
begin
BackupPen.Free;
end;
procedure TPenDialog.FormCreate(Sender: TObject);
begin
BorderStyle:=TeeBorderStyle;
end;
procedure TPenDialog.CBStyleChange(Sender: TObject);
var tmp : Boolean;
begin
if (ThePen is TChartPen) and IsWindowsNT and
(CBStyle.ItemIndex=CBStyle.Items.Count-1) then
begin
TChartPen(ThePen).SmallDots:=True;
tmp:=False;
end
else
begin
tmp:=True;
ThePen.Style:=TPenStyle(CBStyle.ItemIndex);
if ThePen is TChartPen then
TChartPen(ThePen).SmallDots:=False;
end;
UDWidth.Enabled:=tmp; { 5.01 }
SEWidth.Enabled:=tmp;
ModifiedPen:=True;
end;
procedure TPenDialog.BColorClick(Sender: TObject);
begin
CBStyle.Repaint;
ModifiedPen:=True;
end;
{$IFDEF CLX}
procedure TPenDialog.CBStyleDrawItem(Sender: TObject; Index: Integer;
Rect: TRect; State: TOwnerDrawState; var Handled:Boolean);
{$ELSE}
procedure TPenDialog.CBStyleDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
{$ENDIF}
var tmp : TColor;
begin
With TControlCanvas(CBStyle.Canvas) do
begin
{$IFDEF CLX}
Brush.Style:=bsSolid;
if (odFocused in State) or (odSelected in State) then
Brush.Color:=clHighLight;
{$ENDIF}
FillRect(Rect);
{$IFNDEF CLX}
if Index<>CBStyle.Items.Count-1 then
{$ENDIF}
Pen.Style:=TPenStyle(Index);
Pen.Color:=ThePen.Color;
if odSelected in State then tmp:=clHighLight
else tmp:=CBStyle.Color;
if Pen.Color=ColorToRGB(tmp) then
if Pen.Color=clWhite then Pen.Color:=clBlack
else Pen.Color:=clWhite;
{$IFNDEF CLX}
if IsWindowsNT and (Index=CBStyle.Items.Count-1) then { 5.01 }
Pen.Handle:=TeeCreatePenSmallDots(Pen.Color);
{$ENDIF}
MoveTo(Rect.Left+2,Rect.Top+8);
LineTo(Rect.Left+30,Rect.Top+8);
Brush.Style:=bsClear;
{$IFDEF CLX}
if not (odSelected in State) then
Font.Color:=ColorToRGB(clText);
{$ELSE}
UpdateTextFlags;
{$ENDIF}
TextOut(Rect.Left+34,Rect.Top+{$IFDEF CLX}1{$ELSE}2{$ENDIF},CBStyle.Items[Index]);
end;
end;
{ TButtonPen }
procedure TButtonPen.Click;
begin
if Assigned(Instance) then
begin
if EditChartPen(Self,TChartPen(Instance),HideColor) then
begin
Repaint;
inherited;
end;
end
else inherited;
end;
procedure TButtonPen.DrawSymbol(ACanvas: TTeeCanvas);
Const tmpWidth={$IFDEF CLX}13{$ELSE}17{$ENDIF};
var OldChange : TNotifyEvent;
OldWidth : Integer;
begin
if Enabled and Assigned(Instance) then
begin
// allow maximum 6 pixels for symbol height...
with TChartPen(Instance) do
if Width>6 then
begin
OldChange:=OnChange;
OnChange:=nil;
OldWidth:=Width;
Width:=6;
end
else
begin
OldChange:=nil;
OldWidth:=0;
end;
// draw line
With ACanvas do
begin
Brush.Style:=bsClear;
AssignVisiblePen(TChartPen(Instance));
MoveTo(Width-tmpWidth,Height div 2);
LineTo(Width-6,Height div 2);
end;
// reset back old pen width
if Assigned(OldChange) then
with TChartPen(Instance) do
begin
Width:=OldWidth;
OnChange:=OldChange;
end;
end;
end;
procedure TButtonPen.LinkPen(APen: TChartPen);
begin
LinkProperty(APen,'');
Invalidate;
end;
{ Utility functions }
Procedure ShowControls(Show:Boolean; Const AControls:Array of TControl);
var t : Integer;
begin
for t:=Low(AControls) to High(AControls) do AControls[t].Visible:=Show;
end;
Function TeeYesNo(Const Message:String; Owner:TControl=nil):Boolean;
var x : Integer;
y : Integer;
Begin
Screen.Cursor:=crDefault;
if Assigned(Owner) then
begin
x:=Owner.ClientOrigin.X+20;
y:=Owner.ClientOrigin.Y+30;
result:=MessageDlgPos(Message,mtConfirmation,[mbYes,mbNo],0,x,y)=mrYes;
end
else result:=MessageDlg(Message,mtConfirmation,[mbYes,mbNo],0)=mrYes;
End;
Function TeeYesNoDelete(Const Message:String; Owner:TControl=nil):Boolean;
begin
result:=TeeYesNo(Format(TeeMsg_SureToDelete,[Message]),Owner);
end;
{$IFDEF CLX}
Procedure TeeFixParentedForm(AForm:TForm);
var tmpPoint : TPoint;
tmpFlags : Integer;
begin
with AForm do
begin
if not Parent.Showing then Parent.Show;
tmpPoint:=Point(Left,Top);
tmpFlags:=Integer( WidgetFlags_WStyle_NoBorder ) or
Integer( WidgetFlags_WStyle_Customize );
QWidget_reparent(Handle, ParentWidget, Cardinal(tmpFlags), @tmpPoint, Showing);
QOpenWidget_clearWFlags(QOpenWidgetH(Handle), Integer($FFFFFFFF));
QOpenWidget_setWFlags(QOpenWidgetH(Handle), Cardinal(tmpFlags));
Left:=tmpPoint.X;
Top:=tmpPoint.Y;
end;
end;
{$ENDIF}
{$IFNDEF CLR}
type TCustomFormAccess=class(TCustomForm);
{$ENDIF}
Procedure AddFormTo(AForm:TForm; AParent:TWinControl);
begin
AddFormTo(AForm,AParent,nil);
end;
Procedure AddFormTo(AForm:TForm; AParent:TWinControl; ATag:Integer);
begin
{$IFNDEF CLR}
AddFormTo(AForm,AParent,TComponent(ATag));
{$ENDIF}
end;
Procedure AddFormTo(AForm:TForm; AParent:TWinControl; ATag:TPersistent);
{$IFNDEF CLX}
var OldVisibleFlag : Boolean;
{$ENDIF}
begin
{$IFNDEF CLR}
with TCustomFormAccess(AForm) do
begin
{$IFNDEF CLX}
{$IFDEF D7}
ParentBackground:=True;
{$ENDIF}
{$ENDIF}
ParentColor:=True;
end;
{$ENDIF}
With AForm do
begin
{$IFNDEF CLX}
Position:=poDesigned;
{$ENDIF}
BorderStyle:=TeeFormBorderStyle;
BorderIcons:=[];
Tag:={$IFDEF CLR}Variant{$ELSE}Integer{$ENDIF}(ATag);
Parent:=AParent;
{$IFNDEF CLX}
OldVisibleFlag:=Parent.Visible;
Parent.Visible:=True;
{$ENDIF}
Left:=4; { ((AParent.ClientWidth-ClientWidth) div 2); }
Top:=Math.Min(4,Abs(AParent.ClientHeight-ClientHeight) div 2);
{$IFDEF CLX}
Align:=alClient;
TeeFixParentedForm(AForm);
{$ENDIF}
// dont here: TeeTranslateControl(AForm);
Show;
{$IFNDEF CLX}
Parent.Visible:=OldVisibleFlag;
{$ENDIF}
end;
end;
{ Utils }
Procedure AddDefaultValueFormats(AItems:TStrings);
begin
AItems.Add(TeeMsg_DefValueFormat);
AItems.Add('0');
AItems.Add('0.0');
AItems.Add('0.#');
AItems.Add('#.#');
AItems.Add('#,##0.00;(#,##0.00)');
AItems.Add('00e-0');
AItems.Add('#.0 "x10" E+0');
AItems.Add('#.# x10E-#');
end;
Procedure TeeLoadArrowBitmaps(AUp,ADown: TBitmap);
begin
TeeLoadBitmap(AUp,'TeeArrowUp','');
TeeLoadBitmap(ADown,'TeeArrowDown','');
end;
{ Helper Listbox methods... }
procedure MoveList(Source,Dest:TCustomListBox);
var t:Integer;
begin
with Source do
begin
for t:=0 to Items.Count-1 do
if Selected[t] then Dest.Items.AddObject(Items[t],Items.Objects[t]);
t:=0;
While t<Items.Count do
begin
if Selected[t] then Items.Delete(t)
else Inc(t);
end;
end;
end;
procedure MoveListAll(Source,Dest:TStrings);
var t : Integer;
begin
With Source do
for t:=0 to Count-1 do Dest.AddObject(Strings[t],Objects[t]);
Source.Clear;
end;
{ Routines to support "crTeeHand" cursor type }
Function TeeIdentToCursor(Const AName:String; Var ACursor:Integer):Boolean;
begin
if AName=TeeMsg_TeeHand then
begin
ACursor:=crTeeHand;
result:=True;
end
else result:=IdentToCursor(AName,ACursor);
end;
Const TeeCursorPrefix='cr';
Function TeeSetCursor(ACursor:TCursor; const S:String):TCursor;
var tmpCursor : Integer;
begin
if TeeIdentToCursor(TeeCursorPrefix+S,tmpCursor) then
result:=tmpCursor
else
result:=ACursor;
end;
Function TeeCursorToIdent(ACursor:Integer; Var AName:String):Boolean;
begin
if ACursor=crTeeHand then
begin
AName:=TeeMsg_TeeHand;
result:=True;
end
else result:=CursorToIdent(ACursor,AName);
end;
type
TTempCursors=class
private
FCombo : TComboFlat;
procedure ProcGetCursors(const S: string);
end;
Function DeleteCursorPrefix(Const S:String):String;
begin
result:=S;
if Copy(result,1,2)=TeeCursorPrefix then Delete(result,1,2);
end;
procedure TTempCursors.ProcGetCursors(const S: string);
begin
FCombo.Items.Add(DeleteCursorPrefix(S));
end;
procedure TeeFillCursors(ACombo:TComboFlat; ACursor:TCursor);
var tmp : TTempCursors;
tmpSt : String;
begin
With ACombo do
begin
Items.BeginUpdate;
Clear;
// Sorted:=True; 6.02, breaks new "Tree mode" chart editor
// Set Sorted to True at design-time in forms, not here.
tmp:=TTempCursors.Create;
try
tmp.FCombo:=ACombo;
GetCursorValues(tmp.ProcGetCursors);
tmp.ProcGetCursors(TeeMsg_TeeHand);
finally
tmp.Free;
end;
Items.EndUpdate;
if TeeCursorToIdent(ACursor,tmpSt) then
ItemIndex:=Items.IndexOf(DeleteCursorPrefix(tmpSt))
else
ItemIndex:=-1;
end;
end;
end.
|
unit untEasyDesignerPivotGridReg;
{$I cxVer.inc}
interface
uses
Windows, Classes, SysUtils, TypInfo,
Types, DesignIntf, DesignEditors, VCLEditors, Forms, DB, ShellApi, ImgList,
cxDesignWindows, cxEditPropEditors, cxPropEditors, cxControls, cxEdit,
cxStyles, cxPivotGridDesigner, cxCustomPivotGrid, cxDBPivotGrid,
cxPivotGrid, cxPivotGridPredefinedStyles, cxPivotGridStyleSheetsPreview,
cxPivotGridSummaryDataSet, cxPivotGridDrillDownDataSet, cxExportPivotGridLink,
cxPivotGridChartConnection;
procedure DesignerPivotGridRegister;
function cxPivotGridCustomComponentEditor: TComponentEditorClass;
implementation
uses
dxCore, dxCoreReg, cxLibraryReg;
const
scxDesigner = 'Designer...';
scxMajorVersion = '2';
scxProductName = 'ExpressPivotGrid';
type
{ TcxPivotGridFieldHeaderImageIndexProperty }
TcxPivotGridFieldHeaderImageIndexProperty = class(TImageIndexProperty)
public
function GetImages: TCustomImageList; override;
end;
{ TcxPivotGridFieldNameProperty }
TcxPivotGridFieldNameProperty = class(TFieldNameProperty)
public
function GetDataSource: TDataSource; override;
end;
{ TcxPivotGridStylesEventsProperty }
TcxPivotGridStylesEventsProperty = class(TcxNestedEventProperty)
protected
function GetInstance: TPersistent; override;
end;
{ TcxPivotGridPopupMenusEventsProperty }
TcxPivotGridPopupMenusEventsProperty = class(TcxNestedEventProperty)
protected
function GetInstance: TPersistent; override;
end;
{ TcxPivotGridFieldPropertiesEventsProperty }
TcxPivotGridFieldPropertiesEventsProperty = class(TcxNestedEventProperty)
protected
function GetInstance: TPersistent; override;
end;
{ TcxPivotGridFieldPropertiesProperty }
TcxPivotGridFieldPropertiesProperty = class(TClassProperty)
protected
function HasSubProperties: Boolean;
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
{ TcxCustomPivotGridComponentEditor }
TcxCustomPivotGridComponentEditor = class(TdxComponentEditor)
protected
function GetProductMajorVersion: string; override;
function GetProductName: string; override;
end;
{ TcxPivotGridComponentEditor }
TcxPivotGridComponentEditor = class(TcxCustomPivotGridComponentEditor)
protected
function InternalGetVerb(AIndex: Integer): string; override;
function InternalGetVerbCount: Integer; override;
procedure InternalExecuteVerb(AIndex: Integer); override;
end;
{ TcxPivotGridDesignHelper }
TcxPivotGridDesignHelper = class(TcxPivotGridCustomDesignHelper, IUnknown,
IcxPivotGridDesignerHelper {$IFDEF DELPHI6}, IDesignNotification{$ENDIF})
protected
Listeners: TList;
// IUnknown
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall;
{$IFDEF DELPHI6}
// IDesignNotification
procedure ItemDeleted(const ADesigner: IDesigner; AItem: TPersistent);
procedure ItemInserted(const ADesigner: IDesigner; AItem: TPersistent);
procedure ItemsModified(const ADesigner: IDesigner);
procedure SelectionChanged(const ADesigner: IDesigner; const ASelection: IDesignerSelections);
procedure DesignerOpened(const ADesigner: IDesigner; AResurrecting: Boolean);
procedure DesignerClosed(const ADesigner: IDesigner; AGoingDormant: Boolean);
{$ENDIF}
public
constructor Create;
destructor Destroy; override;
procedure AddListener(APivotGrid: TcxCustomPivotGrid);
procedure RemoveListener(APivotGrid: TcxCustomPivotGrid);
function IsObjectSelected(AObject: TPersistent): Boolean;
procedure Select(AObject: TPersistent; AShift: TShiftState);
end;
{$IFDEF DELPHI6}
TcxPivotGridSelectionEditor = class(TSelectionEditor)
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
TcxPivotGridFieldSelectionEditor = class(TSelectionEditor)
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
{$ENDIF}
{ TcxPivotGridFieldHeaderImageIndexProperty }
function TcxPivotGridFieldHeaderImageIndexProperty.GetImages: TCustomImageList;
begin
Result := nil;
if GetComponent(0) is TcxPivotGridField then
Result := TcxPivotGridField(GetComponent(0)).PivotGrid.FieldHeaderImages;
end;
{ TcxPivotGridFieldNameProperty }
function TcxPivotGridFieldNameProperty.GetDataSource: TDataSource;
begin
Result := TcxDBPivotGrid(TcxDBPivotGridFieldDataBinding(
GetComponent(0)).PivotGrid).DataSource;
end;
{ TcxPivotGridStylesEventsProperty }
function TcxPivotGridStylesEventsProperty.GetInstance: TPersistent;
begin
Result := TcxCustomPivotGrid(GetComponent(0)).Styles;
end;
{ TcxPivotGridPopupMenusEventsProperty }
function TcxPivotGridPopupMenusEventsProperty.GetInstance: TPersistent;
begin
Result := TcxCustomPivotGrid(GetComponent(0)).PopupMenus;
end;
{ TcxPivotGridFieldPropertiesEventsProperty }
function TcxPivotGridFieldPropertiesEventsProperty.GetInstance: TPersistent;
begin
Result := TcxPivotGridField(GetComponent(0)).Properties;
end;
{ TcxPivotGridFieldPropertiesProperty }
function TcxPivotGridFieldPropertiesProperty.HasSubProperties: Boolean;
var
I: Integer;
begin
for I := 0 to PropCount - 1 do
begin
Result := TcxPivotGridField(GetComponent(I)).Properties <> nil;
if not Result then Exit;
end;
Result := True;
end;
function TcxPivotGridFieldPropertiesProperty.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes;
if not HasSubProperties then
Exclude(Result, paSubProperties);
Result := Result - [paReadOnly] +
[paValueList, paSortList, paRevertable{$IFDEF DELPHI6}, paVolatileSubProperties{$ENDIF}];
end;
function TcxPivotGridFieldPropertiesProperty.GetValue: string;
begin
if HasSubProperties then
Result := GetRegisteredEditProperties.GetDescriptionByClass(
TcxPivotGridField(GetComponent(0)).Properties.ClassType)
else
Result := '';
end;
procedure TcxPivotGridFieldPropertiesProperty.GetValues(Proc: TGetStrProc);
var
I: Integer;
begin
for I := 0 to GetRegisteredEditProperties.Count - 1 do
Proc(GetRegisteredEditProperties.Descriptions[I]);
end;
procedure TcxPivotGridFieldPropertiesProperty.SetValue(const Value: string);
var
APropertiesClass: TcxCustomEditPropertiesClass;
I: Integer;
begin
APropertiesClass := TcxCustomEditPropertiesClass(GetRegisteredEditProperties.FindByClassName(Value));
if APropertiesClass = nil then
APropertiesClass := TcxCustomEditPropertiesClass(GetRegisteredEditProperties.FindByDescription(Value));
{$IFNDEF DELPHI7}
if GetValue <> Value then
ObjectInspectorCollapseProperty;
{$ENDIF}
for I := 0 to PropCount - 1 do
TcxPivotGridField(GetComponent(I)).PropertiesClass := APropertiesClass;
Modified;
end;
{ TcxCustomPivotGridComponentEditor }
function TcxCustomPivotGridComponentEditor.GetProductMajorVersion: string;
begin
Result := scxMajorVersion;
end;
function TcxCustomPivotGridComponentEditor.GetProductName: string;
begin
Result := scxProductName;
end;
{ TcxPivotGridComponentEditor }
function TcxPivotGridComponentEditor.InternalGetVerb(AIndex: Integer): string;
begin
Result := scxDesigner;
end;
function TcxPivotGridComponentEditor.InternalGetVerbCount: Integer;
begin
Result := 1;
end;
procedure TcxPivotGridComponentEditor.InternalExecuteVerb(AIndex: Integer);
begin
ShowPivotGridDesigner(Designer, Component as TcxCustomPivotGrid);
end;
{ TcxPivotGridDesignHelper }
constructor TcxPivotGridDesignHelper.Create;
begin
Listeners := TList.Create;
{$IFDEF DELPHI6}
RegisterDesignNotification(Self);
{$ENDIF}
end;
destructor TcxPivotGridDesignHelper.Destroy;
begin
{$IFDEF DELPHI6}
UnregisterDesignNotification(Self);
{$ENDIF}
Listeners.Free;
inherited Destroy;
end;
procedure TcxPivotGridDesignHelper.AddListener(
APivotGrid: TcxCustomPivotGrid);
begin
Listeners.Add(APivotGrid);
end;
procedure TcxPivotGridDesignHelper.RemoveListener(
APivotGrid: TcxCustomPivotGrid);
begin
Listeners.Remove(APivotGrid);
end;
function TcxPivotGridDesignHelper.IsObjectSelected(
AObject: TPersistent): Boolean;
begin
Result := False;
if AObject = nil then Exit;
with TcxDesignHelper.Create(AObject as TComponent) do
try
Result := IsObjectSelected(AObject);
finally
Free;
end;
end;
procedure TcxPivotGridDesignHelper.Select(
AObject: TPersistent; AShift: TShiftState);
var
ADesignHelper: TcxDesignHelper;
begin
if AObject = nil then Exit;
ADesignHelper := TcxDesignHelper.Create(AObject as TComponent);
try
if AShift * [ssCtrl, ssAlt] <> [] then Exit;
if ssShift in AShift then
ADesignHelper.ChangeSelection(AObject)
else
ADesignHelper.SelectObject(AObject);
finally
ADesignHelper.Free;
end;
end;
// IUnknown
function TcxPivotGridDesignHelper._AddRef: Integer;
begin
Result := -1;
end;
function TcxPivotGridDesignHelper._Release: Integer;
begin
Result := -1;
end;
function TcxPivotGridDesignHelper.QueryInterface(
const IID: TGUID; out Obj): HResult;
const
cxE_NOINTERFACE = HResult($80004002);
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := cxE_NOINTERFACE;
end;
{$IFDEF DELPHI6}
type
TcxCustomPivotGridAccess = class(TcxCustomPivotGrid);
// IDesignNotification
procedure TcxPivotGridDesignHelper.ItemDeleted(
const ADesigner: IDesigner; AItem: TPersistent);
begin
if AItem is TcxCustomPivotGrid then
RemoveListener(AItem as TcxCustomPivotGrid);
end;
procedure TcxPivotGridDesignHelper.ItemInserted(
const ADesigner: IDesigner; AItem: TPersistent);
begin
end;
procedure TcxPivotGridDesignHelper.ItemsModified(const ADesigner: IDesigner);
begin
end;
procedure TcxPivotGridDesignHelper.SelectionChanged(
const ADesigner: IDesigner; const ASelection: IDesignerSelections);
var
I: Integer;
begin
for I := 0 to Listeners.Count - 1 do
RefreshListener(TcxCustomPivotGrid(Listeners[I]));
end;
procedure TcxPivotGridDesignHelper.DesignerOpened(
const ADesigner: IDesigner; AResurrecting: Boolean);
begin
end;
procedure TcxPivotGridDesignHelper.DesignerClosed(
const ADesigner: IDesigner; AGoingDormant: Boolean);
begin
end;
{ TcxPivotGridSelectionEditor }
procedure TcxPivotGridSelectionEditor.RequiresUnits(Proc: TGetStrProc);
begin
inherited RequiresUnits(Proc);
Proc('cxClasses');
Proc('cxGraphics');
Proc('cxCustomData');
Proc('cxStyles');
Proc('cxEdit');
end;
{ TcxPivotGridFieldSelectionEditor }
procedure TcxPivotGridFieldSelectionEditor.RequiresUnits(Proc: TGetStrProc);
var
I: Integer;
AComponent: TComponent;
AItem: TcxPivotGridField;
begin
inherited RequiresUnits(Proc);
for I := 0 to Designer.Root.ComponentCount - 1 do
begin
AComponent := Designer.Root.Components[I];
if AComponent is TcxPivotGridField then
begin
AItem := TcxPivotGridField(AComponent);
if AItem.Properties <> nil then
Proc(dxShortStringToString(GetTypeData(PTypeInfo(AItem.Properties.ClassType.ClassInfo)).UnitName));
end;
end;
end;
{$ENDIF}
function cxPivotGridCustomComponentEditor: TComponentEditorClass;
begin
Result := TcxCustomPivotGridComponentEditor;
end;
procedure DesignerPivotGridRegister;
begin
{$IFDEF DELPHI9}
ForceDemandLoadState(dlDisable);
{$ENDIF}
RegisterComponents('Easy Grid', [TcxPivotGrid, TcxDBPivotGrid,
TcxPivotGridSummaryDataSet, TcxPivotGridDrillDownDataSet]);
RegisterNoIcon([TcxPivotGridField, TcxDBPivotGridField, TcxPivotGridStyleSheet]);
RegisterClasses([TcxPivotGridField, TcxDBPivotGridField, TcxPivotGridStyleSheet]);
RegisterClasses([TcxPivotGridFieldDataBinding, TcxDBPivotGridFieldDataBinding]);
RegisterComponentEditor(TcxCustomPivotGrid, TcxPivotGridComponentEditor);
RegisterComponentEditor(TcxPivotGridSummaryDataSet, TcxCustomPivotGridComponentEditor);
RegisterComponentEditor(TcxPivotGridDrillDownDataSet, TcxCustomPivotGridComponentEditor);
RegisterPropertyEditor(TypeInfo(Boolean),
TcxPivotGridField, 'IsCaptionAssigned', nil);
RegisterPropertyEditor(TypeInfo(Boolean),
TcxPivotGridFieldGroup, 'IsCaptionAssigned', nil);
RegisterPropertyEditor(TypeInfo(Boolean),
TcxPivotGridOptionsDataField, 'IsCaptionAssigned', nil);
RegisterPropertyEditor(TypeInfo(TComponent),
TcxPivotGridFieldHeaderMenu, 'PopupMenu', TcxControlPopupMenuProperty);
RegisterPropertyEditor(TypeInfo(TComponent),
TcxPivotGridGroupValueMenu, 'PopupMenu', TcxControlPopupMenuProperty);
RegisterPropertyEditor(TypeInfo(TComponent),
TcxPivotGridHeaderAreaMenu, 'PopupMenu', TcxControlPopupMenuProperty);
RegisterPropertyEditor(TypeInfo(TImageIndex), TcxPivotGridField,
'ImageIndex', TcxPivotGridFieldHeaderImageIndexProperty);
RegisterPropertyEditor(TypeInfo(TNotifyEvent), TcxCustomPivotGrid,
'StylesEvents', TcxPivotGridStylesEventsProperty);
RegisterPropertyEditor(TypeInfo(TNotifyEvent), TcxCustomPivotGrid,
'PopupMenusEvents', TcxPivotGridPopupMenusEventsProperty);
RegisterPropertyEditor(TypeInfo(TNotifyEvent), TcxPivotGridField,
'PropertiesEvents', TcxPivotGridFieldPropertiesEventsProperty);
RegisterPropertyEditor(TypeInfo(string), TcxDBPivotGridFieldDataBinding,
'FieldName', TcxPivotGridFieldNameProperty);
RegisterPropertyEditor(TypeInfo(string), TcxPivotGridFieldDataBinding,
'ValueType', TcxValueTypeProperty);
RegisterPropertyEditor(TypeInfo(string), TcxPivotGridField, 'PropertiesClassName', nil);
RegisterPropertyEditor(TypeInfo(TcxCustomEditProperties), TcxPivotGridField,
'Properties', TcxPivotGridFieldPropertiesProperty);
// HideClassProperties(TcxPivotGridField, ['UniqueName']);
HideClassProperties(TcxPivotGridOptionsView, ['TotalsLocation']);
{$IFDEF DELPHI6}
RegisterSelectionEditor(TcxCustomPivotGrid, TcxPivotGridSelectionEditor);
RegisterSelectionEditor(TcxPivotGridField, TcxPivotGridFieldSelectionEditor);
{$ENDIF}
//TcxPivotGridChartConnection
RegisterComponents('Easy Grid', [TcxPivotGridChartConnection]);
RegisterClasses([TcxPivotGridChartConnection]);
RegisterComponentEditor(TcxPivotGridChartConnection, cxPivotGridCustomComponentEditor);
end;
var
ADesignerHelper: TcxPivotGridDesignHelper;
initialization
DesignerHelper := nil;
RegisterStyleSheetClass(TcxPivotGridStyleSheet);
ADesignerHelper := TcxPivotGridDesignHelper.Create;
DesignerHelper := ADesignerHelper as IcxPivotGridDesignerHelper;
DesignerPivotGridRegister;
finalization
DesignerHelper := nil;
UnRegisterStyleSheetClass(TcxPivotGridStyleSheet);
FreeAndNil(ADesignerHelper);
end.
|
unit uObjectUrlDotaz;
interface
uses SysUtils, Types, Classes, IdUri, IdGlobal;
type
TUrlDotaz = class(TObject)
private
function EncodeString(s: string): string;
protected
public
adresa: string;
params: TStringList;
constructor Create; overload;
constructor Create(adr: string); overload;
function GetEncodedUrl: string;
end;
implementation
{ TUrlDotaz }
constructor TUrlDotaz.Create;
begin
inherited Create;
params := TStringList.Create;
end;
constructor TUrlDotaz.Create(adr: string);
begin
inherited Create;
Create;
adresa := adr;
end;
function TUrlDotaz.EncodeString(s: string): string;
begin
s := TIdURI.ParamsEncode(s, IndyUTF8Encoding); // tato f-cia musi dostat aj typ protokolu a host. Preto to 'http://' aj to www.qp.sk
s := StringReplace(s, 'http://www.qp.sk/', '', [rfReplaceAll] ); // teraz to dame prec
result := StringReplace(s, '&', '%26', [rfReplaceAll] );
end;
function TUrlDotaz.GetEncodedUrl: string;
var
i: Integer;
begin
result := adresa;
if params.Count > 0 then begin
result := result + '?';
for i := 0 to params.Count-1 do
result := result + params.Names[i] + '=' + EncodeString(params.ValueFromIndex[i]) + '&';
end;
end;
end.
|
unit QTThunkU;
{$R-,S-,Q-}
//Define only one of these symbols
//If none are defined it defaults to original windows
{$define Generic} //Should work on all versions of Win95
{ $define OSR2} //Works on newer OSR2 versions
{ $define OSR1} //Works on original version of Win95
interface
uses
Windows, SysUtils;
type
THandle16 = Word;
//Windows 95 undocumented routines. These won't be found in Windows NT
{$ifdef Generic}
var
QT_Thunk: TProcedure;
{$else}
procedure QT_Thunk;
{$endif}
function LoadLibrary16(LibFileName: PChar): THandle; stdcall;
procedure FreeLibrary16(LibModule: THandle); stdcall;
function GetProcAddress16(Module: HModule; ProcName: PChar): TFarProc; stdcall;
function GlobalAlloc16(Flags: Integer; Bytes: Longint): THandle16; stdcall;
function GlobalFree16(Mem: THandle16): THandle16; stdcall;
function GlobalLock16(Mem: THandle16): Pointer; stdcall;
function GlobalUnLock16(Mem: THandle16): WordBool; stdcall;
//Windows NT/95 documented but undeclared routines
// 16:16 -> 0:32 Pointer translation.
//
// WOWGetVDMPointer will convert the passed in 16-bit address
// to the equivalent 32-bit flat pointer. If fProtectedMode
// is TRUE, the function treats the upper 16 bits as a selector
// in the local descriptor table. If fProtectedMode is FALSE,
// the upper 16 bits are treated as a real-mode segment value.
// In either case the lower 16 bits are treated as the offset.
//
// The return value is NULL if the selector is invalid.
//
// NOTE: Limit checking is not performed in the retail build
// of Windows NT. It is performed in the checked (debug) build
// of WOW32.DLL, which will cause NULL to be returned when the
// limit is exceeded by the supplied offset.
function WOWGetVDMPointer(vp, dwBytes: DWord;
fProtectedMode: Bool): Pointer; stdcall;
// The following two functions are here for compatibility with
// Windows 95. On Win95, the global heap can be rearranged,
// invalidating flat pointers returned by WOWGetVDMPointer, while
// a thunk is executing. On Windows NT, the 16-bit VDM is completely
// halted while a thunk executes, so the only way the heap will
// be rearranged is if a callback is made to Win16 code.
//
// The Win95 versions of these functions call GlobalFix to
// lock down a segment's flat address, and GlobalUnfix to
// release the segment.
//
// The Windows NT implementations of these functions do *not*
// call GlobalFix/GlobalUnfix on the segment, because there
// will not be any heap motion unless a callback occurs.
// If your thunk does callback to the 16-bit side, be sure
// to discard flat pointers and call WOWGetVDMPointer again
// to be sure the flat address is correct.
function WOWGetVDMPointerFix(vp, dwBytes: DWord;
fProtectedMode: Bool): Pointer; stdcall;
procedure WOWGetVDMPointerUnfix(vp: DWord); stdcall;
//My compound memory routines
function GlobalAllocPtr16(Flags: Word; Bytes: Longint): Pointer;
function GlobalAllocPointer16(Flags: Word; Bytes: Longint;
var FlatPointer: Pointer; var Source; DataSize: Longint): Pointer;
function GlobalFreePtr16(P: Pointer): THandle16;
//My utility routines
function Ptr16To32(P: Pointer): Pointer;
function Ptr16To32Fix(P: Pointer): Pointer;
procedure Ptr16To32Unfix(P: Pointer);
function GetAddress16(Module: HModule; ProcName: String): TFarProc;
function LoadLib16(LibFileName: String): THandle;
function GDI16Handle: THandle;
function Kernel16Handle: THandle;
function User16Handle: THandle;
type
TConvention = (ccPascal, ccCDecl);
function Call16BitRoutine(Name: String; DllHandle: THandle16;
Convention: TConvention; Args: array of const;
ArgSizes: array of Integer): Longint;
implementation
uses
Classes, Dialogs;
type
EInvalidArgument = class(EMathError);
EInvalidProc = class(Exception);
EThunkError = class(Exception);
const
kernel32 = 'kernel32.dll';
wow32 = 'wow32.dll';
//QT_Thunk changes its ordinal number under
//Windows 95 OSR2 so we link to it dynamically
//instead of statically, to ensure we get the right link
{$ifndef Generic}
{$ifdef OSR2}
procedure QT_Thunk; external kernel32 index 561;//name 'QT_Thunk';
{$else} {OSR1 - original Win95}
procedure QT_Thunk; external kernel32 index 559;//name 'QT_Thunk';
{$endif}
{$endif}
//Don't link by name to avoid ugly messages under NT
//These routines are exported with no names, hence the use of index
function LoadLibrary16; external kernel32 index 35;
procedure FreeLibrary16; external kernel32 index 36;
function GetProcAddress16; external kernel32 index 37;
function GlobalAlloc16; external kernel32 index 24;
function GlobalFree16; external kernel32 index 31;
function GlobalLock16; external kernel32 index 25;
function GlobalUnLock16; external kernel32 index 26;
//These routines are exported with names, hence the normal use of name
function WOWGetVDMPointer; external wow32 name 'WOWGetVDMPointer';
function WOWGetVDMPointerFix; external wow32 name 'WOWGetVDMPointerFix';
procedure WOWGetVDMPointerUnfix; external wow32 name 'WOWGetVDMPointerUnfix';
function GlobalAllocPtr16(Flags: Word; Bytes: Longint): Pointer;
begin
Result := nil;
//Ensure memory is fixed, meaning there is no need to lock it
Flags := Flags or gmem_Fixed;
LongRec(Result).Hi := GlobalAlloc16(Flags, Bytes);
end;
//16-bit pointer returned. FlatPointer is 32-bit pointer
//Bytes-sized buffer is allocated and then DataSize bytes
//from Source are copied in
function GlobalAllocPointer16(Flags: Word; Bytes: Longint;
var FlatPointer: Pointer; var Source; DataSize: Longint): Pointer;
begin
//Allocate memory in an address range
//that _can_ be accessed by 16-bit apps
Result := GlobalAllocPtr16(Flags, Bytes);
//Get 32-bit pointer to this memory
FlatPointer := Ptr16To32(Result);
//Copy source data into the new bimodal buffer
Move(Source, FlatPointer^, DataSize);
end;
function GlobalFreePtr16(P: Pointer): THandle16;
begin
Result := GlobalFree16(LongRec(P).Hi);
end;
//Turn 16-bit pointer (selector and offset)
//into 32-bit pointer (offset)
function Ptr16To32(P: Pointer): Pointer;
begin
Result := WOWGetVDMPointer(DWord(P), 0, True);
end;
//Turn 16-bit pointer (selector and offset)
//into 32-bit pointer (offset) and ensure it stays valid
function Ptr16To32Fix(P: Pointer): Pointer;
begin
Result := WOWGetVDMPointerFix(DWord(P), 0, True);
end;
//Apply required housekeping to fixed 16-bit pointer
procedure Ptr16To32Unfix(P: Pointer);
begin
WOWGetVDMPointerUnfix(DWord(P));
end;
function GetAddress16(Module: HModule; ProcName: String): TFarProc;
begin
Result := GetProcAddress16(Module, PChar(ProcName));
if not Assigned(Result) then
raise EInvalidProc.Create('GetProcAddress16 failed');
end;
function LoadLib16(LibFileName: String): THandle;
begin
Result := LoadLibrary16(PChar(LibFileName));
if Result < HInstance_Error then
raise EFOpenError.Create('LoadLibrary16 failed!');
end;
function GDI16Handle: THandle;
begin
//Get GDI handle by loading it.
Result := LoadLib16('GDI.EXE');
//Free this particular load - GDI will stay in memory
FreeLibrary16(Result);
end;
function Kernel16Handle: THandle;
begin
//Get Kernel handle by loading it.
Result := LoadLib16('KRNL386.EXE');
//Free this particular load - Kernel will stay in memory
FreeLibrary16(Result);
end;
function User16Handle: THandle;
begin
//Get User handle by loading it.
Result := LoadLib16('USER.EXE');
//Free this particular load - User will stay in memory
FreeLibrary16(Result);
end;
type
TPtrSize = (ps16, ps32);
const
//Max of 10 pointer params - no error checking yet
MaxPtrs = 10;
//Max of 1024 bytes passed, inc. indirectly - no error checking yet
MaxParamBytes = 1024;
var
ArgByteCount: Integer;
ArgBuf: array[0..MaxParamBytes - 1] of Byte;
ProcAddress: Pointer;
{$StackFrames On}
{$Optimization Off}
function CallQT_Thunk(Convention: TConvention): Longint;
var
EatStackSpace: String[$3C];
begin
//Ensure buffer isn't optimised away
EatStackSpace := '';
//Push ArgByteCount bytes from ArgBuf onto stack
asm
mov edx, 0
@LoopStart:
cmp edx, ArgByteCount
je @DoneStackBit
mov ax, word ptr [ArgBuf + edx]
push ax
inc edx
inc edx
jmp @LoopStart
@DoneStackBit:
mov edx, ProcAddress
call QT_Thunk
mov Result.Word.0, ax
mov Result.Word.2, dx
cmp Convention, ccCDecl
jne @Exit
add esp, ArgByteCount
@Exit:
end;
end;
{$Optimization On}
//DLL must already be loaded with LoadLib16 or LoadLibrary16
//The routine name and DLL handle are passed in, along with
//an indication of the calling convention (C or Pascal)
//Parameters are passed in an array. These can be 1, 2 or 4 byte
//ordinals, or pointers to anything.
//Parameter sizes are passed in a second array. If no parameters
//are required, pass a 0 in both arrays. There must be as
//many sizes as there are parameters. If the parameter is a pointer
//the size is the number of significant bytes it points to
//This routine returns a Longint. Consequently, valid return types
//for the target routine are 1, 2 or 4 byte ordinal types or
//pointers. Pointers returned will be 16-bit. These will need
//reading via Ptr16To32Fix and Ptr16To32Unfix
function Call16BitRoutine(Name: String; DllHandle: THandle16;
Convention: TConvention; Args: array of const;
ArgSizes: array of Integer): Longint;
var
Loop: Integer;
ByteTemp: Word;
Ptrs: array[0..MaxPtrs-1, TPtrSize] of Pointer;
PtrCount: Byte;
PtrArgIndices: array[0..MaxPtrs-1] of integer; // maps Ptrs[] to
// original Args[]
procedure PushParameter(Param: Integer);
begin
if ArgByteCount > MaxParamBytes then
raise EThunkError.Create('Too many parameters');
case Args[Param].VType of
vtInteger, vtBoolean, vtChar:
begin
//Byte-sized args are passed as words
if ArgSizes[Param] = 1 then
begin
//The important byte is stuck as msb of the 4
//To get it into a word, assign it to one
ByteTemp := Byte(Args[Param].VChar);
Move(ByteTemp, ArgBuf[ArgByteCount], SizeOf(ByteTemp));
//This means one extra byte on the stack
Inc(ArgByteCount, 2);
end
else
begin
//If it's a 4 byte item, push the 2 high bytes
if ArgSizes[Param] = 4 then
begin
Move(LongRec(Args[Param].VInteger).Hi,
ArgBuf[ArgByteCount], SizeOf(Word));
Inc(ArgByteCount, SizeOf(Word));
end;
//Either way, push the 2 low bytes
Move(LongRec(Args[Param].VInteger).Lo,
ArgBuf[ArgByteCount], SizeOf(Word));
Inc(ArgByteCount, SizeOf(Word));
end;
end;
vtPointer, vtPChar:
begin
if PtrCount = MaxPtrs then
raise EThunkError.Create('Too many pointer parameters');
//Must keep record of 16-bit and 32-bit
//allocated pointers for terminal housekeeping
Ptrs[PtrCount, ps16] := GlobalAllocPointer16(GPTR,
ArgSizes[Param], Ptrs[PtrCount, ps32],
Args[Param].vPointer^, ArgSizes[Param]);
//Save arg position in arg list, may need
//to copy back if arg is var
PtrArgIndices[PtrCount] := Param;
//Move high and low word of new pointer into ArgBuf
//ready for push onto stack
Move(LongRec(Ptrs[PtrCount, ps16]).Hi,
ArgBuf[ArgByteCount], SizeOf(Word));
Inc(ArgByteCount, SizeOf(Word));
Move(LongRec(Ptrs[PtrCount, ps16]).Lo,
ArgBuf[ArgByteCount], SizeOf(Word));
Inc(ArgByteCount, SizeOf(Word));
Inc(PtrCount);
end;
end;
end;
begin
//Check args
if High(Args) <> High(ArgSizes) then
raise EInvalidArgument.Create('Parameter mismatch');
ArgByteCount := 0;
PtrCount := 0;
ProcAddress := GetProcAddress16(DLLHandle, PChar(Name));
if not Assigned(ProcAddress) then
raise EThunkError.Create('16-bit routine not found');
//This should count up the number of bytes pushed
//onto the stack. If Convention = ccCdecl, the stack
//must be incremented that much after the routine ends
//Also, parameters are pushed in reverse order if cdecl
//Check for no parameters first
if ArgSizes[Low(ArgSizes)] <> 0 then
if Convention = ccPascal then
for Loop := Low(Args) to High(Args) do
PushParameter(Loop)
else
for Loop := High(Args) downto Low(Args) do
PushParameter(Loop);
Result := CallQT_Thunk(Convention);
//Dispose of allocated pointers, copying
//their contents back to 32-bit memory space
//in case any data was updated by 16-bit code
for Loop := 0 to Pred(PtrCount) do
begin
//Copy data back
Move(Ptrs[Loop, ps32]^, Args[PtrArgIndices[Loop]].VPointer^,
ArgSizes[PtrArgIndices[Loop]]);
//Free pointer
GlobalFreePtr16(Ptrs[Loop, ps16]);
end;
end;
{$ifdef Generic}
var
Kernel32Mod: THandle;
initialization
Kernel32Mod := GetModuleHandle('Kernel32.Dll');
QT_Thunk := GetProcAddress(Kernel32Mod, 'QT_Thunk');
if @QT_Thunk = nil then
raise EThunkError.Create('Flat thunks only supported under Windows 95');
{$else}
initialization
if Win32Platform <> Ver_Platform_Win32_Windows then
raise EThunkError.Create('Flat thunks only supported under Windows 95');
{$endif}
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.