text
stringlengths
14
6.51M
unit MyCat.BackEnd.DataSource; interface uses MyCat.Config.Model, MyCat.BackEnd, MyCat.BackEnd.HeartBeat, MyCat.BackEnd.Mysql.CrossSocket.Handler; type TPhysicalDatasource = class private FName: String; FSize: Integer; FConfig: TDBHostConfig; FConMap: TConMap; FHeartbeat: TDBHeartbeat; FReadNode: Boolean; FHeartbeatRecoveryTime: Int64; FHostConfig: TDataHostConfig; FConnHeartBeatHanler: TConnectionHeartBeatHandler; FDBPool: PhysicalDBPool; // 添加DataSource读计数 FReadCount: Int64; // = new AtomicLong(0); // 添加DataSource写计数 FWriteCount: Int64; // = new AtomicLong(0); public constructor Create(Config: TDBHostConfig; HostConfig: TDataHostConfig; IsReadNode: Boolean); end; // = new ConMap(); // public abstract class PhysicalDatasource { // // private static final Logger LOGGER = LoggerFactory.getLogger(PhysicalDatasource.class); // // private final String name; // private final int size; // private final DBHostConfig config; // private final ConMap conMap = new ConMap(); // private DBHeartbeat heartbeat; // private final boolean readNode; // private volatile long heartbeatRecoveryTime; // private final DataHostConfig hostConfig; // private final ConnectionHeartBeatHandler conHeartBeatHanler = new ConnectionHeartBeatHandler(); // private PhysicalDBPool dbPool; // // // 添加DataSource读计数 // private AtomicLong readCount = new AtomicLong(0); // // // 添加DataSource写计数 // private AtomicLong writeCount = new AtomicLong(0); // // // /** // * edit by dingw at 2017.06.08 // * @see https://github.com/MyCATApache/Mycat-Server/issues/1524 // * // */ // // 当前活动连接 // //private volatile AtomicInteger activeCount = new AtomicInteger(0); // // // 当前存活的总连接数,为什么不直接使用activeCount,主要是因为连接的创建是异步完成的 // //private volatile AtomicInteger totalConnection = new AtomicInteger(0); // // /** // * 由于在Mycat中,returnCon被多次调用(与takeCon并没有成对调用)导致activeCount、totalConnection容易出现负数 // */ // //private static final String TAKE_CONNECTION_FLAG = "1"; // //private ConcurrentMap<Long /* ConnectionId */, String /* 常量1*/> takeConnectionContext = new ConcurrentHashMap<>(); // // // // public PhysicalDatasource(DBHostConfig config, DataHostConfig hostConfig, // boolean isReadNode) { // this.size = config.getMaxCon(); // this.config = config; // this.name = config.getHostName(); // this.hostConfig = hostConfig; // heartbeat = this.createHeartBeat(); // this.readNode = isReadNode; // } // // public boolean isMyConnection(BackendConnection con) { // if (con instanceof MySQLConnection) { // return ((MySQLConnection) con).getPool() == this; // } else { // return false; // } // // } // // public long getReadCount() { // return readCount.get(); // } // // public void setReadCount() { // readCount.addAndGet(1); // } // // public long getWriteCount() { // return writeCount.get(); // } // // public void setWriteCount() { // writeCount.addAndGet(1); // } // // public DataHostConfig getHostConfig() { // return hostConfig; // } // // public boolean isReadNode() { // return readNode; // } // // public int getSize() { // return size; // } // // public void setDbPool(PhysicalDBPool dbPool) { // this.dbPool = dbPool; // } // // public PhysicalDBPool getDbPool() { // return dbPool; // } // // public abstract DBHeartbeat createHeartBeat(); // // public String getName() { // return name; // } // // public long getExecuteCount() { // long executeCount = 0; // for (ConQueue queue : conMap.getAllConQueue()) { // executeCount += queue.getExecuteCount(); // // } // return executeCount; // } // // public long getExecuteCountForSchema(String schema) { // return conMap.getSchemaConQueue(schema).getExecuteCount(); // // } // // public int getActiveCountForSchema(String schema) { // return conMap.getActiveCountForSchema(schema, this); // } // // public int getIdleCountForSchema(String schema) { // ConQueue queue = conMap.getSchemaConQueue(schema); // int total = 0; // total += queue.getAutoCommitCons().size() // + queue.getManCommitCons().size(); // return total; // } // // public DBHeartbeat getHeartbeat() { // return heartbeat; // } // // public int getIdleCount() { // int total = 0; // for (ConQueue queue : conMap.getAllConQueue()) { // total += queue.getAutoCommitCons().size() // + queue.getManCommitCons().size(); // } // return total; // } // // /** // * 该方法也不是非常精确,因为该操作也不是一个原子操作,相对getIdleCount高效与准确一些 // * @return // */ /// / public int getIdleCountSafe() { /// / return getTotalConnectionsSafe() - getActiveCountSafe(); /// / } // // /** // * 是否需要继续关闭空闲连接 // * @return // */ /// / private boolean needCloseIdleConnection() { /// / return getIdleCountSafe() > hostConfig.getMinCon(); /// / } // // private boolean validSchema(String schema) { // String theSchema = schema; // return theSchema != null && !"".equals(theSchema) // && !"snyn...".equals(theSchema); // } // // private void checkIfNeedHeartBeat( // LinkedList<BackendConnection> heartBeatCons, ConQueue queue, // ConcurrentLinkedQueue<BackendConnection> checkLis, // long hearBeatTime, long hearBeatTime2) { // int maxConsInOneCheck = 10; // Iterator<BackendConnection> checkListItor = checkLis.iterator(); // while (checkListItor.hasNext()) { // BackendConnection con = checkListItor.next(); // if (con.isClosedOrQuit()) { // checkListItor.remove(); // continue; // } // if (validSchema(con.getSchema())) { // if (con.getLastTime() < hearBeatTime // && heartBeatCons.size() < maxConsInOneCheck) { // if(checkLis.remove(con)) { // //如果移除成功,则放入到心跳连接中,如果移除失败,说明该连接已经被其他线程使用,忽略本次心跳检测 // con.setBorrowed(true); // heartBeatCons.add(con); // } // } // } else if (con.getLastTime() < hearBeatTime2) { // // not valid schema conntion should close for idle // // exceed 2*conHeartBeatPeriod // // 同样,这里也需要先移除,避免被业务连接 // if(checkLis.remove(con)) { // con.close(" heart beate idle "); // } // } // // } // // } // // public int getIndex() { // int currentIndex = 0; // for (int i = 0; i < dbPool.getSources().length; i++) { // PhysicalDatasource writeHostDatasource = dbPool.getSources()[i]; // if (writeHostDatasource.getName().equals(getName())) { // currentIndex = i; // break; // } // } // return currentIndex; // } // // public boolean isSalveOrRead() { // int currentIndex = getIndex(); // if (currentIndex != dbPool.activedIndex || this.readNode) { // return true; // } // return false; // } // // public void heatBeatCheck(long timeout, long conHeartBeatPeriod) { /// / int ildeCloseCount = hostConfig.getMinCon() * 3; // int maxConsInOneCheck = 5; // LinkedList<BackendConnection> heartBeatCons = new LinkedList<BackendConnection>(); // // long hearBeatTime = TimeUtil.currentTimeMillis() - conHeartBeatPeriod; // long hearBeatTime2 = TimeUtil.currentTimeMillis() - 2 // * conHeartBeatPeriod; // for (ConQueue queue : conMap.getAllConQueue()) { // checkIfNeedHeartBeat(heartBeatCons, queue, // queue.getAutoCommitCons(), hearBeatTime, hearBeatTime2); // if (heartBeatCons.size() < maxConsInOneCheck) { // checkIfNeedHeartBeat(heartBeatCons, queue, // queue.getManCommitCons(), hearBeatTime, hearBeatTime2); // } else if (heartBeatCons.size() >= maxConsInOneCheck) { // break; // } // } // // if (!heartBeatCons.isEmpty()) { // for (BackendConnection con : heartBeatCons) { // conHeartBeatHanler // .doHeartBeat(con, hostConfig.getHearbeatSQL()); // } // } // // // check if there has timeouted heatbeat cons // conHeartBeatHanler.abandTimeOuttedConns(); // int idleCons = getIdleCount(); // int activeCons = this.getActiveCount(); // int createCount = (hostConfig.getMinCon() - idleCons) / 3; // // create if idle too little // if ((createCount > 0) && (idleCons + activeCons < size) // && (idleCons < hostConfig.getMinCon())) { // createByIdleLitte(idleCons, createCount); // } else if (idleCons > hostConfig.getMinCon()) { // closeByIdleMany(idleCons - hostConfig.getMinCon()); // } else { // int activeCount = this.getActiveCount(); // if (activeCount > size) { // StringBuilder s = new StringBuilder(); // s.append(Alarms.DEFAULT).append("DATASOURCE EXCEED [name=") // .append(name).append(",active="); // s.append(activeCount).append(",size=").append(size).append(']'); // LOGGER.warn(s.toString()); // } // } // } // // /** // * // * @param ildeCloseCount // * 首先,从已创建的连接中选择本次心跳需要关闭的空闲连接数(由当前连接连接数-减去配置的最小连接数。 // * 然后依次关闭这些连接。由于连接空闲心跳检测与业务是同时并发的,在心跳关闭阶段,可能有连接被使用,导致需要关闭的空闲连接数减少. // * // * 所以每次关闭新连接时,先判断当前空闲连接数是否大于配置的最少空闲连接,如果为否,则结束本次关闭空闲连接操作。 // * 该方法修改之前: // * 首先从ConnMap中获取 ildeCloseCount 个连接,然后关闭;在关闭中,可能又有连接被使用,导致可能多关闭一些链接, // * 导致相对频繁的创建新连接和关闭连接 // * // * 该方法修改之后: // * ildeCloseCount 为预期要关闭的连接 // * 使用循环操作,首先在关闭之前,先再一次判断是否需要关闭连接,然后每次从ConnMap中获取一个空闲连接,然后进行关闭 // * edit by dingw at 2017.06.16 // */ // private void closeByIdleMany(int ildeCloseCount) { // LOGGER.info("too many ilde cons ,close some for datasouce " + name); // List<BackendConnection> readyCloseCons = new ArrayList<BackendConnection>( // ildeCloseCount); // for (ConQueue queue : conMap.getAllConQueue()) { // readyCloseCons.addAll(queue.getIdleConsToClose(ildeCloseCount)); // if (readyCloseCons.size() >= ildeCloseCount) { // break; // } // } // // for (BackendConnection idleCon : readyCloseCons) { // if (idleCon.isBorrowed()) { // LOGGER.warn("find idle con is using " + idleCon); // } // idleCon.close("too many idle con"); // } // /// / LOGGER.info("too many ilde cons ,close some for datasouce " + name); /// / /// / Iterator<ConQueue> conQueueIt = conMap.getAllConQueue().iterator(); /// / ConQueue queue = null; /// / if(conQueueIt.hasNext()) { /// / queue = conQueueIt.next(); /// / } /// / /// / for(int i = 0; i < ildeCloseCount; i ++ ) { /// / /// / if(!needCloseIdleConnection() || queue == null) { /// / break; //如果当时空闲连接数没有超过最小配置连接数,则结束本次连接关闭 /// / } /// / /// / LOGGER.info("cur conns:" + getTotalConnectionsSafe() ); /// / /// / BackendConnection idleCon = queue.takeIdleCon(false); /// / /// / while(idleCon == null && conQueueIt.hasNext()) { /// / queue = conQueueIt.next(); /// / idleCon = queue.takeIdleCon(false); /// / } /// / /// / if(idleCon == null) { /// / break; /// / } /// / /// / if (idleCon.isBorrowed() ) { /// / LOGGER.warn("find idle con is using " + idleCon); /// / } /// / idleCon.close("too many idle con"); /// / /// / } // // } // // private void createByIdleLitte(int idleCons, int createCount) { // LOGGER.info("create connections ,because idle connection not enough ,cur is " // + idleCons // + ", minCon is " // + hostConfig.getMinCon() // + " for " // + name); // NewConnectionRespHandler simpleHandler = new NewConnectionRespHandler(); // // final String[] schemas = dbPool.getSchemas(); // for (int i = 0; i < createCount; i++) { // if (this.getActiveCount() + this.getIdleCount() >= size) { // break; // } // try { // // creat new connection // this.createNewConnection(simpleHandler, null, schemas[i // % schemas.length]); // } catch (IOException e) { // LOGGER.warn("create connection err " + e); // } // // } // } // // public int getActiveCount() { // return this.conMap.getActiveCountForDs(this); // } // // // // public void clearCons(String reason) { // this.conMap.clearConnections(reason, this); // } // // public void startHeartbeat() { // heartbeat.start(); // } // // public void stopHeartbeat() { // heartbeat.stop(); // } // // public void doHeartbeat() { // // 未到预定恢复时间,不执行心跳检测。 // if (TimeUtil.currentTimeMillis() < heartbeatRecoveryTime) { // return; // } // // if (!heartbeat.isStop()) { // try { // heartbeat.heartbeat(); // } catch (Exception e) { // LOGGER.error(name + " heartbeat error.", e); // } // } // } // // private BackendConnection takeCon(BackendConnection conn, // final ResponseHandler handler, final Object attachment, // String schema) { // // conn.setBorrowed(true); // /// / if(takeConnectionContext.putIfAbsent(conn.getId(), TAKE_CONNECTION_FLAG) == null) { /// / incrementActiveCountSafe(); /// / } // // // if (!conn.getSchema().equals(schema)) { // // need do schema syn in before sql send // conn.setSchema(schema); // } // ConQueue queue = conMap.getSchemaConQueue(schema); // queue.incExecuteCount(); // conn.setAttachment(attachment); // conn.setLastTime(System.currentTimeMillis()); // 每次取连接的时候,更新下lasttime,防止在前端连接检查的时候,关闭连接,导致sql执行失败 // handler.connectionAcquired(conn); // return conn; // } // // private void createNewConnection(final ResponseHandler handler, // final Object attachment, final String schema) throws IOException { // // aysn create connection // MycatServer.getInstance().getBusinessExecutor().execute(new Runnable() { // public void run() { // try { // createNewConnection(new DelegateResponseHandler(handler) { // @Override // public void connectionError(Throwable e, BackendConnection conn) { // //decrementTotalConnectionsSafe(); // 如果创建连接失败,将当前连接数减1 // handler.connectionError(e, conn); // } // // @Override // public void connectionAcquired(BackendConnection conn) { // takeCon(conn, handler, attachment, schema); // } // }, schema); // } catch (IOException e) { // handler.connectionError(e, null); // } // } // }); // } // // public void getConnection(String schema, boolean autocommit, // final ResponseHandler handler, final Object attachment) // throws IOException { // // // 从当前连接map中拿取已建立好的后端连接 // BackendConnection con = this.conMap.tryTakeCon(schema, autocommit); // if (con != null) { // //如果不为空,则绑定对应前端请求的handler // takeCon(con, handler, attachment, schema); // return; // // } else { // this.getActiveCount并不是线程安全的(严格上说该方法获取数量不准确), /// / int curTotalConnection = this.totalConnection.get(); /// / while(curTotalConnection + 1 <= size) { /// / /// / if (this.totalConnection.compareAndSet(curTotalConnection, curTotalConnection + 1)) { /// / LOGGER.info("no ilde connection in pool,create new connection for " + this.name + " of schema " + schema); /// / createNewConnection(handler, attachment, schema); /// / return; /// / } /// / /// / curTotalConnection = this.totalConnection.get(); //CAS更新失败,则重新判断当前连接是否超过最大连接数 /// / /// / } /// / /// / // 如果后端连接不足,立即失败,故直接抛出连接数超过最大连接异常 /// / LOGGER.error("the max activeConnnections size can not be max than maxconnections:" + curTotalConnection); /// / throw new IOException("the max activeConnnections size can not be max than maxconnections:" + curTotalConnection); // // int activeCons = this.getActiveCount();// 当前最大活动连接 // if (activeCons + 1 > size) {// 下一个连接大于最大连接数 // LOGGER.error("the max activeConnnections size can not be max than maxconnections"); // throw new IOException("the max activeConnnections size can not be max than maxconnections"); // } else { // create connection // LOGGER.info("no ilde connection in pool,create new connection for " + this.name + " of schema " + schema); // createNewConnection(handler, attachment, schema); // } // } // } // // /** // * 是否超过最大连接数 // * @return // */ /// / private boolean exceedMaxConnections() { /// / return this.totalConnection.get() + 1 > size; /// / } /// / /// / public int decrementActiveCountSafe() { /// / return this.activeCount.decrementAndGet(); /// / } /// / /// / public int incrementActiveCountSafe() { /// / return this.activeCount.incrementAndGet(); /// / } /// / /// / public int getActiveCountSafe() { /// / return this.activeCount.get(); /// / } /// / /// / public int getTotalConnectionsSafe() { /// / return this.totalConnection.get(); /// / } /// / /// / public int decrementTotalConnectionsSafe() { /// / return this.totalConnection.decrementAndGet(); /// / } /// / /// / public int incrementTotalConnectionSafe() { /// / return this.totalConnection.incrementAndGet(); /// / } // // private void returnCon(BackendConnection c) { // // c.setAttachment(null); // c.setBorrowed(false); // c.setLastTime(TimeUtil.currentTimeMillis()); // ConQueue queue = this.conMap.getSchemaConQueue(c.getSchema()); // // boolean ok = false; // if (c.isAutocommit()) { // ok = queue.getAutoCommitCons().offer(c); // } else { // ok = queue.getManCommitCons().offer(c); // } // /// / if(c.getId() > 0 && takeConnectionContext.remove(c.getId(), TAKE_CONNECTION_FLAG) ) { /// / decrementActiveCountSafe(); /// / } // // if(!ok) { // LOGGER.warn("can't return to pool ,so close con " + c); // c.close("can't return to pool "); // // } // // } // // public void releaseChannel(BackendConnection c) { // if (LOGGER.isDebugEnabled()) { // LOGGER.debug("release channel " + c); // } // // release connection // returnCon(c); // } // // public void connectionClosed(BackendConnection conn) { // ConQueue queue = this.conMap.getSchemaConQueue(conn.getSchema()); // if (queue != null ) { // queue.removeCon(conn); // } // /// / decrementTotalConnectionsSafe(); // } // // /** // * 创建新连接 // */ // public abstract void createNewConnection(ResponseHandler handler, String schema) throws IOException; // // /** // * 测试连接,用于初始化及热更新配置检测 // */ // public abstract boolean testConnection(String schema) throws IOException; // // public long getHeartbeatRecoveryTime() { // return heartbeatRecoveryTime; // } // // public void setHeartbeatRecoveryTime(long heartbeatRecoveryTime) { // this.heartbeatRecoveryTime = heartbeatRecoveryTime; // } // // public DBHostConfig getConfig() { // return config; // } // // public boolean isAlive() { // return getHeartbeat().getStatus() == DBHeartbeat.OK_STATUS; // } // } implementation { TPhysicalDatasource } constructor TPhysicalDatasource.Create(Config: TDBHostConfig; HostConfig: TDataHostConfig; IsReadNode: Boolean); begin FConnHeartBeatHanler: TConnectionHeartBeatHandler = new ConnectionHeartBeatHandler(); end; end.
unit GLDDisk; interface uses Classes, GL, GLDTypes, GLDConst, GLDClasses, GLDObjects; type TGLDDisk = class(TGLDEditableObject) private FRadius: GLfloat; FSegments: GLushort; FSides: GLushort; FStartAngle: GLfloat; FSweepAngle: GLfloat; FPoints: PGLDVector3fArray; FNormals: PGLDVector3fArray; {$HINTS OFF} function GetMode: GLubyte; function GetPoint(i, j: GLushort): PGLDVector3f; function GetNormal(i, j: GLushort): PGLDVector3f; {$HINTS ON} procedure SetRadius(Value: GLfloat); procedure SetSegments(Value: GLushort); procedure SetSides(Value: GLushort); procedure SetStartAngle(Value: GLfloat); procedure SetSweepAngle(Value: GLfloat); function GetParams: TGLDDiskParams; procedure SetParams(Value: TGLDDiskParams); protected procedure CalcBoundingBox; override; procedure CreateGeometry; override; procedure DestroyGeometry; override; procedure DoRender; override; procedure SimpleRender; override; public constructor Create(AOwner: TPersistent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function SysClassType: TGLDSysClassType; override; class function VisualObjectClassType: TGLDVisualObjectClass; override; class function RealName: string; override; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; function CanConvertTo(_ClassType: TClass): GLboolean; override; function ConvertTo(Dest: TPersistent): GLboolean; override; function ConvertToTriMesh(Dest: TPersistent): GLboolean; function ConvertToQuadMesh(Dest: TPersistent): GLboolean; function ConvertToPolyMesh(Dest: TPersistent): GLboolean; property Params: TGLDDiskParams read GetParams write SetParams; published property Radius: GLfloat read FRadius write SetRadius; property Segments: GLushort read FSegments write SetSegments default GLD_DISK_SEGMENTS_DEFAULT; property Sides: GLushort read FSides write SetSides default GLD_DISK_SIDES_DEFAULT; property StartAngle: GLfloat read FStartAngle write SetStartAngle; property SweepAngle: GLfloat read FSweepAngle write SetSweepAngle; end; implementation uses SysUtils, GLDGizmos, GLDX, GLDMesh, GLDUtils; var vDiskCounter: GLuint = 0; constructor TGLDDisk.Create(AOwner: TPersistent); begin inherited Create(AOwner); Inc(vDiskCounter); FName := GLD_DISK_STR + IntToStr(vDiskCounter); FRadius := GLD_STD_DISKPARAMS.Radius; FSegments := GLD_STD_DISKPARAMS.Segments; FSides := GLD_STD_DISKPARAMS.Sides; FStartAngle := GLD_STD_DISKPARAMS.StartAngle; FSweepAngle := GLD_STD_DISKPARAMS.SweepAngle; FPosition.Vector3f := GLD_STD_PLANEPARAMS.Position; FRotation.Params := GLD_STD_PLANEPARAMS.Rotation; CreateGeometry; end; destructor TGLDDisk.Destroy; begin inherited Destroy; end; procedure TGLDDisk.Assign(Source: TPersistent); begin if (Source = nil) or (Source = Self) then Exit; inherited Assign(Source); if not (Source is TGLDDisk) then Exit; SetParams(TGLDDisk(Source).GetParams); end; procedure TGLDDisk.DoRender; var iSegs, iP: GLushort; begin for iSegs := 0 to FSegments - 1 do begin glBegin(GL_QUAD_STRIP); for iP := 2 to FSides + 2 do begin glNormal3fv(@FNormals^[iSegs * (FSides + 3) + iP]); glVertex3fv(@FPoints^[iSegs * (FSides + 3) + iP]); glNormal3fv(@FNormals^[(iSegs + 1) * (FSides + 3) + iP]); glVertex3fv(@FPoints^[(iSegs + 1) * (FSides + 3) + iP]); end; glEnd; end; end; procedure TGLDDisk.SimpleRender; var iSegs, iP: GLushort; begin for iSegs := 0 to FSegments - 1 do begin glBegin(GL_QUAD_STRIP); for iP := 2 to FSides + 2 do begin glVertex3fv(@FPoints^[iSegs * (FSides + 3) + iP]); glVertex3fv(@FPoints^[(iSegs + 1) * (FSides + 3) + iP]); end; glEnd; end; end; procedure TGLDDisk.CalcBoundingBox; begin FBoundingBox := GLDXCalcBoundingBox(FPoints, (FSegments + 1) * (FSides + 3)); end; procedure TGLDDisk.CreateGeometry; var iSegs, iP: GLint; A, R: GLfloat; begin if FSegments > 1000 then FSegments := 100 else if FSegments < 1 then FSegments := 1; if FSides > 1000 then FSides := 1000 else if FSides < 1 then FSides := 1; ReallocMem(FPoints, ((FSides + 3) * (FSegments + 1)) * SizeOf(TGLDVector3f)); ReallocMem(FNormals, ((FSides + 3) * (FSegments + 1)) * SizeOf(TGLDVector3f)); A := GLDXGetAngleStep(FStartAngle, FSweepAngle, FSides); R := FRadius / FSegments; for iSegs := 0 to FSegments do for iP := 1 to FSides + 3 do begin FPoints^[iSegs * (FSides + 3) + iP] := GLDXVector3f( GLDXCoSinus(FStartAngle + (iP - 2) * A) * iSegs * R, 0, -GLDXSinus(FStartAngle + (iP - 2) * A) * iSegs * R); end; FModifyList.ModifyPoints( [GLDXVector3fArrayData(FPoints, (FSides + 3) * (FSegments + 1))]); GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f( GLDXVector3fArrayData(FPoints, (FSegments + 1) * (FSides + 3)), GLDXVector3fArrayData(FNormals, (FSegments + 1) * (FSides + 3)), FSegments, FSides + 2)); CalcBoundingBox; end; procedure TGLDDisk.DestroyGeometry; begin if FPoints <> nil then ReallocMem(FPoints, 0); FPoints := nil; if FNormals <> nil then ReallocMem(FNormals, 0); FNormals := nil; end; class function TGLDDisk.SysClassType: TGLDSysClassType; begin Result := GLD_SYSCLASS_DISK; end; class function TGLDDisk.VisualObjectClassType: TGLDVisualObjectClass; begin Result := TGLDDisk; end; class function TGLDDisk.RealName: string; begin Result := GLD_DISK_STR; end; procedure TGLDDisk.LoadFromStream(Stream: TStream); begin inherited LoadFromStream(Stream); Stream.Read(FRadius, SizeOf(GLfloat)); Stream.Read(FSegments, SizeOf(GLushort)); Stream.Read(FSides, SizeOf(GLushort)); Stream.Read(FStartAngle, SizeOf(GLfloat)); Stream.Read(FSweepAngle, SizeOf(GLfloat)); CreateGeometry; end; procedure TGLDDisk.SaveToStream(Stream: TStream); begin inherited SaveToStream(Stream); Stream.Write(FRadius, SizeOf(GLfloat)); Stream.Write(FSegments, SizeOf(GLushort)); Stream.Write(FSides, SizeOf(GLushort)); Stream.Write(FStartAngle, SizeOf(GLfloat)); Stream.Write(FSweepAngle, SizeOf(GLfloat)); end; function TGLDDisk.CanConvertTo(_ClassType: TClass): GLboolean; begin Result := (_ClassType = TGLDDisk) or (_ClassType = TGLDTriMesh) or (_ClassType = TGLDQuadMesh) or (_ClassType = TGLDPolyMesh); end; {$WARNINGS OFF} function TGLDDisk.ConvertTo(Dest: TPersistent): GLboolean; begin Result := False; if not Assigned(Dest) then Exit; if Dest.ClassType = Self.ClassType then begin Dest.Assign(Self); Result := True; end else if Dest is TGLDTriMesh then Result := ConvertToTriMesh(Dest) else if Dest is TGLDQuadMesh then Result := ConvertToQuadMesh(Dest) else if Dest is TGLDPolyMesh then Result := ConvertToPolyMesh(Dest); end; function TGLDDisk.ConvertToTriMesh(Dest: TPersistent): GLboolean; var M: GLubyte; i, j: GLushort; F: TGLDTriFace; begin Result := False; if not Assigned(Dest) then Exit; if not (Dest is TGLDTriMesh) then Exit; M := GetMode; with TGLDTriMesh(Dest) do begin DeleteVertices; case M of 0: VertexCapacity := FSides * FSegments + 1; 1: VertexCapacity := (FSides + 1) * FSegments + 1; end; F.Smoothing := GLD_SMOOTH_ALL; if M = 0 then begin AddVertex(GetPoint(1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; F.Point2 := j + 1; if j = FSides then F.Point3 := 2 else F.Point3 := j + 2; AddFace(F); end; if FSegments > 1 then begin for i := 0 to FSegments - 2 do for j := 1 to FSides do begin F.Point1 := 1 + i * FSides + j; F.Point2 := 1 + (i + 1) * FSides + j; if j = FSides then F.Point3 := 1 + i * FSides + 1 else F.Point3 := 1 + i * FSides + j + 1; AddFace(F); F.Point2 := 1 + (i + 1) * FSides + j; if j = FSides then begin F.Point1 := 1 + i * FSides + 1; F.Point3 := 1 + (i + 1) * FSides + 1; end else begin F.Point1 := 1 + i * FSides + j + 1; F.Point3 := 1 + (i + 1) * FSides + j + 1; end; AddFace(F); end; end; end else if M = 1 then begin AddVertex(GetPoint(1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides + 1 do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; F.Point2 := 1 + j; F.Point3 := 1 + j + 1; AddFace(F); end; if FSegments > 1 then begin for i := 0 to FSegments - 2 do for j := 1 to FSides do begin F.Point1 := 1 + i * (FSides + 1) + j; F.Point2 := 1 + (i + 1) * (FSides + 1) + j; F.Point3 := 1 + i * (FSides + 1) + j + 1; AddFace(F); F.Point1 := 1 + i * (FSides + 1) + j + 1; F.Point2 := 1 + (i + 1) * (FSides + 1) + j; F.Point3 := 1 + (i + 1) * (FSides + 1) + j + 1; AddFace(F); end; end; end; CalcNormals; CalcBoundingBox; PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f; PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f; TGLDTriMesh(Dest).Selected := Self.Selected; TGLDTriMesh(Dest).Name := Self.Name; end; Result := True; end; function TGLDDisk.ConvertToQuadMesh(Dest: TPersistent): GLboolean; var M: GLubyte; i, j: GLushort; F: TGLDQuadFace; begin Result := False; if not Assigned(Dest) then Exit; if not (Dest is TGLDQuadMesh) then Exit; M := GetMode; with TGLDQuadMesh(Dest) do begin DeleteVertices; case M of 0: VertexCapacity := FSides * FSegments + 1; 1: VertexCapacity := (FSides + 1) * FSegments + 1; end; F.Smoothing := GLD_SMOOTH_ALL; if M = 0 then begin AddVertex(GetPoint(1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; F.Point2 := j + 1; if j = FSides then F.Point3 := 2 else F.Point3 := j + 2; F.Point4 := F.Point1; AddFace(F); end; if FSegments > 1 then begin for i := 0 to FSegments - 2 do for j := 1 to FSides do begin F.Point1 := 1 + i * FSides + j; F.Point2 := 1 + (i + 1) * FSides + j; if j = FSides then begin F.Point3 := 1 + (i + 1) * FSides + 1; F.Point4 := 1 + i * FSides + 1; end else begin F.Point3 := 1 + (i + 1) * FSides + j + 1; F.Point4 := 1 + i * FSides + j + 1; end; AddFace(F); end; end; end else if M = 1 then begin AddVertex(GetPoint(1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides + 1 do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin F.Point1 := 1; F.Point2 := 1 + j; F.Point3 := 1 + j + 1; F.Point4 := F.Point1; AddFace(F); end; if FSegments > 1 then begin for i := 0 to FSegments - 2 do for j := 1 to FSides do begin F.Point1 := 1 + i * (FSides + 1) + j; F.Point2 := 1 + (i + 1) * (FSides + 1) + j; F.Point3 := 1 + (i + 1) * (FSides + 1) + j + 1; F.Point4 := 1 + i * (FSides + 1) + j + 1; AddFace(F); end; end; end; CalcNormals; CalcBoundingBox; PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f; PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f; TGLDQuadMesh(Dest).Selected := Self.Selected; TGLDQuadMesh(Dest).Name := Self.Name; end; Result := True; end; function TGLDDisk.ConvertToPolyMesh(Dest: TPersistent): GLboolean; var M: GLubyte; i, j: GLushort; P: TGLDPolygon; begin Result := False; if not Assigned(Dest) then Exit; if not (Dest is TGLDPolyMesh) then Exit; M := GetMode; with TGLDPolyMesh(Dest) do begin DeleteVertices; case M of 0: VertexCapacity := FSides * FSegments + 1; 1: VertexCapacity := (FSides + 1) * FSegments + 1; end; if M = 0 then begin AddVertex(GetPoint(1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 3); P.Data^[1] := 1; P.Data^[2] := j + 1; if j = FSides then P.Data^[3] := 2 else P.Data^[3] := j + 2; //P.Data^[4] := P.Data^[1] AddFace(P); end; if FSegments > 1 then begin for i := 0 to FSegments - 2 do for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 4); P.Data^[1] := 1 + i * FSides + j; P.Data^[2] := 1 + (i + 1) * FSides + j; if j = FSides then begin P.Data^[3] := 1 + (i + 1) * FSides + 1; P.Data^[4] := 1 + i * FSides + 1; end else begin P.Data^[3] := 1 + (i + 1) * FSides + j + 1; P.Data^[4] := 1 + i * FSides + j + 1; end; AddFace(P); end; end; end else if M = 1 then begin AddVertex(GetPoint(1, 1)^, True); for i := 1 to FSegments do for j := 1 to FSides + 1 do AddVertex(GetPoint(i + 1, j)^, True); for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 3); P.Data^[1] := 1; P.Data^[2] := 1 + j; P.Data^[3] := 1 + j + 1; //F.Point4 := F.Point1; AddFace(P); end; if FSegments > 1 then begin for i := 0 to FSegments - 2 do for j := 1 to FSides do begin P := GLD_STD_POLYGON; GLDURealloc(P, 4); P.Data^[1] := 1 + i * (FSides + 1) + j; P.Data^[2] := 1 + (i + 1) * (FSides + 1) + j; P.Data^[3] := 1 + (i + 1) * (FSides + 1) + j + 1; P.Data^[4] := 1 + i * (FSides + 1) + j + 1; AddFace(P); end; end; end; CalcNormals; CalcBoundingBox; PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f; PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f; PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params; TGLDPolyMesh(Dest).Selected := Self.Selected; TGLDPolyMesh(Dest).Name := Self.Name; end; Result := True; end; {$WARNINGS ON} function TGLDDisk.GetMode: GLubyte; begin if GLDXGetAngle(FStartAngle, FSweepAngle) = 360 then Result := 0 else Result := 1; end; function TGLDDisk.GetPoint(i, j: GLushort): PGLDVector3f; begin Result := @FPoints^[(i - 1) * (FSides + 3) + j + 1]; end; function TGLDDisk.GetNormal(i, j: GLushort): PGLDVector3f; begin Result := @FPoints^[(i - 1) * (FSides + 3) + j + 1]; end; procedure TGLDDisk.SetRadius(Value: GLfloat); begin if FRadius = Value then Exit; FRadius := Value; CreateGeometry; Change; end; procedure TGLDDisk.SetSegments(Value: GLushort); begin if FSegments = Value then Exit; FSegments := Value; CreateGeometry; Change; end; procedure TGLDDisk.SetSides(Value: GLushort); begin if FSides = Value then Exit; FSides := Value; CreateGeometry; Change; end; procedure TGLDDisk.SetStartAngle(Value: GLfloat); begin if FStartAngle = Value then Exit; FStartAngle := Value; CreateGeometry; Change; end; procedure TGLDDisk.SetSweepAngle(Value: GLfloat); begin if FSweepAngle = Value then Exit; FSweepAngle := Value; CreateGeometry; Change; end; function TGLDDisk.GetParams: TGLDDiskParams; begin Result := GLDXDiskParams(FColor.Color3ub, FRadius, FSegments, FSides, FStartAngle, FSweepAngle, FPosition.Vector3f, FRotation.Params); end; procedure TGLDDisk.SetParams(Value: TGLDDiskParams); begin if GLDXDiskParamsEqual(GetParams, Value) then Exit; PGLDColor3f(FColor.GetPointer)^ := GLDXColor3f(Value.Color); FRadius := Value.Radius; FSegments := Value.Segments; FSides := Value.Sides; FStartAngle := Value.StartAngle; FSweepAngle := Value.SweepAngle; PGLDVector3f(FPosition.GetPointer)^ := Value.Position; PGLDRotation3D(FRotation.GetPointer)^ := Value.Rotation; CreateGeometry; Change; end; end.
library thrlib; {$mode objfpc}{$H+} uses SysUtils, DateUtils, {Windows,} syncobjs, svm in '..\svm.pas'; {type TMashCriticalSection = class public lock_flag: cardinal; constructor Create; procedure Enter; function TryEnter: boolean; procedure Leave; end; constructor TMashCriticalSection.Create; begin lock_flag := 0; end; procedure TMashCriticalSection.Enter; begin while System.InterlockedCompareExchange(lock_flag, 1, 0) = 1 do sleep(1); end; function TMashCriticalSection.TryEnter: boolean; begin Result := System.InterlockedCompareExchange(lock_flag, 1, 0) = 0; end; procedure TMashCriticalSection.Leave; begin System.InterlockedCompareExchange(lock_flag, 0, 1); end;} type TMashCriticalSection = class public cs: TCriticalSection; constructor Create; destructor Destroy; override; procedure Enter; function TryEnter: boolean; procedure Leave; end; constructor TMashCriticalSection.Create; begin cs := TCriticalSection.Create; end; destructor TMashCriticalSection.Destroy; begin FreeAndNil(cs); inherited; end; procedure TMashCriticalSection.Enter; begin cs.Acquire; end; function TMashCriticalSection.TryEnter: boolean; begin Result := cs.TryEnter; end; procedure TMashCriticalSection.Leave; begin cs.Leave; end; procedure CRITSECT_DESTRUCTOR(pCritSect: pointer); stdcall; begin TMashCriticalSection(pCritSect).Free; end; procedure CRITSECT_CREATE(pctx: pointer); stdcall; begin __Return_Ref(pctx, TMashCriticalSection.Create, @CRITSECT_DESTRUCTOR); end; procedure CRITSECT_ENTER(pctx: pointer); stdcall; begin TMashCriticalSection(__Next_Ref(pctx)).Enter; end; procedure CRITSECT_LEAVE(pctx: pointer); stdcall; begin TMashCriticalSection(__Next_Ref(pctx)).Leave; end; procedure CRITSECT_TRYENTER(pctx: pointer); stdcall; begin __Return_Bool(pctx, TMashCriticalSection(__Next_Ref(pctx)).TryEnter); end; {EXPORTS DB} exports CRITSECT_CREATE name 'CRITICAL_SECTION_CREATE'; exports CRITSECT_ENTER name 'CRITICAL_SECTION_ENTER'; exports CRITSECT_LEAVE name 'CRITICAL_SECTION_LEAVE'; exports CRITSECT_TRYENTER name 'CRITICAL_SECTION_TRYENTER'; begin end.
(****************************************************************************** * * * File: lua54.pas * * * * Authors: TeCGraf (C headers + actual Lua libraries) * * Lavergne Thomas (original translation to Pascal) * * Bram Kuijvenhoven (update to Lua 5.1.1 for FreePascal) * * Egor Skriptunoff (update to Lua 5.2.1 for FreePascal) * * Vladimir Klimov (Delphi compatibility) * * Malcome@Japan (update to Lua 5.4.0 for FreePascal) * * * * Description: Basic Lua library * * Lua auxiliary library * * Standard Lua libraries * * This is 3-in-1 replacement for FPC modules lua.pas,lauxlib.pas,lualib.pas * * * ******************************************************************************) (* ** $Id: lua.h,v 1.325 2014/12/26 17:24:27 roberto Exp $ ** $Id: lauxlib.h,v 1.128 2014/10/29 16:11:17 roberto Exp $ ** $Id: lualib.h,v 1.44 2014/02/06 17:32:33 roberto Exp $ ** Lua - A Scripting Language ** Lua.org, PUC-Rio, Brazil (http://www.lua.org) ** See Copyright Notice at the end of this file *) (* ** Translated to pascal by Lavergne Thomas ** Notes : ** - Pointers type was prefixed with 'P' ** - lua_upvalueindex constant was transformed to function ** - Some compatibility function was isolated because with it you must have ** lualib. ** - LUA_VERSION was suffixed by '_' for avoiding name collision. ** Bug reports : ** - thomas.lavergne@laposte.net ** In french or in english *) (* ** Updated to Lua 5.1.1 by Bram Kuijvenhoven (bram at kuijvenhoven dot net), ** Hexis BV (http://www.hexis.nl), the Netherlands ** Notes: ** - Only tested with FPC (FreePascal Compiler) ** - Using LuaBinaries styled DLL/SO names, which include version names ** - LUA_YIELD was suffixed by '_' for avoiding name collision *) (* ** Updated to Lua 5.2.1 by Egor Skriptunoff ** Notes: ** - Only tested with FPC (FreePascal Compiler) ** - Functions dealing with luaL_Reg were overloaded to accept pointer ** or open array parameter. In any case, do not forget to terminate ** your array with "sentinel". ** - All floating-point exceptions were forcibly disabled in Windows ** to overcome well-known bug ** Bug reports: ** - egor.skriptunoff at gmail.com ** In russian or in english *) (* ** Delphi compatibility by Vladimir Klimov ** Notes: ** - fixed luaL_error syntax ** - PChar replaced with PAnsiChar, String with AnsiString due to since ** D2009 both PChar and String are unicode ** Bug reports: ** - wintarif@narod.ru ** russian or english *) (* ** Updated to Lua 5.4.0 by Malcome@Japan ** Notes: ** - Only tested with FPC (FreePascal Compiler) ** - Needs Delphi with Int64 supported. *) //-------------------------- // What was not translated: //-------------------------- // macro // #define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) // Generic Buffer manipulation functions and macros were not translated. // They are not required in Pascal programs due to powerful String type. // luaL_addchar, luaL_addsize, luaL_buffinit, luaL_prepbuffsize, // luaL_addlstring, luaL_addstring, luaL_addvalue, luaL_pushresult, // luaL_pushresultsize, luaL_buffinitsize, luaL_prepbuffer // Functions defined with LUA_COMPAT_MODULE are deprecated. // They were translated but commented intentionally. // Uncomment them if you really need. // luaL_pushmodule, luaL_openlib, luaL_register {$IFDEF FPC}{$MODE OBJFPC}{$H+}{$ENDIF} unit lua54; interface const {$IFDEF MSWINDOWS} LUA_LIB_NAME = 'lua54.dll'; {$ELSE} LUA_LIB_NAME = 'liblua54.so'; {$ENDIF} const LUA_VERSION_MAJOR = '5'; LUA_VERSION_MINOR = '4'; LUA_VERSION_RELEASE = '0'; LUA_VERSION_NUM = 504; LUA_VERSION_RELEASE_NUM = LUA_VERSION_NUM * 100 + 0; LUA_VERSION_ = 'Lua ' + LUA_VERSION_MAJOR + '.' + LUA_VERSION_MINOR; // LUA_VERSION was suffixed by '_' for avoiding name collision LUA_RELEASE = LUA_VERSION_ + '.' + LUA_VERSION_RELEASE; LUA_COPYRIGHT = LUA_RELEASE + ' Copyright (C) 1994-2015 Lua.org, PUC-Rio'; LUA_AUTHORS = 'R. Ierusalimschy, L. H. de Figueiredo, W. Celes'; LUA_SIGNATURE = #27'Lua'; // mark for precompiled code '<esc>Lua' LUA_MULTRET = -1; // option for multiple returns in 'lua_pcall' and 'lua_call' // pseudo-indices LUA_REGISTRYINDEX = -1001000; function lua_upvalueindex(I: Integer): Integer; inline; // thread status const LUA_OK = 0; LUA_YIELD_ = 1; // LUA_YIELD was suffixed by '_' for avoiding name collision LUA_ERRRUN = 2; LUA_ERRSYNTAX = 3; LUA_ERRMEM = 4; LUA_ERRERR = 5; LUA_ERRFILE = LUA_ERRERR + 1; // extra error code for `luaL_load' type // Type of Numbers in Lua {$IFDEF FPC} lua_Integer = Int64; lua_Unsigned = UInt64; {$ELSE} // Delphi {$IF CompilerVersion < 18} lua_Integer = Int64; lua_Unsigned = Int64; {$ELSE} lua_Integer = Int64; lua_Unsigned = UInt64; {$IFEND} {$ENDIF} Plua_Integer = ^lua_Integer; Plua_Unsigned = ^lua_Unsigned; lua_Number = Double; Plua_Number = ^lua_Number; size_t = Cardinal; Psize_t = ^size_t; Plua_State = Pointer; // type for continuation-function contexts lua_KContext = Pointer; lua_CFunction = function(L: Plua_State): Integer; cdecl; // Type for continuation functions lua_KFunction = function(L: Plua_State; status: Integer; ctx: lua_KContext): Integer; cdecl; // functions that read/write blocks when loading/dumping Lua chunks lua_Reader = function(L: Plua_State; ud: Pointer; sz: Psize_t): PAnsiChar; cdecl; lua_Writer = function(L: Plua_State; const p: Pointer; sz: size_t; ud: Pointer): Integer; cdecl; // prototype for memory-allocation functions lua_Alloc = function(ud, ptr: Pointer; osize, nsize: size_t): Pointer; cdecl; // Type for warning functions lua_WarnFunction = procedure(ud: Pointer; msg: PAnsiChar; tocont: Integer); cdecl; const // basic types LUA_TNONE = -1; LUA_TNIL = 0; LUA_TBOOLEAN = 1; LUA_TLIGHTUSERDATA = 2; LUA_TNUMBER = 3; LUA_TSTRING = 4; LUA_TTABLE = 5; LUA_TFUNCTION = 6; LUA_TUSERDATA = 7; LUA_TTHREAD = 8; LUA_NUMTYPES = 9; // minimum Lua stack available to a C function LUA_MINSTACK = 20; // predefined values in the registry */ LUA_RIDX_MAINTHREAD = 1; LUA_RIDX_GLOBALS = 2; LUA_RIDX_LAST = LUA_RIDX_GLOBALS; // state manipulation function lua_newstate(f: lua_Alloc; ud: Pointer): Plua_state; cdecl; procedure lua_close(L: Plua_State); cdecl; function lua_newthread(L: Plua_State): Plua_State; cdecl; function lua_resetthread(L: Plua_State): Integer; cdecl; function lua_atpanic(L: Plua_State; panicf: lua_CFunction): lua_CFunction; cdecl; function lua_version(L: Plua_State): lua_Number; cdecl; // basic stack manipulation function lua_absindex(L: Plua_State; idx: Integer): Integer; cdecl; function lua_gettop(L: Plua_State): Integer; cdecl; procedure lua_settop(L: Plua_State; idx: Integer); cdecl; procedure lua_pushvalue(L: Plua_State; Idx: Integer); cdecl; procedure lua_rotate(L: Plua_State; idx, n: Integer); cdecl; procedure lua_remove(L: Plua_State; idx: Integer); inline; procedure lua_insert(L: Plua_State; idx: Integer); inline; procedure lua_replace(L: Plua_State; idx: Integer); inline; procedure lua_copy(L: Plua_State; fromidx, toidx: Integer); cdecl; function lua_checkstack(L: Plua_State; n: Integer): LongBool; cdecl; procedure lua_xmove(from, to_: Plua_State; n: Integer); cdecl; // access functions (stack -> C) function lua_isnumber(L: Plua_State; idx: Integer): LongBool; cdecl; function lua_isstring(L: Plua_State; idx: Integer): LongBool; cdecl; function lua_iscfunction(L: Plua_State; idx: Integer): LongBool; cdecl; function lua_isinteger(L: Plua_State; idx: Integer): LongBool; cdecl; function lua_isuserdata(L: Plua_State; idx: Integer): LongBool; cdecl; function lua_type(L: Plua_State; idx: Integer): Integer; cdecl; function lua_typename(L: Plua_State; tp: Integer): PAnsiChar; cdecl; function lua_tonumberx(L: Plua_State; idx: Integer; isnum: PLongBool): lua_Number; cdecl; function lua_tointegerx(L: Plua_State; idx: Integer; isnum: PLongBool): lua_Integer; cdecl; function lua_toboolean(L: Plua_State; idx: Integer): LongBool; cdecl; function lua_tolstring(L: Plua_State; idx: Integer; len: Psize_t): PAnsiChar; cdecl; function lua_rawlen(L: Plua_State; idx: Integer): lua_Unsigned; cdecl; function lua_tocfunction(L: Plua_State; idx: Integer): lua_CFunction; cdecl; function lua_touserdata(L: Plua_State; idx: Integer): Pointer; cdecl; function lua_tothread(L: Plua_State; idx: Integer): Plua_State; cdecl; function lua_topointer(L: Plua_State; idx: Integer): Pointer; cdecl; // Arithmetic functions const LUA_OPADD = 0; (* ORDER TM, ORDER OP *) LUA_OPSUB = 1; LUA_OPMUL = 2; LUA_OPMOD = 3; LUA_OPPOW = 4; LUA_OPDIV = 5; LUA_OPIDIV = 6; LUA_OPBAND = 7; LUA_OPBOR = 8; LUA_OPBXOR = 9; LUA_OPSHL = 10; LUA_OPSHR = 11; LUA_OPUNM = 12; LUA_OPBNOT = 13; procedure lua_arith(L: Plua_State; op: Integer); cdecl; // Comparison functions const LUA_OPEQ = 0; LUA_OPLT = 1; LUA_OPLE = 2; function lua_rawequal(L: Plua_State; idx1, idx2: Integer): LongBool; cdecl; function lua_compare(L: Plua_State; idx1, idx2, op: Integer): LongBool; cdecl; // push functions (C -> stack) procedure lua_pushnil(L: Plua_State); cdecl; procedure lua_pushnumber(L: Plua_State; n: lua_Number); cdecl; procedure lua_pushinteger(L: Plua_State; n: lua_Integer); cdecl; procedure lua_pushlstring(L: Plua_State; const s: PAnsiChar; len: size_t); cdecl; procedure lua_pushstring(L: Plua_State; const s: PAnsiChar); cdecl; overload; procedure lua_pushstring(L: Plua_State; const s: AnsiString); inline; overload; // added for Pascal function lua_pushvfstring(L: Plua_State; const fmt: PAnsiChar; argp: Pointer): PAnsiChar; cdecl; function lua_pushfstring(L: Plua_State; const fmt: PAnsiChar): PAnsiChar; cdecl; varargs; procedure lua_pushcclosure(L: Plua_State; fn: lua_CFunction; n: Integer); cdecl; procedure lua_pushboolean(L: Plua_State; b: LongBool); cdecl; procedure lua_pushlightuserdata(L: Plua_State; p: Pointer); cdecl; procedure lua_pushthread(L: Plua_State); cdecl; // get functions (Lua -> stack) function lua_getglobal(L: Plua_State; const name: PAnsiChar): Integer; cdecl; function lua_gettable(L: Plua_State; idx: Integer): Integer; cdecl; function lua_getfield(L: Plua_state; idx: Integer; k: PAnsiChar): Integer; cdecl; function lua_geti(L: Plua_State; idx: Integer; n: lua_Integer): Integer cdecl; function lua_rawget(L: Plua_State; idx: Integer): Integer; cdecl; function lua_rawgeti(L: Plua_State; idx: Integer; n: lua_Integer): Integer; cdecl; function lua_rawgetp(L: Plua_State; idx: Integer; p: Pointer): Integer; cdecl; procedure lua_createtable(L: Plua_State; narr, nrec: Integer); cdecl; function lua_newuserdatauv(L: Plua_State; sz: size_t; nuvalue: Integer): Pointer; cdecl; function lua_getmetatable(L: Plua_State; objindex: Integer): Integer; cdecl; function lua_getiuservalue(L: Plua_State; idx, n: Integer): Integer; cdecl; // set functions (stack -> Lua) procedure lua_setglobal(L: Plua_State; const name: PAnsiChar); cdecl; procedure lua_settable(L: Plua_State; idx: Integer); cdecl; procedure lua_setfield(L: Plua_State; idx: Integer; k: PAnsiChar); cdecl; procedure lua_seti(L: Plua_State; idx: Integer; n: lua_Integer); cdecl; procedure lua_rawset(L: Plua_State; idx: Integer); cdecl; procedure lua_rawseti(L: Plua_State; idx: Integer; n: lua_Integer); cdecl; procedure lua_rawsetp(L: Plua_State; idx: Integer; p: Pointer); cdecl; function lua_setmetatable(L: Plua_State; objindex: Integer): Integer; cdecl; function lua_setiuservalue(L: Plua_State; idx, n: Integer): Integer; cdecl; // 'load' and 'call' functions (load and run Lua code) procedure lua_callk(L: Plua_State; nargs, nresults: Integer; ctx: lua_KContext; k: lua_KFunction); cdecl; procedure lua_call(L: Plua_State; nargs, nresults: Integer); inline; function lua_pcallk(L: Plua_State; nargs, nresults, errfunc: Integer; ctx: lua_KContext; k: lua_KFunction): Integer; cdecl; function lua_pcall(L: Plua_State; nargs, nresults, errf: Integer): Integer; inline; function lua_load(L: Plua_State; reader: lua_Reader; dt: Pointer; const chunkname, mode: PAnsiChar): Integer; cdecl; function lua_dump(L: Plua_State; writer: lua_Writer; data: Pointer; strip: Integer): Integer; cdecl; // coroutine functions function lua_yieldk(L: Plua_State; nresults: Integer; ctx: lua_KContext; k: lua_KFunction): Integer; cdecl; function lua_yield(L: Plua_State; nresults: Integer): Integer; inline; function lua_resume(L, from: Plua_State; narg: Integer; nres: PInteger): Integer; cdecl; function lua_status(L: Plua_State): Integer; cdecl; function lua_isyieldable(L: Plua_State): LongBool; cdecl; // Warning-related functions procedure lua_setwarnf(L: Plua_State; f: lua_WarnFunction; ud: Pointer); cdecl; procedure lua_warning(L: Plua_State; msg: PAnsiChar; tocont: Integer); cdecl; // garbage-collection function and options const LUA_GCSTOP = 0; LUA_GCRESTART = 1; LUA_GCCOLLECT = 2; LUA_GCCOUNT = 3; LUA_GCCOUNTB = 4; LUA_GCSTEP = 5; LUA_GCSETPAUSE = 6; LUA_GCSETSTEPMUL = 7; LUA_GCISRUNNING = 9; LUA_GCGEN = 10; LUA_GCINC = 11; function lua_gc(L: Plua_State; what: Integer): Integer; cdecl; varargs; // miscellaneous functions function lua_error(L: Plua_State): Integer; cdecl; function lua_next(L: Plua_State; idx: Integer): Integer; cdecl; procedure lua_concat(L: Plua_State; n: Integer); cdecl; procedure lua_len(L: Plua_State; idx: Integer); cdecl; function lua_stringtonumber(L: Plua_State; const s: PAnsiChar): size_t; cdecl; function lua_getallocf(L: Plua_State; ud: PPointer): lua_Alloc; cdecl; procedure lua_setallocf(L: Plua_State; f: lua_Alloc; ud: Pointer); cdecl; procedure lua_toclose(L: Plua_State; idx: Integer); cdecl; // some useful macros function lua_getextraspace(L: Plua_State): Pointer; inline; function lua_tonumber(L: Plua_State; idx: Integer): lua_Number; inline; function lua_tointeger(L: Plua_State; idx: Integer): lua_Integer; inline; procedure lua_pop(L: Plua_State; n: Integer); inline; procedure lua_newtable(L: Plua_state); inline; procedure lua_register(L: Plua_State; const n: PAnsiChar; f: lua_CFunction); inline; procedure lua_pushcfunction(L: Plua_State; f: lua_CFunction); inline; function lua_isfunction(L: Plua_State; n: Integer): Boolean; inline; function lua_istable(L: Plua_State; n: Integer): Boolean; inline; function lua_islightuserdata(L: Plua_State; n: Integer): Boolean; inline; function lua_isnil(L: Plua_State; n: Integer): Boolean; inline; function lua_isboolean(L: Plua_State; n: Integer): Boolean; inline; function lua_isthread(L: Plua_State; n: Integer): Boolean; inline; function lua_isnone(L: Plua_State; n: Integer): Boolean; inline; function lua_isnoneornil(L: Plua_State; n: Integer): Boolean; inline; procedure lua_pushliteral(L: Plua_State; s: PAnsiChar); inline; procedure lua_pushglobaltable(L: Plua_State); inline; function lua_tostring(L: Plua_State; i: Integer): PAnsiChar; inline; // compatibility macros function lua_newuserdata(L: Plua_State; sz: size_t): Pointer; inline; function lua_getuservalue(L: Plua_State; idx: Integer): Integer; inline; function lua_setuservalue(L: Plua_State; idx: Integer): Integer; inline; const LUA_NUMTAGS = LUA_NUMTYPES; // Debug API const // Event codes LUA_HOOKCALL = 0; LUA_HOOKRET = 1; LUA_HOOKLINE = 2; LUA_HOOKCOUNT = 3; LUA_HOOKTAILCALL = 4; // Event masks LUA_MASKCALL = 1 shl Ord(LUA_HOOKCALL); LUA_MASKRET = 1 shl Ord(LUA_HOOKRET); LUA_MASKLINE = 1 shl Ord(LUA_HOOKLINE); LUA_MASKCOUNT = 1 shl Ord(LUA_HOOKCOUNT); LUA_IDSIZE = 60; type lua_Debug = packed record (* activation record *) event: Integer; name: PAnsiChar; (* (n) *) namewhat: PAnsiChar; (* (n) `global', `local', `field', `method' *) what: PAnsiChar; (* (S) `Lua', `C', `main', `tail'*) source: PAnsiChar; (* (S) *) srclen: size_t; (* (S) *) currentline: Integer; (* (l) *) linedefined: Integer; (* (S) *) lastlinedefined: Integer; (* (S) *) nups: Byte; (* (u) number of upvalues *) nparams: Byte; (* (u) number of parameters *) isvararg: ByteBool; (* (u) *) istailcall: ByteBool; (* (t) *) ftransfer: Word; (* (r) index of first value transferred *) ntransfer: Word; (* (r) number of transferred values *) short_src: packed array[0..LUA_IDSIZE - 1] of AnsiChar; (* (S) *) (* private part *) i_ci: Pointer; (* active function *) // ptr to struct CallInfo end; Plua_Debug = ^lua_Debug; // Functions to be called by the debugger in specific events lua_Hook = procedure(L: Plua_State; ar: Plua_Debug); cdecl; function lua_getstack(L: Plua_State; level: Integer; ar: Plua_Debug): Integer; cdecl; function lua_getinfo(L: Plua_State; const what: PAnsiChar; ar: Plua_Debug): Integer; cdecl; function lua_getlocal(L: Plua_State; const ar: Plua_Debug; n: Integer): PAnsiChar; cdecl; function lua_setlocal(L: Plua_State; const ar: Plua_Debug; n: Integer): PAnsiChar; cdecl; function lua_getupvalue(L: Plua_State; funcindex, n: Integer): PAnsiChar; cdecl; function lua_setupvalue(L: Plua_State; funcindex, n: Integer): PAnsiChar; cdecl; function lua_upvalueid(L: Plua_State; funcindex, n: Integer): Pointer; cdecl; procedure lua_upvaluejoin(L: Plua_State; funcindex1, n1, funcindex2, n2: Integer); cdecl; procedure lua_sethook(L: Plua_State; func: lua_Hook; mask: Integer; count: Integer); cdecl; function lua_gethook(L: Plua_State): lua_Hook; cdecl; function lua_gethookmask(L: Plua_State): Integer; cdecl; function lua_gethookcount(L: Plua_State): Integer; cdecl; function lua_setcstacklimit(L: Plua_State; limit: Cardinal): Integer; cdecl; // pre-defined references const LUA_NOREF = -2; LUA_REFNIL = -1; LUAL_NUMSIZES = sizeof(lua_Integer)*16 + sizeof(lua_Number); type luaL_Reg = packed record name: PAnsiChar; func: lua_CFunction; end; PluaL_Reg = ^luaL_Reg; procedure luaL_checkversion_(L: Plua_State; ver: lua_Number; sz: size_t); cdecl; procedure luaL_checkversion(L: Plua_State); inline; function luaL_getmetafield(L: Plua_State; obj: Integer; const e: PAnsiChar): Integer; cdecl; function luaL_callmeta(L: Plua_State; obj: Integer; const e: PAnsiChar): Integer; cdecl; function luaL_tolstring(L: Plua_State; idx: Integer; len: Psize_t): PAnsiChar; cdecl; function luaL_argerror(L: Plua_State; arg: Integer; const extramsg: PAnsiChar): Integer; cdecl; function luaL_typeerror(L: Plua_State; arg: Integer; tname: PAnsiChar): Integer; cdecl; function luaL_checklstring(L: Plua_State; arg: Integer; l_: Psize_t): PAnsiChar; cdecl; function luaL_optlstring(L: Plua_State; arg: Integer; const def: PAnsiChar; l_: Psize_t): PAnsiChar; cdecl; function luaL_checknumber(L: Plua_State; arg: Integer): lua_Number; cdecl; function luaL_optnumber(L: Plua_State; arg: Integer; def: lua_Number): lua_Number; cdecl; function luaL_checkinteger(L: Plua_State; arg: Integer): lua_Integer; cdecl; function luaL_optinteger(L: Plua_State; arg: Integer; def: lua_Integer): lua_Integer; cdecl; procedure luaL_checkstack(L: Plua_State; sz: Integer; const msg: PAnsiChar); cdecl; procedure luaL_checktype(L: Plua_State; arg, t: Integer); cdecl; procedure luaL_checkany(L: Plua_State; arg: Integer); cdecl; function luaL_newmetatable(L: Plua_State; const tname: PAnsiChar): Integer; cdecl; procedure luaL_setmetatable(L: Plua_State; const tname: PAnsiChar); cdecl; function luaL_testudata(L: Plua_State; ud: Integer; const tname: PAnsiChar): Pointer; cdecl; function luaL_checkudata(L: Plua_State; ud: Integer; const tname: PAnsiChar): Pointer; cdecl; procedure luaL_where(L: Plua_State; lvl: Integer); cdecl; function luaL_error(L: Plua_State; const fmt: PAnsiChar): Integer; cdecl; varargs; function luaL_checkoption(L: Plua_State; arg: Integer; def: PAnsiChar; lst: PPAnsiChar): Integer; cdecl; function luaL_fileresult(L: Plua_State; stat: Integer; const fname: PAnsiChar): Integer; cdecl; function luaL_execresult(L: Plua_State; stat: Integer): Integer; cdecl; function luaL_ref(L: Plua_State; t: Integer): Integer; cdecl; procedure luaL_unref(L: Plua_State; t, ref: Integer); cdecl; function luaL_loadfilex(L: Plua_State; const filename, mode: PAnsiChar): Integer; cdecl; function luaL_loadfile(L: Plua_State; const filename: PAnsiChar): Integer; inline; function luaL_loadbufferx(L: Plua_State; const buff: PAnsiChar; sz: size_t; const name, mode: PAnsiChar): Integer; cdecl; function luaL_loadstring(L: Plua_State; const s: PAnsiChar): Integer; cdecl; function luaL_newstate: Plua_State; cdecl; function luaL_len(L: Plua_State; idx: Integer): lua_Integer; cdecl; function luaL_gsub(L: Plua_State; const s, p, r: PAnsiChar): PAnsiChar; cdecl; procedure luaL_setfuncs(L: Plua_State; lr: array of luaL_Reg; nup: Integer); inline; overload; procedure luaL_setfuncs(L: Plua_State; lr: PluaL_Reg; nup: Integer); cdecl; overload; function luaL_getsubtable(L: Plua_State; idx: Integer; const fname: PAnsiChar): Integer; cdecl; procedure luaL_traceback(L, L1: Plua_State; msg: PAnsiChar; level: Integer); cdecl; procedure luaL_requiref(L: Plua_State; const modname: PAnsiChar; openf: lua_CFunction; glb: LongBool); cdecl; // some useful macros procedure luaL_newlibtable(L: Plua_State; lr: array of luaL_Reg); inline; overload; procedure luaL_newlibtable(L: Plua_State; lr: PluaL_Reg); inline; overload; procedure luaL_newlib(L: Plua_State; lr: array of luaL_Reg); inline; overload; procedure luaL_newlib(L: Plua_State; lr: PluaL_Reg); inline; overload; procedure luaL_argcheck(L: Plua_State; cond: Boolean; arg: Integer; extramsg: PAnsiChar); inline; procedure luaL_argexpected(L: Plua_State; cond: Boolean; arg: Integer; tname: PAnsiChar); inline; function luaL_checkstring(L: Plua_State; n: Integer): PAnsiChar; inline; function luaL_optstring(L: Plua_State; n: Integer; d: PAnsiChar): PAnsiChar; inline; function luaL_typename(L: Plua_State; i: Integer): PAnsiChar; inline; function luaL_dofile(L: Plua_State; const filename: PAnsiChar): Integer; inline; function luaL_dostring(L: Plua_State; const str: PAnsiChar): Integer; inline; procedure luaL_getmetatable(L: Plua_State; tname: PAnsiChar); inline; function luaL_loadbuffer(L: Plua_State; const buff: PAnsiChar; size: size_t; const name: PAnsiChar): Integer; inline; // push the value used to represent failure/error procedure luaL_pushfail(L: Plua_State); inline; const LUA_COLIBNAME = 'coroutine'; LUA_TABLIBNAME = 'table'; LUA_IOLIBNAME = 'io'; LUA_OSLIBNAME = 'os'; LUA_STRLIBNAME = 'string'; LUA_UTF8LIBNAME = 'utf8'; LUA_MATHLIBNAME = 'math'; LUA_DBLIBNAME = 'debug'; LUA_LOADLIBNAME = 'package'; function luaopen_base(L: Plua_State): Integer; cdecl; function luaopen_coroutine(L: Plua_State): Integer; cdecl; function luaopen_table(L: Plua_State): Integer; cdecl; function luaopen_io(L: Plua_State): Integer; cdecl; function luaopen_os(L: Plua_State): Integer; cdecl; function luaopen_string(L: Plua_State): Integer; cdecl; function luaopen_utf8(L: Plua_State): Integer; cdecl; function luaopen_math(L: Plua_State): Integer; cdecl; function luaopen_debug(L: Plua_State): Integer; cdecl; function luaopen_package(L: Plua_State): Integer; cdecl; // open all previous libraries procedure luaL_openlibs(L: Plua_State); cdecl; implementation function lua_upvalueindex(I: Integer): Integer; begin Result := LUA_REGISTRYINDEX - i; end; function lua_newstate(f: lua_Alloc; ud: Pointer): Plua_State; cdecl; external LUA_LIB_NAME; procedure lua_close(L: Plua_State); cdecl; external LUA_LIB_NAME; function lua_newthread(L: Plua_State): Plua_State; cdecl; external LUA_LIB_NAME; function lua_resetthread(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; function lua_atpanic(L: Plua_State; panicf: lua_CFunction): lua_CFunction; cdecl; external LUA_LIB_NAME; function lua_version(L: Plua_State): lua_Number; cdecl; external LUA_LIB_NAME; function lua_absindex(L: Plua_State; idx: Integer): Integer; cdecl; external LUA_LIB_NAME; function lua_gettop(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; procedure lua_settop(L: Plua_State; idx: Integer); cdecl; external LUA_LIB_NAME; procedure lua_pushvalue(L: Plua_State; Idx: Integer); cdecl; external LUA_LIB_NAME; procedure lua_rotate(L: Plua_State; idx, n: Integer); cdecl; external LUA_LIB_NAME; procedure lua_remove(L: Plua_State; idx: Integer); begin lua_rotate(L, idx, -1); lua_pop(L, 1); end; procedure lua_insert(L: Plua_State; idx: Integer); begin lua_rotate(L, idx, 1); end; procedure lua_replace(L: Plua_State; idx: Integer); begin lua_copy(L, -1, idx); lua_pop(L, 1); end; procedure lua_copy(L: Plua_State; fromidx, toidx: Integer); cdecl; external LUA_LIB_NAME; function lua_checkstack(L: Plua_State; n: Integer): LongBool; cdecl; external LUA_LIB_NAME; procedure lua_xmove(from, to_: Plua_State; n: Integer); cdecl; external LUA_LIB_NAME; function lua_isnumber(L: Plua_State; idx: Integer): LongBool; cdecl; external LUA_LIB_NAME; function lua_isstring(L: Plua_State; idx: Integer): LongBool; cdecl; external LUA_LIB_NAME; function lua_iscfunction(L: Plua_State; idx: Integer): LongBool; cdecl; external LUA_LIB_NAME; function lua_isinteger(L: Plua_State; idx: Integer): LongBool; cdecl; external LUA_LIB_NAME; function lua_isuserdata(L: Plua_State; idx: Integer): LongBool; cdecl; external LUA_LIB_NAME; function lua_type(L: Plua_State; idx: Integer): Integer; cdecl; external LUA_LIB_NAME; function lua_typename(L: Plua_State; tp: Integer): PAnsiChar; cdecl; external LUA_LIB_NAME; function lua_tonumberx(L: Plua_State; idx: Integer; isnum: PLongBool): lua_Number; cdecl; external LUA_LIB_NAME; function lua_tointegerx(L: Plua_State; idx: Integer; isnum: PLongBool): lua_Integer; cdecl; external LUA_LIB_NAME; procedure lua_arith(L: Plua_State; op: Integer); cdecl; external LUA_LIB_NAME; function lua_rawequal(L: Plua_State; idx1, idx2: Integer): LongBool; cdecl; external LUA_LIB_NAME; function lua_compare(L: Plua_State; idx1, idx2, op: Integer): LongBool; cdecl; external LUA_LIB_NAME; function lua_toboolean(L: Plua_State; idx: Integer): LongBool; cdecl; external LUA_LIB_NAME; function lua_tolstring(L: Plua_State; idx: Integer; len: Psize_t): PAnsiChar; cdecl; external LUA_LIB_NAME; function lua_rawlen(L: Plua_State; idx: Integer): lua_Unsigned; cdecl; external LUA_LIB_NAME; function lua_tocfunction(L: Plua_State; idx: Integer): lua_CFunction; cdecl; external LUA_LIB_NAME; function lua_touserdata(L: Plua_State; idx: Integer): Pointer; cdecl; external LUA_LIB_NAME; function lua_tothread(L: Plua_State; idx: Integer): Plua_State; cdecl; external LUA_LIB_NAME; function lua_topointer(L: Plua_State; idx: Integer): Pointer; cdecl; external LUA_LIB_NAME; procedure lua_pushnil(L: Plua_State); cdecl; external LUA_LIB_NAME; procedure lua_pushnumber(L: Plua_State; n: lua_Number); cdecl; external LUA_LIB_NAME; procedure lua_pushinteger(L: Plua_State; n: lua_Integer); cdecl; external LUA_LIB_NAME; procedure lua_pushlstring(L: Plua_State; const s: PAnsiChar; len: size_t); cdecl; external LUA_LIB_NAME; procedure lua_pushstring(L: Plua_State; const s: PAnsiChar); cdecl; external LUA_LIB_NAME; procedure lua_pushstring(L: Plua_State; const s: AnsiString); begin lua_pushlstring(L, PAnsiChar(s), Length(s)); end; function lua_pushvfstring(L: Plua_State; const fmt: PAnsiChar; argp: Pointer): PAnsiChar; cdecl; external LUA_LIB_NAME; function lua_pushfstring(L: Plua_State; const fmt: PAnsiChar): PAnsiChar; cdecl; varargs; external LUA_LIB_NAME; procedure lua_pushcclosure(L: Plua_State; fn: lua_CFunction; n: Integer); cdecl; external LUA_LIB_NAME; procedure lua_pushboolean(L: Plua_State; b: LongBool); cdecl; external LUA_LIB_NAME; procedure lua_pushlightuserdata(L: Plua_State; p: Pointer); cdecl; external LUA_LIB_NAME; procedure lua_pushthread(L: Plua_State); cdecl; external LUA_LIB_NAME; function lua_getglobal(L: Plua_State; const name: PAnsiChar): Integer; cdecl; external LUA_LIB_NAME; function lua_gettable(L: Plua_State; idx: Integer): Integer; cdecl; external LUA_LIB_NAME; function lua_getfield(L: Plua_state; idx: Integer; k: PAnsiChar): Integer; cdecl; external LUA_LIB_NAME; function lua_geti(L: Plua_State; idx: Integer; n: lua_Integer): Integer cdecl; external LUA_LIB_NAME; function lua_rawget(L: Plua_State; idx: Integer): Integer; cdecl; external LUA_LIB_NAME; function lua_rawgeti(L: Plua_State; idx: Integer; n: lua_Integer): Integer; cdecl; external LUA_LIB_NAME; function lua_rawgetp(L: Plua_State; idx: Integer; p: Pointer): Integer; cdecl; external LUA_LIB_NAME; procedure lua_createtable(L: Plua_State; narr, nrec: Integer); cdecl; external LUA_LIB_NAME; function lua_newuserdatauv(L: Plua_State; sz: size_t; nuvalue: Integer): Pointer; cdecl; external LUA_LIB_NAME; function lua_getmetatable(L: Plua_State; objindex: Integer): Integer; cdecl; external LUA_LIB_NAME; function lua_getiuservalue(L: Plua_State; idx, n: Integer): Integer; cdecl; external LUA_LIB_NAME; procedure lua_setglobal(L: Plua_State; const name: PAnsiChar); cdecl; external LUA_LIB_NAME; procedure lua_settable(L: Plua_State; idx: Integer); cdecl; external LUA_LIB_NAME; procedure lua_setfield(L: Plua_State; idx: Integer; k: PAnsiChar); cdecl; external LUA_LIB_NAME; procedure lua_seti(L: Plua_State; idx: Integer; n: lua_Integer); cdecl; external LUA_LIB_NAME; procedure lua_rawset(L: Plua_State; idx: Integer); cdecl; external LUA_LIB_NAME; procedure lua_rawseti(L: Plua_State; idx: Integer; n: lua_Integer); cdecl; external LUA_LIB_NAME; procedure lua_rawsetp(L: Plua_State; idx: Integer; p: Pointer); cdecl; external LUA_LIB_NAME; function lua_setmetatable(L: Plua_State; objindex: Integer): Integer; cdecl; external LUA_LIB_NAME; function lua_setiuservalue(L: Plua_State; idx, n: Integer): Integer; cdecl; external LUA_LIB_NAME; procedure lua_callk(L: Plua_State; nargs, nresults: Integer; ctx: lua_KContext; k: lua_KFunction); cdecl; external LUA_LIB_NAME; function lua_pcallk(L: Plua_State; nargs, nresults, errfunc: Integer; ctx: lua_KContext; k: lua_KFunction): Integer; cdecl; external LUA_LIB_NAME; function lua_load(L: Plua_State; reader: lua_Reader; dt: Pointer; const chunkname, mode: PAnsiChar): Integer; cdecl; external LUA_LIB_NAME; function lua_dump(L: Plua_State; writer: lua_Writer; data: Pointer; strip: Integer): Integer; cdecl; external LUA_LIB_NAME; function lua_yieldk(L: Plua_State; nresults: Integer; ctx: lua_KContext; k: lua_KFunction): Integer; cdecl; external LUA_LIB_NAME; procedure lua_call(L: Plua_State; nargs, nresults: Integer); begin lua_callk(L, nargs, nresults, nil, nil); end; function lua_pcall(L: Plua_State; nargs, nresults, errf: Integer): Integer; begin Result := lua_pcallk(L, nargs, nresults, errf, nil, nil); end; function lua_yield(L: Plua_State; nresults: Integer): Integer; begin Result := lua_yieldk(L, nresults, nil, nil); end; function lua_resume(L, from: Plua_State; narg: Integer; nres: PInteger): Integer; cdecl; external LUA_LIB_NAME; function lua_status(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; function lua_isyieldable(L: Plua_State): LongBool; cdecl; external LUA_LIB_NAME; procedure lua_setwarnf(L: Plua_State; f: lua_WarnFunction; ud: Pointer); cdecl; external LUA_LIB_NAME; procedure lua_warning(L: Plua_State; msg: PAnsiChar; tocont: Integer); cdecl; external LUA_LIB_NAME; function lua_gc(L: Plua_State; what: Integer): Integer; cdecl; varargs; external LUA_LIB_NAME; function lua_error(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; function lua_next(L: Plua_State; idx: Integer): Integer; cdecl; external LUA_LIB_NAME; procedure lua_concat(L: Plua_State; n: Integer); cdecl; external LUA_LIB_NAME; procedure lua_len(L: Plua_State; idx: Integer); cdecl; external LUA_LIB_NAME; function lua_stringtonumber(L: Plua_State; const s: PAnsiChar): size_t; cdecl; external LUA_LIB_NAME; function lua_getallocf(L: Plua_State; ud: PPointer): lua_Alloc; cdecl; external LUA_LIB_NAME; procedure lua_setallocf(L: Plua_State; f: lua_Alloc; ud: Pointer); cdecl; external LUA_LIB_NAME; procedure lua_toclose(L: Plua_State; idx: Integer); cdecl; external LUA_LIB_NAME; function lua_getextraspace(L: Plua_State): Pointer; const LUA_EXTRASPACE = sizeof(Pointer); begin Result := L - LUA_EXTRASPACE; end; function lua_tonumber(L: Plua_State; idx: Integer): lua_Number; begin Result := lua_tonumberx(L, idx, nil); end; function lua_tointeger(L: Plua_State; idx: Integer): lua_Integer; begin Result := lua_tointegerx(L, idx, nil); end; procedure lua_pop(L: Plua_State; n: Integer); begin lua_settop(L, - n - 1); end; procedure lua_newtable(L: Plua_State); begin lua_createtable(L, 0, 0); end; procedure lua_register(L: Plua_State; const n: PAnsiChar; f: lua_CFunction); begin lua_pushcfunction(L, f); lua_setglobal(L, n); end; procedure lua_pushcfunction(L: Plua_State; f: lua_CFunction); begin lua_pushcclosure(L, f, 0); end; function lua_isfunction(L: Plua_State; n: Integer): Boolean; begin Result := lua_type(L, n) = LUA_TFUNCTION; end; function lua_istable(L: Plua_State; n: Integer): Boolean; begin Result := lua_type(L, n) = LUA_TTABLE; end; function lua_islightuserdata(L: Plua_State; n: Integer): Boolean; begin Result := lua_type(L, n) = LUA_TLIGHTUSERDATA; end; function lua_isnil(L: Plua_State; n: Integer): Boolean; begin Result := lua_type(L, n) = LUA_TNIL; end; function lua_isboolean(L: Plua_State; n: Integer): Boolean; begin Result := lua_type(L, n) = LUA_TBOOLEAN; end; function lua_isthread(L: Plua_State; n: Integer): Boolean; begin Result := lua_type(L, n) = LUA_TTHREAD; end; function lua_isnone(L: Plua_State; n: Integer): Boolean; begin Result := lua_type(L, n) = LUA_TNONE; end; function lua_isnoneornil(L: Plua_State; n: Integer): Boolean; begin Result := lua_type(L, n) <= 0; end; procedure lua_pushliteral(L: Plua_State; s: PAnsiChar); begin lua_pushlstring(L, s, Length(s)); end; procedure lua_pushglobaltable(L: Plua_State); begin lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS); end; function lua_tostring(L: Plua_State; i: Integer): PAnsiChar; begin Result := lua_tolstring(L, i, nil); end; function lua_newuserdata(L: Plua_State; sz: size_t): Pointer; begin Result := lua_newuserdatauv(L, sz, 1); end; function lua_getuservalue(L: Plua_State; idx: Integer): Integer; begin Result := lua_getiuservalue(L, idx, 1); end; function lua_setuservalue(L: Plua_State; idx: Integer): Integer; begin Result := lua_setiuservalue(L, idx, 1); end; function lua_getstack(L: Plua_State; level: Integer; ar: Plua_Debug): Integer; cdecl; external LUA_LIB_NAME; function lua_getinfo(L: Plua_State; const what: PAnsiChar; ar: Plua_Debug): Integer; cdecl; external LUA_LIB_NAME; function lua_getlocal(L: Plua_State; const ar: Plua_Debug; n: Integer): PAnsiChar; cdecl; external LUA_LIB_NAME; function lua_setlocal(L: Plua_State; const ar: Plua_Debug; n: Integer): PAnsiChar; cdecl; external LUA_LIB_NAME; function lua_getupvalue(L: Plua_State; funcindex, n: Integer): PAnsiChar; cdecl; external LUA_LIB_NAME; function lua_setupvalue(L: Plua_State; funcindex, n: Integer): PAnsiChar; cdecl; external LUA_LIB_NAME; function lua_upvalueid(L: Plua_State; funcindex, n: Integer): Pointer; cdecl; external LUA_LIB_NAME; procedure lua_upvaluejoin(L: Plua_State; funcindex1, n1, funcindex2, n2: Integer); cdecl; external LUA_LIB_NAME; procedure lua_sethook(L: Plua_State; func: lua_Hook; mask: Integer; count: Integer); cdecl; external LUA_LIB_NAME; function lua_gethook(L: Plua_State): lua_Hook; cdecl; external LUA_LIB_NAME; function lua_gethookmask(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; function lua_gethookcount(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; function lua_setcstacklimit(L: Plua_State; limit: Cardinal): Integer; cdecl; external LUA_LIB_NAME; procedure luaL_checkversion_(L: Plua_State; ver: lua_Number; sz: size_t); cdecl; external LUA_LIB_NAME; procedure luaL_checkversion(L: Plua_State); begin luaL_checkversion_(L, LUA_VERSION_NUM, LUAL_NUMSIZES); end; procedure luaL_traceback(L, L1: Plua_State; msg: PAnsiChar; level: Integer); cdecl; external LUA_LIB_NAME; function luaL_argerror(L: Plua_State; arg: Integer; const extramsg: PAnsiChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_typeerror(L: Plua_State; arg: Integer; tname: PAnsiChar): Integer; cdecl; external LUA_LIB_NAME; procedure luaL_where(L: Plua_State; lvl: Integer); cdecl; external LUA_LIB_NAME; function luaL_newmetatable(L: Plua_State; const tname: PAnsiChar): Integer; cdecl; external LUA_LIB_NAME; procedure luaL_setmetatable(L: Plua_State; const tname: PAnsiChar); cdecl; external LUA_LIB_NAME; function luaL_testudata(L: Plua_State; ud: Integer; const tname: PAnsiChar): Pointer; cdecl; external LUA_LIB_NAME; function luaL_checkudata(L: Plua_State; ud: Integer; const tname: PAnsiChar): Pointer; cdecl; external LUA_LIB_NAME; function luaL_error(L: Plua_State; const fmt: PAnsiChar): Integer; cdecl; varargs; external LUA_LIB_NAME; function luaL_checkoption(L: Plua_State; arg: Integer; def: PAnsiChar; lst: PPAnsiChar): Integer; cdecl; external LUA_LIB_NAME; procedure luaL_checkstack(L: Plua_State; sz: Integer; const msg: PAnsiChar); cdecl; external LUA_LIB_NAME; procedure luaL_checktype(L: Plua_State; arg, t: Integer); cdecl; external LUA_LIB_NAME; procedure luaL_checkany(L: Plua_State; arg: Integer); cdecl; external LUA_LIB_NAME; function luaL_checklstring(L: Plua_State; arg: Integer; l_: Psize_t): PAnsiChar; cdecl; external LUA_LIB_NAME; function luaL_optlstring(L: Plua_State; arg: Integer; const def: PAnsiChar; l_: Psize_t): PAnsiChar; cdecl; external LUA_LIB_NAME; function luaL_checknumber(L: Plua_State; arg: Integer): lua_Number; cdecl; external LUA_LIB_NAME; function luaL_optnumber(L: Plua_State; arg: Integer; def: lua_Number): lua_Number; cdecl; external LUA_LIB_NAME; function luaL_checkinteger(L: Plua_State; arg: Integer): lua_Integer; cdecl; external LUA_LIB_NAME; function luaL_optinteger(L: Plua_State; arg: Integer; def: lua_Integer): lua_Integer; cdecl; external LUA_LIB_NAME; procedure luaL_argcheck(L: Plua_State; cond: Boolean; arg: Integer; extramsg: PAnsiChar); begin if not cond then luaL_argerror(L, arg, extramsg); end; procedure luaL_argexpected(L: Plua_State; cond: Boolean; arg: Integer; tname: PAnsiChar); begin if not cond then luaL_typeerror(L, arg, tname); end; function luaL_checkstring(L: Plua_State; n: Integer): PAnsiChar; begin Result := luaL_checklstring(L, n, nil); end; function luaL_optstring(L: Plua_State; n: Integer; d: PAnsiChar): PAnsiChar; begin Result := luaL_optlstring(L, n, d, nil); end; function luaL_typename(L: Plua_State; i: Integer): PAnsiChar; begin Result := lua_typename(L, lua_type(L, i)); end; function luaL_dofile(L: Plua_State; const filename: PAnsiChar): Integer; begin Result := luaL_loadfile(L, filename); if Result = 0 then Result := lua_pcall(L, 0, LUA_MULTRET, 0); end; function luaL_dostring(L: Plua_State; const str: PAnsiChar): Integer; begin Result := luaL_loadstring(L, str); if Result = 0 then Result := lua_pcall(L, 0, LUA_MULTRET, 0); end; procedure luaL_getmetatable(L: Plua_State; tname: PAnsiChar); begin lua_getfield(L, LUA_REGISTRYINDEX, tname); end; function luaL_fileresult(L: Plua_State; stat: Integer; const fname: PAnsiChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_execresult(L: Plua_State; stat: Integer): Integer; cdecl; external LUA_LIB_NAME; function luaL_ref(L: Plua_State; t: Integer): Integer; cdecl; external LUA_LIB_NAME; procedure luaL_unref(L: Plua_State; t, ref: Integer); cdecl; external LUA_LIB_NAME; function luaL_loadfilex(L: Plua_State; const filename, mode: PAnsiChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_loadbufferx(L: Plua_State; const buff: PAnsiChar; sz: size_t; const name, mode: PAnsiChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_loadfile(L: Plua_State; const filename: PAnsiChar): Integer; begin Result := luaL_loadfilex(L, filename, nil); end; function luaL_loadbuffer(L: Plua_State; const buff: PAnsiChar; size: size_t; const name: PAnsiChar): Integer; begin Result := luaL_loadbufferx(L, buff, size, name, nil); end; procedure luaL_pushfail(L: Plua_State); begin lua_pushnil(L); end; function luaL_loadstring(L: Plua_State; const s: PAnsiChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_getmetafield(L: Plua_State; obj: Integer; const e: PAnsiChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_callmeta(L: Plua_State; obj: Integer; const e: PAnsiChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_tolstring(L: Plua_State; idx: Integer; len: Psize_t): PAnsiChar; cdecl; external LUA_LIB_NAME; procedure luaL_requiref(L: Plua_State; const modname: PAnsiChar; openf: lua_CFunction; glb: LongBool); cdecl; external LUA_LIB_NAME; procedure luaL_setfuncs(L: Plua_State; lr: PluaL_Reg; nup: Integer); cdecl; external LUA_LIB_NAME; procedure luaL_setfuncs(L: Plua_State; lr: array of luaL_Reg; nup: Integer); begin luaL_setfuncs(L, @lr, nup); end; procedure luaL_newlibtable(L: Plua_State; lr: array of luaL_Reg); begin lua_createtable(L, 0, High(lr)); end; procedure luaL_newlibtable(L: Plua_State; lr: PluaL_Reg); var n: Integer; begin n := 0; while lr^.name <> nil do begin inc(n); inc(lr); end; lua_createtable(L, 0, n); end; procedure luaL_newlib(L: Plua_State; lr: array of luaL_Reg); begin luaL_checkversion(L); luaL_newlibtable(L, lr); luaL_setfuncs(L, @lr, 0); end; procedure luaL_newlib(L: Plua_State; lr: PluaL_Reg); begin luaL_checkversion(L); luaL_newlibtable(L, lr); luaL_setfuncs(L, lr, 0); end; function luaL_gsub(L: Plua_State; const s, p, r: PAnsiChar): PAnsiChar; cdecl; external LUA_LIB_NAME; function luaL_getsubtable(L: Plua_State; idx: Integer; const fname: PAnsiChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_newstate: Plua_State; cdecl; external LUA_LIB_NAME; function luaL_len(L: Plua_State; idx: Integer): lua_Integer; cdecl; external LUA_LIB_NAME; function luaopen_base(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; function luaopen_coroutine(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; function luaopen_table(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; function luaopen_io(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; function luaopen_os(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; function luaopen_string(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; function luaopen_utf8(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; function luaopen_math(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; function luaopen_debug(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; function luaopen_package(L: Plua_State): Integer; cdecl; external LUA_LIB_NAME; procedure luaL_openlibs(L: Plua_State); cdecl; external LUA_LIB_NAME; initialization {$IFDEF MSWINDOWS} Set8087CW($133F); // disable all floating-point exceptions {$ENDIF} (****************************************************************************** * Copyright (C) 1994-2020 Lua.org, PUC-Rio. * * 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. ******************************************************************************) end.
unit uniteRequete; // Encapsule les données entrées par l’utilisateur interface uses SysUtils; //Encapsule les données entrées par le client type Requete = class private //Adresse de la source adresseDemandeur : String; //Date reception de la requete dateReception : TDateTime; //Version HTTP 1.0 ou 1.1 versionProtocole : String; //methose GET methode : String; //URL demande url : String; public //Instancie la Requete avec tous ses attributs // //@param uneAdresseDemandeur l’adresse ip du demandeur exemple : 127.0.0.1 //@param uneDateReception la date de réception de la requête exemple : 2013/09/21 10:51 //@param uneVersionProtocole la version du protocole http utilisé par le client. exemple : HTTP/1.1 //@param uneMethode la demande effectuée par le client exemple : GET, POST, etc //@param unUrl l'url de la page requise constructor create(uneAdresseDemandeur:String; uneDateReception:TDateTime; uneVersionProtocole:String; uneMethode:String; unUrl:String); //Accesseur de l'adresse du demandeur. // //@return String l'adresse du demandeur function getAdresseDemandeur:String; //Accesseur de la date de réception // //@return TdateTime la date de réception function getDateReception:TDateTime; //Accesseur de la version du protocole du client // //@return String la version du protocole du client function getVersionProtocole:String; //Accesseur de la méthode HTTP // //@return String la méthode HTTP function getMethode:String; //Accesseur de l'URL demandé par le client // //@return String l'URL demandé par le client function getUrl:String; end; implementation constructor Requete.create(uneAdresseDemandeur:String; uneDateReception:TDateTime; uneVersionProtocole:String; uneMethode:String; unUrl:String); begin end; function Requete.getAdresseDemandeur:String; begin result := ''; end; function Requete.getDateReception:TDateTime; begin result := 0; end; function Requete.getVersionProtocole:String; begin result := ''; end; function Requete.getMethode:String; begin result := ''; end; function Requete.getUrl:String; begin result := ''; end; end.
unit Objekt.Option; interface uses SysUtils, Classes; type TOption = class private fPasswort: string; fConvert: Boolean; fOldMetadata: Boolean; fStartZeit: TDateTime; fZeitstempel: Boolean; fBackupdatei: string; fLimbo: Boolean; fOnlyMeta: Boolean; fDatenbank: string; fChecksum: Boolean; fUser: string; fNoGarbage: Boolean; fNonTransportable: Boolean; fId: Integer; fServername: string; fMaxAnzBackupDateien: Boolean; fMaxAnzBackup: Integer; fLastBackupDate: TDateTime; fStatusMeldung: String; public constructor Create; destructor Destroy; override; procedure Init; property Servername: string read fServername write fServername; property Datenbank: string read fDatenbank write fDatenbank; property Backupdatei: string read fBackupdatei write fBackupdatei; property StartZeit: TDateTime read fStartZeit write fStartZeit; property User: string read fUser write fUser; property Passwort: string read fPasswort write fPasswort; property Checksum: Boolean read fChecksum write fChecksum; property Limbo: Boolean read fLimbo write fLimbo; property OnlyMeta: Boolean read fOnlyMeta write fOnlyMeta; property NoGarbage: Boolean read fNoGarbage write fNoGarbage; property OldMetadata: Boolean read fOldMetadata write fOldMetadata; property Convert: Boolean read fConvert write fConvert; property Zeitstempel: Boolean read fZeitstempel write fZeitstempel; property NonTransportable: Boolean read fNonTransportable write fNonTransportable; property MaxAnzahlBackupDateien: Boolean read fMaxAnzBackupDateien write fMaxAnzBackupDateien; property MaxAnzahlBackup: Integer read fMaxAnzBackup write fMaxAnzBackup; property Id: Integer read fId write fId; property LastBackupDate: TDateTime read fLastBackupDate write fLastBackupDate; property StatusMeldung: String read fStatusMeldung write fStatusMeldung; function getCSVLine: string; procedure setCSVLine(aValue: string); function BToStr(aValue: Boolean): string; end; implementation { TOption } uses System.Hash, DateUtils; constructor TOption.Create; begin Init; end; destructor TOption.Destroy; begin inherited; end; procedure TOption.Init; begin fServername := ''; fPasswort := ''; fConvert := false; fOldMetadata := false; fStartZeit := 0; fZeitstempel := false; fBackupdatei := ''; fLimbo := false; fOnlyMeta := false; fDatenbank := ''; fChecksum := false; fUser := ''; fNoGarbage := false; fNonTransportable := false; fMaxAnzBackupDateien := false; fMaxAnzBackup := 0; fLastBackupDate := IncDay(trunc(now), -1); fId := 0; fStatusMeldung := 'Wartet'; end; procedure TOption.setCSVLine(aValue: string); var Liste: TStringList; i1: Integer; begin Init; Liste := TStringList.Create; Liste.Delimiter := ';'; Liste.StrictDelimiter := true; Liste.DelimitedText := aValue; if Liste.Count < 16 then exit; fServername := Liste.Strings[0]; fDatenbank := Trim(Liste.Strings[1]); fBackupDatei := Liste.Strings[2]; fUser := Liste.Strings[3]; fPasswort := Liste.Strings[4]; if not TryStrToDateTime(Liste.Strings[5], fStartZeit) then fStartZeit := 0; fConvert := Liste.Strings[6] = '1'; fOldMetadata := Liste.Strings[7] = '1'; fZeitstempel := Liste.Strings[8] = '1'; fLimbo := Liste.Strings[9] = '1'; fOnlyMeta := Liste.Strings[10] = '1'; fCheckSum := Liste.Strings[11] = '1'; fNoGarbage := Liste.Strings[12] = '1'; fNonTransportable := Liste.Strings[13] = '1'; fMaxAnzBackupDateien := Liste.Strings[14] = '1'; if not TryStrToInt(Liste.Strings[15], i1) then begin if fMaxAnzBackupDateien then fMaxAnzBackup := 1 else fMaxAnzBackup := 0; end else fMaxAnzBackup := i1; end; function TOption.getCSVLine: string; begin Result := fServername + ';' + fDatenbank + ';' + fBackupDatei + ';' + fUser + ';' + fPasswort + ';' + FormatDateTime('dd.mm.yyyy hh:nn:ss', fStartZeit) + ';' + BToStr(fConvert) + ';' + BToStr(fOldMetadata) + ';' + BToStr(fZeitstempel) + ';' + BToStr(fLimbo) + ';' + BToStr(fOnlyMeta) + ';' + BToStr(fCheckSum) + ';' + BToStr(fNoGarbage) + ';' + BToStr(fNonTransportable)+ ';' + BToStr(fMaxAnzBackupDateien) + ';' + IntToStr(fMaxAnzBackup); end; function TOption.BToStr(aValue: Boolean): string; begin if aValue then Result := '1' else Result := '0'; end; end.
unit Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, DosCommand, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.CheckLst, JvComponentBase, JvFormMagnet; type TForm1 = class(TForm) ffmpegLog: TMemo; OpenBtn: TButton; DosCommand1: TDosCommand; BananaSplitLog: TMemo; AddJobBtn: TButton; KillTimer: TTimer; OpenDialog1: TOpenDialog; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Panel1: TPanel; Thumb1: TImage; Panel2: TPanel; Thumb2: TImage; BlackSegList: TCheckListBox; CutList: TMemo; JvFormMagnet1: TJvFormMagnet; JobListBtn: TButton; StopBtn: TButton; procedure OpenBtnClick(Sender: TObject); procedure DosCommand1Terminated(Sender: TObject); procedure DosCommand1NewLine(ASender: TObject; const ANewLine: string; AOutputType: TOutputType); procedure FormCreate(Sender: TObject); procedure BlackSegListClick(Sender: TObject); procedure KillTimerTimer(Sender: TObject); procedure AddJobBtnClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormDestroy(Sender: TObject); procedure BlackSegListClickCheck(Sender: TObject); procedure JobListBtnClick(Sender: TObject); procedure StopBtnClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure GetBlackSegments; procedure GetSilence; procedure GenerateThumbnails(idx : integer); end; var Form1: TForm1; ffmpeg : string; implementation uses StrUtils, IOUtils, TimeSpan, DateUtils, Jobs, Inifiles, VCL.Imaging.Jpeg, Contnrs; type TBlackSeg = class StartT : TTime; EndT : TTime; MiddleT : TTime; DurationT : TTime; StartS : string; EndS : string; MiddleS : string; DurationS : string; //function GetDuration : string; function SecondsToTTime(Sec : single) : TTime; public Thumb1 : TJpegImage; Thumb2 : TJpegImage; procedure SetStart(Sec : single); procedure SetEnd(Sec : single); procedure SetMiddle; procedure SetDuration(Sec : single); constructor Create; destructor Destroy; override; end; const //ffmpeg = 'C:\Users\Tsusai\Google Drive\MKLINK\VideoEncoding\RipBot264\Tools\ffmpeg\bin\ffmpeg.exe'; gap = 2; var SegHelper : TObjectlist; cDuration : single = 0; tDuration : string; ashow : string; HardStop : boolean = false; {$R *.dfm} (*------------------------------------------------------------------------------ TBlackSeg, it contains the timecodes for a black frame detection result ------------------------------------------------------------------------------*) function TBlackSeg.SecondsToTTime(Sec : single) : TTime; begin Result := EncodeTime(0,0,0,0); Result := IncSecond(Result,Trunc(Sec)); Result := IncMilliSecond(Result,Trunc((Frac(Sec)*100))); end; procedure TBlackSeg.SetStart(Sec : single); begin StartT := SecondsToTTime(Sec); StartS := FormatDateTime('hh:mm:ss.z',StartT); end; procedure TBlackSeg.SetEnd(Sec : single); begin EndT := SecondsToTTime(Sec); EndS := FormatDateTime('hh:mm:ss.z',EndT); end; procedure TBlackSeg.SetMiddle; begin MiddleT := StartT + (DurationT / 2); MiddleS := FormatDateTime('hh:mm:ss.z',MiddleT); end; procedure TBlackSeg.SetDuration(Sec : single); begin DurationT := SecondsToTTime(Sec); DurationS := FormatDateTime('hh:mm:ss.z',DurationT); end; constructor TBlackSeg.Create; begin inherited Create; StartT := EncodeTime(0,0,0,0); EndT := EncodeTime(0,0,0,0); DurationT := EncodeTime(0,0,0,0); MiddleT := EncodeTime(0,0,0,0); end; destructor TBlackSeg.Destroy; begin if Assigned(Thumb1) then Thumb1.Free; if Assigned(Thumb2) then Thumb2.Free; inherited Destroy; end; (*------------------------------------------------------------------------------ FFmpeg Commands ------------------------------------------------------------------------------*) procedure TForm1.GetBlackSegments; const args = '"%s" -i "%s" -vf blackdetect=d=0.2:pix_th=.1 -f null - -y'; begin Doscommand1.CommandLine := Format(args,[ffmpeg,ashow]); //Doscommand1.OutputLines := Memo1.Lines; BananaSplitLog.Lines.Clear; BananaSplitLog.Lines.Append('Running Blackdetect'); Doscommand1.Execute; while DosCommand1.IsRunning do begin //Sleep(500); //this will stop Application.ProcessMessages; end; end; procedure TForm1.GetSilence; const args = '"%s" -i "%s" -af silencedetect=n=-20dB:d=0.15 -f null - -y'; begin if DosCommand1.IsRunning then exit;//just end my life fam BananaSplitLog.Lines.Append('Looking for Silence During Cut Durations to Improve Accuracy'); DosCommand1.CommandLine := Format(args,[ffmpeg,ashow]); DosCommand1.Execute; while DosCommand1.IsRunning do begin sleep(50); Application.ProcessMessages; end; end; procedure TForm1.GenerateThumbnails(idx : integer); const //TimeString, file, thumbnailname args = '"%s" -i "%s" -ss %s -vframes 1 %s -y'; output = '(%d/%d) %s'; var mid : TTime; filenum : string; Segment : TBlackSeg; BSidx : integer; begin BSidx := -1; if HardStop then exit; if DosCommand1.IsRunning then exit;//just end my life fam if idx >= 0 then begin Segment := TBlackSeg(BlackSegList.Items.Objects[idx]); if not Assigned(Segment.Thumb1) then begin BSidx := BananaSplitLog.Lines.Add( Format(output,[idx+1,BlackSegList.Count,Segment.MiddleS]) + ' (-2)' ); mid := Segment.MiddleT; mid := IncSecond(mid,-gap); filenum := FormatDateTime('hhmmssz', mid)+'.jpg'; DosCommand1.CommandLine := Format(args, [ffmpeg, ashow, FormatDateTime('hh:mm:ss.z', mid), filenum] ); DosCommand1.Execute; while DosCommand1.IsRunning do begin sleep(50); Application.ProcessMessages; end; if FileExists(filenum) then begin Segment.Thumb1 := TJpegImage.Create; Segment.Thumb1.LoadFromFile(filenum); DeleteFile(filenum); //cleanup end; end; if HardStop then exit; if not Assigned(Segment.Thumb2) then begin if BSidx = -1 then begin BSidx := BananaSplitLog.Lines.Add( Format(output,[idx+1,BlackSegList.Count,Segment.MiddleS]) + ' (-2)' ); end else BananaSplitLog.Lines.Strings[BSidx] := BananaSplitLog.Lines.Strings[BSidx] + ' (+2)'; mid := Segment.MiddleT; mid := IncSecond(mid,gap); filenum := FormatDateTime('hhmmssz', mid)+'.jpg'; DosCommand1.CommandLine := Format(args, [ffmpeg, ashow, FormatDateTime('hh:mm:ss.z', mid), filenum] ); DosCommand1.Execute; while DosCommand1.IsRunning do begin sleep(50); Application.ProcessMessages; end; if FileExists(filenum) then begin Segment.Thumb2 := TJpegImage.Create; Segment.Thumb2.LoadFromFile(filenum); DeleteFile(filenum); //cleanup end; end; end; if BSidx <> -1 then BananaSplitLog.Lines.Strings[BSidx] := BananaSplitLog.Lines.Strings[BSidx] + ' ‎✔'; end; (*------------------------------------------------------------------------------ FFmpeg Output Processing ------------------------------------------------------------------------------*) procedure GrabCuts(ALine : string); var Segment : TBlackSeg; AList : TStringList; atime : single; begin ALine := StringReplace(ALine,':','=',[rfReplaceAll]); AList := TStringList.Create; AList.DelimitedText := ALine; //Values are SecondsTotal.milisecond //Times are set to 0 on object creation atime := StrToFloat(AList.Values['black_start']); //Not bothering with anything below 2 minutes or 2 min to the end if (atime >= 120) and ((cDuration-atime) > 120) then begin Segment := TBlackSeg.Create; Segment.SetStart(ATime); atime := StrToFloat(AList.Values['black_end']); Segment.SetEnd(ATime); atime := StrToFloat(AList.Values['black_duration']); Segment.SetDuration(ATime); Segment.SetMiddle; Form1.BlackSegList.AddItem(Segment.MiddleS,Segment); SegHelper.Add(Segment); //Segment.Free; OWNED BY SEGHELPER DO NOT FREE end; AList.Free; end; procedure GrabSilence(ALine : string); var AList : TStringList; atime : single; Silence : TTime; Segment : TBlackSeg; idx : integer; begin ALine := StringReplace(ALine,': ','=',[rfReplaceAll]); ALine := StringReplace(ALine,'|',',',[rfReplaceAll]); AList := TStringList.Create; AList.DelimitedText := ALine; atime := StrToFloat(AList.Values['silence_end']); Silence := EncodeTime(0,0,0,0); Silence := IncSecond(Silence,Trunc(atime)); Silence := IncMilliSecond(Silence,Trunc((Frac(atime)*100))); atime:= StrToFloat(AList.Values['silence_duration']); atime := atime / 2; Silence := IncSecond(Silence,-Trunc(atime)); Silence := IncMilliSecond(Silence,-Trunc((Frac(atime)*100))); AList.Free; for idx := 0 to Form1.BlackSegList.Count -1 do begin Segment := TBlackSeg(Form1.BlackSegList.Items.Objects[idx]); if (Silence > Segment.StartT) and (Silence < Segment.EndT) then begin Form1.BananaSplitLog.Lines.Add('Silence Timecode Match Found, Adjusting'); Segment.MiddleT := Silence; Segment.MiddleS := FormatDateTime('hh:mm:ss.z',Segment.MiddleT); Form1.BlackSegList.Items.Strings[idx] := Segment.MiddleS + '*'; end; end; end; procedure GrabDuration(ALine : string); var AList : TStringList; timeSpan : TTimeSpan; begin cDuration := 0; ALine := Trim(ALine); ALine := StringReplace(ALine,'Duration: ','Duration=',[rfReplaceAll]); AList := TStringList.Create; AList.CommaText := ALine; tDuration := AList.ValueFromIndex[0]; timespan := TTimeSpan.Parse(tDuration); //Values are SecondsTotal.milisecond //Times are set to 0 on object creation cDuration := timespan.TotalSeconds; AList.Free; end; (*------------------------------------------------------------------------------ MainForm Controls ------------------------------------------------------------------------------*) procedure TForm1.OpenBtnClick(Sender: TObject); var idx : integer; begin if OpenDialog1.Execute() then begin ashow := OpenDialog1.FileName; OpenDialog1.FileName := ''; //clear; end else exit; //we found nothing, so do nothing. OpenBtn.Enabled := false; Form1.Caption := ' BananaSplit86 - ' + ExtractFileName(ashow); if DosCommand1.IsRunning then begin BananaSplitLog.Lines.Append('Waiting on Background Processes to Stop'); DosCommand1.Stop; end; while DosCommand1.IsRunning do Sleep(50); HardStop := false; Thumb1.Picture.Assign(nil); Thumb2.Picture.Assign(nil); CutList.Clear; BlackSegList.Clear; SegHelper.Clear; GetBlackSegments; if Not HardStop then begin if BlackSegList.Items.Count = 0 then begin ShowMessage('Nothing detected, stopping'); HardStop := true; end; end; if Not HardStop then GetSilence; if Not HardStop then begin BananaSplitLog.Lines.Append('Generating Thumbnails'); for idx := 0 to BlackSegList.Items.Count - 1 do begin GenerateThumbnails(idx); end; BananaSplitLog.Lines.Append('Finished Generating Thumbnails'); end; OpenBtn.Enabled := true; HardStop := false; end; procedure TForm1.StopBtnClick(Sender: TObject); begin BananaSplitLog.Lines.Append('All Stop Requested'); HardStop := true; KillTimer.Enabled := true; end; procedure TForm1.AddJobBtnClick(Sender: TObject); begin Form2.AddJob(ashow,tDuration); end; procedure TForm1.JobListBtnClick(Sender: TObject); begin if Form2.Showing then Form2.Close else Form2.Show; end; procedure TForm1.BlackSegListClickCheck(Sender: TObject); var idx : integer; CutPoints : TStringList; Segment : TBlackSeg; begin CutList.Clear; CutPoints := TStringList.Create; CutPoints.Add('00:00:00.00'); for idx := 0 to BlackSegList.Items.Count-1 do begin if BlackSegList.Checked[idx] then begin Segment := TBlackSeg(BlackSegList.Items.Objects[idx]); if Assigned(Segment.Thumb1) and Assigned(Segment.Thumb2) then begin Thumb1.Picture.Bitmap.Assign(Segment.Thumb1); Thumb2.Picture.Bitmap.Assign(Segment.Thumb2); end else begin Thumb1.Picture.Assign(nil); Thumb2.Picture.Assign(nil); end; //NEVERMIND //This seems to work the best. Middle is too soon, end is too late, so go half way between mid and end //CutPoints.Add(FormatDateTime('hh:mm:ss.z', Segment._middle + ((Segment._end - Segment._middle)/2))); CutPoints.Add(Segment.MiddleS); end; end; CutPoints.Add(tDuration); //Memo2.Lines.Assign(CutPoints); if CutPoints.Count > 2 then begin for idx := 0 to CutPoints.Count-2 do begin CutList.Lines.Add(CutPoints.Strings[idx] + ',' + CutPoints.Strings[idx+1]); end; end; end; procedure TForm1.DosCommand1NewLine(ASender: TObject; const ANewLine: string; AOutputType: TOutputType); begin ffmpegLog.Lines.Add(ANewLine); if AnsiContainsStr(ANewLine,'Duration: ') and (cDuration < 1) then begin GrabDuration(ANewLine); end; if AnsiStartsStr('[blackdetect @ ',ANewLine) and AnsiContainsStr(ANewLine,'_duration') then begin GrabCuts(ANewLine); end; if AnsiStartsStr('[silencedetect @ ',ANewLine) and AnsiContainsStr(ANewLine,'_duration') then begin GrabSilence(ANewLine); end; end; procedure TForm1.DosCommand1Terminated(Sender: TObject); begin ffmpeglog.Lines.Add('FFMpeg Process Finished'); KillTimer.Enabled := true; end; procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin HardStop := true; Doscommand1.Stop; CanClose := true; end; procedure TForm1.FormCreate(Sender: TObject); var ini : TMemIniFile; begin SegHelper := TObjectList.Create; SegHelper.OwnsObjects := true; ini := TMemIniFile.Create(ChangeFileExt(Application.ExeName,'.ini')); ffmpeg := ini.ReadString('FFmpeg','Executable','c:\full path to exe without quotes please'); ini.Free; if not FileExists(ffmpeg) then begin ShowMessage('Please close the program and set the path to ffmpeg in the ini file'); close; end; Thumb1.Align := alClient; Thumb2.Align := alClient; end; procedure TForm1.FormDestroy(Sender: TObject); var ini : TMemIniFile; begin ini := TMemIniFile.Create(ChangeFileExt(Application.ExeName,'.ini')); ini.WriteString('FFmpeg','Executable',ffmpeg); ini.UpdateFile; ini.Free; SegHelper.Free; end; procedure TForm1.BlackSegListClick(Sender: TObject); var Segment : TBlackSeg; begin if BlackSegList.ItemIndex >=0 then begin Segment := TBlackSeg(BlackSegList.Items.Objects[BlackSegList.ItemIndex]); if Assigned(Segment.Thumb1) then begin Thumb1.Picture.Bitmap.Assign(Segment.Thumb1); Thumb1.Visible := true; end else Thumb1.Visible := false; if Assigned(Segment.Thumb2) then begin Thumb2.Picture.Bitmap.Assign(Segment.Thumb2); Thumb2.Visible := true; end else Thumb2.Visible := false; end; end; procedure TForm1.KillTimerTimer(Sender: TObject); begin DosCommand1.Stop; KillTimer.Enabled := false; end; { eTRL M!!!9 #@@ WHY WON'T THIS WORK RX) I'LL MAKE MY OWN PROGRAM RMR WITH BLACKJACK....AND HOOKERS RM$ RMM B8WL @XUUUUN... z@TMMMMMMMMMMMMMRm. uRMMMMMMMMMMMMMMMMMMMMRc :5MMMMMMMMMMMMMMMMMMMMMMMM$. dMMMMMMMMMMMMMMMMMMMMMMMMMMMMr JMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM. MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM$ MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM) MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMR MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM$.... MMMMMMM8*TTTTTTT???!!!!!!!!!!!!!!!!!!!?N. 3MMMM8?!!U*$$$$$$$$$$$$$$$$$$$$**$$$$$N!!N 4XMM$!!XF~~~~~~"#*$$$$$$R#"~~~~~~~$$$$$$!!) 4XMME!!$~~~~~~~~~~~~~?~~~~~~~(:::~?$$$$$R!) 'MMM!!!&~~~~~~4$$E~~~X~~~~~~~3$$E~4$$$$$E!) EM9!!!M:~~~~~~""!~~~6~~~~~~~~~~~($$$$$$!9 RM@!!!!?i:~~~~~~~~($$N~~~~~~~~~\$$$$$#!XF $MMB!!!!!!!TT#**@******##TTTTTT?!!!!!U# MMMMN!!!!!!!!!!!!!!!!!!!!!!!!!!!!!U# tMMMMMRR@@@*RRMHHMMMMMHHHMMRTTRR@ 4XMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM9 'MMMMMMMMMMMMMMM86QQQQQ8MMMMMMMM9 EMMMMMMMM8*"~~~~f~~~~t~~~~~RMMM@ RMMMMMSF~~R~~~~(!~~~~$~~~~~$#" $MMMMMF~~~Kuuii@m+++*$*++mmR MMMMM9~~~!!~~~~@(::XuBL::~~R .um=*#""""""#*=+@MMMMMN+*#F~~~~M~~~~~X~~~~~$"~:~~~~~~~:("?%u. z*"~~~~~~~~~~~~~~~~~?MMMMMMK~~F~~~~?:~~~~$~~~~~M~~~~~~~~~~~~~~~~~~%u z"(~~~~~~~~~~~~~~~~~~~~~RMMMMMMRi$~:Xuu9emmm@@@%mmhi~~~~~~~~~~~~~~~~~~~^h z"~~~~~~~~~~~~~~~~~~~~~~~~RMMMMMMMMMMMMMMMMMMMMMMMMMMM&~~~~~~~~~~~~~~~'#C#=@c f.ue~~~~~~~~~~~^""#*+iL:~~~$MMMMMMMMMMMMMMMMMMMMMMMMMMMR~~~~~~~~~~~~~~~~~~?L " F~~~~~~~~~~~~~~~~~~~~~:~"*8MMQ8N@*#TTT?!!!!!!!!!!!!?TT%miF~~~~~~~~~~~~~~~~$T*c F~~~~~~~~~~~~~~~~~~~~~~~~~~~~~?tX!!!!!!!!!!!!!!!!!!!!!!!XF~~~~~~~~~~~~~~~~~~N!!?k @.zm%i:~~~~~~~~~~~~~~~~~~~~~~~~~~~"*X!!!!!!!!!!!!!!!!!!!W"~~~~~~~~~~~~~"#NX!!!!!!!k d!!!!!!N/~~~~~~~~~~~~~~~~~~~~~~~~~~~~?t!!!!!!!!!!!!!!!!@~~~~~~~~~~~~~~~~~~~~#X!!!!9 d!!!!!!!!?$RRRRRRRRRRRRNmi.~~~~~~~~~~~~~~N!!!!!!!!!!!!XF~~~~~~~~~~~~~(uz@$RRN!!!!!!! E!!!!!!!!!!$MMMMMMMMMMMM$?"~~~~~~~~~~~~~~~^N??!!!!!!XF~~~~~~~~~~.z@RMMMMMMMMM&!!!!!! 4!!!!!!!!!!!!$MMMMMMMMMMMMMMR$mL~~~~~~~~~~~~~?X!!!!!XF~~~~~~~:eRMMMMMMMMMMMMMM$!!!!!! 4!!!!!!!!!!!!?MMMMMMMMMMMMMMMMMMMMRmL~~~~~~~~~~N!!!!F~~~~~:@RMMMMMMMMMMMMMMMMMM&!!!!! 4WRR$W!!!!!!!!9MMMMMMMMMMMMMMMMMMMMMMMRNi:~~~~~:N!!@~~~~zRMMMMMMMMMMMMMMMMMMMMM$!!!!9 } end.
unit Datapar.Conexao; interface uses Data.DB; type TDataparModoConexao = (mcFireDac = 0, mcDBExpress = 1, mcUniDac = 2, mcDOA = 3); TDataparProvider = class strict private FHost: String; FUser: String; FPassword: String; FDriverName: String; public public constructor create(AHost: String; AUser: String; APassword: String; ADriverName: String); property Host: String Read FHost Write FHost; property User: String Read FUser Write FUser; property Password: String Read FPassword Write FPassword; property DriverName: String Read FDriverName Write FDriverName; end; TDataparCommand = class strict private FSQL : String; public constructor create(ASql: string); property SQL: String Read FSQL Write FSQL; end; TDataparQuery = class abstract public function executaSQL(ACommand: TDataparCommand): TDataSet; virtual; abstract; end; TDataparContext = class strict private FQuery: TDataparQuery; public function executaSQL(ACommand: TDataParCommand): TDataSet; public constructor Create(AQuery: TDataparQuery); end; implementation { TDataparProvider } constructor TDataparProvider.create(AHost, AUser, APassword: String; ADriverName: String); begin FHost := AHost; FUser := AUser; FPassword := APassword; FDriverName := ADriverName; end; { TDataparContext } constructor TDataparContext.Create(AQuery: TDataparQuery); begin self.FQuery := AQuery; end; function TDataparContext.executaSQL(ACommand: TDataParCommand): TDataSet; begin Result := self.FQuery.executaSQL(ACommand); end; { TDataparCommand } constructor TDataparCommand.create(ASql: string); begin self.FSQL := ASql; end; end.
unit PE.Parser.ImportDelayed; interface uses System.Generics.Collections, System.SysUtils, PE.Common, PE.Imports, PE.Types, PE.Types.Directories, PE.Types.FileHeader, // expand TPEImage.Is32bit PE.Types.Imports, PE.Types.ImportsDelayed, PE.Utils; type TPEImportDelayedParser = class(TPEParser) public function Parse: TParserResult; override; end; implementation uses PE.Image, PE.Imports.Func, PE.Imports.Lib; // Testing mode: check if read fields are correct. function ParseTable( const PE: TPEImage; const Table: TDelayLoadDirectoryTable; Testing: boolean ): boolean; var DllName: string; FnName: string; Fn: TPEImportFunctionDelayed; HintNameRva: TRVA; Ilt: TImportLookupTable; iFunc: uint32; var iLen: integer; Ordinal: UInt16; Hint: UInt16 absolute Ordinal; Iat: TRVA; SubValue: uint32; Lib: TPEImportLibrary; begin if Table.UsesVA then SubValue := PE.ImageBase else SubValue := 0; if Testing then begin if (Table.Name = 0) or (Table.Name < SubValue) then begin PE.Msg.Write('Delayed Import: Name address incorrect.'); exit(false); end; if (Table.DelayImportNameTable = 0) or (Table.DelayImportNameTable < SubValue) then begin PE.Msg.Write('Delayed Import: Name table address incorrect.'); exit(false); end; if (Table.DelayImportAddressTable = 0) or (Table.DelayImportAddressTable < SubValue) then begin PE.Msg.Write('Delayed Import: Address table incorrect.'); exit(false); end; end; if not PE.SeekRVA(Table.Name - SubValue) then exit(false); if not PE.ReadAnsiStringLen(MAX_PATH_WIN, iLen, DllName) then exit(false); if not Testing then begin Lib := TPEImportLibrary.Create(DllName, False, True); PE.ImportsDelayed.Add(Lib); end else begin Lib := nil; // compiler friendly end; iFunc := 0; Iat := Table.DelayImportAddressTable - SubValue; while PE.SeekRVA(Table.DelayImportNameTable - SubValue + iFunc * PE.ImageWordSize) do begin HintNameRva := PE.ReadWord(); if HintNameRva = 0 then break; Ilt.Create(HintNameRva, PE.Is32bit); Ordinal := 0; FnName := ''; if Ilt.IsImportByOrdinal then begin // Import by ordinal only. No hint/name. Ordinal := Ilt.OrdinalNumber; end else begin // Import by name. Get hint/name if not PE.SeekRVA(HintNameRva - SubValue) then begin PE.Msg.Write('Delayed Import: incorrect Hint/Name RVA encountered.'); exit(false); end; Hint := PE.ReadWord(2); FnName := PE.ReadANSIString; end; if not Testing then begin Fn := TPEImportFunctionDelayed.Create(FnName, Ordinal); Lib.Functions.Add(Fn); end; inc(Iat, PE.ImageWordSize); inc(iFunc); end; exit(true); end; function TPEImportDelayedParser.Parse: TParserResult; var PE: TPEImage; ddir: TImageDataDirectory; ofs: uint32; Table: TDelayLoadDirectoryTable; Tables: TList<TDelayLoadDirectoryTable>; TablesUseRVA: boolean; begin PE := TPEImage(FPE); result := PR_ERROR; // If no imports, it's ok. if not PE.DataDirectories.Get(DDIR_DELAYIMPORT, @ddir) then exit(PR_OK); if ddir.IsEmpty then exit(PR_OK); // Seek import dir. if not PE.SeekRVA(ddir.VirtualAddress) then exit; Tables := TList<TDelayLoadDirectoryTable>.Create; try // Delay-load dir. tables. ofs := 0; TablesUseRVA := true; // default, compiler-friendly while true do begin if ofs > ddir.Size then exit(PR_ERROR); if not PE.ReadEx(Table, SizeOf(Table)) then break; if Table.Empty then break; // Attribute: // 0: addresses are VA (old VC6 binaries) // 1: addresses are RVA if (ofs = 0) then begin TablesUseRVA := Table.UsesRVA; // initialize once end else if TablesUseRVA <> Table.UsesRVA then begin // Normally all tables must use either VA or RVA. No mix allowed. // If mix found it must be not real table. // For example, some Delphi versions used such optimization. break; end; Tables.Add(Table); inc(ofs, SizeOf(Table)); end; // Parse tables. for Table in Tables do // First test if fields are correct if ParseTable(PE, Table, true) then // Then do real reading. ParseTable(PE, Table, false); exit(PR_OK); finally Tables.Free; end; end; end.
unit ULID; interface { ULID: Universally Unique Lexicographically Sortable Identifier String Representation: ttttttttttrrrrrrrrrrrrrrrr where t is Timestamp r is Randomness For more information see: https://github.com/martinusso/ulid/blob/master/README.md } function CreateULID: string; function EncodeTime(Time: Int64): string; implementation uses DateUtils, SysUtils, Windows; const ENCODING: array[0..31] of string = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z'); // Crockford's Base32 ENCODING_LENGTH = Length(ENCODING); function CreateULID: string; function UNIXTimeInMilliseconds: Int64; var ST: SystemTime; DT: TDateTime; begin GetSystemTime(ST); DT := EncodeDate(ST.wYear, ST.wMonth, ST.wDay) + SysUtils.EncodeTime(ST.wHour, ST.wMinute, ST.wSecond, ST.wMilliseconds); Result := DateUtils.MilliSecondsBetween(DT, UnixDateDelta); end; begin Result := EncodeTime(UNIXTimeInMilliseconds) + EncodeRandom; end; function EncodeRandom: string; const ENCODED_RANDOM_LENGTH = 16; var I: Word; Rand: Integer; begin Result := ''; for I := ENCODED_RANDOM_LENGTH downto 1 do begin Rand := Trunc(ENCODING_LENGTH * Random); Result := ENCODING[Rand] + Result; end; end; function EncodeTime(Time: Int64): string; const ENCODED_TIME_LENGTH = 10; var I: Word; M: Integer; begin Result := ''; for I := ENCODED_TIME_LENGTH downto 1 do begin M := (Time mod ENCODING_LENGTH); Result := ENCODING[M] + Result; Time := Trunc((Time - M) / ENCODING_LENGTH); end; end; end.
namespace GlHelper; interface uses rtl; type { A 4-dimensional vector. Can be used for a variety of purposes: * To represent points or vectors in 4D space, using the X, Y, Z and W fields. * To represent colors with alpha channel information (using the R, G, B and A fields, which are just aliases for X, Y, Z and W) * To represent texture coordinates (S, T, P and Q, again just aliases for X, Y, Z and W). * To group 4 arbitrary values together in an array (C[0]..C[3], also just aliases for X, Y, Z and W) } TVector4 = public record {$REGION 'Internal Declarations'} private method GetComponent(const AIndex: Integer): Single; method SetComponent(const AIndex: Integer; const Value: Single); method GetLength: Single; method SetLength(const AValue: Single); method GetLengthSquared: Single; method SetLengthSquared(const AValue: Single); {$ENDREGION 'Internal Declarations'} public { Sets the four elements (X, Y, Z and W) to 0. } method Init; { Sets the four elements (X, Y, Z and W) to A. Parameters: A: the value to set the three elements to. } method Init(const Value: Single); { Sets the four elements (X, Y, Z and W) to A1, A2, A3 and A4 respectively. Parameters: A1: the value to set the first element to. A2: the value to set the second element to. A3: the value to set the third element to. A4: the value to set the fourth element to. } method Init(const A1, A2, A3, A4: Single); { Sets the first two elements from a 2D vector, and the last two elements from two scalars. Parameters: A1: the vector to use for the first two elements. A2: the value to set the third element to. A3: the value to set the fourth element to. } method Init(const A1: TVector2; const A2, A3: Single); { Sets the first and last elements from two scalars, and the middle two elements from a 2D vector. Parameters: A1: the value to set the first element to. A2: the vector to use for the second and third elements. A3: the value to set the fourth element to. } method Init(const A1: Single; const A2: TVector2; const A3: Single); { Sets the first two elements from two scalars and the last two elements from a 2D vector. Parameters: A1: the value to set the first element to. A2: the value to set the second element to. A3: the vector to use for the last two elements. } method Init(const A1, A2: Single; const A3: TVector2); { Sets the first two elements and last two elements from two 2D vectors. Parameters: A1: the vector to use for the first two elements. A2: the vector to use for the last two elements. } method Init(const A1, A2: TVector2); { Sets the first three elements from a 3D vector, and the fourth element from a scalar. Parameters: A1: the vector to use for the first three elements. A2: the value to set the fourth element to. } method Init(const A1: TVector3; const A2: Single); { Sets the first element from a scaler, and the last three elements from a 3D vector. Parameters: A1: the value to set the first element to. A2: the vector to use for the last three elements. } method Init(const A1: Single; const A2: TVector3); { Checks two vectors for equality. Returns: True if the two vectors match each other exactly. } class operator Equal(const A, B: TVector4): Boolean; inline; { Checks two vectors for inequality. Returns: True if the two vectors are not equal. } class operator NotEqual(const A, B: TVector4): Boolean; inline; { Negates a vector. Returns: The negative value of a vector (eg. (-A.X, -A.Y, -A.Z, -A.W)) } class operator Minus(const A: TVector4): TVector4; inline; { Adds a scalar value to a vector. Returns: (A.X + B, A.Y + B, A.Z + B, A.W + B) } class operator Add(const A: TVector4; const B: Single): TVector4; inline; { Adds a vector to a scalar value. Returns: (A + B.X, A + B.Y, A + B.Z, A + B.W) } class operator Add(const A: Single; const B: TVector4): TVector4;inline; { Adds two vectors. Returns: (A.X + B.X, A.Y + B.Y, A.Z + B.Z, A.W + B.W) } class operator Add(const A, B: TVector4): TVector4; inline; { Subtracts a scalar value from a vector. Returns: (A.X - B, A.Y - B, A.Z - B, A.W - B) } class operator Subtract(const A: TVector4; const B: Single): TVector4; inline; { Subtracts a vector from a scalar value. Returns: (A - B.X, A - B.Y, A - B.Z, A - B.W) } class operator Subtract(const A: Single; const B: TVector4): TVector4; inline; { Subtracts two vectors. Returns: (A.X - B.X, A.Y - B.Y, A.Z - B.Z, A.W - B.W) } class operator Subtract(const A, B: TVector4): TVector4; inline; { Multiplies a vector with a scalar value. Returns: (A.X * B, A.Y * B, A.Z * B, A.W * B) } class operator Multiply(const A: TVector4; const B: Single): TVector4; inline; { Multiplies a scalar value with a vector. Returns: (A * B.X, A * B.Y, A * B.Z, A * B.W) } class operator Multiply(const A: Single; const B: TVector4): TVector4; inline; { Multiplies two vectors component-wise. To calculate a dot product instead, use the Dot function. Returns: (A.X * B.X, A.Y * B.Y, A.Z * B.Z, A.W * B.W) } class operator Multiply(const A, B: TVector4): TVector4; inline; { Divides a vector by a scalar value. Returns: (A.X / B, A.Y / B, A.Z / B, A.W / B) } class operator Divide(const A: TVector4; const B: Single): TVector4; inline; { Divides a scalar value by a vector. Returns: (A / B.X, A / B.Y, A / B.Z, A / B.W) } class operator Divide(const A: Single; const B: TVector4): TVector4; inline; { Divides two vectors component-wise. Returns: (A.X / B.X, A.Y / B.Y, A.Z / B.Z, A.W / B.W) } class operator Divide(const A, B: TVector4): TVector4; inline; { Whether this vector equals another vector, within a certain tolerance. Parameters: AOther: the other vector. ATolerance: (optional) tolerance. If not specified, a small tolerance is used. Returns: True if both vectors are equal (within the given tolerance). } method Equals(const AOther: TVector4; const ATolerance: Single := SINGLE_TOLERANCE): Boolean; { Calculates the distance between this vector and another vector. Parameters: AOther: the other vector. Returns: The distance between this vector and AOther. @bold(Note): If you only want to compare distances, you should use DistanceSquared instead, which is faster. } method Distance(const AOther: TVector4): Single; { Calculates the squared distance between this vector and another vector. Parameters: AOther: the other vector. Returns: The squared distance between this vector and AOther. } method DistanceSquared(const AOther: TVector4): Single; { Calculates the dot product between this vector and another vector. Parameters: AOther: the other vector. Returns: The dot product between this vector and AOther. } method Dot(const AOther: TVector4): Single; { Offsets this vector in a certain direction. Parameters: ADeltaX: the delta X direction. ADeltaY: the delta Y direction. ADeltaZ: the delta Z direction. ADeltaW: the delta W direction. } method Offset(const ADeltaX, ADeltaY, ADeltaZ, ADeltaW: Single); { Offsets this vector in a certain direction. Parameters: ADelta: the delta. @bold(Note): this is equivalent to adding two vectors together. } method Offset(const ADelta: TVector4); { Calculates a normalized version of this vector. Returns: The normalized version of of this vector. That is, a vector in the same direction as A, but with a length of 1. @bold(Note): for a faster, less accurate version, use NormalizeFast. @bold(Note): Does not change this vector. To update this vector itself, use SetNormalized. } method Normalize: TVector4; { Normalizes this vector. This is, keep the current direction, but set the length to 1. @bold(Note): The SIMD optimized versions of this method use an approximation, resulting in a very small error. @bold(Note): If you do not want to change this vector, but get a normalized version instead, then use Normalize. } method SetNormalized; { Calculates a normalized version of this vector. Returns: The normalized version of of this vector. That is, a vector in the same direction as A, but with a length of 1. @bold(Note): this is an SIMD optimized version that uses an approximation, resulting in a small error. For an accurate version, use Normalize. @bold(Note): Does not change this vector. To update this vector itself, use SetNormalizedFast. } method NormalizeFast: TVector4; { Normalizes this vector. This is, keep the current direction, but set the length to 1. @bold(Note): this is an SIMD optimized version that uses an approximation, resulting in a small error. For an accurate version, use SetNormalized. @bold(Note): If you do not want to change this vector, but get a normalized version instead, then use NormalizeFast. } method SetNormalizedFast; { Calculates a vector pointing in the same direction as this vector. Parameters: I: the incident vector. NRef: the reference vector. Returns: A vector that points away from the surface as defined by its normal. If NRef.Dot(I) < 0 then it returns this vector, otherwise it returns the negative of this vector. } method FaceForward(const I, NRef: TVector4): TVector4; { Calculates the reflection direction for this (incident) vector. Parameters: N: the normal vector. Should be normalized in order to achieve the desired result. Returns: The reflection direction calculated as Self - 2 * N.Dot(Self) * N. } method Reflect(const N: TVector4): TVector4; { Calculates the refraction direction for this (incident) vector. Parameters: N: the normal vector. Should be normalized in order to achieve the desired result. Eta: the ratio of indices of refraction. Returns: The refraction vector. @bold(Note): This vector should be normalized in order to achieve the desired result.} method Refract(const N: TVector4; const Eta: Single): TVector4; { Creates a vector with the same direction as this vector, but with the length limited, based on the desired maximum length. Parameters: AMaxLength: The desired maximum length of the vector. Returns: A length-limited version of this vector. @bold(Note): Does not change this vector. To update this vector itself, use SetLimit. } method Limit(const AMaxLength: Single): TVector4; { Limits the length of this vector, based on the desired maximum length. Parameters: AMaxLength: The desired maximum length of this vector. @bold(Note): If you do not want to change this vector, but get a length-limited version instead, then use Limit. } method SetLimit(const AMaxLength: Single); { Creates a vector with the same direction as this vector, but with the length limited, based on the desired squared maximum length. Parameters: AMaxLengthSquared: The desired squared maximum length of the vector. Returns: A length-limited version of this vector. @bold(Note): Does not change this vector. To update this vector itself, use SetLimitSquared. } method LimitSquared(const AMaxLengthSquared: Single): TVector4; { Limits the length of this vector, based on the desired squared maximum length. Parameters: AMaxLengthSquared: The desired squared maximum length of this vector. @bold(Note): If you do not want to change this vector, but get a length-limited version instead, then use LimitSquared. } method SetLimitSquared(const AMaxLengthSquared: Single); { Creates a vector with the same direction as this vector, but with the length clamped between a minimim and maximum length. Parameters: AMinLength: The minimum length of the vector. AMaxLength: The maximum length of the vector. Returns: A length-clamped version of this vector. @bold(Note): Does not change this vector. To update this vector itself, use SetClamped. } method Clamp(const AMinLength, AMaxLength: Single): TVector4; { Clamps the length of this vector between a minimim and maximum length. Parameters: AMinLength: The minimum length of this vector. AMaxLength: The maximum length of this vector. @bold(Note): If you do not want to change this vector, but get a length-clamped version instead, then use Clamp. } method SetClamped(const AMinLength, AMaxLength: Single); { Linearly interpolates between this vector and a target vector. Parameters: ATarget: the target vector. AAlpha: the interpolation coefficient (between 0.0 and 1.0). Returns: The interpolation result vector. @bold(Note): Does not change this vector. To update this vector itself, use SetLerp. } method Lerp(const ATarget: TVector4; const AAlpha: Single): TVector4; { Linearly interpolates between this vector and a target vector and stores the result in this vector. Parameters: ATarget: the target vector. AAlpha: the interpolation coefficient (between 0.0 and 1.0). @bold(Note): If you do not want to change this vector, but get an interpolated version instead, then use Lerp. } method SetLerp(const ATarget: TVector4; const AAlpha: Single); { Whether the vector is normalized (within a small margin of error). Returns: True if the length of the vector is (very close to) 1.0 } method IsNormalized: Boolean; { Whether the vector is normalized within a given margin of error. Parameters: AErrorMargin: the allowed margin of error. Returns: True if the squared length of the vector is 1.0 within the margin of error. } method IsNormalized(const AErrorMargin: Single): Boolean; { Whether this is a zero vector. Returns: True if X, Y, Z and W are exactly 0.0 } method IsZero: Boolean; { Whether this is a zero vector within a given margin of error. Parameters: AErrorMargin: the allowed margin of error. Returns: True if the squared length is smaller then the margin of error. } method IsZero(const AErrorMargin: Single): Boolean; { Whether this vector has a similar direction compared to another vector. The test is performed in 3 dimensions (that is, the W-component is ignored). Parameters: AOther: the other vector. Returns: True if the normalized dot product (ignoring the W-component) is greater than 0. } method HasSameDirection(const AOther: TVector4): Boolean; { Whether this vector has an opposite direction compared to another vector. The test is performed in 3 dimensions (that is, the W-component is ignored). Parameters: AOther: the other vector. Returns: True if the normalized dot product (ignoring the W-component) is less than 0. } method HasOppositeDirection(const AOther: TVector4): Boolean; { Whether this vector runs parallel to another vector (either in the same or the opposite direction). The test is performed in 3 dimensions (that is, the W-component is ignored). Parameters: AOther: the other vector. ATolerance: (optional) tolerance. If not specified, a small tolerance is used. Returns: True if this vector runs parallel to AOther (within the given tolerance and ignoring the W-component) } method IsParallel(const AOther: TVector4; const ATolerance: Single := SINGLE_TOLERANCE): Boolean; { Whether this vector is collinear with another vector. Two vectors are collinear if they run parallel to each other and point in the same direction. The test is performed in 3 dimensions (that is, the W-component is ignored). Parameters: AOther: the other vector. ATolerance: (optional) tolerance. If not specified, a small tolerance is used. Returns: True if this vector is collinear to AOther (within the given tolerance and ignoring the W-component) } method IsCollinear(const AOther: TVector4; const ATolerance: Single := SINGLE_TOLERANCE): Boolean; { Whether this vector is opposite collinear with another vector. Two vectors are opposite collinear if they run parallel to each other and point in opposite directions. The test is performed in 3 dimensions (that is, the W-component is ignored). Parameters: AOther: the other vector. ATolerance: (optional) tolerance. If not specified, a small tolerance is used. Returns: True if this vector is opposite collinear to AOther (within the given tolerance and ignoring the W-component) } method IsCollinearOpposite(const AOther: TVector4; const ATolerance: Single := SINGLE_TOLERANCE): Boolean; { Whether this vector is perpendicular to another vector. The test is performed in 3 dimensions (that is, the W-component is ignored). Parameters: AOther: the other vector. ATolerance: (optional) tolerance. If not specified, a small tolerance is used. Returns: True if this vector is perpendicular to AOther. That is, if the dot product is 0 (within the given tolerance and ignoring the W-component) } method IsPerpendicular(const AOther: TVector4; const ATolerance: Single := SINGLE_TOLERANCE): Boolean; { Returns the components of the vector. This is identical to accessing the C-field, but this property can be used as a default array property. Parameters: AIndex: index of the component to return (0-3). Range is checked with an assertion. } property Components[const AIndex: Integer]: Single read GetComponent write SetComponent; default; { The euclidean length of this vector. @bold(Note): If you only want to compare lengths of vectors, you should use LengthSquared instead, which is faster. @bold(Note): You can also set the length of the vector. In that case, it will keep the current direction. } property Length: Single read GetLength write SetLength; { The squared length of the vector. @bold(Note): This property is faster than Length because it avoids calculating a square root. It is useful for comparing lengths instead of calculating actual lengths. @bold(Note): You can also set the squared length of the vector. In that case, it will keep the current direction. } property LengthSquared: Single read GetLengthSquared write SetLengthSquared; public X, Y, Z, W: Single; property R : Single read X write X; property G : Single read Y write Y; property B : Single read Z write Z; property A : Single read W write W; property S : Single read X write X; property T : Single read Y write Y; property P : Single read Z write Z; property Q : Single read W write W; // case Byte of // { X, Y, Z and W components of the vector. Aliases for C[0], C[1], C[2] // and C[3]. } // 0: (X, Y, Z, W: Single); // // { Red, Green, Blue and Alpha components of the vector. Aliases for C[0], // C[1], C[2] and C[3]. } // 1: (R, G, B, A: Single); // // { S, T, P and Q components of the vector. Aliases for C[0], C[1], C[2] and // C[3]. } // 2: (S, T, P, Q: Single); // // { The four components of the vector. } // 3: (C: array [0..3] of Single); end; implementation { TVector4 } class operator TVector4.Add(const A: TVector4; const B: Single): TVector4; begin Result.X := A.X + B; Result.Y := A.Y + B; Result.Z := A.Z + B; Result.W := A.W + B; end; class operator TVector4.Add(const A: Single; const B: TVector4): TVector4; begin Result.X := A + B.X; Result.Y := A + B.Y; Result.Z := A + B.Z; Result.W := A + B.W; end; class operator TVector4.Add(const A, B: TVector4): TVector4; begin Result.X := A.X + B.X; Result.Y := A.Y + B.Y; Result.Z := A.Z + B.Z; Result.W := A.W + B.W; end; method TVector4.Distance(const AOther: TVector4): Single; begin Result := (Self - AOther).Length; end; method TVector4.DistanceSquared(const AOther: TVector4): Single; begin Result := (Self - AOther).LengthSquared; end; class operator TVector4.Divide(const A: TVector4; const B: Single): TVector4; begin Result.X := A.X / B; Result.Y := A.Y / B; Result.Z := A.Z / B; Result.W := A.W / B; end; class operator TVector4.Divide(const A: Single; const B: TVector4): TVector4; begin Result.X := A / B.X; Result.Y := A / B.Y; Result.Z := A / B.Z; Result.W := A / B.W; end; class operator TVector4.Divide(const A, B: TVector4): TVector4; begin Result.X := A.X / B.X; Result.Y := A.Y / B.Y; Result.Z := A.Z / B.Z; Result.W := A.W / B.W; end; method TVector4.Dot(const AOther: TVector4): Single; begin Result := (X * AOther.X) + (Y * AOther.Y) + (Z * AOther.Z) + (W * AOther.W); end; method TVector4.FaceForward(const I, NRef: TVector4): TVector4; begin if (NRef.Dot(I) < 0) then Result := Self else Result := -Self; end; method TVector4.GetLength: Single; begin Result := Sqrt((X * X) + (Y * Y) + (Z * Z) + (W * W)); end; method TVector4.GetLengthSquared: Single; begin Result := (X * X) + (Y * Y) + (Z * Z) + (W * W); end; class operator TVector4.Multiply(const A: TVector4; const B: Single): TVector4; begin Result.X := A.X * B; Result.Y := A.Y * B; Result.Z := A.Z * B; Result.W := A.W * B; end; class operator TVector4.Multiply(const A: Single; const B: TVector4): TVector4; begin Result.X := A * B.X; Result.Y := A * B.Y; Result.Z := A * B.Z; Result.W := A * B.W; end; class operator TVector4.Multiply(const A, B: TVector4): TVector4; begin Result.X := A.X * B.X; Result.Y := A.Y * B.Y; Result.Z := A.Z * B.Z; Result.W := A.W * B.W; end; class operator TVector4.Minus(const A: TVector4): TVector4; begin Result.X := -A.X; Result.Y := -A.Y; Result.Z := -A.Z; Result.W := -A.W; end; method TVector4.NormalizeFast: TVector4; begin Result := Self * InverseSqrt(Self.LengthSquared); end; method TVector4.Reflect(const N: TVector4): TVector4; begin Result := Self - ((2 * N.Dot(Self)) * N); end; method TVector4.Refract(const N: TVector4; const Eta: Single): TVector4; var D, K: Single; begin D := N.Dot(Self); K := 1 - Eta * Eta * (1 - D * D); if (K < 0) then Result.Init else Result := (Eta * Self) - ((Eta * D + Sqrt(K)) * N); end; method TVector4.SetNormalizedFast; begin Self := Self * InverseSqrt(Self.LengthSquared); end; class operator TVector4.Subtract(const A: TVector4; const B: Single): TVector4; begin Result.X := A.X - B; Result.Y := A.Y - B; Result.Z := A.Z - B; Result.W := A.W - B; end; class operator TVector4.Subtract(const A: Single; const B: TVector4): TVector4; begin Result.X := A - B.X; Result.Y := A - B.Y; Result.Z := A - B.Z; Result.W := A - B.W; end; class operator TVector4.Subtract(const A, B: TVector4): TVector4; begin Result.X := A.X - B.X; Result.Y := A.Y - B.Y; Result.Z := A.Z - B.Z; Result.W := A.W - B.W; end; { TVector4 } method TVector4.Clamp(const AMinLength, AMaxLength: Single): TVector4; var LenSq, EdgeSq: Single; begin LenSq := GetLengthSquared; if (LenSq = 0) then Exit(Self); EdgeSq := AMaxLength * AMaxLength; if (LenSq > EdgeSq) then Exit(Self * Sqrt(EdgeSq / LenSq)); EdgeSq := AMinLength * AMinLength; if (LenSq < EdgeSq) then Exit(Self * Sqrt(EdgeSq / LenSq)); Result := Self; end; class operator TVector4.Equal(const A, B: TVector4): Boolean; begin Result := (A.X = B.X) and (A.Y = B.Y) and (A.Z = B.Z) and (A.W = B.W); end; method TVector4.Equals(const AOther: TVector4; const ATolerance: Single): Boolean; begin Result := (Abs(X - AOther.X) <= ATolerance) and (Abs(Y - AOther.Y) <= ATolerance) and (Abs(Z - AOther.Z) <= ATolerance) and (Abs(W - AOther.W) <= ATolerance); end; method TVector4.GetComponent(const AIndex: Integer): Single; begin case AIndex of 0 : result := X; 1 : result := Y; 2 : result := Z; 3 : result := W; end; // Result := C[AIndex]; end; method TVector4.HasSameDirection(const AOther: TVector4): Boolean; begin Result := (((X * AOther.X) + (Y * AOther.Y) + (Z * AOther.Z)) > 0); end; method TVector4.HasOppositeDirection(const AOther: TVector4): Boolean; begin Result := (((X * AOther.X) + (Y * AOther.Y) + (Z * AOther.Z)) < 0); end; method TVector4.Init(const A1, A2, A3, A4: Single); begin X := A1; Y := A2; Z := A3; W := A4; end; method TVector4.Init(const Value: Single); begin X := Value; Y := Value; Z := Value; W := Value; end; method TVector4.Init; begin X := 0; Y := 0; Z := 0; W := 0; end; method TVector4.Init(const A1: TVector2; const A2, A3: Single); begin X := A1.X; Y := A1.Y; Z := A2; W := A3; end; method TVector4.Init(const A1, A2: TVector2); begin X := A1.X; Y := A1.Y; Z := A2.X; W := A2.Y; end; method TVector4.Init(const A1, A2: Single; const A3: TVector2); begin X := A1; Y := A2; Z := A3.X; W := A3.Y; end; method TVector4.Init(const A1: Single; const A2: TVector2; const A3: Single); begin X := A1; Y := A2.X; Z := A2.Y; W := A3; end; method TVector4.Init(const A1: TVector3; const A2: Single); begin X := A1.X; Y := A1.Y; Z := A1.Z; W := A2; end; method TVector4.Init(const A1: Single; const A2: TVector3); begin X := A1; Y := A2.X; Z := A2.Y; W := A2.Z; end; method TVector4.IsCollinear(const AOther: TVector4; const ATolerance: Single): Boolean; begin Result := IsParallel(AOther, ATolerance) and (HasSameDirection(AOther)); end; method TVector4.IsCollinearOpposite(const AOther: TVector4; const ATolerance: Single): Boolean; begin Result := IsParallel(AOther, ATolerance) and (HasOppositeDirection(AOther)); end; method TVector4.IsNormalized: Boolean; begin Result := IsNormalized(0.000000001); end; method TVector4.IsNormalized(const AErrorMargin: Single): Boolean; begin Result := (Abs(LengthSquared - 1.0) < AErrorMargin); end; method TVector4.IsParallel(const AOther: TVector4; const ATolerance: Single): Boolean; begin Result := (TVector3.Vector3(Y * AOther.Z - Z * AOther.Y, Z * AOther.X - X * AOther.Z, X * AOther.Y - Y * AOther.X).LengthSquared <= ATolerance); end; method TVector4.IsPerpendicular(const AOther: TVector4; const ATolerance: Single): Boolean; begin Result := (Abs((X * AOther.X) + (Y * AOther.Y) + (Z * AOther.Z)) <= ATolerance); end; method TVector4.IsZero: Boolean; begin Result := (X = 0) and (Y = 0) and (Z = 0) and (W = 0); end; method TVector4.IsZero(const AErrorMargin: Single): Boolean; begin Result := (LengthSquared < AErrorMargin); end; method TVector4.Lerp(const ATarget: TVector4; const AAlpha: Single): TVector4; begin Result := Mix(Self, ATarget, AAlpha); end; method TVector4.Limit(const AMaxLength: Single): TVector4; begin Result := LimitSquared(AMaxLength * AMaxLength); end; method TVector4.LimitSquared(const AMaxLengthSquared: Single): TVector4; var LenSq: Single; begin LenSq := GetLengthSquared; if (LenSq > AMaxLengthSquared) then Result := Self * Sqrt(AMaxLengthSquared / LenSq) else Result := Self; end; method TVector4.Normalize: TVector4; begin Result := Self / Length; end; class operator TVector4.NotEqual(const A, B: TVector4): Boolean; begin Result := (A.X <> B.X) or (A.Y <> B.Y) or (A.Z <> B.Z) or (A.W <> B.W); end; method TVector4.Offset(const ADeltaX, ADeltaY, ADeltaZ, ADeltaW: Single); begin X := X + ADeltaX; Y := Y + ADeltaY; Z := Z + ADeltaZ; W := W + ADeltaW; end; method TVector4.Offset(const ADelta: TVector4); begin Self := Self + ADelta; end; method TVector4.SetClamped(const AMinLength, AMaxLength: Single); begin Self := Clamp(AMinLength, AMaxLength); end; method TVector4.SetComponent(const AIndex: Integer; const Value: Single); begin case AIndex of 0 : X := Value; 1 : Y := Value; 2 : Z := Value; 3 : W := Value; end; // C[AIndex] := Value; end; method TVector4.SetLength(const AValue: Single); begin setLengthSquared(AValue * AValue); end; method TVector4.SetLengthSquared(const AValue: Single); var LenSq: Single; begin LenSq := GetLengthSquared; if (LenSq <> 0) and (LenSq <> AValue) then Self := Self * Sqrt(AValue / LenSq); end; method TVector4.SetLerp(const ATarget: TVector4; const AAlpha: Single); begin Self := Mix(Self, ATarget, AAlpha); end; method TVector4.SetLimit(const AMaxLength: Single); begin Self := LimitSquared(AMaxLength * AMaxLength); end; method TVector4.SetLimitSquared(const AMaxLengthSquared: Single); begin Self := LimitSquared(AMaxLengthSquared); end; method TVector4.SetNormalized; begin Self := Self / Length; end; end.
unit uShellIntegration; interface uses Winapi.Windows, Winapi.ShellApi, Winapi.ShlObj, Winapi.ActiveX, System.Win.ComObj, System.SysUtils, System.Classes, System.Variants, System.Math, Vcl.Forms, Vcl.Clipbrd, uMemory, uVistaFuncs, uAppUtils, uVCLHelpers, uFastLoad, uShellNamespaceUtils; function MessageBoxDB(Handle: THandle; AContent, Title, ADescription: string; Buttons, Icon: Integer): Integer; overload; function MessageBoxDB(Handle: THandle; AContent, Title: string; Buttons, Icon: Integer): Integer; overload; procedure TextToClipboard(const S: string); procedure SetDesktopWallpaper(FileName: string; WOptions: Byte); procedure HideFromTaskBar(Handle: Thandle); procedure DisableWindowCloseButton(Handle: Thandle); procedure ShowPropertiesDialog(FName: string); procedure ShowMyComputerProperties(Hwnd: THandle); function ChangeIconDialog(HOwner: THandle; var FileName: string; var IconIndex: Integer): Boolean; overload; function ChangeIconDialog(HOwner: THandle; var IcoName: string): Boolean; overload; procedure LoadFilesFromClipBoard(var Effects: Integer; Files: TStrings); function ExtractAssociatedIconSafe(FileName: string; IconIndex: Word): HICON; overload; function ExtractAssociatedIconSafe(FileName: string): HICON; overload; function CanCopyFromClipboard: Boolean; implementation function MessageBoxDB(Handle: THandle; AContent, Title, ADescription: string; Buttons, Icon: Integer): Integer; overload; var Res: Integer; begin TThread.Synchronize(nil, procedure begin if Handle = 0 then Handle := Screen.ActiveFormHandle; Res := TaskDialog(Handle, AContent, Title, ADescription, Buttons, Icon); end ); Result := Res; end; function MessageBoxDB(Handle: THandle; AContent, Title: string; Buttons, Icon: Integer): Integer; overload; begin TLoad.Instance.RequiredStyle; Result := MessageBoxDB(Handle, AContent, Title, '', Buttons, Icon); end; function CanCopyFromClipboard: Boolean; var Files: TStrings; Effects: Integer; begin Files := TStringList.Create; try LoadFilesFromClipBoard(Effects, Files); Result := Files.Count > 0; finally F(Files); end; if not Result then Result := ClipboardHasPIDList; end; procedure TextToClipboard(const S: string); var N: Integer; Mem: Cardinal; Ptr: Pointer; begin try with Clipboard do try Open; if IsClipboardFormatAvailable(CF_UNICODETEXT) then begin N := (Length(S) + 1) * 2; Mem := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, N); Ptr := GlobalLock(Mem); Move(PWideChar(Widestring(S))^, Ptr^, N); GlobalUnlock(Mem); SetAsHandle(CF_UNICODETEXT, Mem); end; AsText := S; Mem := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, SizeOf(Dword)); Ptr := GlobalLock(Mem); Dword(Ptr^) := (SUBLANG_NEUTRAL shl 10) or LANG_RUSSIAN; GlobalUnLock(Mem); SetAsHandle(CF_LOCALE, Mem); finally Close; end; except end; end; procedure SetDesktopWallpaper(FileName: string; WOptions: Byte); const CLSID_ActiveDesktop: TGUID = '{75048700-EF1F-11D0-9888-006097DEACF9}'; var ActiveDesktop: IActiveDesktop; Options: TWallPaperOpt; begin ActiveDesktop := CreateComObject(CLSID_ActiveDesktop) as IActiveDesktop; ActiveDesktop.SetWallpaper(PChar(FileName), 0); Options.DwSize := SizeOf(_tagWALLPAPEROPT); Options.DwStyle := WOptions; ActiveDesktop.SetWallpaperOptions(Options, 0); ActiveDesktop.ApplyChanges(AD_APPLY_ALL or AD_APPLY_FORCE); end; procedure HideFromTaskBar(Handle: Thandle); var ExtendedStyle: Integer; begin ExtendedStyle := GetWindowLong(Application.Handle, GWL_EXSTYLE); SetWindowLong(Application.Handle, SW_SHOWMINNOACTIVE, WS_EX_TOOLWINDOW or WS_EX_TOPMOST or WS_EX_LTRREADING or WS_EX_LEFT or ExtendedStyle); end; procedure DisableWindowCloseButton(Handle: Thandle); var HMenuHandle: HMENU; begin if (Handle <> 0) then begin HMenuHandle := GetSystemMenu(Handle, FALSE); if (HMenuHandle <> 0) then DeleteMenu(HMenuHandle, SC_CLOSE, MF_BYCOMMAND); end; end; procedure LoadFilesFromClipBoard(var Effects: Integer; Files: TStrings); var Hand: THandle; Count: Integer; Pfname: array [0 .. 10023] of Char; CD: Cardinal; S: string; DwEffect: ^Word; begin Effects := 0; Files.Clear; if IsClipboardFormatAvailable(CF_HDROP) then begin if OpenClipboard(Application.Handle) = False then Exit; CD := 0; repeat CD := EnumClipboardFormats(CD); if (CD <> 0) and (GetClipboardFormatName(CD, Pfname, 1024) <> 0) then begin S := UpperCase(string(Pfname)); if Pos('DROPEFFECT', S) <> 0 then begin Hand := GetClipboardData(CD); if (Hand <> NULL) then begin DwEffect := GlobalLock(Hand); Effects := DwEffect^; GlobalUnlock(Hand); end; CD := 0; end; end; until (CD = 0); Hand := GetClipboardData(CF_HDROP); if (Hand <> NULL) then begin Count := DragQueryFile(Hand, $FFFFFFFF, nil, 0); if Count > 0 then repeat Dec(Count); DragQueryFile(Hand, Count, Pfname, 1024); Files.Add(string(Pfname)); until (Count = 0); end; CloseClipboard; end; end; function ChangeIconDialog(HOwner: THandle; var IcoName: string): Boolean; overload; var FileName: string; IconIndex: Integer; S, Icon: string; I: Integer; begin Result := False; S := IcoName; I := Pos(',', S); FileName := Copy(S, 1, I - 1); Icon := Copy(S, I + 1, Length(S) - I); IconIndex := StrToIntDef(Icon, 0); if ChangeIconDialog(HOwner, FileName, IconIndex) then begin if FileName <> '' then Icon := FileName + ',' + IntToStr(IconIndex); IcoName := Icon; Result := True; end; end; function ChangeIconDialog(HOwner: THandle; var FileName: string; var IconIndex: Integer): Boolean; type SHChangeIconProc = function(Wnd: HWND; SzFileName: PChar; Reserved: Integer; var LpIconIndex: Integer): DWORD; stdcall; SHChangeIconProcW = function(Wnd: HWND; SzFileName: PWideChar; Reserved: Integer; var LpIconIndex: Integer): DWORD; stdcall; const Shell32 = 'shell32.dll'; resourcestring SNotSupported = 'This function is not supported by your version of Windows'; var ShellHandle: THandle; SHChangeIcon: SHChangeIconProc; SHChangeIconW: SHChangeIconProcW; Buf: array [0 .. MAX_PATH] of Char; BufW: array [0 .. MAX_PATH] of WideChar; begin Result := False; SHChangeIcon := nil; SHChangeIconW := nil; ShellHandle := LoadLibrary(PChar(Shell32)); try if ShellHandle <> 0 then begin if Win32Platform = VER_PLATFORM_WIN32_NT then SHChangeIconW := GetProcAddress(ShellHandle, PChar(62)) else SHChangeIcon := GetProcAddress(ShellHandle, PChar(62)); end; if Assigned(SHChangeIconW) then begin StringToWideChar(FileName, BufW, SizeOf(BufW)); Result := SHChangeIconW(HOwner, BufW, SizeOf(BufW), IconIndex) = 1; if Result then FileName := BufW; end else if Assigned(SHChangeIcon) then begin StrPCopy(Buf, FileName); Result := SHChangeIcon(HOwner, Buf, SizeOf(Buf), IconIndex) = 1; if Result then FileName := Buf; end else raise Exception.Create(SNotSupported); finally if ShellHandle <> 0 then FreeLibrary(ShellHandle); end; end; procedure ShowPropertiesDialog(FName: string); var SExInfo: TSHELLEXECUTEINFO; begin ZeroMemory(Addr(SExInfo), SizeOf(SExInfo)); SExInfo.CbSize := SizeOf(SExInfo); SExInfo.LpFile := PWideChar(FName); SExInfo.LpVerb := 'Properties'; SExInfo.FMask := SEE_MASK_INVOKEIDLIST; ShellExecuteEx(Addr(SExInfo)); end; procedure ShowMyComputerProperties(Hwnd: THandle); var PMalloc: IMalloc; Desktop: IShellFolder; Mnu: IContextMenu; Hr: HRESULT; PidlDrives: PItemIDList; Cmd: TCMInvokeCommandInfo; begin Hr := SHGetMalloc(PMalloc); if SUCCEEDED(Hr) then try Hr := SHGetDesktopFolder(Desktop); if SUCCEEDED(Hr) then try Hr := SHGetSpecialFolderLocation(Hwnd, CSIDL_DRIVES, PidlDrives); if SUCCEEDED(Hr) then try Hr := Desktop.GetUIObjectOf(Hwnd, 1, PidlDrives, IContextMenu, nil, Pointer(Mnu)); if SUCCEEDED(Hr) then try FillMemory(@Cmd, Sizeof(Cmd), 0); with Cmd do begin CbSize := Sizeof(Cmd); FMask := 0; Hwnd := 0; LpVerb := PAnsiChar('Properties'); NShow := SW_SHOWNORMAL; end; {Hr := }Mnu.InvokeCommand(Cmd); finally Mnu := nil; end; finally PMalloc.Free(PidlDrives); end; finally Desktop := nil; end; finally PMalloc := nil; end; end; function ExtractAssociatedIconSafe(FileName: string): HICON; var I: Word; PathSize: Integer; IconPath: PChar; begin I := 1; //allocate MAX_PATH chars to store path to icon (MSDN) PathSize := Max(MAX_PATH * 2, FileName.Length); GetMem(IconPath, PathSize * 2); try FillChar(IconPath^, PathSize * 2, #0); CopyMemory(IconPath, @FileName[1], FileName.Length * 2); Result := ExtractAssociatedIcon(Application.Handle, IconPath, I); finally FreeMem(IconPath); end; end; function ExtractAssociatedIconSafe(FileName: string; IconIndex: Word): HICON; begin Result := ExtractAssociatedIcon(Application.Handle, PChar(FileName), IconIndex); end; end.
unit BRegExp; //===================================================================== // BRegExp.pas : Borland Delphi 用 BREGEXP.DLL 利用ユニット // 1998/10/03版 osamu@big.or.jp // // BREGEXP.DLL は、http://www.hi-ho.or.jp/~babaq/ にて公開されている // Perl5互換の正規表現エンジン BREGEXP.DLL を Borland Delphi から利用 // するためのユニットファイルです。Delphi 3 で作成しましたが、32bit // 版の Delphi および C++ Builder で動作可能と思います。 // // BREGEXP.DLL の利用条件などは、同ホームページをご参照下さい。有用な // ライブラリを無償で提供下さっている babaq さんに感謝するとともに、 // 今後のご活躍を期待しています。 // // 本ユニットの著作権については、とやかく言うつもりはありません。好きな // ようにお使い下さい。ただし、利用に当たってはご自分の責任の下にお願 // いします。本ユニットに関して osamu@big.or.jp は何ら責任を負うことは // 無いものとします。 // // 本ユニットは、 DLL とともに配布されているヘッダファイル及び、上記ホーム // ページで行われたユーザサポートのログファイルをもとに作成されました。 // お気づきの点などありましたら、osamu@big.or.jp まで電子メールにて // お知らせ下されば、気分次第ではなんらかの対処をする可能性があります。(^_^; // // 使用方法については付属のヘルプファイルをご覧下さい。 //===================================================================== // 2001/04/14版 osamu@big.or.jp // 本家のドキュメントのバージョンアップに伴い発覚していたバグを修正 // brx 関数を導入 // 空文字に対する検索のエラー回避 // MatchPos を 1 から数え始めるように仕様変更 // Subst 後に Strings[] を参照可能にした // これに伴い大量の文字列に対する置き換え動作は遅くなった //===================================================================== interface uses SysUtils,Windows; //===================================================================== // 本家 BREGEXP.H と、サポートホームページのドキュメントより // BREGEXP.DLL と直結した宣言 //===================================================================== const BREGEXP_ERROR_MAX= 80; // エラーメッセージの最大長 type PPChar=^PChar; TBRegExpRec=packed record outp: PChar; // 置換え結果先頭ポインタ outendp: PChar; // 置換え結果末尾ポインタ splitctr: Integer; // split 結果カウンタ splitp: PPChar; // split 結果ポインタポインタ rsv1: Integer; // 予約済み parap: PChar; // コマンド文字列先頭ポインタ ('s/xxxxx/yy/gi') paraendp: PChar; // コマンド文字列末尾ポインタ transtblp: PChar; // tr テーブルへのポインタ startp: PPChar; // マッチした文字列への先頭ポインタ endp: PPChar; // マッチした文字列への末尾ポインタ nparens: Integer; // match/subst 中の括弧の数 end; pTBRegExpRec=^TBRegExpRec; {function BMatch(str, target, targetendp: PChar; var rxp: pTBRegExpRec; msg: PChar): Boolean; cdecl; external 'bregexp.dll'; function BSubst(str, target, targetendp: PChar; var rxp: pTBRegExpRec; msg: PChar): Boolean; cdecl; external 'bregexp.dll'; function BTrans(str, target, targetendp: PChar; var rxp: pTBRegExpRec; msg: PChar): Boolean; cdecl; external 'bregexp.dll'; function BSplit(str, target, targetendp: PChar; limit: Integer; var rxp: pTBRegExpRec; msg: PChar): Boolean; cdecl; external 'bregexp.dll'; procedure BRegFree(rx: pTBRegExpRec); cdecl; external 'bregexp.dll' name 'BRegfree'; function BRegExpVersion: PChar; cdecl; external 'bregexp.dll' name 'BRegexpVersion';} //===================================================================== // TBRegExp : BREGEXP.DLL の機能をカプセル化するオブジェクト //===================================================================== type EBRegExpError=class(Exception) end; TBRegExpMode=(brxNone, brxMatch, brxSplit); TBRegExp=class(TObject) private Mode: TBRegExpMode; pTargetString: PChar; pBRegExp: PTBRegExpRec; function GetMatchPos: Integer; function GetMatchLength: Integer; function GetSplitCount: Integer; function GetMatchStrings(index:Integer): string; function GetMatchCount: Integer; function GetCount: Integer; function GetStrings(index: Integer): string; function GetSplitStrings(index: Integer): string; function GetLastCommand: string; procedure CheckCommand(const Command: string); public destructor Destroy; override; public function Match(const Command, TargetString: string): Boolean; function Subst(const Command: string; var TargetString: string): Boolean; function Split(const Command, TargetString: string; Limit: Integer): Boolean; function Trans(const Command: string;var TargetString: string): Boolean; property LastCommand: string read GetLastCommand; property MatchPos: Integer read GetMatchPos; property MatchLength: Integer read GetMatchLength; property Count: Integer read GetCount; property Strings[index: Integer]: string read GetStrings; default; end; //===================================================================== // 自動的に実体化、破棄されるユーティリティインスタンス //===================================================================== function brx: TBRegExp; var BMatch:function (str, target, targetendp: PChar; var rxp: pTBRegExpRec; msg: PChar): Boolean;cdecl; BSubst:function (str, target, targetendp: PChar; var rxp: pTBRegExpRec; msg: PChar): Boolean;cdecl; BTrans:function (str, target, targetendp: PChar; var rxp: pTBRegExpRec; msg: PChar): Boolean;cdecl; BSplit:function (str, target, targetendp: PChar; limit: Integer; var rxp: pTBRegExpRec; msg: PChar): Boolean;cdecl; BRegFree:procedure (rx: pTBRegExpRec);cdecl; BRegExpVersion:function : PChar; cdecl;{cdecl;} hDLL:THandle; //===================================================================== implementation //===================================================================== var fbrx: TBRegExp; function brx: TBRegExp; begin if fbrx=nil then fbrx:=TBRegExp.Create; Result:=fbrx; end; //===================================================================== destructor TBRegExp.Destroy; begin if pBRegExp<>nil then BRegFree(pBRegExp); { FreeLibrary(hDLL);} inherited Destroy; end; //===================================================================== // 前回のコマンド文字列を返す function TBRegExp.GetLastCommand: string; var len: Integer; begin if pBRegExp=nil then begin Result:= ''; end else begin len:= Integer(pBRegExp^.paraendp)-Integer(pBRegExp^.parap); SetLength(Result, len); Move(pBRegExp^.parap^, Result[1], len); end; end; //===================================================================== // 前回と異なるコマンドであればキャッシュをクリアする内部手続き procedure TBRegExp.CheckCommand(const Command: string); var p,q: PChar; begin if pBRegExp=nil then Exit; p:= pBRegExp.parap - 1; q:= PChar(@Command[1]) - 1; repeat Inc(p); Inc(q); if p^<>q^ then begin BRegFree(pBRegExp); pBRegExp:= nil; Break; end; until p^=#0; end; //===================================================================== function TBRegExp.Match(const Command, TargetString: string): Boolean; var ErrorString: string; i: Integer; begin CheckCommand(Command); SetLength(ErrorString, BREGEXP_ERROR_MAX); Mode:=brxNone; if TargetString='' then begin // エラー回避 i:=0; Result:=BMatch( PChar(Command), PChar(@i), PChar(@i)+1, pBRegExp, PChar(ErrorString)); end else begin Result:=BMatch( PChar(Command), PChar(TargetString), PChar(TargetString)+Length(TargetString), pBRegExp, PChar(ErrorString)); end; SetLength(ErrorString, StrLen(PChar(ErrorString))); if ErrorString<>'' then raise EBRegExpError.Create(ErrorString); if Result then Mode:= brxMatch; pTargetString:= PChar(TargetString); end; //===================================================================== function TBRegExp.Subst(const Command: string; var TargetString: string): Boolean; const TextBuffer: string=''; var ErrorString: string; ep,sp: PPChar; i: Integer; begin CheckCommand(Command); Result:=False; if TargetString='' then Exit; TextBuffer:= TargetString; // ( ) を正しく返すためにテキストを保存する UniqueString(TextBuffer); SetLength(ErrorString, BREGEXP_ERROR_MAX); Mode:=brxNone; Result:=BSubst( PChar(Command), PChar(TargetString), PChar(TargetString)+Length(TargetString), pBRegExp, PChar(ErrorString)); SetLength(ErrorString,StrLen(PChar(ErrorString))); if ErrorString<>'' then raise EBRegExpError.Create(ErrorString); if Result then begin // ( ) の結果を正しく返すため sp:=pBRegExp^.startp; ep:=pBRegExp^.endp; for i:=0 to GetMatchCount-1 do begin Inc(ep^, Integer(TextBuffer)-Integer(TargetString)); Inc(sp^, Integer(TextBuffer)-Integer(TargetString)); Inc(sp); Inc(ep); end; TargetString:= pBRegExp^.outp; Mode:=brxMatch; end; end; //===================================================================== function TBRegExp.Trans(const Command: string; var TargetString: string): Boolean; var ErrorString: string; begin CheckCommand(Command); Mode:=brxNone; if TargetString='' then // エラー回避 TargetString:= #0; SetLength(ErrorString, BREGEXP_ERROR_MAX); Result:=BTrans( PChar(Command), PChar(TargetString), PChar(TargetString)+Length(TargetString), pBRegExp, PChar(ErrorString)); SetLength(ErrorString,StrLen(PChar(ErrorString))); if ErrorString<>'' then raise EBRegExpError.Create(ErrorString); if Result then TargetString:=pBRegExp^.outp; end; //===================================================================== function TBRegExp.Split(const Command, TargetString: string; Limit: Integer): Boolean; var ErrorString: string; t: string; begin CheckCommand(Command); SetLength(ErrorString, BREGEXP_ERROR_MAX); Mode:=brxNone; if TargetString='' then begin // エラー回避 t:= #0; Result:=BSplit( PChar(Command), PChar(t), PChar(t)+1, Limit, pBRegExp, PChar(ErrorString)); end else begin Result:=BSplit( PChar(Command), PChar(TargetString), PChar(TargetString)+Length(TargetString), Limit, pBRegExp, PChar(ErrorString)); end; SetLength(ErrorString,StrLen(PChar(ErrorString))); if ErrorString<>'' then raise EBRegExpError.Create(ErrorString); Mode:=brxSplit; end; //===================================================================== function TBRegExp.GetMatchPos: Integer; begin if Mode<>brxMatch then raise EBRegExpError.Create('no match pos'); Result:=Integer(pBRegExp.startp^)-Integer(pTargetString)+1; end; //===================================================================== function TBRegExp.GetMatchLength: Integer; begin if Mode<>brxMatch then raise EBRegExpError.Create('no match length'); Result:=Integer(pBRegExp.endp^)-Integer(pBRegExp.startp^); end; //===================================================================== function TBRegExp.GetCount: Integer; begin Result:=0; case Mode of brxNone: raise EBRegExpError.Create('no count now'); brxMatch: Result:=GetMatchCount; brxSplit: Result:=GetSplitCount; end; end; //===================================================================== function TBRegExp.GetMatchCount: Integer; begin Result:= pBRegExp^.nparens+1; end; //===================================================================== function TBRegExp.GetSplitCount: Integer; begin Result:=pBRegExp^.splitctr; end; //===================================================================== function TBRegExp.GetStrings(index: Integer): string; begin Result:=''; case Mode of brxNone: raise EBRegExpError.Create('no strings now'); brxMatch: Result:=GetMatchStrings(index); brxSplit: Result:=GetSplitStrings(index); end; end; //===================================================================== function TBRegExp.GetMatchStrings(index:Integer):string; var sp,ep: PPChar; begin Result:=''; if (index<0) or (index>=GetMatchCount) then raise EBRegExpError.Create('index out of range'); sp:=pBRegExp^.startp; Inc(sp, index); ep:=pBRegExp^.endp; Inc(ep, index); SetLength(Result,Integer(ep^)-Integer(sp^)); Move(sp^^,PChar(Result)^,Integer(ep^)-Integer(sp^)); end; //===================================================================== function TBRegExp.GetSplitStrings(index:Integer): string; var p: PPChar; sp,ep: PChar; begin if (index<0) or (index>=GetSplitCount) then raise EBRegExpError.Create('index out of range'); p:=pBRegExp^.splitp; Inc(p,index*2); sp:=p^; Inc(p); ep:=p^; SetLength(Result,Integer(ep)-Integer(sp)); Move(sp^,PChar(Result)^,Integer(ep)-Integer(sp)); end; //===================================================================== initialization hDLL := LoadLibrary('BREGEXP.DLL'); if hDLL = 0 then raise Exception.Create('BREGEXP.DLLのロードに失敗'#$d#$a'エラーコード=' +IntToStr(GetLastError)); @BMatch:= GetProcAddress(hDLL,'BMatch'); @BSubst:= GetProcAddress(hDLL,'BSubst'); @BTrans:= GetProcAddress(hDLL,'BTrans'); @BSplit:= GetProcAddress(hDLL,'BSplit'); @BRegFree:= GetProcAddress(hDLL,'BRegfree'); @BRegExpVersion:= GetProcAddress(hDLL,'BRegexpVersion'); finalization fbrx.Free; FreeLibrary(hDLL); end.
unit nsOptionsFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ExtCtrls, ShellAPI, nsGlobals, nsUtils, IdSMTP, ImgList, IdIOHandler, IdIOHandlerSocket, System.UITypes, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdMessage, System.ImageList; type TColorBox = class(ExtCtrls.TColorBox) protected procedure DrawItem(Index: integer; Rect: TRect; State: TOwnerDrawState); override; function PickCustomColor: Boolean; override; end; TfrmOptions = class(TForm) PageControl: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; GroupBox1: TGroupBox; rbDefaultProxy: TRadioButton; rbManualProxy: TRadioButton; rbNoProxy: TRadioButton; edtProxyName: TEdit; lblProxyName: TLabel; edtProxyPort: TEdit; lblProxyPort: TLabel; btnViewProxySettings: TButton; GroupBox2: TGroupBox; Label1: TLabel; Label2: TLabel; lbElements: TListBox; cbColors: TColorBox; chkBold: TCheckBox; chkItalic: TCheckBox; chkUnderline: TCheckBox; chkStrikeOut: TCheckBox; TabSheet3: TTabSheet; TabSheet4: TTabSheet; TabSheet5: TTabSheet; GroupBox5: TGroupBox; rbDefaultUseLast: TRadioButton; rbDefaultUseDefault: TRadioButton; Label9: TLabel; pnlFTP: TPanel; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Label15: TLabel; edtHost: TEdit; edtPort: TEdit; edtUser: TEdit; edtHostPwd: TEdit; edtHostDir: TEdit; chkPassive: TCheckBox; ckbDialup: TCheckBox; ckbDialupHangup: TCheckBox; pnlLocal: TPanel; Label16: TLabel; edtLocalFolder: TEdit; btnBrowseForLocalFolder: TButton; cbMediaType: TComboBox; ilOptions1: TImageList; GroupBox3: TGroupBox; trReadSpeed: TTrackBar; Label18: TLabel; Label19: TLabel; Label20: TLabel; Label22: TLabel; Label26: TLabel; Label24: TLabel; chkShowHidden: TCheckBox; Bevel5: TBevel; btnOK: TButton; btnCancel: TButton; btnHelp: TButton; GroupBox6: TGroupBox; Label6: TLabel; edtSMTPServer: TEdit; Label7: TLabel; edtSMTPPort: TEdit; chkSMTP: TCheckBox; edtSMTPAccount: TEdit; edtSMTPPassword: TEdit; lblSMTPAccount: TLabel; lblSMTPPassword: TLabel; GroupBox7: TGroupBox; Label10: TLabel; Label8: TLabel; edtSenderEMail: TEdit; GroupBox8: TGroupBox; Label5: TLabel; cbLanguages: TComboBox; GroupBox9: TGroupBox; ckbPlaySounds: TCheckBox; btSounds: TButton; GroupBox10: TGroupBox; Label4: TLabel; edtProjectDir: TEdit; Label17: TLabel; edtLogDir: TEdit; btnBrowseProjectDir: TButton; btnBrowseLogDir: TButton; chkUseSSL: TCheckBox; cbUseTLS: TComboBox; lblUseTLS: TLabel; GroupBox11: TGroupBox; Label25: TLabel; edtRecipEMail: TEdit; edtSenderName: TEdit; Label27: TLabel; edtRecipName: TEdit; trWriteSpeed: TTrackBar; EmailSender: TIdSMTP; Msg: TIdMessage; IdSSLIOHandlerSocketOpenSSL: TIdSSLIOHandlerSocketOpenSSL; btnTestSMTP: TButton; lblUseTLS2: TLabel; cbUseTLS2: TComboBox; procedure btnViewProxySettingsClick(Sender: TObject); procedure ConnectTypeClick(Sender: TObject); procedure lbElementsClick(Sender: TObject); procedure cbColorsSelect(Sender: TObject); procedure chkBoldClick(Sender: TObject); procedure chkItalicClick(Sender: TObject); procedure chkUnderlineClick(Sender: TObject); procedure chkStrikeOutClick(Sender: TObject); procedure chkSMTPClick(Sender: TObject); procedure btnHelpClick(Sender: TObject); procedure btSoundsClick(Sender: TObject); procedure ckbPlaySoundsClick(Sender: TObject); procedure btnBrowseForLocalFolderClick(Sender: TObject); procedure cbMediaTypeChange(Sender: TObject); procedure btnBrowseProjectDirClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnTestSMTPClick(Sender: TObject); private { Private declarations } FdrNormal: TItemDrawRec; FdrBackup: TItemDrawRec; FdrRestore: TItemDrawRec; // FdrDelete: TItemDrawRec; procedure GetOptions; procedure SetOptions; public { Public declarations } end; function DisplayOptionsDialog(AOwner: TForm; APage: integer = 0): Boolean; implementation {$R *.dfm} function DisplayOptionsDialog(AOwner: TForm; APage: integer = 0): Boolean; begin Result := False; with TfrmOptions.Create(AOwner) do try PageControl.ActivePageIndex := APage; GetOptions; if ShowModal = mrOk then begin SetOptions; Result := True; end; finally Free; end; end; { TOptionsForm } procedure TfrmOptions.GetOptions; var Media: TBackupMedia; begin edtProxyName.Text := g_ProxyName; edtProxyPort.Text := g_ProxyPort; case g_ConnectType of ftpcDefault: rbDefaultProxy.Checked := True; ftpcDirect: rbNoProxy.Checked := True; ftpcUseProxy: rbManualProxy.Checked := True; end; FdrNormal := g_drNormal; FdrRestore := g_drRestore; FdrBackup := g_drBackup; // FdrDelete := g_drDelete; lbElements.ItemIndex := 0; lbElements.OnClick(Self); // cbTextOptions.ItemIndex := Ord(g_NoTextLabels); // cbIconOptions.ItemIndex := Ord(g_LargeIcons); edtSMTPServer.Text := g_SMTPServer; edtSMTPPort.Text := IntToStr(g_SMTPPort); edtSMTPAccount.Text := g_SMTPAccount; edtSMTPPassword.Text := g_SMTPPassword; // edtCollisionFolder.Text := g_CollisionFolder; edtRecipEMail.Text := g_RecipEMail; edtRecipName.Text := g_RecipName; edtSenderEMail.Text := g_SenderEMail; edtSenderName.Text := g_SenderName; chkSMTP.Checked := g_AuthenticationType <> satNone; chkUseSSL.Checked := g_UseSSL; cbUseTLS.ItemIndex := Ord(g_UseTLS); chkSMTPClick(Self); ckbPlaySounds.Checked := g_PlaySounds; for Media := Low(TBackupMedia) to High(TBackupMedia) do cbMediaType.Items.Add(BackupMediaNames[Media]^); cbMediaType.ItemIndex := g_DefaultBackupMedia; cbMediaType.OnChange(Self); rbDefaultUseLast.Checked := g_DefaultBackupLast; rbDefaultUseDefault.Checked := g_DefaultBackupDefined; edtLocalFolder.Text := g_DefaultLocalFolder; edtHost.Text := g_DefaultHostName; edtPort.Text := g_DefaultPort; edtUser.Text := g_DefaultUserName; edtHostPwd.Text := g_DefaultPassword; edtHostDir.Text := g_DefaultHostDirName; chkPassive.Checked := g_DefaultUsePassive; ckbDialupHangup.Checked := g_DefaultHangUpOnCompleted; // 2.1 edtProjectDir.Text := g_ProjectsDir; edtLogDir.Text := g_LogDir; trReadSpeed.Position := g_ReadSpeed; trWriteSpeed.Position := g_WriteSpeed; chkShowHidden.Checked := g_ShowHidden; cbUseTLS2.ItemIndex := Ord(g_SSLVersion); end; procedure TfrmOptions.SetOptions; begin if rbDefaultProxy.Checked then g_ConnectType := ftpcDefault else if rbNoProxy.Checked then g_ConnectType := ftpcDirect else begin g_ConnectType := ftpcUseProxy; g_ProxyName := edtProxyName.Text; g_ProxyPort := edtProxyPort.Text; end; g_drNormal := FdrNormal; g_drRestore := FdrRestore; g_drBackup := FdrBackup; // g_NoTextLabels := Boolean(cbTextOptions.ItemIndex); // g_LargeIcons := Boolean(cbIconOptions.ItemIndex); g_SMTPServer := edtSMTPServer.Text; g_SMTPPort := StrToIntDef(edtSMTPPort.Text, 25); g_SMTPAccount := edtSMTPAccount.Text; g_SMTPPassword := edtSMTPPassword.Text; g_RecipEMail := edtRecipEMail.Text; g_RecipName := edtRecipName.Text; g_SenderEMail := edtSenderEMail.Text; g_SenderName := edtSenderName.Text; g_AuthenticationType := TIdSMTPAuthenticationType(chkSMTP.Checked); g_UseSSL := chkUseSSL.Checked; g_UseTLS := TIdUseTLS(cbUseTLS.ItemIndex); // g_CollisionFolder := edtCollisionFolder.Text; g_PlaySounds := ckbPlaySounds.Checked; g_DefaultBackupLast := rbDefaultUseLast.Checked; g_DefaultBackupDefined := rbDefaultUseDefault.Checked; g_DefaultBackupMedia := cbMediaType.ItemIndex; g_DefaultLocalFolder := edtLocalFolder.Text; g_DefaultHostName := edtHost.Text; g_DefaultPort := edtPort.Text; g_DefaultUserName := edtUser.Text; g_DefaultPassword := edtHostPwd.Text; g_DefaultHostDirName := edtHostDir.Text; g_DefaultUsePassive := chkPassive.Checked; g_DefaultHangUpOnCompleted := ckbDialupHangup.Checked; // 2.1 if DirectoryExists(edtProjectDir.Text) then g_ProjectsDir := IncludeTrailingPathDelimiter(edtProjectDir.Text); if DirectoryExists(edtLogDir.Text) then g_LogDir := IncludeTrailingPathDelimiter(edtLogDir.Text); g_ReadSpeed := trReadSpeed.Position; g_WriteSpeed := trWriteSpeed.Position; g_ShowHidden := chkShowHidden.Checked; g_SSLVersion := TIdSSLVersion(cbUseTLS2.ItemIndex); end; procedure TfrmOptions.btnViewProxySettingsClick(Sender: TObject); begin ShellExecute(Handle, pOpen, 'control.exe', 'inetcpl.cpl,@0,0', nil, SW_SHOWNORMAL); GetDefaultProxySettings(g_ProxyName, g_ProxyPort); end; procedure TfrmOptions.ConnectTypeClick(Sender: TObject); begin lblProxyName.Enabled := rbManualProxy.Checked; edtProxyName.Enabled := rbManualProxy.Checked; lblProxyPort.Enabled := rbManualProxy.Checked; edtProxyPort.Enabled := rbManualProxy.Checked; end; procedure TfrmOptions.lbElementsClick(Sender: TObject); begin case lbElements.ItemIndex of 0: begin cbColors.Selected := FdrNormal.Color; chkBold.Checked := fsBold in FdrNormal.Style; chkUnderline.Checked := fsUnderline in FdrNormal.Style; chkItalic.Checked := fsItalic in FdrNormal.Style; chkStrikeOut.Checked := fsStrikeOut in FdrNormal.Style; end; 1: begin cbColors.Selected := FdrBackup.Color; chkBold.Checked := fsBold in FdrBackup.Style; chkUnderline.Checked := fsUnderline in FdrBackup.Style; chkItalic.Checked := fsItalic in FdrBackup.Style; chkStrikeOut.Checked := fsStrikeOut in FdrBackup.Style; end; 2: begin cbColors.Selected := FdrRestore.Color; chkBold.Checked := fsBold in FdrRestore.Style; chkUnderline.Checked := fsUnderline in FdrRestore.Style; chkItalic.Checked := fsItalic in FdrRestore.Style; chkStrikeOut.Checked := fsStrikeOut in FdrRestore.Style; end; (* 3: begin cbColors.Selected := FdrDelete.Color; chkBold.Checked := fsBold in FdrDelete.Style; chkUnderline.Checked := fsUnderline in FdrDelete.Style; chkItalic.Checked := fsItalic in FdrDelete.Style; chkStrikeOut.Checked := fsStrikeOut in FdrDelete.Style; end; *) end; end; procedure TfrmOptions.cbColorsSelect(Sender: TObject); begin case lbElements.ItemIndex of 0: FdrNormal.Color := cbColors.Selected; 1: FdrBackup.Color := cbColors.Selected; 2: FdrRestore.Color := cbColors.Selected; // 3: FdrDelete.Color := cbColors.Selected; end; end; procedure TfrmOptions.chkBoldClick(Sender: TObject); begin case lbElements.ItemIndex of 0: if chkBold.Checked then FdrNormal.Style := FdrNormal.Style + [fsBold] else FdrNormal.Style := FdrNormal.Style - [fsBold]; 1: if chkBold.Checked then FdrBackup.Style := FdrBackup.Style + [fsBold] else FdrBackup.Style := FdrBackup.Style - [fsBold]; 2: if chkBold.Checked then FdrRestore.Style := FdrRestore.Style + [fsBold] else FdrRestore.Style := FdrRestore.Style - [fsBold]; (* 3: if chkBold.Checked then FdrDelete.Style := FdrDelete.Style + [fsBold] else FdrDelete.Style := FdrDelete.Style - [fsBold]; *) end; end; procedure TfrmOptions.chkItalicClick(Sender: TObject); begin case lbElements.ItemIndex of 0: if chkItalic.Checked then FdrNormal.Style := FdrNormal.Style + [fsItalic] else FdrNormal.Style := FdrNormal.Style - [fsItalic]; 1: if chkItalic.Checked then FdrBackup.Style := FdrBackup.Style + [fsItalic] else FdrBackup.Style := FdrBackup.Style - [fsItalic]; 2: if chkItalic.Checked then FdrRestore.Style := FdrRestore.Style + [fsItalic] else FdrRestore.Style := FdrRestore.Style - [fsItalic]; (* 3: if chkItalic.Checked then FdrDelete.Style := FdrDelete.Style + [fsItalic] else FdrDelete.Style := FdrDelete.Style - [fsItalic]; *) end; end; procedure TfrmOptions.chkUnderlineClick(Sender: TObject); begin case lbElements.ItemIndex of 0: if chkUnderline.Checked then FdrNormal.Style := FdrNormal.Style + [fsUnderline] else FdrNormal.Style := FdrNormal.Style - [fsUnderline]; 1: if chkUnderline.Checked then FdrBackup.Style := FdrBackup.Style + [fsUnderline] else FdrBackup.Style := FdrBackup.Style - [fsUnderline]; 2: if chkUnderline.Checked then FdrRestore.Style := FdrRestore.Style + [fsUnderline] else FdrRestore.Style := FdrRestore.Style - [fsUnderline]; (* 3: if chkUnderline.Checked then FdrDelete.Style := FdrDelete.Style + [fsUnderline] else FdrDelete.Style := FdrDelete.Style - [fsUnderline]; *) end; end; procedure TfrmOptions.chkStrikeOutClick(Sender: TObject); begin case lbElements.ItemIndex of 0: if chkStrikeOut.Checked then FdrNormal.Style := FdrNormal.Style + [fsStrikeOut] else FdrNormal.Style := FdrNormal.Style - [fsStrikeOut]; 1: if chkStrikeOut.Checked then FdrBackup.Style := FdrBackup.Style + [fsStrikeOut] else FdrBackup.Style := FdrBackup.Style - [fsStrikeOut]; 2: if chkStrikeOut.Checked then FdrRestore.Style := FdrRestore.Style + [fsStrikeOut] else FdrRestore.Style := FdrRestore.Style - [fsStrikeOut]; (* 3: if chkStrikeOut.Checked then FdrDelete.Style := FdrDelete.Style + [fsStrikeOut] else FdrDelete.Style := FdrDelete.Style - [fsStrikeOut]; *) end; end; procedure TfrmOptions.chkSMTPClick(Sender: TObject); const DisArray: array[Boolean] of TColor = (clBtnFace, clWindow); begin edtSMTPAccount.Enabled := chkSMTP.Checked; edtSMTPAccount.Color := DisArray[chkSMTP.Checked]; lblSMTPAccount.Enabled := chkSMTP.Checked; edtSMTPPassword.Enabled := chkSMTP.Checked; edtSMTPPassword.Color := DisArray[chkSMTP.Checked]; lblSMTPPassword.Enabled := chkSMTP.Checked; cbUseTLS.Enabled := chkUseSSL.Checked; lblUseTLS.Enabled := chkUseSSL.Checked; cbUseTLS2.Enabled := chkUseSSL.Checked; lblUseTLS2.Enabled := chkUseSSL.Checked; end; procedure TfrmOptions.btnHelpClick(Sender: TObject); begin Application.HelpContext(PageControl.ActivePage.HelpContext); end; procedure TfrmOptions.btnTestSMTPClick(Sender: TObject); begin if not IsValidEmail(edtRecipEMail.Text) then begin MessageDlg(sEnterValidEmail, mtWarning, [mbOK], 0); if edtRecipEMail.CanFocus then edtRecipEMail.SetFocus; Exit; end; if chkUseSSL.Checked then begin EmailSender.IOHandler := IdSSLIOHandlerSocketOpenSSL; EmailSender.UseTLS := TIdUseTLS(cbUseTLS.ItemIndex); IdSSLIOHandlerSocketOpenSSL.SSLOptions.Method := TIdSSLVersion(cbUseTLS2.ItemIndex); end else begin EmailSender.IOHandler := nil; EmailSender.UseTLS := utNoTLSSupport; end; EmailSender.Host := edtSMTPServer.Text; EmailSender.Port := StrToIntDef(edtSMTPPort.Text, 25); if chkSMTP.Checked then begin EmailSender.Username := edtSMTPAccount.Text; EmailSender.Password := edtSMTPPassword.Text; end else begin EmailSender.Username := EmptyStr; EmailSender.Password := EmptyStr; end; try Screen.Cursor := crHourGlass; btnTestSMTP.Enabled := False; try EmailSender.Connect; Msg.From.Address := edtSenderEMail.Text; Msg.From.Name := edtSenderName.Text; Msg.Recipients.EMailAddresses := edtRecipEMail.Text; Msg.Subject := sEmailTestSubject; Msg.Body.Text := sEmailTestBody; EmailSender.Send(Msg); MessageDlg(Format(sEmailTestSend, [edtRecipEMail.Text]), mtInformation, [mbOK], 0); finally Screen.Cursor := crDefault; btnTestSMTP.Enabled := True; if EmailSender.Connected then EmailSender.Disconnect; end; except on E: Exception do MessageDlg(Format(sErrorConnecting, [E.Message]), mtWarning, [mbOK], 0); end; end; procedure TfrmOptions.btSoundsClick(Sender: TObject); begin ShellExecute(0, pOpen, 'rundll32.exe', 'shell32.dll,Control_RunDLL mmsys.cpl', '', SW_SHOWNORMAL); end; procedure TfrmOptions.ckbPlaySoundsClick(Sender: TObject); begin btSounds.Enabled := ckbPlaySounds.Checked; end; procedure TfrmOptions.btnBrowseForLocalFolderClick(Sender: TObject); var sFolder: string; begin sFolder := edtLocalFolder.Text; if SelectDir(sSelectBackupPath, sFolder) then edtLocalFolder.Text := sFolder; end; procedure TfrmOptions.cbMediaTypeChange(Sender: TObject); begin pnlLocal.Visible := cbMediaType.ItemIndex = 0; pnlFTP.Visible := cbMediaType.ItemIndex = 1; end; procedure TfrmOptions.btnBrowseProjectDirClick(Sender: TObject); var Edt: TEdit; sFolder: String; begin case (Sender as TButton).Tag of 1: Edt := edtProjectDir; 2: Edt := edtLogDir; else Exit; end; sFolder := Edt.Text; if SelectDir(sSelectFolder, sFolder) then Edt.Text := sFolder; end; { TColorBox } procedure TColorBox.DrawItem(Index: integer; Rect: TRect; State: TOwnerDrawState); function ColorToBorderColor(AColor: TColor): TColor; type TColorQuad = record Red, Green, Blue, Alpha: byte; end; begin if (TColorQuad(AColor).Red > 192) or (TColorQuad(AColor).Green > 192) or (TColorQuad(AColor).Blue > 192) then Result := clBlack else if odSelected in State then Result := clWhite else Result := AColor; end; var LRect: TRect; LBackground: TColor; begin with Canvas do begin FillRect(Rect); LBackground := Brush.Color; LRect := Rect; // LRect.Right := LRect.Bottom - LRect.Top + LRect.Left; InflateRect(LRect, -1, -1); if Index = 0 then begin DrawText(Handle, PChar(SCustom), -1, LRect, DT_CENTER); Exit; end; Brush.Color := Colors[Index]; if Brush.Color = clDefault then Brush.Color := DefaultColorColor else if Brush.Color = clNone then Brush.Color := NoneColorColor; FillRect(LRect); Brush.Color := ColorToBorderColor(ColorToRGB(Brush.Color)); FrameRect(LRect); Brush.Color := LBackground; // Rect.Left := LRect.Right + 5; // TextRect(Rect, Rect.Left, Rect.Top + (Rect.Bottom - Rect.Top - TextHeight(Items[Index])) div 2, Items[Index]); end; end; function TColorBox.PickCustomColor: Boolean; var LColor: TColor; dlgColor: TColorDialog; begin dlgColor := TColorDialog.Create(Self); try LColor := ColorToRGB(TColor(Items.Objects[0])); Color := LColor; dlgColor.CustomColors.Text := Format('ColorA=%.8x', [LColor]); Result := dlgColor.Execute; if Result then begin Items.Objects[0] := TObject(Color); Self.Invalidate; end; finally FreeAndNil(dlgColor); end; end; procedure TfrmOptions.FormShow(Sender: TObject); begin UpdateVistaFonts(Self); end; end.
namespace Sugar.Collections; interface type HashSet<T> = public class mapped to {$IF COOPER}java.util.HashSet<T>{$ELSEIF ECHOES}System.Collections.Generic.HashSet<T>{$ELSEIF NOUGAT}Foundation.NSMutableSet{$ENDIF} public constructor; mapped to constructor(); method &Add(Item: T): Boolean; method Clear; mapped to {$IF COOPER OR ECHOES}Clear{$ELSE}removeAllObjects{$ENDIF}; method Contains(Item: T): Boolean; method &Remove(Item: T): Boolean; method ForEach(Action: Action<T>); property Count: Integer read {$IF ECHOES OR NOUGAT}mapped.Count{$ELSE}mapped.size{$ENDIF}; end; implementation method HashSet<T>.&Add(Item: T): Boolean; begin {$IF COOPER OR ECHOES} exit mapped.Add(Item); {$ELSEIF NOUGAT} var lSize := mapped.count; mapped.addObject(NullHelper.ValueOf(Item)); exit lSize < mapped.count; {$ENDIF} end; method HashSet<T>.Contains(Item: T): Boolean; begin {$IF COOPER OR ECHOES} exit mapped.Contains(Item); {$ELSEIF NOUGAT} exit mapped.containsObject(NullHelper.ValueOf(Item)); {$ENDIF} end; method HashSet<T>.&Remove(Item: T): Boolean; begin {$IF COOPER OR ECHOES} exit mapped.Remove(Item); {$ELSEIF NOUGAT} var lSize := mapped.count; mapped.removeObject(NullHelper.ValueOf(Item)); exit lSize > mapped.count; {$ENDIF} end; method HashSet<T>.ForEach(Action: Action<T>); begin if Action = nil then raise new Sugar.SugarArgumentNullException("Action"); {$IF COOPER} var Enumerator := mapped.Iterator; while Enumerator.hasNext do Action(Enumerator.next); {$ELSEIF ECHOES} var Enumerator := mapped.GetEnumerator; while Enumerator.MoveNext do Action(Enumerator.Current); {$ELSEIF NOUGAT} var Enumerator := mapped.objectEnumerator; var item := Enumerator.nextObject; while item <> nil do begin Action(NullHelper.ValueOf(item)); item := Enumerator.nextObject; end; {$ENDIF} end; end.
unit CFButtonEdit; interface uses Windows, Classes, Controls, CFControl, Graphics, Messages, CFEdit; type TCBEdit = class(TCFEdit); TCButtonStyle = (cbsLookUp, cbsDrop, cbsFind, cbsFold, cbsNew, cbsOpen, cbsDateTime); TCCustomButtonEdit = class(TCFTextControl) private FEdit: TCBEdit; FButtonStyle: TCButtonStyle; FBtnMouseState: TMouseState; FButtonLeft: Integer; FOnButtonClick: TNotifyEvent; function GetHelpText: string; procedure SetHelpText(const Value: string); procedure SetButtonStyle(Value: TCButtonStyle); protected procedure DoButtonClick; virtual; procedure DrawControl(ACanvas: TCanvas); override; procedure AdjustBounds; override; function GetReadOnly: Boolean; procedure SetReadOnly(Value: Boolean); function GetText: string; procedure SetText(Value: string); function GetOnChange: TNotifyEvent; procedure SetOnChange(Value: TNotifyEvent); // 通过Tab移入焦点 procedure CMUIActivate(var Message: TMessage); message CM_UIACTIVATE; // 通过Tab移出焦点 procedure CMUIDeActivate(var Message: TMessage); message CM_UIDEACTIVATE; // 字体变化 procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; // 左键双击 procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK; // procedure CMMouseEnter(var Msg: TMessage ); message CM_MOUSEENTER; procedure CMMouseLeave(var Msg: TMessage ); message CM_MOUSELEAVE; procedure KeyPress(var Key: Char); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; // procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property ButtonStyle: TCButtonStyle read FButtonStyle write SetButtonStyle; property OnButtonClick: TNotifyEvent read FOnButtonClick write FOnButtonClick; property ReadOnly: Boolean read GetReadOnly write SetReadOnly; property Text: string read GetText write SetText; property OnChange: TNotifyEvent read GetOnChange write SetOnChange; published property HelpText: string read GetHelpText write SetHelpText; end; TCFButtonEdit = class(TCCustomButtonEdit) published property ButtonStyle; property OnButtonClick; property ReadOnly; property Text; property OnChange; end; implementation {$R CFButtonEdit.RES} { TCCustomButtonEdit } procedure TCCustomButtonEdit.AdjustBounds; var DC: HDC; vHeight, vWidth: Integer; begin DC := GetDC(0); try Canvas.Handle := DC; Canvas.Font.Assign(Font); //vWidth := GIconWidth + 2 * GPadding + GetSystemMetrics(SM_CYBORDER) * 4 + GMinWidth; vWidth := GIconWidth + GBorderWidth + GBorderWidth + GMinWidth; if vWidth < Width then begin if Assigned(FEdit) then FEdit.Width := Width - (GIconWidth + GBorderWidth + GBorderWidth); vWidth := Width; end; if Assigned(FEdit) then vHeight := FEdit.Height else vHeight := Canvas.TextHeight('字') + GetSystemMetrics(SM_CYBORDER) * 4 + GBorderWidth + GBorderWidth; // 和Edit的计算方式一致 Canvas.Handle := 0; finally ReleaseDC(0, DC); end; SetBounds(Left, Top, vWidth, vHeight); end; procedure TCCustomButtonEdit.CMFontChanged(var Message: TMessage); begin FEdit.Font := Font; AdjustBounds; inherited; end; procedure TCCustomButtonEdit.CMMouseEnter(var Msg: TMessage); begin inherited; UpdateDirectUI; end; procedure TCCustomButtonEdit.CMMouseLeave(var Msg: TMessage); begin inherited; FBtnMouseState := FBtnMouseState - [cmsMouseIn]; UpdateDirectUI; end; procedure TCCustomButtonEdit.CMUIActivate(var Message: TMessage); begin Message.Result := FEdit.Perform(Message.Msg, Message.WParam, Message.LParam); end; procedure TCCustomButtonEdit.CMUIDeActivate(var Message: TMessage); begin Message.Result := FEdit.Perform(Message.Msg, Message.WParam, Message.LParam); end; constructor TCCustomButtonEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FBtnMouseState := []; FEdit := TCBEdit.Create(Self); FEdit.Parent := Self; Width := Width + GIconWidth; end; destructor TCCustomButtonEdit.Destroy; begin FEdit.Free; inherited; end; procedure TCCustomButtonEdit.DoButtonClick; begin if Assigned(FOnButtonClick) then FOnButtonClick(Self); end; procedure TCCustomButtonEdit.DrawControl(ACanvas: TCanvas); var vRect: TRect; //vIcon: HICON; vBmp: TBitmap; begin inherited DrawControl(ACanvas); vRect := Rect(0, 0, Width, Height); // 背景 ACanvas.Brush.Style := bsSolid; if FEdit.ReadOnly then ACanvas.Brush.Color := GReadOlnyBackColor; if BorderVisible then // 边框 begin if Self.Focused or (cmsMouseIn in MouseState) then ACanvas.Pen.Color := GBorderHotColor else ACanvas.Pen.Color := GBorderColor; ACanvas.Pen.Style := psSolid; end else ACanvas.Pen.Style := psClear; if RoundCorner > 0 then ACanvas.RoundRect(vRect, RoundCorner, RoundCorner) else ACanvas.Rectangle(vRect); vBmp := TBitmap.Create; try vBmp.Transparent := True; case FButtonStyle of cbsDrop: vBmp.LoadFromResourceName(HInstance, 'DROPDOWN'); cbsFind: vBmp.LoadFromResourceName(HInstance, 'FIND'); cbsLookUp: vBmp.LoadFromResourceName(HInstance, 'LOOKUP'); cbsFold: vBmp.LoadFromResourceName(HInstance, 'FOLD'); cbsNew: vBmp.LoadFromResourceName(HInstance, 'NEW'); cbsOpen: vBmp.LoadFromResourceName(HInstance, 'OPEN'); cbsDateTime: vBmp.LoadFromResourceName(HInstance, 'DATETIME'); end; {ACanvas.Pen.Color := GLineColor; ACanvas.MoveTo(FButtonLeft, GBorderWidth); ACanvas.LineTo(FButtonLeft, Height - GBorderWidth);} ACanvas.Draw(FButtonLeft, (Height - GIconWidth) div 2, vBmp); finally vBmp.Free; end; end; function TCCustomButtonEdit.GetHelpText: string; begin Result := FEdit.HelpText; end; function TCCustomButtonEdit.GetOnChange: TNotifyEvent; begin Result := FEdit.OnChange; end; function TCCustomButtonEdit.GetReadOnly: Boolean; begin Result := FEdit.ReadOnly; end; function TCCustomButtonEdit.GetText: string; begin Result := FEdit.Text; end; procedure TCCustomButtonEdit.KeyDown(var Key: Word; Shift: TShiftState); begin FEdit.KeyDown(Key, Shift); end; procedure TCCustomButtonEdit.KeyPress(var Key: Char); begin FEdit.KeyPress(Key); end; procedure TCCustomButtonEdit.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if PtInRect(FEdit.ClientRect, Point(X, Y)) then FEdit.MouseDown(Button, Shift, X, Y); end; procedure TCCustomButtonEdit.MouseMove(Shift: TShiftState; X, Y: Integer); var vRect: TRect; begin inherited; if PtInRect(FEdit.ClientRect, Point(X, Y)) then begin Self.Cursor := crIBeam; FEdit.MouseMove(Shift, X, Y); end else begin Self.Cursor := crDefault; vRect := Rect(Width - GIconWidth - GPadding, (Height - GIconWidth) div 2, Width - GBorderWidth, Height - GBorderWidth); if PtInRect(vRect, Point(X, Y)) then begin if not (cmsMouseIn in FBtnMouseState) then begin FBtnMouseState := FBtnMouseState + [cmsMouseIn]; UpdateDirectUI(vRect); end; end else begin if cmsMouseIn in FBtnMouseState then begin FBtnMouseState := FBtnMouseState - [cmsMouseIn]; UpdateDirectUI(vRect); end; end; end; end; procedure TCCustomButtonEdit.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if PtInRect(FEdit.ClientRect, Point(X, Y)) then FEdit.MouseUp(Button, Shift, X, Y) else if PtInRect(Rect(Width - GIconWidth - GPadding * 2, GBorderWidth, Width - GBorderWidth, Height - GBorderWidth), Point(X, Y)) then DoButtonClick; end; procedure TCCustomButtonEdit.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin if Assigned(FEdit) then // 设计期 begin FEdit.SetBounds(0, 0, Width - GIconWidth - GBorderWidth, AHeight); FButtonLeft := FEdit.Left + FEdit.Width; end; inherited; end; procedure TCCustomButtonEdit.SetButtonStyle(Value: TCButtonStyle); begin if FButtonStyle <> Value then begin FButtonStyle := Value; UpdateDirectUI; end; end; procedure TCCustomButtonEdit.SetHelpText(const Value: string); begin FEdit.HelpText := Value; end; procedure TCCustomButtonEdit.SetOnChange(Value: TNotifyEvent); begin FEdit.OnChange := Value; end; procedure TCCustomButtonEdit.SetReadOnly(Value: Boolean); begin FEdit.ReadOnly := Value; end; procedure TCCustomButtonEdit.SetText(Value: string); begin FEdit.Text := Value; end; procedure TCCustomButtonEdit.WMLButtonDblClk(var Message: TWMLButtonDblClk); begin inherited; if PtInRect(FEdit.ClientRect, Point(Message.XPos, Message.YPos)) then FEdit.WMLButtonDblClk(Message); end; end.
unit Demo.MaterialScatterChart.DualY; interface uses System.Classes, Demo.BaseFrame, cfs.GCharts; type TDemo_MaterialScatterChart_DualY = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation procedure TDemo_MaterialScatterChart_DualY.GenerateChart; var Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally begin Chart := TcfsGChartProducer.Create; Chart.ClassChartType := TcfsGChartProducer.CLASS_MATERIAL_SCATTER_CHART; // Data Chart.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Student ID'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Hours Studied'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Final') ]); Chart.Data.AddRow([0, 0, 67]); Chart.Data.AddRow([1, 1, 88]); Chart.Data.AddRow([2, 2, 77]); Chart.Data.AddRow([3, 3, 93]); Chart.Data.AddRow([4, 4, 85]); Chart.Data.AddRow([5, 5, 91]); Chart.Data.AddRow([6, 6, 71]); Chart.Data.AddRow([7, 7, 78]); Chart.Data.AddRow([8, 8, 93]); Chart.Data.AddRow([9, 9, 80]); Chart.Data.AddRow([10, 10, 82]); Chart.Data.AddRow([11, 0, 75]); Chart.Data.AddRow([12, 5, 80]); Chart.Data.AddRow([13, 3, 90]); Chart.Data.AddRow([14, 1, 72]); Chart.Data.AddRow([15, 5, 75]); Chart.Data.AddRow([16, 6, 68]); Chart.Data.AddRow([17, 7, 98]); Chart.Data.AddRow([18, 3, 82]); Chart.Data.AddRow([19, 9, 94]); Chart.Data.AddRow([20, 2, 79]); Chart.Data.AddRow([21, 2, 95]); Chart.Data.AddRow([22, 2, 86]); Chart.Data.AddRow([23, 3, 67]); Chart.Data.AddRow([24, 4, 60]); Chart.Data.AddRow([25, 2, 80]); Chart.Data.AddRow([26, 6, 92]); Chart.Data.AddRow([27, 2, 81]); Chart.Data.AddRow([28, 8, 79]); Chart.Data.AddRow([29, 9, 83]); // Options Chart.Options.Title('Students'' Final Grades'); Chart.Options.Subtitle('based on hours studied'); Chart.Options.Series(['0: {axis: ''hours studied''}', '1: {axis: ''final grade''}']); Chart.Options.Axes('y', '{''hours studied'': {label: ''Hours Studied'' }, ''final grade'': {label: ''Final Exam Grade''}}'); // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetBody( '<div style="width:80%; height:10%"></div>' + '<div id="Chart" style="width:80%; height:80%;margin: auto"></div>' + '<div style="width:80%; height:10%"></div>' ); GChartsFrame.DocumentGenerate('Chart', Chart); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_MaterialScatterChart_DualY); end.
// Copyright (c) 2009, ConTEXT Project Ltd // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. unit uMultiLanguage; interface {$I ConTEXT.inc} uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Menus, ActnList, IniFiles, Buttons, JclFileUtils; function mlLoadLanguageFile(fname: string): boolean; function mlEnumerateAllLanguages(path: string): TStringList; procedure mlEnumerateDispose(var ss: TStringList); function mlStr(index: integer; default: string): string; procedure mlApplyLanguageToForm(form: TWinControl; name: string); const LANGUAGE_DIR = 'language\'; ML_MAIN_HINT_NOTDEFINED = 01000; ML_MAIN_CANNOT_EXPORT_TXT_FILES = 01001; ML_MAIN_CLOSE_FILES = 01010; ML_MAIN_CLOSE_ALL_OPEN_FILES = 01011; ML_MAIN_CONFIRM_CAPT = 01012; ML_MAIN_OVERWRITE_WARNING = 01013; ML_MAIN_ACCESS_DENIED_ON_FILE = 01014; ML_TAB_CONVERSION_CAPTION = 01020; ML_TAB_CONVERSION_QUERY = 01021; ML_RENAME_FILE_CAPTION = 01100; ML_RENAME_FILE_NEW_FILENAME = 01101; ML_RENAME_FILE_ERR_EXISTS = 01102; ML_RENAME_FILE_ERROR = 01103; ML_REVERT_TO_BACKUP_QUERY = 01110; ML_REVERT_TO_SAVED_QUERY = 01111; ML_MAIN_TB_HINT_NEW = 01300; ML_MAIN_TB_HINT_OPEN = 01301; ML_MAIN_TB_HINT_SAVE = 01302; ML_MAIN_TB_HINT_SAVE_ALL = 01303; ML_MAIN_TB_HINT_CLOSE = 01304; ML_MAIN_TB_HINT_PRINT = 01305; ML_MAIN_TB_HINT_PRINT_PREVIEW = 01306; ML_MAIN_TB_HINT_CUT = 01307; ML_MAIN_TB_HINT_COPY = 01308; ML_MAIN_TB_HINT_PASTE = 01309; ML_MAIN_TB_HINT_UNDO = 01310; ML_MAIN_TB_HINT_REDO = 01311; ML_MAIN_TB_HINT_FIND = 01312; ML_MAIN_TB_HINT_FIND_NEXT = 01313; ML_MAIN_TB_HINT_REPLACE = 01314; ML_MAIN_TB_HINT_WORDWRAP = 01315; ML_MAIN_TB_HINT_STAY_ON_TOP = 01316; ML_MAIN_TB_HINT_ACTIVE_HIGHLIGHTER = 01317; ML_MAIN_TB_HINT_HELP = 01318; ML_CUSTTYP_EXT_EDIT_CAPTION = 02000; ML_CUSTTYP_EXT_EDIT_TEXT = 02001; ML_EDIT_MODIFIED = 03000; ML_EDIT_INSERT = 03001; ML_EDIT_OVERWRITE = 03002; ML_EDIT_RECORDING = 03003; ML_EDIT_SEL_NORMAL = 03004; ML_EDIT_SEL_COLUMN = 03005; ML_EDIT_FILE_SIZE = 03006; ML_EDIT_READONLY_MARKER = 03007; ML_EDIT_CHARS_COUNT_CAPTION = 03008; ML_EDIT_LINES_COUNT_CAPTION = 03009; ML_EDIT_ERR_OPENING = 03010; ML_EDIT_ERR_SAVING = 03011; ML_EDIT_ERR_CAPTION = 03012; ML_EDIT_WARN_FILE_CHANGED = 03013; ML_EDIT_WARN_FILE_DELETED = 03014; ML_EDIT_WARN_FILE_NOT_SAVED = 03015; ML_EDIT_ERR_SAVING_BACKUP = 03016; ML_EDIT_READ_ONLY_WARNING = 03017; ML_EDIT_GOTO_CAPTION = 03020; ML_EDIT_GOTO_TEXT = 03021; ML_FIND_CAPT_FIND = 04000; ML_FIND_CAPT_REPLACE = 04001; ML_FIND_FIND_BTN_CAPTION = 04002; ML_FIND_FINDNEXT_BTN_CAPTION = 04003; ML_FIND_NOT_FOUND = 04010; ML_FIND_REPLACE_REPORT = 04011; ML_FIND_MACROSTOP = 04012; ML_FIND_PANEL_CAPTION = 04020; ML_MACRO_SYNTAX_ERROR = 05100; ML_MACRO_ERR_SAVING = 05101; ML_MACROSTART_CAPT = 06500; ML_MACROEDIT_CAPT = 06501; ML_MACRO_SAVE_PROMPT = 06502; ML_MACRO_MANAGE_LV_CAPT_NAME = 06510; ML_MACRO_MANAGE_LV_CAPT_SHORTCUT = 06511; ML_MACRO_MANAGE_LV_CAPT_ENABLED = 06512; ML_MACRO_START_HOTKEY_USED = 07000; ML_MACRO_START_HOTKEY_DEFINED = 07001; ML_OPT_USER_EXEC_KEYS = 08000; ML_OPT_USER_EXT_EDIT_CAPT = 08001; ML_OPT_USER_EXT_EDIT_TEXT = 08002; ML_OPT_USER_DEL_USR_CMD = 08003; ML_OPT_ASSOC_CAPT = 08010; ML_OPT_ASSOC_TEXT = 08011; ML_OPT_ASSOC_DEL = 08012; ML_OPT_LANGUAGE_CHANGE = 08013; ML_OPT_SELECT_BACKUP_DIR = 08014; ML_OPT_ASSOC_EXEFILES_NOT_ALLOWED = 08015; ML_OPT_ONSTART_NOTHING = 08020; ML_OPT_ONSTART_CREATE_BLANK_FILE = 08021; ML_OPT_ONSTART_OPEN_LAST_FILE = 08022; ML_OPT_CURSOR_SHAPE1 = 08100; ML_OPT_CURSOR_SHAPE2 = 08101; ML_OPT_CURSOR_SHAPE3 = 08102; ML_OPT_CURSOR_SHAPE4 = 08103; ML_OPT_FGBG_CAPT1 = 08110; ML_OPT_FGBG_CAPT2 = 08111; ML_OPT_TABSMODE1 = 08125; ML_OPT_TABSMODE2 = 08126; ML_OPT_KEYS_LV_COMMAND = 08200; ML_OPT_KEYS_LV_SHORTCUT = 08201; ML_OPT_KEYS_DEFAULT_WARNING = 08205; ML_OPT_HELP_LV_FILETYPE = 08210; ML_OPT_HELP_LV_HELPFILE = 08211; ML_OPT_EXEC_SAVE_CURRENT = 08300; ML_OPT_EXEC_SAVE_ALL = 08301; ML_OPT_EXEC_SAVE_NONE = 08302; ML_PRN_INVALID_NUM = 09000; ML_PRN_NO_DRIVER = 09010; ML_PRN_PAGE_NUM = 09020; ML_PRN_ZOOM1 = 09030; ML_PRN_ZOOM2 = 09031; ML_PRN_ZOOM3 = 09032; ML_PRN_SPACING1 = 09040; ML_PRN_SPACING2 = 09041; ML_PRN_SPACING3 = 09042; ML_PRN_SPACING4 = 09043; ML_PRN_HINT_FIRST = 09050; ML_PRN_HINT_PREV = 09051; ML_PRN_HINT_NEXT = 09052; ML_PRN_HINT_LAST = 09053; ML_PRN_HINT_ZOOM = 09054; ML_PRN_HINT_PRINT = 09055; ML_PRN_HINT_PAGE_NUM = 09100; ML_PRN_HINT_TOTAL_PAGES = 09101; ML_PRN_HINT_TIME = 09102; ML_PRN_HINT_DATE = 09103; ML_PRN_HINT_FILENAME = 09104; ML_PRN_HINT_FONT = 09105; ML_PRN_HINT_BOLD = 09106; ML_PRN_HINT_ITALIC = 09107; ML_PRN_HINT_UNDERLINE = 09108; ML_USREXEC_ERR_CREATING_PIPE = 10000; ML_USREXEC_ERR_EXEC_SUBPRG = 10001; ML_USREXEC_ERR_PARAM_CAPT = 10010; ML_USREXEC_ERR_PARAM_TEXT = 10011; ML_USREXEC_ERR_NO_ASSOCIATON = 10012; ML_USREXEC_EXECUTING = 10013; ML_USREXEC_FINISHED = 10014; ML_USREXEC_TERMINATED = 10015; ML_USREXEC_TERMINATE_CAPTION = 10016; ML_USREXEC_FINISHED_DLG = 10020; ML_EXEC_POP_COPY = 10030; ML_EXEC_POP_CLEAR = 10031; ML_EXEC_POP_HIDE = 10032; ML_EXEC_POP_COPY_LINE = 10033; ML_EXEC_POP_COMPILER_JUMP_TO_LINE = 10040; ML_EXEC_POP_SET_FONT = 10041; ML_USREXEC_PANEL_CAPTION = 10050; ML_FILLBLOCK_CAPT = 11000; ML_FILLBLOCK_TEXT = 11001; ML_CODETEMPLATE_LV_NAME = 12000; ML_CODETEMPLATE_LV_DESCR = 12001; ML_EXPL_HINT_ADD = 13000; ML_EXPL_HINT_REMOVE = 13001; ML_EXPL_HINT_OPEN = 13002; ML_EXPL_HINT_TOGGLEPATH = 13003; ML_EXPL_HINT_MOVEUP = 13004; ML_EXPL_HINT_MOVEDOWN = 13005; ML_EXPL_HINT_REMOVE_ALL = 13006; ML_EXPL_LARGE_ICONS = 13010; ML_EXPL_SMALL_ICONS = 13011; ML_EXPL_LIST = 13012; ML_EXPL_DETAILS = 13013; ML_EXPL_CAPT_FAVORITES = 13014; ML_EXPL_VIEWSTYLE = 13015; ML_EXPL_UPONELEVEL = 13016; ML_EXPL_FILTER = 13017; ML_EXPL_FILETREE = 13018; ML_FAV_ADD = 13020; ML_FAV_REMOVE = 13021; ML_FAV_OPEN = 13022; ML_FAV_SHOW_PATH = 13023; ML_FAV_MOVE_UP = 13024; ML_FAV_MOVE_DOWN = 13025; ML_FAV_REMOVE_ALL = 13026; ML_EXPL_CAPTION = 13050; ML_EXPL_PAGE_EXPLORER = 13051; ML_EXPL_PAGE_FAVORITES = 13052; ML_EXPL_PAGE_HISTORY = 13053; ML_EXPL_PAGE_PROJECT = 13054; ML_PRJFILES_HINT_ADD = 14000; ML_PRJFILES_HINT_ADD_CURRENT = 14001; ML_PRJFILES_HINT_ADD_ALL = 14002; ML_PRJFILES_HINT_REMOVE = 14003; ML_PRJFILES_HINT_OPEN_FILE = 14004; ML_PRJFILES_HINT_CLOSE_FILE = 14005; ML_PRJFILES_HINT_MOVE_UP = 14006; ML_PRJFILES_HINT_MOVE_DN = 14007; ML_PRJFILES_HINT_RELATIVE_TO = 14008; ML_PRJFILES_HINT_SET_MAKEFILE = 14009; ML_PRJFILES_CAPT_ADD_CURRENT = 14020; ML_PRJFILES_CAPT_ADD_ALL = 14021; ML_PRJFILES_CAPT_CLOSE = 14022; ML_PRJFILES_CAPT_SET_MAKEFILE = 14023; ML_PRJFILES_CAPT_NEW_PRJ = 14024; ML_STATS_FILENAME = 15000; ML_STATS_CREATED = 15001; ML_STATS_MODIFIED = 15002; ML_STATS_LINES = 15003; ML_STATS_NONEMPTY_LINES = 15004; ML_STATS_CHARS = 15005; ML_STATS_CHARS_WITHOUT_BLANKS = 15006; ML_STATS_COMMENTED_CHARS = 15007; ML_STATS_COMMENTED_CHARS_PERCENT = 15008; implementation uses uCommon, fMain, fOptions, fMacroStart, fEditor, fAbout, fCustomizeFileTypes, fMacroSelect; var msg: TStringList; fm: TStringList; hints: TStringList; const LANG_FILE_EXT = 'lng'; MESSAGES_SECTION = 'messages'; HINTS_SECTION = 'hints'; type TMyControl = class(TControl); {----------------------------------------------------------------} function mlEnumerateAllLanguages(path: string): TStringList; var F: TSearchRec; ok: boolean; fname: string; ss: TStringList; name: string; pStr: pTString; function GetLanguageName(fname: string): string; var s: string; iniF: TIniFile; begin s := ''; if FileExists(fname) then begin iniF := TIniFile.Create(fname); s := iniF.ReadString('LanguageDescriptor', 'Name', ExtractFileName(fname)); iniF.Free; end; result := s; end; begin ss := TStringList.Create; path := PathAddSeparator(path); ok := FindFirst(path + '*.' + LANG_FILE_EXT, faAnyFile, F) = 0; if ok then begin repeat fname := F.FindData.cFileName; // uzmi long filename name := GetLanguageName(path + fname); if (Length(name) > 0) then begin New(pStr); pStr^ := fname; ss.AddObject(name, pointer(pStr)); end; ok := FindNext(F) = 0; until not ok; end; SysUtils.FindClose(F); result := ss; end; {----------------------------------------------------------------} procedure mlEnumerateDispose(var ss: TStringList); var i: integer; begin if not Assigned(ss) then EXIT; for i := 0 to ss.Count - 1 do if Assigned(ss.Objects[i]) then Dispose(pTString(ss.Objects[i])); ss := nil; end; {----------------------------------------------------------------} function mlStr(index: integer; default: string): string; var i: integer; found: boolean; begin if not Assigned(msg) then begin result := default; EXIT; end; i := 0; found := FALSE; while (i < msg.Count) do begin if (index = integer(msg.Objects[i])) then begin result := msg[i]; found := TRUE; BREAK; end; inc(i); end; if not found then result := default; end; {----------------------------------------------------------------} {///////////////////////////////////////////////////////////////// Load functions /////////////////////////////////////////////////////////////////} {----------------------------------------------------------------} procedure mlMsgListAdd(name, value: string); var Index, i: integer; begin if not Assigned(msg) then EXIT; Val(name, Index, i); if (i = 0) then begin // zamijeni kontrolne znakove while (Pos('\n', value) > 0) do begin i := Pos('\n', value); value[i] := #13; value[i + 1] := #10; end; msg.AddObject(value, pointer(Index)); end; end; {----------------------------------------------------------------} procedure ExtractNameValue(s: string; var name, value: string); var ii: integer; begin name := ''; value := ''; s := Trim(s); ii := Pos('=', s); if (ii > 0) then begin name := Copy(s, 1, ii - 1); Delete(s, 1, ii); if (s[1] = '"') then Delete(s, 1, 1); if (s[Length(s)] = '"') then SetLength(s, Length(s) - 1); value := s; end; end; {----------------------------------------------------------------} function mlLoadLanguageFile(fname: string): boolean; type TSection = (ssNone, ssForm, ssHints, ssMsg); var ok: boolean; ss: TStringList; i: integer; section: TSection; str: TStringList; name: string; value: string; s: string; procedure ExtractFormName(var s: string); begin Delete(s, 1, 1); SetLength(s, Length(s) - 1); end; begin ok := FALSE; section := ssNone; str := nil; if (Length(fname) > 0) then begin fname := ApplicationDir + LANGUAGE_DIR + fname; ok := FileExists(fname); if ok then begin ss := TStringList.Create; try ss.LoadFromFile(fname); for i := 0 to ss.Count - 1 do begin s := Trim(ss[i]); // ako je komentar, preskoči liniju if ((Length(s) > 0) and (Copy(s, 1, 2) <> '//')) then begin // pogledaj je li naziv forme if (s[1] = '[') then begin ExtractFormName(s); if (LowerCase(s) = MESSAGES_SECTION) then section := ssMsg else if (LowerCase(s) = HINTS_SECTION) then section := ssHints else begin section := ssForm; str := TStringList.Create; fm.AddObject(s, str); end; end else begin case section of ssForm: if Assigned(str) then str.Add(s); ssMsg: begin ExtractNameValue(s, name, value); mlMsgListAdd(name, value); end; ssHints: begin ExtractNameValue(s, name, value); end; end; end; end; end; except end; ss.Free; end; end; result := ok; end; {----------------------------------------------------------------} procedure mlApplyLanguageToForm(form: TWinControl; name: string); var i: integer; procedure Apply(str: TStringList); var C: TComponent; name: string; value: string; i: integer; caption_set: boolean; begin caption_set := FALSE; for i := 0 to str.Count - 1 do begin ExtractNameValue(str[i], name, value); if not caption_set and (name = 'FormCaption') then begin if (form is TForm) then TForm(form).Caption := value; caption_set := TRUE; end else begin C := form.FindComponent(name); if Assigned(C) then begin if (C is TControl) then TMyControl(C).Caption := Value else if (C is TMenuItem) then TMenuItem(C).Caption := Value else if (C is TAction) then TAction(C).Caption := Value; end; end; end; end; begin i := 0; while (i < fm.Count) do begin if (fm[i] = name) then begin Apply(TStringList(fm.Objects[i])); BREAK; end; inc(i); end; end; {----------------------------------------------------------------} initialization msg := TStringList.Create; fm := TStringList.Create; hints := TStringList.Create; finalization if Assigned(msg) then msg.Free; if Assigned(hints) then hints.Free; if Assigned(fm) then begin while (fm.Count > 0 ) do if Assigned(fm.Objects[fm.Count - 1]) then TStringList(fm.Objects[fm.Count - 1]).Free; fm.Free; end; end. //////////////////////////////////////////////////////////////////
namespace Stack; interface type // An implementation of a generic stack. Based on the example in // ch. 11 of Bertrand Meyer's "Object Oriented Software Construction" 2nd Ed Stack<T> = public class private fCount: Integer; fCapacity: Integer; representation: array of T; method GetIsEmpty: Boolean; method GetIsFull: Boolean; method GetItem: T; public constructor(capacity: Integer); method PutItem(newItem: T); method RemoveItem; property Count: Integer read fCount; property Item: T read GetItem; property IsEmpty: Boolean read GetIsEmpty; property IsFull: Boolean read GetIsFull; public invariants fCount >= 0; fCount <= fCapacity; fCapacity <= length(representation); IsEmpty = (fCount = 0); (fCount > 0) implies (representation[fCount].equals(Item)); end; implementation constructor Stack<T>(capacity: Integer); require capacity >= 0; begin fCount := 0; fCapacity := capacity; representation := new T[fCapacity]; ensure fCapacity = capacity; assigned(representation); IsEmpty; end; method Stack<T>.GetIsFull: Boolean; begin result := fCount = (fCapacity - 1); ensure // The imperative and the applicative result = (fCount = (fCapacity - 1)); end; method Stack<T>.GetIsEmpty: boolean; begin result := fCount = 0; ensure result = (fCount = 0); end; method Stack<T>.GetItem: T; require not IsEmpty; begin result := representation[Count]; end; method Stack<T>.PutItem(newItem: T); require not IsFull; begin inc(fCount); representation[fCount] := newItem; ensure not IsEmpty; Item.equals(newItem); fCount = old fCount + 1; end; method Stack<T>.RemoveItem; require not IsEmpty; begin dec(fCount); ensure not IsFull; fCount = old fCount - 1; end; end.
unit uMaterials; interface uses uMesh, uClasses, GLVectorGeometry, GLColor, SysUtils, GLMaterial, GLTexture{, uPngCopy}; procedure ResetMaterialData (var MaterialData: TMaterialData); procedure ApplyMaterialData (MatLib: TGLMaterialLibrary; Obj: TMesh); procedure SetMaterialTexture (fName: AnsiString; mat : TGlMaterial); implementation procedure ResetMaterialData(var MaterialData: TMaterialData); begin MaterialData.Texture.Scale := VectorMake(1,1,1); MaterialData.Texture.Offset := VectorMake(1,1,1); end; procedure ApplyMaterialData(MatLib: TGLMaterialLibrary; Obj: TMesh); var aa: AnsiString; begin with MatLib.Materials.GetLibMaterialByName(Obj.MaterialData.Name) do begin Material.Texture.Enabled := Obj.MaterialData.Texture.Enable; if Trim(Obj.MaterialData.Texture.FileName) <> '' then Material.Texture.Image.LoadFromFile(Obj.MaterialData.Texture.FileName) else Material.Texture.Enabled:= False; // TextureScale.AsVector := Obj.MaterialData.Texture.Scale; Material.BlendingMode := bmOpaque; case Obj.MaterialData.Effect of effNone : Material.Texture.MappingMode := tmmUser; effReflect : Material.Texture.MappingMode := tmmCubeMapReflection; effReflect2 : Material.Texture.MappingMode := tmmCubeMapLight0; { effAlphaChanelPNG : SetMaterialPngTexture(Obj.MaterialData.Texture.FileName,Material)} end; if Obj.MaterialData.Effect <> effNone then TextureScale.AsVector := Obj.MaterialData.Texture.Scale; Material.FrontProperties.Diffuse := Obj.MaterialData.Color; Material.Texture.TextureMode := tmReplace; if Obj.MaterialData.Color.Alpha < 1 then begin Obj.MoveLast; Material.BlendingMode := bmTransparency; end; end; end; procedure SetMaterialTexture(fName: AnsiString; mat : TGlMaterial); begin with mat,mat.FrontProperties do begin Texture.Disabled := false; BlendingMode := bmOpaque; Texture.TextureMode := tmReplace; Texture.Image.LoadFromFile(fName); Ambient .SetColor(1,1,1,1); Diffuse .SetColor(1,1,1,1); Emission.SetColor(1,1,1,1); Specular.SetColor(1,1,1,1); end; end; end.
unit uHTMLCreator; interface uses Classes, Generics.Collections; type {Criar classes para cada Type} THTMLInputTypeEnum = (itButton, itCheckBox, itColor, itDate, itDateTime, itEmail, itFile, itHidden, itImage, itMonth, itNumber, itPassword, itRadio, itRange, itReset, itSearch, itSubmit, itTel, itText, itTime, itUrl, itWeek); THTMLInputTypeHelper = record helper for THTMLInputTypeEnum strict private const arInputTypesNames: array[THTMLInputTypeEnum] of string = ('button','checkbox','color','date','datetime-local','email','file', 'hidden','image','month','number','password','radio','range','reset','search','submit','tel','text','time','url','week'); public function GetName: string; end; THTMLInputItem = class ID: string; &Label: string; Name: string; &Type: THTMLInputTypeEnum; Value: string; function Generate: string; end; THTMLInputGroup = class private FInputs: TObjectList<THTMLInputItem>; public var Caption: string; property Inputs: TObjectList<THTMLInputItem> read FInputs; function Generate: string; constructor Create; destructor Destroy; override; end; THTMLFormCreator = class private FKeys: TList<string>; FGroups: TObjectDictionary<string,THTMLInputGroup>; public var Title: string; var Subtitle: string; var Action: string; procedure AddGroup(_AGroup: THTMLInputGroup); procedure AddOrSetGroup(_AGroup: THTMLInputGroup); function FindGroup(_ACaption: string): THTMLInputGroup; function TryFindGroup(_ACaption: string; out _AGroup: THTMLInputGroup): Boolean; // property Groups: TObjectList<THTMLInputGroup> read FGroups; function Generate: string; constructor Create; destructor Destroy; override; end; implementation uses System.SysUtils; { THTMLCreator } procedure THTMLFormCreator.AddGroup(_AGroup: THTMLInputGroup); begin if FGroups.ContainsKey(_AGroup.Caption) then raise Exception.Create('Error Message'); FKeys.Add(_AGroup.Caption); FGroups.Add(_AGroup.Caption, _AGroup); end; procedure THTMLFormCreator.AddOrSetGroup(_AGroup: THTMLInputGroup); begin if not FGroups.ContainsKey(_AGroup.Caption) then FKeys.Add(_AGroup.Caption); FGroups.AddOrSetValue(_AGroup.Caption, _AGroup); end; constructor THTMLFormCreator.Create; begin FKeys := TList<string>.Create; FGroups := TObjectDictionary<string, THTMLInputGroup>.Create; end; destructor THTMLFormCreator.Destroy; begin FKeys.Free; FGroups.Free; inherited; end; function THTMLFormCreator.FindGroup(_ACaption: string): THTMLInputGroup; begin Result := nil; if FGroups.ContainsKey(_ACaption) then Result := FGroups.Items[_ACaption]; end; function THTMLFormCreator.Generate: string; var AHTML, AKey: string; begin AHTML := ''; for AKey in FKeys do begin if FGroups.ContainsKey(AKey) then begin AHTML := AHTML + FGroups.Items[AKey].Generate; end; end; Result := '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">' + '<html>' + ' <head>' + Format(' <title>%s</title>', [Title]) + ' </head>' + ' <style>' + ' table {border: 1px solid black; width:40%;}' + ' th {background-color: DodgerBlue; color: white; height: 30px;text-align: center}' + ' tr {text-align: center;}' + ' tr:nth-child(even) {background-color: #F2F2F2;}' + ' tr:hover {background-color: LightGray;}' + ' .submitbutton {border-radius: 8px; background-color: DodgerBlue; padding: 10px; width: 12em; color: white;font-weight: bold}' + ' </style>' + ' <body>' + ' <div align="center">' + Format(' <h1>%s</h1>', [Title]) + ' <h2>Configurações</h2>' + ' <form name="content" method="post" action="' + Action + '" >' + AHTML + Format('<center><input type="%s" class="submitbutton" value="Submit"/></center>',[itSubmit.GetName]) + ' </form>' + ' </div>' + ' </body>' + '</html>'; end; function THTMLFormCreator.TryFindGroup(_ACaption: string; out _AGroup: THTMLInputGroup): Boolean; begin _AGroup := FindGroup(_ACaption); Result := (_AGroup <> nil); end; { THTMLInputGroup } constructor THTMLInputGroup.Create; begin FInputs := TObjectList<THTMLInputItem>.Create; end; destructor THTMLInputGroup.Destroy; begin FInputs.Free; inherited; end; function THTMLInputGroup.Generate: string; var AInput: THTMLInputItem; begin Result := '<table>'; Result := Result + Format('<tr><th colspan="2">%s</th></tr>', [Caption]); for AInput in FInputs do begin Result := Result + AInput.Generate; end; Result := Result + '<tr></tr>'; Result := Result + '</table>'; Result := Result + '<br/>'; end; { THTMLInputTypeHelper } function THTMLInputTypeHelper.GetName: string; begin Result := arInputTypesNames[Self]; end; { THTMLInputItem } function THTMLInputItem.Generate: string; var AValue: string; begin AValue := Value; case &Type of itCheckBox: begin if StrToIntDef(AValue, 0) = 0 then AValue := '' else AValue := 'checked="checked"'; end; itPassword: begin AValue := ''; end else AValue := Format('value="%s"', [AValue]); end; Result := Format('<tr><td><label for="%s">%s:</label></td><td><input id="%s" name="%s" type="%s" %s/></td></tr>', [ID, &Label, ID, Name, &Type.GetName, AValue]); end; end.
{******************************************************************************} { } { Delphi OPENSSL Library } { Copyright (c) 2016 Luca Minuti } { https://bitbucket.org/lminuti/delphi-openssl } { } {******************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {******************************************************************************} unit SSLDemo.MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.StdCtrls, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls; type TMainForm = class(TForm) pgcMain: TPageControl; procedure FormCreate(Sender: TObject); private procedure AddFrame(const Caption: string; FrameClass: TControlClass); public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} uses SSLDemo.MainFrame, SSLDemo.RSABufferFrame, SSLDemo.EncFrame, SSLDemo.UnpackPKCS7Frame, SSLDemo.RandFrame, SSLDemo.KeyPairFrame; { TMainForm } procedure TMainForm.AddFrame(const Caption: string; FrameClass: TControlClass); var TabSheet: TTabSheet; AFrame: TControl; begin TabSheet := TTabSheet.Create(pgcMain); TabSheet.Caption := Caption; TabSheet.PageControl := pgcMain; AFrame := FrameClass.Create(Application); AFrame.Parent := TabSheet; end; procedure TMainForm.FormCreate(Sender: TObject); begin AddFrame('Tutorial', TMainFrame); AddFrame('RSABuffer', TRSABufferFrame); AddFrame('Encryption', TEncFrame); AddFrame('Random', TRandomFrame); AddFrame('Unpack PKCS7', TUnpackPKCS7Frame); AddFrame('KeyPair', TKeyPairFrame); end; end.
unit LrTreeData; interface uses SysUtils, Classes, Contnrs, LrDocument; type TLrLeafItem = class(TComponent) private FDisplayName: string; protected function GetDisplayName: string; virtual; procedure SetDisplayName(const Value: string); virtual; public constructor Create; reintroduce; virtual; published property DisplayName: string read GetDisplayName write SetDisplayName; end; // TLrDataItems = class(TComponent) protected function GetCount: Integer; function GetItems(inIndex: Integer): TLrDataItem; procedure Clear; procedure DefineProperties(Filer: TFiler); override; procedure ReadItems(Stream: TStream); procedure WriteItems(Stream: TStream); public constructor Create(inOwner: TComponent); reintroduce; destructor Destroy; override; function Find(const inName: string): TLrDataItem; function GetUniqueName(const inName: string): string; procedure Add(inItem: TLrDataItem); procedure LoadFromStream(inStream: TStream); procedure SaveToStream(inStream: TStream); //procedure LoadFromFile(const inFilename: string); //procedure SaveToFile(const inFilename: string); property Count: Integer read GetCount; property Items[inIndex: Integer]: TLrDataItem read GetItems; default; end; // TLrDataItem = class(TLeafItem) private FItems: TLrDataItems; protected procedure SetItems(const Value: TLrDataItems); public constructor Create; override; destructor Destroy; override; published property Items: TLrDataItems read FItems write SetItems; end; // TLrDataItem = class(TComponent) private FDisplayName: string; protected function GetDisplayName: string; virtual; procedure SetDisplayName(const Value: string); virtual; public constructor Create; reintroduce; virtual; published property DisplayName: string read GetDisplayName write SetDisplayName; end; // TLrTree = class(TLrDataItem) end; implementation uses LrVclUtils; { TLrDataItem } constructor TLrDataItem.Create; begin inherited Create(nil); end; function TLrDataItem.GetDestination: string; begin Result := FDestination; end; function TLrDataItem.GetDisplayName: string; begin if FDisplayName <> '' then Result := FDisplayName else begin Result := ExtractFileName(Source); if Result = '' then Result := '(untitled)'; end; end; function TLrDataItem.GetSource: string; begin Result := FSource; end; procedure TLrDataItem.SetDestination(const Value: string); begin FDestination := Value; end; procedure TLrDataItem.SetDisplayName(const Value: string); begin FDisplayName := Value; end; procedure TLrDataItem.SetSource(const Value: string); begin FSource := Value; end; { TLrDataItems } constructor TLrDataItems.Create(inOwner: TComponent); begin inherited Create(inOwner); end; destructor TLrDataItems.Destroy; begin inherited; end; procedure TLrDataItems.Clear; begin DestroyComponents; end; procedure TLrDataItems.ReadItems(Stream: TStream); var c, i: Integer; begin Stream.Read(c, 4); for i := 0 to Pred(c) do Add(TLrDataItem(Stream.ReadComponent(nil))); end; procedure TLrDataItems.WriteItems(Stream: TStream); var c, i: Integer; begin c := Count; Stream.Write(c, 4); for i := 0 to Pred(Count) do Stream.WriteComponent(Items[i]); end; procedure TLrDataItems.DefineProperties(Filer: TFiler); begin Filer.DefineBinaryProperty('Items', ReadItems, WriteItems, true); end; procedure TLrDataItems.SaveToStream(inStream: TStream); begin LrSaveComponentToStream(Self, inStream); end; procedure TLrDataItems.LoadFromStream(inStream: TStream); begin Clear; LrLoadComponentFromStream(Self, inStream); end; function TLrDataItems.GetCount: Integer; begin Result := ComponentCount; end; function TLrDataItems.GetItems(inIndex: Integer): TLrDataItem; begin Result := TLrDataItem(Components[inIndex]); end; procedure TLrDataItems.Add(inItem: TLrDataItem); begin InsertComponent(inItem); end; function TLrDataItems.Find(const inName: string): TLrDataItem; //var // i: Integer; begin Result := TLrDataItem(FindComponent(inName)); { Result := nil; for i := 0 to Pred(Count) do if (Items[i].Name = inName) then begin Result := Items[i]; break; end; } end; function TLrDataItems.GetUniqueName(const inName: string): string; var i: Integer; begin if Find(inName) = nil then Result := inName else begin i := 0; repeat Inc(i); Result := inName + IntToStr(i); until Find(Result) = nil; end; end; { TLrTree } constructor TLrTree.Create; begin inherited; //EnableSaveAs('TurboPhp Projects', '.trboprj'); FItems := TLrDataItems.Create(nil); end; destructor TLrTree.Destroy; begin Items.Free; inherited; end; function TLrTree.GetUntitledName: string; begin Result := 'Untitled Project'; end; function TLrTree.Find(const inSource: string): TLrDataItem; begin Result := Items.Find(inSource); end; function TLrTree.GetUniqueName(const inName: string): string; var i: Integer; begin if Find(inName) = nil then Result := inName else begin i := 0; repeat Inc(i); Result := inName + IntToStr(i); until Find(Result) = nil; end; end; procedure TLrTree.AddItem(inItem: TLrDataItem); begin Items.Add(inItem); Change; end; end.
unit ibSHDDLCommentator; interface uses SysUtils, Classes, StrUtils, SHDesignIntf, ibSHDesignIntf, ibSHTool; type TibSHDDLCommentator = class(TibBTTool, IibSHDDLCommentator, IibSHBranch, IfbSHBranch) private FMode: string; FGoNext: Boolean; function GetMode: string; procedure SetMode(Value: string); function GetGoNext: Boolean; procedure SetGoNext(Value: Boolean); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Mode: string read GetMode write SetMode; property GoNext: Boolean read GetGoNext write SetGoNext; end; TibSHDDLCommentatorFactory = class(TibBTToolFactory) end; procedure Register; implementation uses ibSHConsts, ibSHDDLCommentatorActions, ibSHDDLCommentatorEditors; procedure Register; begin SHRegisterImage(GUIDToString(IibSHDDLCommentator), 'DDLCommentator.bmp'); SHRegisterImage(TibSHDDLCommentatorPaletteAction.ClassName, 'DDLCommentator.bmp'); SHRegisterImage(TibSHDDLCommentatorFormAction.ClassName, 'Form_Description.bmp'); SHRegisterImage(TibSHDDLCommentatorToolbarAction_Run.ClassName, 'Button_Run.bmp'); SHRegisterImage(TibSHDDLCommentatorToolbarAction_Pause.ClassName, 'Button_Stop.bmp'); SHRegisterImage(TibSHDDLCommentatorToolbarAction_Refresh.ClassName, 'Button_Refresh.bmp'); SHRegisterComponents([ TibSHDDLCommentator, TibSHDDLCommentatorFactory]); SHRegisterActions([ // Palette TibSHDDLCommentatorPaletteAction, // Forms TibSHDDLCommentatorFormAction, // Toolbar TibSHDDLCommentatorToolbarAction_Run, // TibSHDDLCommentatorToolbarAction_Pause, TibSHDDLCommentatorToolbarAction_Refresh]); SHRegisterPropertyEditor(IibSHDDLCommentator, 'Mode', TibSHDDLCommentatorModePropEditor); end; { TibSHDDLCommentator } constructor TibSHDDLCommentator.Create(AOwner: TComponent); begin inherited Create(AOwner); FMode := CommentModes[0]; FGoNext := True; end; destructor TibSHDDLCommentator.Destroy; begin inherited Destroy; end; function TibSHDDLCommentator.GetMode: string; begin Result := FMode; end; procedure TibSHDDLCommentator.SetMode(Value: string); begin if FMode <> Value then begin FMode := Value; if Assigned(Designer.CurrentComponentForm) and AnsiContainsText(Designer.CurrentComponentForm.CallString, SCallDescriptions) then (Designer.CurrentComponentForm as ISHRunCommands).Refresh; end; end; function TibSHDDLCommentator.GetGoNext: Boolean; begin Result := FGoNext; end; procedure TibSHDDLCommentator.SetGoNext(Value: Boolean); begin FGoNext := Value; end; initialization Register; end.
unit dxtools; {DXTools - delphi helper functions for managing DirectX things} {(c) February 1997 by Luc Cluitmans} {This source is provided free as part of an example of using Direct3D in Delphi. No guarantees; I am not responsible for nasty things that may happen to you or your computer by using this code} {Sorry for the lack of documentary comments :-)} interface uses OLE2, Windows, Messages, SysUtils, D3DRMObj, D3DTypes, D3DRMDef, DDraw, D3D, D3Drm, Dialogs, misc_utils; type EDirectX = class(Exception); procedure COMRelease(var p: IUnknown); // safe release of COM object {---------------------------------------------------------------------} {Error handling} function COMFailed(var r2: HRESULT; r: HRESULT): Boolean; {assigns r to r2; returns True when r indicates failure} procedure DXCheck(r: HResult; const msg:string); {Throws a EDirectX exception if r indicates a failure} {Returns normally when r is DD_OK or an equivalent} {example 1: (special processing required on error) if COMFailed(r, lpDDClipper.SetHWnd(0, Handle)) then begin COMRelease(lpDDClipper); DXCheck(r); end; example 2: (no special processing required on error) DXCheck(Direct3DRMCreate(lpD3DRM)); } Procedure DXFailCheck(r: HResult;const msg:string); implementation procedure COMRelease(var p: IUnknown); var i:integer; begin if Assigned(p) then begin p.Release; p := nil; end else begin ShowMessage('COMRelease of NULL object'); end; end; function COMFailed(var r2: HRESULT; r: HRESULT): Boolean; begin r2 := r; Result := (r <> DD_OK); end; Function GetErrorStr(r:Hresult):string; var s: string; begin Result:=''; if r <> DD_OK then begin Case r of DDERR_ALREADYINITIALIZED: S:='This object is already initialized.'; DDERR_BLTFASTCANTCLIP: S:=' if a clipper object is attached to the source surface passed into a BltFast call.'; DDERR_CANNOTATTACHSURFACE: S:='This surface can not be attached to the requested surface.'; DDERR_CANNOTDETACHSURFACE: S:='This surface can not be detached from the requested surface.'; DDERR_CANTCREATEDC: S:='Windows can not create any more DCs.'; DDERR_CANTDUPLICATE: S:='Cannot duplicate primary & 3D surfaces, or surfaces that are implicitly created.'; DDERR_CLIPPERISUSINGHWND: S:='An attempt was made to set a cliplist for a clipper object that is already monitoring an hwnd.'; DDERR_COLORKEYNOTSET: S:='No src color key specified for this operation.'; DDERR_CURRENTLYNOTAVAIL: S:='Support is currently not available.'; DDERR_DIRECTDRAWALREADYCREATED: S:='A DirectDraw object representing this driver has already been created for this process.'; DDERR_EXCEPTION: S:='An exception was encountered while performing the requested operation.'; DDERR_EXCLUSIVEMODEALREADYSET: S:='An attempt was made to set the cooperative level when it was already set to exclusive.'; DDERR_GENERIC: S:='Generic failure.'; DDERR_HEIGHTALIGN: S:='Height of rectangle provided is not a multiple of reqd alignment.'; DDERR_HWNDALREADYSET: S:='The CooperativeLevel HWND has already been set. It can not be reset while the process has surfaces or palettes created.'; DDERR_HWNDSUBCLASSED: S:='HWND used by DirectDraw CooperativeLevel has been subclassed, this prevents DirectDraw from restoring state.'; DDERR_IMPLICITLYCREATED: S:='This surface can not be restored because it is an implicitly created surface.'; DDERR_INCOMPATIBLEPRIMARY: S:='Unable to match primary surface creation request with existing primary surface.'; DDERR_INVALIDCAPS: S:='One or more of the caps bits passed to the callback are incorrect.'; DDERR_INVALIDCLIPLIST: S:='DirectDraw does not support the provided cliplist.'; DDERR_INVALIDDIRECTDRAWGUID: S:='The GUID passed to DirectDrawCreate is not a valid DirectDraw driver identifier.'; DDERR_INVALIDMODE: S:='DirectDraw does not support the requested mode.'; DDERR_INVALIDOBJECT: S:='DirectDraw received a pointer that was an invalid DIRECTDRAW object.'; DDERR_INVALIDPARAMS: S:='One or more of the parameters passed to the function are incorrect.'; DDERR_INVALIDPIXELFORMAT: S:='The pixel format was invalid as specified.'; DDERR_INVALIDPOSITION: S:='Returned when the position of the overlay on the destination is no longer legal for that destination.'; DDERR_INVALIDRECT: S:='Rectangle provided was invalid.'; DDERR_LOCKEDSURFACES: S:='Operation could not be carried out because one or more surfaces are locked.'; DDERR_NO3D: S:='There is no 3D present.'; DDERR_NOALPHAHW: S:='Operation could not be carried out because there is no alpha accleration hardware present or available.'; DDERR_NOBLTHW: S:='No blitter hardware present.'; DDERR_NOCLIPLIST: S:='No cliplist available.'; DDERR_NOCLIPPERATTACHED: S:='No clipper object attached to surface object.'; DDERR_NOCOLORCONVHW: S:='Operation could not be carried out because there is no color conversion hardware present or available.'; DDERR_NOCOLORKEY: S:='Surface does not currently have a color key'; DDERR_NOCOLORKEYHW: S:='Operation could not be carried out because there is no hardware support of the destination color key.'; DDERR_NOCOOPERATIVELEVELSET: S:='Create function called without DirectDraw object method SetCooperativeLevel being called.'; DDERR_NODC: S:='No DC was ever created for this surface.'; DDERR_NODDROPSHW: S:='No DirectDraw ROP hardware.'; DDERR_NODIRECTDRAWHW: S:='A hardware-only DirectDraw object creation was attempted but the driver did not support any hardware.'; DDERR_NOEMULATION: S:='Software emulation not available.'; DDERR_NOEXCLUSIVEMODE: S:='Operation requires the application to have exclusive mode but the application does not have exclusive mode.'; DDERR_NOFLIPHW: S:='Flipping visible surfaces is not supported.'; DDERR_NOGDI: S:='There is no GDI present.'; DDERR_NOHWND: S:='Clipper notification requires an HWND or no HWND has previously been set as the CooperativeLevel HWND.'; DDERR_NOMIRRORHW: S:='Operation could not be carried out because there is no hardware present or available.'; DDERR_NOOVERLAYDEST: S:='Returned when GetOverlayPosition is called on an overlay that UpdateOverlay has never been called on to establish a destination.'; DDERR_NOOVERLAYHW: S:='Operation could not be carried out because there is no overlay hardware present or available.'; DDERR_NOPALETTEATTACHED: S:='No palette object attached to this surface.'; DDERR_NOPALETTEHW: S:='No hardware support for 16 or 256 color palettes.'; DDERR_NORASTEROPHW: S:='Operation could not be carried out because there is no appropriate raster op hardware present or available.'; DDERR_NOROTATIONHW: S:='Operation could not be carried out because there is no rotation hardware present or available.'; DDERR_NOSTRETCHHW: S:='Operation could not be carried out because there is no hardware support for stretching.'; DDERR_NOT4BITCOLOR: S:='DirectDrawSurface is not in 4 bit color palette and the requested operation requires 4 bit color palette.'; DDERR_NOT4BITCOLORINDEX: S:='DirectDrawSurface is not in 4 bit color index palette and the requested operation requires 4 bit color index palette.'; DDERR_NOT8BITCOLOR: S:='DirectDrawSurface is not in 8 bit color mode and the requested operation requires 8 bit color.'; DDERR_NOTAOVERLAYSURFACE: S:='Returned when an overlay member is called for a non-overlay surface.'; DDERR_NOTEXTUREHW: S:='Operation could not be carried out because there is no texture mapping hardware present or available.'; DDERR_NOTFLIPPABLE: S:='An attempt has been made to flip a surface that is not flippable.'; DDERR_NOTFOUND: S:='Requested item was not found.'; DDERR_NOTLOCKED: S:='Surface was not locked. An attempt to unlock a surface that was not locked at all, or by this process, has been attempted.'; DDERR_NOTPALETTIZED: S:='The surface being used is not a palette-based surface.'; DDERR_NOVSYNCHW: S:='Operation could not be carried out because there is no hardware support for vertical blank synchronized operations.'; DDERR_NOZBUFFERHW: S:='Operation could not be carried out because there is no hardware support for zbuffer blitting.'; DDERR_NOZOVERLAYHW: S:='Overlay surfaces could not be z layered based on their BltOrder because the hardware does not support z layering of overlays.'; DDERR_OUTOFCAPS: S:='The hardware needed for the requested operation has already been allocated.'; DDERR_OUTOFMEMORY: S:='DirectDraw does not have enough memory to perform the operation.'; DDERR_OUTOFVIDEOMEMORY: S:='DirectDraw does not have enough memory to perform the operation.'; DDERR_OVERLAYCANTCLIP: S:='The hardware does not support clipped overlays.'; DDERR_OVERLAYCOLORKEYONLYONEACTIVE: S:='Can only have ony color key active at one time for overlays.'; DDERR_OVERLAYNOTVISIBLE: S:='Returned when GetOverlayPosition is called on a hidden overlay.'; DDERR_PALETTEBUSY: S:='Access to this palette is being refused because the palette is already locked by another thread.'; DDERR_PRIMARYSURFACEALREADYEXISTS: S:='This process already has created a primary surface.'; DDERR_REGIONTOOSMALL: S:='Region passed to Clipper::GetClipList is too small.'; DDERR_SURFACEALREADYATTACHED: S:='This surface is already attached to the surface it is being attached to.'; DDERR_SURFACEALREADYDEPENDENT: S:='This surface is already a dependency of the surface it is being made a dependency of.'; DDERR_SURFACEBUSY: S:='Access to this surface is being refused because the surface is already locked by another thread.'; DDERR_SURFACEISOBSCURED: S:='Access to surface refused because the surface is obscured.'; DDERR_SURFACELOST: S:='Access to this surface is being refused because the surface memory is gone. The DirectDrawSurface object representing this surface should have Restore called on it.'; DDERR_SURFACENOTATTACHED: S:='The requested surface is not attached.'; DDERR_TOOBIGHEIGHT: S:='Height requested by DirectDraw is too large.'; DDERR_TOOBIGSIZE: S:='Size requested by DirectDraw is too large, but the individual height and width are OK.'; DDERR_TOOBIGWIDTH: S:='Width requested by DirectDraw is too large.'; DDERR_UNSUPPORTED: S:='Action not supported.'; DDERR_UNSUPPORTEDFORMAT: S:='FOURCC format requested is unsupported by DirectDraw.'; DDERR_UNSUPPORTEDMASK: S:='Bitmask in the pixel format requested is unsupported by DirectDraw.'; DDERR_VERTICALBLANKINPROGRESS: S:='Vertical blank is in progress.'; DDERR_WASSTILLDRAWING: S:='Informs DirectDraw that the previous Blt which is transfering information to or from this Surface is incomplete.'; DDERR_WRONGMODE: S:='This surface can not be restored because it was created in a different mode.'; DDERR_XALIGN: S:='Rectangle provided was not horizontally aligned on required boundary.'; D3DERR_BADMAJORVERSION: S:='D3DERR_BADMAJORVERSION'; D3DERR_BADMINORVERSION: S:='D3DERR_BADMINORVERSION'; D3DERR_EXECUTE_LOCKED: S:='D3DERR_EXECUTE_LOCKED'; D3DERR_EXECUTE_NOT_LOCKED: S:='D3DERR_EXECUTE_NOT_LOCKED'; D3DERR_EXECUTE_CREATE_FAILED: S:='D3DERR_EXECUTE_CREATE_FAILED'; D3DERR_EXECUTE_DESTROY_FAILED: S:='D3DERR_EXECUTE_DESTROY_FAILED'; D3DERR_EXECUTE_LOCK_FAILED: S:='D3DERR_EXECUTE_LOCK_FAILED'; D3DERR_EXECUTE_UNLOCK_FAILED: S:='D3DERR_EXECUTE_UNLOCK_FAILED'; D3DERR_EXECUTE_FAILED: S:='D3DERR_EXECUTE_FAILED'; D3DERR_EXECUTE_CLIPPED_FAILED: S:='D3DERR_EXECUTE_CLIPPED_FAILED'; D3DERR_TEXTURE_NO_SUPPORT: S:='D3DERR_TEXTURE_NO_SUPPORT'; D3DERR_TEXTURE_NOT_LOCKED: S:='D3DERR_TEXTURE_NOT_LOCKED'; D3DERR_TEXTURE_LOCKED: S:='D3DERR_TEXTURELOCKED'; D3DERR_TEXTURE_CREATE_FAILED: S:='D3DERR_TEXTURE_CREATE_FAILED'; D3DERR_TEXTURE_DESTROY_FAILED: S:='D3DERR_TEXTURE_DESTROY_FAILED'; D3DERR_TEXTURE_LOCK_FAILED: S:='D3DERR_TEXTURE_LOCK_FAILED'; D3DERR_TEXTURE_UNLOCK_FAILED: S:='D3DERR_TEXTURE_UNLOCK_FAILED'; D3DERR_TEXTURE_LOAD_FAILED: S:='D3DERR_TEXTURE_LOAD_FAILED'; D3DERR_MATRIX_CREATE_FAILED: S:='D3DERR_MATRIX_CREATE_FAILED'; D3DERR_MATRIX_DESTROY_FAILED: S:='D3DERR_MATRIX_DESTROY_FAILED'; D3DERR_MATRIX_SETDATA_FAILED: S:='D3DERR_MATRIX_SETDATA_FAILED'; D3DERR_SETVIEWPORTDATA_FAILED: S:='D3DERR_SETVIEWPORTDATA_FAILED'; D3DERR_MATERIAL_CREATE_FAILED: S:='D3DERR_MATERIAL_CREATE_FAILED'; D3DERR_MATERIAL_DESTROY_FAILED: S:='D3DERR_MATERIAL_DESTROY_FAILED'; D3DERR_MATERIAL_SETDATA_FAILED: S:='D3DERR_MATERIAL_SETDATA_FAILED'; D3DERR_LIGHT_SET_FAILED: S:='D3DERR_LIGHT_SET_FAILED'; D3DRMERR_BADOBJECT: S:='D3DRMERR_BADOBJECT'; D3DRMERR_BADTYPE: S:='D3DRMERR_BADTYPE'; D3DRMERR_BADALLOC: S:='D3DRMERR_BADALLOC'; D3DRMERR_FACEUSED: S:='D3DRMERR_FACEUSED'; D3DRMERR_NOTFOUND: S:='D3DRMERR_NOTFOUND'; D3DRMERR_NOTDONEYET: S:='D3DRMERR_NOTDONEYET'; D3DRMERR_FILENOTFOUND: S:='The file was not found.'; D3DRMERR_BADFILE: S:='D3DRMERR_BADFILE'; D3DRMERR_BADDEVICE: S:='D3DRMERR_BADDEVICE'; D3DRMERR_BADVALUE: S:='D3DRMERR_BADVALUE'; D3DRMERR_BADMAJORVERSION: S:='D3DRMERR_BADMAJORVERSION'; D3DRMERR_BADMINORVERSION: S:='D3DRMERR_BADMINORVERSION'; D3DRMERR_UNABLETOEXECUTE: S:='D3DRMERR_UNABLETOEXECUTE'; Else S:='Unrecognized error value.'; end; S := Format ('DirectX call failed: %x%s%s', [r, #13, s]); Result:=s; {raise EDirectX.Create (S);} end; end; Procedure DXFailCheck(r: HResult;const msg:string); var s:string; begin if r=DD_OK then exit; raise EDirectX.Create (GetErrorStr(r)+' '+msg); end; procedure DXCheck(r: HResult; const msg:string); begin if r=DD_OK then exit; PanMessage(mt_warning,GetErrorStr(r)+' '+msg); end; end.
unit uDownloadThread; interface uses System.Classes; type TDownloadThreadDataEvent = procedure(const Sender: TObject; ThreadNo, ASpeed: Integer; AContentLength: Int64; AReadCount: Int64; var Abort: Boolean; const VisualObject: TObject) of object; TDownloadThread = class(TThread) private FOnThreadData: TDownloadThreadDataEvent; FVisualObject: TObject; FCanResume: Boolean; FShouldResume: Boolean; FLastDownloaded: Int64; FPauseDownload: Boolean; procedure Download(AStartPoint, AEndPoint: Int64); protected FURL, FFileName: string; FStartPoint, FEndPoint: Int64; FThreadNo: Integer; FTimeStart: Cardinal; procedure ReceiveDataEvent(const Sender: TObject; AContentLength: Int64; AReadCount: Int64; var Abort: Boolean); public constructor Create(const URL, FileName: string; ThreadNo: Integer; StartPoint, EndPoint: Int64); destructor Destroy; override; procedure Execute; override; procedure ResumeDownload; procedure PauseDownload; property VisualObject: TObject read FVisualObject write FVisualObject; property CanResume: Boolean read FCanResume write FCanResume; property IsPaused: Boolean read FPauseDownload; property OnThreadData: TDownloadThreadDataEvent write FOnThreadData; end; implementation uses System.Net.URLClient, System.Net.HttpClient, System.SysUtils; { TDownloadThread } constructor TDownloadThread.Create(const URL, FileName: string; ThreadNo: Integer; StartPoint, EndPoint: Int64); begin inherited Create(True); FURL := URL; FFileName := FileName; FThreadNo := ThreadNo; FStartPoint := StartPoint; FEndPoint := EndPoint; FLastDownloaded := 0; FShouldResume := False; FPauseDownload := False; end; destructor TDownloadThread.Destroy; begin inherited; end; procedure TDownloadThread.Execute; begin Download(FStartPoint, FEndPoint); while not terminated and FCanResume do begin if FShouldResume then begin FShouldResume := False; FPauseDownload := False; Download(FLastDownloaded, FEndPoint); end; end; end; procedure TDownloadThread.PauseDownload; begin FPauseDownload := True; end; procedure TDownloadThread.Download(AStartPoint, AEndPoint: Int64); var LResponse: IHTTPResponse; LStream: TFileStream; LHttpClient: THTTPClient; begin inherited; LHttpClient := THTTPClient.Create; try LHttpClient.OnReceiveData := ReceiveDataEvent; LStream := TFileStream.Create(FFileName, fmOpenWrite or fmShareDenyNone); try FTimeStart := GetTickCount; if FEndPoint = 0 then LResponse := LHttpClient.Get(FURL, LStream) else begin LStream.Seek(AStartPoint, TSeekOrigin.soBeginning); LResponse := LHttpClient.GetRange(FURL, AStartPoint, AEndPoint, LStream); end; finally LStream.Free; end; finally LHttpClient.Free; end; end; procedure TDownloadThread.ReceiveDataEvent(const Sender: TObject; AContentLength, AReadCount: Int64; var Abort: Boolean); var LTime: Cardinal; LSpeed: Integer; begin if Terminated or FPauseDownload then begin ABort := true; FLastDownloaded := FLastDownloaded + AReadCount; end else if Assigned(FOnThreadData) then begin LTime := GetTickCount - FTimeStart; if AReadCount = 0 then LSpeed := 0 else LSpeed := (AReadCount * 1000) div LTime; FOnThreadData(Sender, FThreadNo, LSpeed, FLastDownloaded + AContentLength, FLastDownloaded + AReadCount, Abort, FVisualObject); end; end; procedure TDownloadThread.ResumeDownload; begin FShouldResume := True; end; end.
unit uFrmBaixarContaReceber; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFrmBase, StdCtrls, DXPControl, DXPButtons, Mask, RxToolEdit, RxCurrEdit, uContaReceberDAOClient, ContaReceber; type TFrmBaixarContaReceber = class(TFrmBase) Label1: TLabel; cedValor: TCurrencyEdit; Label2: TLabel; lbFormaPagamento: TListBox; btnBaixar: TDXPButton; Label3: TLabel; deData: TDateEdit; procedure btnBaixarClick(Sender: TObject); private { Private declarations } public { Public declarations } ContaReceberId: Integer; ValorRestante, ValorTotal: Currency; Baixou, BaixaTotal: Boolean; end; var FrmBaixarContaReceber: TFrmBaixarContaReceber; implementation uses MensagensUtils, uFrmPrincipal; {$R *.dfm} procedure TFrmBaixarContaReceber.btnBaixarClick(Sender: TObject); var ContaReceberDAO: TContaReceberDAOClient; ContaReceber: TContaReceber; begin inherited; if deData.Date = 0 then begin Atencao('Informe a data da baixa.'); Exit; end; if cedValor.Value = 0 then begin Atencao('Informe o valor a ser baixado.'); Exit; end; if lbFormaPagamento.ItemIndex = -1 then begin Atencao('Informe a forma de pagamento.'); Exit; end; if cedValor.Value > ValorRestante then begin Atencao('O valor deste conta a receber é '+FormatCurr(',0.00', ValorRestante)); Exit; end; if Confirma('Baixar parcela?') then begin ContaReceberDAO := TContaReceberDAOClient.Create(FrmPrincipal.ConnServidor.DBXConnection); try ContaReceber := TContaReceber.Create(ContaReceberId); ContaReceber.Valor := ValorTotal; BaixaTotal := ContaReceberDAO.BaixarConta(ContaReceber, deData.Date, cedValor.Value, lbFormaPagamento.ItemIndex); Baixou := True; finally ContaReceberDAO.Free; Self.Close; end; end; end; end.
unit stmTransform1; interface uses classes, sysutils, util1, stmdef,stmObj, stmObv0, stmMvtX1, cuda1, stmPG, sysPal32, Direct3D9G, stmstmX0, Dprocess, stmVSBM1, stmvec1,ncdef2, debug0; { TVStransform effectue une transformation des pixels d'une surface ( un VSbitmap) obSource est la source obvis est la destination si obsource vaut nil, la source est désignée par obvis si obvis vaut nil, la destination est la RenderSurface de l'écran de stimulation TVStransform se comporte comme n'importe quel stimulus mais: - c'est DoTransform qui agit sur l'affichage. - quand la destination est stimScreen (obvis=nil), Dotransform est appelé après l'affichage des autres stims - sinon, Dotransform est appelé pendant CalculMvt - setVisiFlags est modifié pour tenir compte du cas (obvis=nil) et de DispDisable } type TVStransform = class(TonOff) tf: TransformClass; // objet C++ associé x1,y1,dx1,dy1:single; // rectangle source en coordonnées réelles x2,y2,dx2,dy2:single; // rectangle dest en coordonnées réelles mvtON:boolean; RgbMask: integer; obSource: TVSbitmap; // bitmap source, obvis est la destination DispDisable: boolean; // si la destination est un bm intermédiaire, inutile de l'afficher dxSrc,dySrc:single; // dim réelles de l'objet source wSrc,hsrc:integer; // dim en pixels de l'objet source dxDest,dyDest:single; // dim réelles de l'objet dest wDest,hDest:integer; // dim en pixels de l'objet dest xcSrc, ycSrc:single; // position du centre en pixels dans le rectangle source xcDest, ycDest:single;// position du centre en pixels dans le rectangle dest TransformON: boolean; ParamValue: array of array of double; FsingleTransform: boolean; // positionné par execute uniquement // remis à false immédiatement StimScreenAsSource: boolean; constructor create;override; destructor destroy;override; class function stmClassName: AnsiString;override; procedure freeRef;override; procedure processMessage(id:integer;source:typeUO;p:pointer);override; procedure DoTransform; procedure DoTransform1;virtual; // vide procedure InitSrcRect(xa,ya,dxa,dya:float); procedure InitDestRect(xa,ya,dxa,dya:float); // les descendants doivent implémenter Init et DoTransform1 procedure InitMvt;override; procedure doneMvt;override; procedure CalculeMvt;override; function valid:boolean;override; procedure setObvis(uo:typeUO);override; procedure setSource(uo:typeUO);virtual; procedure setVisiFlags(flag:boolean);override; procedure initObvis;override; procedure AddTraj1(num:Integer; vec: Tvector); function AddTraj( st: AnsiString; vec: Tvector): integer;virtual; procedure updateTraj(numcycle:integer);virtual; // transfert les vecteurs traj dans les params courants procedure updateTraj1(numcycle:integer); // appelle updateTraj function MaxTrajParams:integer;virtual; function execute:integer; function UseRenderSurface: boolean;virtual; end; TVSpolarToCart = class(TVStransform) class function stmClassName: AnsiString;override; procedure DoTransform1;override; procedure Init(xa,ya,dxa,dya:float); end; TVSwave = class(TVStransform) x0,y0,Amp,f0,v0,tau:float; x0I,y0I: integer; yrefI:integer; AmpI,v0I, tauI: float; yref:float; waveMode: integer; constructor create;override; destructor destroy;override; class function stmClassName: AnsiString;override; procedure setObvis(uo:typeUO);override; procedure setSource(uo:typeUO);override; procedure Init(xa,ya,dxa,dya, x01,y01,Amp1,f01,v01,tau1:float); procedure DoTransform1;override; procedure InitMvt;override; procedure doneMvt;override; function AddTraj(st:AnsiString;vec:Tvector): integer;override; end; TVSsmooth = class(TVStransform) Nlum, Nalpha:integer; x0,y0,dmax1,dmax2:float; // Centre et distance max de l'atténuation x0I,y0I,dm1,dm2: integer; // idem converties LumRefI: array[1..3] of integer; LumRef: float; class function stmClassName: AnsiString;override; procedure InitMvt;override; procedure DoTransform1;override; function MaxTrajParams: integer;override; function AddTraj(st:AnsiString;vec:Tvector):integer;override; procedure updateTraj(numCycle:integer);override; end; TVSrings = class(TVStransform) x0,y0,AmpBase,Amp,WaveLen,Phi,tau:float; x0I,y0I: integer; AmpBaseI, AmpI,WaveLenI, tauI: float; waveMode: integer; constructor create;override; destructor destroy;override; class function stmClassName: AnsiString;override; procedure setSource(uo:typeUO);override; procedure Init(x01,y01,Amp0,Amp1,waveLen1,Phi1,tau1:float); procedure DoTransform1;override; procedure InitMvt;override; procedure doneMvt;override; function AddTraj(st:AnsiString;vec:Tvector): integer;override; function UseRenderSurface: boolean;override; end; TtransformList=class(Tlist) function UseRenderSurface:boolean; procedure DoRenderSurfaceTransforms; procedure RegisterRenderSurface; procedure UnRegisterRenderSurface; end; var TransformList: Ttransformlist; { Liste des objets du type TVStransform } procedure proTVStransform_setSource(var puOb,pu:typeUO);pascal; procedure proTVStransform_setStimScreenAsSource(var pu:typeUO);pascal; procedure proTVStransform_setDestination(var puOb,pu:typeUO);pascal; procedure proTVStransform_setDestination_1(var puOb:typeUO; DisableDisplay:boolean; var pu:typeUO);pascal; procedure proTVStransform_AddTraj(st: AnsiString; var vec: Tvector;var pu:typeUO);pascal; procedure proTVStransform_Execute(var pu:typeUO);pascal; procedure proTVSpolarToCart_create(var pu:typeUO);pascal; procedure proTVSpolarToCart_create_1(x1,y1,dx1,dy1:float;var pu:typeUO);pascal; procedure proTVSwave_create(x01,y01,Amp1,f01,v01,tau1:float;var pu:typeUO);pascal; procedure proTVSwave_create_1(x01,y01,Amp1,f01,v01,tau1,x1,y1,dx1,dy1:float;var pu:typeUO);pascal; procedure proTVSwave_yref(w:float;var pu: typeUO);pascal; function fonctionTVSwave_yref(var pu: typeUO):float;pascal; procedure proTVSwave_WaveMode(w:integer;var pu: typeUO);pascal; function fonctionTVSwave_WaveMode(var pu: typeUO):integer;pascal; procedure proTVSsmooth_create(N1, N2:integer;var pu:typeUO);pascal; procedure proTVSsmooth_setAttenuationParams(xA,yA,dA1,dA2,lum:float;var pu:typeUO);pascal; procedure proTVSrings_create(x01,y01,Amp0,Amp1,waveLen1,Phi1,tau1:float;var pu:typeUO);pascal; implementation { TVStransform } constructor TVStransform.create; begin inherited; TransformList.Add(self); //if assigned(DXscreen) then DXscreen.CheckRenderSurface; case sysPaletteNumber of 1: RgbMask := 4; 2: RgbMask := 2; 3: RgbMask := 1; 4: RgbMask := 6; 5: RgbMask := 5; 6: RgbMask := 3; else RgbMask := 7; end; dx1:= screenWidth; dy1:= screenHeight; dx2:= screenWidth; dy2:= screenHeight; TransformON:=true; end; destructor TVStransform.destroy; begin TransformList.Remove(self); if assigned(DXscreen) then DXscreen.CheckRenderSurface; derefObjet(typeUO(obSource)); inherited; end; procedure TVSTransform.freeRef; begin inherited; derefObjet(typeUO(obSource)); end; procedure TVStransform.DoTransform; var objetON:boolean; begin if not active or not TransformON then exit; with timeMan do objetON:=(timeS mod DureeC<DtOn) and (timeProcess<tend); if objetON then DoTransform1; end; procedure TVStransform.DoTransform1; begin end; procedure TVStransform.InitMvt; var res:integer; woffset1,hoffset1,width1, height1:integer; woffset2,hoffset2,width2, height2:integer; SrcResource, DestResource: pointer; begin inherited; initObvis; updateTraj1(0); // Destination if obvis<>nil then begin wDest:= TVSbitmap(obvis).Width; hDest:= TVSbitmap(obvis).Height; dxDest:= TVSbitmap(obvis).dxBM; dyDest:= TVSbitmap(obvis).dyBM; woffset2:= round(wDest/2+ (x2-dx2/2)* wDest/DxDest ); hoffset2:= round(hDest/2+ (y2-dy2/2)* hDest/DyDest ); width2 := wdest; //degToPix(dx2); height2 := hdest; //degToPix(dy2); if woffset2<0 then woffset2:=0; if hoffset2<0 then hoffset2:=0; if woffset2 + width2>= wDest then width2:= wDest- woffset2; if hoffset2 + height2>=hDest then height2:= hDest- hoffset2; end else begin wDest:= SSWidth; hDest:= SSHeight; dxDest:= ScreenWidth; dyDest:= ScreenHeight; woffset2:= degToX(x2-dx2/2); hoffset2:= degToY(y2+dy2/2); width2 := degToPix(dx2); height2 := degToPix(dy2); if woffset2<0 then woffset2:=0; if hoffset2<0 then hoffset2:=0; if woffset2 + width2>=SSWidth then width2:= SSwidth - woffset2; if hoffset2 + height2>=SSheight then height2:= SSheight - hoffset2; end; if obSource<>nil then begin wSrc:= obSource.Width; hSrc:= obSource.Height; dxSrc:= obSource.dxBM; dySrc:= obSource.dyBM; woffset1:= round(wSrc/2+ (x1-dx1/2)* wSrc/DxSrc ); hoffset1:= round(hSrc/2+ (y1-dy1/2)* hSrc/DySrc ); width1 := wsrc; //degToPix(dx1); height1 := hsrc; //degToPix(dy1); if woffset1<0 then woffset1:=0; if hoffset1<0 then hoffset1:=0; if woffset1 + width1>= wSrc then width1:= wSrc- woffset1; if hoffset1 + height1>=hSrc then height1:= hSrc- hoffset1; end else //if StimScreenAsSource then // begin wSrc:= wDest; hSrc:= hDest; dxSrc:= dxDest; dySrc:= dyDest; woffset1:= wOffset2; hoffset1:= hOffset2; width1 := width2; height1 := height2; end; xcSrc:= wSrc/2 -wOffset1; ycSrc:= hSrc/2 - hOffset1; xcDest:= wDest/2 -wOffset2; ycDest:= hDest/2 - hOffset2; DXscreen.CheckRenderSurface; if (obvis=nil)and UseRenderSurface then begin DXscreen.registerCuda; DestResource:= DXscreen.RenderResource; end else if obvis<>nil then begin TVSbitmap(obvis).registerCuda; DestResource:= TVSbitmap(obvis).BMCudaResource; end; if StimScreenAsSource and UseRenderSurface then begin DXscreen.registerCuda; SrcResource:= DXscreen.RenderResource; end else if (obsource<>nil) then begin obSource.registerCuda; SrcResource:= obSource.BMCudaResource; end else SrcResource:=nil; tf:= InitTransform(SrcResource, DestResource); cuda1.initSrcRect(tf,woffset1,hoffset1,width1,height1); cuda1.initDestRect(tf,woffset2,hoffset2,width2,height2); cuda1.initCenters(tf,xcSrc,ycSrc,xcDest,ycDest); mvtON:=true; cuda1.SetStream0(tf,cudaStream0); end; procedure TVStransform.doneMvt; begin cuda1.SetStream0(tf,0); DoneTransform(tf); mvtON:=false; // if (obvis<>nil) then TVSbitmap(obvis).unregisterCuda else DXscreen.UnregisterCuda; // if (obSource<>nil) then obSource.unregisterCuda else DXscreen.UnregisterCuda; end; procedure TVStransform.CalculeMvt; var tcycle, num:integer; begin if (obvis=nil) or not initCudaLib1 then exit; tCycle:=timeS mod dureeC; num:= timeS div dureeC; UpdateTraj1(num); if (tcycle=0) and (num<CycleCount) then begin TVSbitmap(obvis).MapResource; if assigned(ObSource) then TVSbitmap(obSource).MapResource; DoTransform; TVSbitmap(obvis).UnMapResource; if assigned(ObSource) then TVSbitmap(obSource).UnMapResource; end; end; procedure TVStransform.InitSrcRect(xa, ya, dxa, dya: float); begin x1:=xa; y1:=ya; dx1:=dxa; dy1:=dya; end; procedure TVStransform.InitDestRect(xa, ya, dxa, dya: float); begin x2:=xa; y2:=ya; dx2:=dxa; dy2:=dya; end; class function TVStransform.stmClassName: AnsiString; begin result:='VStransform'; end; function TVStransform.valid: boolean; begin result:=true; end; procedure TVStransform.AddTraj1(num:Integer; vec: Tvector); var i:integer; begin if vec.Icount<cycleCount then sortieErreur( 'T'+stmClassName+'.AddTraj : Not enough data in vector'); setLength(paramValue[num],vec.Icount); for i:=0 to vec.Icount-1 do paramValue[num,i]:= vec[vec.Istart+i]; end; function TVStransform.MaxTrajParams: integer; begin result:=1; end; function TVStransform.AddTraj( st: AnsiString; vec: Tvector):integer; begin if length(paramValue)=0 then setLength(paramValue,MaxTrajParams); st:=UpperCase(st); result:=-1; if st='TRANSFORMON' then result:=0; if result>=0 then AddTraj1(result,vec); end; procedure TVStransform.updateTraj(numcycle: integer); begin if length(paramvalue)>0 then begin if length(paramvalue[0])>numCycle then TransformON := (paramValue[0,numCycle]<>0); end; end; procedure TVStransform.updateTraj1(numcycle: integer); begin if not FsingleTransform then updateTraj(numcycle); end; procedure TVStransform.setObvis(uo: typeUO); begin if uo is TVSbitmap then begin inherited; with TVSbitmap(uo) do initDestRect(0,0,dxBM,dyBM); end; end; procedure TVStransform.setSource(uo: typeUO); begin if uo is TVSbitmap then begin derefObjet(typeUO(ObSource)); obSource:=TVSbitmap(uo); refObjet(typeUO(obSource)); with TVSbitmap(uo) do initSrcRect(0,0,dxBM,dyBM); end; end; procedure TVStransform.setVisiFlags(flag: boolean); begin if (obvis<>nil) and initCudaLib1 and flag and not DispDisable then obvis.FlagOnScreen:=true; end; procedure TVStransform.initObvis; begin if assigned(obvis) then obvis.prepareS; if assigned(obSource) then obSource.prepareS; end; procedure TVStransform.processMessage(id: integer; source: typeUO; p: pointer); begin inherited processMessage(id,source,p); case id of UOmsg_destroy: begin if (obSource=source) then begin obSource:=nil; derefObjet(source); end; end; end; end; function TVStransform.execute: integer; begin FsingleTransform:=true; InitMvt; try TVSbitmap(obvis).MapResource; if assigned(ObSource) then TVSbitmap(obSource).MapResource; DoTransform1; TVSbitmap(obvis).UnMapResource; if assigned(ObSource) then TVSbitmap(obSource).UnMapResource; finally FsingleTransform:=false; DoneMvt; result:=0; // code d'erreur ? end; end; function TVStransform.UseRenderSurface: boolean; begin result:= (obvis=nil) or StimScreenAsSource; end; {TVSpolarToCart } class function TVSpolarToCart.stmClassName: AnsiString; begin result:='VSpolarToCart'; end; procedure TVSpolarToCart.Init(xa, ya, dxa, dya: float); begin initSrcRect(xa,ya,dxa,dya); initDestRect(xa,ya,dxa,dya); end; procedure TVSpolarToCart.DoTransform1; var res:integer; begin res:=TransformCartToPol1(tf,syspal.BKcolIndex); end; { TVSwave } constructor TVSwave.create; begin inherited; end; destructor TVSwave.destroy; begin inherited; end; class function TVSwave.stmClassName: AnsiString; begin result:='VSwave'; end; procedure TVSwave.doneMvt; begin inherited; end; procedure TVSwave.setObvis(uo: typeUO); begin inherited; //obsource:=TVSbitmap(obvis); end; procedure TVSwave.setSource(uo: typeUO); begin inherited; //obvis:= obSource; end; procedure TVSwave.Init(xa,ya,dxa,dya, x01,y01,Amp1,f01,v01,tau1:float); begin initSrcRect(xa,ya,dxa,dya); initDestRect(xa,ya,dxa,dya); x0:= x01; y0:= y01; Amp:= Amp1; f0:= f01; v0:= v01; if tau1>0 then tau:=tau1 else tau:=0; end; procedure TVSwave.DoTransform1; var res:integer; a,b: single; begin if waveMode=0 then a:= 2*pi*f0/v0I else a:= 2*pi*f0/v0; b:= 2*pi*f0*timeS*Xframe; res:= WaveTransform1(tf,AmpI,a,b, tauI, x0I,y0I,yrefI,true, RgbMask,Wavemode=1); if res<>0 then WarningList.add('DoTransform1= '+Istr(res) ); //statuslineTxt(Istr(timeS)+' '+Estr(b,3)); end; procedure TVSwave.InitMvt; begin inherited; AmpI:= Amp/syspal.GammaGain; if yRef>=0 then yrefI:= syspal.LumIndex(yref) else yrefI:= -syspal.LumIndex(yref); if obvis=nil then begin x0I:= degToX(x0); y0I:= degToY(y0); end else with TVSbitmap(obvis) do begin x0I:= round(width/2+ self.x0*width/DxBM ); y0I:= round(height/2+ self.y0*height/DyBM ); end; v0I:= DegToPixR(v0); tauI:= DegToPixR(tau); end; function TVSwave.AddTraj(st: AnsiString; vec: Tvector):integer; begin result:= inherited AddTraj(st,vec); end; { TVSsmooth } procedure TVSsmooth.DoTransform1; var i,n:integer; begin x0I:= round(wsrc/Dxsrc*x0 ) +wsrc div 2; y0I:= -round(hsrc/Dysrc*y0) +hsrc div 2; dm1:= round(hsrc/Dysrc*dmax1); dm2:= round(hsrc/Dysrc*dmax2); n:= syspal.LumIndex(LumRef); for i:=1 to 3 do LumRefI[i]:= ((RgbMask shr (i-1)) and 1 ) * n; SmoothSurface(tf, Nlum, Nalpha , x0I,y0I,dm1,dm2, @LumRefI); end; procedure TVSsmooth.InitMvt; begin inherited; initDumRect(tf); x0I:= round(wsrc/Dxsrc*x0 ) +wsrc div 2; y0I:= -round(hsrc/Dysrc*y0) +hsrc div 2; end; class function TVSsmooth.stmClassName: AnsiString; begin result:='VSsmooth'; end; function TVSsmooth.MaxTrajParams: integer; begin result:= inherited MaxTrajParams +5; end; function TVSsmooth.AddTraj(st: AnsiString; vec: Tvector): integer; var base:integer; begin st:=UpperCase(st); result:= inherited AddTraj(st,vec); if result<0 then begin base:= inherited MaxTrajParams; if st='X0' then result:= base +0 else if st='Y0' then result:= base +1 else if st='LUMREF' then result:= base +2 else if st='DMAX1' then result:= base +3 else if st='DMAX2' then result:= base +4; if result>=0 then AddTraj1(result,vec); end; end; procedure TVSsmooth.updateTraj(numCycle: integer); var base:integer; begin if length(paramvalue)>0 then begin inherited UpdateTraj(numCycle); base:= inherited MaxTrajParams; if length(paramvalue[base +0])>numCycle then x0:=paramValue[base +0,numCycle]; if length(paramvalue[base +1])>numCycle then y0:=paramValue[base +1,numCycle]; if length(paramvalue[base +2])>numCycle then LumRef:=paramValue[base +2,numCycle]; if length(paramvalue[base +3])>numCycle then Dmax1:=paramValue[base +3,numCycle]; if length(paramvalue[base +4])>numCycle then Dmax2:=paramValue[base +4,numCycle]; end; end; { TVSrings } constructor TVSrings.create; begin inherited; end; destructor TVSrings.destroy; begin inherited; end; class function TVSrings.stmClassName: AnsiString; begin result:= 'TVSrings'; end; procedure TVSrings.doneMvt; begin inherited; end; procedure TVSrings.DoTransform1; var res:integer; a,b: single; begin inherited; a:= 2*pi/WaveLenI; b:= Phi; res:= BuildRings1(tf,AmpBaseI, AmpI,a,b, tauI, x0I,y0I,RgbMask,Wavemode); if res<>0 then WarningList.add('DoTransform1= '+Istr(res) ); end; procedure TVSrings.Init(x01,y01,Amp0,Amp1,waveLen1,Phi1,tau1:float); begin x0:= x01; y0:= y01; AmpBase:= Amp0; Amp:= Amp1; WaveLen:= WaveLen1; Phi:=Phi1; if tau1>0 then tau:=tau1 else tau:=0; end; procedure TVSrings.InitMvt; begin inherited; AmpBaseI:= AmpBase/syspal.GammaGain; AmpI:= Amp/syspal.GammaGain; if obvis=nil then begin x0I:= degToX(x0); y0I:= degToY(y0); end else with TVSbitmap(obvis) do begin x0I:= round(width/2+ self.x0*width/DxBM ); y0I:= round(height/2+ self.y0*height/DyBM ); end; WaveLenI:= DegToPixR(WaveLen); tauI:= DegToPixR(tau); end; procedure TVSrings.setSource(uo: typeUO); begin // Rien end; function TVSrings.AddTraj(st: AnsiString; vec: Tvector): integer; begin //TODO end; function TVSrings.UseRenderSurface: boolean; begin result:= (obvis=nil); end; { TtransformList } procedure TtransformList.DoRenderSurfaceTransforms; var i,res:integer; begin if initCudaLib1 and UseRenderSurface and (DXscreen.renderResource<>nil) then begin res:=cuda1.MapResources(@DXscreen.renderResource,1); for i:=0 to count-1 do with TVStransform(items[i]) do if obvis=nil then DoTransform; res:=cuda1.UnMapResources(@DXscreen.renderResource,1); end; end; procedure TtransformList.RegisterRenderSurface; var res:integer; begin affdebug('RegisterRenderSurface',199); if initCudaLib1 then begin if UseRenderSurface then begin res:= cuda1.RegisterTransformSurface(Idirect3DTexture9(DXscreen.renderSurface), DXscreen.RenderResource); affdebug('RegisterTransformSurface '+Istr(res)+' '+Istr(intG(DXscreen.renderSurface)),199); end; end; end; procedure TtransformList.UnRegisterRenderSurface; var res:integer; begin affdebug('UnRegisterRenderSurface',199); if initCudaLib1 then begin if UseRenderSurface then begin res:= cuda1.UnRegisterTransformSurface( DXscreen.RenderResource); affdebug('UnRegisterTransformSurface '+Istr(res)+' '+Istr(intG(DXscreen.renderSurface)),199); DXscreen.RenderResource:=nil; end; end; end; function TtransformList.UseRenderSurface: boolean; var i:integer; begin result:=false; for i:=0 to count-1 do if TVStransform(items[i]).UseRenderSurface then begin result:=true; exit; end; end; { Méthodes stm TVStransform} procedure proTVStransform_setSource(var puOb,pu:typeUO); begin verifierObjet(pu); verifierObjet(puOb); TVStransform(pu).setSource(puOb); end; procedure proTVStransform_setStimScreenAsSource(var pu:typeUO);pascal; begin verifierObjet(pu); TVStransform(pu).StimScreenAsSource:=true; end; procedure proTVStransform_setDestination(var puOb,pu:typeUO); begin verifierObjet(pu); verifierObjet(puOb); TVStransform(pu).setObvis(puOb); end; procedure proTVStransform_setDestination_1(var puOb:typeUO; DisableDisplay:boolean; var pu:typeUO); begin verifierObjet(pu); verifierObjet(puOb); TVStransform(pu).setObvis(puOb); TVStransform(pu).DispDisable:= DisableDisplay; end; procedure proTVStransform_AddTraj(st: AnsiString; var vec: Tvector;var pu:typeUO); begin verifierObjet(pu); verifierVecteur(vec); if TVStransform(pu).AddTraj(st,vec)<0 then sortieErreur('T'+pu.stmClassName+'.AddTraj : Bad Parameter Name') ; end; procedure proTVStransform_Execute(var pu:typeUO); var k:integer; begin verifierObjet(pu); k:= TVStransform(pu).Execute; if k<>0 then sortieErreur('T'+pu.stmClassName+'.Execute : error = '+Istr(k)) ; end; { Métodes stm TVSpolarToCart } procedure proTVSpolarToCart_create(var pu:typeUO); begin createPgObject('',pu,TVSpolarToCart); TVSpolarToCart(pu).Init(0,0,ScreenWidth,screenHeight); end; procedure proTVSpolarToCart_create_1(x1,y1,dx1,dy1:float;var pu:typeUO); begin createPgObject('',pu,TVSpolarToCart); TVSpolarToCart(pu).Init(x1,y1,dx1,dy1); end; { Méthodes stm TVSwave } procedure proTVSwave_create(x01,y01,Amp1,f01,v01,tau1:float;var pu:typeUO); begin createPgObject('',pu,TVSwave); TVSwave(pu).Init(0,0,ScreenWidth,screenHeight,x01,y01,Amp1,f01,v01,tau1); end; procedure proTVSwave_create_1(x01,y01,Amp1,f01,v01,tau1,x1,y1,dx1,dy1:float;var pu:typeUO); begin createPgObject('',pu,TVSwave); TVSwave(pu).Init(x1,y1,dx1,dy1,x01,y01,Amp1,f01,v01,tau1); end; procedure proTVSwave_yref(w:float;var pu: typeUO); begin verifierObjet(pu); TVSwave(pu).yref:=w; end; function fonctionTVSwave_yref(var pu: typeUO):float; begin verifierObjet(pu); result:= TVSwave(pu).yref; end; procedure proTVSwave_WaveMode(w:integer;var pu: typeUO); begin verifierObjet(pu); TVSwave(pu).WaveMode:=w; end; function fonctionTVSwave_WaveMode(var pu: typeUO):integer; begin verifierObjet(pu); result:= TVSwave(pu).WaveMode; end; {Méthodes stm TVSsmooth } procedure proTVSsmooth_create(N1,N2:integer;var pu:typeUO); begin createPgObject('',pu,TVSsmooth);; TVSsmooth(pu).Nlum:=N1; TVSsmooth(pu).Nalpha:=N2; end; procedure proTVSsmooth_setAttenuationParams(xA,yA,dA1,dA2,lum:float;var pu:typeUO); begin verifierObjet(pu); with TVSsmooth(pu) do begin x0:=xA; y0:=yA; dmax1:=dA1; dmax2:=dA2; LumRef:=lum; end; end; procedure proTVSrings_create(x01,y01,Amp0, Amp1,waveLen1,Phi1,tau1:float;var pu:typeUO); begin createPgObject('',pu,TVSrings); TVSrings(pu).Init(x01,y01,Amp0,Amp1,WaveLen1,Phi1,tau1); end; initialization TransformList:= Ttransformlist.create; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmBaseEdit Purpose : Base Edit class used by other "rmEdit" controls. Date : 01-15-2000 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmBaseEdit; interface {$I CompilerDefines.INC} uses Messages, Windows, Classes, StdCtrls; type TrmCustomEdit = class(TCustomEdit) private fWantTabs: boolean; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; public constructor Create(AOwner:TComponent); override; property BorderStyle; property ReadOnly; property WantTabs:boolean read fWantTabs write fWantTabs default false; end; implementation { TrmCustomEdit } procedure TrmCustomEdit.WMGetDlgCode(var Message: TWMGetDlgCode); begin inherited; if fWantTabs then Message.Result := Message.Result or DLGC_WANTTAB; end; constructor TrmCustomEdit.Create(AOwner: TComponent); begin inherited; fWantTabs := false; end; end.
unit ThChangeNotifier; interface uses SysUtils, Classes, Graphics; type TThChangeNotifier = class(TPersistent) private FOnChange: TNotifyEvent; public procedure Change; public property OnChange: TNotifyEvent read FOnChange write FOnChange; end; implementation { TThChangeNotifier } procedure TThChangeNotifier.Change; begin if Assigned(OnChange) then OnChange(Self); end; end.
unit Common.Barcode.Drawer; interface type IBarcodeDrawer = interface ['{A253E38C-AA33-47D5-B258-2DEE410BD8F2}'] function SVG(const AEncodedData: string): string; end; TBarcodeDrawer = class(TInterfacedObject, IBarcodeDrawer) protected function Get1(const Position, Length: single): string; virtual; function Get0(const Position: single): string; virtual; //IBarcodeDrawer function SVG(const AEncodedData: string): string; virtual; end; implementation uses System.SysUtils; { TBarcodeDrawer } function TBarcodeDrawer.Get0(const Position: single): string; begin result := format('m %s,0', [Position.ToString.Replace(',','.')]); end; function TBarcodeDrawer.Get1(const Position, Length: single): string; var Space: string; Line: string; begin Space := format('m %s,0', [Position.ToString.Replace(',','.')]); Line := format('h -%s v %s h %s z', [Position.ToString.Replace(',','.'), Length.ToString.Replace(',','.'), Position.ToString.Replace(',','.') ]); result := string.Join(' ', [Space,Line]); end; function TBarcodeDrawer.SVG(const AEncodedData: string): string; var Item: char; LPath: string; Size, Length: currency; begin Size := 0.33; Length := 1.0; result := Get0(1); for Item in AEncodedData do begin if Item = '0' then LPath := Get0(Size) else LPath := Get1(Size, Length); result := result + LPath; end; end; end.
unit uI2XOCRProcThread; interface uses SysUtils, Classes, uI2XDLL, uDWImage, GR32, uI2XThreadBase, uStrUtil, uHashTable, uI2XConstants, uImage2XML, uI2XTemplate, uI2XOCR, uI2XProduct, Typinfo, uI2XPluginManager, uI2XMemMap; type TOnImageAttributesCalculated = procedure( Sender : TObject; const Boundary : TRect; const FirstCharacter : TI2XOCRItem ) of object; TI2XOCRProcJobThread = class(TI2XThreadedImageJob) private FOnImageAttributesCalculated : TOnImageAttributesCalculated; FTemplateAsString : string; FTests : TDLLOCRTests; FTestsCreatedInternally : boolean; FResultXML : string; FTestCount : integer; FTemplate : CTemplate; FBoundary : TRect; FFirstCharacter : TI2XOCRItem; FFirstCharacterAsXML : string; //thread friend object representation of the first character FOffsetCorrection : boolean; //turn off Offset Correcton here function getTemplate: CTemplate; procedure setTemplate(const Value: CTemplate); protected procedure Execute; override; procedure SetOCREngineTests( OCREngineTests : TDLLOCRTests ); procedure OnImageAttributesCalculated( const Boundary : TRect; const FirstCharacter : TI2XOCRItem ); procedure DoImageAttributesCalculated(); virtual; public function ExecuteOCR() : boolean; property Template : CTemplate read getTemplate write setTemplate; property OCREngineTests : TDLLOCRTests read FTests write SetOCREngineTests; property TestCount : integer read FTestCount write FTestCount; property ResultXML : string read FResultXML write FResultXML; property EnableOffsetCorrection : boolean read FOffsetCorrection write FOffsetCorrection; property OnImageAttributesCalculatedEvent : TOnImageAttributesCalculated read FOnImageAttributesCalculated write FOnImageAttributesCalculated; constructor Create(); overload; constructor Create( bmp32: TBitmap32 ); overload; destructor Destroy; override; end; implementation { TI2XImageProcJobThread } constructor TI2XOCRProcJobThread.Create; begin inherited Create(); FTests := TDLLOCRTests.Create(); FResultXML := ''; FFirstCharacter := TI2XOCRItem.Create(); FOffsetCorrection := true; end; constructor TI2XOCRProcJobThread.Create(bmp32: TBitmap32); begin inherited Create( bmp32 ); FTests := TDLLOCRTests.Create(); FFirstCharacter := TI2XOCRItem.Create(); FResultXML := ''; FOffsetCorrection := true; end; destructor TI2XOCRProcJobThread.Destroy; begin if ( FTestsCreatedInternally ) then FreeAndNil( FTests ); if ( FTemplate <> nil ) then FreeAndNil( FTemplate ); if ( FFirstCharacter <> nil ) then FreeAndNil( FFirstCharacter ); inherited; end; procedure TI2XOCRProcJobThread.DoImageAttributesCalculated; begin if ( Assigned( self.FOnImageAttributesCalculated )) then begin self.FFirstCharacter.FromXML( self.FFirstCharacterAsXML ); FOnImageAttributesCalculated( self, self.FBoundary, self.FFirstCharacter ); end; end; procedure TI2XOCRProcJobThread.Execute; Begin ExecuteOCR(); End; function TI2XOCRProcJobThread.ExecuteOCR() : boolean; var DLLOCREngine : TDLLOCREngine; iOCRDLLEntry, iOCREngine, iTest, iProductUnitCount, TotalTestCount : smallint; sOCRDataMMID : string; OCREngines : THashTable; ocrdata : TI2XOCRResults; ocrDataList : array of TI2XOCRResults; productsList : array of TI2XProductItems; productFinal : TI2XProductItems; bInvert : boolean; productcompare : TI2XProductItemCompare; oDLLTest : TDLLOCRTestEntry; oTest : TDLLOCRTest; Plugins : TI2XPluginManager; ThreadMemoryMapManager : TI2XMemoryMapManager; oTemplate : CTemplate; sAction : string; BoundaryTest: TPoint; OCRItemTest: TI2XOCRItem; BestAccuracy : single; //this flag is important because if we do not have test of a whole page, it is difficult // to determine the offset of the scanned page. We must perform 1 full page test to determine // if there is some offset bWholeImageTest, bOffsetTestPerformed : boolean; arrTestEntriesSortedByWholeTests: TIndexValueArray; Offset : TPoint; Begin try //OCRItemTest := TI2XOCRItem.Create(); Initialize( Offset ); OCRItemTest := nil; bWholeImageTest := false; bOffsetTestPerformed := false; BestAccuracy := 0; ThreadMemoryMapManager := TI2XMemoryMapManager.Create; oTemplate := CTemplate.Create(); //life is always much easier if we create this object in the same thread oTemplate.LoadFromXML( self.FTemplateAsString ); FTestCount := 0; Result := false; if ( self.FCreatePluginMananger ) then begin Plugins := TI2XPluginManager.Create( DLLSearchPath ); if ( Plugins.SearchAndLoadOCRPlugins = 0 ) then raise Exception.Create('OCR Processing DLLS were not found in search path ' + DLLSearchPath ); end else Plugins := self.PluginManager; //Load Image Plugins OCREngines := THashTable.Create; ocrdata := TI2XOCRResults.Create; if self.EnableJobEvents then OnJobStart( FTests.TestCount ); if ( FTests.TestCount = 0 ) then begin OnStatusChange('There were no tests to perform.'); OnJobEnd( 0, '' ); end else begin try if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( 'Creating TI2XProductItemCompare' ); productcompare := TI2XProductItemCompare.Create( oTemplate ); if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( 'Initializing Variables' ); //TotalTestCount := FTests.TestCount; TotalTestCount := 0; if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( 'Calculating how many test we have to process' ); // figure out how many tests we have to process for iOCRDLLEntry := 0 to self.FTests.Count - 1 do begin oDLLTest := FTests.Items[ iOCRDLLEntry ]; if ( oDLLTest.Enabled ) then begin arrTestEntriesSortedByWholeTests := oDLLTest.IndexByWholeTests; for iTest := 0 to oDLLTest.Count - 1 do begin //oTest := oDLLTest[ iTest ]; oTest := TDLLOCRTest( arrTestEntriesSortedByWholeTests[ iTest ].obj ); if ( not bWholeImageTest ) then bWholeImageTest := oTest.IsWholePageTest; if ( oTest.Enabled ) then begin Inc( TotalTestCount ); end; end; //if a whole image test was not found and the template has document offset // correction set. if ( ( not bWholeImageTest) and ( oTemplate.DocumentOffsetCorrectionType <> ocNone ) ) then begin oDLLTest.Items[0].Enabled := true; end; end; end; if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( 'Starting Job...' ); OnJobStart( TotalTestCount ); SetLength(ocrDataList, TotalTestCount ); SetLength(productsList, TotalTestCount); for iOCRDLLEntry := 0 to self.FTests.Count - 1 do begin oDLLTest := FTests.Items[ iOCRDLLEntry ]; if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( 'Accessing DLL ' + oDLLTest.Name ); if ( not oDLLTest.Enabled ) then begin if ( Integer( self.DebugLevel ) >= 1 ) then begin OnStatusChange('The DLL (' + oDLLTest.Name + ') is disabled.'); if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( 'The DLL (' + oDLLTest.Name + ') is disabled.' ); end; end else begin DLLOCREngine := Plugins.OCRDLLByName( oDLLTest.Name ); if ( DLLOCREngine = nil ) then raise Exception.Create( 'DLL Test Entry of "' + oDLLTest.Name + '" does not have a corresponding DLL Engine' ); //DLLOCREngine := TDLLOCREngine( OCREngines[ oDLLTest.Name ] ); arrTestEntriesSortedByWholeTests := oDLLTest.IndexByWholeTests; for iTest := 0 to oDLLTest.Count - 1 do begin oTest := TDLLOCRTest( arrTestEntriesSortedByWholeTests[ iTest ].obj ); //oTest := oDLLTest[ iTest ]; self.LastDebugMessage := 'Accessing test ' + oTest.Name + ' of DLL ' + oDLLTest.Name + ' ( Enabled=' + uStrUtil.BoolToStr(oTest.Enabled, 'Yes', 'No') + ', Sliced=' + uStrUtil.BoolToStr(oTest.Slice, 'Yes', 'No') + ', Inverted=' + uStrUtil.BoolToStr(oTest.Invert, 'Yes', 'No') + ' )' ; if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( self.LastDebugMessage ); if ( oTest.Enabled ) then begin ocrDataList[FTestCount] := TI2XOCRResults.Create; // if we try to slice and image but no offset test has been performed AND // document offset correction is on, then we raise and error because // we missed a step somehwere // because we are using the template to fill with slices, it becomes // important to set the offset before we call this. // this value is calculated using an OCr from a whole image if ( oTest.Slice ) then begin self.LastDebugMessage := 'Slicing Images' ; if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( self.LastDebugMessage ); if ( FOffsetCorrection ) then begin if ( oTemplate.DocumentOffsetCorrectionType <> ocNone ) then begin if ( bOffsetTestPerformed ) then begin if (( Offset.X <> 0 ) or ( Offset.Y <> 0 )) then begin oTemplate.Offset( Offset.X, Offset.Y ); end; end else begin raise Exception.Create( 'If the template specifies document offset correction, then we cannot slice image without first testing to see if the document needs to be offset.' ) end; end; end; oTemplate.FillWithRegionSlices( ocrDataList[FTestCount] ); if ( oTemplate.IsOffset ) then oTemplate.Offset( 0, 0 ); end; try if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( ' Saving OCR Data to Memory Map' ); ThreadMemoryMapManager.Write( sOCRDataMMID, ocrDataList[ FTestCount ] ); //ocrDataList[ FTestCount ].SaveToMemoryMap( sOCRDataMMID ); except on e : Exception do begin self.LastDebugMessage := 'Error while trying to save OCR data to memory map. Exception Error:' + e.Message; if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( self.LastDebugMessage ); raise Exception.Create( self.LastDebugMessage ); end; end; try if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( 'Performing OCR using Image MMID=' + self.ImageMemoryMapID + ' and Data MMID=' + sOCRDataMMID + ' Invert=' + uStrUtil.BoolToStr(oTest.Invert, 'Yes', 'No') ); DLLOCREngine.OCRImage( self.ImageMemoryMapID, sOCRDataMMID, oTest.Invert ); except on e : Exception do begin self.LastDebugMessage := 'Error while calling OCR Engine.' + e.Message; if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( self.LastDebugMessage ); raise Exception.Create( self.LastDebugMessage ); end; end; if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( 'OCR Complete... Load MemoryMap ' + sOCRDataMMID ); try ThreadMemoryMapManager.Read( sOCRDataMMID, ocrDataList[ FTestCount ] ); //ocrDataList[ FTestCount ].LoadFromMemoryMap( sOCRDataMMID ); except self.LastDebugMessage := 'Error while Loading from Memory Map.'; if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( self.LastDebugMessage ); raise Exception.Create( self.LastDebugMessage ); end; if ( Integer( self.DebugLevel ) >= 2 ) then ocrDataList[FTestCount].SaveToFile( self.DebugPath + 'OCRDataDump_' + oTest.Name + '.xml' ); try OCRItemTest := nil; if ( ocrDataList[FTestCount].Count > 0 ) then begin OCRItemTest := ocrDataList[FTestCount].FirstCharacter; if (( OCRItemTest <> nil ) and ( BestAccuracy < OCRItemTest.Accuracy )) then begin FFirstCharacter.Assign( OCRItemTest ); FBoundary := ocrDataList[FTestCount].Boundary; BestAccuracy := FFirstCharacter.Accuracy; end; end; if ( FOffsetCorrection ) then begin if ( ( not bOffsetTestPerformed ) and ( oTemplate.DocumentOffsetCorrectionType <> ocNone ) and ( oTest.IsWholePageTest ) ) then begin self.LastDebugMessage := 'Performing Offset test...' ; if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( self.LastDebugMessage ); OffsetCorrection( oTemplate, ocrDataList[FTestCount], Offset ); self.LastDebugMessage := '.. Rest returned offset of X=' + IntToStr(Offset.X) + ' Y=' + IntToStr(Offset.Y) ; bOffsetTestPerformed := true; end; end; //end; self.LastDebugMessage := 'Creating Product Items for test ' + Alphabet[iTest + 1] + '. ' ; if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( self.LastDebugMessage ); productsList[ FTestCount ] := TI2XProductItems.Create( Alphabet[iTest + 1] ); //if this is a whole page and document offset correction is set // and we have an offset test performed, then we do the page offset // We do not do this for slices because the offset it already calculated when // we slice up the image if (( FOffsetCorrection ) and ( oTest.IsWholePageTest ) and ( oTemplate.DocumentOffsetCorrectionType <> ocNone ) and ( bOffsetTestPerformed )) then begin self.LastDebugMessage := 'Consuming OCR Results for test ' + Alphabet[(iTest + 1)] + ' with offset of X=' + IntToStr(Offset.X) + ' Y=' + IntToStr(Offset.Y); if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( self.LastDebugMessage ); oTemplate.Offset( Offset.X, Offset.Y ); productsList[ FTestCount ].ConsumeOCRResults( oTemplate, ocrDataList[FTestCount] ); if ( oTemplate.IsOffset ) then oTemplate.Offset( 0, 0 ); end else begin self.LastDebugMessage := 'Consuming OCR Results for test ' + Alphabet[iTest + 1] + ' with no offset'; if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( self.LastDebugMessage ); productsList[ FTestCount ].ConsumeOCRResults( oTemplate, ocrDataList[FTestCount] ); end; self.LastDebugMessage := 'Possible write out... '; if ( Integer( self.DebugLevel ) >= 2 ) then productsList[ FTestCount ].SaveToFile( self.DebugPath + 'OCRDataFormatted_' + oTest.Name + '.xml' ); except on e : Exception do begin self.LastDebugMessage := self.LastDebugMessage + ' Error while Consuming OCR Results. Exception Error:' + e.Message; if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( self.LastDebugMessage ); raise Exception.Create( self.LastDebugMessage ); end; end; productcompare.Add( productsList[FTestCount] ); OnStatusChange('OCR is ' + IntToStr( Round((FTestCount / ( TotalTestCount + 1 )) * 100)) + '% Complete.'); ; Inc( FTestCount ); end; end; //for end; //if DLLTest enabled end; if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( 'Comparing Results' ); if self.EnableJobEvents then self.OnImageAttributesCalculated( FBoundary, self.FFirstCharacter ); productFinal := TI2XProductItems.Create( 'RESULTS' ); productcompare.CompareRecusively( productFinal ); productFinal.SaveToFile( self.DebugPath + 'OCRData_RESULT.xml' ); productFinal.SourceImageFileName := ImageFileName; FResultXML := productFinal.AsXML(); except on E : Exception do begin if ( integer( self.DebugLevel ) >= 2 ) then OnDebugMessage( 'ERROR: ' + E.ClassName + ': ' + E.Message + #13 + 'ERROR: Last Debug Message=' + self.LastDebugMessage + #13 + 'ERROR: Last Status Message=' + self.LastStatusMessage ); self.OnJobError( ERROR_OCR_THREAD_FAILED, E.ClassName + ': ' + E.Message + ' ' + self.LastStatusMessage ); end; end; OnStatusChange( 'Image processing completed'); if self.EnableJobEvents then OnReturnXML( FResultXML ); if self.EnableJobEvents then OnJobEnd( FTestCount, self.ImageMemoryMapID ); end; Result := true; finally for iTest := 0 to Length( ocrDataList ) - 1 do if ( ocrDataList[iTest] <> nil ) then ocrDataList[iTest].Free; for iTest := 0 to Length( productsList ) - 1 do if ( productsList[iTest] <> nil ) then productsList[iTest].Free; //productsList[iTest].Free; if ( productcompare <> nil ) then FreeAndNil( productcompare ); if ( productFinal <> nil ) then FreeAndNil( productFinal ); if ( OCREngines <> nil ) then FreeAndNil( OCREngines ); if ( ocrdata <> nil ) then FreeAndNil( ocrdata ); if ( oTemplate <> nil ) then FreeAndNil( oTemplate ); if ( FCreatePluginMananger ) then FreeAndNil( Plugins ); if ( ThreadMemoryMapManager <> nil ) then FreeAndNil( ThreadMemoryMapManager ); //if ( OCRItemTest <> nil ) then FreeAndNil( OCRItemTest ); end; End; Function TI2XOCRProcJobThread.getTemplate: CTemplate; Begin if ( FTemplate <> nil ) then FreeAndNil( FTemplate ); FTemplate := CTemplate.Create(); FTemplate.LoadFromXML( self.FTemplateAsString ); result := FTemplate; End; procedure TI2XOCRProcJobThread.OnImageAttributesCalculated( const Boundary : TRect; const FirstCharacter : TI2XOCRItem ); begin self.FBoundary := Boundary; self.FFirstCharacterAsXML := FirstCharacter.AsXML(); self.Synchronize( self.DoImageAttributesCalculated ); end; Procedure TI2XOCRProcJobThread.SetOCREngineTests(OCREngineTests: TDLLOCRTests); Begin //If we set FTests externally, since we have already allocated it internally, // it will cause a memory leak if we do not destroy the old instance. if ( FTests <> nil ) then FTests.Free; FTestsCreatedInternally := false; FTests := OCREngineTests; End; procedure TI2XOCRProcJobThread.setTemplate(const Value: CTemplate); Begin self.FTemplateAsString := Value.asXML( xcComplete ); End; END.
unit voro; { Algorithm according to Shamos-Hoey and Lee that creates the voronoi diagram of a 2D point field in N log(N). Copyright (C) 2002 Christian Huettig Released: 08/08/2002 Restrictions: The line-cut algorithm isn't perfect (5% failure, but indicated!) Huge problems with collinearity Inefficient line discard algorithm How to use: Just throw the main unit and all whats related to out. Please let me know if you were able to fix something. Contact: snakers@gmx.net First published: www.torry.net This source is free; 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 source is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA } interface uses System.Classes, Vcl.Graphics, System.SysUtils, Vcl.Forms, // Voro GraphObjects; type TVoronoi = class(TObject) private Canvas: TCanvas; function Iterate(L: TList): TList; // The result is the convex hull ! public LGlobal: TList; // Global List of Points (and later Lines) constructor Create(C: TCanvas; L: TList); procedure ClearLines; // Deletes all Lines from LGlobal procedure CalcVoronoi(ShowCHull, ShowTriangulation: boolean); // Builds the Voronoi Diagram into LGlobal end; implementation uses main; constructor TVoronoi.Create(C: TCanvas; L: TList); begin LGlobal := L; Canvas := C; end; // --------------------------------------------------------------------- function getPointCount(L: TList): integer; var z: integer; begin result := 0; if L.Count = 0 then exit; for z := 0 to L.Count - 1 do if assigned(L.Items[z]) then if TObject(L.Items[z]) is TGPoint then inc(result); end; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- function TVoronoi.Iterate(L: TList): TList; // integrates the voronoi diagram from a given point list L into LGlobal, and returns the convex hull var iterateList1, iterateList2, temp: TList; z, i, i1, i2, points: integer; avgX, aex, aey, bex, bey: extended; ConvexHull1, ConvexHull2: TList; chain, el, er: TList; // el,er represents the voronoi polygon of pl/pr Edge: TGLine; v, pl, pr, ip1, ip2: TGPoint; mina, minb, maxa, a: extended; i1maxx, i2minx, i1max, i1min, i2max, i2min: integer; // indexes for the new convex hull label done, abort; {$I service.pas} // modularized the algorithm to keep it clear // --------------------------------------------------------------------------------------------- begin points := getPointCount(L); if points = 0 then begin raise ERangeError.Create('Received 0 point list in iteration!'); exit; end; result := TList.Create; if points = 1 then begin for z := 0 to L.Count - 1 do if assigned(L.Items[z]) then if TObject(L.Items[z]) is TGPoint then begin TGPoint(L.Items[z]).MoveToList(result); exit; end; raise ERangeError.Create('Found 0 points instead of 1!'); exit; end; if points = 3 then begin // collinear check, VERY incomplete. if TGPoint(L.Items[0]).areCollinear(L.Items[1], L.Items[2]) then begin if TGPoint(L.Items[0]).getx = TGPoint(L.Items[1]).getx then begin Sort(L, @SortY); end else if TGPoint(L.Items[0]).gety = TGPoint(L.Items[1]).gety then begin Sort(L, @SortX); end else Sort(L, @SortY); // integrate bisectors TGPoint(L.Items[0]).bisector(L.Items[1]).MoveToList(LGlobal); TGPoint(L.Items[1]).bisector(L.Items[2]).MoveToList(LGlobal); // build chull TGPoint(L.Items[0]).MoveToList(result); TGPoint(L.Items[2]).MoveToList(result); exit; end; end; iterateList1 := TList.Create; iterateList2 := TList.Create; avgX := getavgX(L); // divide all points into 2 seperate lists according to avgX for z := 0 to L.Count - 1 do if assigned(L.Items[z]) then if TObject(L.Items[z]) is TGPoint then if TGPoint(L.Items[z]).getx < avgX then TGPoint(L.Items[z]).MoveToList(iterateList1) else TGPoint(L.Items[z]).MoveToList(iterateList2); // for the case that all points have the same x value. we can't iterate an empty list if iterateList1.Count = 0 then TGPoint(iterateList2.Items[iterateList2.Count - 1]) .MoveToList(iterateList1); if iterateList2.Count = 0 then TGPoint(iterateList1.Items[iterateList1.Count - 1]) .MoveToList(iterateList2); // now the iteration ConvexHull1 := Iterate(iterateList1); ConvexHull2 := Iterate(iterateList2); // the hard part... chain := TList.Create; // // constructing new convex hull according to the Preparata-Hong algorithm // maxa := -66666; i1maxx := -1; for z := 0 to ConvexHull1.Count - 1 do if TGPoint(ConvexHull1.Items[z]).getx >= maxa then begin i1maxx := z; maxa := TGPoint(ConvexHull1.Items[z]).getx; end; mina := 66666; i2minx := -1; for z := 0 to ConvexHull2.Count - 1 do if TGPoint(ConvexHull2.Items[z]).getx <= mina then begin i2minx := z; mina := TGPoint(ConvexHull2.Items[z]).getx; end; // find upper supporting line i1 := i1maxx; i2 := i2minx; while (TGPoint(ConvexHull1.Items[i1]).Angle(ConvexHull2.Items[i2]) > TGPoint(ConvexHull1.Items[i1]).Angle(ConvexHull2.Items[next(i2, ConvexHull2) ])) or (TGPoint(ConvexHull2.Items[i2]).Angle(ConvexHull1.Items[i1]) < TGPoint(ConvexHull2.Items[i2]).Angle(ConvexHull1.Items[prev(i1, ConvexHull1)])) do begin while TGPoint(ConvexHull1.Items[i1]).Angle(ConvexHull2.Items[i2]) > TGPoint(ConvexHull1.Items[i1]) .Angle(ConvexHull2.Items[next(i2, ConvexHull2)]) do i2 := next(i2, ConvexHull2); while TGPoint(ConvexHull2.Items[i2]).Angle(ConvexHull1.Items[i1]) < TGPoint(ConvexHull2.Items[i2]) .Angle(ConvexHull1.Items[prev(i1, ConvexHull1)]) do i1 := prev(i1, ConvexHull1); end; i1max := i1; i2max := i2; // find lower supporting line i1 := i1maxx; i2 := i2minx; while (TGPoint(ConvexHull1.Items[i1]).Angle(ConvexHull2.Items[i2]) < TGPoint(ConvexHull1.Items[i1]).Angle(ConvexHull2.Items[prev(i2, ConvexHull2) ])) or (TGPoint(ConvexHull2.Items[i2]).Angle(ConvexHull1.Items[i1]) > TGPoint(ConvexHull2.Items[i2]).Angle(ConvexHull1.Items[next(i1, ConvexHull1)])) do begin while TGPoint(ConvexHull1.Items[i1]).Angle(ConvexHull2.Items[i2]) < TGPoint(ConvexHull1.Items[i1]) .Angle(ConvexHull2.Items[prev(i2, ConvexHull2)]) do i2 := prev(i2, ConvexHull2); while TGPoint(ConvexHull2.Items[i2]).Angle(ConvexHull1.Items[i1]) > TGPoint(ConvexHull2.Items[i2]) .Angle(ConvexHull1.Items[next(i1, ConvexHull1)]) do i1 := next(i1, ConvexHull1); end; i1min := i1; i2min := i2; // // constructing the dividing chain // el := nil; er := nil; TGPoint(ConvexHull1.Items[i1max]).bisector(ConvexHull2.Items[i2max]) .MoveToList(chain); // initial ray Edge := chain.Items[0]; if Edge.ey > 0 then // put v into a "conveniant large ordinate" v := TGPoint.Create(Edge.p2.getx + 6000 * Edge.ex, Edge.p2.gety + 6000 * Edge.ey, nil, nil) else v := TGPoint.Create(Edge.p2.getx - 6000 * Edge.ex, Edge.p2.gety - 6000 * Edge.ey, nil, nil); pl := ConvexHull1.Items[i1max]; pr := ConvexHull2.Items[i2max]; repeat GetVPoly(pl.GetOrigIndex, el); i1 := 0; GetVPoly(pr.GetOrigIndex, er); i2 := 0; if (el.Count = 0) and (er.Count = 0) then // only one bisector, can skip procedure goto done; ip1 := nil; ip2 := nil; mina := FindMinIPDistance(el, i1, ip1); minb := FindMinIPDistance(er, i2, ip2); // if mina=minb then raise ERangeError.Create('Wrong Cut'); if mina = minb then begin // the bad part. some cut went the wrong way, but to keep it running we skip the procedure. form1.Label1.Visible := true; goto abort; end; if mina < minb then begin aex := TGLine(el.Items[i1]).ex; aey := TGLine(el.Items[i1]).ey; bex := Edge.ex; bey := Edge.ey; if aey < 0 then aex := -aex; if bey < 0 then bex := -bex; if ((aex < bex) and (aex >= 0)) or ((aex > bex) and (aex < 0)) then TGLine(el.Items[i1]).CutLeft(Edge) else TGLine(el.Items[i1]).CutRight(Edge); v.Free; v := ip1.clone as TGPoint; if TGLine(el.Items[i1]).BisectorOf[1] = pl.GetOrigIndex then pl := LGlobal.Items[TGLine(el.Items[i1]).BisectorOf[2]] else pl := LGlobal.Items[TGLine(el.Items[i1]).BisectorOf[1]]; pl.bisector(pr).MoveToList(chain); end else begin aex := TGLine(er.Items[i2]).ex; aey := TGLine(er.Items[i2]).ey; bex := Edge.ex; bey := Edge.ey; if aey < 0 then aex := -aex; if bey < 0 then bex := -bex; if ((aex < bex) and (aex >= 0)) or ((aex > bex) and (aex < 0)) then TGLine(er.Items[i2]).CutRight(Edge) else TGLine(er.Items[i2]).CutLeft(Edge); v.Free; v := ip2.clone as TGPoint; if TGLine(er.Items[i2]).BisectorOf[1] = pr.GetOrigIndex then pr := LGlobal.Items[TGLine(er.Items[i2]).BisectorOf[2]] else pr := LGlobal.Items[TGLine(er.Items[i2]).BisectorOf[1]]; pr.bisector(pl).MoveToList(chain); end; if ip1 <> nil then ip1.Free; if ip2 <> nil then ip2.Free; Edge.CutBoth(chain.last); done: Edge := chain.last; until ((Edge.BisectorOf[1] = TGPoint(ConvexHull1.Items[i1min]).GetOrigIndex) and (Edge.BisectorOf[2] = TGPoint(ConvexHull2.Items[i2min]).GetOrigIndex)) or ((Edge.BisectorOf[2] = TGPoint(ConvexHull1.Items[i1min]).GetOrigIndex) and (Edge.BisectorOf[1] = TGPoint(ConvexHull2.Items[i2min]).GetOrigIndex)); abort: DiscardLines; // doesn't work perfect, and is very inefficent for z := 0 to chain.Count - 1 do // move chain to LGlobal TGLine(chain.Items[z]).MoveToList(LGlobal); // building new chull i := i1min; TGraphObject(ConvexHull1.Items[i]).MoveToList(result); while i <> i1max do begin i := next(i, ConvexHull1); TGraphObject(ConvexHull1.Items[i]).MoveToList(result); end; i := i2max; TGraphObject(ConvexHull2.Items[i]).MoveToList(result); while i <> i2min do begin i := next(i, ConvexHull2); TGraphObject(ConvexHull2.Items[i]).MoveToList(result); end; // finished chain.Free; ConvexHull1.Free; ConvexHull2.Free; iterateList2.Free; iterateList1.Free; end; procedure TVoronoi.ClearLines; // Deletes all Lines from LGlobal var z: integer; begin for z := 0 to LGlobal.Count - 1 do if assigned(LGlobal.Items[z]) then if TObject(LGlobal.Items[z]) is TGLine then begin TGLine(LGlobal.Items[z]).Free; LGlobal.Items[z] := nil; end; LGlobal.Pack; for z := 0 to LGlobal.Count - 1 do if TObject(LGlobal.Items[z]) is TGPoint then TGPoint(LGlobal.Items[z]).ReIndex(true); end; procedure TVoronoi.CalcVoronoi; // Builds the Voronoi Diagram into LGlobal var iterateList, chull: TList; L: TGLine; z: integer; begin form1.Label1.Visible := false; application.ProcessMessages; // must clone all points out of LGlobal because all points will be moved and killed during iteration if getPointCount(LGlobal) < 2 then exit; iterateList := TList.Create; for z := 0 to LGlobal.Count - 1 do if assigned(LGlobal.Items[z]) then if TObject(LGlobal.Items[z]) is TGPoint then TGPoint(LGlobal.Items[z]).CloneToList(iterateList); // ------------------------------------------------- chull := Iterate(iterateList); // ------------------------------------------------- if ShowTriangulation then begin for z := 0 to LGlobal.Count - 1 do if TObject(LGlobal.Items[z]) is TGLine then begin L := LGlobal.Items[z]; if L.BisectorOf[1] > -1 then begin TGLine.Create(LGlobal.Items[L.BisectorOf[1]], LGlobal.Items[L.BisectorOf[2]], TwoPoint, LGlobal, Canvas) .Color.Color := clgreen; end; end; end; if ShowCHull then begin for z := 0 to chull.Count - 2 do begin TGLine.Create(chull.Items[z], chull.Items[z + 1], TwoPoint, LGlobal, Canvas).Color.Color := clYellow; end; TGLine.Create(chull.Items[chull.Count - 1], chull.Items[0], TwoPoint, LGlobal, Canvas).Color.Color := clYellow; end; iterateList.Free; end; end.
unit UObjectCacheClass; interface uses uCommonForm, Classes,Buttons,Menus,UIdListsClass,uOilQuery,Ora, uOilStoredProc; type TObjectCache = class private function GetValues(p_Num:integer):pointer; public List: TList; property Values[p_Num:integer]:pointer read GetValues; default; function NextIndex:integer; function Add(p_Pointers: array of pointer):integer; procedure Delete(p_Num: integer); procedure MenuGroupClick(Sender: TObject); constructor Create; overload; destructor Destroy; override; end; implementation uses UReportClass; //============================================================================== constructor TObjectCache.Create; begin List:=TList.Create; end; //============================================================================== destructor TObjectCache.Destroy; begin List.Destroy; end; //============================================================================== function TObjectCache.NextIndex:integer; begin result:=List.Count; end; //============================================================================== function TObjectCache.Add(p_Pointers: array of pointer): integer; var newlist: TList; i: integer; begin newlist:=TList.Create; for i:=Low(p_Pointers) to High(p_Pointers) do newlist.Add(p_Pointers[i]); List.Add(newlist); result:=List.Count-1; end; //============================================================================== procedure TObjectCache.Delete(p_Num: integer); var templist:TList; begin templist:=List[p_Num]; templist.Destroy; List[p_Num]:=nil; end; //============================================================================== function TObjectCache.GetValues(p_Num:integer):pointer; begin result:=List[p_Num]; end; //============================================================================== procedure TObjectCache.MenuGroupClick(Sender: TObject); var ObjectCacheIndex,MenuItemIndex: integer; lst: TList; sb: TSpeedButton; groupidlist: TGroupIdList; proc: TMenuGroupProcedure; R: TReport; begin ObjectCacheIndex:=(Sender as TMenuItem).Tag div 1000; MenuItemIndex:=(Sender as TMenuItem).Tag mod 1000; lst:=List[ObjectCacheIndex]; sb:=lst[0]; groupidlist:=lst[1]; proc:=lst[2]; R:=lst[3]; proc(groupidlist,MenuItemIndex,sb,R); end; end.
unit PlatformListViewOptionsMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView.Types, Data.Bind.GenData, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.ObjectScope, FMX.ListView, IPPeerClient, REST.Backend.ServiceTypes, REST.Backend.MetaTypes, System.JSON, REST.Backend.KinveyServices, REST.Backend.BindSource, REST.Backend.ServiceComponents, REST.Backend.KinveyProvider, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.Bind.DBScope, REST.Response.Adapter, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.Stan.StorageBin, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ListBox, FMX.Layouts; type TForm24 = class(TForm) ListView1: TListView; ToolBar1: TToolBar; Label1: TLabel; ToolBar2: TToolBar; Layout1: TLayout; Grouped: TSpeedButton; Styled: TSpeedButton; Indexed: TSpeedButton; FDMemTable1: TFDMemTable; BindSourceDB1: TBindSourceDB; BindingsList1: TBindingsList; LinkFillControlToField1: TLinkFillControlToField; procedure GroupedClick(Sender: TObject); procedure IndexedClick(Sender: TObject); procedure StyledClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form24: TForm24; implementation {$R *.fmx} procedure TForm24.GroupedClick(Sender: TObject); begin if TListViewNativeOption.Grouped in ListView1.NativeOptions then ListView1.NativeOptions := ListView1.NativeOptions - [TListViewNativeOption.Grouped] else ListView1.NativeOptions := ListView1.NativeOptions + [TListViewNativeOption.Grouped]; end; procedure TForm24.IndexedClick(Sender: TObject); begin if TListViewNativeOption.Indexed in ListView1.NativeOptions then ListView1.NativeOptions := ListView1.NativeOptions - [TListViewNativeOption.Indexed] else ListView1.NativeOptions := ListView1.NativeOptions + [TListViewNativeOption.Indexed]; end; procedure TForm24.StyledClick(Sender: TObject); begin if TListViewNativeOption.Styled in ListView1.NativeOptions then ListView1.NativeOptions := ListView1.NativeOptions - [TListViewNativeOption.Styled] else ListView1.NativeOptions := ListView1.NativeOptions + [TListViewNativeOption.Styled]; end; end.
//********************************************************************************************************************** // $Id: udOpenFiles.pas,v 1.9 2006-08-23 15:19:11 dale Exp $ //---------------------------------------------------------------------------------------------------------------------- // DKLang Translation Editor // Copyright ęDK Software, http://www.dk-soft.org/ //********************************************************************************************************************** unit udOpenFiles; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DKLTranEdFrm, DKLang, StdCtrls, TntStdCtrls, ExtCtrls, TntExtCtrls; type TdOpenFiles = class(TDKLTranEdForm) bCancel: TTntButton; bDisplayFileBrowse: TTntButton; bHelp: TTntButton; bOK: TTntButton; bSourceFileBrowse: TTntButton; bTranFileBrowse: TTntButton; cbDisplayFile: TTntComboBox; cbSourceFile: TTntComboBox; cbTranFile: TTntComboBox; cbUseDisplayFile: TTntCheckBox; dklcMain: TDKLanguageController; lSource: TTntLabel; pMain: TTntPanel; rbNewTran: TTntRadioButton; rbOpenTran: TTntRadioButton; procedure AdjustOKCancel(Sender: TObject); procedure bDisplayFileBrowseClick(Sender: TObject); procedure bOKClick(Sender: TObject); procedure bSourceFileBrowseClick(Sender: TObject); procedure bTranFileBrowseClick(Sender: TObject); procedure cbUseDisplayFileClick(Sender: TObject); procedure RBTranClick(Sender: TObject); private // Source, display and translation file names FSourceFile: WideString; FDisplayFile: WideString; FTranFile: WideString; // Source, display and translation MRU lists FSourceMRUStrings: TStrings; FDisplayMRUStrings: TStrings; FTranMRUStrings: TStrings; // Updates the display-file controls depending on state of cbUseDisplayFile procedure UpdateDisplayFileCtls; // Updates the translation-file controls depending on state of radiobuttons procedure UpdateTranFileCtls; protected procedure DoCreate; override; procedure ExecuteInitialize; override; end; // Shows new/open translation dialog. If bNewMode=True, the dialog is for creating a new translation; otherwise this // is for opening an existing one function SelectLangFiles(var wsSourceFile, wsDisplayFile, wsTranFile: WideString; SourceMRUStrings, DisplayMRUStrings, TranMRUStrings: TStrings): Boolean; implementation {$R *.dfm} uses ConsVars; function SelectLangFiles(var wsSourceFile, wsDisplayFile, wsTranFile: WideString; SourceMRUStrings, DisplayMRUStrings, TranMRUStrings: TStrings): Boolean; begin with TdOpenFiles.Create(Application) do try FSourceFile := wsSourceFile; FDisplayFile := wsDisplayFile; FTranFile := wsTranFile; FSourceMRUStrings := SourceMRUStrings; FDisplayMRUStrings := DisplayMRUStrings; FTranMRUStrings := TranMRUStrings; Result := ExecuteModal; if Result then begin wsSourceFile := FSourceFile; wsDisplayFile := FDisplayFile; wsTranFile := FTranFile; end; finally Free; end; end; //=================================================================================================================== // TdOpenFiles //=================================================================================================================== procedure TdOpenFiles.AdjustOKCancel(Sender: TObject); begin bOK.Enabled := (cbSourceFile.Text<>'') and (not cbUseDisplayFile.Checked or (cbDisplayFile.Text<>'')) and (not rbOpenTran.Checked or (cbTranFile.Text<>'')); end; procedure TdOpenFiles.bDisplayFileBrowseClick(Sender: TObject); begin with TOpenDialog.Create(Self) do try DefaultExt := STranFileExt; Filter := DKLangConstW('STranFileFilter'); FileName := cbDisplayFile.Text; Options := [ofHideReadOnly, ofPathMustExist, ofFileMustExist, ofEnableSizing]; Title := DKLangConstW('SDlgTitle_SelectDisplayFile'); if Execute then begin cbDisplayFile.Text := FileName; AdjustOKCancel(nil); end; finally Free; end; end; procedure TdOpenFiles.bOKClick(Sender: TObject); begin // Source file FSourceFile := cbSourceFile.Text; CheckFileExists(FSourceFile); // Display file if cbUseDisplayFile.Checked then begin FDisplayFile := cbDisplayFile.Text; CheckFileExists(FDisplayFile); end else FDisplayFile := ''; // Translation file if rbOpenTran.Checked then begin FTranFile := cbTranFile.Text; CheckFileExists(FTranFile); end else FTranFile := ''; ModalResult := mrOK; end; procedure TdOpenFiles.bSourceFileBrowseClick(Sender: TObject); begin with TOpenDialog.Create(Self) do try DefaultExt := SLangSourceFileExt; Filter := DKLangConstW('SLangSourceFileFilter'); FileName := cbSourceFile.Text; Options := [ofHideReadOnly, ofPathMustExist, ofFileMustExist, ofEnableSizing]; Title := DKLangConstW('SDlgTitle_SelectLangSourceFile'); if Execute then begin cbSourceFile.Text := FileName; AdjustOKCancel(nil); end; finally Free; end; end; procedure TdOpenFiles.bTranFileBrowseClick(Sender: TObject); begin with TSaveDialog.Create(Self) do try DefaultExt := STranFileExt; Filter := DKLangConstW('STranFileFilter'); FileName := cbTranFile.Text; Options := [ofHideReadOnly, ofPathMustExist, ofFileMustExist, ofEnableSizing]; Title := DKLangConstW('SDlgTitle_SelectTranFile'); if Execute then begin cbTranFile.Text := FileName; AdjustOKCancel(nil); end; finally Free; end; end; procedure TdOpenFiles.cbUseDisplayFileClick(Sender: TObject); begin UpdateDisplayFileCtls; if Visible and cbUseDisplayFile.Checked then cbDisplayFile.SetFocus; AdjustOKCancel(nil); end; procedure TdOpenFiles.DoCreate; begin inherited DoCreate;; // Initialize help context ID HelpContext := IDH_iface_dlg_open_files; end; procedure TdOpenFiles.ExecuteInitialize; begin inherited ExecuteInitialize; // Source file cbSourceFile.Items.Assign(FSourceMRUStrings); cbSourceFile.Text := FSourceFile; // Display file cbDisplayFile.Items.Assign(FDisplayMRUStrings); cbDisplayFile.Text := FDisplayFile; cbUseDisplayFile.Checked := FDisplayFile<>''; UpdateDisplayFileCtls; // Translation file cbTranFile.Items.Assign(FTranMRUStrings); cbTranFile.Text := FTranFile; rbOpenTran.Checked := FTranFile<>''; UpdateTranFileCtls; AdjustOKCancel(nil); end; procedure TdOpenFiles.RBTranClick(Sender: TObject); begin UpdateTranFileCtls; if Visible and rbOpenTran.Checked then cbTranFile.SetFocus; AdjustOKCancel(nil); end; procedure TdOpenFiles.UpdateDisplayFileCtls; begin EnableWndCtl(cbDisplayFile, cbUseDisplayFile.Checked); bDisplayFileBrowse.Enabled := cbUseDisplayFile.Checked; end; procedure TdOpenFiles.UpdateTranFileCtls; begin EnableWndCtl(cbTranFile, rbOpenTran.Checked); bTranFileBrowse.Enabled := rbOpenTran.Checked; end; end.
unit Dialog_EditUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,ElTree, StdCtrls,DW,ADODB,BaseContext, RzLabel, Mask, RzEdit, Class_OperaTree,Class_AppCheck; type TDialogEditUnit = class(TForm) Btn_OK: TButton; Btn_Cancel: TButton; ChkBox_Child: TCheckBox; RzLabel1: TRzLabel; RzLabel2: TRzLabel; RzLabel3: TRzLabel; RzLabel5: TRzLabel; RzLabel6: TRzLabel; RzLabel7: TRzLabel; RzLabel8: TRzLabel; RzLabel9: TRzLabel; Edit_Name: TRzEdit; Edit_Kind: TRzEdit; Edit_Photo: TRzEdit; Edit_MainMan: TRzEdit; Edit_Code: TRzEdit; Edit_State: TRzEdit; Edit_Address: TRzEdit; Edit_FinMan: TRzEdit; Label_Length: TRzLabel; procedure FormShow(Sender: TObject); procedure Btn_OKClick(Sender: TObject); procedure ChkBox_ChildClick(Sender: TObject); procedure Btn_CancelClick(Sender: TObject); procedure Edit_CodeKeyPress(Sender: TObject; var Key: Char); private FOperaMode:Integer; FParItem :TElTreeItem;//父级 FCodeRule:string; protected procedure SetInitialize; // procedure SaveUnit; procedure InsertDB; procedure UpdateDB; // procedure RendUnit(ADW:TDW); protected //property function GetActiveLength:Integer; //设置(*位); function GetActiveLevel:Integer; function GetActiveCodeLink:string; function GetActiveUnit:TDW; // function CheckLicit:Boolean; procedure SetLabelLengthCaption; protected property ActiveLength :Integer read GetActiveLength; property ActiveLevel :Integer read GetActiveLevel; property ActiveCodeLink:string read GetActiveCodeLink; property ActiveUnit :TDW read GetActiveUnit; public constructor Create(AOwner: TComponent); override; end; var DialogEditUnit: TDialogEditUnit; function FuncEditUnit(AOperaMode:Integer;ACodeRule:string;AParItem:TElTreeItem):Integer; implementation uses ConstValues; {$R *.dfm} { TFormEditUnit } function FuncEditUnit(AOperaMode:Integer;ACodeRule:string;AParItem:TElTreeItem):Integer; begin try DialogEditUnit:=TDialogEditUnit.Create(Application); DialogEditUnit.FOperaMode:=AOperaMode; DialogEditUnit.FParItem :=AParItem; DialogEditUnit.FCodeRule :=ACodeRule; Result:=DialogEditUnit.ShowModal; finally FreeAndNil(DialogEditUnit); end; end; constructor TDialogEditUnit.Create(AOwner: TComponent); begin inherited; Position:=poScreenCenter; BorderStyle:=bsDialog; end; procedure TDialogEditUnit.SetInitialize; begin Btn_OK.Caption:='确定'; Btn_Cancel.Caption:='取消'; case FOperaMode of 0:Caption:='新增单位' ; 1:begin Caption:='单位编辑'; RendUnit(ActiveUnit); end; end; if Length(FCodeRule)=Self.ActiveLevel then begin ChkBox_Child.Enabled:=False; end; SetLabelLengthCaption; end; procedure TDialogEditUnit.FormShow(Sender: TObject); begin SetInitialize; end; procedure TDialogEditUnit.Btn_OKClick(Sender: TObject); begin SaveUnit; end; procedure TDialogEditUnit.SaveUnit; begin case FOperaMode of 0: InsertDB ; 1: UpdateDB ; end; end; procedure TDialogEditUnit.InsertDB; var ADW:TDW; ADOCon:TADOConnection; begin if not CheckLicit then Exit; try ADOCon:=Context.GetConnection(0,C_MODULE_XZGL); try ADW:=TDW.Create; ADW.MC :=Self.Edit_Name.Text; ADW.BM :=Self.Edit_Code.Text; ADW.BML:=Self.ActiveCodeLink; ADW.JS :=Self.ActiveLevel; ADW.DWFZR:=Edit_MainMan.Text; ADW.CWFZR:=Edit_FinMan.Text; ADW.LXDH :=Edit_Photo.Text; ADW.DZ :=Edit_Address.Text; ADW.ZT :=C_Active; //EX ADW.InsertDB(ADOCon); ShowMessage('保存成功'); ModalResult:=mrOk; except raise Exception.Create('保存失败.请检查数据库结构完整性'); end; finally Context.ReleaseConnection(ADOCon); end; end; procedure TDialogEditUnit.UpdateDB; var ADOCon:TADOConnection; begin try try ADOCon:=Context.GetConnection(0,C_MODULE_XZGL); ActiveUnit.MC :=Edit_Name.Text; ActiveUnit.DWFZR:=Edit_MainMan.Text; ActiveUnit.CWFZR:=Edit_FinMan.Text; ActiveUnit.LXDH :=Edit_Photo.Text; ActiveUnit.DZ :=Edit_Address.Text; ActiveUnit.ZT :=C_Active; ActiveUnit.UpdateDB(ADOCon); ShowMessage('更新成功'); except ShowMessage('更新出错,请职系维护人员'); Exit; end; finally Context.ReleaseConnection(ADOCon); end; ModalResult:=mrOk; end; function TDialogEditUnit.GetActiveLevel: Integer; var ADW:TDW; begin Result:=1; ADW:=nil; if FParItem<>nil then begin ADW:=TDW(FParItem.Data); end; case FOperaMode of 0:begin if ADW=nil then Exit; Result:=ADW.JS; if ChkBox_Child.Checked then begin Result:=ADW.JS+1; end; end ; 1:begin Result:=ADW.JS; end ; end; end; function TDialogEditUnit.GetActiveCodeLink: string; var ADW:TDW; Temp:string; begin if FOperaMode=1 then raise Exception.Create('ERROR:VISIT ERROR'); Result:=Edit_Code.Text; if Self.ActiveLevel=1 then Exit; ADW:=TDW(FParItem.Data); if ChkBox_Child.Checked then begin Result:=ADW.BML+'-'+Edit_Code.Text; end else begin Temp :=TOperaTree.GetLastCode(ADW.JS,ADW.BML,FCodeRule); Result:=Temp+'-'+Edit_Code.Text; end; end; function TDialogEditUnit.CheckLicit: Boolean; begin Result:=False; if Edit_Name.Text='' then begin ShowMessage('请输入单位名称'); Edit_Name.SetFocus; Exit; end; if Edit_Code.Text='' then begin ShowMessage('请输入单位编码'); Edit_Code.SetFocus; Exit; end; if Length(Edit_Code.Text)<>Self.ActiveLength then begin ShowMessage(Format('单位编码应该为%d位',[Self.ActiveLength])); Edit_Code.SetFocus; Exit; end; if AppCheck.Check_Unit_CodeLink_ExistedDB(Self.ActiveCodeLink) then begin ShowMessage('单位编码存在重复'); Edit_Code.SetFocus; Exit; end; Result:=True; end; function TDialogEditUnit.GetActiveLength:Integer; var ALevel:Integer; begin ALevel:=Self.ActiveLevel; Result:=StrToInt(FCodeRule[ALevel]); end; procedure TDialogEditUnit.SetLabelLengthCaption; var ACount:Integer; begin ACount:=Self.ActiveLength; Label_Length.Caption:=Format('(%d位)',[ACount]); end; procedure TDialogEditUnit.ChkBox_ChildClick(Sender: TObject); begin SetLabelLengthCaption; end; procedure TDialogEditUnit.RendUnit(ADW: TDW); begin Edit_Code.Text:=ADW.BM; Edit_Code.Enabled:=False; Edit_Name.Text:=ADW.MC; Edit_FinMan.SetFocus; Edit_Photo.Text:=ADW.LXDH; Edit_Address.Text:=ADW.DZ; Edit_MainMan.Text:=ADW.DWFZR; Edit_FinMan.Text :=ADW.CWFZR; end; function TDialogEditUnit.GetActiveUnit: TDW; begin Result:=nil; if FParItem<>nil then begin Result:=TDW(FParItem.Data); end; end; procedure TDialogEditUnit.Btn_CancelClick(Sender: TObject); begin ModalResult:=mrOk; end; procedure TDialogEditUnit.Edit_CodeKeyPress(Sender: TObject; var Key: Char); begin if not(Key in['0'..'9',#8,#13]) then begin Beep; Key:=#0; end; end; end.
unit OTFEFreeOTFEDLL_U; { TOTFEFreeOTFEDLL is a wrapper round the DLL and also does all drive operations, enc data, create new vols, etc is a singleton class, only ever one instance - this is enforced by assertion in base class ctor set up instance by calling OTFEFreeOTFEBase_U.SetFreeOTFEType then get instance by calling OTFEFreeOTFEBase_U.GetFreeOTFE or TOTFEFreeOTFEDLL.GetFreeOTFE } interface uses Classes, Windows, SDUGeneral, OTFE_U, OTFEFreeOTFEBase_U, pkcs11_session, PKCS11Lib, FreeOTFEDLLMainAPI, FreeOTFEDLLHashAPI, FreeOTFEDLLCypherAPI, DriverAPI, OTFEFreeOTFE_DriverHashAPI, OTFEFreeOTFE_DriverCypherAPI; type TMainAPI = record LibFilename: string; hDLL: THandle; DSK_Init: PDSK_Init; DSK_Deinit: PDSK_Deinit; DSK_Open: PDSK_Open; DSK_Close: PDSK_Close; DSK_IOControl: PDSK_IOControl; DSK_Seek: PDSK_Seek; DSK_Read: PDSK_Read; DSK_Write: PDSK_Write; DSK_PowerDown: PDSK_PowerDown; DSK_PowerUp: PDSK_PowerUp; MainDLLFnDeriveKey: PMainDLLFnDeriveKey; MainDLLFnMACData: PMainDLLFnMACData; end; THashAPI = record LibFilename: string; hDLL: THandle; HashDLLFnIdentifyDriver: PHashDLLFnIdentifyDriver; HashDLLFnIdentifySupported: PHashDLLFnIdentifySupported; HashDLLFnGetHashDetails: PHashDLLFnGetHashDetails; HashDLLFnHash: PHashDLLFnHash; end; PHashAPI = ^THashAPI; TCypherAPI = record LibFilename: string; hDLL: THandle; CypherDLLFnIdentifyDriver: PCypherDLLFnIdentifyDriver; CypherDLLFnIdentifySupported_v1: PCypherDLLFnIdentifySupported_v1; CypherDLLFnIdentifySupported_v3: PCypherDLLFnIdentifySupported_v3; CypherDLLFnGetCypherDetails_v1: PCypherDLLFnGetCypherDetails_v1; CypherDLLFnGetCypherDetails_v3: PCypherDLLFnGetCypherDetails_v3; CypherDLLFnEncrypt: PCypherDLLFnEncrypt; CypherDLLFnEncryptSector: PCypherDLLFnEncryptSector; CypherDLLFnEncryptWithASCII: PCypherDLLFnEncryptWithASCII; CypherDLLFnEncryptSectorWithASCII: PCypherDLLFnEncryptSectorWithASCII; CypherDLLFnDecrypt: PCypherDLLFnDecrypt; CypherDLLFnDecryptSector: PCypherDLLFnDecryptSector; CypherDLLFnDecryptWithASCII: PCypherDLLFnDecryptWithASCII; CypherDLLFnDecryptSectorWithASCII: PCypherDLLFnDecryptSectorWithASCII; end; PCypherAPI = ^TCypherAPI; TMountedHandle = record DeviceHandle: DWORD; OpenHandle: DWORD; BytesPerSector: DWORD; end; PMountedHandle = ^TMountedHandle; TOTFEFreeOTFEDLL = class(TOTFEFreeOTFEBase) private FExeDir: string; function GetDLLDir: string; protected DriverAPI: TMainAPI; fMountedHandles: TStringList;// in unicdoe fCachedDiskGeometry: TStringList; // Cached information: The strings in the list are DLL path and filenames, // the objects are THashAPI/TCypherAPI fCachedHashAPI: TStringList; fCachedCypherAPI: TStringList; function Connect(): boolean; override; function Disconnect(): boolean; override; procedure AddHandles(driveLetter: char; handles: TMountedHandle); function GetHandles(driveLetter: char; var handles: TMountedHandle): boolean; procedure DeleteHandles(driveLetter: char); procedure AddDiskGeometry(driveLetter: char; diskGeometry: TSDUDiskGeometry); procedure DeleteDiskGeometry(driveLetter: char); // Internal use only; callers should normally use GetDiskGeometry(...) // (without prefixing "_") instead function _GetDiskGeometry( DriveLetter: char; var diskGeometry: TSDUDiskGeometry ): boolean; function _GetCypherDriverCyphers_v1(cypherDriver: ansistring; var cypherDriverDetails: TFreeOTFECypherDriver): boolean; override; function _GetCypherDriverCyphers_v3(cypherDriver: ansistring; var cypherDriverDetails: TFreeOTFECypherDriver): boolean; override; procedure GetAllDriversUnderExeDir(driverFilenames: TStringList); function LoadLibraryMain(var api: TMainAPI): boolean; procedure FreeLibraryMain(var api: TMainAPI); function LoadLibraryHash(const libFilename: string; var api: THashAPI): boolean; function LoadLibraryCachedHash(const libFilename: string; var api: THashAPI): boolean; procedure FreeLibraryHash(var api: THashAPI); function LoadLibraryCypher(const libFilename: string; var api: TCypherAPI): boolean; function LoadLibraryCachedCypher(const libFilename: string; var api: TCypherAPI): boolean; procedure FreeLibraryCypher(var api: TCypherAPI); function MainDLLFilename(): string; // --------- // FreeOTFE *disk* *device* management functions // These talk directly to the disk devices to carrry out operations function MountDiskDevice( deviceName: string; // PC kernel drivers: disk device to mount. PC DLL: "Drive letter" volFilename: string; volumeKey: TSDUBytes; sectorIVGenMethod: TFreeOTFESectorIVGenMethod; volumeIV: TSDUBytes; readonly: boolean; IVHashDriver: ansistring; IVHashGUID: TGUID; IVCypherDriver: ansistring; IVCypherGUID: TGUID; mainCypherDriver: ansistring; mainCypherGUID: TGUID; VolumeFlags: integer; metaData: TOTFEFreeOTFEVolumeMetaData; offset: int64 = 0; size: int64 = 0; storageMediaType: TFreeOTFEStorageMediaType = mtFixedMedia // PC kernel drivers *only* - ignored otherwise ): boolean; override; function CreateMountDiskDevice( volFilename: string; volumeKey: TSDUBytes; sectorIVGenMethod: TFreeOTFESectorIVGenMethod; volumeIV: TSDUBytes; readonly: boolean; IVHashDriver: ansistring; IVHashGUID: TGUID; IVCypherDriver: ansistring; IVCypherGUID: TGUID; mainCypherDriver: ansistring; mainCypherGUID: TGUID; VolumeFlags: integer; DriveLetter: char; // PC kernel drivers: disk device to mount. PC DLL: "Drive letter" offset: int64 = 0; size: int64 = 0; MetaData_LinuxVolume: boolean = FALSE; // Linux volume MetaData_PKCS11SlotID: integer = PKCS11_NO_SLOT_ID; // PKCS11 SlotID MountMountAs: TFreeOTFEMountAs = fomaRemovableDisk; // PC kernel drivers *only* - ignored otherwise mountForAllUsers: boolean = TRUE // PC kernel drivers *only* - ignored otherwise ): boolean; override; function DismountDiskDevice( deviceName: string; // PC kernel drivers: disk device to mount. PC DLL: "Drive letter" emergency: boolean ): boolean; override; // --------- // Raw volume access functions function ReadWritePlaintextToVolume( readNotWrite: boolean; volFilename: string; volumeKey: TSDUBytes; sectorIVGenMethod: TFreeOTFESectorIVGenMethod; IVHashDriver: Ansistring; IVHashGUID: TGUID; IVCypherDriver: Ansistring; IVCypherGUID: TGUID; mainCypherDriver: Ansistring; mainCypherGUID: TGUID; VolumeFlags: integer; mountMountAs: TFreeOTFEMountAs; dataOffset: int64; // Offset from within mounted volume from where to read/write data dataLength: integer; // Length of data to read/write. In bytes var data: TSDUBytes; // Data to read/write offset: int64 = 0; size: int64 = 0; storageMediaType: TFreeOTFEStorageMediaType = mtFixedMedia ): boolean; override; // --------- // Internal caching functions procedure CachesCreate(); override; procedure CachesDestroy(); override; procedure CachesAddHashAPI(const libFilename: string; const api: THashAPI); function CachesGetHashAPI(const libFilename: string; var api: THashAPI): boolean; procedure CachesAddCypherAPI(const libFilename: string; const api: TCypherAPI); function CachesGetCypherAPI(const libFilename: string; var api: TCypherAPI): boolean; // --------- // Misc functions function GetNextDriveLetter(userDriveLetter, requiredDriveLetter: char): char; overload; override; function DriverType(): string; override; public // ----------------------------------------------------------------------- // TOTFE standard API constructor Create(); override; destructor Destroy; override; function Dismount(driveLetter: char; emergency: boolean = FALSE): boolean; overload; override; function Version(): cardinal; overload; override; function DrivesMounted(): string; overload; override; // ----------------------------------------------------------------------- // TOTFEFreeOTFEBase standard API function GetVolumeInfo(driveLetter: char; var volumeInfo: TOTFEFreeOTFEVolumeInfo): boolean; override; function GetHashDrivers(var hashDrivers: TFreeOTFEHashDriverArray): boolean; override; function GetHashDriverHashes(hashDriver: ansistring; var hashDriverDetails: TFreeOTFEHashDriver): boolean; override; function GetCypherDrivers(var cypherDrivers: TFreeOTFECypherDriverArray): boolean; override; function _EncryptDecryptData( encryptFlag: boolean; cypherDriver: ansistring; cypherGUID: TGUID; var key: TSDUBytes; var IV: Ansistring; var inData: Ansistring; var outData: Ansistring ): boolean; override; function EncryptDecryptSectorData( encryptFlag: boolean; cypherDriver: ansistring; cypherGUID: TGUID; SectorID: LARGE_INTEGER; SectorSize: integer; var key: TSDUBytes; var IV: Ansistring; var inData: Ansistring; var outData: Ansistring ): boolean; override; function HashData( hashDriver: Ansistring; hashGUID: TGUID; const data: TSDUBytes; out hashOut: TSDUBytes ): boolean; override; function MACData( macAlgorithm: TFreeOTFEMACAlgorithm; HashDriver: Ansistring; HashGUID: TGUID; CypherDriver: Ansistring; CypherGUID: TGUID; var key: PasswordString; var data: Ansistring; var MACOut: Ansistring; tBits: integer = -1 ): boolean; override; function DeriveKey( kdfAlgorithm: TFreeOTFEKDFAlgorithm; HashDriver: Ansistring; HashGUID: TGUID; CypherDriver: Ansistring; CypherGUID: TGUID; Password: TSDUBytes; Salt: array of byte; Iterations: integer; dkLenBits: integer; // In *bits* out DK: TSDUBytes ): boolean; override; // ----------------------------------------------------------------------- // Extended FreeOTFE DLL specific functions function Seek(driveLetter: char; offset: DWORD): boolean; function ReadData_Sectors( DriveLetter: char; SectorNoStart: DWORD; CountSectors: DWORD; stm: TStream ): boolean; function WriteData_Sectors( DriveLetter: char; SectorNoStart: DWORD; CountSectors: DWORD; stm: TStream ): boolean; function ReadData_Bytes( DriveLetter: char; Offset: ULONGLONG; DataLength: ULONGLONG; Data: TStream ): boolean; function WriteData_Bytes( DriveLetter: char; Offset: ULONGLONG; DataLength: ULONGLONG; Data: TStream ): boolean; function GetDiskGeometry( DriveLetter: char; var diskGeometry: TSDUDiskGeometry ): boolean; published // The directory under which the "DLL" dir resides // property ExeDir: string read FExeDir ; end; {returns an instance of the only object. call SetFreeOTFEType first} function GetFreeOTFEDLL : TOTFEFreeOTFEDLL; implementation uses // delphi dialogs, SysUtils, Math, Controls, Forms, strutils, //sdu SDUSysUtils, SDUi18n, SDUClasses, SDUFileIterator_U, //LibreCrypt OTFEConsts_U, frmKeyEntryFreeOTFE, frmKeyEntryLinux, frmKeyEntryLUKS, OTFEFreeOTFE_LUKSAPI, VolumeFileAPI; const DLL_HASH_FILE_PREFIX = 'FreeOTFEHash'; DLL_CYPHER_FILE_PREFIX = 'FreeOTFECypher'; // ---------------------------------------------------------------------------- //procedure Register; //begin // RegisterComponents('OTFE', [TOTFEFreeOTFEDLL]); //end; // ---------------------------------------------------------------------------- constructor TOTFEFreeOTFEDLL.Create(); begin inherited; fMountedHandles := TStringList.Create(); fCachedDiskGeometry:= TStringList.Create(); fExeDir := ExtractFilePath(Application.ExeName); end; // ---------------------------------------------------------------------------- destructor TOTFEFreeOTFEDLL.Destroy(); var i: integer; currDrvStr: string; currDrvChar: char; begin for i:=0 to (fCachedDiskGeometry.Count-1) do begin currDrvStr := fCachedDiskGeometry[i]; // unicode->ansi not a data loss because only ansistring stored if (length(currDrvStr) > 0) then // Sanity check begin currDrvChar := currDrvStr[1]; DeleteDiskGeometry(currDrvChar); end; end; fMountedHandles.Free(); fCachedDiskGeometry.Free(); inherited; end; // ---------------------------------------------------------------------------- // This dismount routine is based on the MS "media eject" routine for NT/2k/XP // at: // http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/Q165/7/21.asp&NoWebContent=1 function TOTFEFreeOTFEDLL.Dismount(driveLetter: char; emergency: boolean = FALSE): boolean; var volumeInfo: TOTFEFreeOTFEVolumeInfo; // unableToOpenDrive: boolean; begin CheckActive(); Result := TRUE; if (Result) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('getVolumeInfo'); {$ENDIF} Result := GetVolumeInfo(driveLetter, volumeInfo); // If we couldn't get the drive info, then we can't even do an // emergency dismount; we don't know which FreeOTFE device to dismount if not Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('getVolumeInfo NOT Result'); {$ENDIF} emergency := FALSE; end; end; if (Result or emergency) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('dismountdevice'); {$ENDIF} Result := DismountDiskDevice(driveLetter, emergency); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.Version(): cardinal; var majorVersion, minorVersion, revisionVersion, buildVersion: integer; begin Result := VERSION_ID_FAILURE; CheckActive(); // If we have the version ID cached, use the cached information if (fCachedVersionID <> VERSION_ID_NOT_CACHED) then begin Result := fCachedVersionID; end else begin if SDUGetVersionInfo( MainDLLFilename(), majorVersion, minorVersion, revisionVersion, buildVersion ) then begin Result := ( (majorVersion shl 24) + (minorVersion shl 16) + (revisionVersion) ); fCachedVersionID := Result; end; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.DrivesMounted(): string; var i: integer; begin // DLL version doesn't have concept of drive letters as in system drive // letters, but uses them to reference different mounted volumes Result := ''; for i:=0 to (fMountedHandles.count - 1) do begin Result := Result + fMountedHandles[i]; // unicode->ansi not a data loss because only ansistring stored end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.Connect(): boolean; begin Result := FALSE; if LoadLibraryMain(DriverAPI) then begin Result := TRUE; end else begin LastErrorCode := OTFE_ERR_DRIVER_FAILURE; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.Disconnect(): boolean; begin FreeLibraryMain(DriverAPI); Result:= TRUE; end; // ---------------------------------------------------------------------------- // Use the FreeOTFE device driver to mount the specified volume, and either: // *) Read in and decrypt specified data, returning the decrypted version // *) Encrypt specified data, and write to volume // readNotWrite - Set to TRUE to read, FALSE to write function TOTFEFreeOTFEDLL.ReadWritePlaintextToVolume( readNotWrite: boolean; volFilename: string; volumeKey: TSDUBytes; sectorIVGenMethod: TFreeOTFESectorIVGenMethod; IVHashDriver: Ansistring; IVHashGUID: TGUID; IVCypherDriver: Ansistring; IVCypherGUID: TGUID; mainCypherDriver: Ansistring; mainCypherGUID: TGUID; VolumeFlags: integer; mountMountAs: TFreeOTFEMountAs; dataOffset: int64; // Offset from within mounted volume from where to read/write data dataLength: integer; // Length of data to read/write. In bytes var data: TSDUBytes; // Data to read/write offset: int64 = 0; // Offset within volume where encrypted data starts size: int64 = 0; // Size of volume storageMediaType: TFreeOTFEStorageMediaType = mtFixedMedia ): boolean; var dummyMetadata: TOTFEFreeOTFEVolumeMetaData; tempMountDriveLetter: char; stm: TSDUMemoryStream; // emptyIV : TSDUBytes; // volumeKeyStr: AnsiString; begin LastErrorCode := OTFE_ERR_SUCCESS; CheckActive(); PopulateVolumeMetadataStruct( FALSE, // Linux volume PKCS11_NO_SLOT_ID, // PKCS11 SlotID dummyMetadata ); // Attempt to mount the device tempMountDriveLetter:= GetNextDriveLetter(); // SDUInitAndZeroBuffer(0,emptyIV); Result := MountDiskDevice( tempMountDriveLetter, volFilename, volumeKey, sectorIVGenMethod, nil, FALSE, IVHashDriver, IVHashGUID, IVCypherDriver, // IV cypher IVCypherGUID, // IV cypher mainCypherDriver, // Main cypher mainCypherGUID, // Main cypher VolumeFlags, dummyMetadata, offset, size, FreeOTFEMountAsStorageMediaType[mountMountAs] ); if Result then begin try stm := TSDUMemoryStream.Create(); try // Read decrypted data from mounted device if (readNotWrite) then begin Result := ReadData_Bytes( tempMountDriveLetter, dataOffset, dataLength, stm ); if Result then begin stm.Position := 0; data := SDUStringToSDUBytes(stm.ReadString(dataLength, 0)); end; end else begin stm.Position := 0; stm.WriteString(SDUBytesToString(data), dataLength, 0); Result := WriteData_Bytes( tempMountDriveLetter, dataOffset, dataLength, stm ); end; finally stm.Free(); end; finally // Unmount DismountDiskDevice(tempMountDriveLetter, TRUE); end; end; // if (Result) then end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.LoadLibraryMain(var api: TMainAPI): boolean; var libFilename: string; begin Result := FALSE; libFilename := MainDLLFilename(); api.hDLL := LoadLibrary(PChar(libFilename)); if (api.hDLL <> 0) then begin Result := TRUE; api.LibFilename := libFilename; @api.DSK_Init := GetProcAddress( api.hDLL, DLLEXPORT_MAIN_DSK_Init ); if (@api.DSK_Init = nil) then begin Result := FALSE; end; @api.DSK_Deinit := GetProcAddress( api.hDLL, DLLEXPORT_MAIN_DSK_Deinit ); if (@api.DSK_Deinit = nil) then begin Result := FALSE; end; @api.DSK_Open := GetProcAddress( api.hDLL, DLLEXPORT_MAIN_DSK_Open ); if (@api.DSK_Open = nil) then begin Result := FALSE; end; @api.DSK_Close := GetProcAddress( api.hDLL, DLLEXPORT_MAIN_DSK_Close ); if (@api.DSK_Close = nil) then begin Result := FALSE; end; @api.DSK_IOControl := GetProcAddress( api.hDLL, DLLEXPORT_MAIN_DSK_IOControl ); if (@api.DSK_IOControl = nil) then begin Result := FALSE; end; @api.DSK_Seek := GetProcAddress( api.hDLL, DLLEXPORT_MAIN_DSK_Seek ); if (@api.DSK_Seek = nil) then begin Result := FALSE; end; @api.DSK_Read := GetProcAddress( api.hDLL, DLLEXPORT_MAIN_DSK_Read ); if (@api.DSK_Read = nil) then begin Result := FALSE; end; @api.DSK_Write := GetProcAddress( api.hDLL, DLLEXPORT_MAIN_DSK_Write ); if (@api.DSK_Write = nil) then begin Result := FALSE; end; @api.DSK_PowerDown := GetProcAddress( api.hDLL, DLLEXPORT_MAIN_DSK_PowerDown ); if (@api.DSK_PowerDown = nil) then begin Result := FALSE; end; @api.DSK_PowerUp := GetProcAddress( api.hDLL, DLLEXPORT_MAIN_DSK_PowerUp ); if (@api.DSK_PowerUp = nil) then begin Result := FALSE; end; @api.MainDLLFnMACData := GetProcAddress( api.hDLL, DLLEXPORT_MAIN_MACDATA ); if (@api.MainDLLFnMACData = nil) then begin Result := FALSE; end; @api.MainDLLFnDeriveKey := GetProcAddress( api.hDLL, DLLEXPORT_MAIN_DERIVEKEY ); if (@api.MainDLLFnDeriveKey = nil) then begin Result := FALSE; end; if not(Result) then begin FreeLibrary(api.hDLL); end; end; end; procedure TOTFEFreeOTFEDLL.FreeLibraryMain(var api: TMainAPI); begin if (api.hDLL <> 0) then begin FreeLibrary(api.hDLL); api.hDLL := 0; api.LibFilename := ''; end; end; function TOTFEFreeOTFEDLL.LoadLibraryHash(const libFilename: string; var api: THashAPI): boolean; begin Result := FALSE; api.hDLL := LoadLibrary(PChar(libFilename)); if (api.hDLL <> 0) then begin Result := TRUE; api.LibFilename := libFilename; @api.HashDLLFnIdentifyDriver := GetProcAddress( api.hDLL, DLLEXPORT_HASH_IDENTIFYDRIVER ); if (@api.HashDLLFnIdentifyDriver = nil) then begin Result := FALSE; end; @api.HashDLLFnIdentifySupported := GetProcAddress( api.hDLL, DLLEXPORT_HASH_IDENTIFYSUPPORTED ); if (@api.HashDLLFnIdentifySupported = nil) then begin Result := FALSE; end; @api.HashDLLFnGetHashDetails := GetProcAddress( api.hDLL, DLLEXPORT_HASH_GETHASHDETAILS ); if (@api.HashDLLFnGetHashDetails = nil) then begin Result := FALSE; end; @api.HashDLLFnHash := GetProcAddress( api.hDLL, DLLEXPORT_HASH_HASH ); if (@api.HashDLLFnHash = nil) then begin Result := FALSE; end; if not(Result) then begin FreeLibrary(api.hDLL); end; end; end; function TOTFEFreeOTFEDLL.LoadLibraryCachedHash(const libFilename: string; var api: THashAPI): boolean; begin Result:= CachesGetHashAPI(libFilename, api); if not(Result) then begin Result := LoadLibraryHash(libFilename, api); if Result then begin CachesAddHashAPI(libFilename, api); end; end; end; procedure TOTFEFreeOTFEDLL.FreeLibraryHash(var api: THashAPI); begin if (api.hDLL <> 0) then begin FreeLibrary(api.hDLL); api.hDLL := 0; api.LibFilename := ''; end; end; function TOTFEFreeOTFEDLL.LoadLibraryCypher(const libFilename: string; var api: TCypherAPI): boolean; begin Result := FALSE; api.hDLL := LoadLibrary(PChar(libFilename)); if (api.hDLL <> 0) then begin Result := TRUE; api.LibFilename := libFilename; @api.CypherDLLFnIdentifyDriver := GetProcAddress( api.hDLL, DLLEXPORT_CYPHER_IDENTIFYDRIVER ); if (@api.CypherDLLFnIdentifyDriver = nil) then begin Result := FALSE; end; @api.CypherDLLFnIdentifySupported_v1 := GetProcAddress( api.hDLL, DLLEXPORT_CYPHER_IDENTIFYSUPPORTED_v1 ); if (@api.CypherDLLFnIdentifySupported_v1 = nil) then begin Result := FALSE; end; @api.CypherDLLFnIdentifySupported_v3 := GetProcAddress( api.hDLL, DLLEXPORT_CYPHER_IDENTIFYSUPPORTED_v3 ); if (@api.CypherDLLFnIdentifySupported_v3 = nil) then begin Result := FALSE; end; @api.CypherDLLFnGetCypherDetails_v1 := GetProcAddress( api.hDLL, DLLEXPORT_CYPHER_GETCYPHERDETAILS_v1 ); if (@api.CypherDLLFnGetCypherDetails_v1 = nil) then begin Result := FALSE; end; @api.CypherDLLFnGetCypherDetails_v3 := GetProcAddress( api.hDLL, DLLEXPORT_CYPHER_GETCYPHERDETAILS_v3 ); if (@api.CypherDLLFnGetCypherDetails_v3 = nil) then begin Result := FALSE; end; @api.CypherDLLFnEncrypt := GetProcAddress( api.hDLL, DLLEXPORT_CYPHER_ENCRYPT ); if (@api.CypherDLLFnEncrypt = nil) then begin Result := FALSE; end; @api.CypherDLLFnEncryptSector := GetProcAddress( api.hDLL, DLLEXPORT_CYPHER_ENCRYPTSECTOR ); if (@api.CypherDLLFnEncryptSector = nil) then begin Result := FALSE; end; @api.CypherDLLFnEncryptWithASCII := GetProcAddress( api.hDLL, DLLEXPORT_CYPHER_ENCRYPTWITHASCII ); if (@api.CypherDLLFnEncryptWithASCII = nil) then begin Result := FALSE; end; @api.CypherDLLFnEncryptSectorWithASCII := GetProcAddress( api.hDLL, DLLEXPORT_CYPHER_ENCRYPTSECTORWITHASCII ); if (@api.CypherDLLFnEncryptSectorWithASCII = nil) then begin Result := FALSE; end; @api.CypherDLLFnDecrypt := GetProcAddress( api.hDLL, DLLEXPORT_CYPHER_DECRYPT ); if (@api.CypherDLLFnDecrypt = nil) then begin Result := FALSE; end; @api.CypherDLLFnDecryptSector := GetProcAddress( api.hDLL, DLLEXPORT_CYPHER_DECRYPTSECTOR ); if (@api.CypherDLLFnDecryptSector = nil) then begin Result := FALSE; end; @api.CypherDLLFnDecryptWithASCII := GetProcAddress( api.hDLL, DLLEXPORT_CYPHER_DECRYPTWITHASCII ); if (@api.CypherDLLFnDecryptWithASCII = nil) then begin Result := FALSE; end; @api.CypherDLLFnDecryptSectorWithASCII := GetProcAddress( api.hDLL, DLLEXPORT_CYPHER_DECRYPTSECTORWITHASCII ); if (@api.CypherDLLFnDecryptSectorWithASCII = nil) then begin Result := FALSE; end; if not(Result) then begin FreeLibrary(api.hDLL); end; end; end; function TOTFEFreeOTFEDLL.LoadLibraryCachedCypher(const libFilename: string; var api: TCypherAPI): boolean; begin Result:= CachesGetCypherAPI(libFilename, api); if not(Result) then begin Result := LoadLibraryCypher(libFilename, api); if Result then begin CachesAddCypherAPI(libFilename, api); end; end; end; procedure TOTFEFreeOTFEDLL.FreeLibraryCypher(var api: TCypherAPI); begin if (api.hDLL <> 0) then begin FreeLibrary(api.hDLL); api.hDLL := 0; api.LibFilename := ''; end; end; function TOTFEFreeOTFEDLL.GetDLLDir(): string; const { Subdir which should be searched for drivers path is <exepath>/DLLs/<config>/<Platform> eg .\bin\PC\DLLs\Debug\Win32 } CONFIG = // use debug DLLS or not, debug ones are much slower {$IFDEF DEBUG_DLLS} 'Debug' {$ELSE} 'Release' {$ENDIF} ; begin //the dll version required is based on if the *app* is 32 or 64 bit - not the OS result := IncludeTrailingPathDelimiter(fExeDir) +'DLLs\'+ CONFIG+'\'+ Ifthen( SDUApp64bit(), 'x64', 'Win32'); end; procedure TOTFEFreeOTFEDLL.GetAllDriversUnderExeDir(driverFilenames: TStringList); var fileIterator: TSDUFileIterator; filename: string; begin // Compile a list of drivers in the ExeDir fileIterator:= TSDUFileIterator.Create(nil); try fileIterator.Directory := GetDLLDir(); fileIterator.FileMask := '*.dll'; fileIterator.RecurseSubDirs := FALSE; fileIterator.OmitStartDirPrefix := FALSE; fileIterator.IncludeDirNames := FALSE; fileIterator.Reset(); filename := fileIterator.Next(); while (filename<>'') do begin driverFilenames.Add(filename); filename := fileIterator.Next(); end; finally fileIterator.Free(); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.GetHashDrivers(var hashDrivers: TFreeOTFEHashDriverArray): boolean; var dllNames: TStringList; j: integer; begin Result := TRUE; SetLength(hashDrivers, 0); dllNames:= TStringList.Create(); try GetAllDriversUnderExeDir(dllNames); for j:=0 to (dllNames.count-1) do begin if pos(DLL_HASH_FILE_PREFIX, ExtractFilename(dllNames[j]))>0 then begin // Get the details for the device SetLength(hashDrivers, (Length(hashDrivers)+1)); Result := GetHashDriverHashes(dllNames[j], hashDrivers[high(hashDrivers)]); // unicode->ansi not a data loss because only ansistring stored // Note: This "break" condition differs between the DLL and kernel // driver versions if not(Result) then begin break; end; end; end; finally dllNames.Free(); end; end; function TOTFEFreeOTFEDLL.GetCypherDrivers(var cypherDrivers: TFreeOTFECypherDriverArray): boolean; var dllNames: TStringList; j: integer; begin Result := TRUE; SetLength(cypherDrivers, 0); dllNames:= TStringList.Create(); try GetAllDriversUnderExeDir(dllNames); for j:=0 to (dllNames.count-1) do begin if pos(DLL_CYPHER_FILE_PREFIX, ExtractFilename(dllNames[j]))>0 then begin // Get the details for the device SetLength(cypherDrivers, (Length(cypherDrivers)+1)); Result := GetCypherDriverCyphers(dllNames[j], cypherDrivers[high(cypherDrivers)]); // unicode->ansi not a data loss because only ansistring stored // Note: This "break" condition differs between the DLL and kernel // driver versions if not(Result) then begin break; end; end; end; finally dllNames.Free(); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.GetHashDriverHashes(hashDriver: ansistring; var hashDriverDetails: TFreeOTFEHashDriver): boolean; var DIOCBuffer: TDIOC_HASH_IDENTIFYDRIVER; ptrBuffer: Pointer; ptrBufferOffset: Pointer; {$IFDEF FREEOTFE_DEBUG} DIOCBufferHashes: PDIOC_HASH_IDENTIFYSUPPORTED; {$ENDIF} bufferSize: cardinal; hashDetails: PHASH; i: integer; arrIdx: integer; hashAPI: THashAPI; begin Result := FALSE; if CachesGetHashDriver(hashDriver, hashDriverDetails) then begin Result := TRUE; end else begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Connecting to: '+hashDriver); {$ENDIF} if not(LoadLibraryCachedHash(hashDriver, hashAPI)) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Couldn''t connect to: '+hashDriver); {$ENDIF} end else begin if (hashAPI.HashDLLFnIdentifyDriver(@DIOCBuffer) = ERROR_SUCCESS) then begin hashDriverDetails.DriverGUID := DIOCBuffer.DriverGUID; hashDriverDetails.LibFNOrDevKnlMdeName := hashDriver; // hashDriverDetails.DeviceName := GetDeviceName(hashKernelModeDeviceName); // hashDriverDetails.DeviceUserModeName := DeviceUserModeName; hashDriverDetails.Title := Copy(DIOCBuffer.Title, 1, StrLen(DIOCBuffer.Title)); hashDriverDetails.VersionID := DIOCBuffer.VersionID; hashDriverDetails.HashCount := DIOCBuffer.HashCount; bufferSize := sizeof(TDIOC_HASH_IDENTIFYSUPPORTED) - sizeof(hashDetails^) + (sizeof(hashDetails^) * hashDriverDetails.HashCount); // Round up to next "DIOC boundry". Although this always results in an // oversized buffer, it's guaranteed to be big enough. bufferSize := bufferSize + (DIOC_BOUNDRY - (bufferSize mod DIOC_BOUNDRY)); ptrBuffer := allocmem(bufferSize); SetLength(hashDriverDetails.Hashes, hashDriverDetails.HashCount); if (hashAPI.HashDLLFnIdentifySupported(bufferSize, ptrBuffer) = ERROR_SUCCESS) then begin {$IFDEF FREEOTFE_DEBUG} DIOCBufferHashes := (PDIOC_HASH_IDENTIFYSUPPORTED(ptrBuffer)); DebugMsg('hash details count: '+inttostr(DIOCBufferHashes.BufCount)); {$ENDIF} ptrBufferOffset := Pointer(PAnsiChar(ptrBuffer) + sizeof(TDIOC_HASH_IDENTIFYSUPPORTED) - sizeof(hashDetails^)); arrIdx := low(hashDriverDetails.Hashes); for i:=1 to hashDriverDetails.HashCount do begin hashDetails := (PHASH(ptrBufferOffset)); hashDriverDetails.Hashes[arrIdx].HashGUID := hashDetails.HashGUID; hashDriverDetails.Hashes[arrIdx].Title := Copy(hashDetails.Title, 1, StrLen(hashDetails.Title)); hashDriverDetails.Hashes[arrIdx].VersionID := hashDetails.VersionID; hashDriverDetails.Hashes[arrIdx].Length := hashDetails.Length; hashDriverDetails.Hashes[arrIdx].BlockSize := hashDetails.BlockSize; // Setup for the next one... ptrBufferOffset := Pointer(PAnsiChar(ptrBufferOffset) + sizeof(hashDetails^)); inc(arrIdx); end; // Cache the information retrieved CachesAddHashDriver(hashDriver, hashDriverDetails); Result := TRUE; end else begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('gethashdrivers DIOC 2 FAIL'); {$ENDIF} end; FreeMem(ptrBuffer); end; end; end; // if CachesGetHashDriver(hashDriver, hashDriverDetails) then end; // ---------------------------------------------------------------------------- // Get cypher details - using FreeOTFE v3 and later API // Don't call this function directly! Call GetCypherDriverCyphers(...) instead! function TOTFEFreeOTFEDLL._GetCypherDriverCyphers_v1(cypherDriver: ansistring; var cypherDriverDetails: TFreeOTFECypherDriver): boolean; var DIOCBuffer: TDIOC_CYPHER_IDENTIFYDRIVER; ptrBuffer: Pointer; ptrBufferOffset: Pointer; {$IFDEF FREEOTFE_DEBUG} DIOCBufferCyphers: PDIOC_CYPHER_IDENTIFYSUPPORTED_v1; {$ENDIF} bufferSize: cardinal; cypherDetails: PCYPHER_v1; i: integer; currCypherMode: TFreeOTFECypherMode; arrIdx: integer; cypherAPI: TCypherAPI; begin Result := FALSE; if CachesGetCypherDriver(cypherDriver, cypherDriverDetails) then begin Result := TRUE; end else begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Connecting to: '+cypherDriver); {$ENDIF} if not(LoadLibraryCachedCypher(cypherDriver, cypherAPI)) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Couldn''t connect to: '+cypherDriver); {$ENDIF} end else begin if (cypherAPI.CypherDLLFnIdentifyDriver(@DIOCBuffer) = ERROR_SUCCESS) then begin cypherDriverDetails.DriverGUID := DIOCBuffer.DriverGUID; cypherDriverDetails.LibFNOrDevKnlMdeName := cypherDriver; // cypherDriverDetails.DeviceName := GetDeviceName(cypherKernelModeDeviceName); // cypherDriverDetails.DeviceUserModeName := DeviceUserModeName; cypherDriverDetails.Title := Copy(DIOCBuffer.Title, 1, StrLen(DIOCBuffer.Title)); cypherDriverDetails.VersionID := DIOCBuffer.VersionID; cypherDriverDetails.CypherCount := DIOCBuffer.CypherCount; bufferSize := sizeof(TDIOC_CYPHER_IDENTIFYSUPPORTED_v1) - sizeof(cypherDetails^) + (sizeof(cypherDetails^) * cypherDriverDetails.CypherCount); // Round up to next "DIOC boundry". Although this always results in an // oversized buffer, it's guaranteed to be big enough. bufferSize := bufferSize + (DIOC_BOUNDRY - (bufferSize mod DIOC_BOUNDRY)); ptrBuffer := allocmem(bufferSize); SetLength(cypherDriverDetails.Cyphers, cypherDriverDetails.CypherCount); if (cypherAPI.CypherDLLFnIdentifySupported_v1(bufferSize, ptrBuffer) = ERROR_SUCCESS) then begin {$IFDEF FREEOTFE_DEBUG} DIOCBufferCyphers := (PDIOC_CYPHER_IDENTIFYSUPPORTED_v1(ptrBuffer)); DebugMsg('cypher details count: '+inttostr(DIOCBufferCyphers.BufCount)); {$ENDIF} ptrBufferOffset := Pointer( PAnsiChar(ptrBuffer) + sizeof(TDIOC_CYPHER_IDENTIFYSUPPORTED_v1) - sizeof(cypherDetails^) ); arrIdx := low(cypherDriverDetails.Cyphers); for i:=1 to cypherDriverDetails.CypherCount do begin cypherDetails := (PCYPHER_v1(ptrBufferOffset)); cypherDriverDetails.Cyphers[arrIdx].CypherGUID := cypherDetails.CypherGUID; cypherDriverDetails.Cyphers[arrIdx].Title := Copy(cypherDetails.Title, 1, StrLen(cypherDetails.Title)); // Failsafe to "unknown" cypherDriverDetails.Cyphers[arrIdx].Mode := focmUnknown; for currCypherMode:=low(FreeOTFECypherModeID) to high(FreeOTFECypherModeID) do begin if (cypherDetails.Mode = FreeOTFECypherModeID[currCypherMode]) then begin cypherDriverDetails.Cyphers[arrIdx].Mode := currCypherMode; end; end; cypherDriverDetails.Cyphers[arrIdx].KeySizeUnderlying := cypherDetails.KeySizeUnderlying; cypherDriverDetails.Cyphers[arrIdx].BlockSize := cypherDetails.BlockSize; cypherDriverDetails.Cyphers[arrIdx].VersionID := cypherDetails.VersionID; cypherDriverDetails.Cyphers[arrIdx].KeySizeRequired := cypherDetails.KeySizeUnderlying; // Setup for the next one... ptrBufferOffset := Pointer( PAnsiChar(ptrBufferOffset) + sizeof(cypherDetails^) ); inc(arrIdx); end; // Cache the information retrieved CachesAddCypherDriver(cypherDriver, cypherDriverDetails); Result := TRUE; end else begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('getcypherdrivers DIOC 2 FAIL'); {$ENDIF} end; FreeMem(ptrBuffer); end; end; end; // if CachesGetCypherDriver(driver, cypherDriverDetails) then {$IFDEF FREEOTFE_DEBUG} DebugMsg('Exiting function...'); {$ENDIF} end; // ---------------------------------------------------------------------------- // Get cypher details - using FreeOTFE v3 and later API // Don't call this function directly! Call GetCypherDriverCyphers(...) instead! function TOTFEFreeOTFEDLL._GetCypherDriverCyphers_v3(cypherDriver: ansistring; var cypherDriverDetails: TFreeOTFECypherDriver): boolean; var DIOCBuffer: TDIOC_CYPHER_IDENTIFYDRIVER; ptrBuffer: Pointer; ptrBufferOffset: Pointer; {$IFDEF FREEOTFE_DEBUG} DIOCBufferCyphers: PDIOC_CYPHER_IDENTIFYSUPPORTED_v3; {$ENDIF} bufferSize: cardinal; cypherDetails: PCYPHER_v3; i: integer; currCypherMode: TFreeOTFECypherMode; arrIdx: integer; cypherAPI: TCypherAPI; begin Result := FALSE; if CachesGetCypherDriver(cypherDriver, cypherDriverDetails) then begin Result := TRUE; end else begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Connecting to: '+cypherDriver); {$ENDIF} if not(LoadLibraryCachedCypher(cypherDriver, cypherAPI)) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Couldn''t connect to: '+cypherDriver); {$ENDIF} end else begin if (cypherAPI.CypherDLLFnIdentifyDriver(@DIOCBuffer) = ERROR_SUCCESS) then begin cypherDriverDetails.DriverGUID := DIOCBuffer.DriverGUID; cypherDriverDetails.LibFNOrDevKnlMdeName := cypherDriver; // cypherDriverDetails.DeviceName := GetDeviceName(cypherKernelModeDeviceName); // cypherDriverDetails.DeviceUserModeName := DeviceUserModeName; cypherDriverDetails.Title := Copy(DIOCBuffer.Title, 1, StrLen(DIOCBuffer.Title)); cypherDriverDetails.VersionID := DIOCBuffer.VersionID; cypherDriverDetails.CypherCount := DIOCBuffer.CypherCount; bufferSize := sizeof(TDIOC_CYPHER_IDENTIFYSUPPORTED_v3) - sizeof(cypherDetails^) + (sizeof(cypherDetails^) * cypherDriverDetails.CypherCount); // Round up to next "DIOC boundry". Although this always results in an // oversized buffer, it's guaranteed to be big enough. bufferSize := bufferSize + (DIOC_BOUNDRY - (bufferSize mod DIOC_BOUNDRY)); ptrBuffer := allocmem(bufferSize); SetLength(cypherDriverDetails.Cyphers, cypherDriverDetails.CypherCount); if (cypherAPI.CypherDLLFnIdentifySupported_v3(bufferSize, ptrBuffer) = ERROR_SUCCESS) then begin {$IFDEF FREEOTFE_DEBUG} DIOCBufferCyphers := (PDIOC_CYPHER_IDENTIFYSUPPORTED_v3(ptrBuffer)); DebugMsg('cypher details count: '+inttostr(DIOCBufferCyphers.BufCount)); {$ENDIF} ptrBufferOffset := Pointer( PAnsiChar(ptrBuffer) + sizeof(TDIOC_CYPHER_IDENTIFYSUPPORTED_v3) - sizeof(cypherDetails^) ); arrIdx := low(cypherDriverDetails.Cyphers); for i:=1 to cypherDriverDetails.CypherCount do begin cypherDetails := (PCYPHER_v3(ptrBufferOffset)); cypherDriverDetails.Cyphers[arrIdx].CypherGUID := cypherDetails.CypherGUID; cypherDriverDetails.Cyphers[arrIdx].Title := Copy(cypherDetails.Title, 1, StrLen(cypherDetails.Title)); // Failsafe to "unknown" cypherDriverDetails.Cyphers[arrIdx].Mode := focmUnknown; for currCypherMode:=low(FreeOTFECypherModeID) to high(FreeOTFECypherModeID) do begin if (cypherDetails.Mode = FreeOTFECypherModeID[currCypherMode]) then begin cypherDriverDetails.Cyphers[arrIdx].Mode := currCypherMode; end; end; cypherDriverDetails.Cyphers[arrIdx].KeySizeRequired := cypherDetails.KeySizeRequired; cypherDriverDetails.Cyphers[arrIdx].KeySizeUnderlying := cypherDetails.KeySizeUnderlying; cypherDriverDetails.Cyphers[arrIdx].BlockSize := cypherDetails.BlockSize; cypherDriverDetails.Cyphers[arrIdx].VersionID := cypherDetails.VersionID; // Setup for the next one... ptrBufferOffset := Pointer( PAnsiChar(ptrBufferOffset) + sizeof(cypherDetails^) ); inc(arrIdx); end; // Cache the information retrieved CachesAddCypherDriver(cypherDriver, cypherDriverDetails); Result := TRUE; end else begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('getcypherdrivers DIOC 2 FAIL'); {$ENDIF} end; FreeMem(ptrBuffer); end; end; end; // if CachesGetCypherDriver(driver, cypherDriverDetails) then {$IFDEF FREEOTFE_DEBUG} DebugMsg('Exiting function...'); {$ENDIF} end; // ---------------------------------------------------------------------------- // Hash the specified data with the supplied hash device/hash GUID function TOTFEFreeOTFEDLL.HashData( hashDriver: Ansistring; hashGUID: TGUID; const data: TSDUBytes; out hashOut: TSDUBytes ): boolean; var ptrDIOCBufferIn: PDIOC_HASH_DATA_IN; bufferSizeIn: DWORD; ptrDIOCBufferOut: PDIOC_HASH_DATA_OUT; bufferSizeOut: DWORD; hashDetails: TFreeOTFEHash; hashByteCount: integer; expectedHashSizeBits: integer; // In *bits* hashAPI: THashAPI; bitsReturned: DWORD; begin LastErrorCode := OTFE_ERR_SUCCESS; Result := FALSE; CheckActive(); if GetSpecificHashDetails(hashDriver, hashGUID, hashDetails) then begin if not(LoadLibraryCachedHash(hashDriver, hashAPI)) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('couldn''t connect to: '+hashDriver); {$ENDIF} LastErrorCode := OTFE_ERR_DRIVER_FAILURE; end else begin bufferSizeIn := sizeof(ptrDIOCBufferIn^) - sizeof(byte) + Length(Data); // Round up to next "DIOC boundry". Although this always results in an // oversized buffer, it's guaranteed to be big enough. bufferSizeIn := bufferSizeIn + (DIOC_BOUNDRY - (bufferSizeIn mod DIOC_BOUNDRY)); ptrDIOCBufferIn := allocmem(bufferSizeIn); try // Just make sure its big enough expectedHashSizeBits := hashDetails.Length; if (hashDetails.Length = -1) then begin expectedHashSizeBits := (Length(Data) * 8); end; bufferSizeOut := sizeof(ptrDIOCBufferOut^) - sizeof(byte) + (expectedHashSizeBits div 8); ptrDIOCBufferOut := allocmem(bufferSizeOut); try ptrDIOCBufferIn.HashGUID := hashGUID; ptrDIOCBufferIn.DataLength := Length(Data) * 8; StrMove(@ptrDIOCBufferIn.Data, PAnsiChar(Data), Length(Data)); bitsReturned := expectedHashSizeBits; if (hashAPI.HashDLLFnHash( @hashGUID, ptrDIOCBufferIn.DataLength, PByte(@(ptrDIOCBufferIn.Data)), @bitsReturned, PByte(@(ptrDIOCBufferOut.Hash)) ) = ERROR_SUCCESS) then begin hashByteCount := (bitsReturned div 8); {$IFDEF FREEOTFE_DEBUG} DebugMsg('hashByteCount: '+inttostr(hashByteCount)); {$ENDIF} // Set hashOut so that it has enough characters which can be // overwritten with StrMove SDUInitAndZeroBuffer(hashByteCount, hashOut ); // hashOut := StringOfChar(Ansichar(#0), hashByteCount); StrMove(PAnsiChar(hashOut), @ptrDIOCBufferOut.Hash, hashByteCount); Result := TRUE; end else begin LastErrorCode := OTFE_ERR_HASH_FAILURE; {$IFDEF FREEOTFE_DEBUG} DebugMsg('hash DIOC 2 FAIL'); {$ENDIF} end; finally FillChar(ptrDIOCBufferOut^, bufferSizeOut, 0); FreeMem(ptrDIOCBufferOut); end; finally FillChar(ptrDIOCBufferIn^, bufferSizeIn, 0); FreeMem(ptrDIOCBufferIn); end; end; end else begin LastErrorCode := OTFE_ERR_DRIVER_FAILURE; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Unable to GetSpecificHashDetails'); {$ENDIF} end; // ELSE PART - if GetSpecificHashDetails(hashKernelModeDeviceName, hashGUID, hashDetails) then end; // ---------------------------------------------------------------------------- // Generate MAC of data using hash driver/encryption driver identified // Note: "tBits" is in *bits* not *bytes* // tBits - Set the the number of bits to return; set to -ve value for no // truncation/padding // If tBits is larger than the number of bits the MAC would normally // be, then the MAC will be right-padded with NULLs // If tBits is set to a -ve number, then this function will return // an MAC of variable length function TOTFEFreeOTFEDLL.MACData( macAlgorithm: TFreeOTFEMACAlgorithm; HashDriver: Ansistring; HashGUID: TGUID; CypherDriver: Ansistring; CypherGUID: TGUID; var key: PasswordString; var data: Ansistring; var MACOut: Ansistring; tBits: integer = -1 ): boolean; var ptrDIOCBufferIn: PDIOC_GENERATE_MAC_IN_PC_DLL; bufferSizeIn: DWORD; ptrDIOCBufferOut: PDIOC_GENERATE_MAC_OUT; bufferSizeOut: DWORD; outputByteCount: integer; tmpSizeBytes: integer; minBufferSizeOut: integer; begin LastErrorCode := OTFE_ERR_SUCCESS; Result := FALSE; CheckActive(); bufferSizeIn := sizeof(ptrDIOCBufferIn^) - sizeof(ptrDIOCBufferIn^.Key) + Length(key) - sizeof(ptrDIOCBufferIn^.Data) + Length(data); // Round up to next "DIOC boundry". Although this always results in an // oversized buffer, it's guaranteed to be big enough. bufferSizeIn := bufferSizeIn + (DIOC_BOUNDRY - (bufferSizeIn mod DIOC_BOUNDRY)); ptrDIOCBufferIn := allocmem(bufferSizeIn); try // We use the maximum buffer possible, as the full DK length depends on // the algorithm, hash, etc tmpSizeBytes := (max(MAX_MAC_LENGTH, tBits) div 8); // Convert to bytes minBufferSizeOut := sizeof(ptrDIOCBufferOut^) - sizeof(ptrDIOCBufferOut^.MAC); bufferSizeOut := minBufferSizeOut + tmpSizeBytes; // Round up to next "DIOC boundry". Although this always results in an // oversized buffer, it's guaranteed to be big enough. bufferSizeOut := bufferSizeOut + (DIOC_BOUNDRY - (bufferSizeOut mod DIOC_BOUNDRY)); ptrDIOCBufferOut := allocmem(bufferSizeOut); try ptrDIOCBufferIn.MACAlgorithm := FreeOTFEMACID[macAlgorithm]; StringToWideChar(HashDriver, ptrDIOCBufferIn.HashDeviceName, (length(ptrDIOCBufferIn.HashDeviceName)-1)); ptrDIOCBufferIn.HashGUID := HashGUID; StringToWideChar(CypherDriver, ptrDIOCBufferIn.CypherDeviceName, (length(ptrDIOCBufferIn.CypherDeviceName)-1)); ptrDIOCBufferIn.CypherGUID := CypherGUID; ptrDIOCBufferIn.LengthWanted := tBits; ptrDIOCBufferIn.KeyLength := Length(key) * 8; ptrDIOCBufferIn.DataLength := Length(data) * 8; // This may seem a little weird, but we do this because the data is // immediatly after the key StrMove(@ptrDIOCBufferIn.Key, PAnsiChar(key), Length(key)); StrMove(((PAnsiChar(@ptrDIOCBufferIn.Key))+length(key)), PAnsiChar(data), Length(data)); if (DriverAPI.MainDLLFnMACData( bufferSizeIn, ptrDIOCBufferIn, bufferSizeOut, ptrDIOCBufferOut ) = ERROR_SUCCESS) then begin outputByteCount := (ptrDIOCBufferOut.MACLength div 8); {$IFDEF FREEOTFE_DEBUG} DebugMsg('outputByteCount: '+inttostr(outputByteCount)); {$ENDIF} // Set MACOut so that it has enough characters which can be // overwritten with StrMove MACOut := StringOfChar(Ansichar(#0), outputByteCount); StrMove(PAnsiChar(MACOut), @ptrDIOCBufferOut.MAC, outputByteCount); Result := TRUE; end else begin LastErrorCode := OTFE_ERR_MAC_FAILURE; {$IFDEF FREEOTFE_DEBUG} DebugMsg('MAC DIOC 2 FAIL'); {$ENDIF} end; finally FillChar(ptrDIOCBufferOut^, bufferSizeOut, 0); FreeMem(ptrDIOCBufferOut); end; finally FillChar(ptrDIOCBufferIn^, bufferSizeIn, 0); FreeMem(ptrDIOCBufferIn); end; end; // ---------------------------------------------------------------------------- // dkLenBits - This must *always* be >= 0 function TOTFEFreeOTFEDLL.DeriveKey( kdfAlgorithm: TFreeOTFEKDFAlgorithm; HashDriver: Ansistring; HashGUID: TGUID; CypherDriver: Ansistring; CypherGUID: TGUID; Password: TSDUBytes; Salt: array of byte; Iterations: integer; dkLenBits: integer; // In *bits* out DK: TSDUBytes ): boolean; var ptrDIOCBufferIn: PDIOC_DERIVE_KEY_IN_PC_DLL; bufferSizeIn: DWORD; ptrDIOCBufferOut: PDIOC_DERIVE_KEY_OUT; bufferSizeOut: DWORD; outputByteCount: integer; tmpSizeBytes: integer; minBufferSizeOut: integer; begin LastErrorCode := OTFE_ERR_SUCCESS; Result := FALSE; CheckActive(); bufferSizeIn := sizeof(ptrDIOCBufferIn^) - sizeof(ptrDIOCBufferIn^.Password) + Length(Password) - sizeof(ptrDIOCBufferIn^.Salt) + Length(Salt); // Round up to next "DIOC boundry". Although this always results in an // oversized buffer, it's guaranteed to be big enough. bufferSizeIn := bufferSizeIn + (DIOC_BOUNDRY - (bufferSizeIn mod DIOC_BOUNDRY)); ptrDIOCBufferIn := allocmem(bufferSizeIn); try // We use the maximum buffer possible, as the full MAC length depends on // the MAC, hash, etc tmpSizeBytes := (max(MAX_DERIVED_KEY_LENGTH, dkLenBits) div 8); // Convert to bytes minBufferSizeOut := sizeof(ptrDIOCBufferOut^) - sizeof(ptrDIOCBufferOut^.DerivedKey); bufferSizeOut := minBufferSizeOut + tmpSizeBytes; // Round up to next "DIOC boundry". Although this always results in an // oversized buffer, it's guaranteed to be big enough. bufferSizeOut := bufferSizeOut + (DIOC_BOUNDRY - (bufferSizeOut mod DIOC_BOUNDRY)); ptrDIOCBufferOut := allocmem(bufferSizeOut); try ptrDIOCBufferIn.KDFAlgorithm := FreeOTFEKDFID[kdfAlgorithm]; StringToWideChar(HashDriver, ptrDIOCBufferIn.HashDeviceName, (length(ptrDIOCBufferIn.HashDeviceName)-1)); ptrDIOCBufferIn.HashGUID := HashGUID; StringToWideChar(CypherDriver, ptrDIOCBufferIn.CypherDeviceName, (length(ptrDIOCBufferIn.CypherDeviceName)-1)); ptrDIOCBufferIn.CypherGUID := CypherGUID; ptrDIOCBufferIn.Iterations := Iterations; ptrDIOCBufferIn.LengthWanted := dkLenBits; ptrDIOCBufferIn.PasswordLength := (Length(Password) * 8); ptrDIOCBufferIn.SaltLength := (Length(Salt) * 8); // This may seem a little weird, but we do this because the salt is // immediatly after the password StrMove(@ptrDIOCBufferIn.Password, PAnsiChar(Password), Length(Password)); StrMove(((PAnsiChar(@ptrDIOCBufferIn.Password))+length(Password)), PAnsiChar(@Salt[0]), Length(Salt)); if (DriverAPI.MainDLLFnDeriveKey( bufferSizeIn, ptrDIOCBufferIn, bufferSizeOut, ptrDIOCBufferOut ) = ERROR_SUCCESS) then begin outputByteCount := (ptrDIOCBufferOut.DerivedKeyLength div 8); {$IFDEF FREEOTFE_DEBUG} DebugMsg('outputByteCount: '+inttostr(outputByteCount)); {$ENDIF} // Set DK so that it has enough characters which can be // overwritten with StrMove SDUInitAndZeroBuffer(outputByteCount,DK); // DK := StringOfChar(AnsiChar(#0), outputByteCount); // SDUCopyArrays(DK,ptrDIOCBufferOut.DerivedKey,); StrMove(PAnsiChar(DK), @ptrDIOCBufferOut.DerivedKey, outputByteCount); Result := TRUE; end else begin LastErrorCode := OTFE_ERR_KDF_FAILURE; {$IFDEF FREEOTFE_DEBUG} DebugMsg('MAC DIOC 2 FAIL'); {$ENDIF} end; finally FillChar(ptrDIOCBufferOut^, bufferSizeOut, 0); FreeMem(ptrDIOCBufferOut); end; finally FillChar(ptrDIOCBufferIn^, bufferSizeIn, 0); FreeMem(ptrDIOCBufferIn); end; end; // ---------------------------------------------------------------------------- // encryptFlag - set to TRUE to encrypt, FALSE to decrypt function TOTFEFreeOTFEDLL._EncryptDecryptData( encryptFlag: boolean; cypherDriver: ansistring; cypherGUID: TGUID; var key: TSDUBytes; var IV: Ansistring; var inData: Ansistring; var outData: Ansistring ): boolean; var ptrDIOCBufferIn: PDIOC_CYPHER_DATA_IN; bufferSizeIn: DWORD; ptrDIOCBufferOut: PDIOC_CYPHER_DATA_OUT; bufferSizeOut: DWORD; cypherDetails: TFreeOTFECypher_v3; cypherAPI: TCypherAPI; dllOpOK: boolean; begin LastErrorCode := OTFE_ERR_SUCCESS; Result := FALSE; CheckActive(); if GetSpecificCypherDetails(cypherDriver, cypherGUID, cypherDetails) then begin if LoadLibraryCachedCypher(cypherDriver, cypherAPI) then begin LastErrorCode := OTFE_ERR_DRIVER_FAILURE; {$IFDEF FREEOTFE_DEBUG} DebugMsg('couldn''t connect to: '+cypherDriver); {$ENDIF} end else begin bufferSizeIn := sizeof(ptrDIOCBufferIn^) - sizeof(ptrDIOCBufferIn^.Key) + Length(key) - sizeof(ptrDIOCBufferIn^.IV) + Length(IV) - sizeof(ptrDIOCBufferIn^.Data) + Length(inData); // Round up to next "DIOC boundry". Although this always results in an // oversized buffer, it's guaranteed to be big enough. bufferSizeIn := bufferSizeIn + (DIOC_BOUNDRY - (bufferSizeIn mod DIOC_BOUNDRY)); ptrDIOCBufferIn := allocmem(bufferSizeIn); try // Just make sure its big enough bufferSizeOut := sizeof(ptrDIOCBufferOut^) - sizeof(ptrDIOCBufferOut^.Data) + Length(inData); ptrDIOCBufferOut := allocmem(bufferSizeOut); try ptrDIOCBufferIn.CypherGUID := cypherGUID; ptrDIOCBufferIn.KeyLength := (Length(key) * 8); // In *bits* ptrDIOCBufferIn.IVLength := (Length(IV) * 8); // In *bits* ptrDIOCBufferIn.DataLength := Length(inData); // In *bytes* // This may seem a little weird, but we do this because the data is // immediatly after the IV, which is immediatly after the key StrMove(@ptrDIOCBufferIn.Key, PAnsiChar(key), Length(key)); StrMove(((PAnsiChar(@ptrDIOCBufferIn.Key))+length(key)), PAnsiChar(IV), Length(IV)); StrMove(((PAnsiChar(@ptrDIOCBufferIn.Key))+length(key)+length(IV)), PAnsiChar(inData), Length(inData)); if encryptFlag then begin dllOpOK := (cypherAPI.CypherDLLFnEncrypt( bufferSizeIn, ptrDIOCBufferIn, bufferSizeOut, ptrDIOCBufferOut ) = ERROR_SUCCESS); end else begin dllOpOK := (cypherAPI.CypherDLLFnDecrypt( bufferSizeIn, ptrDIOCBufferIn, bufferSizeOut, ptrDIOCBufferOut ) = ERROR_SUCCESS); end; if dllOpOK then begin // Set outData so that it has enough characters which can be // overwritten with StrMove outData := StringOfChar(AnsiChar(#0), ptrDIOCBufferIn.DataLength); StrMove(PAnsiChar(outData), @ptrDIOCBufferOut.Data, ptrDIOCBufferIn.DataLength); Result := TRUE; end else begin LastErrorCode := OTFE_ERR_CYPHER_FAILURE; {$IFDEF FREEOTFE_DEBUG} DebugMsg('cypher DIOC 2 FAIL'); {$ENDIF} end; finally FillChar(ptrDIOCBufferOut^, bufferSizeOut, 0); FreeMem(ptrDIOCBufferOut); end; finally FillChar(ptrDIOCBufferIn^, bufferSizeIn, 0); FreeMem(ptrDIOCBufferIn); end; end; end else begin LastErrorCode := OTFE_ERR_DRIVER_FAILURE; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Unable to EncryptDecryptData'); {$ENDIF} end; end; // ---------------------------------------------------------------------------- // encryptFlag - set to TRUE to encrypt, FALSE to decrypt function TOTFEFreeOTFEDLL.EncryptDecryptSectorData( encryptFlag: boolean; cypherDriver: ansistring; cypherGUID: TGUID; SectorID: LARGE_INTEGER; SectorSize: integer; var key: TSDUBytes; var IV: Ansistring; var inData: Ansistring; var outData: Ansistring ): boolean; var ptrDIOCBufferIn: PDIOC_CYPHER_SECTOR_DATA_IN; bufferSizeIn: DWORD; ptrDIOCBufferOut: PDIOC_CYPHER_DATA_OUT; bufferSizeOut: DWORD; cypherDetails: TFreeOTFECypher_v3; cypherAPI: TCypherAPI; dllOpOK: boolean; begin LastErrorCode := OTFE_ERR_SUCCESS; Result := FALSE; CheckActive(); if GetSpecificCypherDetails(cypherDriver, cypherGUID, cypherDetails) then begin if not(LoadLibraryCachedCypher(cypherDriver, cypherAPI)) then begin LastErrorCode := OTFE_ERR_DRIVER_FAILURE; {$IFDEF FREEOTFE_DEBUG} DebugMsg('couldn''t connect to: '+cypherDriver); {$ENDIF} end else begin bufferSizeIn := sizeof(ptrDIOCBufferIn^) - sizeof(ptrDIOCBufferIn^.Key) + Length(key) - sizeof(ptrDIOCBufferIn^.IV) + Length(IV) - sizeof(ptrDIOCBufferIn^.Data) + Length(inData); // Round up to next "DIOC boundry". Although this always results in an // oversized buffer, it's guaranteed to be big enough. bufferSizeIn := bufferSizeIn + (DIOC_BOUNDRY - (bufferSizeIn mod DIOC_BOUNDRY)); ptrDIOCBufferIn := allocmem(bufferSizeIn); try // Just make sure its big enough bufferSizeOut := sizeof(ptrDIOCBufferOut^) - sizeof(ptrDIOCBufferOut^.Data) + Length(inData); ptrDIOCBufferOut := allocmem(bufferSizeOut); try ptrDIOCBufferIn.CypherGUID := cypherGUID; ptrDIOCBufferIn.SectorID := SectorID; ptrDIOCBufferIn.SectorSize := SectorSize; ptrDIOCBufferIn.KeyLength := (Length(key) * 8); // In *bits* ptrDIOCBufferIn.IVLength := (Length(IV) * 8); // In *bits* ptrDIOCBufferIn.DataLength := Length(inData); // In *bytes* // This may seem a little weird, but we do this because the data is // immediatly after the IV, which is immediatly after the key StrMove(@ptrDIOCBufferIn.Key, PAnsiChar(key), Length(key)); StrMove(((PAnsiChar(@ptrDIOCBufferIn.Key))+length(key)), PAnsiChar(IV), Length(IV)); StrMove(((PAnsiChar(@ptrDIOCBufferIn.Key))+length(key)+length(IV)), PAnsiChar(inData), Length(inData)); if encryptFlag then begin dllOpOK := (cypherAPI.CypherDLLFnEncryptSector( bufferSizeIn, ptrDIOCBufferIn, bufferSizeOut, ptrDIOCBufferOut ) = ERROR_SUCCESS); end else begin dllOpOK := (cypherAPI.CypherDLLFnDecryptSector( bufferSizeIn, ptrDIOCBufferIn, bufferSizeOut, ptrDIOCBufferOut ) = ERROR_SUCCESS); end; if dllOpOK then begin // Set outData so that it has enough characters which can be // overwritten with StrMove outData := StringOfChar(AnsiChar(#0), ptrDIOCBufferIn.DataLength); StrMove(PAnsiChar(outData), @ptrDIOCBufferOut.Data, ptrDIOCBufferIn.DataLength); Result := TRUE; end else begin LastErrorCode := OTFE_ERR_CYPHER_FAILURE; {$IFDEF FREEOTFE_DEBUG} DebugMsg('cypher DIOC 2 FAIL'); {$ENDIF} end; finally FillChar(ptrDIOCBufferOut^, bufferSizeOut, 0); FreeMem(ptrDIOCBufferOut); end; finally FillChar(ptrDIOCBufferIn^, bufferSizeIn, 0); FreeMem(ptrDIOCBufferIn); end; end; // If there was a problem, fallback to using v1 cypher API if not(Result) then begin Result := _EncryptDecryptData( encryptFlag, cypherDriver, cypherGUID, key, IV, inData, outData ); end; end else begin LastErrorCode := OTFE_ERR_DRIVER_FAILURE; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Unable to EncryptDecryptData'); {$ENDIF} end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.MainDLLFilename(): string; const DLL_MAIN_DRIVER = 'FreeOTFE.dll'; begin Result := GetDLLDir() + '\' + DLL_MAIN_DRIVER; Result :=SDUGetFinalPath(Result); end; // ---------------------------------------------------------------------------- // Attempt to mount on an existing device function TOTFEFreeOTFEDLL.MountDiskDevice( deviceName: string; volFilename: string; volumeKey: TSDUBytes; sectorIVGenMethod: TFreeOTFESectorIVGenMethod; volumeIV: TSDUBytes; readonly: boolean; IVHashDriver: ansistring; IVHashGUID: TGUID; IVCypherDriver: ansistring; IVCypherGUID: TGUID; mainCypherDriver: ansistring; mainCypherGUID: TGUID; VolumeFlags: integer; metaData: TOTFEFreeOTFEVolumeMetaData; offset: int64 = 0; size: int64 = 0; storageMediaType: TFreeOTFEStorageMediaType = mtFixedMedia ): boolean; var ptrDIOCBuffer: PDIOC_MOUNT_PC_DLL; bufferSize: integer; mainCypherDetails: TFreeOTFECypher_v3; useVolumeFlags: integer; strMetaData: Ansistring; mntHandles: TMountedHandle; openAccessCode: DWORD; openShareMode: DWORD; diskGeometry: TSDUDiskGeometry; useDriveLetter: char; volumeKeyStr :Ansistring; begin Result := FALSE; // Sanity check Assert( (deviceName <> ''), 'deviceName passed into MountDiskDevice was empty string' ); {$IFDEF FREEOTFE_DEBUG} DebugMsg('In MountDiskDevice'); {$ENDIF} useDriveLetter := deviceName[1]; VolumeMetadataToString(metaData, strMetaData); {$IFDEF FREEOTFE_DEBUG} DebugMsg('MountDiskDevice called with: '); DebugMsg(' deviceName: '+deviceName); DebugMsg(' filename: '+volFilename); DebugMsg(' volumeKey: '); DebugMsg(volumeKey); DebugMsg(' IVHashDriver: '+IVHashDriver); DebugMsg(' IVHashGUID: '+GUIDToString(IVHashGUID)); DebugMsg(' IVCypherDriver: '+IVCypherDriver); DebugMsg(' IVCypherGUID: '+GUIDToString(IVCypherGUID)); DebugMsg(' mainCypherDriver: '+mainCypherDriver); DebugMsg(' mainCypherGUID: '+GUIDToString(mainCypherGUID)); DebugMsg(' sectorIVGenMethod: '+FreeOTFESectorIVGenMethodTitle[sectorIVGenMethod]); DebugMsg(' VolumeFlags: '+inttostr(VolumeFlags)); DebugMsg(' metaData: <not shown>'); DebugMsg(' strMetaData:'); DebugMsgBinary(strMetaData); DebugMsg(' offset: '+inttostr(offset)); DebugMsg(' size: '+inttostr(size)); {$ENDIF} CheckActive(); if not(GetSpecificCypherDetails(mainCypherDriver, mainCypherGUID, mainCypherDetails)) then begin exit; end; // Ensure the volumeKey's length matches that of the cypher's keysize, if // the cypher's keysize is >= 0 if (mainCypherDetails.KeySizeRequired >= 0) then begin // THIS IS CORRECT; caters for both volumeKey>keysize and // volumeKey<keysize // Copy as much of the hash value as possible to match the key length volumeKeyStr := SDUBytesToString(volumeKey); volumeKeyStr := Copy(volumeKeyStr, 1, min((mainCypherDetails.KeySizeRequired div 8), length(volumeKeyStr))); // If the hash wasn't big enough, pad out with zeros volumeKeyStr := volumeKeyStr + StringOfChar(AnsiChar(#0), ((mainCypherDetails.KeySizeRequired div 8) - Length(volumeKeyStr))); SafeSetLength(volumeKey,(mainCypherDetails.KeySizeRequired div 8)); assert(SDUBytestostring(volumeKey) = volumeKeyStr) ; end; // If the sector IV doesn't use hashing, don't pass a hash algorithm in if not(SCTRIVGEN_USES_HASH[sectorIVGenMethod]) then begin IVHashDriver := ''; IVHashGUID := StringToGUID(NULL_GUID); end; // If the sector IV doesn't use hashing, don't pass a hash algorithm in if not(SCTRIVGEN_USES_CYPHER[sectorIVGenMethod]) then begin IVCypherDriver := ''; IVCypherGUID := StringToGUID(NULL_GUID); end; // Subtract sizeof(char) - once for the volume key, once for the volumeIV bufferSize := sizeof(ptrDIOCBuffer^) - sizeof(Ansichar) + (sizeof(Ansichar)*Length(volumeKey)) - sizeof(Ansichar) + (sizeof(Ansichar)*Length(volumeIV)) - sizeof(Ansichar) + (sizeof(Ansichar)*Length(strMetaData)); // Round up to next "DIOC boundry". Although this always results in an // oversized buffer, it's guaranteed to be big enough. bufferSize := bufferSize + (DIOC_BOUNDRY - (bufferSize mod DIOC_BOUNDRY)); ptrDIOCBuffer := allocmem(bufferSize); try StringToWideChar(volFilename, ptrDIOCBuffer.Filename, (length(ptrDIOCBuffer.Filename)-1)); ptrDIOCBuffer.DataStart := offset; ptrDIOCBuffer.DataEnd := 0; if (size > 0) then begin ptrDIOCBuffer.DataEnd := offset + size; end; StringToWideChar(IVHashDriver, ptrDIOCBuffer.IVHashDeviceName, (length(ptrDIOCBuffer.IVHashDeviceName)-1)); ptrDIOCBuffer.IVHashGUID := IVHashGUID; StringToWideChar(IVCypherDriver, ptrDIOCBuffer.IVCypherDeviceName, (length(ptrDIOCBuffer.IVCypherDeviceName)-1)); ptrDIOCBuffer.IVCypherGUID := IVCypherGUID; StringToWideChar(mainCypherDriver, ptrDIOCBuffer.MainCypherDeviceName, (length(ptrDIOCBuffer.MainCypherDeviceName)-1)); ptrDIOCBuffer.MainCypherGUID := mainCypherGUID; ptrDIOCBuffer.ReadOnly := readonly; ptrDIOCBuffer.MountSource := FreeOTFEMountSourceID[fomsFile]; if IsPartition_UserModeName(volFilename) then begin ptrDIOCBuffer.MountSource := FreeOTFEMountSourceID[fomsPartition]; end; useVolumeFlags := VolumeFlags; // Yes, this timestamp reverting is the right way around; if the bit // *isn't* set, the timestamps get reverted if frevertVolTimestamps then begin // Strip off bit VOL_FLAGS_NORMAL_TIMESTAMPS useVolumeFlags := useVolumeFlags and not(VOL_FLAGS_NORMAL_TIMESTAMPS); end else begin // Set bit VOL_FLAGS_NORMAL_TIMESTAMPS useVolumeFlags := useVolumeFlags or VOL_FLAGS_NORMAL_TIMESTAMPS end; ptrDIOCBuffer.VolumeFlags := useVolumeFlags; ptrDIOCBuffer.SectorIVGenMethod := FreeOTFESectorIVGenMethodID[sectorIVGenMethod]; ptrDIOCBuffer.MasterKeyLength := Length(volumeKey) * 8; ptrDIOCBuffer.VolumeIVLength := Length(volumeIV) * 8; ptrDIOCBuffer.MetaDataLength := Length(strMetaData); // This may seem a little weird, but we do this because the VolumeIV and metaData are // immediatly after the master key StrMove(@ptrDIOCBuffer.MasterKey, PAnsiChar(volumeKey), Length(volumeKey)); StrMove(((PAnsiChar(@ptrDIOCBuffer.MasterKey))+length(volumeKey)), PAnsiChar(volumeIV), Length(volumeIV)); StrMove(((PAnsiChar(@ptrDIOCBuffer.MasterKey))+length(volumeKey)+length(volumeIV)), PAnsiChar(strMetaData), Length(strMetaData)); mntHandles.DeviceHandle := DriverAPI.DSK_Init(nil, ptrDIOCBuffer); if (mntHandles.DeviceHandle <> 0) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Mounted OK!'); {$ENDIF} openAccessCode := (GENERIC_READ or GENERIC_WRITE); if readonly then begin openAccessCode := GENERIC_READ; end; openShareMode := 0; // Don't allow sharing mntHandles.OpenHandle := DriverAPI.DSK_Open( mntHandles.DeviceHandle, openAccessCode, openShareMode ); if (mntHandles.OpenHandle = 0) then begin DriverAPI.DSK_Deinit(mntHandles.DeviceHandle); end else begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Opened OK!'); {$ENDIF} mntHandles.BytesPerSector := 0; // Store tmp handles... AddHandles(useDriveLetter, mntHandles); if _GetDiskGeometry(useDriveLetter, diskGeometry) then begin // Cache the disk geometry... AddDiskGeometry(useDriveLetter, diskGeometry); // Add the bytes per sector, then delete and re-store the handles mntHandles.BytesPerSector := diskGeometry.BytesPerSector; DeleteHandles(useDriveLetter); AddHandles(useDriveLetter, mntHandles); Result := TRUE; end else begin DismountDiskDevice(useDriveLetter, FALSE); end; end; end; finally FreeMem(ptrDIOCBuffer); end; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Exiting MountDiskDevice'); {$ENDIF} end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.CreateMountDiskDevice( volFilename: string; volumeKey: TSDUBytes; sectorIVGenMethod: TFreeOTFESectorIVGenMethod; volumeIV: TSDUBytes; readonly: boolean; IVHashDriver: ansistring; IVHashGUID: TGUID; IVCypherDriver: ansistring; IVCypherGUID: TGUID; mainCypherDriver: ansistring; mainCypherGUID: TGUID; VolumeFlags: integer; DriveLetter: char; // PC kernel drivers: disk device to mount. PC DLL: "Drive letter" offset: int64 = 0; size: int64 = 0; MetaData_LinuxVolume: boolean = FALSE; // Linux volume MetaData_PKCS11SlotID: integer = PKCS11_NO_SLOT_ID; // PKCS11 SlotID MountMountAs: TFreeOTFEMountAs = fomaRemovableDisk; // PC kernel drivers *only* - ignored otherwise mountForAllUsers: boolean = TRUE // PC kernel drivers *only* - ignored otherwise ): boolean; var mountMetadata: TOTFEFreeOTFEVolumeMetaData; begin Result:= FALSE; PopulateVolumeMetadataStruct( MetaData_LinuxVolume, MetaData_PKCS11SlotID, mountMetadata ); // Attempt to mount the device if MountDiskDevice( DriveLetter, volFilename, volumeKey, sectorIVGenMethod, volumeIV, readonly, IVHashDriver, IVHashGUID, IVCypherDriver, IVCypherGUID, mainCypherDriver, mainCypherGUID, VolumeFlags, mountMetadata, offset, size, FreeOTFEMountAsStorageMediaType[MountMountAs] ) then begin Result := TRUE; end; end; // ---------------------------------------------------------------------------- // Attempt to dismount a device function TOTFEFreeOTFEDLL.DismountDiskDevice(deviceName: string; emergency: boolean): boolean; var DIOCBuffer: TDIOC_FORCE_DISMOUNTS; bytesReturned: DWORD; handles: TMountedHandle; useDriveLetter: char; begin Result := FALSE; CheckActive(); // Sanity check... Assert( (deviceName <> ''), 'deviceName set to empty string in call to DismountDiskDevice' ); { TODO 1 -otdk -cclean : pass in just drive letter } useDriveLetter := deviceName[1]; if GetHandles(useDriveLetter, handles) then begin if emergency then begin DIOCBuffer.ForceDismounts := emergency; DriverAPI.DSK_IOControl( handles.OpenHandle, IOCTL_FREEOTFE_SET_FORCE_DISMOUNT, @DIOCBuffer, sizeof(DIOCBuffer), nil, 0, @bytesReturned ); end; DriverAPI.DSK_Close(handles.OpenHandle); DriverAPI.DSK_Deinit(handles.DeviceHandle); DeleteDiskGeometry(useDriveLetter); DeleteHandles(useDriveLetter); Result := TRUE; end; end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEDLL.AddHandles(driveLetter: char; handles: TMountedHandle); var ptrMountedHandles: PMountedHandle; begin new(ptrMountedHandles); ptrMountedHandles^ := handles; fMountedHandles.AddObject(driveLetter, TObject(ptrMountedHandles)); end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.GetHandles(driveLetter: char; var handles: TMountedHandle): boolean; var ptrMountedHandles: PMountedHandle; idx: integer; begin Result := FALSE; idx := fMountedHandles.IndexOf(uppercase(driveLetter)); if (idx >= 0) then begin ptrMountedHandles := PMountedHandle(fMountedHandles.Objects[idx]); handles := ptrMountedHandles^; Result := TRUE; end; end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEDLL.DeleteHandles(driveLetter: char); var ptrMountedHandles: PMountedHandle; idx: integer; begin idx := fMountedHandles.IndexOf(driveLetter); if (idx >= 0) then begin ptrMountedHandles := PMountedHandle(fMountedHandles.Objects[idx]); Dispose(ptrMountedHandles); fMountedHandles.Delete(idx); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.GetNextDriveLetter(userDriveLetter, requiredDriveLetter: char): char; var c: char; begin Result := #0; for c:='A' to 'Z' do begin if (fMountedHandles.IndexOf(c) < 0) then begin Result := c; break; end; end; // Sanity check; although this isn't actually true (we could go onto numbers, // lowercase, etc), it is if we keep with the drive letter paradigm... Assert( (Result <> #0), 'Unable to open more then 26 volumes at the same time' ); end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.DriverType(): string; begin Result := _('DLL driver'); end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.GetVolumeInfo(driveLetter: char; var volumeInfo: TOTFEFreeOTFEVolumeInfo): boolean; var BytesReturned: DWORD; outBuffer: TDIOC_DISK_DEVICE_STATUS_PC_DLL; tmpSectorIVGenMethod: TFreeOTFESectorIVGenMethod; handles: TMountedHandle; begin Result := FALSE; CheckActive(); driveLetter := upcase(driveLetter); if GetHandles(driveLetter, handles) then begin if DriverAPI.DSK_IOControl( handles.OpenHandle, IOCTL_FREEOTFE_GET_DISK_DEVICE_STATUS, nil, 0, @outBuffer, sizeof(outBuffer), @BytesReturned ) then begin if (BytesReturned <= sizeof(outBuffer)) then begin volumeInfo.Filename := Copy(outBuffer.Filename, 1, SDUWStrLen(outBuffer.Filename)); { TODO 1 -otdk -cinvestigate : what if unicode filename? } volumeInfo.DeviceName := driveLetter; volumeInfo.IVHashDevice := Copy(outBuffer.IVHashDeviceName, 1, SDUWStrLen(outBuffer.IVHashDeviceName)); { TODO 1 -otdk -cinvestigate : what if unicode? } volumeInfo.IVHashGUID := outBuffer.IVHashGUID; volumeInfo.IVCypherDevice := Copy(outBuffer.IVCypherDeviceName, 1, SDUWStrLen(outBuffer.IVCypherDeviceName)); { TODO 1 -otdk -cinvestigate : what if unicode? } volumeInfo.IVCypherGUID := outBuffer.IVCypherGUID; volumeInfo.MainCypherDevice := Copy(outBuffer.MainCypherDeviceName, 1, SDUWStrLen(outBuffer.MainCypherDeviceName)); { TODO 1 -otdk -cinvestigate : what if unicode? } volumeInfo.MainCypherGUID := outBuffer.MainCypherGUID; volumeInfo.Mounted := TRUE; volumeInfo.ReadOnly := outBuffer.ReadOnly; volumeInfo.VolumeFlags := outBuffer.VolumeFlags; volumeInfo.SectorIVGenMethod:= foivgUnknown; for tmpSectorIVGenMethod := low(TFreeOTFESectorIVGenMethod) to high(TFreeOTFESectorIVGenMethod) do begin if (FreeOTFESectorIVGenMethodID[tmpSectorIVGenMethod] = outBuffer.SectorIVGenMethod) then begin volumeInfo.SectorIVGenMethod:= tmpSectorIVGenMethod; end; end; volumeInfo.DriveLetter := AnsiChar( driveLetter); // pos can be char - see todo in volinfo struct // Functionality in DLL/PDA driver to retrieve metadata not currently implemented! Result := TRUE; // Result := GetVolumeMetaData(driveLetter, outBuffer.MetaDataLength, volumeInfo.MetaData); // volumeInfo.MetaDataStructValid := ParseVolumeMetadata( // volumeInfo.MetaData, // volumeInfo.MetaDataStruct // ); end; end; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.Seek(driveLetter: char; offset: DWORD): boolean; var handles: TMountedHandle; begin Result:= FALSE; CheckActive(); if GetHandles(driveLetter, handles) then begin if (DriverAPI.DSK_Seek( handles.OpenHandle, offset, FILE_BEGIN ) = ERROR_SUCCESS) then begin end; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.ReadData_Sectors( DriveLetter: char; SectorNoStart: DWORD; CountSectors: DWORD; stm: TStream ): boolean; var handles: TMountedHandle; ptrBuffer: PByte; sgReq: TSG_REQ; bufferSize: DWORD; bytesReturned: DWORD; begin Result:= FALSE; CheckActive(); if GetHandles(driveLetter, handles) then begin bufferSize:= (CountSectors * handles.BytesPerSector); ptrBuffer := AllocMem(bufferSize); try sgReq.sr_start:= sectorNoStart; sgReq.sr_num_sec:= countSectors; sgReq.sr_num_sg:= 1; // Only 1 SG buffer sgReq.sr_status:= ERROR_SUCCESS; sgReq.sr_callback:= nil; sgReq.sr_sglist[1].sb_len := bufferSize; sgReq.sr_sglist[1].sb_buf := ptrBuffer; if DriverAPI.DSK_IOControl( handles.OpenHandle, IOCTL_DISK_READ, // DISK_IOCTL_READ, - old const; changed to IOCTL_DISK_READ in WinCE 3.0 @sgReq, sizeof(sgReq), nil, 0, @bytesReturned ) then begin if (sgReq.sr_status = ERROR_SUCCESS) then begin stm.Write(ptrBuffer^, bufferSize); Result := TRUE; end; end; finally FreeMem(ptrBuffer); end; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.WriteData_Sectors( DriveLetter: char; SectorNoStart: DWORD; CountSectors: DWORD; stm: TStream ): boolean; var handles: TMountedHandle; ptrBuffer: PByte; sgReq: TSG_REQ; bufferSize: DWORD; bytesReturned: DWORD; begin Result:= FALSE; CheckActive(); if GetHandles(driveLetter, handles) then begin bufferSize:= (CountSectors * handles.BytesPerSector); ptrBuffer := AllocMem(bufferSize); try stm.Read(ptrBuffer^, bufferSize); sgReq.sr_start:= sectorNoStart; sgReq.sr_num_sec:= countSectors; sgReq.sr_num_sg:= 1; // Only 1 SG buffer sgReq.sr_status:= ERROR_SUCCESS; sgReq.sr_callback:= nil; sgReq.sr_sglist[1].sb_len := bufferSize; sgReq.sr_sglist[1].sb_buf := ptrBuffer; if DriverAPI.DSK_IOControl( handles.OpenHandle, IOCTL_DISK_WRITE, // DISK_IOCTL_WRITE, - old const; changed to IOCTL_DISK_WRITE in WinCE 3.0 @sgReq, sizeof(sgReq), nil, 0, @bytesReturned ) then begin if (sgReq.sr_status = ERROR_SUCCESS) then begin Result := TRUE; end; end; finally FreeMem(ptrBuffer); end; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.ReadData_Bytes( DriveLetter: char; Offset: ULONGLONG; DataLength: ULONGLONG; Data: TStream ): boolean; var diskGeometry: TSDUDiskGeometry; sectorID_i64: int64; sectorID: DWORD; cntSectors: DWORD; partialSector: boolean; tmpStream: TSDUMemoryStream; begin Result := TRUE; // Short circuit... if (DataLength = 0) then begin Result := TRUE; exit; end; if Result then begin Result := GetDiskGeometry(DriveLetter, diskGeometry); end; sectorID := 0; if Result then begin if (Offset mod int64(diskGeometry.BytesPerSector) <> 0) then begin //lplp - xxx - eliminate this restriction showmessage('NON-SECTOR (offset + length) READS must start from a sector offset in current implementation'); Result := FALSE; end; sectorID_i64 := Offset div int64(diskGeometry.BytesPerSector); sectorID := sectorID_i64 and $FFFFFFFF; end; if Result then begin // If the amount of data to transfer isn't a multiple of the sector size, we // have to use a temp stream to hold the data partialSector := ((DataLength mod diskGeometry.BytesPerSector) <> 0); cntSectors := (DataLength div diskGeometry.BytesPerSector); if partialSector then begin inc(cntSectors); tmpStream:= TSDUMemoryStream.Create(); try Result := ReadData_Sectors(DriveLetter, sectorID, cntSectors, tmpStream); tmpStream.Position := 0; Data.CopyFrom(tmpStream, DataLength); finally tmpStream.Free(); end; end else begin Result := ReadData_Sectors(DriveLetter, sectorID, cntSectors, Data); end; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.WriteData_Bytes( DriveLetter: char; Offset: ULONGLONG; DataLength: ULONGLONG; Data: TStream ): boolean; var diskGeometry: TSDUDiskGeometry; sectorID_i64: int64; sectorID: DWORD; cntSectors: DWORD; partialSector: boolean; tmpStream: TSDUMemoryStream; begin Result := TRUE; // Short circuit... if (DataLength = 0) then begin Result := TRUE; exit; end; if Result then begin Result := GetDiskGeometry(DriveLetter, diskGeometry); end; sectorID := 0; if Result then begin if (Offset mod int64(diskGeometry.BytesPerSector) <> 0) then begin //lplp - xxx - eliminate this restriction showmessage('NON-SECTOR (offset + length) WRITES must start from a sector offset in current implementation'); Result := FALSE; end; sectorID_i64 := Offset div int64(diskGeometry.BytesPerSector); sectorID := sectorID_i64 and $FFFFFFFF; end; if Result then begin // If the amount of data to transfer isn't a multiple of the sector size, we // have to use a temp stream to hold the data partialSector := ((DataLength mod diskGeometry.BytesPerSector) <> 0); cntSectors := (DataLength div diskGeometry.BytesPerSector); if partialSector then begin tmpStream:= TSDUMemoryStream.Create(); try inc(cntSectors); // In order to preserve the data previously written to the sector's slack // space, read in the previous data and overlay the new data onto it. if ReadData_Sectors( DriveLetter, sectorID, cntSectors, tmpStream ) then begin tmpStream.Position := 0; tmpStream.CopyFrom(Data, DataLength); tmpStream.Position := 0; Result := WriteData_Sectors(DriveLetter, sectorID, cntSectors, tmpStream); end; finally tmpStream.Free(); end; end else begin Result := WriteData_Sectors(DriveLetter, sectorID, cntSectors, Data); end; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL._GetDiskGeometry( DriveLetter: char; var diskGeometry: TSDUDiskGeometry ): boolean; var handles: TMountedHandle; bytesReturned: DWORD; begin Result:= FALSE; CheckActive(); if GetHandles(driveLetter, handles) then begin if DriverAPI.DSK_IOControl( handles.OpenHandle, IOCTL_DISK_GETINFO, nil, 0, @diskGeometry, sizeof(diskGeometry), @bytesReturned ) then begin Result := TRUE; end; end; end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEDLL.AddDiskGeometry(driveLetter: char; diskGeometry: TSDUDiskGeometry); var ptrDiskGeometry: PSDUDiskGeometry; begin new(ptrDiskGeometry); ptrDiskGeometry^ := diskGeometry; fCachedDiskGeometry.AddObject(driveLetter, TObject(ptrDiskGeometry)); end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.GetDiskGeometry(driveLetter: char; var diskGeometry: TSDUDiskGeometry): boolean; var ptrDiskGeometry: PSDUDiskGeometry; idx: integer; begin Result := FALSE; idx := fCachedDiskGeometry.IndexOf(uppercase(driveLetter)); if (idx >= 0) then begin ptrDiskGeometry := PSDUDiskGeometry(fCachedDiskGeometry.Objects[idx]); diskGeometry := ptrDiskGeometry^; Result := TRUE; end; end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEDLL.DeleteDiskGeometry(driveLetter: char); var ptrDiskGeometry: PSDUDiskGeometry; idx: integer; begin idx := fCachedDiskGeometry.IndexOf(driveLetter); if (idx >= 0) then begin ptrDiskGeometry := PSDUDiskGeometry(fCachedDiskGeometry.Objects[idx]); Dispose(ptrDiskGeometry); fCachedDiskGeometry.Delete(idx); end; end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEDLL.CachesCreate(); begin inherited; fCachedHashAPI:= TStringList.Create(); fCachedCypherAPI:= TStringList.Create(); end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEDLL.CachesDestroy(); var i: integer; begin inherited; for i:=0 to (fCachedHashAPI.Count-1) do begin if (fCachedHashAPI.Objects[i] <> nil) then begin FreeLibraryHash((PHashAPI(fCachedHashAPI.Objects[i]))^); Dispose(PHashAPI(fCachedHashAPI.Objects[i])); end; end; fCachedHashAPI.Free(); for i:=0 to (fCachedCypherAPI.Count-1) do begin if (fCachedCypherAPI.Objects[i] <> nil) then begin FreeLibraryCypher((PCypherAPI(fCachedCypherAPI.Objects[i]))^); Dispose(PCypherAPI(fCachedCypherAPI.Objects[i])); end; end; fCachedCypherAPI.Free(); end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEDLL.CachesAddHashAPI(const libFilename: string; const api: THashAPI); var ptrRec: PHashAPI; begin new(ptrRec); ptrRec^ := api; fCachedHashAPI.AddObject(libFilename, Pointer(ptrRec)); end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.CachesGetHashAPI(const libFilename: string; var api: THashAPI): boolean; var ptrRec: PHashAPI; idx: integer; cacheHit: boolean; begin cacheHit := FALSE; idx := fCachedHashAPI.IndexOf(libFilename); if (idx >= 0) then begin ptrRec := PHashAPI(fCachedHashAPI.Objects[idx]); api := ptrRec^; cacheHit := TRUE; end; Result := cacheHit; end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEDLL.CachesAddCypherAPI(const libFilename: string; const api: TCypherAPI); var ptrRec: PCypherAPI; begin new(ptrRec); ptrRec^ := api; fCachedCypherAPI.AddObject(libFilename, Pointer(ptrRec)); end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEDLL.CachesGetCypherAPI(const libFilename: string; var api: TCypherAPI): boolean; var ptrRec: PCypherAPI; idx: integer; cacheHit: boolean; begin cacheHit := FALSE; idx := fCachedCypherAPI.IndexOf(libFilename); if (idx >= 0) then begin ptrRec := PCypherAPI(fCachedCypherAPI.Objects[idx]); api := ptrRec^; cacheHit := TRUE; end; Result := cacheHit; end; {returns an instance of the only object. call SetFreeOTFEType first} function GetFreeOTFEDLL : TOTFEFreeOTFEDLL; begin assert (GetFreeOTFEBase is TOTFEFreeOTFEDLL,'call SetFreeOTFEType with correct type'); result := GetFreeOTFEBase as TOTFEFreeOTFEDLL; end; END.
unit uLivroModel; interface uses uGenericEntity, uEditoraModel, uAutorModel; type TLivroModel = class(TGenericEntity) private FTitulo: String; FCodigo: Integer; FEditora: TEditoraModel; FAutor: TAutorModel; procedure SetCodigo(const Value: Integer); procedure SetEditora(const Value: TEditoraModel); procedure SetTitulo(const Value: String); procedure SetAutor(const Value: TAutorModel); public property Codigo: Integer read FCodigo write SetCodigo; property Titulo: String read FTitulo write SetTitulo; property Editora: TEditoraModel read FEditora write SetEditora; property Autor: TAutorModel read FAutor write SetAutor; constructor Create(ACodigo: Integer = 0; ATitulo: String = ''); end; implementation uses SysUtils; { TLivro } constructor TLivroModel.Create(ACodigo: Integer; ATitulo: String); begin FCodigo := ACodigo; FTitulo := ATitulo; end; procedure TLivroModel.SetAutor(const Value: TAutorModel); begin FAutor := Value; end; procedure TLivroModel.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TLivroModel.SetEditora(const Value: TEditoraModel); begin FEditora := Value; end; procedure TLivroModel.SetTitulo(const Value: String); begin FTitulo := Value; end; end.
unit com.example.android.accelerometerplay; {* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *} interface uses java.util, android.os, android.app, android.util, android.content, android.view, android.graphics, android.hardware; type {* * Each of our particle holds its previous and current position, its * acceleration. for added realism each particle has its own friction * coefficient. *} Particle = class private // friction of the virtual table and air const sFriction = 0.1; var mAccelX: Single; var mAccelY: Single; var mPosX: Single; var mPosY: Single; var mLastPosX: Single; var mLastPosY: Single; var mOneMinusFriction: Single; var mView: SimulationView; public constructor(v: SimulationView); method computePhysics(sx, sy, dT, dTC: Single); method resolveCollisionWithBounds; property PosX: Single read mPosX write mPosX; property PosY: Single read mPosY write mPosY; end; implementation constructor Particle(v: SimulationView); begin mView := v; // make each particle a bit different by randomizing its // coefficient of friction var r := (Single(Math.random) - 0.5) * 0.2; mOneMinusFriction := 1.0 - sFriction + r; end; method Particle.computePhysics(sx, sy, dT, dTC: Single); const m = 1000; // mass of our virtual object invm = 1.0 / m; begin // Force of gravity applied to our virtual object var gx := -sx * m; var gy := -sy * m; {* * ?F = mA <=> A = ?F / m We could simplify the code by * completely eliminating "m" (the mass) from all the equations, * but it would hide the concepts from this sample code. *} var ax := gx * invm; var ay := gy * invm; {* * Time-corrected Verlet integration The position Verlet * integrator is defined as x(t+?t) = x(t) + x(t) - x(t-?t) + * a(t)?t² However, the above equation doesn't handle variable * ?t very well, a time-corrected version is needed: x(t+?t) = * x(t) + (x(t) - x(t-?t)) * (?t/?t_prev) + a(t)?t² We also add * a simple friction term (f) to the equation: x(t+?t) = x(t) + * (1-f) * (x(t) - x(t-?t)) * (?t/?t_prev) + a(t)?t² *} var dTdT := dT * dT; //x(t+?t) = x(t) + (1-f) * (x(t) - x(t-?t)) * (?t/?t_prev) + a(t)?t² var x := mPosX + (mOneMinusFriction * dTC * (mPosX - mLastPosX)) + (mAccelX * dTdT); var y := mPosY + (mOneMinusFriction * dTC * (mPosY - mLastPosY)) + (mAccelY * dTdT); mLastPosX := mPosX; mLastPosY := mPosY; mPosX := x; mPosY := y; mAccelX := ax; mAccelY := ay; end; {* * Resolving constraints and collisions with the Verlet integrator * can be very simple, we simply need to move a colliding or * constrained particle in such way that the constraint is * satisfied. *} method Particle.resolveCollisionWithBounds; begin var xmax := mView.HorizontalBound; var ymax := mView.VerticalBound; var x := mPosX; var y := mPosY; if x > xmax then mPosX := xmax else if x < -xmax then mPosX := -xmax; if y > ymax then mPosY := ymax else if y <= -ymax then mPosY := -ymax; end; end.
program HowToCreateAnAnimation; uses SwinGame, sgTypes; procedure Main(); var explosion: Sprite; begin OpenAudio(); OpenGraphicsWindow('Create Animation', 200, 200); LoadResourceBundle('explosion_bundle.txt'); explosion := CreateSprite(BitmapNamed('explosionBmp'), AnimationScriptNamed('explosionScrpt')); SpriteStartAnimation(explosion, 'explosion_loop'); SpriteSetX(explosion, 64); SpriteSetY(explosion, 64); repeat ClearScreen(ColorWhite); DrawSprite(explosion); RefreshScreen(60); UpdateSprite(explosion); ProcessEvents(); until WindowCloseRequested(); Delay(800); FreeSprite(explosion); CloseAudio(); ReleaseAllResources(); end; begin Main(); end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmNotebookReg Purpose : Declares the component and property editors for the rmNotebook control Date : 11-20-02 Author : Ryan J. Mills Version : 1.92 Notes : ================================================================================} unit rmNotebookReg; interface {$I CompilerDefines.INC} {$ifdef D6_or_higher} uses Classes, DesignIntf, DesignEditors, TypInfo; {$else} uses Classes, DsgnIntf, TypInfo; {$endif} type TrmNotebookActivePageProperty = class(TComponentProperty) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; end; TrmCustomNotebookControlEditor = class(TDefaultEditor) procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; implementation uses rmNotebook2; const SNotebookIndexError = 'Notebook Page Index Error'; StrAddPage = 'New Page'; StrNextPage = 'Next Page'; StrPrevPage = 'Previous Page'; { TrmNotebookActivePageProperty } function TrmNotebookActivePageProperty.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TrmNotebookActivePageProperty.GetValues(Proc: TGetStrProc); var I: Integer; Component: TComponent; begin {$ifdef D6_or_higher} for I := 0 to Designer.Root.ComponentCount - 1 do begin Component := Designer.Root.Components[I]; if (Component.Name <> '') and (Component is TrmNotebookPage) and (TrmNotebookPage(Component).NotebookControl = GetComponent(0)) then Proc(Component.Name); end; {$else} for I := 0 to Designer.Form.ComponentCount - 1 do begin Component := Designer.Form.Components[I]; if (Component.Name <> '') and (Component is TrmNotebookPage) and (TrmNotebookPage(Component).NotebookControl = GetComponent(0)) then Proc(Component.Name); end; {$endif} end; { TrmCustomNotebookControlEditor } procedure TrmCustomNotebookControlEditor.ExecuteVerb(Index: Integer); var NotebookControl: TrmCustomNotebookControl; Page: TrmNotebookPage; begin if Component is TrmNotebookPage then NotebookControl := TrmNotebookPage(Component).NotebookControl else NotebookControl := TrmCustomNotebookControl(Component); if NotebookControl <> nil then begin if Index = 0 then begin {$ifdef D6_or_higher} Page := TrmNotebookPage.Create(Designer.Root); {$else} Page := TrmNotebookPage.Create(Designer.Form); {$endif} try Page.Name := Designer.UniqueName(TrmNotebookPage.ClassName); Page.NotebookControl := NotebookControl; Page.Caption := Page.Name; except Page.Free; raise; end; NotebookControl.ActivePage := Page; Designer.SelectComponent(Page); Designer.Modified; end else begin Page := NotebookControl.FindNextPage(NotebookControl.ActivePage, Index = 1); if (Page <> nil) and (Page <> NotebookControl.ActivePage) then begin NotebookControl.ActivePage := Page; if Component is TrmNotebookPage then Designer.SelectComponent(Page); Designer.Modified; end; end; end; end; function TrmCustomNotebookControlEditor.GetVerb(Index: Integer): string; begin case Index of 0 : Result:= StrAddPage; 1 : Result:= StrNextPage; 2 : Result:= StrPrevPage; end; end; function TrmCustomNotebookControlEditor.GetVerbCount: Integer; begin Result := 3; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [COMPRA_COTACAO] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM 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. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit CompraCotacaoVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL, CompraReqCotacaoDetalheVO, CompraFornecedorCotacaoVO, ViewCompraMapaComparativoVO; type TCompraCotacaoVO = class(TVO) private FID: Integer; FDATA_COTACAO: TDateTime; FDESCRICAO: String; FSITUACAO: String; //Transientes FListaCompraReqCotacaoDetalheVO: TListaCompraReqCotacaoDetalheVO; FListaCompraFornecedorCotacao: TListaCompraFornecedorCotacaoVO; FListaMapaComparativo: TListaViewCompraMapaComparativoVO; published constructor Create; override; destructor Destroy; override; property Id: Integer read FID write FID; property DataCotacao: TDateTime read FDATA_COTACAO write FDATA_COTACAO; property Descricao: String read FDESCRICAO write FDESCRICAO; property Situacao: String read FSITUACAO write FSITUACAO; //Transientes property ListaCompraReqCotacaoDetalheVO: TListaCompraReqCotacaoDetalheVO read FListaCompraReqCotacaoDetalheVO write FListaCompraReqCotacaoDetalheVO; property ListaCompraFornecedorCotacao: TListaCompraFornecedorCotacaoVO read FListaCompraFornecedorCotacao write FListaCompraFornecedorCotacao; property ListaMapaComparativo: TListaViewCompraMapaComparativoVO read FListaMapaComparativo write FListaMapaComparativo; end; TListaCompraCotacaoVO = specialize TFPGObjectList<TCompraCotacaoVO>; implementation constructor TCompraCotacaoVO.Create; begin inherited; FListaCompraReqCotacaoDetalheVO := TListaCompraReqCotacaoDetalheVO.Create; FListaCompraFornecedorCotacao := TListaCompraFornecedorCotacaoVO.Create; FListaMapaComparativo := TListaViewCompraMapaComparativoVO.Create; end; destructor TCompraCotacaoVO.Destroy; begin FreeAndNil(FListaCompraReqCotacaoDetalheVO); FreeAndNil(FListaCompraFornecedorCotacao); FreeAndNil(FListaMapaComparativo); inherited; end; initialization Classes.RegisterClass(TCompraCotacaoVO); finalization Classes.UnRegisterClass(TCompraCotacaoVO); end.
unit uFrmAdvertisingConfig; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, Menus, Mask, DBCtrls, cxDBEdit, cxContainer, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxImageComboBox, cxSpinEdit, cxCalendar, CheckLst, cxCheckBox, siComp; type TFrmAdvertisingConfig = class(TForm) pnlButtons: TPanel; btnClose: TBitBtn; btnSave: TBitBtn; pnlFilter: TPanel; grdAdvertisingDB: TcxGridDBTableView; grdAdvertisingLevel1: TcxGridLevel; grdAdvertising: TcxGrid; dsAdvertising: TDataSource; grdAdvertisingDBDescription: TcxGridDBColumn; grdAdvertisingDBFileName: TcxGridDBColumn; grdAdvertisingDBStartDate: TcxGridDBColumn; grdAdvertisingDBEndDate: TcxGridDBColumn; grdAdvertisingDBDaysOfWeekString: TcxGridDBColumn; grdAdvertisingDBDuration: TcxGridDBColumn; Button1: TButton; pnlNewAdveritising: TPanel; btnAddAdveritising: TButton; btnAbortAdv: TButton; Label1: TLabel; Label2: TLabel; Label3: TLabel; cbxType: TcxDBImageComboBox; cxDBTextEdit1: TcxDBTextEdit; cxDBTextEdit2: TcxDBTextEdit; btnImgLogo: TSpeedButton; OP: TOpenDialog; Label4: TLabel; cxDBDateEdit1: TcxDBDateEdit; Label5: TLabel; cxDBDateEdit2: TcxDBDateEdit; Label6: TLabel; Label8: TLabel; cxDBSpinEdit3: TcxDBSpinEdit; Label9: TLabel; chkDaysOfWeek: TCheckListBox; grdAdvertisingDBTypeString: TcxGridDBColumn; dtStart: TcxDateEdit; Label10: TLabel; Label11: TLabel; dtEnd: TcxDateEdit; cbxAdType: TcxComboBox; Label12: TLabel; cbxControlVideo: TcxDBCheckBox; chkDisplayDescrip: TcxDBCheckBox; grdAdvertisingDBDisplayDescription: TcxGridDBColumn; chkHours: TCheckListBox; siLang: TsiLang; pnlButtoms: TPanel; btnNew: TSpeedButton; btnEdit: TSpeedButton; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnCloseClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure btnAbortAdvClick(Sender: TObject); procedure btnImgLogoClick(Sender: TObject); procedure btnAddAdveritisingClick(Sender: TObject); procedure cxDBImageComboBox1PropertiesChange(Sender: TObject); procedure Button1Click(Sender: TObject); procedure dsAdvertisingDataChange(Sender: TObject; Field: TField); procedure btnNewClick(Sender: TObject); procedure btnEditClick(Sender: TObject); private FResult : Boolean; function GetWeekDayList: String; procedure SetWeekDayList(WeekDays : String); function GetHourList: String; procedure SetHourList(Hours : String); procedure FillWeekDays; procedure FillHours; public function Start : Boolean; end; implementation uses uDM, DBClient, uDMGlobal; {$R *.dfm} { TFrmAdvertisingConfig } function TFrmAdvertisingConfig.Start: Boolean; begin FResult := False; ShowModal; Result := FResult; end; procedure TFrmAdvertisingConfig.FormClose(Sender: TObject; var Action: TCloseAction); begin if DM.cdsAdvertising.State in [dsEdit, dsInsert] then DM.cdsAdvertising.Cancel; Action := caFree; end; procedure TFrmAdvertisingConfig.btnCloseClick(Sender: TObject); begin FResult := False; Close; end; procedure TFrmAdvertisingConfig.btnSaveClick(Sender: TObject); begin DM.SaveAdvertising; FResult := True; Close; end; procedure TFrmAdvertisingConfig.btnAbortAdvClick(Sender: TObject); begin pnlFilter.Visible := True; pnlNewAdveritising.Visible := False; if DM.cdsAdvertising.State in [dsEdit, dsInsert] then DM.cdsAdvertising.Cancel; end; procedure TFrmAdvertisingConfig.btnImgLogoClick(Sender: TObject); begin if OP.Execute then if DM.cdsAdvertising.State in [dsEdit, dsInsert] then DM.cdsAdvertising.FieldByName('FileName').AsString := OP.FileName; end; procedure TFrmAdvertisingConfig.btnAddAdveritisingClick(Sender: TObject); begin with DM.cdsAdvertising do if State in [dsEdit, dsInsert] then begin FieldByName('DaysOfWeek').AsString := GetWeekDayList; FieldByName('Hours').AsString := GetHourList; DM.FLastDesc := DM.FLastDesc + 1; Post; if (btnAddAdveritising.Tag = 0) then Append; end; end; function TFrmAdvertisingConfig.GetWeekDayList: String; var i : Integer; begin Result := ''; for i := 0 to chkDaysOfWeek.Items.Count-1 do if chkDaysOfWeek.Checked[i] then Result := Result + IntToStr(i+1) + ','; end; procedure TFrmAdvertisingConfig.SetWeekDayList(WeekDays: String); var i : Integer; begin for i := 0 to chkDaysOfWeek.Items.Count-1 do if Pos((IntToStr(i+1) + ','), WeekDays) > 0 then chkDaysOfWeek.Checked[i] := True; end; procedure TFrmAdvertisingConfig.FillWeekDays; var i : Integer; begin for i := 0 to chkDaysOfWeek.Items.Count-1 do chkDaysOfWeek.Checked[i] := True; end; procedure TFrmAdvertisingConfig.FillHours; var i : Integer; begin for i := 0 to chkHours.Items.Count-1 do chkHours.Checked[i] := True; end; procedure TFrmAdvertisingConfig.cxDBImageComboBox1PropertiesChange( Sender: TObject); begin cbxControlVideo.Visible := False; if cbxType.ItemIndex = ADV_BITMAP then OP.Filter := ADV_BITMAP_EXT else if cbxType.ItemIndex = ADV_JPG then OP.Filter := ADV_JPG_EXT else if cbxType.ItemIndex = ADV_FLASH then OP.Filter := ADV_FLASH_EXT else if cbxType.ItemIndex = ADV_WEB then OP.Filter := ADV_WEB_EXT else if cbxType.ItemIndex = ADV_VIDEO then begin OP.Filter := ADV_VIDEO_EXT; cbxControlVideo.Visible := True; end; end; procedure TFrmAdvertisingConfig.Button1Click(Sender: TObject); var AFilter : String; begin if dtStart.Text <> '' then AFilter := 'StartDate <= ' + QuotedStr(FormatDateTime('ddddd', dtStart.Date)); if dtEnd.Text <> '' then if AFilter = '' then AFilter := 'EndDate > ' + QuotedStr(FormatDateTime('ddddd', Now)) else AFilter := AFilter + ' AND EndDate > ' + QuotedStr(FormatDateTime('ddddd', Now)); if cbxAdType.Text <> '' then if AFilter = '' then AFilter := 'Type = ' + IntToStr(cbxAdType.ItemIndex) else AFilter := AFilter + ' AND Type = ' + IntToStr(cbxAdType.ItemIndex); with DM.cdsAdvertising do begin Filtered := False; Filter := AFilter; Filtered := True; end; end; procedure TFrmAdvertisingConfig.dsAdvertisingDataChange(Sender: TObject; Field: TField); begin SetWeekDayList(DM.cdsAdvertising.FieldByName('DaysOfWeek').AsString); cbxControlVideo.Visible := DM.cdsAdvertising.FieldByName('VideoControl').AsBoolean; end; function TFrmAdvertisingConfig.GetHourList: String; var i : Integer; begin Result := ''; for i := 0 to chkHours.Items.Count-1 do if chkHours.Checked[i] then Result := Result + IntToStr(i+1) + ','; end; procedure TFrmAdvertisingConfig.SetHourList(Hours: String); var i : Integer; begin for i := 0 to chkHours.Items.Count-1 do if Pos((IntToStr(i+1) + ','), Hours) > 0 then chkHours.Checked[i] := True; end; procedure TFrmAdvertisingConfig.btnNewClick(Sender: TObject); begin pnlFilter.Visible := False; pnlNewAdveritising.Visible := True; btnAddAdveritising.Caption := 'Add'; btnAddAdveritising.Tag := 0; with DM.cdsAdvertising do begin Filtered := False; Filter := ''; end; with DM.cdsAdvertising do if not (State in [dsEdit, dsInsert]) then begin Append; FillWeekDays; FillHours; end; end; procedure TFrmAdvertisingConfig.btnEditClick(Sender: TObject); begin pnlFilter.Visible := False; pnlNewAdveritising.Visible := True; btnAddAdveritising.Caption := 'Save'; btnAddAdveritising.Tag := 1; with DM.cdsAdvertising do begin Filtered := False; Filter := ''; end; with DM.cdsAdvertising do if not (State in [dsEdit, dsInsert]) then begin Edit; SetWeekDayList(FieldByName('DaysOfWeek').AsString); SetHourList(FieldByName('Hours').AsString); end; end; end.
// Copyright (c) 2009, ConTEXT Project Ltd // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. unit uCustomHL; interface {$I ConTEXT.inc} uses Windows, SysUtils, Classes, Graphics, Forms, uCommon, SynEditHighlighter, SynHighlighterMyGeneral, JclFileUtils; type TCustHLDef = record Language :string; Filter :string; HelpFile :string; LineComment :string; CommentBeg :string; CommentEnd :string; BlockAutoindent :boolean; BlockBegStr :string; BlockEndStr :string; IdentifierChars :string; IdentifierBegChars :string; NumConstChars :string; NumConstBeg :string; Keywords1 :string; Keywords2 :string; Keywords3 :string; Keywords4 :string; Keywords5 :string; StringBegChars :string; StringEndChars :string; Description :string; EscapeChar :char; MultilineStrings :boolean; CaseSensitive :boolean; UsePreprocessor :boolean; CurrLineHighlighted :boolean; OverrideTxtFgColor :boolean; SpaceCol :TFgBg; Keyword1Col :TFgBg; Keyword1Attr :TFontStyles; Keyword2Col :TFgBg; Keyword2Attr :TFontStyles; Keyword3Col :TFgBg; Keyword3Attr :TFontStyles; Keyword4Col :TFgBg; Keyword4Attr :TFontStyles; Keyword5Col :TFgBg; Keyword5Attr :TFontStyles; IdentifierCol :TFgBg; IdentifierAttr :TFontStyles; CommentCol :TFgBg; CommentAttr :TFontStyles; NumberCol :TFgBg; NumberAttr :TFontStyles; StringCol :TFgBg; StringAttr :TFontStyles; SymbolCol :TFgBg; SymbolAttr :TFontStyles; PreprocessorCol :TFgBg; PreprocessorAttr :TFontStyles; SelectionCol :TFgBg; CurrentLineCol :TFgBg; MatchedBracesCol :TFgBg; dummyAttr :TFontStyles; end; pTCustHLDef = ^TCustHLDef; procedure LoadCustomHLFiles; function EnumCustomHL(var HL:TSynCustomHighlighter; var n:integer):boolean; procedure SaveCustomHLFile(pHL:pTHighLighter); procedure FreeCustomHighlighters; implementation type TToken = ( tkNONE, tkEOF, tkIDENT, tkKW_LANG, tkKW_FILTER, tkKW_COMMENTCOL, tkKW_ESCAPECHAR, tkKW_IDENTCHARS, tkKW_IDENTBEGCHARS, tkKW_IDENTCOL, tkKW_NUMCHARS, tkKW_NUMBEGCHARS, tkKW_KEYWORDS1, tkKW_KEYWORDS2, tkKW_KEYWORDS3, tkKW_KEYWORDS4, tkKW_KEYWORDS5, tkKW_KEYWORD1COL, tkKW_KEYWORD2COL, tkKW_KEYWORD3COL, tkKW_KEYWORD4COL, tkKW_KEYWORD5COL, tkKW_STRDELIMITERS, tkKW_SPACECOL, tkKW_STRINGCOL, tkKW_CURRENTLINEHL, tkKW_MATCHEDBRACESCOL, tkKW_SYMBOLCOL, tkKW_SELECTIONCOL, tkKW_CURRENTLINECOL, tkKW_USERPREPROC, tkKW_NUMBERCOL, tkKW_PREDPROCCOL, tkKW_HELPFILE, tkKW_CASESENSITIVE, tkKW_LINECOMMENT, tkKW_COMMENTBEG, tkKW_COMMENTEND, tkKW_STRINGBEGCHAR, tkKW_STRINGENDCHAR, tkKW_MULTILINESTRINGS, tkKW_OVERRIDETXTFGCOLOR, tkKW_BLOCKBEGSTR, tkKW_BLOCKENDSTR, tkKW_BLOCKAUTOINDENT, tkKW_DESCRIPTION ); var strCustomHL :TStringList; listCustomHL :TList; token :TToken; svalue :string; ptr :PChar; ptr_beg :PChar; const CUSTOM_HL_FILE_EXT = 'chl'; //////////////////////////////////////////////////////////////////////////////////////////// // HL functions //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ function EnumCustomHL(var HL:TSynCustomHighlighter; var n:integer):boolean; var ok :boolean; begin ok:=(n<listCustomHL.Count); if ok then begin HL:=TSynCustomHighlighter(listCustomHL[n]); inc(n); end; result:=ok; end; //------------------------------------------------------------------------------------------ procedure FreeCustomHighlighters; var i :integer; begin if Assigned(listCustomHL) then begin for i:=0 to listCustomHL.Count-1 do if Assigned(listCustomHL[i]) then TSynCustomHighlighter(listCustomHL[i]).Free; listCustomHL.Free; end; end; //------------------------------------------------------------------------------------------ procedure AddHL(SrcFileName:string; CHL:pTCustHLDef); var HL :TSynMyGeneralSyn; Attr :TSynHighlighterAttributes; function ExpandIdentCh(s:string):string; var ss :string; i, ii, n :integer; str :TStringList; begin str:=TStringList.Create; try str.Text:=PChar(s); for i:=0 to str.Count-1 do begin s:=str[i]; n:=Pos('..',s); if (n=2) and (Length(s)=4) then begin for ii:=ord(s[1]) to ord(s[4]) do ss:=ss+chr(ii); end else ss:=ss+s; end; finally str.Free; end; result:=ss; end; procedure SetAttrColor(HL:TSynMyGeneralSyn; AttrName:string; Fg, Bg:TColor); begin Attr:=HL.Attribute[FindAttrIndex(AttrName, HL)]; if Assigned(Attr) then begin if (Fg<>clNone) then Attr.Foreground:=Fg; if (Bg<>clNone) then Attr.Background:=Bg; end; end; begin HL:=TSynMyGeneralSyn.Create(nil); with HL do begin // general AddAdditionalToHighlighter(HL); LanguageName:=CHL^.Language; DefaultFilter:=CHL^.Filter; Description:=CHL^.Description; // colors CommentAttri.Foreground:=CHL^.CommentCol.Fg; CommentAttri.Background:=CHL^.CommentCol.Bg; IdentifierAttri.Foreground:=CHL^.IdentifierCol.Fg; IdentifierAttri.Background:=CHL^.IdentifierCol.Bg; KeyAttri1.Foreground:=CHL^.Keyword1Col.Fg; KeyAttri1.Background:=CHL^.Keyword1Col.Bg; KeyAttri2.Foreground:=CHL^.Keyword2Col.Fg; KeyAttri2.Background:=CHL^.Keyword2Col.Bg; KeyAttri3.Foreground:=CHL^.Keyword3Col.Fg; KeyAttri3.Background:=CHL^.Keyword3Col.Bg; KeyAttri4.Foreground:=CHL^.Keyword4Col.Fg; KeyAttri4.Background:=CHL^.Keyword4Col.Bg; KeyAttri5.Foreground:=CHL^.Keyword5Col.Fg; KeyAttri5.Background:=CHL^.Keyword5Col.Bg; NumberAttri.Foreground:=CHL^.NumberCol.Fg; NumberAttri.Background:=CHL^.NumberCol.Bg; PreprocessorAttri.Foreground:=CHL^.PreprocessorCol.Fg; PreprocessorAttri.Background:=CHL^.PreprocessorCol.Bg; SpaceAttri.Foreground:=CHL^.SpaceCol.Fg; SpaceAttri.Background:=CHL^.SpaceCol.Bg; StringAttri.Foreground:=CHL^.StringCol.Fg; StringAttri.Background:=CHL^.StringCol.Bg; SymbolAttri.Foreground:=CHL^.SymbolCol.Fg; SymbolAttri.Background:=CHL^.SymbolCol.Bg; // attributes CommentAttri.Style:=CHL^.CommentAttr; IdentifierAttri.Style:=CHL^.IdentifierAttr; KeyAttri1.Style:=CHL^.Keyword1Attr; KeyAttri2.Style:=CHL^.Keyword2Attr; KeyAttri3.Style:=CHL^.Keyword3Attr; KeyAttri4.Style:=CHL^.Keyword4Attr; KeyAttri5.Style:=CHL^.Keyword5Attr; NumberAttri.Style:=CHL^.NumberAttr; PreprocessorAttri.Style:=CHL^.PreprocessorAttr; StringAttri.Style:=CHL^.StringAttr; SymbolAttri.Style:=CHL^.SymbolAttr; // additional colors SetAttrColor(HL, ATTR_SELECTION_STR, CHL^.SelectionCol.Fg, CHL^.SelectionCol.Bg); SetAttrColor(HL, ATTR_CURRENT_LINE_STR, CHL^.CurrentLineCol.Fg, CHL^.CurrentLineCol.Bg); SetAttrColor(HL, ATTR_MATCHED_BRACES, CHL^.MatchedBracesCol.Fg, CHL^.MatchedBracesCol.Bg); //!! ed.memo.RightEdgeColor:=HL.Attribute[FindAttrIndex(ATTR_RIGHTEDGE_STR,HL)].Foreground; while (Pos(' ',CHL^.StringBegChars)>0) do Delete(CHL^.StringBegChars, Pos(' ',CHL^.StringBegChars),1); while (Pos(' ',CHL^.StringEndChars)>0) do Delete(CHL^.StringEndChars, Pos(' ',CHL^.StringEndChars),1); // other IdentifierChars:=ExpandIdentCh(CHL^.IdentifierChars); IdentifierBegChars:=ExpandIdentCh(CHL^.IdentifierBegChars); NumConstChars:=ExpandIdentCh(CHL^.NumConstChars); NumBegChars:=ExpandIdentCh(CHL^.NumConstBeg); DetectPreprocessor:=CHL^.UsePreprocessor; CaseSensitive:=CHL^.CaseSensitive; CurrLineHighlighted:=CHL^.CurrLineHighlighted; OverrideTxtFgColor:=CHL^.OverrideTxtFgColor; HelpFile:=CHL^.HelpFile; SetCommentStrings(CHL^.LineComment, CHL^.CommentBeg, CHL^.CommentEnd); SetStringParams(CHL^.StringBegChars, CHL^.StringEndChars, CHL^.MultilineStrings); EscapeChar:=CHL^.EscapeChar; BlockAutoindent:=CHL^.BlockAutoindent; BlockBegStr:=CHL^.BlockBegStr; BlockEndStr:=CHL^.BlockEndStr; // keywords if CaseSensitive then begin HL.Keywords1.Text:=CHL^.Keywords1; HL.Keywords2.Text:=CHL^.Keywords2; HL.Keywords3.Text:=CHL^.Keywords3; HL.Keywords4.Text:=CHL^.Keywords4; HL.Keywords5.Text:=CHL^.Keywords5; end else begin HL.Keywords1.Text:=UpperCase(CHL^.Keywords1); HL.Keywords2.Text:=UpperCase(CHL^.Keywords2); HL.Keywords3.Text:=UpperCase(CHL^.Keywords3); HL.Keywords4.Text:=UpperCase(CHL^.Keywords4); HL.Keywords5.Text:=UpperCase(CHL^.Keywords5); end; end; HL.SourceFileName:=SrcFileName; HL.MakeMethodTables; listCustomHL.Add(HL); end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // Parse functions //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ function CheckIsKeyword(var svalue:string; var token:TToken):boolean; var old_tok :TToken; begin old_tok:=token; if (Length(svalue)>0) and (svalue[Length(svalue)]=':') then begin SetLength(svalue,Length(svalue)-1); if (Length(svalue)>0) then begin case (svalue[1]) of 'B': if (svalue='BlockCommentBeg') then token:=tkKW_COMMENTBEG else if (svalue='BlockBegStr') then token:=tkKW_BLOCKBEGSTR else if (svalue='BlockEndStr') then token:=tkKW_BLOCKENDSTR else if (svalue='BlockCommentEnd') then token:=tkKW_COMMENTEND else if (svalue='BlockAutoindent') then token:=tkKW_BLOCKAUTOINDENT; 'L': if (svalue='Language') then token:=tkKW_LANG else if (svalue='LineComment') then token:=tkKW_LINECOMMENT; 'E': if (svalue='EscapeChar') then token:=tkKW_ESCAPECHAR; 'F': if (svalue='Filter') then token:=tkKW_FILTER; 'C': if (svalue='CommentCol') then token:=tkKW_COMMENTCOL else if (svalue='CurrentLineCol') then token:=tkKW_CURRENTLINECOL else if (svalue='CurrLineHighlighted') then token:=tkKW_CURRENTLINEHL else if (svalue='CaseSensitive') then token:=tkKW_CASESENSITIVE; 'D': if (svalue='Description') then token:=tkKW_DESCRIPTION; 'H': if (svalue='HelpFile') then token:=tkKW_HELPFILE; 'I': if (svalue='IdentifierChars') then token:=tkKW_IDENTCHARS else if (svalue='IdentifierBegChars') then token:=tkKW_IDENTBEGCHARS else if (svalue='IdentifierCol') then token:=tkKW_IDENTCOL; 'K': if (svalue='KeyWords1') then token:=tkKW_KEYWORDS1 else if (svalue='Keyword1Col') then token:=tkKW_KEYWORD1COL else if (svalue='KeyWords2') then token:=tkKW_KEYWORDS2 else if (svalue='Keyword2Col') then token:=tkKW_KEYWORD2COL else if (svalue='KeyWords3') then token:=tkKW_KEYWORDS3 else if (svalue='Keyword3Col') then token:=tkKW_KEYWORD3COL else if (svalue='KeyWords4') then token:=tkKW_KEYWORDS4 else if (svalue='Keyword4Col') then token:=tkKW_KEYWORD4COL else if (svalue='KeyWords5') then token:=tkKW_KEYWORDS5 else if (svalue='Keyword5Col') then token:=tkKW_KEYWORD5COL; 'M': if (svalue='MultilineStrings') then token:=tkKW_MULTILINESTRINGS else if (svalue='MatchedBracesCol') then token:=tkKW_MATCHEDBRACESCOL; 'O': if (svalue='OverrideTxtFgColor') then token:=tkKW_OVERRIDETXTFGCOLOR; 'S': if (svalue='StringBegChar') then token:=tkKW_STRINGBEGCHAR else if (svalue='StringEndChar') then token:=tkKW_STRINGENDCHAR else if (svalue='SpaceCol') then token:=tkKW_SPACECOL else if (svalue='StringCol') then token:=tkKW_STRINGCOL else if (svalue='SymbolCol') then token:=tkKW_SYMBOLCOL else if (svalue='SelectionCol') then token:=tkKW_SELECTIONCOL; 'U': if (svalue='UsePreprocessor') then token:=tkKW_USERPREPROC; 'N': if (svalue='NumberCol') then token:=tkKW_NUMBERCOL else if (svalue='NumConstChars') then token:=tkKW_NUMCHARS else if (svalue='NumConstBegChars') then token:=tkKW_NUMBEGCHARS; 'P': if (svalue='PreprocessorCol') then token:=tkKW_PREDPROCCOL; end; end; end; result:=(token<>old_tok); end; //------------------------------------------------------------------------------------------ procedure lex; label Error; function NextNonBlankChar:char; var ptr_ :PChar; begin ptr_:=ptr; repeat inc(ptr_) until ((ptr_^>' ') or (ptr_^=#0)); result:=ptr_^; end; begin // skip blanks while (ptr^<>#0) do begin if (ptr^>' ') then break; inc(ptr); end; // skip EOL while ((ptr^) in [#13,#10]) do inc(ptr); // check EOF if (ptr^=#0) then begin token:=tkEOF; EXIT; end; // komentar, ali samo ako je na početku linije if ((ptr^='/') and ((ptr+1)^='/')) and ((ptr=ptr_beg) or ((ptr-1)^=#10)) then begin while (not (ptr^ in [#13,#10,#00])) do inc(ptr); lex; EXIT; end; // match identifiers svalue := ptr^; inc(ptr); while (not (ptr^ in [' ',#09,#13,#10,#00])) do begin svalue := svalue + ptr^; inc(ptr); end; token := tkIDENT; if (Length(svalue)>0) and (svalue[Length(svalue)]=':') then CheckIsKeyword(svalue, token); EXIT; end; //------------------------------------------------------------------------------------------ procedure InitCHL(CHL:pTCustHLDef); procedure ResetColor(var FgBg:TFgBg); begin FgBg.Fg:=clWindowText; FgBg.Bg:=clWindow; end; begin FillChar(CHL^, SizeOf(TCustHLDef), 0); with CHL^ do begin ResetColor(SpaceCol); ResetColor(Keyword1Col); ResetColor(Keyword2Col); ResetColor(Keyword3Col); ResetColor(Keyword4Col); ResetColor(Keyword5Col); ResetColor(IdentifierCol); ResetColor(CommentCol); ResetColor(NumberCol); ResetColor(StringCol); ResetColor(SymbolCol); ResetColor(PreprocessorCol); ResetColor(SelectionCol); ResetColor(CurrentLineCol); ResetColor(MatchedBracesCol); end; end; //------------------------------------------------------------------------------------------ procedure Parse(SrcFileName:string); var CHL :TCustHLDef; IsFirst :boolean; function GetColor(var Attr:TFontStyles):TFgBg; begin result.Fg:=clNone; result.Bg:=clNone; // Foreground lex; if (token=tkIDENT) then try result.Fg:=StringToColor(svalue); except end; // Background lex; if (token=tkIDENT) then try result.Bg:=StringToColor(svalue); except end; lex; if (token=tkIDENT) then begin Attr:=[]; svalue:=UpperCase(svalue); if (Pos('B',svalue)>0) then Include(Attr,fsBold); if (Pos('I',svalue)>0) then Include(Attr,fsItalic); if (Pos('U',svalue)>0) then Include(Attr,fsUnderline); if (Pos('S',svalue)>0) then Include(Attr,fsStrikeOut); end; end; function GetKeywords:string; begin result:=''; repeat lex; if (token=tkIDENT) then begin result:=result+svalue+#13#10; end; until (token<>tkIDENT); if (Length(result)>0) then SetLength(result,Length(result)-2); end; function GetParams:string; begin result:=''; repeat lex; if (token=tkIDENT) then begin result:=result+svalue+' '; end; until (token<>tkIDENT); if (Length(result)>0) then SetLength(result,Length(result)-1); end; function GetParamsToEOL:string; begin result:=''; while (ptr^ in [' ',#09]) do inc(ptr); while (not (ptr^ in [#13,#10,#0])) do begin result:=result+ptr^; inc(ptr); end; result:=Trim(result); token:=tkNONE; end; function GetChar:char; var s :string; begin s:=GetParamsToEOL; if (Length(s)>0) then result:=s[1] else result:=#255; end; function GetInt:integer; begin lex; result:=StrToIntDef(svalue, 0); end; function GetBool: boolean; begin lex; result:=StrToIntDef(svalue, 0)<>0; end; begin IsFirst:=TRUE; repeat if (token in [tkNONE, tkEOF, tkIDENT]) then lex; case token of tkKW_LANG: begin if not IsFirst and (Length(CHL.Language)>0) then AddHL(SrcFileName,@CHL); InitCHL(@CHL); CHL.Language:=GetParams; IsFirst:=FALSE; end; tkKW_FILTER: CHL.Filter:=GetParams; tkKW_DESCRIPTION: CHL.Description:=GetParamsToEOL; tkKW_HELPFILE: CHL.HelpFile:=GetParams; tkKW_CASESENSITIVE: CHL.CaseSensitive:=GetBool; tkKW_LINECOMMENT: CHL.LineComment:=GetParamsToEOL; tkKW_COMMENTBEG: CHL.CommentBeg:=GetParamsToEOL; tkKW_COMMENTEND: CHL.CommentEnd:=GetParamsToEOL; tkKW_BLOCKAUTOINDENT: CHL.BlockAutoindent:=GetBool; tkKW_BLOCKBEGSTR: CHL.BlockBegStr:=GetParamsToEOL; tkKW_BLOCKENDSTR: CHL.BlockEndStr:=GetParamsToEOL; tkKW_STRINGBEGCHAR: CHL.StringBegChars:=GetParamsToEOL; tkKW_STRINGENDCHAR: CHL.StringEndChars:=GetParamsToEOL; tkKW_MULTILINESTRINGS: CHL.MultilineStrings:=GetBool; tkKW_IDENTCHARS: CHL.IdentifierChars:=GetKeywords; tkKW_IDENTBEGCHARS: CHL.IdentifierBegChars:=GetKeywords; tkKW_NUMCHARS: CHL.NumConstChars:=GetKeywords; tkKW_NUMBEGCHARS: CHL.NumConstBeg:=GetKeywords; tkKW_ESCAPECHAR: CHL.EscapeChar:=GetChar; tkKW_KEYWORDS1: CHL.Keywords1:=GetKeywords; tkKW_KEYWORDS2: CHL.Keywords2:=GetKeywords; tkKW_KEYWORDS3: CHL.Keywords3:=GetKeywords; tkKW_KEYWORDS4: CHL.Keywords4:=GetKeywords; tkKW_KEYWORDS5: CHL.Keywords5:=GetKeywords; tkKW_USERPREPROC: CHL.UsePreprocessor:=GetBool; tkKW_COMMENTCOL: CHL.CommentCol:=GetColor(CHL.CommentAttr); tkKW_IDENTCOL: CHL.IdentifierCol:=GetColor(CHL.IdentifierAttr); tkKW_KEYWORD1COL: CHL.Keyword1Col:=GetColor(CHL.Keyword1Attr); tkKW_KEYWORD2COL: CHL.Keyword2Col:=GetColor(CHL.Keyword2Attr); tkKW_KEYWORD3COL: CHL.Keyword3Col:=GetColor(CHL.Keyword3Attr); tkKW_KEYWORD4COL: CHL.Keyword4Col:=GetColor(CHL.Keyword4Attr); tkKW_KEYWORD5COL: CHL.Keyword5Col:=GetColor(CHL.Keyword5Attr); tkKW_SPACECOL: CHL.SpaceCol:=GetColor(CHL.dummyAttr); tkKW_STRINGCOL: CHL.StringCol:=GetColor(CHL.StringAttr); tkKW_SYMBOLCOL: CHL.SymbolCol:=GetColor(CHL.SymbolAttr); tkKW_SELECTIONCOL: CHL.SelectionCol:=GetColor(CHL.dummyAttr); tkKW_NUMBERCOL: CHL.NumberCol:=GetColor(CHL.NumberAttr); tkKW_PREDPROCCOL: CHL.PreprocessorCol:=GetColor(CHL.PreprocessorAttr); tkKW_CURRENTLINECOL: CHL.CurrentLineCol:=GetColor(CHL.dummyAttr); tkKW_MATCHEDBRACESCOL: CHL.MatchedBracesCol:=GetColor(CHL.dummyAttr); tkKW_CURRENTLINEHL: CHL.CurrLineHighlighted:=GetBool; tkKW_OVERRIDETXTFGCOLOR: CHL.OverrideTxtFgColor:=GetBool; end; until (token in [tkEOF]); if (Length(CHL.Language)>0) then AddHL(SrcFileName,@CHL); end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // Load functions //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ function EnumAllCustomHLFiles(path:string):TStringList; var F :TSearchRec; ok :boolean; ss :TStringList; begin ss:=TStringList.Create; path:=PathAddSeparator(path); ok:=FindFirst(path+'*.'+CUSTOM_HL_FILE_EXT,faAnyFile,F)=0; if ok then begin repeat ss.Add(path+F.FindData.cFileName); // uzmi long filename ok:=FindNext(F)=0; until not ok; end; SysUtils.FindClose(F); result:=ss; end; //------------------------------------------------------------------------------------------ procedure LoadCustomHLFiles; var ss :TStringList; strCustomHL :TStringList; i :integer; fname :string; begin ss:=EnumAllCustomHLFiles(ApplicationDir+'Highlighters'); listCustomHL:=TList.Create; strCustomHL:=TStringList.Create; try for i:=0 to ss.Count-1 do begin try strCustomHL.LoadFromFile(ss[i]); fname:=ss[i]; ptr:=PChar(strCustomHL.Text); ptr_beg:=ptr; Parse(fname); except DlgErrorOpenFile(ss[i]); end; end; finally strCustomHL.Free; ss.Free; end; end; //------------------------------------------------------------------------------------------ procedure SaveCustomHLFile(pHL:pTHighLighter); var HL :TSynMyGeneralSyn; ss :TStringList; const VALUE_TAB = 25; function LoadFile:boolean; begin try ss.LoadFromFile(HL.SourceFileName); result:=TRUE; except DlgErrorOpenFile(HL.SourceFileName); result:=FALSE; end; end; function SaveFile:boolean; begin try ss.SaveToFile(HL.SourceFileName); result:=TRUE; except DlgErrorSaveFile(HL.SourceFileName); result:=FALSE; end; end; function FindParameterLine(KeyName:string):integer; var i :integer; kword :string; p :PChar; begin result:=-1; i:=0; while (i<ss.Count) do begin p:=PChar(ss[i]); if not (p^ in [#0,'/']) then begin kword:=''; while not (p^ in [':',#0,#13,#10]) do begin kword:=kword+p^; inc(p); end; if (kword=KeyName) then begin result:=i; BREAK; end; end; inc(i); end; end; procedure SetKeyValue(KeyName:string; Value:string); var n :integer; s :string; begin n:=FindParameterLine(KeyName); s:=KeyName+':'; while (Length(s)<VALUE_TAB-1) do s:=s+' '; s:=TrimRight(s+Value); if (n>-1) then ss[n]:=s else ss.Add(s); end; procedure SetColorAttr(KeyName:string; Attr:TSynHighlighterAttributes); function GetFontAttr(fs:TFontStyles):string; begin result:=''; if (fsBold in fs) then result:=result+'B'; if (fsItalic in fs) then result:=result+'I'; if (fsUnderline in fs) then result:=result+'U'; if (fsStrikeOut in fs) then result:=result+'S'; end; begin if Assigned(Attr) then SetKeyValue(KeyName, ColorToString(Attr.Foreground)+' '+ColorToString(Attr.Background)+' '+GetFontAttr(Attr.Style)); end; begin if not (Assigned(pHL) and Assigned(pHL^.HL) and (pHL^.HL is TSynMyGeneralSyn)) then EXIT; HL:=(pHL^.HL as TSynMyGeneralSyn); ss:=TStringList.Create; if LoadFile then begin SetKeyValue('Filter', pHL^.HL.DefaultFilter); SetKeyValue('HelpFile',pHL^.HelpFile); SetKeyValue('CurrLineHighlighted',IntToStr(integer(pHL^.ColorCurrentLine))); SetKeyValue('OverrideTxtFgColor',IntToStr(integer(pHL^.OverrideTxtFgColor))); SetKeyValue('BlockAutoindent',IntToStr(integer(pHL^.BlockAutoindent))); SetKeyValue('BlockBegStr',pHL^.BlockBegStr); SetKeyValue('BlockEndStr',pHL^.BlockEndStr); SetColorAttr('SpaceCol', HL.SpaceAttri); SetColorAttr('Keyword1Col', HL.KeyAttri1); SetColorAttr('Keyword2Col', HL.KeyAttri2); SetColorAttr('Keyword3Col', HL.KeyAttri3); SetColorAttr('Keyword4Col', HL.KeyAttri4); SetColorAttr('Keyword5Col', HL.KeyAttri5); SetColorAttr('IdentifierCol', HL.IdentifierAttri); SetColorAttr('CommentCol', HL.CommentAttri); SetColorAttr('NumberCol', HL.NumberAttri); SetColorAttr('StringCol', HL.StringAttri); SetColorAttr('SymbolCol', HL.SymbolAttri); SetColorAttr('PreprocessorCol', HL.PreprocessorAttri); SetColorAttr('SelectionCol', HL.Attribute[FindAttrIndex(ATTR_SELECTION_STR, HL)]); SetColorAttr('CurrentLineCol', HL.Attribute[FindAttrIndex(ATTR_CURRENT_LINE_STR, HL)]); SetColorAttr('MatchedBracesCol', HL.Attribute[FindAttrIndex(ATTR_MATCHED_BRACES, HL)]); SaveFile; end; ss.Free; end; //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ initialization finalization if Assigned(strCustomHL) then strCustomHL.Free; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Data.DB, Data.Win.ADODB, SportFrm; type TForm1 = class(TSportForm) Connection1: TADOConnection; Query1: TADOQuery; protected procedure LoadSports; override; end; var Form1: TForm1; implementation {$R *.dfm} uses Sport, NtBase, NtLocalization; procedure TForm1.LoadSports; function GetLanguageCode: String; begin if LoadedResourceLocale = '' then Result := 'en' else Result := TNtLocale.LocaleToIso639(TNtLocale.ExtensionToLocale(LoadedResourceLocale)); end; begin // Load sport data from a database Connection1.Connected := True; Query1.Close; Query1.SQL.Text := Format('SELECT * FROM Sport WHERE Lang=''%s''', [GetLanguageCode]); Query1.Open; FSports.LoadDatabase(Query1); end; end.
{: Using the GLBumpShader for object space bump mapping.<p> The bump shader runs an ambient light pass and a pass for each light shining in the scene. There are currently 2 bump methods: a dot3 texture combiner and a basic ARB fragment program.<p> The dot3 texture combiner only supports diffuse lighting but is fast and works on lower end graphics adapters.<p> The basic ARBFP method supports diffuse and specular lighting<p> Both methods pick up the light and material options through the OpenGL state.<p> The normal map is expected as the primary texture.<p> Diffuse textures are supported through the secondary texture and can be enabled using the boDiffuseTexture2 bump option.<p> Specular textures are supported through the tertiary texture and can be enabled using the boSpecularTexture3 bump option and setting the SpecularMode to smBlinn or smPhong (smOff will disable specular in the shader).<p> With the boLightAttenutation flag set the shader will use the OpenGL light attenuation coefficients when calculating light intensity.<p> } unit Unit1; interface uses SysUtils, Classes, Graphics, Controls, Forms, Dialogs, GLObjects, GLTexture, GLBumpShader, GLScene, GLVectorFileObjects, GLCadencer, GLLCLViewer, ExtCtrls, StdCtrls, GLAsyncTimer, GLCrossPlatform, GLMaterial, GLCoordinates; type TForm1 = class(TForm) GLSceneViewer1: TGLSceneViewer; GLScene1: TGLScene; GLCadencer1: TGLCadencer; GLMaterialLibrary1: TGLMaterialLibrary; Camera: TGLCamera; WhiteLight: TGLLightSource; Bunny: TGLFreeForm; RedLight: TGLLightSource; BlueLight: TGLLightSource; GLBumpShader1: TGLBumpShader; Panel1: TPanel; ComboBox1: TComboBox; Label1: TLabel; GroupBox1: TGroupBox; CheckBox1: TCheckBox; CheckBox2: TCheckBox; CheckBox3: TCheckBox; Shape1: TShape; Shape2: TShape; Shape3: TShape; ColorDialog1: TColorDialog; DCLights: TGLDummyCube; AsyncTimer1: TGLAsyncTimer; CheckBox4: TCheckBox; ComboBox2: TComboBox; Label2: TLabel; procedure FormCreate(Sender: TObject); procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); procedure ShapeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); procedure CheckBoxClick(Sender: TObject); procedure AsyncTimer1Timer(Sender: TObject); procedure ComboBox1Change(Sender: TObject); procedure FormResize(Sender: TObject); procedure GLSceneViewer1BeforeRender(Sender: TObject); procedure ComboBox2Change(Sender: TObject); private { Private declarations } public { Public declarations } mx, my, dx, dy: integer; IsInitialized: boolean; StartHeight: integer; end; var Form1: TForm1; implementation {$R *.lfm} uses GLVectorGeometry, GLContext, GLUtils; procedure TForm1.FormCreate(Sender: TObject); begin SetGLSceneMediaDir(); // Load the bunny mesh and scale for viewing Bunny.LoadFromFile('bunny.glsm'); Bunny.Scale.Scale(2 / Bunny.BoundingSphereRadius); // Load the normal map with GLMaterialLibrary1.Materials[0].Material.Texture.Image do LoadFromFile('bunnynormals.jpg'); // Link the lights to their toggles CheckBox1.Tag := 0; CheckBox2.Tag := 1; CheckBox3.Tag := 2; Shape1.Tag := 0; Shape2.Tag := 1; Shape3.Tag := 2; ComboBox1.ItemIndex := 0; ComboBox1Change(nil); StartHeight := Height; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); begin // Orbit the camera if (dx <> 0) or (dy <> 0) then begin Camera.MoveAroundTarget(dy, dx); dx := 0; dy := 0; end; // Rotate the light sources if CheckBox4.Checked then DCLights.Turn(deltaTime * 20); GLSceneViewer1.Invalidate; end; procedure TForm1.CheckBoxClick(Sender: TObject); begin // Light Shining CheckBox case TCheckBox(Sender).Tag of 0: WhiteLight.Shining := TCheckBox(Sender).Checked; 1: RedLight.Shining := TCheckBox(Sender).Checked; 2: BlueLight.Shining := TCheckBox(Sender).Checked; end; end; procedure TForm1.ShapeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); begin // Light Color Dialog ColorDialog1.Color := TShape(Sender).Brush.Color; if ColorDialog1.Execute then begin TShape(Sender).Brush.Color := ColorDialog1.Color; case TShape(Sender).Tag of 0: WhiteLight.Diffuse.AsWinColor := ColorDialog1.Color; 1: RedLight.Diffuse.AsWinColor := ColorDialog1.Color; 2: BlueLight.Diffuse.AsWinColor := ColorDialog1.Color; end; end; end; procedure TForm1.ComboBox1Change(Sender: TObject); begin if ComboBox1.Text = 'Per-Vertex' then Bunny.Material.LibMaterialName := '' else if ComboBox1.Text = 'Dot3 Texture Combiner' then begin Bunny.Material.LibMaterialName := 'Bump'; GLBumpShader1.BumpMethod := bmDot3TexCombiner; end else if ComboBox1.Text = 'Basic Fragment Program' then begin Bunny.Material.LibMaterialName := 'Bump'; GLBumpShader1.BumpMethod := bmBasicARBFP; end; end; procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); begin mx := x; my := y; dx := 0; dy := 0; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer); begin if ssLeft in Shift then begin dx := dx + (mx - x); dy := dy + (my - y); end else begin dx := 0; dy := 0; end; mx := x; my := y; end; procedure TForm1.AsyncTimer1Timer(Sender: TObject); begin Form1.Caption := 'GLBumpShader Demo - ' + GLSceneViewer1.FramesPerSecondText; GLSceneViewer1.ResetPerformanceMonitor; end; procedure TForm1.FormResize(Sender: TObject); begin Camera.SceneScale := Height / StartHeight; end; procedure TForm1.GLSceneViewer1BeforeRender(Sender: TObject); begin if IsInitialized then exit; if GL.ARB_multitexture and GL.ARB_vertex_program and GL.ARB_texture_env_dot3 then ComboBox1.Items.Add('Dot3 Texture Combiner'); if GL.ARB_multitexture and GL.ARB_vertex_program and GL.ARB_fragment_program then begin ComboBox1.Items.Add('Basic Fragment Program'); if GLSceneViewer1.Buffer.LimitOf[limNbTextureUnits] < 3 then GLBumpShader1.SpecularMode := smOff; end; IsInitialized := True; end; procedure TForm1.ComboBox2Change(Sender: TObject); begin case ComboBox2.ItemIndex of 0: GLBumpShader1.SpecularMode := smOff; 1: GLBumpShader1.SpecularMode := smBlinn; 2: GLBumpShader1.SpecularMode := smPhong; end; end; end.
unit uOperationSystem; interface uses Windows, SysUtils; type // added osVista and osW7 by Antonio. TOSVersion = (osUnknown, os95, os95OSR2, os98, os98SE, osME, osNT3, osNT4, os2K, osXP, osVista, osW7); function GetOS(var BuildInfo:String): TOSVersion; implementation function GetOS(var BuildInfo:String): TOSVersion; var OS: TOSVersionInfo; begin ZeroMemory(@OS,SizeOf(OS)); OS.dwOSVersionInfoSize := SizeOf(OS); GetVersionEx(OS); Result := osUnknown; if OS.dwPlatformId = VER_PLATFORM_WIN32_NT then case OS.dwMajorVersion of 3: Result := osNT3; 4: Result := osNT4; 5: begin case OS.dwMinorVersion of 0: Result:= os2K; end; end; 6: begin case OS.dwMinorVersion of 0: result := osVista; 1: result := osW7; end; end; end else if (OS.dwMajorVersion = 4) and (OS.dwMinorVersion = 0) then begin Result := os95; if (Trim(OS.szCSDVersion) = 'B') then Result := os95OSR2; end else if (OS.dwMajorVersion = 4) and (OS.dwMinorVersion = 10) then begin Result := os98; if Trim(OS.szCSDVersion) = 'A' then Result := os98SE; end else if (OS.dwMajorVersion = 4) and (OS.dwMinorVersion = 90) then begin Result := osME; end; BuildInfo := Format('%d.%.2d.%d', [OS.dwMajorVersion, OS.dwMinorVersion, OS.dwBuildNumber and $FFFF]); end; end.
//------------------------------------------------------------------------------ //InterServer UNIT //------------------------------------------------------------------------------ // What it does- // The Inter Server. // Contains the brunt of the Inter and packet processes. // // Changes - // December 17th, 2006 - RaX - Created Header. // [2007/03/28] CR - Cleaned up uses clauses, using Icarus as a guide. // June 28th, 2008 - Tsusai - Updated GetPacketLength to PacketDB.GetLength // in various calls // //------------------------------------------------------------------------------ unit InterServer; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} Classes, SysUtils, {Project} GMCommands, InterOptions, PacketTypes, ZoneServerInfo, {3rd Party} IdContext, List32, Server ; type (*= CLASS =====================================================================* TInterServer *------------------------------------------------------------------------------* Overview: *------------------------------------------------------------------------------* Acts as the Inter-server that message passes and brokers between Zone(Game) servers. It handles anything that communicates between zones, IE:: Whisper chat, guild chat, party chat, GM Commands, etc. [2007/05/19] CR - TODO: Someone with more knowledge of the overall workings should mention which tasks the InterServer is charged with. What specific things is the InterServer responsible for? [2007/05/21] RaX - Added small description addition. *------------------------------------------------------------------------------* Revisions: *------------------------------------------------------------------------------* (Format: [yyyy/mm/dd] <Author> - <Description of Change>) [2007/05/19] CR - Added class header. Removed private section - all private fields and methods are now protected. Added properties ClientList, ZoneServerInfo, and ZoneServerLink to encapsulate the lookup and casting dirty work to shield it from other TInterServer routines. Lends clarity to code that used to do the casting work in-situ. *=============================================================================*) TInterServer = class(TServer) protected fZoneServerList : TIntList32; Procedure OnDisconnect(AConnection: TIdContext);override; Procedure OnExecute(AConnection: TIdContext);override; Procedure OnException(AConnection: TIdContext; AException: Exception);override; procedure OnConnect(AConnection: TIdContext);override; Function GetZoneServerInfo( const Index : Integer ) : TZoneServerInfo; Function GetZoneServerLink( const Index : Integer ) : TZoneServerLink; Procedure LoadOptions; procedure VerifyZoneServer( AClient : TIdContext; InBuffer : TBuffer ); public ServerName : String; Commands : TGMCommands; Options : TInterOptions; ClientList : TList; Instances : TStringList; InstanceZones : TList; Constructor Create; Destructor Destroy;Override; Procedure Start;override; Procedure Stop;override; property ZoneServerList : TIntList32 read fZoneServerList; property ZoneServerInfo[const Index : Integer] : TZoneServerInfo read GetZoneServerInfo; {[2007/05/19] CR - N.B.: This is the link held in the fClientList NOT the objects held in fZoneServerList! } property ZoneServerLink[const Index : Integer] : TZoneServerLink read GetZoneServerLink; End;(* TInterServer *== CLASS ====================================================================*) implementation uses {RTL/VCL} StrUtils, {Project} //none BufferIO, Globals, Main, TCPServerRoutines, ZoneInterCommunication, InterRecv {3rd Party} //none ; //------------------------------------------------------------------------------ //Create () CONSTRUCTOR //------------------------------------------------------------------------------ // What it does- // Initializes our inter server // // Changes - // September 19th, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ Constructor TInterServer.Create; begin Inherited; Commands := TGMCommands.Create; fZoneServerList := TIntList32.Create; ClientList := TList.Create; Instances := TStringList.Create; Instances.Duplicates := dupAccept; //Record zones that allow instance InstanceZones := TList.Create; end;{Create} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Destroy() DESTRUCTOR //------------------------------------------------------------------------------ // What it does- // Destroys our inter server // // Changes - // September 19th, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ Destructor TInterServer.Destroy; begin fZoneServerList.Free; ClientList.Free; Commands.Free; Instances.Free; InstanceZones.Free; Inherited; end;{Destroy} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //OnConnect EVENT //------------------------------------------------------------------------------ // What it does- // An event which fires when a zone server connects to the inter. // // Changes - // March 18th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ procedure TInterServer.OnConnect(AConnection: TIdContext); begin ClientList.Add(AConnection); end;{OnDisconnect} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //OnDisconnect() EVENT //------------------------------------------------------------------------------ // What it does- // An event which fires when a zone server disconnects from the inter. // // Changes - // November 29th, 2006 - RaX - Created. // //------------------------------------------------------------------------------ procedure TInterServer.OnDisconnect(AConnection: TIdContext); var Index : integer; AZoneServInfo : TZoneServerInfo; begin if AConnection.Data is TZoneServerLink then begin AZoneServInfo := TZoneServerLink(AConnection.Data).Info; Index := Instances.IndexOfObject(AConnection.Data); while Index > -1 do begin Instances.Delete(Index); Index := Instances.IndexOfObject(AConnection.Data); end; Index := InstanceZones.IndexOf(AConnection.Data); if Index > -1 then begin InstanceZones.Delete(Index); end; Index := fZoneServerList.IndexOfObject(AZoneServInfo); if not (Index = -1) then begin fZoneServerList.Delete(Index); end; AConnection.Data.Free; AConnection.Data:=nil; end; ClientList.Delete(ClientList.IndexOf(AConnection)); end;{OnDisconnect} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //OnException EVENT //------------------------------------------------------------------------------ // What it does- // Handles Socket exceptions gracefully by outputting the exception message // and then disconnecting the client. // // Changes - // September 19th, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TInterServer.OnException(AConnection: TIdContext; AException: Exception); begin if AnsiContainsStr(AException.Message, '10053') or AnsiContainsStr(AException.Message, '10054') then begin AConnection.Connection.Disconnect; end; end;{OnException} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Start() PROCEDURE //------------------------------------------------------------------------------ // What it does- // Enables the Inter server to accept incoming connections // // Changes - // September 19th, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ Procedure TInterServer.Start(); begin if NOT Started then begin inherited; LoadOptions; Port := Options.Port; ActivateServer('Inter',TCPServer, Options.IndySchedulerType, Options.IndyThreadPoolSize); end else begin Console.Message('Cannot Start():: Inter Server already running!', 'Inter Server', MS_ALERT); end; end;{Start} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Stop() PROCEDURE //------------------------------------------------------------------------------ // What it does- // Stops the Inter server from accepting incoming connections // // Changes - // September 19th, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ Procedure TInterServer.Stop(); begin if Started then begin DeActivateServer('Inter',TCPServer); Options.Save; Options.Free; inherited; end else begin Console.Message('Cannot Start():: Inter Server not running.', 'Inter Server', MS_ALERT); end; end;{Start} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ParseInterServ PROCEDURE //------------------------------------------------------------------------------ // What it does- // Root procedure to handling client connections to the Inter Server. // // Changes - // March 18th, 2007 - RaX - Created. // April 26th, 2007 - Aeomin - added packet 0x2208 support // //------------------------------------------------------------------------------ procedure TInterServer.OnExecute(AConnection : TIdContext); var ABuffer : TBuffer; PacketID : Word; Size : Word; begin RecvBuffer(AConnection,ABuffer,2); PacketID := BufferReadWord(0, ABuffer); if AConnection.Data is TZoneServerLink then begin case PacketID of $2202: // Zone Server sending new WAN location details begin RecvBuffer(AConnection,ABuffer[2],2); Size := BufferReadWord(2,ABuffer); RecvBuffer(AConnection,ABuffer[4],Size-4); TZoneServerLink(AConnection.Data).Info.WAN := BufferReadString(4,Size-4,ABuffer); Console.Message('Received updated Zone Server WANIP.', 'Inter Server', MS_NOTICE); end; $2203: // Zone Server sending new LAN location details begin RecvBuffer(AConnection,ABuffer[2],2); Size := BufferReadWord(2,ABuffer); RecvBuffer(AConnection,ABuffer[4],Size-4); TZoneServerLink(AConnection.Data).Info.LAN := BufferReadString(4,Size-4,ABuffer); Console.Message('Received updated Zone Server LANIP.', 'Inter Server', MS_NOTICE); end; $2204: // Zone Server sending new Online User count begin RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($2204)-2); //TZoneServerLink(AClient.Data).Info.OnlineUsers := BufferReadWord(2,ABuffer); Console.Message('Received updated Zone Server Online Users.', 'Inter Server', MS_NOTICE); end; $2205: // Zone server sending GM command to be sent to other servers + self begin RecvBuffer(AConnection,ABuffer[2],2); Size := BufferReadWord(2,ABuffer); RecvBuffer(AConnection,ABuffer[4],Size-4); RecvGMCommand(AConnection, ABuffer); end; $2207: // Zone server sending GM command result begin RecvBuffer(AConnection,ABuffer[2],2); Size := BufferReadWord(2,ABuffer); RecvBuffer(AConnection,ABuffer[4],Size-4); RecvGMCommandReply(AConnection, ABuffer); end; $2208: // Zone server sending Warp Request begin RecvBuffer(AConnection,ABuffer[2],2); Size := BufferReadWord(2,ABuffer); RecvBuffer(AConnection,ABuffer[4],Size-4); RecvZoneWarpRequest(AConnection, ABuffer); end; $2210: //Zone Server send Private Message begin RecvBuffer(AConnection,ABuffer[2],2); Size := BufferReadWord(2,ABuffer); RecvBuffer(AConnection,ABuffer[4],Size-4); RecvWhisper(AConnection, ABuffer); end; $2211: begin RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($2211)-2); RecvWhisperReply(AConnection, ABuffer); end; $2215: begin RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($2215)-2); RecvZoneRequestFriend(AConnection, ABuffer); end; $2217: begin RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($2217)-2); RecvZoneRequestFriendReply(AConnection, ABuffer); end; $2218: begin RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($2218)-2); RecvZonePlayerOnlineStatus(AConnection, ABuffer); end; $2220: begin RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($2220)-2); RecvZonePlayerOnlineReply(AConnection, ABuffer); end; $2222: begin RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($2222)-2); RecvZoneNewMailNotify(AConnection, ABuffer); end; $2224: //Request create instance map begin RecvBuffer(AConnection,ABuffer[2],2); Size := BufferReadWord(2,ABuffer); RecvBuffer(AConnection,ABuffer[4],Size-4); RecvZoneCreateInstanceMapRequest(AConnection, ABuffer); end; $2226: //Set allow instance begin RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($2226)-2); RecvSetAllowInstance(AConnection, ABuffer); end; $2228: //Instance created begin RecvBuffer(AConnection,ABuffer[2],2); Size := BufferReadWord(2,ABuffer); RecvBuffer(AConnection,ABuffer[4],Size-4); RecvInstanceCreated(AConnection, ABuffer); end; $2229: //Instance List begin RecvBuffer(AConnection,ABuffer[2],2); Size := BufferReadWord(2,ABuffer); RecvBuffer(AConnection,ABuffer[4],Size-4); RecvInstanceList(AConnection, ABuffer); end; $2230: //Destroy instance map begin RecvBuffer(AConnection,ABuffer[2],2); Size := BufferReadWord(2,ABuffer); RecvBuffer(AConnection,ABuffer[4],Size-4); RecvDeleteInstance(AConnection, ABuffer); end; else begin Console.Message('Unknown Inter Server Packet : ' + IntToHex(PacketID,4), 'Inter Server', MS_WARNING); end; end; end else begin case PacketID of $2200: // Zone Server Connection request begin RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($2200)-2); VerifyZoneServer(AConnection,ABuffer); end; else begin Console.Message('Unknown Inter Server Packet : ' + IntToHex(PacketID,4), 'Inter Server', MS_WARNING); end; end; end; end; {ParseCharaInterServ} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //LoadOptions PROCEDURE //------------------------------------------------------------------------------ // What it does- // Creates and Loads the inifile. // // Changes - // January 4th, 2007 - RaX - Created Header. // //------------------------------------------------------------------------------ Procedure TInterServer.LoadOptions; begin Options := TInterOptions.Create(MainProc.Options.ConfigDirectory+'/Inter.ini'); Options.Load; Options.Save; end;{LoadOptions} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //VerifyZoneServer PROCEDURE //------------------------------------------------------------------------------ // What it does- // Verify request connection from zone server // // Changes - // January 14th, 2007 - Tsusai - Added // January 20th, 2007 - Tsusai - Wrapped the console messages, now using // IdContext.Binding shortcut // March 12th, 2007 - Aeomin - Fix the header. // March 21st, 2007 - RaX - Copied here from Character server // //------------------------------------------------------------------------------ procedure TInterServer.VerifyZoneServer( AClient : TIdContext; InBuffer : TBuffer ); var Password : string; Validated : byte; ZServerInfo : TZoneServerInfo; ID : LongWord; begin Validated := 0; //Assume true Console.Message( 'Reading Zone Server connection from ' + AClient.Binding.PeerIP, 'Inter Server', MS_NOTICE ); ID := BufferReadLongWord(2,InBuffer); Password := BufferReadMD5(8,InBuffer); if (fZoneServerList.IndexOf(ID) > -1) then begin Console.Message('Zone Server failed verification. ID already in use.', 'Inter Server', MS_WARNING); Validated := 1; end; if (Password <> GetMD5(Options.Key)) then begin Console.Message('Zone Server failed verification. Invalid Security Key.', 'Inter Server', MS_WARNING); Validated := 2; end; if Validated = 0 then begin Console.Message('Zone Server connection validated.','Inter Server', MS_INFO); ZServerInfo := TZoneServerInfo.Create; ZServerInfo.Connection := AClient; ZServerInfo.ZoneID := ID; ZServerInfo.Port := BufferReadWord(6,InBuffer); AClient.Data := TZoneServerLink.Create(AClient); TZoneServerLink(AClient.Data).DatabaseLink := Database; TZoneServerLink(AClient.Data).Info := ZServerInfo; fZoneServerList.AddObject(ZServerInfo.ZoneID,ZServerInfo); end; SendValidateFlagToZone(AClient,Validated); end; //------------------------------------------------------------------------------ (*- Function ------------------------------------------------------------------* TInterServer.GetZoneServerInfo -------------------------------------------------------------------------------- Overview: -- Does the dirty work of casting the object held in the TZoneServerList -- Pre: Index must be in range of the fZoneServerList count. Post: TODO -- Revisions: -- (Format: [yyyy/mm/dd] <Author> - <Comment>) [2007/05/19] CR - Created routine. Property read handler for ZoneServerInfo. *-----------------------------------------------------------------------------*) Function TInterServer.GetZoneServerInfo( const Index : Integer ) : TZoneServerInfo; Begin //Pre Assert( (Index >= 0) AND (Index < fZoneServerList.Count), 'ZoneServerInfo Index out of bounds.' ); //-- Result := TZoneServerInfo(fZoneServerList.Objects[Index]); End;(* Func TInterServer.GetZoneServerInfo *-----------------------------------------------------------------------------*) (*- Function ------------------------------------------------------------------* TInterServer.GetZoneServerLink -------------------------------------------------------------------------------- Overview: -- Does the dirty work of casting for our Client List entries, so that our calling code for ZoneServerLink[] is cleaner, and that both are cleaner than all the casting to dig and get this object reference from the fClientList. Returns the given TZoneServerLink associated with fClientLink at Index. -- Pre: Index must be in range of 0..fClientLink.Count-1 Post: TODO -- Revisions: -- (Format: [yyyy/mm/dd] <Author> - <Comment>) [2007/05/19] CR - Created routine. Property Read handler for ZoneServerLink. *-----------------------------------------------------------------------------*) Function TInterServer.GetZoneServerLink( const Index : Integer ) : TZoneServerLink; Begin //Pre Assert( (Index >= 0) AND (Index < ClientList.Count), 'ClientList Index out of bounds.' ); //-- Result := TZoneServerLink(TIdContext(ClientList[Index]).Data); End; (* Func TInterServer.GetZoneServerLink *-----------------------------------------------------------------------------*) end.
(* * FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * *) unit uFrmInputBox; interface uses LCLIntf, LCLType, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls; type TfrmInputBox = class(TForm) lbText: TLabel; edText: TEdit; Bevel1: TBevel; bbAcept: TBitBtn; bbCancel: TBitBtn; procedure edTextKeyPress(Sender: TObject; var Key: Char); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } InputType : LongInt; end; var frmInputBox: TfrmInputBox; function feInputBox( title, prompt : string; var input : string; itype : Integer ) : Integer; implementation function feInputBox( title, prompt : string; var input : string; itype : Integer ) : Integer; begin frmInputBox.InputType := itype; frmInputBox.lbText.Caption := prompt; frmInputBox.edText.Text := input; frmInputBox.Caption := title; frmInputBox.ShowModal; input := frmInputBox.edText.Text; result := frmInputBox.ModalResult; end; {$R *.lfm} procedure TfrmInputBox.edTextKeyPress(Sender: TObject; var Key: Char); begin case InputType of 1 : case key of '0' .. '9', chr(8): begin end; else key := chr(13); end; end; end; procedure TfrmInputBox.FormCreate(Sender: TObject); begin InputType := 0; end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFMenuModel; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefMenuModelRef = class(TCefBaseRefCountedRef, ICefMenuModel) protected function IsSubMenu: Boolean; function Clear: Boolean; function GetCount: Integer; function AddSeparator: Boolean; function AddItem(commandId: Integer; const text: ustring): Boolean; function AddCheckItem(commandId: Integer; const text: ustring): Boolean; function AddRadioItem(commandId: Integer; const text: ustring; groupId: Integer): Boolean; function AddSubMenu(commandId: Integer; const text: ustring): ICefMenuModel; function InsertSeparatorAt(index: Integer): Boolean; function InsertItemAt(index, commandId: Integer; const text: ustring): Boolean; function InsertCheckItemAt(index, commandId: Integer; const text: ustring): Boolean; function InsertRadioItemAt(index, commandId: Integer; const text: ustring; groupId: Integer): Boolean; function InsertSubMenuAt(index, commandId: Integer; const text: ustring): ICefMenuModel; function Remove(commandId: Integer): Boolean; function RemoveAt(index: Integer): Boolean; function GetIndexOf(commandId: Integer): Integer; function GetCommandIdAt(index: Integer): Integer; function SetCommandIdAt(index, commandId: Integer): Boolean; function GetLabel(commandId: Integer): ustring; function GetLabelAt(index: Integer): ustring; function SetLabel(commandId: Integer; const text: ustring): Boolean; function SetLabelAt(index: Integer; const text: ustring): Boolean; function GetType(commandId: Integer): TCefMenuItemType; function GetTypeAt(index: Integer): TCefMenuItemType; function GetGroupId(commandId: Integer): Integer; function GetGroupIdAt(index: Integer): Integer; function SetGroupId(commandId, groupId: Integer): Boolean; function SetGroupIdAt(index, groupId: Integer): Boolean; function GetSubMenu(commandId: Integer): ICefMenuModel; function GetSubMenuAt(index: Integer): ICefMenuModel; function IsVisible(commandId: Integer): Boolean; function isVisibleAt(index: Integer): Boolean; function SetVisible(commandId: Integer; visible: Boolean): Boolean; function SetVisibleAt(index: Integer; visible: Boolean): Boolean; function IsEnabled(commandId: Integer): Boolean; function IsEnabledAt(index: Integer): Boolean; function SetEnabled(commandId: Integer; enabled: Boolean): Boolean; function SetEnabledAt(index: Integer; enabled: Boolean): Boolean; function IsChecked(commandId: Integer): Boolean; function IsCheckedAt(index: Integer): Boolean; function setChecked(commandId: Integer; checked: Boolean): Boolean; function setCheckedAt(index: Integer; checked: Boolean): Boolean; function HasAccelerator(commandId: Integer): Boolean; function HasAcceleratorAt(index: Integer): Boolean; function SetAccelerator(commandId, keyCode: Integer; shiftPressed, ctrlPressed, altPressed: Boolean): Boolean; function SetAcceleratorAt(index, keyCode: Integer; shiftPressed, ctrlPressed, altPressed: Boolean): Boolean; function RemoveAccelerator(commandId: Integer): Boolean; function RemoveAcceleratorAt(index: Integer): Boolean; function GetAccelerator(commandId: Integer; out keyCode: Integer; out shiftPressed, ctrlPressed, altPressed: Boolean): Boolean; function GetAcceleratorAt(index: Integer; out keyCode: Integer; out shiftPressed, ctrlPressed, altPressed: Boolean): Boolean; function SetColor(commandId: Integer; colorType: TCefMenuColorType; color: TCefColor): Boolean; function SetColorAt(index: Integer; colorType: TCefMenuColorType; color: TCefColor): Boolean; function GetColor(commandId: Integer; colorType: TCefMenuColorType; out color: TCefColor): Boolean; function GetColorAt(index: Integer; colorType: TCefMenuColorType; out color: TCefColor): Boolean; function SetFontList(commandId: Integer; const fontList: ustring): Boolean; function SetFontListAt(index: Integer; const fontList: ustring): Boolean; public class function UnWrap(data: Pointer): ICefMenuModel; class function New(const delegate: ICefMenuModelDelegate): ICefMenuModel; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions; function TCefMenuModelRef.AddCheckItem(commandId: Integer; const text: ustring): Boolean; var t: TCefString; begin t := CefString(text); Result := PCefMenuModel(FData).add_check_item(PCefMenuModel(FData), commandId, @t) <> 0; end; function TCefMenuModelRef.AddItem(commandId: Integer; const text: ustring): Boolean; var t: TCefString; begin t := CefString(text); Result := PCefMenuModel(FData).add_item(PCefMenuModel(FData), commandId, @t) <> 0; end; function TCefMenuModelRef.AddRadioItem(commandId: Integer; const text: ustring; groupId: Integer): Boolean; var t: TCefString; begin t := CefString(text); Result := PCefMenuModel(FData).add_radio_item(PCefMenuModel(FData), commandId, @t, groupId) <> 0; end; function TCefMenuModelRef.AddSeparator: Boolean; begin Result := PCefMenuModel(FData).add_separator(PCefMenuModel(FData)) <> 0; end; function TCefMenuModelRef.AddSubMenu(commandId: Integer; const text: ustring): ICefMenuModel; var t: TCefString; begin t := CefString(text); Result := TCefMenuModelRef.UnWrap(PCefMenuModel(FData).add_sub_menu(PCefMenuModel(FData), commandId, @t)); end; function TCefMenuModelRef.IsSubMenu: Boolean; begin Result := PCefMenuModel(FData).is_sub_menu(PCefMenuModel(FData)) <> 0; end; function TCefMenuModelRef.Clear: Boolean; begin Result := PCefMenuModel(FData).clear(PCefMenuModel(FData)) <> 0; end; function TCefMenuModelRef.GetAccelerator(commandId: Integer; out keyCode: Integer; out shiftPressed, ctrlPressed, altPressed: Boolean): Boolean; var sp, cp, ap: Integer; begin Result := PCefMenuModel(FData).get_accelerator(PCefMenuModel(FData), commandId, @keyCode, @sp, @cp, @ap) <> 0; shiftPressed := sp <> 0; ctrlPressed := cp <> 0; altPressed := ap <> 0; end; function TCefMenuModelRef.GetAcceleratorAt(index: Integer; out keyCode: Integer; out shiftPressed, ctrlPressed, altPressed: Boolean): Boolean; var sp, cp, ap: Integer; begin Result := PCefMenuModel(FData).get_accelerator_at(PCefMenuModel(FData), index, @keyCode, @sp, @cp, @ap) <> 0; shiftPressed := sp <> 0; ctrlPressed := cp <> 0; altPressed := ap <> 0; end; function TCefMenuModelRef.SetColor(commandId: Integer; colorType: TCefMenuColorType; color: TCefColor): Boolean; begin Result := PCefMenuModel(FData).set_color(PCefMenuModel(FData), commandId, colorType, color) <> 0; end; function TCefMenuModelRef.SetColorAt(index: Integer; colorType: TCefMenuColorType; color: TCefColor): Boolean; begin Result := PCefMenuModel(FData).set_color_at(PCefMenuModel(FData), index, colorType, color) <> 0; end; function TCefMenuModelRef.GetColor(commandId: Integer; colorType: TCefMenuColorType; out color: TCefColor): Boolean; begin Result := PCefMenuModel(FData).get_color(PCefMenuModel(FData), commandId, colorType, @color) <> 0; end; function TCefMenuModelRef.GetColorAt(index: Integer; colorType: TCefMenuColorType; out color: TCefColor): Boolean; begin Result := PCefMenuModel(FData).get_color_at(PCefMenuModel(FData), index, colorType, @color) <> 0; end; function TCefMenuModelRef.SetFontList(commandId: Integer; const fontList: ustring): Boolean; var TempString : TCefString; begin TempString := CefString(fontList); Result := PCefMenuModel(FData).set_font_list(PCefMenuModel(FData), commandId, @TempString) <> 0; end; function TCefMenuModelRef.SetFontListAt(index: Integer; const fontList: ustring): Boolean; var TempString : TCefString; begin TempString := CefString(fontList); Result := PCefMenuModel(FData).set_font_list_at(PCefMenuModel(FData), index, @TempString) <> 0; end; function TCefMenuModelRef.GetCommandIdAt(index: Integer): Integer; begin Result := PCefMenuModel(FData).get_command_id_at(PCefMenuModel(FData), index); end; function TCefMenuModelRef.GetCount: Integer; begin Result := PCefMenuModel(FData).get_count(PCefMenuModel(FData)); end; function TCefMenuModelRef.GetGroupId(commandId: Integer): Integer; begin Result := PCefMenuModel(FData).get_group_id(PCefMenuModel(FData), commandId); end; function TCefMenuModelRef.GetGroupIdAt(index: Integer): Integer; begin Result := PCefMenuModel(FData).get_group_id(PCefMenuModel(FData), index); end; function TCefMenuModelRef.GetIndexOf(commandId: Integer): Integer; begin Result := PCefMenuModel(FData).get_index_of(PCefMenuModel(FData), commandId); end; function TCefMenuModelRef.GetLabel(commandId: Integer): ustring; begin Result := CefStringFreeAndGet(PCefMenuModel(FData).get_label(PCefMenuModel(FData), commandId)); end; function TCefMenuModelRef.GetLabelAt(index: Integer): ustring; begin Result := CefStringFreeAndGet(PCefMenuModel(FData).get_label_at(PCefMenuModel(FData), index)); end; function TCefMenuModelRef.GetSubMenu(commandId: Integer): ICefMenuModel; begin Result := TCefMenuModelRef.UnWrap(PCefMenuModel(FData).get_sub_menu(PCefMenuModel(FData), commandId)); end; function TCefMenuModelRef.GetSubMenuAt(index: Integer): ICefMenuModel; begin Result := TCefMenuModelRef.UnWrap(PCefMenuModel(FData).get_sub_menu_at(PCefMenuModel(FData), index)); end; function TCefMenuModelRef.GetType(commandId: Integer): TCefMenuItemType; begin Result := PCefMenuModel(FData).get_type(PCefMenuModel(FData), commandId); end; function TCefMenuModelRef.GetTypeAt(index: Integer): TCefMenuItemType; begin Result := PCefMenuModel(FData).get_type_at(PCefMenuModel(FData), index); end; function TCefMenuModelRef.HasAccelerator(commandId: Integer): Boolean; begin Result := PCefMenuModel(FData).has_accelerator(PCefMenuModel(FData), commandId) <> 0; end; function TCefMenuModelRef.HasAcceleratorAt(index: Integer): Boolean; begin Result := PCefMenuModel(FData).has_accelerator_at(PCefMenuModel(FData), index) <> 0; end; function TCefMenuModelRef.InsertCheckItemAt(index, commandId: Integer; const text: ustring): Boolean; var t: TCefString; begin t := CefString(text); Result := PCefMenuModel(FData).insert_check_item_at(PCefMenuModel(FData), index, commandId, @t) <> 0; end; function TCefMenuModelRef.InsertItemAt(index, commandId: Integer; const text: ustring): Boolean; var t: TCefString; begin t := CefString(text); Result := PCefMenuModel(FData).insert_item_at(PCefMenuModel(FData), index, commandId, @t) <> 0; end; function TCefMenuModelRef.InsertRadioItemAt(index, commandId: Integer; const text: ustring; groupId: Integer): Boolean; var t: TCefString; begin t := CefString(text); Result := PCefMenuModel(FData).insert_radio_item_at(PCefMenuModel(FData), index, commandId, @t, groupId) <> 0; end; function TCefMenuModelRef.InsertSeparatorAt(index: Integer): Boolean; begin Result := PCefMenuModel(FData).insert_separator_at(PCefMenuModel(FData), index) <> 0; end; function TCefMenuModelRef.InsertSubMenuAt(index, commandId: Integer; const text: ustring): ICefMenuModel; var t: TCefString; begin t := CefString(text); Result := TCefMenuModelRef.UnWrap(PCefMenuModel(FData).insert_sub_menu_at( PCefMenuModel(FData), index, commandId, @t)); end; function TCefMenuModelRef.IsChecked(commandId: Integer): Boolean; begin Result := PCefMenuModel(FData).is_checked(PCefMenuModel(FData), commandId) <> 0; end; function TCefMenuModelRef.IsCheckedAt(index: Integer): Boolean; begin Result := PCefMenuModel(FData).is_checked_at(PCefMenuModel(FData), index) <> 0; end; function TCefMenuModelRef.IsEnabled(commandId: Integer): Boolean; begin Result := PCefMenuModel(FData).is_enabled(PCefMenuModel(FData), commandId) <> 0; end; function TCefMenuModelRef.IsEnabledAt(index: Integer): Boolean; begin Result := PCefMenuModel(FData).is_enabled_at(PCefMenuModel(FData), index) <> 0; end; function TCefMenuModelRef.IsVisible(commandId: Integer): Boolean; begin Result := PCefMenuModel(FData).is_visible(PCefMenuModel(FData), commandId) <> 0; end; function TCefMenuModelRef.isVisibleAt(index: Integer): Boolean; begin Result := PCefMenuModel(FData).is_visible_at(PCefMenuModel(FData), index) <> 0; end; class function TCefMenuModelRef.New( const delegate: ICefMenuModelDelegate): ICefMenuModel; begin Result := UnWrap(cef_menu_model_create(CefGetData(delegate))); end; function TCefMenuModelRef.Remove(commandId: Integer): Boolean; begin Result := PCefMenuModel(FData).remove(PCefMenuModel(FData), commandId) <> 0; end; function TCefMenuModelRef.RemoveAccelerator(commandId: Integer): Boolean; begin Result := PCefMenuModel(FData).remove_accelerator(PCefMenuModel(FData), commandId) <> 0; end; function TCefMenuModelRef.RemoveAcceleratorAt(index: Integer): Boolean; begin Result := PCefMenuModel(FData).remove_accelerator_at(PCefMenuModel(FData), index) <> 0; end; function TCefMenuModelRef.RemoveAt(index: Integer): Boolean; begin Result := PCefMenuModel(FData).remove_at(PCefMenuModel(FData), index) <> 0; end; function TCefMenuModelRef.SetAccelerator(commandId, keyCode: Integer; shiftPressed, ctrlPressed, altPressed: Boolean): Boolean; begin Result := PCefMenuModel(FData).set_accelerator(PCefMenuModel(FData), commandId, keyCode, Ord(shiftPressed), Ord(ctrlPressed), Ord(altPressed)) <> 0; end; function TCefMenuModelRef.SetAcceleratorAt(index, keyCode: Integer; shiftPressed, ctrlPressed, altPressed: Boolean): Boolean; begin Result := PCefMenuModel(FData).set_accelerator_at(PCefMenuModel(FData), index, keyCode, Ord(shiftPressed), Ord(ctrlPressed), Ord(altPressed)) <> 0; end; function TCefMenuModelRef.setChecked(commandId: Integer; checked: Boolean): Boolean; begin Result := PCefMenuModel(FData).set_checked(PCefMenuModel(FData), commandId, Ord(checked)) <> 0; end; function TCefMenuModelRef.setCheckedAt(index: Integer; checked: Boolean): Boolean; begin Result := PCefMenuModel(FData).set_checked_at(PCefMenuModel(FData), index, Ord(checked)) <> 0; end; function TCefMenuModelRef.SetCommandIdAt(index, commandId: Integer): Boolean; begin Result := PCefMenuModel(FData).set_command_id_at(PCefMenuModel(FData), index, commandId) <> 0; end; function TCefMenuModelRef.SetEnabled(commandId: Integer; enabled: Boolean): Boolean; begin Result := PCefMenuModel(FData).set_enabled(PCefMenuModel(FData), commandId, Ord(enabled)) <> 0; end; function TCefMenuModelRef.SetEnabledAt(index: Integer; enabled: Boolean): Boolean; begin Result := PCefMenuModel(FData).set_enabled_at(PCefMenuModel(FData), index, Ord(enabled)) <> 0; end; function TCefMenuModelRef.SetGroupId(commandId, groupId: Integer): Boolean; begin Result := PCefMenuModel(FData).set_group_id(PCefMenuModel(FData), commandId, groupId) <> 0; end; function TCefMenuModelRef.SetGroupIdAt(index, groupId: Integer): Boolean; begin Result := PCefMenuModel(FData).set_group_id_at(PCefMenuModel(FData), index, groupId) <> 0; end; function TCefMenuModelRef.SetLabel(commandId: Integer; const text: ustring): Boolean; var t: TCefString; begin t := CefString(text); Result := PCefMenuModel(FData).set_label(PCefMenuModel(FData), commandId, @t) <> 0; end; function TCefMenuModelRef.SetLabelAt(index: Integer; const text: ustring): Boolean; var t: TCefString; begin t := CefString(text); Result := PCefMenuModel(FData).set_label_at(PCefMenuModel(FData), index, @t) <> 0; end; function TCefMenuModelRef.SetVisible(commandId: Integer; visible: Boolean): Boolean; begin Result := PCefMenuModel(FData).set_visible(PCefMenuModel(FData), commandId, Ord(visible)) <> 0; end; function TCefMenuModelRef.SetVisibleAt(index: Integer; visible: Boolean): Boolean; begin Result := PCefMenuModel(FData).set_visible_at(PCefMenuModel(FData), index, Ord(visible)) <> 0; end; class function TCefMenuModelRef.UnWrap(data: Pointer): ICefMenuModel; begin if data <> nil then Result := Create(data) as ICefMenuModel else Result := nil; end; end.
unit SelectAddKind; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxControls, cxContainer, cxEdit, cxRadioGroup; type TSelectAddKind_Form = class(TForm) RadioGroup: TcxRadioGroup; ApplyButton: TcxButton; CancelButton: TcxButton; procedure ApplyButtonClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } destructor Destroy; override; end; var SelectAddKind_Form: TSelectAddKind_Form; implementation {$R *.dfm} procedure TSelectAddKind_Form.ApplyButtonClick(Sender: TObject); begin ModalResult := mrOk; end; procedure TSelectAddKind_Form.CancelButtonClick(Sender: TObject); begin ModalResult := mrCancel; end; destructor TSelectAddKind_Form.Destroy; begin SelectAddKind_Form := nil; inherited; end; procedure TSelectAddKind_Form.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; end.
{: The Simple Paint Program using Gui components from GLScene.<p> To use the Gui you must place a TGLGUILayout component on your form, this is a storage for Gui layouts within a single texture, each layout is identified by a name. All Layouts can be used with any Gui Component, however features like a forms title might look awkward on a checkbox... For correct usage a Material Library should be used. If a BitmapFont or WindowsFont is applied to a layout it is auto set to the components, however it is perfectly valid to set it to someother font. To Interface correctly, handlers must send the mouse and key events to a root gui component, this can be any of the keyboard aware gui components or a RootControl(a tramsparent component with no other purpose) Plus the root gui component should have its DoChanges invoked, this makes form movement and other mouse/key events changes fluintly match the rendering process, eg no flicker. All other Gui component must be below the root control in the GLScene hierachy, this is a rule which allows you to seperate gui from the rest of glscene and save some clock cycles on <tab> operations. Plus mouse events... For a more thorough look on the gui please check out my article on the caperaven site: http://caperaven.co.za under "Online documentation" called "Gui Interface" The two BMP's pen.bmp and brush.bmp have been published by Borland in the Doc/GraphEx demo that comes with Delphi. The rest is MPL as part of the GLScene project. NOTICE IS YOU HAVE A LOW FRAME RATE and you feel the drawing is lagging to far behind, try setting GLCanvas.MaxInvalidRenderCount to a lower value in the formcreate event. <b>History : </b><font size=-1><ul> <li>01/05/03 - JAJ - Creation </ul></font> } unit Unit1; interface uses SysUtils, Classes, Graphics, Controls, Forms, Dialogs, GLScene, GLHUDObjects, GLObjects, GLCadencer, ExtCtrls, GLBitmapFont, GLLCLViewer, GLWindowsFont, Menus, GLWindows, GLGui, GLTexture, GLCrossPlatform, GLMaterial, GLCoordinates, GLBaseClasses; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLLightSource1: TGLLightSource; GLCamera1: TGLCamera; GLCadencer1: TGLCadencer; Timer1: TTimer; WindowsBitmapFont1: TGLWindowsBitmapFont; MainMenu1: TMainMenu; Font1: TMenuItem; WindowsFont1: TMenuItem; FontDialog1: TFontDialog; GLGuiLayout1: TGLGuiLayout; GLForm1: TGLForm; GLMaterialLibrary1: TGLMaterialLibrary; BrushButton: TGLButton; PenButton: TGLButton; GLPanel1: TGLPanel; GLCanvas: TGLCustomControl; WhiteButton: TGLButton; BlackButton: TGLButton; RedButton: TGLButton; GreenButton: TGLButton; BlueButton: TGLButton; GuiRoot: TGLBaseControl; File1: TMenuItem; Open1: TMenuItem; Save1: TMenuItem; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure Timer1Timer(Sender: TObject); procedure WindowsFont1Click(Sender: TObject); procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure GLCanvasMouseDown(Sender: TObject; Button: TGLMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLCanvasMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure GLCanvasMouseUp(Sender: TObject; Button: TGLMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLCanvasRender(sender: TGLCustomControl; Bitmap: TBitmap); procedure FormCreate(Sender: TObject); procedure WhiteButtonButtonClick(Sender: TObject); procedure BlackButtonButtonClick(Sender: TObject); procedure RedButtonButtonClick(Sender: TObject); procedure GreenButtonButtonClick(Sender: TObject); procedure BlueButtonButtonClick(Sender: TObject); procedure PenButtonButtonClick(Sender: TObject); procedure BrushButtonButtonClick(Sender: TObject); procedure GLCanvasAcceptMouseQuery(Sender: TGLBaseControl; Shift: TShiftState; Action: TGLMouseAction; Button: TGLMouseButton; X, Y: Integer; var accept: Boolean); procedure GLForm1Moving(Sender: TGLForm; var Left, Top: Single); procedure Open1Click(Sender: TObject); procedure Save1Click(Sender: TObject); private { Déclarations privées } public StartX : Integer; StartY : Integer; CurrentX : Integer; CurrentY : Integer; end; var Form1: TForm1; implementation {$R *.lfm} procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin // set frame rate to 10 when program is not focused to reduce cpu usage... If Form1.Focused then GLCadencer1.SleepLength := 0 else GLCadencer1.SleepLength := 100; // make things move a little GLForm1.DoChanges; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Caption:=Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]); GLSceneViewer1.ResetPerformanceMonitor; end; procedure TForm1.WindowsFont1Click(Sender: TObject); begin FontDialog1.Font:=WindowsBitmapFont1.Font; if FontDialog1.Execute then WindowsBitmapFont1.Font:=FontDialog1.Font; end; procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin GuiRoot.MouseDown(Sender,TGLMouseButton(Button),Shift,X,Y); end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin GuiRoot.MouseMove(Sender,Shift,X,Y); end; procedure TForm1.GLSceneViewer1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin GuiRoot.MouseUp(Sender,TGLMouseButton(Button),Shift,X,Y); end; procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin GuiRoot.KeyDown(Sender,Key,Shift); end; procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char); begin GuiRoot.KeyPress(Sender,Key); end; procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin GuiRoot.KeyUp(Sender,Key,Shift); end; procedure TForm1.GLCanvasMouseDown(Sender: TObject; Button: TGLMouseButton; Shift: TShiftState; X, Y: Integer); begin If Button = mbLeft then Begin // Make sure all mouse events are sent to the canvas before other GuiComponents, see GLCanvasAcceptMouseQuery. GuiRoot.ActiveControl := GLCanvas; // Set a status not to send mouse message to child components if any, see GLCanvasAcceptMouseQuery. GLCanvas.KeepMouseEvents := True; StartX := X; StartY := Y; End; end; procedure TForm1.GLCanvasMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin CurrentX := X; CurrentY := Y; end; procedure TForm1.GLCanvasMouseUp(Sender: TObject; Button: TGLMouseButton; Shift: TShiftState; X, Y: Integer); begin If Button = mbLeft then Begin StartX := -1; StartY := -1; // Set normal mouse message handling, see GLCanvasAcceptMouseQuery. GuiRoot.ActiveControl := Nil; // Set that childs are allowed to get mouse events, meant for then, see GLCanvasAcceptMouseQuery. GLCanvas.KeepMouseEvents := False; End; end; procedure TForm1.GLCanvasRender(sender: TGLCustomControl; Bitmap: TBitmap); begin Bitmap.Width := Round(GLCanvas.width); Bitmap.Height := Round(GLCanvas.height); If StartX <> -1 then Begin Bitmap.Canvas.MoveTo(StartX-Round(Sender.Position.X),StartY-Round(Sender.Position.Y)); Bitmap.Canvas.LineTo(CurrentX-Round(Sender.Position.X),CurrentY-Round(Sender.Position.Y)); StartX := CurrentX; StartY := CurrentY; End; end; procedure TForm1.FormCreate(Sender: TObject); begin GLCanvas.MaxInvalidRenderCount := 40; StartX := -1; end; procedure TForm1.WhiteButtonButtonClick(Sender: TObject); begin GLCanvas.Bitmap.Canvas.Pen.Color := clWhite; end; procedure TForm1.BlackButtonButtonClick(Sender: TObject); begin GLCanvas.Bitmap.Canvas.Pen.Color := clBlack; end; procedure TForm1.RedButtonButtonClick(Sender: TObject); begin GLCanvas.Bitmap.Canvas.Pen.Color := clRed; end; procedure TForm1.GreenButtonButtonClick(Sender: TObject); begin GLCanvas.Bitmap.Canvas.Pen.Color := clGreen; end; procedure TForm1.BlueButtonButtonClick(Sender: TObject); begin GLCanvas.Bitmap.Canvas.Pen.Color := clBlue; end; procedure TForm1.PenButtonButtonClick(Sender: TObject); begin GLCanvas.Bitmap.Canvas.Pen.Width := 1; end; procedure TForm1.BrushButtonButtonClick(Sender: TObject); begin GLCanvas.Bitmap.Canvas.Pen.Width := 5; end; procedure TForm1.GLCanvasAcceptMouseQuery(Sender: TGLBaseControl; Shift: TShiftState; Action: TGLMouseAction; Button: TGLMouseButton; X, Y: Integer; var accept: Boolean); begin // Sender.KeepMouseEvents is set when drawing, // if drawing this component, gets mouse events even if they are out of bounds! If Sender.KeepMouseEvents then Accept := True; end; procedure TForm1.GLForm1Moving(Sender: TGLForm; var Left, Top: Single); begin // make sure the form isn't moved out of bounds... If Left > GLSceneViewer1.width-32 then Left := GLSceneViewer1.width-32; If Left+Sender.width < 32 then Left := 32-Sender.Width; If Top > GLSceneViewer1.Height-32 then Top := GLSceneViewer1.Height-32; If Top < 0 then Top := 0; end; procedure TForm1.Open1Click(Sender: TObject); begin If OpenDialog1.Execute then begin GLCanvas.Bitmap.LoadFromFile(OpenDialog1.FileName); End; end; procedure TForm1.Save1Click(Sender: TObject); begin If SaveDialog1.Execute then begin GLCanvas.Bitmap.SaveToFile(SaveDialog1.FileName); End; end; end.
unit Aurelius.Schema.Register; {$I Aurelius.inc} interface uses Generics.Collections, Aurelius.Schema.Interfaces; type TSchemaImporterRegister = class private class var FInstance: TSchemaImporterRegister; private FImporters: TDictionary<string, ISchemaImporter>; procedure PrivateCreate; procedure PrivateDestroy; public class function GetInstance: TSchemaImporterRegister; procedure RegisterImporter(const SqlDialect: string; SchemaImporter: ISchemaImporter); function GetImporter(const SqlDialect: string): ISchemaImporter; end; implementation uses Aurelius.Schema.Exceptions, SysUtils; { TSchemaImporterRegister } procedure TSchemaImporterRegister.RegisterImporter(const SqlDialect: string; SchemaImporter: ISchemaImporter); begin if not FImporters.ContainsKey(UpperCase(SqlDialect)) then FImporters.Add(UpperCase(SqlDialect), SchemaImporter) else FImporters[UpperCase(SqlDialect)] := SchemaImporter; end; function TSchemaImporterRegister.GetImporter(const SqlDialect: string): ISchemaImporter; begin if not FImporters.ContainsKey(UpperCase(SqlDialect)) then raise ESchemaImporterNotFound.Create(SqlDialect); Result := FImporters[UpperCase(SqlDialect)]; end; class function TSchemaImporterRegister.GetInstance: TSchemaImporterRegister; begin if FInstance = nil then begin FInstance := TSchemaImporterRegister.Create; FInstance.PrivateCreate; end; Result := FInstance; end; procedure TSchemaImporterRegister.PrivateCreate; begin FImporters := TDictionary<string, ISchemaImporter>.Create; end; procedure TSchemaImporterRegister.PrivateDestroy; begin FImporters.Free; end; initialization finalization if TSchemaImporterRegister.FInstance <> nil then begin TSchemaImporterRegister.FInstance.PrivateDestroy; TSchemaImporterRegister.FInstance.Free; TSchemaImporterRegister.FInstance := nil; end; end.
unit UDRecords; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, UCrpe32; type TCrpeRecordsDlg = class(TForm) pnlRecords: TPanel; pnlMonitor: TPanel; lblRead: TLabel; lblSelected: TLabel; lblPrinted: TLabel; editRead: TEdit; editSelected: TEdit; editPrinted: TEdit; cbMonitor: TCheckBox; btnOk: TButton; btnCancel: TButton; Timer1: TTimer; btnSetRecordLimit: TButton; editSetRecordLimit: TEdit; btnSetTimeLimit: TButton; editSetTimeLimit: TEdit; lblPercentRead: TLabel; lblPercentCompleted: TLabel; editPercentRead: TEdit; editPercentCompleted: TEdit; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure editSetRecordLimitEnter(Sender: TObject); procedure editSetRecordLimitExit(Sender: TObject); procedure editSetTimeLimitEnter(Sender: TObject); procedure editSetTimeLimitExit(Sender: TObject); procedure btnSetRecordLimitClick(Sender: TObject); procedure btnSetTimeLimitClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure UpdateRecords; procedure InitializeControls(OnOff: boolean); procedure Timer1Timer(Sender: TObject); procedure cbMonitorClick(Sender: TObject); private { Private declarations } public { Public declarations } Cr : TCrpe; PrevNum : string; end; var CrpeRecordsDlg: TCrpeRecordsDlg; bRecords : boolean; implementation {$R *.DFM} uses UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeRecordsDlg.FormCreate(Sender: TObject); begin bRecords := True; LoadFormPos(Self); end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeRecordsDlg.FormShow(Sender: TObject); begin editSetRecordLimit.Text := '0'; editSetTimeLimit.Text := '0'; UpdateRecords; end; {------------------------------------------------------------------------------} { UpdateRecords } {------------------------------------------------------------------------------} procedure TCrpeRecordsDlg.UpdateRecords; var OnOff : Boolean; begin OnOff := not IsStrEmpty(Cr.ReportName); InitializeControls(OnOff); if OnOff then begin cbMonitor.Checked := (Cr.ReportWindowHandle > 0); Timer1.Enabled := cbMonitor.Checked; end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeRecordsDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TCheckBox then TCheckBox(Components[i]).Enabled := OnOff; if Components[i] is TEdit then begin if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { editSetRecordLimitEnter } {------------------------------------------------------------------------------} procedure TCrpeRecordsDlg.editSetRecordLimitEnter(Sender: TObject); begin if IsNumeric(editSetRecordLimit.Text) then PrevNum := editSetRecordLimit.Text; end; {------------------------------------------------------------------------------} { editSetRecordLimitExit } {------------------------------------------------------------------------------} procedure TCrpeRecordsDlg.editSetRecordLimitExit(Sender: TObject); begin if not IsNumeric(editSetRecordLimit.Text) then editSetRecordLimit.Text := PrevNum; end; {------------------------------------------------------------------------------} { editSetTimeLimitEnter } {------------------------------------------------------------------------------} procedure TCrpeRecordsDlg.editSetTimeLimitEnter(Sender: TObject); begin if IsNumeric(editSetTimeLimit.Text) then PrevNum := editSetTimeLimit.Text; end; {------------------------------------------------------------------------------} { editSetTimeLimitExit } {------------------------------------------------------------------------------} procedure TCrpeRecordsDlg.editSetTimeLimitExit(Sender: TObject); begin if not IsNumeric(editSetTimeLimit.Text) then editSetTimeLimit.Text := PrevNum; end; {------------------------------------------------------------------------------} { btnSetRecordLimitClick } {------------------------------------------------------------------------------} procedure TCrpeRecordsDlg.btnSetRecordLimitClick(Sender: TObject); begin if IsNumeric(editSetRecordLimit.Text) then Cr.Records.SetRecordLimit(StrToInt(editSetRecordLimit.Text)); end; {------------------------------------------------------------------------------} { btnSetTimeLimitClick } {------------------------------------------------------------------------------} procedure TCrpeRecordsDlg.btnSetTimeLimitClick(Sender: TObject); begin if IsNumeric(editSetTimeLimit.Text) then Cr.Records.SetTimeLimit(StrToInt(editSetTimeLimit.Text)); end; {------------------------------------------------------------------------------} { cbMonitorClick } {------------------------------------------------------------------------------} procedure TCrpeRecordsDlg.cbMonitorClick(Sender: TObject); begin Timer1.Enabled := cbMonitor.Checked; end; {------------------------------------------------------------------------------} { Timer1Timer } {------------------------------------------------------------------------------} procedure TCrpeRecordsDlg.Timer1Timer(Sender: TObject); begin editRead.Text := IntToStr(Cr.Records.Read); editSelected.Text := IntToStr(Cr.Records.Selected); editPrinted.Text := IntToStr(Cr.Records.Printed); editPercentRead.Text := IntToStr(Cr.Records.PercentRead); editPercentCompleted.Text := IntToStr(Cr.Records.PercentCompleted); end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeRecordsDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { btnCancelClick } {------------------------------------------------------------------------------} procedure TCrpeRecordsDlg.btnCancelClick(Sender: TObject); begin Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeRecordsDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin Timer1.Enabled := False; bRecords := False; Release; end; end.
unit TestURateioVO; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, SysUtils, Atributos, UItensRateioVO, UCondominioVO, Generics.Collections, UGenericVO, Classes, Constantes, URateioVO; type // Test methods for class TRateioVO TestTRateioVO = class(TTestCase) strict private FRateioVO: TRateioVO; public procedure SetUp; override; procedure TearDown; override; published procedure TestValidarCamposObrigatorios; procedure TestValidarCamposObrigatoriosNaoEncontrado; end; implementation procedure TestTRateioVO.SetUp; begin FRateioVO := TRateioVO.Create; end; procedure TestTRateioVO.TearDown; begin FRateioVO.Free; FRateioVO := nil; end; procedure TestTRateioVO.TestValidarCamposObrigatorios; var Rateio : TRateioVO; begin Rateio := TRateioVO.Create; Rateio.dtRateio := StrToDate('01/01/2016'); Rateio.idRateio := 11; try Rateio.ValidarCamposObrigatorios; Check(True,'Sucesso!') except on E: Exception do Check(False,'Erro!'); end; end; procedure TestTRateioVO.TestValidarCamposObrigatoriosNaoEncontrado; var Rateio : TRateioVO; begin Rateio := TRateioVO.Create; Rateio.dtRateio := StrToDate('01/01/2016'); Rateio.idRateio := 1; try Rateio.ValidarCamposObrigatorios; Check(false,'Erro!') except on E: Exception do Check(True,'Sucesso!'); end; end; initialization // Register any test cases with the test runner RegisterTest(TestTRateioVO.Suite); end.
unit uPRK_SP_EDUCORG; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uKlassVuzLicense, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, FIBQuery, pFIBQuery, pFIBStoredProc, Placemnt, dxBar, dxBarExtItems, ActnList, ImgList, dxStatusBar, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid; type TFormPRK_SP_EDUCORG = class(TFormKlassVuzLicense) colNAME_FULL: TcxGridDBColumn; colNAME_SHORT: TcxGridDBColumn; procedure FormCreate(Sender: TObject); procedure ActionADDExecute(Sender: TObject); procedure ActionChangeExecute(Sender: TObject); procedure ActionViewExecute(Sender: TObject); procedure ActionDELExecute(Sender: TObject); private procedure InicCaption;override; procedure InicalisationDataSet;override; public { Public declarations } end; var FormPRK_SP_EDUCORG: TFormPRK_SP_EDUCORG; implementation uses uConstants,AArray,uPRK_SP_EDUCORG_Edit; {$R *.dfm} procedure TFormPRK_SP_EDUCORG.FormCreate(Sender: TObject); begin inherited; {ID_NAME должен стоять первым так как в SelectSQLText может делаться CloseOpen} ID_NAME :='ID_ORG'; SelectSQLText :='Select * from PRK_SP_EDUCORG_SELECT(:ID_PLACE_IN,:ID_TYPE_IN)'; StoredProcAddName :='PRK_SP_EDUCORG_ADD'; StoredProcChangeName :='PRK_SP_EDUCORG_CHANGE'; StoredProcDelName :='PRK_SP_EDUCORG_DEL'; InicFormCaption :=nFormPRK_SP_EDUCORG_Caption[IndLangVL]; //CheckAccessAdd :=''; //CheckAccessChange :=''; //CheckAccessDel :=''; end; procedure TFormPRK_SP_EDUCORG.InicCaption; begin inherited; colNAME_FULL.Caption :=nColName[IndLangVL]; colNAME_SHORT.Caption :=nColShortName[IndLangVL]; end; procedure TFormPRK_SP_EDUCORG.ActionADDExecute(Sender: TObject); var DataVLAdd :TAArray; T:TFormPRK_SP_EDUCORG_Edit; TryAgain :boolean; begin TryAgain:=false; DataVLAdd :=TAArray.Create; DataVLAdd['NAME_FULL'].AsString :=''; DataVLAdd['NAME_SHORT'].AsString :=''; DataVLAdd['SHORT_NAME_TYPE'].AsString :=''; DataVLAdd['NAME_PLACE'].AsString :=''; if DataSetPrKVuzLicense.FieldValues[ID_NAME]<>Null then DataVLAdd['ID'].AsInt64:=StrToInt64(DataSetPrKVuzLicense.FieldValues[ID_NAME]); T := TFormPRK_SP_EDUCORG_Edit.Create(self,DataVLAdd); T.cxLabelFormCaption.Caption :=nFormKlassSpravEdit_Add[IndLangVL]; if T.ShowModal=MrOk then begin StoredProcPrKVuzLicense.Transaction.StartTransaction; StoredProcPrKVuzLicense.StoredProcName:=StoredProcAddName; StoredProcPrKVuzLicense.Prepare; StoredProcPrKVuzLicense.ParamByName('NAME_FULL').AsString :=DataVLAdd['NAME_FULL'].AsString; StoredProcPrKVuzLicense.ParamByName('NAME_SHORT').AsString :=DataVLAdd['NAME_SHORT'].AsString; StoredProcPrKVuzLicense.ParamByName('ID_TYPE').AsInt64 :=DataVLAdd['ID_TYPE'].AsInt64; StoredProcPrKVuzLicense.ParamByName('ID_PLACE').AsInt64 :=DataVLAdd['ID_PLACE'].AsInt64; try StoredProcPrKVuzLicense.ExecProc; StoredProcPrKVuzLicense.Transaction.commit; DataVLAdd['ID'].AsInt64:=StoredProcPrKVuzLicense.FieldByName('ID_OUT').AsInt64; except on e: Exception do begin MessageBox(Handle,Pchar(nMsgErrorTransaction[IndLangVL]+chr(13)+ nMsgTryAgain[IndLangVL]+nMsgOr[IndLangVL]+nMsgToAdmin[IndLangVL]+chr(13)+ e.Message),Pchar(nMsgBoxTitle[IndLangVL]),MB_OK or MB_ICONWARNING); StoredProcPrKVuzLicense.Transaction.Rollback; TryAgain:=true; end; end; end; T.Free; T:=nil; Obnovit(DataVLAdd['ID'].AsInt64); DataVLAdd.Free; DataVLAdd:=Nil; if TryAgain=true then ActionADDExecute(Sender); end; procedure TFormPRK_SP_EDUCORG.ActionChangeExecute(Sender: TObject); var DataVLChange :TAArray; T:TFormPRK_SP_EDUCORG_Edit; TryAgain :boolean; begin TryAgain:=false; if DataSetPrKVuzLicense.FieldValues[ID_NAME]<>Null then begin if StrToInt(DataSetPrKVuzLicense.FieldValues['IS_READ_ONLY'])=1 then begin ShowMessage(nMsgCannotEdit[IndLangVL]); exit; end; DataVLChange :=TAArray.Create; DataVLChange['ID'].AsInt64 :=DataSetPrKVuzLicense.FieldValues[ID_NAME]; DataVLChange['NAME_FULL'].AsString :=DataSetPrKVuzLicense.FieldValues['NAME_FULL']; DataVLChange['NAME_SHORT'].AsString :=DataSetPrKVuzLicense.FieldValues['NAME_SHORT']; DataVLChange['ID_TYPE'].AsInt64 :=DataSetPrKVuzLicense.FieldValues['ID_TYPE']; DataVLChange['SHORT_NAME_TYPE'].AsString :=DataSetPrKVuzLicense.FieldValues['SHORT_NAME_TYPE']; DataVLChange['ID_PLACE'].AsInt64 :=DataSetPrKVuzLicense.FieldValues['ID_PLACE']; DataVLChange['NAME_PLACE'].AsString :=DataSetPrKVuzLicense.FieldValues['NAME_PLACE']; T:=TFormPRK_SP_EDUCORG_Edit.Create(self,DataVLChange); T.cxLabelFormCaption.Caption :=nFormKlassSpravEdit_Change[IndLangVL]; if T.ShowModal=MrOk then begin StoredProcPrKVuzLicense.Transaction.StartTransaction; StoredProcPrKVuzLicense.StoredProcName:=StoredProcChangeName; StoredProcPrKVuzLicense.Prepare; StoredProcPrKVuzLicense.ParamByName(ID_NAME).AsInt64 :=DataVLChange['ID'].AsInt64; StoredProcPrKVuzLicense.ParamByName('NAME_FULL').AsString :=DataVLChange['NAME_FULL'].AsString; StoredProcPrKVuzLicense.ParamByName('NAME_SHORT').AsString :=DataVLChange['NAME_SHORT'].AsString; StoredProcPrKVuzLicense.ParamByName('ID_TYPE').AsInt64 :=DataVLChange['ID_TYPE'].AsInt64; StoredProcPrKVuzLicense.ParamByName('ID_PLACE').AsInt64 :=DataVLChange['ID_PLACE'].AsInt64; StoredProcPrKVuzLicense.ParamByName('IS_VUS').AsInteger :=DataSetPrKVuzLicense['IS_VUS']; try StoredProcPrKVuzLicense.ExecProc; StoredProcPrKVuzLicense.Transaction.Commit; except on e: Exception do begin MessageBox(Handle,Pchar(nMsgErrorTransaction[IndLangVL]+chr(13)+ nMsgTryAgain[IndLangVL]+nMsgOr[IndLangVL]+nMsgToAdmin[IndLangVL]+chr(13)+ e.Message),Pchar(nMsgBoxTitle[IndLangVL]),MB_OK or MB_ICONWARNING); StoredProcPrKVuzLicense.Transaction.Rollback; TryAgain:=true; end; end; end; T.Free; T:=nil; Obnovit(DataVLChange['ID'].AsInt64); DataVLChange.Free; DataVLChange:=nil; end; if TryAgain=true then ActionChangeExecute(sender); end; procedure TFormPRK_SP_EDUCORG.ActionViewExecute(Sender: TObject); var DataVLView :TAArray; T:TFormPRK_SP_EDUCORG_Edit; begin if DataSetPrKVuzLicense.FieldValues[ID_NAME]<>Null then begin DataVLView :=TAArray.Create; DataVLView['ID'].AsInt64 := DataSetPrKVuzLicense.FieldValues[ID_NAME]; DataVLView['NAME_FULL'].AsString :=DataSetPrKVuzLicense.FieldValues['NAME_FULL']; DataVLView['NAME_SHORT'].AsString :=DataSetPrKVuzLicense.FieldValues['NAME_SHORT']; DataVLView['SHORT_NAME_TYPE'].AsString :=DataSetPrKVuzLicense.FieldValues['SHORT_NAME_TYPE']; if DataSetPrKVuzLicense.FieldValues['NAME_PLACE']<> null then DataVLView['NAME_PLACE'].AsString :=DataSetPrKVuzLicense.FieldValues['NAME_PLACE'] else DataVLView['NAME_PLACE'].AsString :=''; T:=TFormPRK_SP_EDUCORG_Edit.Create(self,DataVLView); T.cxLabelFormCaption.Caption :=nFormKlassSpravEdit_View[IndLangVL]; T.cxTextEditName.Properties.ReadOnly :=true; T.cxTextEditShortName.Properties.ReadOnly :=true; T.cxButtonEditTYPE.Properties.ReadOnly :=true; T.cxButtonEditTYPE.Properties.Buttons[0].Visible :=false; T.cxButtonEditPLACE.Properties.ReadOnly :=true; T.cxButtonEditPLACE.Properties.Buttons[0].Visible :=false; T.cxTextEditName.Style.Color :=TextViewColor; T.cxTextEditShortName.Style.Color :=TextViewColor; T.cxButtonEditTYPE.Style.Color :=TextViewColor; T.cxButtonEditPLACE.Style.Color :=TextViewColor; T.ShowModal; T.Free; T:=nil; DataVLView.Free; DataVLView:=nil; end; end; procedure TFormPRK_SP_EDUCORG.ActionDELExecute(Sender: TObject); begin if DataSetPrKVuzLicense.FieldValues[ID_NAME]<>Null then if StrToInt(DataSetPrKVuzLicense.FieldValues['IS_READ_ONLY'])=1 then ShowMessage(nMsgCannotEdit[IndLangVL]) else inherited; end; procedure TFormPRK_SP_EDUCORG.InicalisationDataSet; begin DataBasePrKVuzLicense.close; DataSetPrKVuzLicense.Active :=false; DataBasePrKVuzLicense.Handle := TFormKlassVuzLicense(self).DBHANDLE; DataBasePrKVuzLicense.DefaultTransaction := TransactionReadPrKVuzLicense; DataSetPrKVuzLicense.Database := DataBasePrKVuzLicense; DataSetPrKVuzLicense.Transaction := TransactionReadPrKVuzLicense; DataSetPrKVuzLicense.SelectSQL.Clear; DataSetPrKVuzLicense.SQLs.SelectSQL.Text := SelectSQLText; DataSetPrKVuzLicense.ParamByName('ID_PLACE_IN').AsInt64:= TFormKlassVuzLicense(self).ResultArray['Input']['ID_PLACE_IN'].AsInt64; DataSetPrKVuzLicense.ParamByName('ID_TYPE_IN').AsInt64 := TFormKlassVuzLicense(self).ResultArray['Input']['ID_TYPE_IN'].AsInt64; DataSetPrKVuzLicense.CloseOpen(false); end; end.
unit uTools; {$mode objfpc}{$H+} interface uses Classes, SysUtils, strutils; function removeDiacritics(aStr: string): string; function NormalizeTerm(const aSearchTerm: string): string; function StripNonAlphaNumeric(const aValue: string): string; function CopyAndSplitCammelCaseString(const aValue: string): string; function GlobCheck(const aGlob, aValue: string): boolean; function GlobCheckAll(const aGlobList, aValue: string): boolean; implementation uses character; function NormalizeTerm(const aSearchTerm: string): string; var lSearchTerm: string; begin lSearchTerm := removeDiacritics(aSearchTerm); lSearchTerm := LowerCase(lSearchTerm); lSearchTerm := Trim(lSearchTerm); lSearchTerm := StripNonAlphaNumeric(lSearchTerm); lSearchTerm := DelSpace1(lSearchTerm); lSearchTerm := Trim(lSearchTerm); Result := lSearchTerm; end; function removeDiacritics(aStr: string): string; begin Result := aStr; //Čeština: á, é, í, ó, ú, ý, č, ď, ě, ň, ř, š, ť, ž, ů Result := StringReplace(Result, 'á', 'a', [rfReplaceAll]); Result := StringReplace(Result, 'é', 'e', [rfReplaceAll]); Result := StringReplace(Result, 'í', 'i', [rfReplaceAll]); Result := StringReplace(Result, 'ó', 'o', [rfReplaceAll]); Result := StringReplace(Result, 'ú', 'u', [rfReplaceAll]); Result := StringReplace(Result, 'ý', 'y', [rfReplaceAll]); Result := StringReplace(Result, 'č', 'c', [rfReplaceAll]); Result := StringReplace(Result, 'ď', 'd', [rfReplaceAll]); Result := StringReplace(Result, 'ě', 'e', [rfReplaceAll]); Result := StringReplace(Result, 'ň', 'n', [rfReplaceAll]); Result := StringReplace(Result, 'ř', 'r', [rfReplaceAll]); Result := StringReplace(Result, 'š', 's', [rfReplaceAll]); Result := StringReplace(Result, 'ť', 't', [rfReplaceAll]); Result := StringReplace(Result, 'ž', 'z', [rfReplaceAll]); Result := StringReplace(Result, 'ů', 'u', [rfReplaceAll]); Result := StringReplace(Result, 'Á', 'A', [rfReplaceAll]); Result := StringReplace(Result, 'É', 'E', [rfReplaceAll]); Result := StringReplace(Result, 'Í', 'I', [rfReplaceAll]); Result := StringReplace(Result, 'Ó', 'O', [rfReplaceAll]); Result := StringReplace(Result, 'Ú', 'U', [rfReplaceAll]); Result := StringReplace(Result, 'Ý', 'Y', [rfReplaceAll]); Result := StringReplace(Result, 'Č', 'C', [rfReplaceAll]); Result := StringReplace(Result, 'Ď', 'D', [rfReplaceAll]); Result := StringReplace(Result, 'Ě', 'E', [rfReplaceAll]); Result := StringReplace(Result, 'Ň', 'N', [rfReplaceAll]); Result := StringReplace(Result, 'Ř', 'R', [rfReplaceAll]); Result := StringReplace(Result, 'Š', 'S', [rfReplaceAll]); Result := StringReplace(Result, 'Ť', 'T', [rfReplaceAll]); Result := StringReplace(Result, 'Ž', 'Z', [rfReplaceAll]); Result := StringReplace(Result, 'Ů', 'U', [rfReplaceAll]); //Dánština a norština: å, ø //Esperanto: ĉ, ĝ, ĥ, ĵ, ŝ, ŭ //Estonština: š, ž, õ, ä, ö, ü //Francouzština: à, â, ç, é, è, ê, ë, î, ï, ô, ù, û, ü, ÿ //Chorvatština a bosenština: ž, š, č, ć, đ //Irština: á, é, í, ó, ú //Lotyština: ā, ē, ī, ū, č, š, ž, ļ, ķ, ņ, ģ //Maďarština: á, é, í, ó, ú, ö, ü, ő, ű //Němčina: ä, ö, ü //Nizozemština ë, ï //Polština: ą, ć, ę, ł, ń, ó, ś, ź, ż //Rumunština: ă, â, î, ș, ț //Slovenština: á, ä, č, ď, é, í, ĺ, ľ, ň, ó, ô, ŕ, š, ť, ú, ý, ž //Španělština: ñ //Švédština: å, ä, ö //Turečtina: ç, ş, ğ //Vietnamština: ă, â, đ, ê, ô, ơ, ư end; function StripNonAlphaNumeric(const aValue: string): string; var C: char; begin Result := ''; for C in aValue do if IsLetterOrDigit(C) then Result := Result + C else Result := Result + ' '; end; function CopyAndSplitCammelCaseString(const aValue: string): string; const ALPHA_CHARS = ['a'..'z', 'A'..'Z', '0'..'9']; var C, O: char; lUpraveno: string; begin lUpraveno := ''; O := ' '; Result := aValue; for C in aValue do begin if (C = UpperCase(C)) and (O in ALPHA_CHARS) then lUpraveno := lUpraveno + ' '; lUpraveno := lUpraveno + C; O := C; end; if Result <> lUpraveno then Result := DelSpace1(Result + ' ' + lUpraveno); end; Function GlobCheck(Const aGlob, aValue: string): boolean; Var lFirst, lLast: Char; lStrip: String; Begin lFirst := aGlob[1]; lLast := aGlob[Length(aGlob)]; if (lFirst = '*') and (lLast = '*') then begin lStrip := Copy(aGlob, 2, Length(aGlob) - 2); Result := AnsiContainsText(aValue, lStrip); //else if End else if (lFirst = '*') and (lLast <> '*') then begin lStrip := Copy(aGlob, 2, Length(aGlob)); Result := AnsiEndsText(lStrip, aValue); End else if (lFirst <> '*') and (lLast = '*') then begin lStrip := Copy(aGlob, 1, Length(aGlob) - 1); Result := AnsiStartsText(lStrip, aValue); End else if (lFirst <> '*') and (lLast <> '*') then begin Result := SameText(aGlob, aValue); End; end; Function GlobCheckAll(Const aGlobList, aValue: string): boolean; var sl: TStringList; i: Integer; Begin sl := TStringList.Create; try //sl.StrictDelimiter := true; sl.Delimiter := ':'; sl.DelimitedText := aGlobList; for i := 0 to sl.Count - 1 do begin if GlobCheck(sl[i], aValue) then begin Result := true; break; End; End; finally sl.Free; end; end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Unit de controle Base - Cliente. The MIT License Copyright: Copyright (C) 2014 T2Ti.COM 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. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 ******************************************************************************* } unit Controller; interface uses Classes, FPJson, SessaoUsuario, SysUtils, Forms, VO, TypInfo, FGL, Biblioteca, T2TiORM; type TController = class(TPersistent) private public class function ServidorAtivo: Boolean; protected class function Sessao: TSessaoUsuario; end; TClassController = class of TController; implementation { TController } class function TController.Sessao: TSessaoUsuario; begin Result := TSessaoUsuario.Instance; end; class function TController.ServidorAtivo: Boolean; var Url: String; begin Result := False; try //se tiver ativo Result := True; except Result := False; end; end; end.
//*********************************************************************** //* Проект "Студгородок" * //* Форма регистрации проживающих - изменение данных по льготам * //* Выполнил: Чернявский А.Э. 2004-2005 г. * //*********************************************************************** unit St_PfLg_Add_Form; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, DB, FIBDataSet, pFIBDataSet, cxTextEdit, cxButtonEdit, StdCtrls, cxButtons, cxLabel, cxMaskEdit, cxDropDownEdit, cxCalendar, cxControls, cxContainer, cxEdit, cxGroupBox, St_Proc, st_ConstUnit, DataModule1_Unit, st_common_types, st_common_loader; type TPfLg_Add_Form = class(TForm) Label16: TLabel; cxGroupBox1: TcxGroupBox; DateBegEdit: TcxDateEdit; cxLabel1: TcxLabel; DateEndEdit: TcxDateEdit; cxLabel2: TcxLabel; OkButton: TcxButton; CancelButton: TcxButton; TypeEdit: TcxButtonEdit; ReadDataSet: TpFIBDataSet; Full_LG_Label: TLabel; cxGroupBox2: TcxGroupBox; DataPrikaza_Edit: TcxDateEdit; DataPrikaza_Label: TcxLabel; NomerPrikaza_Label: TcxLabel; NomerPrikaza_Edit: TcxTextEdit; procedure CancelButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure TypeEditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure OkButtonClick(Sender: TObject); procedure DateBegEditKeyPress(Sender: TObject; var Key: Char); procedure DateEndEditKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure TypeEditExit(Sender: TObject); procedure TypeEditKeyPress(Sender: TObject; var Key: Char); procedure DataPrikaza_EditKeyPress(Sender: TObject; var Key: Char); procedure NomerPrikaza_EditKeyPress(Sender: TObject; var Key: Char); procedure FormCreate(Sender: TObject); private PLanguageIndex: byte; procedure FormIniLanguage(); public ID_LG: integer; fullname: string; is_admin : Boolean; end; var PfLg_Add_Form: TPfLg_Add_Form; implementation uses Unit_of_Utilits, St_Pfio_Add_Form; {$R *.dfm} procedure TPfLg_Add_Form.FormIniLanguage(); begin // индекс языка (1-укр, 2 - рус) PLanguageIndex:= St_Proc.cnLanguageIndex; //названия кнопок OkButton.Caption := st_ConstUnit.st_Accept[PLanguageIndex]; CancelButton.Caption := st_ConstUnit.st_Cancel[PLanguageIndex]; //Номер льготы Label16.Caption := st_ConstUnit.st_LgNomer[PLanguageIndex]; //Дата приказа DataPrikaza_Label.Caption := st_ConstUnit.st_PikazDate[PLanguageIndex]; //Номер приказа NomerPrikaza_Label.Caption := st_ConstUnit.st_PrikazNomer[PLanguageIndex]; //С cxLabel1.Caption := st_ConstUnit.st_Z[PLanguageIndex]; //По cxLabel2.Caption := st_ConstUnit.st_Po[PLanguageIndex]; end; procedure TPfLg_Add_Form.CancelButtonClick(Sender: TObject); begin close; end; procedure TPfLg_Add_Form.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TPfLg_Add_Form.TypeEditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var aParameter : TstSimpleParams; res : Variant; begin aParameter := TstSimpleParams.Create; aParameter.Owner := self; aParameter.Db_Handle := DataModule1.DB.Handle; aParameter.Formstyle := fsNormal; aParameter.WaitPakageOwner := self; aParameter.is_admin := is_admin; res := RunFunctionFromPackage(aParameter, 'Studcity\st_sp_lgots.bpl', 'ShowSpLgota'); If VarArrayDimCount(res) <> 0 then begin TypeEdit.Text := res[2]; ID_Lg := res[0]; fullname := res[1]; Full_LG_Label.Caption := fullname ; end; aParameter.free; end; procedure TPfLg_Add_Form.OkButtonClick(Sender: TObject); var i: integer; AllowDateCategoryBeg, AllowDateCategoryEnd : boolean; begin if TypeEdit.Text='' then begin ShowMessage('Необходимо ввести тип льготы'); TypeEdit.SetFocus; exit; end; if DateBegEdit.Text='' then begin ShowMessage('Необходимо ввести дату начала'); DateBegEdit.SetFocus; exit; end; if DateEndEdit.Text='' then begin ShowMessage('Необходимо ввести дату окончания'); DateEndEdit.SetFocus; exit; end; if DateBegEdit.Date > DateEndEdit.Date then begin ShowMessage('Дата начала должна быть меньше даты окончания'); DateEndEdit.SetFocus; exit; end; //проверка льгот на предмет вхождения дат по-умлчанию в даты по льготам AllowDateCategoryBeg:=false; AllowDateCategoryEnd := false; ReadDataSet.SelectSQL.Clear; ReadDataSet.sqls.SelectSQL.Text := 'select * from ST_SP_LGOT_SUM_SELECT(:id_lgot)'; ReadDataSet.ParamByName('id_lgot').AsInt64 := ID_LG; ReadDataSet.Open; If ReadDataSet.RecordCount <> 0 then begin AllowDateCategoryBeg:=true; AllowDateCategoryEnd:=true; End; ReadDataSet.Close; if (not AllowDateCategoryBeg) or (not AllowDateCategoryEnd ) then begin ShowMessage('Ошибка! Срок действия данной льготы не совпадает с введенными датами начала и окончания льготы.'); TypeEdit.SetFocus; exit; end; //Registration_Form_Add.Redact:=true; Registration_Form_Add.Redact_Lgot:=true; ModalResult := mrOk; end; procedure TPfLg_Add_Form.DateBegEditKeyPress(Sender: TObject; var Key: Char); begin if key=#13 then DateEndEdit.SetFocus; end; procedure TPfLg_Add_Form.DateEndEditKeyPress(Sender: TObject; var Key: Char); begin if key=#13 then DataPrikaza_Edit.SetFocus; end; procedure TPfLg_Add_Form.FormShow(Sender: TObject); begin TypeEdit.SetFocus; end; procedure TPfLg_Add_Form.TypeEditExit(Sender: TObject); begin Full_LG_Label.Caption:=''; If TypeEdit.Text='' then exit; with PfLg_Add_Form do begin If IntegerCheck(TypeEdit.Text) = false then begin ShowMessage('Номер льготы введен неверно!'); TypeEdit.SetFocus; exit; end; ReadDataSet.Close; ReadDataSet.SelectSQL.Clear; ReadDataSet.SelectSQL.Text:='select * from ST_DT_PFIO_NLGOTA_EXITCONTROL( '+ TypeEdit.Text+ ')'; ReadDataSet.Open; if ReadDataSet['N_LGOTA_CORRECT']=0 then begin ShowMessage('Номер льготы введен неверно, т.к. записи в базе данных "Студгородок" с указанным номером льготы не существует.'); TypeEdit.SetFocus; ReadDataSet.Close; exit; end else begin Full_LG_Label.Caption:= ReadDataSet['Short_name'] ; fullname:= ReadDataSet['Short_name'] ; ID_Lg:= ReadDataSet['KOD_LG']; end; ReadDataSet.Close; end; end; procedure TPfLg_Add_Form.TypeEditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then DateBegEdit.SetFocus; end; procedure TPfLg_Add_Form.DataPrikaza_EditKeyPress(Sender: TObject; var Key: Char); begin if key=#13 then NomerPrikaza_Edit.SetFocus; end; procedure TPfLg_Add_Form.NomerPrikaza_EditKeyPress(Sender: TObject; var Key: Char); begin if key=#13 then OkButton.SetFocus; end; procedure TPfLg_Add_Form.FormCreate(Sender: TObject); begin FormIniLanguage(); end; end.
unit NewFrontiers.Validation.VclHelper; interface uses Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Controls; type TEditHelper = class helper for TEdit function getValidationText: string; procedure valid; procedure invalid; end; implementation uses Vcl.Graphics; { TEditHelper } function TEditHelper.getValidationText: string; begin result := self.Text; end; procedure TEditHelper.invalid; begin Font.Color := clWhite; color := clRed; end; procedure TEditHelper.valid; begin Font.Color := clWindowText; Color := clWhite; end; end.
PROGRAM JunkMail (Input,Output, Junk); {**************************************************************************** Author: Scott Janousek Due: Fri March 26, 1993 Student ID: 4361106 Section: 1 MWF 10:10 Program Assignment 3 Instructor: Jeff Clouse Program Desciption: This Program creates Junk Mail which can be sent out to specific people who are on the mailing List. INPUT: 3 Data Files, which are composed of Text. ----- 1) ADDRESSES.DAT 2) SENDERINFO.DAT 3) LETTERBODY.DAT Within is the information needed to create a Junk Mail List. OUTPUT: (JUNKMAIL.DAT) Junk Mail Catalog of the People. ------ ****************************************************************************} CONST SendFromFile = 'SENDERINFO.DAT'; {* Sendee Text File *} SendToFile = 'ADDRESSES.DAT'; {* Address Text File *} LetterBodyFile = 'LETTERBODY.DAT'; {* Letter Body Text *} JunkMailFile = 'JUNKMAIL.DAT'; {* Junk Mail Letters *} MAX = 75; {* Max Number *} {**************************************************************************} VAR Blank, TextLine : packed ARRAY [1..MAX] OF Char; {* Line of Text *} SendTo, SendFrom, BodyLetter, Junk : Text; {* The 4 Files *} {***************************************************************************} PROCEDURE OpenTheFiles (VAR SendTo, BodyLetter, SendFrom, Junk : Text); {* Creates and accesses the Files needed for the Program to Manipulate *} BEGIN {** Open the Files for I/O Operations **} Writeln; Writeln ('[= Opening the Files =]'); OPEN (SendTo, SendToFile, OLD); Reset (SendTo); OPEN (BodyLetter, LetterBodyFile, OLD); Reset (BodyLetter); OPEN (SendFrom, SendFromFile, OLD); Reset (SendFrom); OPEN (Junk, JunkMailFile); Rewrite (Junk); END; {** Opens the Files for I/O Opertions **} {***************************************************************************} PROCEDURE WriteBlankLine (X : integer); {* Writes a Specified Number of Blank Lines *} VAR i: integer; BEGIN {** Create Blank Lines **} FOR i := 1 TO X DO Writeln(Junk); END; {** Create Blank Lines **} {***************************************************************************} PROCEDURE ReadtheAddress (VAR SendTo, Junk : Text); {* Reads the Address Information from the "Clients" on the Junk Mail List *} BEGIN {** of Read the Addresses **} Readln (SendTo, TextLine); Writeln (Junk, ' ',TextLine:30); Readln (SendTo, TextLine); Writeln (Junk, ' ',TextLine:30); Readln (SendTo, TextLine); Writeln (Junk, ' ',TextLine:30); IF NOT (EOF (SendTo)) THEN Readln(SendTo); {* Make Check For End Of File *} END; {** of Read the Addresses **} {***************************************************************************} PROCEDURE PrintClosing (SendFrom, Junk); {* Prints the Closing of a Junk Mail Letter *} VAR i: integer; BEGIN {** of Print the Closing **} FOR i := 1 to 40 DO {* Indent and Print *} Write (Junk, ' '); Writeln (Junk, 'Truly Yours,'); {* Closing *} WriteBlankLine(2); FOR i := 1 to 40 DO Write(Junk, ' '); RESET (SendFrom); {* Reset Sendee *} Readln (SendFrom, TextLine); Writeln (Junk, TextLine:30); {* Name Signature *} WriteBlankLine(5); FOR i := 1 to 70 DO {* Creats Divider *} Write(Junk, '-'); Writeln(Junk); END; {** of Print the Closing **} {***************************************************************************} PROCEDURE MakeTheLetters (VAR SendTo, BodyLetter, SendFrom, Junk: Text); {* Makes the Junk Mail Listing *} VAR i : integer; {*************************************************} PROCEDURE PrintSendee (VAR SendFrom, Junk : Text); {* Prints the Sendee's Address and Offical Title *} VAR i: integer; BEGIN {** Write the Sendee Information **} WriteBlankLine(5); {* Print 5 Blank Lines *} RESET (SendFrom); {* Reset Send File *} WHILE NOT (EOF (SendFrom)) DO BEGIN {* While not end of File SendFrom *} Readln (SendFrom, TextLine); {* Read the Sendee's Address *} FOR i := 1 to 40 DO Write (Junk,' '); Writeln (Junk, TextLine:30); {* Write the Sendee's Address *} END; {* While not end of File SendFrom *} WritelnBlanks (2); {* Write 2 Blank Lines *} END; {** Write the Sendee Information **} {*************************************************} BEGIN {*** Make the Letters ***} WHILE NOT (EOF (SendTo)) DO {* While not END OF FILE Address *} BEGIN PrintSendee (SendFrom, Junk); {* Print the Sendee *} ReadtheAddress (SendTo, Junk); {* Read one Address *} WriteBlankLine (1); Writeln (Junk, ' Dear Esteemed Person With Taste,'); WriteBlankLine (1); RESET (BodyLetter); {* Reset Body of Letter *} WHILE NOT ((EOF (BodyLetter))) DO BEGIN {* of While *} Readln (BodyLetter, TextLine); {* Read a Line *} FOR i := 1 TO 5 DO Write (Junk,' '); {* Indent and Write *} Writeln (Junk, TextLine:60); {* Write Body *} END; {* of While *} WriteBlankLine (2); {* Write 2 Blanks *} PrintClosing (SendFrom, Junk); {* Print the Closing *} END; {** While NOT END OF FILE Address **} END; {*** Make the Letters ***} {***************************************************************************} BEGIN {***** Main Program *****} Writeln('[= Welcome to JUNK MAIL LIST =]'); Writeln; Writeln('By Scott Janousek'); OpenTheFiles (SendTo, BodyLetter, SendFrom, Junk); MaketheLetters (SendTo, BodyLetter, SendFrom, Junk); writeln('[= Junk Mail has been created =]'); writeln; writeln('[= Type/Print JunkMail.Dat at prompt =]'); writeln; writeln; writeln('Thank you for using this program'); writeln('Goodbye.'); writeln; END. {***** Main Program *****}
unit VoxelMap; // This is a 3D grid that supports some interesting voxel treatment // operations for normalizing and rendering. // 28/01/2009: Version 1.0 by Banshee interface uses BasicMathsTypes, BasicDataTypes, ThreeDPointList, Voxel, Normals, BasicConstants, BasicFunctions, VolumeGreyData, Dialogs, SysUtils; {$INCLUDE source/Global_Conditionals.inc} type TVoxelMap = class private // Variables //FMap : T3DSingleGrid; FMap: T3DVolumeGreyData; FBias : integer; FSection : TVoxelSection; // Constructors and Destructors procedure Clear; procedure FillMap(_Mode : integer = C_MODE_NONE; _Value : integer = C_INSIDE_VOLUME); procedure Initialize(_Mode : integer = C_MODE_NONE; _Value : integer = C_INSIDE_VOLUME); // Gets function GetMap(_x,_y,_z: integer): single; function GetMapSafe(_x,_y,_z: integer): single; function GetBias : integer; // Sets procedure SetMap(_x,_y,_z: integer; _value: single); procedure SetMapSafe(_x,_y,_z: integer; _value: single); procedure SetBias(_value: integer); // Misc procedure SetMapSize; public // Constructors and Destructors constructor CreateQuick(const _Voxel: TVoxelSection; _Bias: integer); constructor Create(const _Voxel: TVoxelSection; _Bias: integer); overload; constructor Create(const _Voxel: TVoxelSection; _Bias: integer; _Mode: integer; _Value : integer); overload; constructor Create(const _Map : TVoxelMap); overload; procedure Reset; destructor Destroy; override; // Gets function GetMaxX: integer; function GetMaxY: integer; function GetMaxZ: integer; // Generates procedure GenerateUsedMap(_Used, _Unused: integer); procedure GenerateVolumeMap; procedure GenerateInfluenceMap; procedure GenerateSurfaceMap; procedure GenerateExternalSurfaceMap; procedure GenerateInfluenceMapOnly; procedure GenerateFullMap; procedure GenerateSurfaceAndRefinementMap; procedure GenerateRayCastingMap; // Copies procedure Assign(const _Map : TVoxelMap); function CopyMap(const _Map: T3DVolumeGreyData): T3DVolumeGreyData; // Misc procedure FloodFill(const _Point : TVector3i; _value : single); procedure MergeMapData(const _Source : TVoxelMap; _Data : single); procedure MapInfluences; procedure MapSurfaces(_Value: single); overload; procedure MapSurfaces(_Candidate,_InsideVolume,_Surface: single); overload; procedure MapSurfacesOnly(_Value: single); procedure MapExternalSurfaces(_Value: single); procedure MapSemiSurfaces(var _SemiSurfaces: T3DIntGrid); procedure MapTopologicalProblems(_Surface: single); procedure MapRefinementZones(_Surface: single); procedure MapSkeletonRefinementZones(_Surface: single); procedure CastRayFromVoxel(const _Point: TVector3i; const _Direction: TVector3i; _Threshold, _Increment: integer); function SynchronizeWithSection(_Mode: integer; _Threshold : single): integer; overload; function SynchronizeWithSection(_Threshold : single): integer; overload; procedure ConvertValues(_Values : array of single); // Properties property Map[_x,_y,_z: integer] : single read GetMap write SetMap; default; property MapSafe[_x,_y,_z: integer] : single read GetMapSafe write SetMapSafe; property Bias: integer read GetBias write SetBias; function GenerateFilledDataParam(_Filled, _Unfilled: integer): integer; function IsPointOK (const x,y,z: integer) : boolean; end; PVoxelMap = ^TVoxelMap; implementation uses GlobalVars, BasicVXLSETypes; // Constructors and Destructors constructor TVoxelMap.Create(const _Voxel: TVoxelSection; _Bias: Integer); var Bias: longword; begin FBias := _Bias; FSection := _Voxel; Bias := 2 * _Bias; FMap := T3DVolumeGreyData.Create(FSection.Tailer.XSize + Bias, FSection.Tailer.YSize + Bias,FSection.Tailer.ZSize + Bias); FillMap(C_MODE_NONE,C_OUTSIDE_VOLUME); end; constructor TVoxelMap.Create(const _Voxel: TVoxelSection; _Bias: Integer; _Mode: integer; _Value: integer); var Bias: longword; begin FBias := _Bias; FSection := _Voxel; Bias := 2 * _Bias; FMap := T3DVolumeGreyData.Create(FSection.Tailer.XSize + Bias, FSection.Tailer.YSize + Bias,FSection.Tailer.ZSize + Bias); FillMap(_Mode,_Value); end; constructor TVoxelMap.Create(const _Map : TVoxelMap); begin Assign(_Map); end; constructor TVoxelMap.CreateQuick(const _Voxel: TVoxelSection; _Bias: Integer); var Bias: longword; begin FBias := _Bias; FSection := _Voxel; Bias := 2 * _Bias; FMap := T3DVolumeGreyData.Create(FSection.Tailer.XSize + Bias, FSection.Tailer.YSize + Bias,FSection.Tailer.ZSize + Bias); end; destructor TVoxelMap.Destroy; begin Clear; FSection := nil; inherited Destroy; end; procedure TVoxelMap.Clear; begin FMap.Clear; end; procedure TVoxelMap.FillMap(_Mode : integer = C_MODE_NONE; _Value: integer = C_INSIDE_VOLUME); var x,y,z : integer; Filled : integer; Unfilled : integer; V : TVoxelUnpacked; begin if _Mode = C_MODE_USED then begin Unfilled := _Value and $FFFF; Filled := _Value shr 16; for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do begin if FSection.GetVoxelSafe(x-FBias,y-FBias,z-FBias,v) then begin // Check if it's used. if v.Used then begin FMap.DataUnsafe[x,y,z] := Filled; end else begin FMap.DataUnsafe[x,y,z] := Unfilled; end end else begin FMap.DataUnsafe[x,y,z] := Unfilled; end; end; end else if _Mode = C_MODE_COLOUR then begin for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do begin if FSection.GetVoxelSafe(x-FBias,y-FBias,z-FBias,v) then begin FMap.DataUnsafe[x,y,z] := v.Colour; end else begin FMap.DataUnsafe[x,y,z] := 0; end; end; end else if _Mode = C_MODE_NORMAL then begin for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do begin if FSection.GetVoxelSafe(x-FBias,y-FBias,z-FBias,v) then begin FMap.DataUnsafe[x,y,z] := v.Normal; end else begin FMap.DataUnsafe[x,y,z] := 0; end; end; end else if (_Mode <> C_MODE_NONE) then begin for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do FMap.DataUnsafe[x,y,z] := _Value; end; end; procedure TVoxelMap.Initialize(_Mode : integer = C_MODE_NONE; _Value : integer = C_INSIDE_VOLUME); begin SetMapSize; FillMap(_Mode,_Value); end; procedure TVoxelMap.Reset; begin Clear; Initialize(C_MODE_NONE,0); end; // Gets // Note: I want something quicker than checking if every damn point is ok. function TVoxelMap.GetMap(_x: Integer; _y: Integer; _z: Integer): single; begin try Result := FMap.DataUnsafe[_x,_y,_z]; except Result := -1; end; end; function TVoxelMap.GetMapSafe(_x: Integer; _y: Integer; _z: Integer): single; begin Result := FMap[_x,_y,_z]; end; function TVoxelMap.GetBias: integer; begin Result := FBias; end; function TVoxelMap.GetMaxX: integer; begin Result := FMap.MaxX; end; function TVoxelMap.GetMaxY: integer; begin Result := FMap.MaxY; end; function TVoxelMap.GetMaxZ: integer; begin Result := FMap.MaxZ; end; // Sets // Note: I want something quicker than checking if every damn point is ok. procedure TVoxelMap.SetMap(_x: Integer; _y: Integer; _z: Integer; _value: single); begin try FMap.DataUnsafe[_x,_y,_z] := _value; except exit; end; end; procedure TVoxelMap.SetMapSafe(_x: Integer; _y: Integer; _z: Integer; _value: single); begin FMap[_x,_y,_z] := _value; end; procedure TVoxelMap.SetBias(_value: Integer); var OldMapBias, Offset: integer; Map : T3DVolumeGreyData; x, y, z: Integer; begin if FBias = _Value then exit; OldMapBias := FBias; Map := CopyMap(FMap); FBias := _Value; SetMapSize; Offset := abs(OldMapBias - FBias); if OldMapBias > FBias then begin for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do begin FMap.DataUnsafe[x,y,z] := Map.DataUnsafe[Offset+x,Offset+y,Offset+z]; end; end else begin for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do begin FMap.DataUnsafe[x,y,z] := 0; end; for x := 0 to Map.MaxX do for y := 0 to Map.MaxY do for z := 0 to Map.MaxZ do begin FMap.DataUnsafe[x+Offset,y+Offset,z+Offset] := Map.DataUnsafe[x,y,z]; end; end; // Free memory Map.Free; end; // Generates procedure TVoxelMap.GenerateUsedMap(_Used, _Unused: integer); begin FillMap(C_MODE_USED,GenerateFilledDataParam(_Used,_Unused)); end; // This procedure generates a map that specifies the voxels that are inside and // outside the volume as 0 and 1. procedure TVoxelMap.GenerateVolumeMap; var FilledMap : TVoxelMap; begin FillMap(C_MODE_USED,GenerateFilledDataParam(C_INSIDE_VOLUME,C_OUTSIDE_VOLUME)); FilledMap := TVoxelMap.Create(FSection,FBias,C_MODE_USED,GenerateFilledDataParam(C_OUTSIDE_VOLUME,C_INSIDE_VOLUME)); FilledMap.FloodFill(SetVectorI(0,0,0),0); MergeMapData(FilledMap,C_INSIDE_VOLUME); FilledMap.Free; end; procedure TVoxelMap.GenerateInfluenceMap; var FilledMap : TVoxelMap; begin FillMap(C_MODE_USED,GenerateFilledDataParam(1,C_OUTSIDE_VOLUME)); FilledMap := TVoxelMap.Create(FSection,FBias,C_MODE_USED,GenerateFilledDataParam(C_OUTSIDE_VOLUME,1)); FilledMap.FloodFill(SetVectorI(0,0,0),0); MergeMapData(FilledMap,1); FilledMap.Free; MapInfluences; end; procedure TVoxelMap.GenerateSurfaceMap; var FilledMap : TVoxelMap; begin FillMap(C_MODE_USED,GenerateFilledDataParam(1,C_OUTSIDE_VOLUME)); FilledMap := TVoxelMap.Create(FSection,FBias,C_MODE_USED,GenerateFilledDataParam(C_OUTSIDE_VOLUME,1)); FilledMap.FloodFill(SetVectorI(0,0,0),0); MergeMapData(FilledMap,1); FilledMap.Free; MapSurfaces(1); end; procedure TVoxelMap.GenerateExternalSurfaceMap; var FilledMap : TVoxelMap; begin FillMap(C_MODE_USED,GenerateFilledDataParam(C_INSIDE_VOLUME,C_OUTSIDE_VOLUME)); FilledMap := TVoxelMap.Create(FSection,FBias,C_MODE_USED,GenerateFilledDataParam(C_OUTSIDE_VOLUME,C_INSIDE_VOLUME)); FilledMap.FloodFill(SetVectorI(0,0,0),C_OUTSIDE_VOLUME); MergeMapData(FilledMap,C_INSIDE_VOLUME); FilledMap.Free; MapExternalSurfaces(C_OUTSIDE_VOLUME); end; procedure TVoxelMap.GenerateInfluenceMapOnly; begin FillMap(C_MODE_All,0); MapInfluences; end; procedure TVoxelMap.GenerateFullMap; var FilledMap : TVoxelMap; begin FillMap(C_MODE_USED,GenerateFilledDataParam(1,C_OUTSIDE_VOLUME)); FilledMap := TVoxelMap.Create(FSection,FBias,C_MODE_USED,GenerateFilledDataParam(C_OUTSIDE_VOLUME,1)); FilledMap.FloodFill(SetVectorI(0,0,0),0); MergeMapData(FilledMap,1); FilledMap.Free; MapInfluences; MapSurfaces(C_SURFACE); end; procedure TVoxelMap.GenerateSurfaceAndRefinementMap; var FilledMap : TVoxelMap; begin FillMap(C_MODE_USED,GenerateFilledDataParam(511,C_OUTSIDE_VOLUME)); FilledMap := TVoxelMap.Create(FSection,FBias,C_MODE_USED,GenerateFilledDataParam(C_OUTSIDE_VOLUME,511)); FilledMap.FloodFill(SetVectorI(0,0,0),0); MergeMapData(FilledMap,511); FilledMap.Free; MapSurfaces(511,1023,511); MapRefinementZones(511); //MapTopologicalProblems(511); end; // Make sure that _FilledMap has bias 1 and it is filled with 0 (transparent) or 1 (solid) procedure TVoxelMap.GenerateRayCastingMap; begin FillMap(C_MODE_USED,GenerateFilledDataParam(16,C_OUTSIDE_VOLUME)); // Cast rays from the 8 corners. CastRayFromVoxel(SetVectorI(0,0,0),SetVectorI(1,1,1),16,1); CastRayFromVoxel(SetVectorI(0,0,GetMaxZ),SetVectorI(1,1,-1),16,1); CastRayFromVoxel(SetVectorI(0,GetMaxY,0),SetVectorI(1,-1,1),16,1); CastRayFromVoxel(SetVectorI(0,GetMaxY,GetMaxZ),SetVectorI(1,-1,-1),16,1); CastRayFromVoxel(SetVectorI(GetMaxX,0,0),SetVectorI(-1,1,1),16,1); CastRayFromVoxel(SetVectorI(GetMaxX,0,GetMaxZ),SetVectorI(-1,1,-1),16,1); CastRayFromVoxel(SetVectorI(GetMaxX,GetMaxY,0),SetVectorI(-1,-1,1),16,1); CastRayFromVoxel(SetVectorI(GetMaxX,GetMaxY,GetMaxZ),SetVectorI(-1,-1,-1),16,1); end; // Copies procedure TVoxelMap.Assign(const _Map : TVoxelMap); begin FBias := _Map.FBias; FSection := _Map.FSection; FMap := T3DVolumeGreyData.Create(_Map.FMap); end; function TVoxelMap.CopyMap(const _Map: T3DVolumeGreyData): T3DVolumeGreyData; begin Result := T3DVolumeGreyData.Create(_Map); end; // Misc procedure TVoxelMap.SetMapSize; var Bias : integer; begin Bias := 2 * FBias; FMap.Resize(FSection.Tailer.XSize + Bias, FSection.Tailer.YSize + Bias,FSection.Tailer.ZSize + Bias); end; procedure TVoxelMap.FloodFill(const _Point : TVector3i; _value : single); var List : C3DPointList; // Check Class3DPointList.pas; x,y,z : integer; begin List := C3DPointList.Create; //List.UseSmartMemoryManagement(true); List.UseFixedRAM(6* FMap.XSize * FMap.YSize * FMap.ZSize); List.Add(_Point.X,_Point.Y,_Point.Z); FMap[_Point.X,_Point.Y,_Point.Z] := _value; // It will fill the map while there are elements in the list. while List.GetPosition(x,y,z) do begin // Check and add the neighbours (6 faces) if IsPointOK(x-1,y,z) then if FMap.DataUnsafe[x-1,y,z] <> _value then begin FMap.DataUnsafe[x-1,y,z] := _value; List.Add(x-1,y,z); end; if IsPointOK(x+1,y,z) then if FMap.DataUnsafe[x+1,y,z] <> _value then begin FMap.DataUnsafe[x+1,y,z] := _value; List.Add(x+1,y,z); end; if IsPointOK(x,y-1,z) then if FMap.DataUnsafe[x,y-1,z] <> _value then begin FMap.DataUnsafe[x,y-1,z] := _value; List.Add(x,y-1,z); end; if IsPointOK(x,y+1,z) then if FMap.DataUnsafe[x,y+1,z] <> _value then begin FMap.DataUnsafe[x,y+1,z] := _value; List.Add(x,y+1,z); end; if IsPointOK(x,y,z-1) then if FMap.DataUnsafe[x,y,z-1] <> _value then begin FMap.DataUnsafe[x,y,z-1] := _value; List.Add(x,y,z-1); end; if IsPointOK(x,y,z+1) then if FMap.DataUnsafe[x,y,z+1] <> _value then begin FMap.DataUnsafe[x,y,z+1] := _value; List.Add(x,y,z+1); end; end; List.Free; end; procedure TVoxelMap.MergeMapData(const _Source : TVoxelMap; _Data : single); var x,y,z : integer; begin if _Source.FSection = FSection then begin // Copies every data from the source to the map. for x := 0 to _Source.FMap.MaxX do for y := 0 to _Source.FMap.MaxY do for z := 0 to _Source.FMap.MaxZ do begin if _Source.FMap.DataUnsafe[x,y,z] = _Data then FMap.DataUnsafe[x,y,z] := _Data; end; end; end; procedure TVoxelMap.MapInfluences; var x,y,z : integer; InitialPosition,FinalPosition : integer; V : TVoxelUnpacked; begin // Scan the volume on the direction z for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do begin // Get the initial position. z := 0; InitialPosition := -1; while (z <= FMap.MaxZ) and (InitialPosition = -1) do begin if FSection.GetVoxelSafe(x-FBias,y-FBias,z-FBias,v) then begin if v.Used then begin InitialPosition := z; end; end; inc(z); end; // Get the final position, if there is a used pizel in the axis. if InitialPosition <> -1 then begin z := FMap.MaxZ; FinalPosition := -1; while (z >= 0) and (FinalPosition = -1) do begin if FSection.GetVoxelSafe(x-FBias,y-FBias,z-FBias,v) then begin if v.Used then begin FinalPosition := z; end; end; dec(z); end; // Now we fill everything between the initial and final positions. z := InitialPosition; while z <= FinalPosition do begin FMap.DataUnsafe[x,y,z] := FMap.DataUnsafe[x,y,z] + 1; inc(z); end; end; end; // Scan the volume on the direction x for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do begin // Get the initial position. x := 0; InitialPosition := -1; while (x <= FMap.MaxX) and (InitialPosition = -1) do begin if FSection.GetVoxelSafe(x-FBias,y-FBias,z-FBias,v) then begin if v.Used then begin InitialPosition := x; end; end; inc(x); end; // Get the final position, if there is a used pizel in the axis. if InitialPosition <> -1 then begin x := FMap.MaxX; FinalPosition := -1; while (x >= 0) and (FinalPosition = -1) do begin if FSection.GetVoxelSafe(x-FBias,y-FBias,z-FBias,v) then begin if v.Used then begin FinalPosition := x; end; end; dec(x); end; // Now we fill everything between the initial and final positions. x := InitialPosition; while x <= FinalPosition do begin FMap.DataUnsafe[x,y,z] := FMap.DataUnsafe[x,y,z] + 1; inc(x); end; end; end; // Scan the volume on the direction y for x := 0 to FMap.MaxX do for z := 0 to FMap.MaxZ do begin // Get the initial position. y := 0; InitialPosition := -1; while (y <= FMap.MaxY) and (InitialPosition = -1) do begin if FSection.GetVoxelSafe(x-FBias,y-FBias,z-FBias,v) then begin if v.Used then begin InitialPosition := y; end; end; inc(y); end; // Get the final position, if there is a used pizel in the axis. if InitialPosition <> -1 then begin y := FMap.MaxY; FinalPosition := -1; while (y >= 0) and (FinalPosition = -1) do begin if FSection.GetVoxelSafe(x-FBias,y-FBias,z-FBias,v) then begin if v.Used then begin FinalPosition := y; end; end; dec(y); end; // Now we fill everything between the initial and final positions. y := InitialPosition; while y <= FinalPosition do begin FMap.DataUnsafe[x,y,z] := FMap.DataUnsafe[x,y,z] + 1; inc(y); end; end; end; end; procedure TVoxelMap.MapSurfaces(_Value: single); var Cube : TNormals; CurrentNormal : TVector3f; x, y, z, i, maxi : integer; begin Cube := TNormals.Create(6); maxi := Cube.GetLastID; if (maxi > 0) then begin for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do begin if FMap.DataUnsafe[x,y,z] = _Value then begin i := 0; while i <= maxi do begin CurrentNormal := Cube[i]; if (GetMapSafe(x + Round(CurrentNormal.X),y + Round(CurrentNormal.Y),z + Round(CurrentNormal.Z)) >= _Value) then begin inc(i); end else begin // surface i := maxi * 2; end; end; if i <> (maxi * 2) then begin // inside the voxel FMap.DataUnsafe[x,y,z] := C_INSIDE_VOLUME; end else // surface begin FMap.DataUnsafe[x,y,z] := C_SURFACE; end; end; end; end; Cube.Free; end; procedure TVoxelMap.MapSurfaces(_Candidate,_InsideVolume,_Surface: single); var Cube : TNormals; CurrentNormal : TVector3f; x, y, z, i, maxi : integer; begin Cube := TNormals.Create(6); maxi := Cube.GetLastID; if (maxi > 0) then begin for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do begin if FMap.DataUnsafe[x,y,z] = _Candidate then begin i := 0; while i <= maxi do begin CurrentNormal := Cube[i]; if (GetMapSafe(x + Round(CurrentNormal.X),y + Round(CurrentNormal.Y),z + Round(CurrentNormal.Z)) >= _Candidate) then begin inc(i); end else begin // surface i := maxi * 2; end; end; if i <> (maxi * 2) then begin // inside the voxel FMap.DataUnsafe[x,y,z] := _InsideVolume; end else // surface begin FMap.DataUnsafe[x,y,z] := _Surface; end; end; end; end; Cube.Free; end; procedure TVoxelMap.MapSurfacesOnly(_Value: single); var Cube : TNormals; CurrentNormal : TVector3f; x, y, z, i, maxi : integer; begin Cube := TNormals.Create(6); maxi := Cube.GetLastID; if (maxi > 0) then begin for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do begin if FMap.DataUnsafe[x,y,z] = _Value then begin i := 0; while i <= maxi do begin CurrentNormal := Cube[i]; if (GetMapSafe(x + Round(CurrentNormal.X),y + Round(CurrentNormal.Y),z + Round(CurrentNormal.Z)) <= _Value) then begin inc(i); end else begin // surface i := maxi * 2; end; end; if i = (maxi * 2) then begin FMap.DataUnsafe[x,y,z] := C_SURFACE; end; end; end; end; Cube.Free; end; procedure TVoxelMap.MapExternalSurfaces(_Value: single); var Cube : TNormals; CurrentNormal : TVector3f; x, y, z, i, maxi : integer; begin Cube := TNormals.Create(6); maxi := Cube.GetLastID; if (maxi > 0) then begin for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do begin if FMap.DataUnsafe[x,y,z] = _Value then begin i := 0; while i <= maxi do begin CurrentNormal := Cube[i]; if (GetMapSafe(x + Round(CurrentNormal.X),y + Round(CurrentNormal.Y),z + Round(CurrentNormal.Z)) <= _Value) then begin inc(i); end else begin // surface i := maxi * 2; end; end; if i = (maxi * 2) then begin FMap.DataUnsafe[x,y,z] := C_SURFACE; end; end; end; end; Cube.Free; end; procedure TVoxelMap.MapSemiSurfaces(var _SemiSurfaces: T3DIntGrid); const SSRequirements: array [0..19] of integer = (33, 17, 9, 5, 25, 41, 21, 37, 36, 40, 24, 20, 34, 18, 10, 6, 26, 42, 22, 38); SSMapPointerList: array [0..19] of integer = (0, 2, 4, 6, 8, 14, 20, 26, 32, 34, 36, 38, 40, 42, 44, 46, 48, 54, 60, 66); SSMapQuantList: array [0..19] of integer = (2, 2, 2, 2, 6, 6, 6, 6, 2, 2, 2, 2, 2, 2, 2, 2, 6, 6, 6, 6); SSMapVertsList: array [0..71] of integer = (0, 11, 0, 15, 0, 13, 0, 9, 0, 2, 13, 14, 3, 15, 1, 0, 12, 13, 3, 11, 4, 9, 16, 0, 2, 15, 4, 10, 9, 1, 0, 11, 11, 9, 11, 13, 15, 13, 15, 9, 11, 17, 15, 17, 17, 13, 17, 9, 17, 19, 13, 14, 20, 15, 18, 17, 12, 13, 20, 11, 21, 9, 16, 17, 19 , 15, 21, 10, 9, 18, 17 , 11); SSMapResultsList: array [0..71] of integer = (C_SF_TOP_RIGHT_LINE, C_SF_BOTTOM_LEFT_LINE, C_SF_BOTTOM_RIGHT_LINE, C_SF_TOP_LEFT_LINE, C_SF_RIGHT_FRONT_LINE, C_SF_LEFT_BACK_LINE, C_SF_RIGHT_BACK_LINE, C_SF_LEFT_FRONT_LINE, C_SF_BOTTOM_FRONT_RIGHT_POINT, C_SF_TOP_FRONT_RIGHT_POINT, C_SF_BOTTOM_BACK_LEFT_POINT, C_SF_TOP_BACK_LEFT_POINT, C_SF_BOTTOM_BACK_RIGHT_POINT, C_SF_TOP_FRONT_LEFT_POINT, C_SF_BOTTOM_FRONT_RIGHT_POINT, C_SF_TOP_FRONT_RIGHT_POINT, C_SF_BOTTOM_BACK_LEFT_POINT, C_SF_TOP_BACK_LEFT_POINT, C_SF_TOP_BACK_RIGHT_POINT, C_SF_BOTTOM_FRONT_LEFT_POINT, C_SF_BOTTOM_FRONT_RIGHT_POINT, C_SF_BOTTOM_FRONT_LEFT_POINT, C_SF_TOP_FRONT_LEFT_POINT, C_SF_BOTTOM_BACK_RIGHT_POINT, C_SF_TOP_BACK_RIGHT_POINT, C_SF_TOP_BACK_LEFT_POINT, C_SF_TOP_FRONT_RIGHT_POINT, C_SF_BOTTOM_FRONT_LEFT_POINT, C_SF_TOP_FRONT_LEFT_POINT, C_SF_BOTTOM_BACK_RIGHT_POINT, C_SF_TOP_BACK_RIGHT_POINT, C_SF_BOTTOM_BACK_LEFT_POINT, C_SF_BOTTOM_BACK_LINE, C_SF_TOP_FRONT_LINE, C_SF_BOTTOM_FRONT_LINE, C_SF_TOP_BACK_LINE, C_SF_TOP_FRONT_LINE, C_SF_BOTTOM_BACK_LINE, C_SF_TOP_BACK_LINE, C_SF_BOTTOM_FRONT_LINE, C_SF_BOTTOM_RIGHT_LINE, C_SF_TOP_LEFT_LINE, C_SF_TOP_RIGHT_LINE, C_SF_BOTTOM_LEFT_LINE, C_SF_LEFT_FRONT_LINE, C_SF_RIGHT_BACK_LINE, C_SF_LEFT_BACK_LINE, C_SF_RIGHT_FRONT_LINE, C_SF_BOTTOM_FRONT_LEFT_POINT, C_SF_TOP_FRONT_LEFT_POINT, C_SF_BOTTOM_BACK_RIGHT_POINT, C_SF_TOP_BACK_RIGHT_POINT, C_SF_BOTTOM_BACK_LEFT_POINT, C_SF_TOP_FRONT_RIGHT_POINT, C_SF_BOTTOM_FRONT_LEFT_POINT, C_SF_TOP_FRONT_LEFT_POINT, C_SF_BOTTOM_BACK_RIGHT_POINT, C_SF_TOP_BACK_RIGHT_POINT, C_SF_TOP_BACK_LEFT_POINT, C_SF_BOTTOM_FRONT_RIGHT_POINT, C_SF_BOTTOM_FRONT_LEFT_POINT, C_SF_BOTTOM_FRONT_RIGHT_POINT, C_SF_TOP_FRONT_RIGHT_POINT, C_SF_BOTTOM_BACK_LEFT_POINT, C_SF_TOP_BACK_LEFT_POINT, C_SF_TOP_BACK_RIGHT_POINT, C_SF_TOP_FRONT_LEFT_POINT, C_SF_BOTTOM_FRONT_RIGHT_POINT, C_SF_TOP_FRONT_RIGHT_POINT, C_SF_BOTTOM_BACK_LEFT_POINT, C_SF_TOP_BACK_LEFT_POINT, C_SF_BOTTOM_BACK_RIGHT_POINT); var x, y, z : integer; CubeNeighboors : TNormals; FaceNeighboors : TNormals; CurrentNormal : TVector3f; CubeNormal : TVector3f; VertsAndEdgesNeighboors: TNormals; i, c, maxC, MaxFace, MaxEdge,MissingFaces: integer; begin CubeNeighboors := TNormals.Create(6); FaceNeighboors := TNormals.Create(7); VertsAndEdgesNeighboors := TNormals.Create(8); MaxFace := FaceNeighboors.GetLastID; MaxEdge := VertsAndEdgesNeighboors.GetLastID; SetLength(_SemiSurfaces,FMap.XSize,FMap.YSize,FMap.ZSize); for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do _SemiSurfaces[x,y,z] := 0; for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do begin // Let's check if the surface has face neighbors if FMap[x,y,z] = C_SURFACE then begin MissingFaces := 0; i := 0; while (i <= MaxFace) do begin CurrentNormal := FaceNeighboors[i]; if (GetMapSafe(x + Round(CurrentNormal.X),y + Round(CurrentNormal.Y),z + Round(CurrentNormal.Z)) < C_SURFACE) then begin MissingFaces := MissingFaces or ($1 shl i); end; inc(i); end; i := 0; // check all non-face neighboors (8 vertices and 12 edges) while (i <= MaxEdge) do begin if (MissingFaces and SSRequirements[i]) >= SSRequirements[i] then begin CurrentNormal := VertsAndEdgesNeighboors[i]; // if neighboor has content, we'll estabilish a connection in the _SemiSurfaces. if (GetMapSafe(x + Round(CurrentNormal.X),y + Round(CurrentNormal.Y),z + Round(CurrentNormal.Z)) >= C_SURFACE) then begin c := SSMapPointerList[i]; maxC := c + SSMapQuantList[i]; while c < maxC do begin CubeNormal := CubeNeighboors[SSMapVertsList[c]]; if FMap[x + Round(CubeNormal.X),y + Round(CubeNormal.Y),z + Round(CubeNormal.Z)] < C_SURFACE then begin _SemiSurfaces[x + Round(CubeNormal.X),y + Round(CubeNormal.Y),z + Round(CubeNormal.Z)] := _SemiSurfaces[x + Round(CubeNormal.X),y + Round(CubeNormal.Y),z + Round(CubeNormal.Z)] or SSMapResultsList[c]; FMap[x + Round(CubeNormal.X),y + Round(CubeNormal.Y),z + Round(CubeNormal.Z)] := C_SEMI_SURFACE; end; inc(c); end; end; end; inc(i); end; end; end; CubeNeighboors.Free; FaceNeighboors.Free; VertsAndEdgesNeighboors.Free; end; procedure TVoxelMap.MapTopologicalProblems(_Surface: single); const CubeVertexBit: array [0..25] of byte = (15,10,5,12,3,4,8,1,2,51,34,170,136,204,68,85,17,240,160,80,192,48,64,128,16,32); EdgeDetectionBit: array[0..11] of longword = (513,8193,131584,139264,32769,2049,163840,133120,33280,2560,40960,10240); EdgeForbiddenBit: array[0..11] of longword = (16,8,2097152,1048576,4,2,524288,262144,65536,1024,16384,4096); EdgeVertexBit: array[0..11] of byte = (3,12,48,192,5,10,80,160,17,34,68,136); VertexDetectionBit: array[0..7,0..2] of longword = ((65537,516,32784),(1025,514,2064),(16385,8196,32776),(4097,2056,8194),(524800,2129920,196608),(262656,2099200,132096),(532480,1081344,147456),(1050624,270336,135168)); VertexForbiddenBit: array[0..7,0..2] of longword = ((33428,98449,66181),(2834,3345,1795),(41004,49193,24613),(10314,12355,6217),(19103744,17498624,19431936),(35785728,33949184,35916288),(5423104,4874240,5808128),(8794112,9574400,9709568)); var Cube : TNormals; CurrentNormal : TVector3f; x, y, z, i, j, maxi,VertexConfig,BitValue,BitCount : integer; RegionBitConfig: longword; begin Cube := TNormals.Create(6); maxi := Cube.GetLastID; if (maxi > 0) then begin // Check all voxels. for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do begin // refinement zones are points out of the model that are close to // surfaces if FMap.DataUnsafe[x,y,z] < _Surface then begin // Generate our bit config that we'll need to use later to find // if there is any topological problem in our region. i := 0; RegionBitConfig := 0; while i <= maxi do begin CurrentNormal := Cube[i]; // So, if the neighbour is surface, then.. if (GetMapSafe(x + Round(CurrentNormal.X),y + Round(CurrentNormal.Y),z + Round(CurrentNormal.Z)) >= _Surface) then begin // increments the config with the neighbour config RegionBitConfig := RegionBitConfig or (1 shl i); end; inc(i); end; // Verify the presence of problematic edges and fill the // vertexes that belong to it. i := 0; VertexConfig := 0; while i < 12 do begin if ((RegionBitConfig and EdgeDetectionBit[i]) = EdgeDetectionBit[i]) and ((RegionBitConfig and EdgeForbiddenBit[i]) = 0) then begin VertexConfig := VertexConfig or EdgeVertexBit[i]; end; inc(i); end; // Verify the presence of problematic vertexes on the ones // that are not part of the problematic edges. i := 0; while i < 8 do begin // if vertex not in VertexConfig, verify it. if ((1 shl i) and VertexConfig) = 0 then begin // verify the 3 possible situations of vertex topological // problems for each vertex: j := 0; while j < 3 do begin if ((RegionBitConfig and VertexDetectionBit[i,j]) = VertexDetectionBit[i,j]) and ((RegionBitConfig and VertexForbiddenBit[i,j]) = 0) then begin VertexConfig := VertexConfig or (1 shl i); j := 3; end; inc(j); end; end; inc(i); end; // The vertexes in VertexConfig are part of the final // mesh, but we'll add inside vertexes that are neighbour to // them. BitValue := VertexConfig; i := 0; while i < 26 do begin // if region i is in the surface, then if ((1 shl i) and RegionBitConfig) > 0 then begin // if it has one of the problematic vertexes, then if CubeVertexBit[i] and VertexConfig > 0 then begin // increment our config with its vertexes. BitValue := BitValue or CubeVertexBit[i]; end; end; inc(i); end; // check if it has 5 or more vertexes. BitCount := 0; if BitValue and 1 > 0 then inc(BitCount); if BitValue and 2 > 0 then inc(BitCount); if BitValue and 4 > 0 then inc(BitCount); if BitValue and 8 > 0 then inc(BitCount); if BitValue and 16 > 0 then inc(BitCount); if BitValue and 32 > 0 then inc(BitCount); if BitValue and 64 > 0 then inc(BitCount); if BitValue and 128 > 0 then inc(BitCount); if BitCount >= 5 then begin // Finally, we write the value of the refinement zone here. {$ifdef MESH_TEST} GlobalVars.MeshFile.Add('Interpolation Zone Location: (' + IntToStr(x-1) + ',' + IntToStr(y-1) + ',' + IntToStr(z-1) + '), config is ' + IntToStr(BitValue) + ' and in binary it is (' + IntToStr((BitValue and 128) shr 7) + ',' + IntToStr((BitValue and 64) shr 6) + ',' + IntToStr((BitValue and 32) shr 5) + ',' + IntToStr((BitValue and 16) shr 4) + ',' + IntToStr((BitValue and 8) shr 3) + ',' + IntToStr((BitValue and 4) shr 2) + ',' + IntToStr((BitValue and 2) shr 1) + ',' + IntToStr(BitValue and 1) + ').'); {$endif} FMap.DataUnsafe[x,y,z] := BitValue; end; end; end; end; Cube.Free; end; procedure TVoxelMap.MapSkeletonRefinementZones(_Surface: single); const CubeVertexBit: array [0..25] of byte = (15,10,5,12,3,4,8,1,2,51,34,170,136,204,68,85,17,240,160,80,192,48,64,128,16,32); EdgeDetectionBit: array[0..11] of longword = (513,8193,131584,139264,32769,2049,163840,133120,33280,2560,40960,10240); EdgeForbiddenBit: array[0..11] of longword = (16,8,2097152,1048576,4,2,524288,262144,65536,1024,16384,4096); EdgeVertexBit: array[0..11] of byte = (3,12,48,192,5,10,80,160,17,34,68,136); VertexDetectionBit: array[0..7,0..2] of longword = ((65537,516,32784),(1025,514,2064),(16385,8196,32776),(4097,2056,8194),(524800,2129920,196608),(262656,2099200,132096),(532480,1081344,147456),(1050624,270336,135168)); VertexForbiddenBit: array[0..7,0..2] of longword = ((33428,98449,66181),(2834,3345,1795),(41004,49193,24613),(10314,12355,6217),(19103744,17498624,19431936),(35785728,33949184,35916288),(5423104,4874240,5808128),(8794112,9574400,9709568)); var Cube : TNormals; CurrentNormal : TVector3f; x, y, z, i, j, maxi,VertexConfig,BitValue : integer; RegionBitConfig: longword; begin Cube := TNormals.Create(6); maxi := Cube.GetLastID; if (maxi > 0) then begin // Check all voxels. for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do begin // refinement zones are points out of the model that are close to // surfaces if FMap.DataUnsafe[x,y,z] < _Surface then begin // Generate our bit config that we'll need to use later to find // if there is any topological problem in our region. i := 0; RegionBitConfig := 0; while i <= maxi do begin CurrentNormal := Cube[i]; // So, if the neighbour is surface, then.. if (GetMapSafe(x + Round(CurrentNormal.X),y + Round(CurrentNormal.Y),z + Round(CurrentNormal.Z)) >= _Surface) then begin // increments the config with the neighbour config RegionBitConfig := RegionBitConfig or (1 shl i); end; inc(i); end; // Verify the presence of edges in the skeleton and fill the // vertexes that belong to it. i := 0; VertexConfig := 0; while i < 12 do begin if (RegionBitConfig and EdgeDetectionBit[i]) = EdgeDetectionBit[i] then begin VertexConfig := VertexConfig or EdgeVertexBit[i]; end; inc(i); end; // Verify the presence of vertexes in the skeleton, the ones // that are not part of the edges. i := 0; while i < 8 do begin // if vertex not in VertexConfig, verify it. if ((1 shl i) and VertexConfig) = 0 then begin // verify the 3 possible situations of vertex topological // problems for each vertex: j := 0; while j < 3 do begin if ((RegionBitConfig and VertexDetectionBit[i,j]) = VertexDetectionBit[i,j]) and ((RegionBitConfig and VertexForbiddenBit[i,j]) = 0) then begin VertexConfig := VertexConfig or (1 shl i); j := 3; end; inc(j); end; end; inc(i); end; // The vertexes in VertexConfig is something that I'll figure // out what to do with them. BitValue := VertexConfig; i := 0; while i < 26 do begin // if region i is in the surface, then if ((1 shl i) and RegionBitConfig) > 0 then begin // if it has one of the problematic vertexes, then if CubeVertexBit[i] and VertexConfig > 0 then begin // increment our config with its vertexes. BitValue := BitValue or CubeVertexBit[i]; end; end; inc(i); end; // Finally, we write the value of the refinement zone here. {$ifdef MESH_TEST} GlobalVars.MeshFile.Add('Interpolation Zone Location: (' + IntToStr(x-1) + ',' + IntToStr(y-1) + ',' + IntToStr(z-1) + '), config is ' + IntToStr(BitValue) + ' and in binary it is (' + IntToStr((BitValue and 128) shr 7) + ',' + IntToStr((BitValue and 64) shr 6) + ',' + IntToStr((BitValue and 32) shr 5) + ',' + IntToStr((BitValue and 16) shr 4) + ',' + IntToStr((BitValue and 8) shr 3) + ',' + IntToStr((BitValue and 4) shr 2) + ',' + IntToStr((BitValue and 2) shr 1) + ',' + IntToStr(BitValue and 1) + ').'); {$endif} FMap.DataUnsafe[x,y,z] := BitValue; end; end; end; Cube.Free; end; // Refinement zones are regions that are neighbour to two surface voxels that // are 'linked by edge or vertex'. These zones, while considered to be out of // the volume, they'll have part of the volume of the model, in order to avoid // regions where the internal volume does not exist, therefore not being // manifolds. We'll do a sort of marching cubes on these regions. procedure TVoxelMap.MapRefinementZones(_Surface: single); const CubeVertexBit: array [0..25] of byte = (15,10,5,12,3,4,8,1,2,51,34,170,136,204,68,85,17,240,160,80,192,48,64,128,16,32); CubeFaceBit: array[0..25] of byte = (47,45,46,39,43,38,37,42,41,59,57,61,53,55,54,62,58,31,29,30,23,27,22,21,26,25); var Cube : TNormals; CurrentNormal : TVector3f; x, y, z, i, maxi,FaceConfig,bitValue,bitCount : integer; begin Cube := TNormals.Create(6); maxi := Cube.GetLastID; if (maxi > 0) then begin // Check all voxels. for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do begin // refinement zones are points out of the model that are close to // surfaces if FMap.DataUnsafe[x,y,z] < _Surface then begin // verify if we have any face neighbour (which is one of the // requirements of refinement zone. FaceConfig := 0; if (GetMapSafe(x-1,y,z) >= _Surface) then begin FaceConfig := FaceConfig or 32; end; if (GetMapSafe(x+1,y,z) >= _Surface) then begin FaceConfig := FaceConfig or 16; end; if (GetMapSafe(x,y-1,z) >= _Surface) then begin FaceConfig := FaceConfig or 8; end; if (GetMapSafe(x,y+1,z) >= _Surface) then begin FaceConfig := FaceConfig or 4; end; if (GetMapSafe(x,y,z-1) >= _Surface) then begin FaceConfig := FaceConfig or 2; end; if (GetMapSafe(x,y,z+1) >= _Surface) then begin FaceConfig := FaceConfig or 1; end; // Now we check if we have a face neighbour and if 5 vertexes // are checked. if FaceConfig > 0 then begin // Now, we really calculate the configuration of this // region. // Visit all neighbours and calculate a preliminary config. i := 0; BitValue := 0; while i <= maxi do begin // If this neighbour is neighbour to any face that // incides in this refinement zone... if CubeFaceBit[i] and FaceConfig <> 0 then begin CurrentNormal := Cube[i]; // So, if the neighbour is surface, then.. if (GetMapSafe(x + Round(CurrentNormal.X),y + Round(CurrentNormal.Y),z + Round(CurrentNormal.Z)) >= _Surface) then begin // increments the config with the neighbour config BitValue := BitValue or CubeVertexBit[i]; end; end; inc(i); end; // check if it has 5 or more vertexes. BitCount := 0; if BitValue and 1 > 0 then inc(BitCount); if BitValue and 2 > 0 then inc(BitCount); if BitValue and 4 > 0 then inc(BitCount); if BitValue and 8 > 0 then inc(BitCount); if BitValue and 16 > 0 then inc(BitCount); if BitValue and 32 > 0 then inc(BitCount); if BitValue and 64 > 0 then inc(BitCount); if BitValue and 128 > 0 then inc(BitCount); if BitCount >= 5 then begin FMap.DataUnsafe[x,y,z] := BitValue; end; end else // In this case, the only valid config is a tetrahedron. begin // Visit all neighbours and calculate a preliminary config. i := 0; BitValue := 0; while i <= maxi do begin CurrentNormal := Cube[i]; // So, if the neighbour is surface, then.. if (GetMapSafe(x + Round(CurrentNormal.X),y + Round(CurrentNormal.Y),z + Round(CurrentNormal.Z)) >= _Surface) then begin // increments the config with the neighbour config BitValue := BitValue or CubeVertexBit[i]; end; inc(i); end; // We've got the config. If it is a tetrahedron (configs: // 23, 43, 77, 105, 113, 142, 150, 178, 212, 232) then we // confirm the region. if (BitValue = 23) or (BitValue = 43) or (BitValue = 77) or (BitValue = 105) or (BitValue = 113) or (BitValue = 142) or (BitValue = 150) or (BitValue = 178) or (BitValue = 212) or (BitValue = 232) then begin FMap.DataUnsafe[x,y,z] := BitValue; end; end; // End tetrahedron detection. end; end; end; Cube.Free; end; procedure TVoxelMap.CastRayFromVoxel(const _Point: TVector3i; const _Direction: TVector3i; _Threshold, _Increment: integer); var List : C3DPointList; // Check Class3DPointList.pas; x,y,z,a : integer; VisitedMap : TVoxelMap; begin VisitedMap := TVoxelMap.Create(FSection,FBias); List := C3DPointList.Create; List.UseSmartMemoryManagement(true); List.Add(_Point.X,_Point.Y,_Point.Z); FMap.DataUnsafe[_Point.X,_Point.Y,_Point.Z] := FMap.DataUnsafe[_Point.X,_Point.Y,_Point.Z] + _Increment; VisitedMap[_Point.X,_Point.Y,_Point.Z] := 1; // It will fill the map while there are elements in the list. while List.GetPosition(x,y,z) do begin // Check and add the neighbours (6 faces) a := x+_Direction.X; if IsPointOK(a,y,z) then if VisitedMap.Map[a,y,z] = 0 then if FMap.DataUnsafe[a,y,z] < _Threshold then begin FMap.DataUnsafe[a,y,z] := FMap.DataUnsafe[a,y,z] + _Increment; VisitedMap.Map[a,y,z] := 1; List.Add(a,y,z); end; a := y+_Direction.Y; if IsPointOK(x,a,z) then if VisitedMap.Map[x,a,z] = 0 then if FMap.DataUnsafe[x,a,z] < _Threshold then begin FMap.DataUnsafe[x,a,z] := FMap.DataUnsafe[x,a,z] + _Increment; VisitedMap.Map[x,a,z] := 1; List.Add(x,a,z); end; a := z+_Direction.Z; if IsPointOK(x,y,a) then if VisitedMap.Map[x,y,a] = 0 then if FMap.DataUnsafe[x,y,a] < _Threshold then begin FMap.DataUnsafe[x,y,a] := FMap.DataUnsafe[x,y,a] + _Increment; VisitedMap.Map[x,y,a] := 1; List.Add(x,y,a); end; end; List.Free; VisitedMap.Free; end; function TVoxelMap.SynchronizeWithSection(_Mode : integer; _Threshold : single): integer; var x, y, z : integer; V : TVoxelUnpacked; begin Result := 0; if _MODE = C_MODE_USED then begin for x := Low(FSection.Data) to High(FSection.Data) do for y := Low(FSection.Data[0]) to High(FSection.Data[0]) do for z := Low(FSection.Data[0,0]) to High(FSection.Data[0,0]) do begin FSection.GetVoxel(x,y,z,v); if v.Used then begin v.Used := (FMap.DataUnsafe[x + FBias, y + FBias, z + FBias] >= _Threshold); if not v.Used then inc(Result); FSection.SetVoxel(x,y,z,v); end else begin v.Used := (FMap.DataUnsafe[x + FBias, y + FBias, z + FBias] >= _Threshold); FSection.SetVoxel(x,y,z,v); end; end; end else if _MODE = C_MODE_COLOUR then begin for x := Low(FSection.Data) to High(FSection.Data) do for y := Low(FSection.Data[0]) to High(FSection.Data[0]) do for z := Low(FSection.Data[0,0]) to High(FSection.Data[0,0]) do begin FSection.GetVoxel(x,y,z,v); if v.Used then begin v.Colour := Round(FMap.DataUnsafe[x + FBias,y + FBias, z + FBias]); FSection.SetVoxel(x,y,z,v); end; end; end else if _MODE = C_MODE_NORMAL then begin for x := Low(FSection.Data) to High(FSection.Data) do for y := Low(FSection.Data[0]) to High(FSection.Data[0]) do for z := Low(FSection.Data[0,0]) to High(FSection.Data[0,0]) do begin FSection.GetVoxel(x,y,z,v); if v.Used then begin v.Normal := Round(FMap.DataUnsafe[x + FBias,y + FBias, z + FBias]); FSection.SetVoxel(x,y,z,v); end; end; end; end; function TVoxelMap.SynchronizeWithSection(_Threshold : single): integer; begin Result := SynchronizeWithSection(C_MODE_USED,_Threshold); end; procedure TVoxelMap.ConvertValues(_Values : array of single); var x, y, z : integer; begin if High(_Values) >= 0 then begin for x := 0 to FMap.MaxX do for y := 0 to FMap.MaxY do for z := 0 to FMap.MaxZ do begin if (FMap.DataUnsafe[x,y,z] > 0) and (FMap.DataUnsafe[x,y,z] <= High(_Values)) then begin FMap.DataUnsafe[x,y,z] := _Values[Round(FMap.DataUnsafe[x,y,z])]; end; end; end; end; // Check if the point is valid. function TVoxelMap.IsPointOK (const x,y,z: integer) : boolean; begin result := false; if (x < 0) or (x > FMap.MaxX) then exit; if (y < 0) or (y > FMap.MaxY) then exit; if (z < 0) or (z > FMap.MaxZ) then exit; result := true; end; function TVoxelMap.GenerateFilledDataParam(_Filled: Integer; _Unfilled: Integer): integer; begin Result := (_Filled shl 16) + _Unfilled; end; end.
unit EditorSettings; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, inifiles, Main; type TEditorSettingsForm = class(TForm) SaveBtn: TBitBtn; BaggrundFarve: TColorBox; Label1: TLabel; SkriftFarve: TColorBox; Label2: TLabel; procedure SaveBtnClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var EditorSettingsForm: TEditorSettingsForm; ConfigFile: TINIFile; PathToINIFile: String; implementation {$R *.dfm} procedure TEditorSettingsForm.SaveBtnClick(Sender: TObject); Begin PathToINIFile:=IncludeTrailingBackslash(ExtractFilePath(ParamStr(0)))+'settings.ini'; ConfigFile:=TINIFile.Create(PathToINIFile); ConfigFile.WriteString('Editor', 'BaggrundsFarve', ColorToString(BaggrundFarve.Selected)); ConfigFile.WriteString('Editor', 'SkriftFarve', ColorToString(SkriftFarve.Selected)); ConfigFile.Free; Close; end; procedure TEditorSettingsForm.FormShow(Sender: TObject); begin PathToINIFile:=IncludeTrailingBackslash(ExtractFilePath(ParamStr(0)))+Main.ConfFil; ConfigFile := TINIFile.Create(PathToINIFile); AlphaBlendValue:=main.Trans; BaggrundFarve.Selected:=StringToColor(ConfigFile.ReadString('Editor', 'BaggrundsFarve', 'clWhite')); SkriftFarve.Selected:=StringToColor(ConfigFile.ReadString('Editor', 'SkriftFarve', 'clBlack')); ConfigFile.Free; end; end.
////////////////////////////////////////////////////////////////////////// // This file is a part of NotLimited.Framework.Wpf NuGet package. // You are strongly discouraged from fiddling with it. // If you do, all hell will break loose and living will envy the dead. ////////////////////////////////////////////////////////////////////////// using System.Collections.Generic; using System.Windows; namespace NotLimited.Framework.Wpf { public class SizeChangedReactor { private readonly Queue<SizeChangedEventHandler> _handlers = new Queue<SizeChangedEventHandler>(); public SizeChangedReactor Then(SizeChangedEventHandler handler) { _handlers.Enqueue(handler); return this; } public static SizeChangedReactor AfterSizeChanged(FrameworkElement element, SizeChangedEventHandler handler) { return new SizeChangedReactor(element, handler); } private SizeChangedReactor(FrameworkElement element, SizeChangedEventHandler handler) { _handlers.Enqueue(handler); element.SizeChanged += OnSizeChanged; } private void OnSizeChanged(object sender, SizeChangedEventArgs args) { var handler = _handlers.Dequeue(); if (_handlers.Count == 0) ((FrameworkElement)sender).SizeChanged -= OnSizeChanged; handler(sender, args); } } }
unit UCnae; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UtelaCadastro, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Mask, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, UCnaeVo, UCnaeController, Generics.Collections; type TFTelaCadastroCnae = class(TFTelaCadastro) LabelEditDescricao: TLabeledEdit; MaskEditCnae: TMaskEdit; Cep: TLabel; GroupBox2: TGroupBox; RadioButtonDescricao: TRadioButton; RadioButtonCnae: TRadioButton; function MontaFiltro: string; procedure FormCreate(Sender: TObject); function DoSalvar: boolean; override; function DoExcluir: boolean; override; procedure DoConsultar; override; procedure CarregaObjetoSelecionado; override; procedure BitBtnNovoClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } procedure GridParaEdits; override; function EditsToObject(Cnae: TCnaeVo): TCnaeVo; end; var FTelaCadastroCnae: TFTelaCadastroCnae; ControllerCnae: TCnaeController; implementation {$R *.dfm} { TFTelaCadastroCnae } procedure TFTelaCadastroCnae.BitBtnNovoClick(Sender: TObject); begin inherited; MaskEditCnae.SetFocus; end; procedure TFTelaCadastroCnae.CarregaObjetoSelecionado; begin if not CDSGrid.IsEmpty then begin ObjetoRetornoVO := TCnaeVo.Create; TCnaeVo(ObjetoRetornoVO).idCnae := CDSGrid.FieldByName('IDCNAE').AsInteger; TCnaeVo(ObjetoRetornoVO).descricao := CDSGrid.FieldByName('DESCRICAO').AsString; TCnaeVo(ObjetoRetornoVO).codigoCnae := CDSGrid.FieldByName('CODIGOCNAE').AsString; end; end; procedure TFTelaCadastroCnae.DoConsultar; var listaCnae: TObjectList<TCnaeVo>; filtro: string; begin filtro := MontaFiltro; listaCnae := ControllerCnae.Consultar(filtro); PopulaGrid<TCnaeVo>(listaCnae); end; function TFTelaCadastroCnae.DoExcluir: boolean; var Cnae: TCnaeVo; begin try try Cnae := TCnaeVo.Create; Cnae.idCnae := CDSGrid.FieldByName('IDCNAE').AsInteger; ControllerCnae.Excluir(Cnae); except on E: Exception do begin ShowMessage('Ocorreu um erro ao excluir o registro: ' + #13 + #13 + E.Message); Result := false; end; end; finally end; end; function TFTelaCadastroCnae.DoSalvar: boolean; var Cnae: TCnaeVo; begin Cnae:=EditsToObject(TCnaeVO.Create); try try if (Cnae.ValidarCamposObrigatorios()) then begin if (StatusTela = stInserindo) then begin ControllerCnae.Inserir(Cnae); Result := true; end else if (StatusTela = stEditando) then begin Cnae := ControllerCnae.ConsultarPorId(CDSGrid.FieldByName('IDCNAE') .AsInteger); Cnae := EditsToObject(Cnae); ControllerCnae.Alterar(Cnae); Result := true; end; end else Result := false; except on E: Exception do begin ShowMessage(E.Message); Result := false; end; end; finally end; end; function TFTelaCadastroCnae.EditsToObject(Cnae: TCnaeVo): TCnaeVo; begin Cnae.codigoCnae := MaskEditCnae.Text; Cnae.descricao := LabelEditDescricao.Text; Result := Cnae; end; procedure TFTelaCadastroCnae.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; FreeAndNil(ControllerCnae); end; procedure TFTelaCadastroCnae.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TCnaeVo; RadioButtonCnae.Checked := true; ControllerCnae := TCnaeController.create; inherited; end; procedure TFTelaCadastroCnae.GridParaEdits; var Cnae: TCnaeVo; begin inherited; Cnae := nil; if not CDSGrid.IsEmpty then Cnae := ControllerCnae.ConsultarPorId(CDSGrid.FieldByName('IDCNAE') .AsInteger); if Assigned(Cnae) then begin MaskEditCnae.Text := Cnae.codigoCnae; LabelEditDescricao.Text := Cnae.descricao; end; end; function TFTelaCadastroCnae.MontaFiltro: string; begin Result := ''; if (RadioButtonCnae.Checked = true) then begin if (editBusca.Text <> '') then Result := '( UPPER(CODIGOCNAE) LIKE ' + QuotedStr('%' + UpperCase(editBusca.Text) + '%') + ' ) '; end else if (RadioButtonDescricao.Checked = true) then begin if (editBusca.Text <> '') then Result := '( UPPER(DESCRICAO) LIKE ' + QuotedStr('%' + UpperCase(editBusca.Text) + '%') + ' ) '; end; end; end.
unit UCadastroUnidadeMedida; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrmCRUD, Menus, Buttons, StdCtrls, ExtCtrls , UUnidadeMedida , URegraCRUDUnidadeMedida , UUtilitarios ; type TFrmCadastroUnidadeMedida = class(TFrmCRUD) gbInformacoes: TGroupBox; edDescricao: TLabeledEdit; edSigla: TLabeledEdit; protected FUNIDADEMEDIDA : TUNIDADEMEDIDA; FRegraCRUDUnidadeMedida : TRegraCRUDUnidadeMedida; procedure Inicializa; override; procedure PreencheEntidade; override; procedure PreencheFormulario; override; procedure PosicionaCursorPrimeiroCampo; override; procedure HabilitaCampos(const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); override; private { Private declarations } public { Public declarations } end; var FrmCadastroUnidadeMedida: TFrmCadastroUnidadeMedida; implementation uses UOpcaoPesquisa , UEntidade ; {$R *.dfm} { TFrmCadastroUnidadeMedida } procedure TFrmCadastroUnidadeMedida.HabilitaCampos( const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); begin inherited; gbInformacoes.Enabled := ceTipoOperacaoUsuario in [touInsercao, touAtualizacao]; end; procedure TFrmCadastroUnidadeMedida.Inicializa; begin inherited; DefineEntidade(@FUNIDADEMEDIDA, TUNIDADEMEDIDA); DefineRegraCRUD(@FRegraCRUDUnidadeMedida, TRegraCRUDUnidadeMedida); AdicionaOpcaoPesquisa(TOpcaoPesquisa.Create .DefineVisao(VW_UNIDADEMEDIDA) .DefineNomeCampoRetorno(VW_UNIDADEMEDIDA_ID) .AdicionaFiltro(VW_UNIDADEMEDIDA_DESCRICAO) .DefineNomePesquisa(STR_UNIDADEMEDIDA)); AdicionaOpcaoPesquisa(TOpcaoPesquisa.Create .DefineVisao(VW_UNIDADEMEDIDA) .DefineNomeCampoRetorno(VW_UNIDADEMEDIDA_ID) .AdicionaFiltro(VW_UNIDADEMEDIDA_DESCRICAO) .DefineNomePesquisa('Pesquisa X')); end; procedure TFrmCadastroUnidadeMedida.PosicionaCursorPrimeiroCampo; begin inherited; edDescricao.SetFocus; end; procedure TFrmCadastroUnidadeMedida.PreencheEntidade; begin inherited; FUNIDADEMEDIDA.DESCRICAO := edDescricao.Text; FUNIDADEMEDIDA.SIGLA := edSigla.Text; end; procedure TFrmCadastroUnidadeMedida.PreencheFormulario; begin inherited; edDescricao.Text := FUNIDADEMEDIDA.DESCRICAO; edSigla.Text := FUNIDADEMEDIDA.SIGLA; end; end.
unit CCJSO_AccessUserAlert; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, ADODB, StdCtrls, ToolWin, ComCtrls, ExtCtrls, CheckLst, ActnList; type TfrmCCJSO_AccessUserAlert = class(TForm) pnlControl: TPanel; pnlControl_Tool: TPanel; pnlControl_Show: TPanel; tbarControl: TToolBar; pnlMain: TPanel; lblCheckShowAlert: TLabel; spDSRefAlertType: TADOStoredProc; spAlertTypeAccessCheck: TADOStoredProc; chListBox: TCheckListBox; aList: TActionList; aExit: TAction; aSaveSet: TAction; ToolButton1: TToolButton; ToolButton2: TToolButton; spSelectList_Insert: TADOStoredProc; spSelectList_Clear: TADOStoredProc; spAlertTypeSetAccess: TADOStoredProc; procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure aExitExecute(Sender: TObject); procedure aSaveSetExecute(Sender: TObject); private { Private declarations } ISignActivate : integer; IdUserAction : longint; NUSER : integer; procedure ShowGets; public { Public declarations } procedure SetUser(Parm : integer); end; var frmCCJSO_AccessUserAlert: TfrmCCJSO_AccessUserAlert; implementation uses UMain, UCCenterJournalNetZkz; {$R *.dfm} procedure TfrmCCJSO_AccessUserAlert.FormCreate(Sender: TObject); begin { Инициализация } ISignActivate := 0; end; procedure TfrmCCJSO_AccessUserAlert.FormActivate(Sender: TObject); var CheckAccess : integer; begin if ISignActivate = 0 then begin { Иконка формы } FCCenterJournalNetZkz.imgMain.GetIcon(330,self.Icon); { Уникальный идентификатор действия } IdUserAction := FCCenterJournalNetZkz.GetIdUserAction; { Формируем список типов уведомлений } try chListBox.Clear; if spDSRefAlertType.Active then spDSRefAlertType.Active := false; spDSRefAlertType.Parameters.ParamValues['@Descr'] := ''; spDSRefAlertType.Open; spDSRefAlertType.First; while not spDSRefAlertType.Eof do begin chListBox.Items.AddObject ( spDSRefAlertType.FieldByName('Descr').AsString, TObject(spDSRefAlertType.FieldByName('row_id').AsInteger) ); { Смотрим наличие доступа к показу уведомления } CheckAccess := 0; spAlertTypeAccessCheck.Parameters.ParamValues['@AlertType'] := spDSRefAlertType.FieldByName('row_id').AsInteger; spAlertTypeAccessCheck.Parameters.ParamValues['@USER'] := NUSER; spAlertTypeAccessCheck.ExecProc; CheckAccess := spAlertTypeAccessCheck.Parameters.ParamValues['@Check']; if CheckAccess = 1 then begin chListBox.Checked[chListBox.Count-1] := true; end; spDSRefAlertType.Next; end; except on e:Exception do begin ShowMessage('Сбой при загрузке прав доступа.' + chr(10) + e.Message); end; end; { Форма активна } ISignActivate := 1; ShowGets; end; end; procedure TfrmCCJSO_AccessUserAlert.ShowGets; begin if ISignActivate = 1 then begin end; end; procedure TfrmCCJSO_AccessUserAlert.SetUser(Parm : integer); begin NUSER := Parm; end; procedure TfrmCCJSO_AccessUserAlert.aExitExecute(Sender: TObject); begin { Чистим список выбранных типов уведоилений } spSelectList_Clear.Parameters.ParamValues['@IDENT'] := IdUserAction; spSelectList_Clear.ExecProc; Self.Close; end; procedure TfrmCCJSO_AccessUserAlert.aSaveSetExecute(Sender: TObject); var iListBoxItems : integer; begin try { Фиксируем выбранные типы уведомлений } spDSRefAlertType.First; while not spDSRefAlertType.Eof do begin iListBoxItems := chListBox.Items.IndexOfObject( TObject(spDSRefAlertType.FieldByName('row_id').AsInteger) ); if chListBox.Checked[iListBoxItems] then begin spSelectList_Insert.Parameters.ParamValues['@IDENT'] := IdUserAction; spSelectList_Insert.Parameters.ParamValues['@SUnitCode'] := 'JSO_RefAlertType'; spSelectList_Insert.Parameters.ParamValues['@PRN'] := spDSRefAlertType.FieldByName('row_id').AsInteger; spSelectList_Insert.Parameters.ParamValues['@BigPRN'] := 0; spSelectList_Insert.Parameters.ParamValues['@USER'] := NUSER; spSelectList_Insert.ExecProc; end; spDSRefAlertType.Next; end; { Установка доступа к раздаче уведомлений пользователю } spAlertTypeSetAccess.Parameters.ParamValues['@IDENT'] := IdUserAction; spAlertTypeSetAccess.Parameters.ParamValues['@USER'] := NUSER; spAlertTypeSetAccess.ExecProc; { Чистим список выбранных типов уведоилений } spSelectList_Clear.Parameters.ParamValues['@IDENT'] := IdUserAction; spSelectList_Clear.ExecProc; Self.Close; except on e:Exception do begin ShowMessage('Сбой при формировании списка групп аптек.' + chr(10) + e.Message); end; end; end; end.
(* Taken from PC World Best of *.* Volume 1 (1988) NO LICENSE PROVIDED, PROBABLY PUBLIC DOMAIN (published on coverdisk) Documentation: Title: "New Math for Turbo Pascal" Reference: PC World August 1989 Author: Keith Hattes The file MATH.PAS is a Turbo Pascal unit (submodule) that contains a variety of math functions not normally available, including a function to raise numbers to a power, convert radians to degrees, and calculate permutations. To use the unit, compile MATH.PAS to disk, creating MATH.TPU. Then, insert the phrase USES MATH; after your PROGRAM declaration. This makes the functions in the compiled unit available to your program. Turbo Pascal 4.0 users must have a math coprocessor in order to use the MATH unit. Versions 5.0 and 5.5 (and presumably later releases) work with and without a math chip. *) (* Turbo Pascal Math Functions by Keith A. Hattes *) unit Math; {$IFDEF VER40} {$N+} {$ELSE} {$N+,E+} {$ENDIF} interface Function Power( base, exponent : Double ) : Double; { Power of base rased to exponent } Function Log( argument : Double ) : Double; { Log (base 10) of argument } Function Rad( degrees : Double ) : Double; { Convert radians to degrees } Function Deg( radians : Double ) : Double; { Convert degrees to radians } Function Fact( x : Integer ) : Double; { Factorial of x } Function Perm( n, r : integer ) : Double; { Permutations of n taken r at a time } Function Comb( n, r : Integer ) : Double; { Combinations of n taken r at a time } implementation (* Original Power function from *.* 8/89 Function Power( base, exponent : Double ) : Double; begin Power := Exp( exponent * Ln( base ) ) end; { Power } *) (* Corrected Power function from *.* 12/89*) function power( base, exponent : Double ) : Double; function f( b, e : Double ) : Double; begin f := exp( e * ln( b ) ); end; begin if base = 0.0 then if exponent = 0.0 then power := 1.0 else if exponent < 0.0 then runError( 207 ) { 0^negative } else power := 0.0 else if base > 0.0 then power := f( base, exponent ) else if frac( exponent ) = 0.0 then if odd( trunc( exponent ) ) then power := -f( -base, exponent ) else power := f( -base, exponent ) else runError( 207 ) { negative^noninteger } end; { power } Function Log( argument : Double ) : Double; const BASE = 10; begin Log := Ln( argument ) / Ln( BASE ) end; { Log } Function Rad( degrees : Double ) : Double; const DEGCONVERT = 180.0; begin Rad := Degrees * Pi / DEGCONVERT end; { Rad } Function Deg( radians : Double ) : Double; const RADCONVERT = 180.0; begin Deg := Radians * Radconvert / Pi end; { Deg } Function Fact( x : Integer ) : Double; var loop : Integer; mult : Double; begin mult := 1; For loop := 1 To X Do mult := mult * loop; Fact := mult end; { Fact } Function Perm( n, r : integer ) : Double; begin Perm := Fact( n ) / Fact( n - r ) end; { Perm } Function Comb( n, r : Integer ) : Double; begin Comb := Perm( n, r ) / Fact( r ) end; { Comb } end. { Math unit }
// Eduardo - 13/09/2021 unit FMX.CodeEditor.Caret; interface uses FMX.Controls, System.UITypes, FMX.Types; type TInternalCaret = class private FCaret: TCaret; function GetColor: TAlphaColor; procedure SetColor(const Value: TAlphaColor); function GetX: Single; function GetY: Single; procedure SetX(const Value: Single); procedure SetY(const Value: Single); public property Color: TAlphaColor read GetColor write SetColor; property X: Single read GetX write SetX; property Y: Single read GetY write SetY; procedure Resize(LineHeight: Single); procedure Show; constructor Create(const AOwner: TFMXObject); destructor Destroy; override; end; implementation uses System.Types; { TInternalCaret } constructor TInternalCaret.Create(const AOwner: TFMXObject); begin FCaret := TCaret.Create(AOwner); FCaret.Width := 1; FCaret.Pos := TPointF.Create(0, 0); FCaret.Visible := True; end; destructor TInternalCaret.Destroy; begin FCaret.DisposeOf; inherited; end; function TInternalCaret.GetColor: TAlphaColor; begin Result := FCaret.Color; end; procedure TInternalCaret.SetColor(const Value: TAlphaColor); begin FCaret.Color := Value; end; function TInternalCaret.GetX: Single; begin Result := FCaret.Pos.X; end; procedure TInternalCaret.SetX(const Value: Single); begin FCaret.Pos := TPointF.Create(Value, FCaret.Pos.Y); end; function TInternalCaret.GetY: Single; begin Result := FCaret.Pos.Y; end; procedure TInternalCaret.SetY(const Value: Single); begin FCaret.Pos := TPointF.Create(FCaret.Pos.X, Value); end; procedure TInternalCaret.Resize(LineHeight: Single); begin if FCaret.Size.Height <> LineHeight then FCaret.Size := TSizeF.Create(1, LineHeight); end; procedure TInternalCaret.Show; begin FCaret.Show; end; end.
unit Matriz; interface const cOrdemMax= 100; type tMatriz= array[1..cOrdemMax, 1..cOrdemMax] of Extended; var eMatriz: tMatriz; procedure MultiplicarPorEscalar (Largura, Altura: Integer; Escalar: Extended); procedure Triangular (Ordem: Integer; var Sinal: SmallInt); function CalcularDeterminanteTriangulacao (Ordem: Integer): Extended; implementation uses Principal; procedure MultiplicarPorEscalar (Largura, Altura: Integer; Escalar: Extended); var X, Y: Integer; begin for Y:= 1 to Largura do for X:= 1 to Altura do eMatriz[X, Y]:= eMatriz[X, Y]*Escalar; end; // MultiplicarPorEscalar () procedure PermutarLinhas (Ordem: Integer; A, B: LongInt); var X : LongInt; Temp: Extended; begin for X:= 1 to Ordem do begin Temp := eMatriz[X, B]; eMatriz[X, B]:= eMatriz[X, A]; eMatriz[X, A]:= Temp; end; end; // PermutarLinhas () procedure TriangularLinhas (Ordem: Integer; PosicaoPivo: LongInt); var X, Y : LongInt; Escalar: Extended; begin for Y:= PosicaoPivo+1 to Ordem do begin Escalar := eMatriz[PosicaoPivo, Y]/eMatriz[PosicaoPivo, PosicaoPivo]; eMatriz[PosicaoPivo, Y]:= 0.0; for X:= PosicaoPivo+1 to Ordem do eMatriz[X, Y]:= eMatriz[X, Y] - eMatriz[X, PosicaoPivo]*Escalar; end; end; // TriangularLinhas () function ProcurarNaoZero (Ordem: Integer; X, Y: LongInt): LongInt; var P: LongInt; begin Result:= -1; for P:= Y to Ordem do if eMatriz[X, P] <> 0 then begin Result:= P; Exit; end end; // ProcurarNaoZero () // O sinal do DETERMINANTE muda quando se permuta 2 linhas procedure Triangular (Ordem: Integer; var Sinal: SmallInt); var P, PosicaoPivo: LongInt; begin Sinal:= 1; for P:= 1 to Ordem do if eMatriz[P, P] <> 0.0 then TriangularLinhas (Ordem, P) else if P < Ordem then begin // Para evitar de permutar a última linha PosicaoPivo:= ProcurarNaoZero (Ordem, P, P); if PosicaoPivo > 0 then begin Sinal:= -Sinal; PermutarLinhas (Ordem, P, PosicaoPivo); TriangularLinhas (Ordem, P); end; end; end; // Triangular () function CalcularDeterminanteTriangulacao (Ordem: Integer): Extended; var Sinal: SmallInt; P : LongInt; begin Result:= 1; Triangular (Ordem, Sinal); for P:= 1 to Ordem do Result:= Result*eMatriz[P, P]; // Multiplicar os elementos da Diagonal Principal Result:= Result*Sinal; end; // CalcularDeterminanteTriangulacao () end.
//virtualbox images read/write operations unit vdi; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses windows, sysutils; const INVALID_SET_FILE_POINTER = $FFFFFFFF; type VDIDISKGEOMETRY=record //** Cylinders. */ cCylinders:dword; //** Heads. */ cHeads:dword; //** Sectors per track. */ cSectors:dword; //** Sector size. (bytes per sector) */ cbSector:dword; end; PVDIPREHEADER=^VDIPREHEADER; VDIPREHEADER = record szFileInfo : array[0..63] of ansiChar; u32Signature : dword; u32Version : dword; end; PVDIHEADER1=^VDIHEADER1; VDIHEADER1 = record cbHeader : cardinal; u32Type : cardinal; fFlags : cardinal; szComment : array[0..255] of ansiChar; offBlocks : cardinal; offData : cardinal; Geometry : VDIDISKGEOMETRY; u32Translation : cardinal; cbDisk : int64; cbBlock : cardinal; cbBlockExtra : cardinal; cBlocks : cardinal; cBlocksAllocated : cardinal; uuidCreate : TGuid; uuidModify : TGuid; uuidLinkage : TGuid; uuidParentModify : TGuid; end; function vdi_read_buffer_at_offset(handle:thandle;buffer:pointer;size:cardinal; offset:int64):integer;stdcall; function vdi_write_buffer_at_offset(handle:thandle;buffer:pointer;size:cardinal; offset:int64):integer;stdcall; function vdi_open(filename:pansichar;read_only:integer):thandle;stdcall; function vdi_close(handle:thandle):boolean;stdcall; function vdi_get_media_size():int64;stdcall; function vdi_get_offset_datas():int64;stdcall; function vdi_get_offset_blocks():int64;stdcall; function vdi_get_blocks_allocated():int64;stdcall; implementation var BlockSize,offblocks,offData,BlocksAllocated:cardinal; IndexMap:array of dword; media_size:int64; function round512(n:cardinal):cardinal; begin if n mod 512=0 then result:= (n div 512) * 512 else result:= (1 + (n div 512)) * 512 end; function vdi_get_media_size():int64;stdcall; begin result:=media_size; end; function vdi_get_offset_datas():int64;stdcall; begin result:=offData ; end; function vdi_get_offset_blocks():int64;stdcall; begin result:=offblocks ; end; function vdi_get_blocks_allocated():int64;stdcall; begin result:=BlocksAllocated ; end; { Hsize = 512 + 4N + (508 + 4N) mod 512 = offdata Zblock = int( Z / BlockSize ) Zoffset = Z mod BlockSize Fblock = IndexMap[Zblock] Fposition = Hsize + ( Fblock * BlockSize ) + ZOffset } function vdi_read_buffer_at_offset(handle:thandle;buffer:pointer;size:cardinal; offset:int64):integer;stdcall; var readbytes:cardinal; zblock,zoffset:integer; fposition:int64; fblock:dword; begin result:=0; if offset>=media_size then exit; zblock:=offset div BlockSize ; zoffset:= offset mod BlockSize ; fblock:=IndexMap[zblock]; if fblock=high(dword) then begin {$i-}writeln('vdi_read_buffer_at_offset block not found:'+inttostr(zblock));{$i+} zeromemory(buffer,size); result:=size; exit; end; fposition:=offData + (fblock * BlockSize ) + zoffset ; {$i-}writeln('vdi_read_buffer_at_offset - size:'+inttostr(size)+' offset:'+inttostr(fposition));{$i+} try readbytes:=0; //if SetFilePointer(handle, fposition, nil, FILE_BEGIN)<>INVALID_SET_FILE_POINTER if SetFilePointer(handle, int64rec(fposition).lo, @int64rec(fposition).hi, FILE_BEGIN)<>INVALID_SET_FILE_POINTER then readfile(handle,buffer^,size,readbytes,nil); result:=readbytes; except on e:exception do {$i-}writeln(e.message);{$i+} end; end; function rewrite_indexmap(handle:thandle):boolean; var readbytes,writtenbytes:cardinal; buffer:array[0..511] of byte; p:pointer; begin // SetFilePointer(handle, 0, nil, FILE_BEGIN); ReadFile(handle, buffer, sizeof(buffer), readbytes, nil); PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cBlocksAllocated:=BlocksAllocated ; writtenbytes:=0; if SetFilePointer(handle, 0, nil, FILE_BEGIN)<>INVALID_SET_FILE_POINTER then writefile(handle,buffer,sizeof(buffer),writtenbytes,nil); // getmem(p,length(indexmap)*sizeof(dword)); copymemory(p,@indexmap[0],length(indexmap)*sizeof(dword)); writtenbytes:=0; if SetFilePointer(handle, offblocks, nil, FILE_BEGIN)<>INVALID_SET_FILE_POINTER then writefile(handle,p^,length(indexmap)*sizeof(dword),writtenbytes,nil); freemem(p); end; function vdi_write_buffer_at_offset(handle:thandle;buffer:pointer;size:cardinal; offset:int64):integer;stdcall; var writtenbytes:cardinal; zblock,zoffset:integer; fposition:int64; fblock:dword; begin zblock:=offset div BlockSize ; zoffset:= offset mod BlockSize ; fblock:=IndexMap[zblock]; if fblock=high(dword) then begin //{$i-}writeln('vdi_write_buffer_at_offset - offset:'+inttostr(offset)+ ' block not found:'+inttostr(zblock));{$i+} {$i-}writeln('vdi_write_buffer_at_offset - allocating new block:'+inttostr(zblock));{$i+} IndexMap[BlocksAllocated]:=1+IndexMap[BlocksAllocated-1]; BlocksAllocated:=BlocksAllocated+1; rewrite_indexmap(handle); fblock:=IndexMap[zblock]; //result:=0; //exit; end; fposition:=offData + (fblock * BlockSize ) + zoffset ; {$i-}writeln('vdi_write_buffer_at_offset - size:'+inttostr(size)+' offset:'+inttostr(fposition));{$i+} try writtenbytes:=0; if SetFilePointer(handle, fposition, nil, FILE_BEGIN)<>INVALID_SET_FILE_POINTER then writefile(handle,buffer^,size,writtenbytes,nil); result:=writtenbytes; except on e:exception do {$i-}writeln(e.message);{$i+} end; if writtenbytes =0 then {$i-}writeln('vdi_write_buffer_at_offset - offset:'+inttostr(fposition)+' error:'+inttostr(getlasterror));{$i+} end; function vdi_close(handle:thandle):boolean;stdcall; begin result:=Closehandle(handle); { *Converti depuis CloseHandle* } end; function vdi_open(filename:pansichar;read_only:integer):thandle;stdcall; var Src:thandle; buffer:array[0..511] of byte; mapsize,readbytes:cardinal; p:pointer; begin result:=dword(-1); if read_only=1 then Src:=CreateFileA(filename, GENERIC_READ, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0) else Src:=CreateFileA(filename, GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if src<>dword(-1) then begin fillchar(buffer,sizeof(buffer),0); ReadFile(Src, buffer, sizeof(buffer), readbytes, nil); {$i-}writeln ('szFileInfo:'+strpas(PVDIPREHEADER(@buffer[0])^.szFileInfo)); {$i+} {$i-}writeln ('u32Signature:'+inttohex(PVDIPREHEADER(@buffer[0])^.u32Signature,4));{$i+} {$i-}writeln ('u32Version:'+inttostr(PVDIPREHEADER(@buffer[0])^.u32Version));{$i+} {$i-}writeln ('cbHeader:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cbHeader));{$i+} {$i-}writeln ('u32Type:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.u32Type));{$i+} {$i-}writeln ('fFlags:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.fFlags));{$i+} {$i-}writeln ('szComment:'+strpas(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.szComment));{$i+} {$i-}writeln ('offBlocks:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.offBlocks));{$i+} {$i-}writeln ('offData:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.offData));{$i+} {$i-}writeln ('cCylinders:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.Geometry.cCylinders ));{$i+} {$i-}writeln ('cHeads:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.Geometry.cHeads ));{$i+} {$i-}writeln ('cSectors:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.Geometry.cSectors ));{$i+} {$i-}writeln ('cbSector:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.Geometry.cbSector ));{$i+} {$i-}writeln ('cbSector:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.u32Translation ));{$i+} {$i-}writeln ('cbDisk:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cbDisk )); {$i+} {$i-}writeln ('cbBlock:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cbBlock ));{$i+} {$i-}writeln ('cbBlockExtra:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cbBlockExtra ));{$i+} {$i-}writeln ('cBlocks:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cBlocks ));{$i+} {$i-}writeln ('cBlocksAllocated:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cBlocksAllocated ));{$i+} //needed when reading media_size:=PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cbDisk ; offblocks :=PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.offBlocks; offData := PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.offData; blocksize:=PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cbBlock; BlocksAllocated:=PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cBlocksAllocated; // //get indexmap SetFilePointer(src, offblocks, nil, FILE_BEGIN); mapsize:=round512(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cBlocks); setlength(IndexMap,mapsize); getmem(p,mapsize*4); readfile(src,p^,mapsize*4,readbytes,nil); copymemory(@IndexMap[0],p,mapsize*4); freemem(p); // result:=src; end; end; end.
unit uHistoryGen; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, uMemoControl, uFControl, uLabeledFControl, uCharControl, Buttons, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet; type TfmHistoryGen = class(TForm) DBUser: TqFCharControl; DBPassword: TqFCharControl; Tables: TqFMemoControl; SaveDialog1: TSaveDialog; OkButton: TBitBtn; CancelButton: TBitBtn; DB: TpFIBDatabase; ReadTransaction: TpFIBTransaction; DefaultTransaction: TpFIBTransaction; FieldsDS: TpFIBDataSet; ConnectionString: TqFCharControl; SQLListBox: TListBox; procedure OkButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure CancelButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var fmHistoryGen: TfmHistoryGen; implementation {$R *.dfm} uses qFTools; procedure TfmHistoryGen.OkButtonClick(Sender: TObject); var i: Integer; table_name, hst_table_name, fields, old_fields, new_fields, trigSQL: string; SQL: string; f: TextFile; begin DB.Connected := False; DB.DBName := ConnectionString.Value; DB.ConnectParams.UserName := DBUser.Value; DB.ConnectParams.Password := DBPassword.Value; DB.Connected := True; for i := 0 to Tables.Memo.Lines.Count - 1 do begin table_name := Tables.Memo.Lines[i]; FieldsDS.Close; FieldsDS.ParamByName('Table_Name').AsString := table_name; FieldsDS.Open; // history table hst_table_name := Copy(table_name + '_HST', 0, 31); SQL := SQL + 'CREATE TABLE ' + hst_table_name + '('#13#10 + ' Id_Hst Tkey16 NOT NULL,'#13#10 + ' User_Fio_Hst Tvarchar255,'#13#10 + ' Date_Time_Hst Ttimestamp,'#13#10 + ' Action_Hst Tvarchar20,'#13#10 + ' Id_History_Info_Hst Tkey16_Maynull,'#13#10; fields := ''; old_fields := ''; new_fields := ''; FieldsDS.First; while not FieldsDS.Eof do begin SQL := SQL + ' ' + FieldsDS['RDB$Field_Name'] + ' ' + FieldsDS['RDB$Field_Source']; fields := fields + ' ' + FieldsDS['RDB$Field_Name']; old_fields := old_fields + ' OLD.' + FieldsDS['RDB$Field_Name']; new_fields := new_fields + ' NEW.' + FieldsDS['RDB$Field_Name']; FieldsDS.Next; if not FieldsDS.Eof then begin SQL := SQL + ','; fields := fields + ','#13#10; old_fields := old_fields + ','#13#10; new_fields := new_fields + ','#13#10; end; SQL := SQL + #13#10; end; SQL := SQL + ');'#13#10#13#10; // trigger trigSQL := SQLListBox.Items.Text; trigSQL := StringReplace(trigSQL, ':Table_Name', table_name, [rfReplaceAll]); trigSQL := StringReplace(trigSQL, ':Hst_Table_Name', hst_table_name, [rfReplaceAll]); trigSQL := StringReplace(trigSQL, ':Fields', fields, [rfReplaceAll]); trigSQL := StringReplace(trigSQL, ':Old_Fields', old_fields, [rfReplaceAll]); trigSQL := StringReplace(trigSQL, ':New_Fields', new_fields, [rfReplaceAll]); SQL := SQL + trigSQL; end; if SaveDialog1.Execute then begin AssignFile(f, SaveDialog1.FileName); Rewrite(f); Write(f, SQL); CloseFile(f); ShowMessage('Ok!'); end; end; procedure TfmHistoryGen.FormClose(Sender: TObject; var Action: TCloseAction); begin qFAutoSaveIntoRegistry(Self); end; procedure TfmHistoryGen.FormCreate(Sender: TObject); begin qFAutoLoadFromRegistry(Self); end; procedure TfmHistoryGen.CancelButtonClick(Sender: TObject); begin Close; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Options.Common; interface uses DPM.Core.Types; type TCommonOptions = class private FNoBanner : boolean; FVerbosity : TVerbosity; FHelp : boolean; FConfigFile : string; FNonInteractive : boolean; class var FDefault : TCommonOptions; public class constructor CreateDefault; class property Default : TCommonOptions read FDefault; constructor Create; property NonInteractive : boolean read FNonInteractive write FNonInteractive; property NoBanner : boolean read FNoBanner write FNoBanner; property Verbosity : TVerbosity read FVerbosity write FVerbosity; property Help : boolean read FHelp write FHelp; property ConfigFile : string read FConfigFile write FConfigFile; end; implementation { TCommonOptions } constructor TCommonOptions.Create; begin {$IFDEF DEBUG} FVerbosity := TVerbosity.Debug; {$ELSE} FVerbosity := TVerbosity.Normal; {$ENDIF} end; class constructor TCommonOptions.CreateDefault; begin FDefault := TCommonOptions.Create; end; end.
unit UPessoaJuridica; interface uses UPessoa; type TPessoaJuridica = Class(TPessoa) private protected FRS:string; FFantasia:string; FIE:String; FCNPJ:String; FTelefone2:string; FCelular2:string; public constructor Create; destructor Destroy; procedure setRS(vRS:string); procedure setFantasia(vFantasia:string); procedure setIE(vIE:string); procedure setCNPJ(vCNPJ:string); procedure setTelefone2(vTelefone2:string); procedure setCelular2(vCelular2:string); function getRS:string; function getFantasia:string; function getIE:string; function getCNPJ:string; function getTelefone2:string; function getCelular2:string; property RS:String read getRS write setRS; property Fantasia:string read getFantasia write setFantasia; property IE:string read getIE write setIE; property CNPJ:string read getCNPJ write setCNPJ; property Telefone2:string read getTelefone2 write setTelefone2; property Celular2:string read getCelular2 write setCelular2; End; implementation { TPessoaJuridica } constructor TPessoaJuridica.Create; begin inherited; FRS:=''; FFantasia:=''; FIE:=''; FCNPJ:=''; FTelefone2:=''; FCelular2:=''; end; destructor TPessoaJuridica.Destroy; begin inherited; end; function TPessoaJuridica.getCelular2: string; begin Result:=FCelular2; end; function TPessoaJuridica.getCNPJ: string; begin Result:=FCNPJ; end; function TPessoaJuridica.getFantasia: string; begin Result:=FFantasia; end; function TPessoaJuridica.getIE: string; begin Result:=FIE; end; function TPessoaJuridica.getRS: string; begin Result:= FRS; end; function TPessoaJuridica.getTelefone2: string; begin Result:=FTelefone2; end; procedure TPessoaJuridica.setCelular2(vCelular2: string); begin FCelular2:=vCelular2; end; procedure TPessoaJuridica.setCNPJ(vCNPJ: string); begin FCNPJ:=vCNPJ; end; procedure TPessoaJuridica.setFantasia(vFantasia: string); begin FFantasia:=vFantasia; end; procedure TPessoaJuridica.setIE(vIE: string); begin FIE:=vIE; end; procedure TPessoaJuridica.setRS(vRS: string); begin FRS:=vRS; end; procedure TPessoaJuridica.setTelefone2(vTelefone2: string); begin FTelefone2:=vTelefone2; end; end.
unit Objekt.Ini; interface uses SysUtils, Classes, variants, Objekt.Global; type TIni = class(TComponent) private function getTMSPfad: string; procedure setTMSPfad(const Value: string); function getAV_TMS: string; procedure setAV_TMS(const Value: string); function getBibliotheksPfad32: string; procedure setBibliotheksPfad32(const Value: string); function getSuchPfad32: string; procedure setSuchpfad32(const Value: string); function getOptimaPfad: string; procedure setOptimaPfad(const Value: string); function getAV_OPTIMA: string; procedure setAV_OPTIMA(const Value: string); function getBibliotheksPfad64: string; function getSuchPfad64: string; procedure setBibliotheksPfad64(const Value: string); procedure setSuchpfad64(const Value: string); function getGnosticePfad: string; procedure setGnosticePfad(const Value: string); function getMadCollectionPfad: string; procedure setMadCollectionPfad(const Value: string); protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property TMSPfad: string read getTMSPfad write setTMSPfad; property OptimaPfad: string read getOptimaPfad write setOptimaPfad; property GnosticePfad: string read getGnosticePfad write setGnosticePfad; property MadCollectionPfad: string read getMadCollectionPfad write setMadCollectionPfad; property AV_TMS: string read getAV_TMS write setAV_TMS; // Anwendervariable TMS property AV_OPTIMA: string read getAV_OPTIMA write setAV_OPTIMA; // Anwendervariable Optima-Komponenten property BibliotheksPfad32: string read getBibliotheksPfad32 write setBibliotheksPfad32; property Suchpfad32: string read getSuchPfad32 write setSuchpfad32; property BibliotheksPfad64: string read getBibliotheksPfad64 write setBibliotheksPfad64; property Suchpfad64: string read getSuchPfad64 write setSuchpfad64; end; implementation { TIni } uses Allgemein.RegIni; constructor TIni.Create(AOwner: TComponent); begin inherited; end; destructor TIni.Destroy; begin inherited; end; function TIni.getAV_OPTIMA: string; begin Result := ReadRegistry(HKEY_CURRENT_USER_, 'Software\Embarcadero\BDS\19.0\Environment Variables', 'OPTIMA', ''); end; function TIni.getAV_TMS: string; begin Result := ReadRegistry(HKEY_CURRENT_USER_, 'Software\Embarcadero\BDS\19.0\Environment Variables', 'TMS', ''); end; function TIni.getBibliotheksPfad32: string; begin Result := ReadRegistry(HKEY_CURRENT_USER_, 'Software\Embarcadero\BDS\19.0\Library\Win32', 'Search Path', ''); end; function TIni.getBibliotheksPfad64: string; begin Result := ReadRegistry(HKEY_CURRENT_USER_, 'Software\Embarcadero\BDS\19.0\Library\Win64', 'Search Path', ''); end; function TIni.getGnosticePfad: string; begin Result := ReadIni(Global.IniFilename, 'Pfad', 'Gnostice', ''); end; function TIni.getMadCollectionPfad: string; begin Result := ReadIni(Global.IniFilename, 'Pfad', 'MadCollection', ''); end; function TIni.getOptimaPfad: string; begin Result := ReadIni(Global.IniFilename, 'Pfad', 'OPTIMA', ''); end; function TIni.getSuchPfad32: string; begin Result := ReadRegistry(HKEY_CURRENT_USER_, 'Software\Embarcadero\BDS\19.0\Library\Win32', 'Browsing Path', ''); end; function TIni.getSuchPfad64: string; begin Result := ReadRegistry(HKEY_CURRENT_USER_, 'Software\Embarcadero\BDS\19.0\Library\Win64', 'Browsing Path', ''); end; function TIni.getTMSPfad: string; begin Result := ReadIni(Global.IniFilename, 'Pfad', 'TMS', ''); end; procedure TIni.setAV_TMS(const Value: string); begin WriteRegistry(HKEY_CURRENT_USER_, 'Software\Embarcadero\BDS\19.0\Environment Variables', 'TMS', Value); end; procedure TIni.setBibliotheksPfad32(const Value: string); begin WriteRegistry(HKEY_CURRENT_USER_, 'Software\Embarcadero\BDS\19.0\Library\Win32', 'Search Path', Value); end; procedure TIni.setBibliotheksPfad64(const Value: string); begin WriteRegistry(HKEY_CURRENT_USER_, 'Software\Embarcadero\BDS\19.0\Library\Win64', 'Search Path', Value); end; procedure TIni.setGnosticePfad(const Value: string); begin WriteIni(Global.IniFilename, 'Pfad', 'Gnostice', Value); end; procedure TIni.setMadCollectionPfad(const Value: string); begin WriteIni(Global.IniFilename, 'Pfad', 'MadCollection', Value); end; procedure TIni.setAV_OPTIMA(const Value: string); begin WriteRegistry(HKEY_CURRENT_USER_, 'Software\Embarcadero\BDS\19.0\Environment Variables', 'OPTIMA', Value); end; procedure TIni.setOptimaPfad(const Value: string); begin WriteIni(Global.IniFilename, 'Pfad', 'OPTIMA', Value); end; procedure TIni.setSuchpfad32(const Value: string); begin WriteRegistry(HKEY_CURRENT_USER_, 'Software\Embarcadero\BDS\19.0\Library\Win32', 'Browsing Path', Value); end; procedure TIni.setSuchpfad64(const Value: string); begin WriteRegistry(HKEY_CURRENT_USER_, 'Software\Embarcadero\BDS\19.0\Library\Win64', 'Browsing Path', Value); end; procedure TIni.setTMSPfad(const Value: string); begin WriteIni(Global.IniFilename, 'Pfad', 'TMS', Value); end; end.
unit FDBase; (*==================================================================== MDI Window with one database. Here is the top level implementation of most DiskBase commands. ======================================================================*) interface uses SysUtils, {$ifdef mswindows} Windows {$ELSE} LCLIntf, LCLType, LMessages, ComCtrls, {$ENDIF} Messages, Classes, Graphics, Controls, Forms, Dialogs, Grids, Outline, StdCtrls, ExtCtrls, Menus, FSettings, UCollectionsExt, UApiTypes, UStringList, UTypes, PrintersDlgs {$ifdef LOGFONT} , UFont {$endif} ; const MaxTreeLevels = 32; maxColumnAttribs = 6; defHintDelayPeriod = 100; type TOneColumn = record Width : Integer; Content: (coName, coTime, coSize, coDesc); end; TPrintWhat = (prSelectedPanel, prDisks, prTree, prFiles); // class representing one displayed line of the folder tree TOneTreeLine = class(TObject) Level : Integer; Line : string[MaxTreeLevels]; end; // class representing one displayed line of the folders TOneFileLine = class(TObject) POneFile : TPOneFile; FileType : TFileType; ExtAttr : byte; constructor Create(aOneFile: TOneFile); destructor Destroy; override; end; { TFormDBase } TFormDBase = class(TForm) ///HeaderTop: THeader; ///OutlineTree: TOutline; HeaderTop: THeaderControl; ImageList: TImageList; OutlineTree: TTreeView; MenuDeleteFile: TMenuItem; DrawGridDisks: TDrawGrid; DrawGridFiles: TDrawGrid; PopupMenuDisk: TPopupMenu; PopupMenuTree: TPopupMenu; PopupMenuFiles: TPopupMenu; MenuDeleteDisk: TMenuItem; MenuUndeleteDisk: TMenuItem; MenuRenameDisk: TMenuItem; MenuSelectDisks: TMenuItem; MenuDeselectDisk: TMenuItem; MenuShowTree: TMenuItem; MenuExpandTree: TMenuItem; MenuBrief: TMenuItem; MenuDetailed: TMenuItem; N1: TMenuItem; MenuSortName: TMenuItem; MenuSortExt: TMenuItem; MenuSortTime: TMenuItem; MenuSortSize: TMenuItem; N2: TMenuItem; MenuHelpFiles: TMenuItem; N3: TMenuItem; MenuEditDesc: TMenuItem; MenuPrintFiles: TMenuItem; MenuCopyFile: TMenuItem; N4: TMenuItem; MenuHelpTree: TMenuItem; MenuHelpDisks: TMenuItem; N6: TMenuItem; MenuPrintDisks: TMenuItem; MenuInfoDisk: TMenuItem; MenuCollapseTree: TMenuItem; MenuSelectFiles: TMenuItem; MenuUnselectFiles: TMenuItem; MenuSelectAllFiles: TMenuItem; N5: TMenuItem; N7: TMenuItem; MenuSelectAllDisks: TMenuItem; MenuCopyDisk: TMenuItem; N8: TMenuItem; ///PrintDialog: TPrintDialog; MenuPrintTree: TMenuItem; MenuRescan: TMenuItem; HeaderBottom: THeaderControl; MenuOpen: TMenuItem; PrintDialog: TPrintDialog; Splitter1: TSplitter; Splitter2: TSplitter; procedure HeaderTopSized(Sender: TObject; ASection, AWidth: Integer); procedure FormCreate(Sender: TObject); procedure ChangePanel(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure DrawGridDisksDrawCell(Sender: TObject; Col, Row: Longint; Rect: TRect; State: TGridDrawState); procedure DrawGridDisksDblClick(Sender: TObject); procedure DrawGridDisksKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DrawGridFilesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormResize(Sender: TObject); procedure DrawGridFilesDrawCell(Sender: TObject; Col, Row: Longint; Rect: TRect; State: TGridDrawState); procedure DrawGridFilesSelectCell(Sender: TObject; Col, Row: Longint; var CanSelect: Boolean); procedure DrawGridDisksSelectCell(Sender: TObject; Col, Row: Longint; var CanSelect: Boolean); procedure OutlineTreeClick(Sender: TObject); procedure DrawGridFilesDblClick(Sender: TObject); procedure DrawGridFilesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure DrawGridDisksMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure MenuDeleteDiskClick(Sender: TObject); procedure MenuUndeleteDiskClick(Sender: TObject); procedure MenuRenameDiskClick(Sender: TObject); procedure MenuSelectDisksClick(Sender: TObject); procedure MenuDeselectDiskClick(Sender: TObject); procedure MenuInfoDiskClick(Sender: TObject); procedure MenuPrintDisksClick(Sender: TObject); procedure MenuHelpDisksClick(Sender: TObject); procedure PopupMenuTreePopup(Sender: TObject); procedure MenuShowTreeClick(Sender: TObject); procedure MenuExpandTreeClick(Sender: TObject); procedure MenuHelpTreeClick(Sender: TObject); procedure MenuCollapseTreeClick(Sender: TObject); procedure PopupMenuFilesPopup(Sender: TObject); procedure MenuCopyFileClick(Sender: TObject); procedure MenuEditDescClick(Sender: TObject); procedure MenuBriefClick(Sender: TObject); procedure MenuDetailedClick(Sender: TObject); procedure MenuSortNameClick(Sender: TObject); procedure MenuSortExtClick(Sender: TObject); procedure MenuSortTimeClick(Sender: TObject); procedure MenuSortSizeClick(Sender: TObject); procedure MenuPrintFilesClick(Sender: TObject); procedure MenuHelpFilesClick(Sender: TObject); procedure PopupMenuDiskPopup(Sender: TObject); procedure MenuSelectFilesClick(Sender: TObject); procedure MenuUnselectFilesClick(Sender: TObject); procedure MenuSelectAllFilesClick(Sender: TObject); procedure MenuSelectAllDisksClick(Sender: TObject); procedure MenuCopyDiskClick(Sender: TObject); procedure MenuPrintTreeClick(Sender: TObject); procedure MenuRescanClick(Sender: TObject); procedure DrawGridFilesMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure MenuOpenClick(Sender: TObject); procedure SplitterMoved(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure MenuDeleteFileClick(Sender: TObject); private FilesList : TQStringList; NeedReSort : boolean; {if QOptions.SortCrit changes, resort in idle time} TreePtrCol : PQPtrCollection; DirToScrollHandle : PDirColHandle; ColumnAttrib : array[0..maxColumnAttribs] of TOneColumn; HeaderWidths : TPanelHeaderWidths; TimeWidth : Integer; BitmapFolder : TBitmap; BitmapParent : TBitmap; BitmapArchive : TBitmap; StatusLineFiles : ShortString; StatusLineSubTotals: ShortString; LastSelectedFile : ShortString; {name of the current file - from the status line} FormIsClosed : boolean; {because Form gets Resize Event after closing!} PanelsLocked : boolean; LastDiskSelected : Integer; {for undo} LastFileSelected : Integer; CurFileSelected : Integer; ScrollBarHeight : Integer; MakeDiskSelection : boolean; {set when shift is pressed} MakeFileSelection : boolean; MaxFileNameLength : Integer; {max. length of name in current list} MaxFileNamePxLength: Integer; FormWasResized : Integer; {the ResizeEvent appears multiple times, so we must limit the response} SubTotals : TSubTotals; StatusSection0Size : Integer; LastMouseMoveTime : longint; FilesHintDisplayed : boolean; LastMouseXFiles : integer; LastMouseYFiles : integer; LastHintRect : TRect; DisableHints : integer; DisableNextDoubleClick: boolean; MousePosAlreadyChecked: boolean; ShiftState : TShiftState; // for mouse double click check procedure ResetDrawGridFiles; procedure UpdateDiskWindow; procedure UpdateFileWindowGrid(SelPos: Integer); procedure ScanTree(DirColHandle: PDirColHandle; Level: Integer; var TotalItemCount: Integer); procedure ReloadTree; procedure RescanTree(SavePosition: boolean); function GetSelectedFileName: ShortString; procedure ReloadFileCol(SaveFileName: ShortString); ///procedure ExpandBranch(AnItem: TOutlineNode); procedure ExpandBranch(AnItem: TTreeNode); procedure JumpInOutline(SubDirCol: pointer); procedure ResetFontsAndRowHeights; procedure UpdateStatusLine(Index: Integer; SubTotalsToo: boolean); procedure UpdateHeader; procedure ResizeHeaderBottom; function DoScan (Drive: char; StartPath: ShortString; DiskName: ShortString; AutoRun, NoOverWarning: boolean): boolean; procedure ScanQDir4Database; procedure FindConvertDLLs; procedure DrawGridFilesToggleSelection; procedure ShowFileHint; procedure EraseFileHint; function FindOneFileLine(Point: TPoint; var Rect: TRect): TOneFileLine; procedure ExecuteUserCommand(sDll: AnsiString; sParams: AnsiString; bTestExist: boolean); public DBaseHandle : PDBaseHandle; QGlobalOptions : TGlobalOptions; {class} QLocalOptions : TLocalOptions; {record} ConvertDLLs : TStringList; DBaseFileName : ShortString; ShortDBaseFileName : ShortString; DBaseIsReadOnly : boolean; function AttachDBase(FName: ShortString): boolean; procedure LocalIdle; procedure LocalTimer; procedure ChangeGlobalOptions; procedure ChangeLocalOptions; procedure SetBriefFileDisplay(Brief: boolean); procedure ShowOrHideTreePanel; procedure SetNeedResort(SortCrit: TSortCrit); function DBaseIsEmpty: boolean; procedure MsgShouldExit; function ScanDisk (Drive: char; AutoRun: boolean): boolean; // returns false when interrupted procedure RescanDisk; procedure ScanFolder(Directory, DiskName, VolumeLabel: ShortString; NoOverWarning: boolean); procedure ImportFromQDir41(FileName: ShortString); procedure DeleteRecord; function CanUndeleteRecord: boolean; procedure UndeleteRecord; procedure ChangeDiskName; procedure SearchName; procedure SearchSelected; procedure SearchParam(ParamFindFile: ShortString); procedure SearchEmpty; procedure ShowDiskInfo; procedure ShowDBaseInfo; procedure JumpTo(Disk, Dir, FileName: ShortString); procedure EditDescription; function GetDBaseHandle: PDBaseHandle; procedure SelectDisksOrFiles (Disks: boolean); procedure SelectAllDisksOrFiles (Disks: boolean); procedure UnselectDisksOrFiles (Disks: boolean); procedure GoToParent; procedure DoSelection; procedure SelectAll; procedure UnselectAll; procedure MakeCopy; procedure MakeCopyDisks; procedure MakeCopyFiles; procedure DeleteFiles; function ActivePanel: Integer; procedure MakePrintDisk; procedure MakePrintTree; procedure MakePrintFiles; procedure DoPrint(PrintWhat: TPrintWhat); procedure ExportToOtherFormat; procedure ExecFile(POneFile: TPOneFile); procedure OpenExplorer(POneFile: TPOneFile); procedure DiscGearPrint(hWindow: HWND); end; function GetSortString(OneFile: TOneFile; FileType: TFileType; SortCrit: TSortCrit; Reversed: boolean): ShortString; var g_bShowHelpAfterClose: boolean; g_PanelHeaderWidths : TPanelHeaderWidths; //==================================================================== implementation uses Clipbrd, {Printers,} UExceptions, {ShellApi,} FAskForLabel, FScanProgress, FDiskInfo, FDBInfo, FDescription, UBaseUtils, FMain, FFindFile, FFindEmpty, FFindFileDlg, FFindEmptyDlg, FFoundFile, FFoundEmpty, FRenameDlg, FLocalOptions, FMaskSelect, UCollections, FAbortPrint, FDiskPrint, UApi, ULang, UPrinter, FScanFolder, UDrives, FHidden, UExport, FDiskExport, UDebugLog, UUserDll, UPluginDiscGear; {$R *.dfm} const ClipboardLimit: longint = 63 * 1024 + 1000; boSavePos = true; boJumpToDir = false; var TmpLocalOptions: TLocalOptions; //-------------------------------------------------------------------- // creates sort string from the name - assures that folders are always first function GetSortString(OneFile: TOneFile; FileType: TFileType; SortCrit: TSortCrit; Reversed: boolean): ShortString; var TmpL: longint; begin Result[0] := #1; with OneFile do begin if SortCrit <> scUnsort then begin if Reversed then begin Result[1] := '1'; if FileType = ftParent then Result[1] := '4'; if FileType = ftDir then Result[1] := '3'; if (LongName+Ext) = lsDiskInfo then Result[1] := '5'; end else begin Result[1] := '5'; if FileType = ftParent then Result[1] := '2'; if FileType = ftDir then Result[1] := '3'; if (LongName+Ext) = lsDiskInfo then Result[1] := '1'; end; end; case SortCrit of scName: begin Result := Result + LongName + Ext; end; scExt: begin Result := Result + Ext + LongName; end; scTime: begin TmpL := MaxLongInt - Time; Result := Result + Format('%10.10d', [TmpL]) + Ext + LongName; end; scSize: begin TmpL := MaxLongInt - Size; Result := Result + Format('%10.10d', [TmpL]) + Ext + LongName; end; end; end; end; //-------------------------------------------------------------------- function GridRect(Left, Top, Right, Bottom: longint): TGridRect; begin Result.Top := Top; Result.Left := Left; Result.Bottom := Bottom; Result.Right := Right; end; //=TOneFileLine======================================================= // TOneFileLine constructor - gets the file type constructor TOneFileLine.Create(aOneFile: TOneFile); begin GetMemOneFile(POneFile, aOneFile); ExtAttr := 0; with POneFile^ do begin if LongName = '..' then FileType := ftParent else if Attr and faQArchive = faQArchive then FileType := ftArc else if Attr and faDirectory = faDirectory then FileType := ftDir else FileType := ftFile; end; end; //-------------------------------------------------------------------- // TOneFileLine destructor destructor TOneFileLine.Destroy; begin FreeMemOneFile(POneFile); end; //===TFormDBase======================================================= // event -issued when the user resizes the top bar with Disk-Tree-Files // - the panels are resized accordingly and saved to global options procedure TFormDBase.HeaderTopSized(Sender: TObject; ASection, AWidth: Integer); var i: Integer; begin if FormIsClosed then exit; ///for i := 0 to 2 do HeaderWidths[i] := HeaderTop.SectionWidth[i]; for i := 0 to 2 do HeaderWidths[i] := HeaderTop.Sections[i].Width; QGlobalOptions.PanelHeaderWidths := HeaderWidths; g_PanelHeaderWidths := HeaderWidths; ResizeHeaderBottom; case ASection of 0: begin DrawGridDisks.Width := AWidth; if AWidth > 50 then DrawGridDisks.ColWidths[0] := DrawGridDisks.Width-2 else DrawGridDisks.ColWidths[0] := 50; end; 1: begin if QGlobalOptions.ShowTree then OutlineTree.Width := AWidth; end; 2: begin end; end; end; //-------------------------------------------------------------------- // event issued when the user moves with the splitter between panels procedure TFormDBase.SplitterMoved(Sender: TObject); begin if FormIsClosed then exit; HeaderWidths[0] := DrawGridDisks.Width + Splitter1.Width div 2; HeaderWidths[1] := OutlineTree.Width + Splitter1.Width div 2 + Splitter2.Width div 2; HeaderWidths[2] := DrawGridFiles.Width; QGlobalOptions.PanelHeaderWidths := HeaderWidths; g_PanelHeaderWidths := HeaderWidths; ResizeHeaderBottom; if DrawGridDisks.Width > 50 then DrawGridDisks.ColWidths[0] := DrawGridDisks.Width-2 else DrawGridDisks.ColWidths[0] := 50; ///HeaderTop.SectionWidth[0] := HeaderWidths[0]; HeaderTop.Sections[0].Width := HeaderWidths[0]; if not OutlineTree.Visible then begin ///HeaderTop.SectionWidth[1] := 0; ///eaderTop.SectionWidth[2] := HeaderWidths[1] + HeaderWidths[2]; HeaderTop.Sections[1].Width := 0; HeaderTop.Sections[2].Width := HeaderWidths[1] + HeaderWidths[2]; end else begin ///HeaderTop.SectionWidth[1] := HeaderWidths[1]; ///HeaderTop.SectionWidth[2] := HeaderWidths[2]; HeaderTop.Sections[1].Width := HeaderWidths[1]; HeaderTop.Sections[2].Width := HeaderWidths[2]; end; end; //-------------------------------------------------------------------- // Called when the form is created or display options are changed // recalculates the properties of the Files panel procedure TFormDBase.ResetDrawGridFiles; var i : Integer; WidthInPixels: Integer; //S: shortString; begin ResetFontsAndRowHeights; if QGlobalOptions.FileDisplayType = fdBrief then with DrawGridFiles do begin Options := [goFixedVertLine, goFixedHorzLine, goVertLine, goDrawFocusSelected]; FixedRows := 0; ColCount := 1; ScrollBars := ssHorizontal; end; if QGlobalOptions.FileDisplayType = fdDetailed then with DrawGridFiles do begin Options := [goFixedVertLine, goFixedHorzLine, goVertLine, goDrawFocusSelected, goRowSelect, goColSizing]; RowCount := 2; FixedRows := 1; ScrollBars := ssBoth; i := 0; WidthInPixels := MaxFileNamePxLength + 5; if QGlobalOptions.ShowIcons then inc(WidthInPixels, BitmapFolder.Width); ColumnAttrib[i].Width := WidthInPixels; ColumnAttrib[i].Content := coName; inc(i); if QGlobalOptions.ShowSize then begin ColumnAttrib[i].Width := DrawGridFiles.Canvas.TextWidth(FormatSize(2000000000, QGlobalOptions.ShowInKb)) + 2; ColumnAttrib[i].Content := coSize; inc(i); end; if QGlobalOptions.ShowTime then begin ColumnAttrib[i].Width := DrawGridFiles.Canvas.TextWidth(' ' + DosDateToStr (694026240)) { 30.10.2000 } + TimeWidth + 2; {timewidth is set in ResetFont} ColumnAttrib[i].Content := coTime; inc(i); end; if QGlobalOptions.ShowDescr then begin ColumnAttrib[i].Width := 25 * DrawGridFiles.Canvas.TextWidth('Mmmmxxxxx '); ColumnAttrib[i].Content := coDesc; inc(i); end; ColCount := i; for i := 0 to pred(ColCount) do ColWidths[i] := ColumnAttrib[i].Width; end; end; //-------------------------------------------------------------------- // initialization done, when the form is created procedure TFormDBase.FormCreate(Sender: TObject); var i: Integer; begin FormIsClosed := false; PanelsLocked := false; StatusSection0Size := 0; ScrollBarHeight := GetSystemMetrics(SM_CXHTHUMB); {should be equal to vertical size of ScrollBar} QGlobalOptions := TGlobalOptions.Create; FormSettings.GetOptions(QGlobalOptions); HeaderTop.Font.Size := 8; HeaderBottom.Font.Size := 8; ///for i := 0 to 2 do HeaderTop.SectionWidth[i] := QGlobalOptions.PanelHeaderWidths[i]; ///for i := 0 to 2 do HeaderWidths[i] := HeaderTop.SectionWidth[i]; for i := 0 to 2 do HeaderTop.Sections[i].Width := QGlobalOptions.PanelHeaderWidths[i]; for i := 0 to 2 do HeaderWidths[i] := HeaderTop.Sections[i].Width; ///DrawGridDisks.Width := HeaderTop.SectionWidth[0]; DrawGridDisks.Width := HeaderTop.Sections[0].Width; DrawGridDisks.ColWidths[0] := DrawGridDisks.Width-2; ///OutlineTree.Width := HeaderTop.SectionWidth[1]; OutlineTree.Width := HeaderTop.Sections[1].Width; FilesList := TQStringList.Create; FilesList.Sorted := true; FilesList.Reversed := false; FilesList.Duplicates := qdupAccept; NeedReSort := false; ConvertDLLs := TStringList.Create; ConvertDLLs.Sorted := true; TreePtrCol := New(PQPtrCollection, Init(1000, 1000)); ///BitmapFolder := OutlineTree.PictureLeaf; ///BitmapParent := OutlineTree.PicturePlus; ///BitmapArchive := OutlineTree.PictureMinus; ResetDrawGridFiles; ShowOrHideTreePanel; FindConvertDLLs; Tag := GetNewTag; MakeDiskSelection := false; MakeFileSelection := false; MaxFileNameLength := 12; MaxFileNamePxLength := 50; FillChar(SubTotals, SizeOf(SubTotals), 0); LastMouseMoveTime := $0FFFFFFF; FilesHintDisplayed := false; DisableHints := 0; DisableNextDoubleClick := false; SetRectEmpty(LastHintRect); end; //-------------------------------------------------------------------- // Event issued when the MDI window with the database is to be closed procedure TFormDBase.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin MainForm.AddToLastFilesList(DBaseFileName); CanClose := true; QI_CloseDatabase(DBaseHandle, false); FormIsClosed := true; QGlobalOptions.Free; FilesList.Free; ConvertDLLs.Free; if TreePtrCol <> nil then Dispose(TreePtrCol, Done); TreePtrCol := nil; end; //-------------------------------------------------------------------- // event issued when the user changes focus between panels - either by Tab key, // or by mouse procedure TFormDBase.ChangePanel(Sender: TObject); var APanel: Integer; begin APanel := ActivePanel; EraseFileHint; if APanel = 1 ///then HeaderTop.Sections.Strings[0] := ShortDBaseFileName ///else HeaderTop.Sections.Strings[0] := ''; then HeaderTop.Sections[0].Text := ShortDBaseFileName else HeaderTop.Sections[0].Text := ''; if APanel = 2 then UpdateHeader ///else HeaderTop.Sections.Strings[1] := ''; else HeaderTop.Sections[1].Text := ''; if APanel = 3 then UpdateHeader ///else HeaderTop.Sections.Strings[2] := ''; else HeaderTop.Sections[2].Text := ''; ///HeaderTop.SectionWidth[0] := HeaderWidths[0]; ///HeaderTop.SectionWidth[2] := HeaderWidths[2]; HeaderTop.Sections[0].Width := HeaderWidths[0]; HeaderTop.Sections[2].Width := HeaderWidths[2]; if QGlobalOptions.ShowTree ///then HeaderTop.SectionWidth[1] := HeaderWidths[1] ///else HeaderTop.SectionWidth[1] := 0; then HeaderTop.Sections[1].Width := HeaderWidths[1] else HeaderTop.Sections[1].Width := 0; end; //-------------------------------------------------------------------- // event issued when the window with the database is closed procedure TFormDBase.FormClose(Sender: TObject; var Action: TCloseAction); begin if FormIsClosed then Action := caFree; end; //-------------------------------------------------------------------- // attaches a database to the MDI window function TFormDBase.AttachDBase(FName: ShortString): boolean; var SaveSelected : Integer; TmpKey : ShortString; TmpAttr : Word; Dir, Name, Ext : ShortString; DBaseInfo : TDBaseInfo; sMessage : ShortString; MsgText : array[0..256] of char; begin Result := false; try if not QI_OpenDatabase(FName, false, DBaseHandle, sMessage) then begin FormIsClosed := true; // this must be before the message box Application.MessageBox(StrPCopy(MsgText, sMessage), lsError, mb_OK or mb_IconStop); exit; end; //Expired := QI_DBaseExpired(DBaseHandle); //if (Expired <> 0) then g_bShowHelpAfterClose := true; DBaseFileName := FName; FSplit(FName, Dir, Name, Ext); ShortDBaseFileName := AnsiLowerCase(Name); ShortDBaseFileName[1] := Name[1]; Caption := ShortDBaseFileName; QI_GetLocalOptions (DBaseHandle, QLocalOptions); QI_GetCurrentKey (DBaseHandle, TmpKey, TmpAttr, SaveSelected); QI_SetCurrentKeyPos(DBaseHandle, SaveSelected); LastDiskSelected := SaveSelected; UpdateDiskWindow; Result := true; QI_GetDBaseInfo(DBaseHandle, DBaseInfo); DBaseIsReadOnly := DBaseInfo.ReadOnly; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // should be called when something changes in the Disk list // - if only selection changes, it is not a reason to call this procedure TFormDBase.UpdateDiskWindow; var CountToShow : Integer; KeyIndex : Integer; Key : ShortString; Attr : Word; begin if FormIsClosed then exit; try QI_ClearNeedUpdDiskWin(DBaseHandle); CountToShow := QI_GetCountToShow (DBaseHandle); if CountToShow = 0 then begin DrawGridDisks.Row := 0; DrawGridDisks.RowCount := 1; DrawGridDisks.Refresh; exit; end; if QI_GetCurrentKey (DbaseHandle, Key, Attr, KeyIndex) then begin if (DrawGridDisks.Row >= CountToShow) then DrawGridDisks.Row := pred(CountToShow); DrawGridDisks.RowCount := CountToShow; if DrawGridDisks.Row <> KeyIndex then if KeyIndex < DrawGridDisks.RowCount //KeyIndex value can be bigger from the past - if deleted disks were displayed then DrawGridDisks.Row := KeyIndex; DrawGridDisks.Repaint; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // called to draw one cell of the disks list procedure TFormDBase.DrawGridDisksDrawCell(Sender: TObject; Col, Row: Longint; Rect: TRect; State: TGridDrawState); var Key : ShortString; Attr : Word; IsDeleted : boolean; IsSelected : boolean; begin //LOG('DrawGridDisksDrawCell', []); if FormIsClosed then exit; try if QI_GetKeyAt(DBaseHandle, Key, Attr, Row) then begin IsDeleted := Attr and kaDeleted <> 0; IsSelected := Attr and kaSelected <> 0; if IsDeleted then Key:= '(' + Key + ')'; if IsSelected then Key := Key + #164; if IsDeleted and not(gdSelected in State) then DrawGridDisks.Canvas.Font.Color := clQDeletedText; if IsSelected and not(gdSelected in State) then begin DrawGridDisks.Canvas.Brush.Color := clQSelectedBack; DrawGridDisks.Canvas.Font.Color := clQSelectedText; end; DrawGridDisks.Canvas.TextRect(Rect, Rect.Left+1, Rect.Top, Key); //LOG('DrawGridDisks.Canvas.TextRect', []); end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // issued when the user double-clicks on the disk panel - changes // the selection flag procedure TFormDBase.DrawGridDisksDblClick(Sender: TObject); begin if FormIsClosed then exit; try QI_ToggleSelectionFlag(DBaseHandle, DrawGridDisks.Row); DrawGridDisks.Repaint; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // event issued when the user presses a key in the Disks panel procedure TFormDBase.DrawGridDisksKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if FormIsClosed then exit; if (Shift = []) then begin if ((Key = vk_Insert) or (Key = vk_Space)) then begin DrawGridDisksDblClick(Sender); if (DrawGridDisks.Row + 1) < DrawGridDisks.RowCount then DrawGridDisks.Row := DrawGridDisks.Row + 1; end; with DrawGridDisks do if RowCount > 0 then begin if Key = vk_Next then begin if (Row + VisibleRowCount) < RowCount then Row := Row + VisibleRowCount else Row := pred(RowCount); end; if Key = vk_Prior then begin if (Row - VisibleRowCount) > 0 then Row := Row - VisibleRowCount else Row := 0; end; if Key = vk_Home then Row := 0; if Key = vk_End then Row := pred(RowCount); end; end; if Key = vk_Delete then DeleteRecord; if (ssShift in Shift) and ((Key = vk_Down) or (Key = vk_Up) or (Key = vk_Prior) or (Key = vk_Next) or (Key = vk_Home) or (Key = vk_End)) then begin LastDiskSelected := DrawGridDisks.Selection.Top; MakeDiskSelection := true; end; end; //-------------------------------------------------------------------- // called when the file collection is reloaded, or the type of display is changed, // also called in idle time // SelPos = - 1 -> do not change position procedure TFormDBase.UpdateFileWindowGrid (SelPos: Integer); var WidthInPixels: Integer; CalcRows : Integer; CalcCols : Integer; SpaceForRows : Integer; begin if FormIsClosed then exit; WidthInPixels := MaxFileNamePxLength + 5; ///if QGlobalOptions.ShowIcons then inc(WidthInPixels, BitmapFolder.Width); if QGlobalOptions.FileDisplayType = fdBrief then begin if SelPos = -1 then with DrawGridFiles do SelPos := Col*RowCount + Row; SpaceForRows := DrawGridFiles.Height - 1; if SpaceForRows < 0 then SpaceForRows := 50; CalcRows := SpaceForRows div succ(DrawGridFiles.DefaultRowHeight); {succ includes the line between} if CalcRows = 0 then CalcRows := 1; CalcCols := (FilesList.Count + pred(CalcRows)) div CalcRows; if (CalcCols * succ(WidthInPixels)) >= DrawGridFiles.Width then begin {correction because of Scroll Bar} dec(SpaceForRows, ScrollBarHeight); if SpaceForRows < 0 then SpaceForRows := 50; CalcRows := SpaceForRows div succ(DrawGridFiles.DefaultRowHeight); if CalcRows = 0 then CalcRows := 1; CalcCols := (FilesList.Count + pred(CalcRows)) div CalcRows; end; with DrawGridFiles do begin Selection := GridRect(0, 0, 0, 0); {this must be here, otherwise} LeftCol := 0; {exception "Grid out of bound" happens} TopRow := 0; DefaultColWidth := WidthInPixels; RowCount := CalcRows; ColCount := CalcCols; Col := SelPos div CalcRows; Row := SelPos mod CalcRows; end; end else begin with DrawGridFiles do begin ColWidths[0] := WidthInPixels; if SelPos = -1 then SelPos := pred(Row); if FilesList.Count > 0 then RowCount := FilesList.Count + 1 else RowCount := FilesList.Count + 2; if SelPos >= FilesList.Count then SelPos := 0; {to be sure} Row := succ(SelPos); end; end; DrawGridFiles.Invalidate; end; //-------------------------------------------------------------------- // event issued when the user presses a key in the Files panel procedure TFormDBase.DrawGridFilesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if FormIsClosed then exit; ShiftState := Shift; EraseFileHint; with DrawGridFiles do begin if (ssShift in Shift) and ((Key = vk_Down) or (Key = vk_Up) or (Key = vk_Left) or (Key = vk_Right) or (Key = vk_Prior) or (Key = vk_Next)) then MakeFileSelection := true; if (Key = vk_Space) or (Key = vk_Insert) then begin DrawGridFilesToggleSelection; Key := vk_Down; end; if Key = vk_Back then begin GoToParent; Key := 0; exit; end; if (Key = vk_Return) then begin DrawGridFilesDblClick(Sender); Key := 0; exit; end; if QGlobalOptions.FileDisplayType = fdBrief then begin if FilesList.Count > 0 then begin if (Key = vk_Down) and (Row = pred(RowCount)) then if Col < pred(ColCount) then begin Row := 0; Col := Col + 1; Key := 0; end; if (Key = vk_Up) and (Row = 0) then if Col > 0 then begin Col := Col - 1; Row := pred(RowCount); Key := 0; end; if (Key = vk_Right) or ((Key = vk_Next) and (Row = pred(RowCount))) then if (Col < pred(ColCount)) then begin if succ(Col)*RowCount + Row >= FilesList.Count then Row := FilesList.Count - succ(Col)*RowCount - 1; Col := Col + 1; Key := 0; end else begin Row := FilesList.Count - pred(ColCount)*RowCount - 1; Key := 0; end; if (Key = vk_Left) or ((Key = vk_Prior) and (Row = 0)) then if (Col > 0) then begin Col := Col - 1; Key := 0; end else begin Row := 0; Key := 0; end; if (Key = vk_Home) then begin Col := 0; Row := 0; Key := 0; end; if (Key = vk_End) then begin Row := FilesList.Count - pred(ColCount)*RowCount - 1; Col := pred(ColCount); Key := 0; end; end; end; end; end; //-------------------------------------------------------------------- // event issued when the user resizes the database window. // Update of panels is made in idle time procedure TFormDBase.FormResize(Sender: TObject); begin if FormIsClosed then exit; FormWasResized := 1; end; //-------------------------------------------------------------------- // called to draw a cell of the Files panel procedure TFormDBase.DrawGridFilesDrawCell(Sender: TObject; Col, Row: Longint; Rect: TRect; State: TGridDrawState); var i: Integer; S: ShortString; StartX : Integer; DosDateTime: longint; PartRect : TRect; FileType : TFileType; OneFileLine: TOneFileLine; Offset : Integer; Bitmap : TBitmap; Description: TFilePointer; begin //LOG('DrawGridFilesDrawCell', []); if FormIsClosed then exit; try if QGlobalOptions.FileDisplayType = fdBrief then begin i := Col*DrawGridFiles.RowCount + Row; if i < FilesList.Count then begin OneFileLine := TOneFileLine(FilesList.Objects[i]); Offset := 0; if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGridFiles.Canvas.Brush.Color := clQSelectedBack; DrawGridFiles.Canvas.Font.Color := clQSelectedText; end; if QGlobalOptions.ShowIcons then begin ///inc(Offset, BitmapFolder.Width); case OneFileLine.FileType of ftDir : Bitmap := BitmapFolder; ftParent: Bitmap := BitmapParent; ftArc : Bitmap := BitmapArchive; else Bitmap := BitmapFolder; end; if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then DrawGridFiles.Canvas.FillRect(Classes.Rect(Rect.Left, Rect.Top, Rect.Left + Offset, Rect.Bottom)); ///if (OneFileLine.FileType <> ftFile) then ///DrawGridFiles.Canvas.BrushCopy( /// Bounds(Rect.Left + 1, Rect.Top, Bitmap.Width, Bitmap.Height), /// Bitmap, Bounds(0, 0, Bitmap.Width, Bitmap.Height), clOlive); end; DrawGridFiles.Canvas.TextRect(Classes.Rect(Rect.Left + Offset, Rect.Top, Rect.Right, Rect.Bottom), Rect.Left + Offset + 1, Rect.Top, OneFileLine.POneFile^.LongName + OneFileLine.POneFile^.Ext); end; end else begin if Col <= maxColumnAttribs then begin if Row = 0 then ColumnAttrib[Col].Width := DrawGridFiles.ColWidths[Col]; {this is becuase of non-existence of event on resizing columns} if Row <= FilesList.Count then begin case ColumnAttrib[Col].Content of coName: if Row = 0 then DrawGridFiles.Canvas.TextRect(Rect, Rect.Left+2, Rect.Top, lsName) else begin OneFileLine := TOneFileLine(FilesList.Objects[Row-1]); Offset := 0; if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGridFiles.Canvas.Brush.Color := clQSelectedBack; DrawGridFiles.Canvas.Font.Color := clQSelectedText; end; if QGlobalOptions.ShowIcons then begin inc(Offset, BitmapFolder.Width); case OneFileLine.FileType of ftParent: Bitmap := BitmapParent; ftArc : Bitmap := BitmapArchive; else Bitmap := BitmapFolder; end; if OneFileLine.ExtAttr and eaSelected <> 0 then DrawGridFiles.Canvas.FillRect(Classes.Rect(Rect.Left, Rect.Top, Rect.Left + Offset, Rect.Bottom)); if OneFileLine.FileType <> ftFile then DrawGridFiles.Canvas.BrushCopy( Bounds(Rect.Left + 1, Rect.Top, Bitmap.Width, Bitmap.Height), Bitmap, Bounds(0, 0, Bitmap.Width, Bitmap.Height), clOlive); end; DrawGridFiles.Canvas.TextRect(Classes.Rect(Rect.Left + Offset, Rect.Top, Rect.Right, Rect.Bottom), Rect.Left + Offset + 1, Rect.Top, OneFileLine.POneFile^.LongName + OneFileLine.POneFile^.Ext); //LOG('DrawGridFiles.Canvas.TextRect', []); end; coTime: begin if Row = 0 then begin S := lsDateAndTime; StartX := Rect.Right - DrawGridFiles.Canvas.TextWidth(S) - 2; DrawGridFiles.Canvas.TextRect(Rect, StartX, Rect.Top, S); end else begin OneFileLine := TOneFileLine(FilesList.Objects[Row-1]); DosDateTime := OneFileLine.POneFile^.Time; if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGridFiles.Canvas.Brush.Color := clQSelectedBack; DrawGridFiles.Canvas.Font.Color := clQSelectedText; end; if DosDateTime <> 0 then begin S := DosTimeToStr(DosDateTime, QGlobalOptions.ShowSeconds); StartX := Rect.Right - DrawGridFiles.Canvas.TextWidth(S) - 2; DrawGridFiles.Canvas.TextRect(Rect, StartX, Rect.Top, S); S := DosDateToStr(DosDateTime); PartRect := Rect; PartRect.Right := PartRect.Right - TimeWidth; if PartRect.Right < PartRect.Left then PartRect.Right := PartRect.Left; StartX := PartRect.Right - DrawGridFiles.Canvas.TextWidth(S) - 2; DrawGridFiles.Canvas.TextRect(PartRect, StartX, Rect.Top, S); end else if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then DrawGridFiles.Canvas.FillRect(Classes.Rect(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom)); end; end; coSize: begin if Row = 0 then S := lsSize else begin OneFileLine := TOneFileLine(FilesList.Objects[Row-1]); FileType := OneFileLine.FileType; if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGridFiles.Canvas.Brush.Color := clQSelectedBack; DrawGridFiles.Canvas.Font.Color := clQSelectedText; end; case FileType of ftDir : S := lsFolder; ftParent: S := ''; else S := FormatSize( TOneFileLine(FilesList.Objects[Row-1]).POneFile^.Size, QGlobalOptions.ShowInKb); end; end; StartX := Rect.Right - DrawGridFiles.Canvas.TextWidth(S) - 2; DrawGridFiles.Canvas.TextRect(Rect, StartX, Rect.Top, S); end; coDesc: if Row = 0 then DrawGridFiles.Canvas.TextRect(Rect, Rect.Left+2, Rect.Top, lsDescription) else begin OneFileLine := TOneFileLine(FilesList.Objects[Row-1]); Description := OneFileLine.POneFile^.Description; if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGridFiles.Canvas.Brush.Color := clQSelectedBack; DrawGridFiles.Canvas.Font.Color := clQSelectedText; end; if Description <> 0 then begin DrawGridFiles.Canvas.FillRect(Classes.Rect(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom)); if QI_GetShortDesc(DBaseHandle, Description, S) then DrawGridFiles.Canvas.TextRect(Rect, Rect.Left + 1, Rect.Top, S); end else if (OneFileLine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then DrawGridFiles.Canvas.FillRect(Classes.Rect(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom)); end; end; end; end; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Issued when the user selects a cell in the Files panel procedure TFormDBase.DrawGridFilesSelectCell(Sender: TObject; Col, Row: Longint; var CanSelect: Boolean); var i : Integer; bNeedRepaint : boolean; begin if FormIsClosed then exit; EraseFileHint; if QGlobalOptions.FileDisplayType = fdBrief then begin i := Col*DrawGridFiles.RowCount + Row; CanSelect := i < FilesList.Count; if CanSelect then begin UpdateStatusLine(i, false); LastFileSelected := CurFileSelected; CurFileSelected := i; end; end else begin CanSelect := Row <= FilesList.Count; if CanSelect then begin UpdateStatusLine(Row-1, false); LastFileSelected := CurFileSelected; CurFileSelected := Row-1; end; end; if MakeFileSelection then begin MakeFileSelection := false; if CurFileSelected <= LastFileSelected then for i := succ(CurFileSelected) to LastFileSelected do with TOneFileLine(FilesList.Objects[i]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected else for i := pred(CurFileSelected) downto LastFileSelected do with TOneFileLine(FilesList.Objects[i]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; if abs(CurFileSelected - LastFileSelected) > 1 then DrawGridFiles.Repaint; end else if not UsePersistentBlocks then begin bNeedRepaint := false; for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do if (ExtAttr and eaSelected) <> 0 then begin bNeedRepaint := true; ExtAttr := ExtAttr and not eaSelected; end; if bNeedRepaint then DrawGridFiles.Repaint; end; end; //-------------------------------------------------------------------- procedure TFormDBase.ScanTree(DirColHandle: PDirColHandle; Level: Integer; var TotalItemCount: Integer); var i : Integer; OneFile : TOneFile; OneDir : TOneDir; Count : Integer; SubDirColHandle : PDirColHandle; Node : TTreeNode; begin try Count := QI_GetDirColCount(DirColHandle); {returns 0, if it is nil} Node:=nil; for i := 0 to pred(Count) do begin FillChar(OneFile, SizeOf(TOneFile), 0); SubDirColHandle := QI_GetDirColAt(DirColHandle, i); QI_GetOneDirDta(SubDirColHandle, OneDir); OneFile.LongName := OneDir.LongName; OneFile.Ext := OneDir.Ext; OneFile.Size := OneDir.Size; {to distinguish between folder and archive} ///OutLineTree.AddChildObject(Level, OneFile.LongName + OneFile.Ext, /// SubDirColHandle); Node:=OutLineTree.Items.AddChildObject(Node, OneFile.LongName + OneFile.Ext, SubDirColHandle); TreePtrCol^.Insert(SubDirColHandle); inc(TotalItemCount); if SubDirColHandle <> nil then begin ScanTree(SubDirColHandle, TotalItemCount, TotalItemCount); end; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Reloads a tree from the database. Called when the disk selection changes // - call is made in the idle time, so that the user can browse disks fast procedure TFormDBase.ReloadTree; var DirsInTree: Integer; RootDirColHandle: PDirColHandle; begin if PanelsLocked then exit; try if QI_GetCountToShow(DBaseHandle) = 0 then begin ///OutLineTree.Clear; OutLineTree.Items.Clear; TreePtrCol^.DeleteAll; ///OutLineTree.AddObject (0, '\', nil); OutLineTree.Items.AddObject (nil, '\', nil); UpdateHeader; exit; end; QI_GoToKeyAt (DBaseHandle, DrawGridDisks.Selection.Top); if not QGlobalOptions.ShowTree then exit; ///OutLineTree.Clear; OutLineTree.Items.Clear; TreePtrCol^.DeleteAll; RootDirColHandle := QI_GetRootDirCol(DBaseHandle); ///OutLineTree.AddObject (0, '\', RootDirColHandle); OutLineTree.Items.AddObject (nil, '\', RootDirColHandle); TreePtrCol^.Insert(RootDirColHandle); DirsInTree := 1; try ScanTree (RootDirColHandle, 1, DirsInTree); except ///on Error: EOutlineError do /// NormalErrorMessage(Error.Message); end; if QGlobalOptions.ExpandTree then with OutlineTree do begin OutlineTree.BeginUpdate; OutlineTree.FullExpand; OutlineTree.EndUpdate; end else ///OutLineTree.Items[1].Expand; OutLineTree.Items[1].Expand(false); UpdateHeader; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Expandes one branch in the tree - used when some items in the tree // has to be found and selected - typically when the user double-clicks // in the window with fould files and the location of the file is to be // displayed. ///procedure TFormDBase.ExpandBranch(AnItem: TOutlineNode); procedure TFormDBase.ExpandBranch(AnItem: TTreeNode); begin if FormIsClosed then exit; if not AnItem.IsVisible then ExpandBranch(AnItem.Parent); AnItem.Expand(false); end; //-------------------------------------------------------------------- // Rescans current tree - does not change it - used when the panel // with the tree is shown/hidden procedure TFormDBase.RescanTree(SavePosition: boolean); var DirsInTree: Integer; RootDirColHandle: PDirColHandle; SaveSelected: longint; begin if FormIsClosed then exit; if PanelsLocked then exit; if DBaseIsEmpty then exit; try if not QGlobalOptions.ShowTree then exit; ///SaveSelected := OutlineTree.SelectedItem; OutLineTree.Items.Clear; TreePtrCol^.DeleteAll; RootDirColHandle := QI_GetRootDirCol(DBaseHandle); ///OutLineTree.AddObject (0, '\', RootDirColHandle); OutLineTree.Items.AddObject (nil, '\', RootDirColHandle); TreePtrCol^.Insert(RootDirColHandle); DirsInTree := 1; try ScanTree (RootDirColHandle, 1, DirsInTree); except ///on Error: EOutlineError do /// NormalErrorMessage(Error.Message); end; if QGlobalOptions.ExpandTree then with OutlineTree do begin OutlineTree.BeginUpdate; OutlineTree.FullExpand; OutlineTree.EndUpdate; end else OutLineTree.Items[1].Expand(false); if SavePosition and (SaveSelected > 0) then begin ExpandBranch(OutlineTree.Items[SaveSelected]); ///OutlineTree.SelectedItem := SaveSelected; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Event issued when the user selects a cell in the Disks list, // the update of other pnales is made in idle time procedure TFormDBase.DrawGridDisksSelectCell(Sender: TObject; Col, Row: Longint; var CanSelect: Boolean); var i: Integer; begin if FormIsClosed then exit; try if MakeDiskSelection then begin MakeDiskSelection := false; if LastDiskSelected <= Row then for i := LastDiskSelected to pred(Row) do QI_ToggleSelectionFlag(DBaseHandle, i) else for i := LastDiskSelected downto succ(Row) do QI_ToggleSelectionFlag(DBaseHandle, i); if abs(LastDiskSelected - Row) > 1 then DrawGridDisks.Repaint; end; if DrawGridDisks.Selection.Top <> Row then begin LastDiskSelected := DrawGridDisks.Selection.Top; QI_SetCurrentKeyPos(DBaseHandle, Row); QI_SetNeedUpdTreeWin(DBaseHandle); end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Fucntion called when there is no message in the message queue. Time-consuming // updates are located here, so that the program can respond to users events // quickly. procedure TFormDBase.LocalIdle; begin if FormIsClosed then exit; if PanelsLocked then exit; try if QI_NeedUpdDiskWin(DBaseHandle) then UpdateDiskWindow; if QI_NeedUpdTreeWin(DBaseHandle) then begin ReloadTree; QI_ClearNeedUpdTreeWin(DBaseHandle); end; if QI_NeedUpdFileWin(DBaseHandle) then begin ReloadFileCol(''); QI_ClearNeedUpdFileWin(DBaseHandle); end; if NeedReSort then begin NeedReSort := false; ReloadFileCol(GetSelectedFileName); end; if FormWasResized > 0 then begin Dec(FormWasResized); if FormWasResized = 0 then begin UpdateFileWindowGrid(-1); ResizeHeaderBottom; end; end; if HeaderBottom.Sections[0].Text <> StatusLineSubTotals then begin if StatusSection0Size = 0 then begin //workaround - it made problems in the first run StatusSection0Size := 1; HeaderBottom.Sections[0].Text := '-'; end else begin HeaderBottom.Sections[0].Text := StatusLineSubTotals; StatusSection0Size := HeaderBottom.Sections[0].Width; end; ResizeHeaderBottom; end; if HeaderBottom.Sections[1].Text <> StatusLineFiles then begin HeaderBottom.Sections[1].Text := StatusLineFiles; ResizeHeaderBottom; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; if QI_GetErrorCounter(DBaseHandle) > 0 then begin QI_ClearErrorCounter(DBaseHandle); NormalErrorMessage(lsErrorInDBaseFound); end; end; //-------------------------------------------------------------------- // Timer procedure called from the timer in the main application window // - thi assures only one timer per application is used. procedure TFormDBase.LocalTimer; begin if FormIsClosed then exit; if PanelsLocked then exit; if QGlobalOptions.ShowFileHints and ((longint(GetTickCount) - LastMouseMoveTime) > defHintDelayPeriod) then ShowFileHint; end; //-------------------------------------------------------------------- // Calculates, which file is selected in the file panel and returns its name+ext function TFormDBase.GetSelectedFileName: ShortString; var i: Integer; begin Result := ''; if FormIsClosed then exit; if FilesList.Count = 0 then exit; if QGlobalOptions.FileDisplayType = fdBrief then i := DrawGridFiles.Selection.Left*DrawGridFiles.RowCount + DrawGridFiles.Selection.Top else i := pred(DrawGridFiles.Selection.Top); if (i >= 0) and (i < FilesList.Count) then with TOneFileLine(FilesList.Objects[i]).POneFile^ do Result := LongName + Ext; end; //-------------------------------------------------------------------- // Reloads the collection of files from the database. Used when the // the collection is to be re-sorted or updated procedure TFormDBase.ReloadFileCol(SaveFileName: ShortString); var FileColHandle: PFileColHandle; i, Count : Integer; OneFile : TOneFile; OneFileLine: TOneFileLine; {ukazatel} DirPos : Integer; Jump : boolean; TmpInt : Integer; begin if FormIsClosed then exit; if PanelsLocked then exit; inc(DisableHints); try LastFileSelected := 0; CurFileSelected := 0; if QI_GetCountToShow(DBaseHandle) = 0 then begin FilesList.Clear; FillChar(SubTotals, SizeOf(SubTotals), 0); UpdateFileWindowGrid(0); UpdateStatusLine(0, true); dec(DisableHints); exit; end; FilesList.Clear; FilesList.Reversed := QGlobalOptions.ReversedSort; Jump := false; QI_GetCurDirColSubTotals(DBaseHandle, SubTotals); FileColHandle := QI_GetFileCol(DBaseHandle); Count := QI_GetFileColCount(FileColHandle); MaxFileNameLength := 12; MaxFileNamePxLength := DrawGridFiles.Canvas.TextWidth('MMMMMMMM.MMM'); for i := 0 to pred(Count) do begin QI_GetOneFileFromCol(FileColHandle, i, OneFile); TmpInt := length(OneFile.LongName) + length(OneFile.Ext); if TmpInt > MaxFileNameLength then MaxFileNameLength := TmpInt; TmpInt := DrawGridFiles.Canvas.TextWidth(OneFile.LongName + OneFile.Ext); if TmpInt > MaxFileNamePxLength then MaxFileNamePxLength := TmpInt; OneFileLine := TOneFileLine.Create(OneFile); if (OneFile.LongName + OneFile.Ext) = SaveFileName then begin OneFileLine.ExtAttr := OneFileLine.ExtAttr or eaToBeSelected; Jump := true; end; if (SaveFileName[0] = #0) and (DirToScrollHandle <> nil) and (OneFileLine.FileType <> ftFile) and (OneFile.SubDirCol = DirToScrollHandle) then begin OneFileLine.ExtAttr := OneFileLine.ExtAttr or eaToBeSelected; DirToScrollHandle := nil; Jump := true; end; FilesList.AddObject(GetSortString(OneFile, OneFileLine.FileType, QGlobalOptions.SortCrit, QGlobalOptions.ReversedSort), OneFileLine); end; DirPos := 0; if Jump then for i := 0 to pred(Count) do if (TOneFileLine(FilesList.Objects[i]).ExtAttr and eaToBeSelected) <> 0 then begin DirPos := i; break; end; UpdateFileWindowGrid(DirPos); UpdateStatusLine(DirPos, true); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; dec(DisableHints); end; //-------------------------------------------------------------------- // Event issued when the user clicks to the tree panel procedure TFormDBase.OutlineTreeClick(Sender: TObject); begin if FormIsClosed then exit; try if not QGlobalOptions.ShowTree then exit; with OutlineTree do begin ///if SelectedItem > 0 then if Selected.Count > 0 then begin ///if Items[SelectedItem].Data <> nil then if Items[Selected.Index].Data <> nil then begin ///QI_SetCurDirCol (DBaseHandle, Items[SelectedItem].Data); QI_SetCurDirCol (DBaseHandle, Items[Selected.Index].Data); QI_UpdateFileCol(DBaseHandle); UpdateHeader; end; end; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Procedure used to open/execute selected file. Verifies the presence // of the file and then uses shell to make the action appropriate to the // file extension. procedure TFormDBase.ExecFile(POneFile: TPOneFile); var Msg : AnsiString; RelativePath : ShortString; OrigDiskName : ShortString; OrigVolumeLabel: ShortString; BasePath : ShortString; Index : Integer; Attr : Word; FileSystem : TFileSystem; VolumeLabel : ShortString; DriveType : integer; Exists : boolean; InArchive : boolean; DriveAccessible: boolean; DriveRemovable : boolean; DriveNetwork : boolean; VolumeLabelDiffers: boolean; Retry : boolean; iResult : integer; begin Retry := true; LOG('->ExecFile', []); while Retry do begin Retry := false; QI_GetCurrentKeyEx (DBaseHandle, OrigDiskName, OrigVolumeLabel, BasePath, Attr, Index); LOG('BasePath=%s, OrigDiskName=%s, OrigVolumeLabel=%s', [BasePath, OrigDiskName, OrigVolumeLabel]); QI_GetFullDirPath(DBaseHandle, RelativePath); InArchive := QI_IsInArchive (DBaseHandle); If InArchive then RelativePath := QI_GetArchivePath(DBaseHandle); if length(BasePath) > 0 then // cut the last backslash if BasePath[length(BasePath)] = '\' then BasePath[0] := char(byte(BasePath[0])-1); if (InArchive) then begin // relative path does not have backslash at the end LOG('Is in archive', []); Msg := BasePath + RelativePath; end else begin if RelativePath[length(RelativePath)] <> '\' then RelativePath := RelativePath + '\'; Msg := BasePath + RelativePath + POneFile^.LongName + POneFile^.Ext; end; LOG('Msg=%s', [Msg]); Exists := FileExists(Msg); VolumeLabel := ''; DriveAccessible := ReadVolumeLabel (BasePath[1] + ':', VolumeLabel, FileSystem, DriveType); ///DriveRemovable := (DriveType = DRIVE_REMOVABLE) or /// (DriveType = DRIVE_CDROM); ///DriveNetwork := DriveType = DRIVE_REMOTE; VolumeLabelDiffers := false; // OrigVolumeLabel - by the older version of DiskBase is '', otherwise VolumeLabel if (length(VolumeLabel) > 0) then VolumeLabelDiffers := AnsiUppercase(OrigVolumeLabel) <> AnsiUppercase(VolumeLabel); if not Exists then begin Msg := Msg + lsFileCannotBeOpen; if not DriveAccessible then Msg := Msg + lsDiskNotAccessible; if DriveRemovable then Msg := Msg + lsDifferentDisk; if InArchive then Msg := Msg + lsFileInArchive; if DriveNetwork then Msg := Msg + lsDiskIsNetworkDrive; if VolumeLabelDiffers then Msg := Msg + lsVolumeLabelDiffers; Msg := Msg + lsFileProbablyDeleted; Retry := Application.MessageBox(PChar(Msg), lsFileNotFound, MB_RETRYCANCEL) = IDRETRY; LOG('Does not exist: %s', [Msg]); end else begin LOG('Executing shell: %s', [Msg]); {$ifdef mswindows} iResult := ShellExecute(Handle, nil, PChar(Msg), nil, nil, SW_SHOWNORMAL); if (iResult <= 32) then // failed if iResult = SE_ERR_NOASSOC then // no association begin LOG('No association, retry with relative path', []); if RelativePath[length(RelativePath)] = '\' then RelativePath[0] := char(byte(RelativePath[0])-1); Msg := BasePath + RelativePath; iResult := ShellExecute(Handle, nil, PChar(Msg), nil, nil, SW_SHOWNORMAL); LOG('Executing shell: %s, result=%d', [Msg, iResult]); end; {$endif} end; end; end; //-------------------------------------------------------------------- // Used to open Windows Explorer to display the contents of the folder procedure TFormDBase.OpenExplorer(POneFile: TPOneFile); var Msg : AnsiString; RelativePath : ShortString; OrigDiskName : ShortString; OrigVolumeLabel: ShortString; BasePath : ShortString; Index : Integer; Attr : Word; FileSystem : TFileSystem; VolumeLabel : ShortString; DriveType : integer; Exists : boolean; InArchive : boolean; DriveAccessible: boolean; DriveRemovable : boolean; DriveNetwork : boolean; VolumeLabelDiffers: boolean; Retry : boolean; begin Retry := true; LOG('->OpenExplorer', []); while Retry do begin Retry := false; InArchive := QI_IsInArchive (DBaseHandle); if (InArchive) then begin ExecFile(POneFile); exit; end; QI_GetCurrentKeyEx (DBaseHandle, OrigDiskName, OrigVolumeLabel, BasePath, Attr, Index); QI_GetFullDirPath(DBaseHandle, RelativePath); if length(BasePath) > 0 then // cut the last backslash if BasePath[length(BasePath)] = '\' then BasePath[0] := char(byte(BasePath[0])-1); if RelativePath[length(RelativePath)] <> '\' then RelativePath := RelativePath + '\'; Msg := BasePath + RelativePath + POneFile^.LongName + POneFile^.Ext; Exists := DirExists(Msg); VolumeLabel := ''; DriveAccessible := ReadVolumeLabel (BasePath[1] + ':', VolumeLabel, FileSystem, DriveType); ///DriveRemovable := (DriveType = DRIVE_REMOVABLE) or /// (DriveType = DRIVE_CDROM); ///DriveNetwork := DriveType = DRIVE_REMOTE; VolumeLabelDiffers := false; if (length(VolumeLabel) > 0) then VolumeLabelDiffers := AnsiUppercase(OrigVolumeLabel) <> AnsiUppercase(VolumeLabel); if not Exists then begin Msg := Msg + lsFolderCannotBeOpen; if not DriveAccessible then Msg := Msg + lsDiskNotAccessible; if DriveRemovable then Msg := Msg + lsDifferentDisk; if InArchive then Msg := Msg + lsFolderInArchive; if DriveNetwork then Msg := Msg + lsDiskIsNetworkDrive; if VolumeLabelDiffers then Msg := Msg + lsVolumeLabelDiffers; Msg := Msg + lsFolderProbablyDeleted; Retry := Application.MessageBox(PChar(Msg), lsFolderNotFound, MB_RETRYCANCEL) = IDRETRY; LOG('Does not exist: %s', [Msg]); end else begin LOG('Executing shell: %s', [Msg]); ///ShellExecute(Handle, nil, PChar(Msg), nil, nil, SW_SHOWNORMAL); end; end; end; //-------------------------------------------------------------------- // Event issued when the user double-clicks on the files panel. procedure TFormDBase.DrawGridFilesDblClick(Sender: TObject); var i : Integer; begin if FormIsClosed then exit; if DisableNextDoubleClick then exit; EraseFileHint; try if QGlobalOptions.FileDisplayType = fdBrief then i := DrawGridFiles.Selection.Left*DrawGridFiles.RowCount + DrawGridFiles.Selection.Top else i := pred(DrawGridFiles.Row); if i < FilesList.Count then with TOneFileLine(FilesList.Objects[i]) do begin DirToScrollHandle := nil; if FileType = ftParent then DirToScrollHandle := QI_GetCurDirCol(DBaseHandle); // ShiftState set in Mouse and Key down if ssShift in ShiftState // shift - open file or explore folder then begin if (POneFile^.Attr and faDirectory <> 0) and (POneFile^.Attr and faQArchive = 0) then begin if FileType <> ftParent then OpenExplorer(POneFile); end else begin // click on file ExecFile(POneFile); end; end else if ssCtrl in ShiftState then begin EditDescription; end else // no shift state begin if (POneFile^.Attr and (faDirectory or faQArchive) <> 0) then begin if (POneFile^.SubDirCol <> nil) then begin QI_SetCurDirCol (DBaseHandle, POneFile^.SubDirCol); QI_UpdateFileCol(DBaseHandle); UpdateHeader; JumpInOutline(POneFile^.SubDirCol); end; end else begin // click on file if QGlobalOptions.EnableShellExecute then ExecFile(POneFile); end; end; end; // with except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Procedure used to inverse selection procedure TFormDBase.DrawGridFilesToggleSelection; var i : Integer; begin if FormIsClosed then exit; if QGlobalOptions.FileDisplayType = fdBrief then i := DrawGridFiles.Selection.Left*DrawGridFiles.RowCount + DrawGridFiles.Selection.Top else i := pred(DrawGridFiles.Row); if i < FilesList.Count then begin with TOneFileLine(FilesList.Objects[i]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; end; end; //-------------------------------------------------------------------- // Used to select programatically the folder in the tree panel - typically // when the user double-clicks on a found file, the appropriate disk is // selected, folder in the tree panel selcted (by this function) and the // file in the file panel selected procedure TFormDBase.JumpInOutline(SubDirCol: pointer); var i : Integer; Found: boolean; begin if FormIsClosed then exit; if not QGlobalOptions.ShowTree then exit; Found := false; with OutlineTree do ///if SelectedItem > 0 then if Selected.Count > 0 then ///if Items[SelectedItem].Level > 1 then /// Items[SelectedItem].Collapse; if Items[Selected.Index].Level > 1 then Items[Selected.Index].Collapse(true); for i := 0 to pred(TreePtrCol^.Count) do if TreePtrCol^.At(i) = SubDirCol then begin Found := true; break; end; if Found then begin inc(i); if i > 1 then ExpandBranch(OutlineTree.Items[i]); ///OutlineTree.SelectedItem := i; OutlineTree.Selected.Index := i; end; end; //-------------------------------------------------------------------- // Called when global options are changed, so the view of the tree and files // can be updated procedure TFormDBase.ChangeGlobalOptions; var SaveFileName : ShortString; SaveExpandTree : boolean; begin if FormIsClosed then exit; SaveExpandTree := QGlobalOptions.ExpandTree; FormSettings.GetOptions(QGlobalOptions); SaveFileName := GetSelectedFileName; if SaveExpandTree <> QGlobalOptions.ExpandTree then begin with OutlineTree do if QGlobalOptions.ExpandTree then begin BeginUpdate; FullExpand; EndUpdate; end else begin BeginUpdate; FullCollapse; EndUpdate; Items[1].Expand(false); end; end; ShowOrHideTreePanel; ResetDrawGridFiles; ReloadFileCol(SaveFileName); end; //-------------------------------------------------------------------- // Called when global options are changed, so the view of the deleted // disks can be updated procedure TFormDBase.ChangeLocalOptions; begin if FormIsClosed then exit; try FormLocalOptions.GetOptions(QLocalOptions); QI_GetLocalOptions (DBaseHandle, TmpLocalOptions); QI_SetLocalOptions (DBaseHandle, QLocalOptions); if QLocalOptions.ShowDeleted <> TmpLocalOptions.ShowDeleted then begin UpdateDiskWindow; QI_SetNeedUpdTreeWin(DBaseHandle); end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Changes the type of display of files to brief procedure TFormDBase.SetBriefFileDisplay(Brief: boolean); var SavePos : Integer; begin if FormIsClosed then exit; if Brief and (QGlobalOptions.FileDisplayType = fdBrief) then exit; if QGlobalOptions.FileDisplayType = fdBrief then with DrawGridFiles do SavePos := Col*RowCount + Row else SavePos := pred(DrawGridFiles.Row); if Brief then QGlobalOptions.FileDisplayType := fdBrief else QGlobalOptions.FileDisplayType := fdDetailed; ResetDrawGridFiles; UpdateFileWindowGrid(SavePos); end; //-------------------------------------------------------------------- // Hides or shows the tree panel procedure TFormDBase.ShowOrHideTreePanel; begin if FormIsClosed then exit; try if QGlobalOptions.ShowTree and not OutlineTree.Visible then begin RescanTree(false); if not DBaseIsEmpty then JumpInOutline(QI_GetCurDirCol(DBaseHandle)); OutlineTree.Left := Splitter1.Left + Splitter1.Width + 1; OutlineTree.Show; // make sure it is on right Splitter2.Align := alNone; Splitter2.Left := OutlineTree.Left + OutlineTree.Width + 1; Splitter2.Align := alLeft; Splitter2.Show; QI_ClearNeedUpdFileWin(DBaseHandle); // already updated HeaderTop.Sections[1].Width := HeaderWidths[1]; ResizeHeaderBottom; RescanTree(true); exit; end; if not QGlobalOptions.ShowTree and OutlineTree.Visible then begin OutlineTree.Hide; Splitter2.Hide; OutLineTree.Items.Clear; HeaderTop.Sections[1].Width := 0; ResizeHeaderBottom; RescanTree(true); exit; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Set fonts from global options and recalculates the sizes. Used after // the global options are changed and at the program startup. procedure TFormDBase.ResetFontsAndRowHeights; begin if FormIsClosed then exit; with QGlobalOptions do begin {$ifndef LOGFONT} DrawGridDisks.Font.Assign (DiskFont); DrawGridDisks.Canvas.Font.Assign(DiskFont); OutlineTree.Font.Assign (TreeFont); OutlineTree.Canvas.Font.Assign (TreeFont); DrawGridFiles.Font.Assign (FileFont); DrawGridFiles.Canvas.Font.Assign(FileFont); FormDescription.MemoDesc.Font.Assign(DescFont); {$else} SetFontFromLogFont(DrawGridDisks.Font, DiskLogFont); SetFontFromLogFont(DrawGridDisks.Canvas.Font, DiskLogFont); SetFontFromLogFont(OutlineTree.Font, TreeLogFont); SetFontFromLogFont(OutlineTree.Canvas.Font, TreeLogFont); SetFontFromLogFont(DrawGridFiles.Font, FileLogFont); SetFontFromLogFont(DrawGridFiles.Canvas.Font, FileLogFont); SetFontFromLogFont(FormDescription.MemoDesc.Font, DescLogFont); {$endif} end; DrawGridDisks.DefaultRowHeight := DrawGridDisks.Canvas.TextHeight('My'); DrawGridFiles.DefaultRowHeight := DrawGridFiles.Canvas.TextHeight('My'); TimeWidth := DrawGridFiles.Canvas.TextWidth(DosTimeToStr(longint(23) shl 11, QGlobalOptions.ShowSeconds)); TimeWidth := TimeWidth + TimeWidth div 6; ///if OutlineTree.Font.Size < 9 /// then OutlineTree.OutlineStyle := osTreeText /// else OutlineTree.OutlineStyle := osTreePictureText; end; //-------------------------------------------------------------------- // Updates the status line with the information about the currently selected file procedure TFormDBase.UpdateStatusLine(Index: Integer; SubTotalsToo: boolean); var OneFileLine: TOneFileLine; DosDateTime: longint; Description: TFilePointer; S : ShortString; begin if FormIsClosed then exit; try StatusLineFiles := ' '; if (FilesList.Count > 0) and (Index >= 0) and (Index < FilesList.Count) then begin OneFileLine := TOneFileLine(FilesList.Objects[Index]); with OneFileLine do begin LastSelectedFile := POneFile^.LongName + POneFile^.Ext; StatusLineFiles := StatusLineFiles + POneFile^.LongName + POneFile^.Ext + ' '; DosDateTime := POneFile^.Time; case FileType of ftDir : StatusLineFiles := StatusLineFiles + lsFolder1; ftParent: ; else StatusLineFiles := StatusLineFiles + FormatSize(POneFile^.Size, QGlobalOptions.ShowInKb) + ' '; end; if DosDateTime <> 0 then StatusLineFiles := StatusLineFiles + DosDateToStr(DosDateTime) + ' ' + DosTimeToStr(DosDateTime, QGlobalOptions.ShowSeconds) + ' '; Description := POneFile^.Description; if Description <> 0 then begin if QI_GetShortDesc(DBaseHandle, Description, S) then StatusLineFiles := StatusLineFiles + ' ' + S; end; end; end; if SubTotalsToo then begin StatusLineSubTotals := ' '; if (SubTotals.DataFileSize > 0) then begin if (SubTotals.PhysDirs = SubTotals.DataDirs) and (SubTotals.PhysFiles = SubTotals.DataFiles) and (SubTotals.PhysFileSize = SubTotals.DataFileSize) then begin StatusLineSubTotals := lsTotalFolders + IntToStr(SubTotals.PhysDirs) + lsTotalFiles + IntToStr(SubTotals.PhysFiles) + lsTotalSize + FormatBigSize(SubTotals.PhysFileSize); end else begin StatusLineSubTotals := lsTotalFolders + IntToStr(SubTotals.PhysDirs) + '/' + IntToStr(SubTotals.DataDirs) + lsTotalFiles + IntToStr(SubTotals.PhysFiles) + '/' + IntToStr(SubTotals.DataFiles) + lsTotalSize + FormatBigSize(SubTotals.PhysFileSize)+ '/' + FormatBigSize(SubTotals.DataFileSize); end; end; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Updates the header of the panels procedure TFormDBase.UpdateHeader; var S : ShortString; Attr : Word; Index : Integer; begin if FormIsClosed then exit; try if (ActiveControl is TDrawGrid) and (TDrawGrid(ActiveControl).Tag = 1) and (HeaderTop.Sections[0].Text <> ShortDBaseFileName) then begin HeaderTop.Sections[0].Text := ShortDBaseFileName; HeaderTop.Sections[0].Width := HeaderWidths[0]; end; {$ifdef mswindows} if QGlobalOptions.ShowTree and (ActiveControl is TTreeView) and (TOutline(ActiveControl).Tag = 2) then begin if QI_GetCurrentKey(DBaseHandle, S, Attr, Index) then begin if HeaderTop.Sections.Strings[1] <> S then begin HeaderTop.Sections.Strings[1] := S; HeaderTop.SectionWidth[1] := HeaderWidths[1]; end; end; end; if (ActiveControl is TDrawGrid) and (TDrawGrid(ActiveControl).Tag = 3) then begin QI_GetFullDirPath(DBaseHandle, S); if HeaderTop.Sections.Strings[2] <> S then begin HeaderTop.Sections.Strings[2] := S; HeaderTop.SectionWidth[2] := HeaderWidths[2]; end; end; {$endif} except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Updates the size of the sections of the bottom header (containing the status line) procedure TFormDBase.ResizeHeaderBottom; var SizeNeeded: Integer; begin SizeNeeded := HeaderTop.Sections[0].Width+HeaderTop.Sections[1].Width; if SizeNeeded < StatusSection0Size then SizeNeeded := StatusSection0Size; HeaderBottom.Sections[0].Width := SizeNeeded; end; //-------------------------------------------------------------------- // Sets the flag for resorting in the idle time procedure TFormDBase.SetNeedResort(SortCrit: TSortCrit); begin NeedResort := true; if QGlobalOptions.SortCrit = SortCrit then QGlobalOptions.ReversedSort := not QGlobalOptions.ReversedSort else QGlobalOptions.ReversedSort := false; QGlobalOptions.SortCrit := SortCrit; end; //-------------------------------------------------------------------- // Handles the event issued when the user clicks by mouse in the file panel procedure TFormDBase.DrawGridFilesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var i, Current: Integer; TotalWidth: Integer; begin if FormIsClosed then exit; ShiftState := Shift; EraseFileHint; DisableNextDoubleClick := false; if QGlobalOptions.FileDisplayType = fdDetailed then with DrawGridFiles do if Y < DefaultRowHeight then begin DisableNextDoubleClick := true; TotalWidth := 0; for i := 0 to pred(ColCount) do with ColumnAttrib[i] do begin inc(TotalWidth, Width); if X < TotalWidth then begin case Content of coName: if X > TotalWidth - Width div 2 then SetNeedResort(scExt) else SetNeedResort(scName); coTime : SetNeedResort(scTime); coSize : SetNeedResort(scSize); end; break; end; end; exit; end; if ssCtrl in Shift then DrawGridFilesToggleSelection; if ssShift in Shift then begin if LastFileSelected >= FilesList.Count then LastFileSelected := pred(FilesList.Count); for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do ExtAttr := ExtAttr and not eaSelected; if QGlobalOptions.FileDisplayType = fdBrief then Current := DrawGridFiles.Selection.Left*DrawGridFiles.RowCount + DrawGridFiles.Selection.Top else Current := pred(DrawGridFiles.Row); if LastFileSelected <= Current then for i := LastFileSelected to Current do with TOneFileLine(FilesList.Objects[i]) do ExtAttr := ExtAttr or eaSelected else for i := LastFileSelected downto Current do with TOneFileLine(FilesList.Objects[i]) do ExtAttr := ExtAttr or eaSelected; DrawGridFiles.Repaint; end; end; //-------------------------------------------------------------------- // Determines, whether the database is empty function TFormDBase.DBaseIsEmpty: boolean; begin Result := true; if FormIsClosed then exit; Result := QI_GetCountToShow(DBaseHandle) = 0; end; //-------------------------------------------------------------------- // Error message displayed when a critical error was encountered procedure TFormDBase.MsgShouldExit; begin Application.MessageBox(lsSeriousProblemWritingToDBase, lsError, mb_Ok or mb_IconStop); end; //-------------------------------------------------------------------- // Scans a disk to the database. function TFormDBase.ScanDisk (Drive: char; AutoRun: boolean): boolean; begin Result := true; if FormIsClosed then exit; if DBaseIsReadOnly then exit; try PanelsLocked := true; Result := DoScan(Drive, '', '', AutoRun, false); PanelsLocked := false; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Rescans existing disk in the database procedure TFormDBase.RescanDisk; var OrigDiskName, OrigVolumeLabel, OrigPath: ShortString; Index: Integer; Attr : Word; RealVolumeLabel: ShortString; SaveStr1, SaveStr2: ShortString; MsgText: array[0..1024] of char; OK: boolean; begin QI_GetCurrentKeyEx (DBaseHandle, OrigDiskName, OrigVolumeLabel, OrigPath, Attr, Index); if Attr and kaDeleted <> 0 then exit; if length(OrigPath) = 2 then OrigPath := OrigPath + '\'; // save the contents of the form for usage as scan folder SaveStr1 := FormScanFolder.EditFolder.Text; SaveStr2 := FormScanFolder.EditDiskName.Text; FormScanFolder.EditFolder.Text := OrigPath; FormScanFolder.EditDiskName.Text := OrigDiskName; FormScanFolder.SetAppearance(false); OK := FormScanFolder.ShowModal = mrOk; FormScanFolder.SetAppearance(true); OrigPath := FormScanFolder.Directory; OrigDiskName := FormScanFolder.DiskName; RealVolumeLabel := FormScanFolder.VolumeLabel; FormScanFolder.EditFolder.Text := SaveStr1; FormScanFolder.EditDiskName.Text := SaveStr2; if OK then begin if AnsiUpperCase(OrigVolumeLabel) <> AnsiUpperCase(RealVolumeLabel) then begin StrPCopy(MsgText, Format(lsVolumesDifferent1, [RealVolumeLabel, OrigVolumeLabel])); StrCat(MsgText, lsVolumesDifferent2); StrCat(MsgText, lsVolumesDifferent3); if Application.MessageBox(MsgText, lsWarning, MB_YESNOCANCEL) <> IDYES then exit; end; ScanFolder(OrigPath, OrigDiskName, RealVolumeLabel, true); end; end; //-------------------------------------------------------------------- // Scans a folder to database as a disk procedure TFormDBase.ScanFolder(Directory, DiskName, VolumeLabel: ShortString; NoOverWarning: boolean); begin if FormIsClosed then exit; if DBaseIsReadOnly then exit; try PanelsLocked := true; DoScan(Directory[1], Directory, DiskName, false, NoOverWarning); PanelsLocked := false; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Does the actual scan of the disk, returns false when interrupted by the user function TFormDBase.DoScan (Drive: char; StartPath: ShortString; DiskName: ShortString; AutoRun, NoOverWarning: boolean): boolean; var VolumeLabel : ShortString; MsgText, MsgCaption: array[0..256] of char; TmpKey : ShortString; KeyPos : Integer; SaveKey : ShortString; SaveSelected : Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; FileSystem : TFileSystem; DriveType : integer; DoRepeat : boolean; KeyToBeDeletedAtExit: integer; TmpStr10 : String[10]; i : integer; begin // the exceptions are handled in the caller functions (ScanDisk, ...) Result := false; if FormIsClosed then exit; if DBaseIsReadOnly then exit; SaveKey := ''; KeyToBeDeletedAtExit := -1; SaveAttr := 0; SaveSelected := 0; SavePath := ''; QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); SaveFile := LastSelectedFile; if not ReadVolumeLabel (Drive + ':', VolumeLabel, FileSystem, DriveType) then begin Application.MessageBox( StrPCopy(MsgText, lsDrive + Drive + ':' + lsIsNotAccesible), StrPCopy(MsgCaption, lsError), mb_Ok); exit; end; if DiskName = '' then begin DiskName := VolumeLabel; with FormAskForLabel do begin Caption := Drive + ':'; if DiskName <> '' then begin TmpKey := AnsiUpperCase(DiskName); if TmpKey = DiskName then begin DiskName := AnsiLowerCase(DiskName); DiskName[1] := TmpKey[1]; end; end; GeneratedName := ''; if QLocalOptions.DiskNamePattern <> '' then begin GeneratedName := QLocalOptions.DiskNamePattern; i := Pos('#N', GeneratedName); if i = 0 then i := Pos('#n', GeneratedName); if (i>0) then begin ShortDelete(GeneratedName, i, 2); TmpStr10 := IntToStr(QLocalOptions.DiskCounter+1); ShortInsert(TmpStr10, GeneratedName, i); end; i := Pos('#D', GeneratedName); if i = 0 then i := Pos('#d', GeneratedName); if (i>0) then begin ShortDelete(GeneratedName, i, 2); ShortInsert(DiskName, GeneratedName, i); end; end; EditDiskName.Text := TrimSpaces(DiskName); DoRepeat := true; while DoRepeat do begin DoRepeat := false; if not AutoRun or (EditDiskName.Text = '') then if ShowModal <> mrOk then exit; EditDiskName.Text := TrimSpaces(EditDiskName.Text); if EditDiskName.Text = '' then exit; {$ifdef mswindows} {$ifndef DELPHI1} if (AnsiLowerCase(VolumeLabel) <> AnsiLowerCase(EditDiskName.Text)) and ((DriveType=0) or (DriveType=DRIVE_REMOVABLE) or (DriveType=DRIVE_FIXED) and not QLocalOptions.DisableVolNameChange) then begin i := Application.MessageBox( StrPCopy(MsgText, lsLabelDifferent_Change), StrPCopy(MsgCaption, lsDifferentNames), mb_YesNoCancel); if i = IDCANCEL then exit; if i = IDYES then begin if (FileSystem = FAT) and (length(EditDiskName.Text) > 12) then begin Application.MessageBox( StrPCopy(MsgText, lsOnDisk + Drive + ':' + lsLimitedLength), StrPCopy(MsgCaption, lsError), mb_Ok); DoRepeat := true; end else begin if not WriteVolumeLabel (Drive + ':', EditDiskName.Text) then Application.MessageBox( StrPCopy(MsgText, lsVolumeLabel + Drive + ':' + lsCannotBeChanged), StrPCopy(MsgCaption, lsError), mb_Ok) else VolumeLabel := EditDiskName.Text; // we need to save the proper volume label end; end; end; {$endif} {$endif} end; {while} DiskName := EditDiskName.Text; if GeneratedNameUsed then inc(QLocalOptions.DiskCounter); end; {with} end; TmpKey := DiskName; if QI_GetCountToShow(DBaseHandle) > 0 then // to delete begin if QI_KeySearch(DBaseHandle, TmpKey, KeyPos) then // existing found begin // TmpKey is filled by the item from KeyField - by the QI_KeySearch proc.} if not AutoRun and QLocalOptions.OverwriteWarning and not NoOverWarning then if Application.MessageBox( StrPCopy(MsgText, lsOverwriteExistingRecord + DiskName + '?'), StrPCopy(MsgCaption, lsWarning), mb_YesNoCancel) <> IdYes then exit; QI_ReadDBaseEntryToSaved(DBaseHandle, KeyPos); // we save the tree for faster scanning KeyToBeDeletedAtExit := KeyPos; end; end; QI_ClearSearchCol(DBaseHandle); QI_ClearTreeStruct(DBaseHandle); FormScanProgress.DBaseHandle := DBaseHandle; FormScanProgress.Drive := Drive; FormScanProgress.DiskName := DiskName; FormScanProgress.VolumeLabel := VolumeLabel; FormScanProgress.StartPath := StartPath; FormScanProgress.ScanningQDir4 := false; FormScanProgress.ShowModal; if FormScanProgress.Success then begin if (KeyToBeDeletedAtExit <> -1) then begin // firts we must save TreeStruct, otherwise it would be deleted when the disk is deleted QI_SaveTreeStruct(DBaseHandle); QI_DeleteDBaseEntry(DBaseHandle, KeyToBeDeletedAtExit); //no error checking // restore TreeStruct from the backup QI_RestoreTreeStruct(DBaseHandle); end; if not QI_AppendNewDBaseEntry(DBaseHandle) then // here is also the change in keyfield begin MsgShouldExit; QI_ClearTreeStruct(DBaseHandle); JumpTo(SaveKey, SavePath, SaveFile); exit; end; end; QI_ClearTreeStruct(DBaseHandle); QI_ClearSavedTreeStruct(DBaseHandle); QI_GoToKey(DBaseHandle, TmpKey); Result := FormScanProgress.Success; end; //-------------------------------------------------------------------- // Import from QuickDir 4.1 - predecessor of DiskBase procedure TFormDBase.ImportFromQDir41(FileName: ShortString); var Response: integer; begin {$ifdef CZECH} if FormIsClosed then exit; if DBaseIsReadOnly then exit; Response := Application.MessageBox(lsImportConversion, lsImportFrom4, MB_YESNOCANCEL or MB_DEFBUTTON2); if Response = IDCANCEL then exit; QI_SetQDir4CharConversion (Response = IDYES); try PanelsLocked := true; QI_OpenQDir4Database(FileName); ScanQDir4Database; QI_CloseQDir4Database; PanelsLocked := false; UpdateDiskWindow; ReloadTree; ReloadFileCol(''); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; {$endif} end; //-------------------------------------------------------------------- // Import from QuickDir 4.1 - predecessor of DiskBase procedure TFormDBase.ScanQDir4Database; var TmpKey : ShortString; SaveKey : ShortString; SaveSelected : Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; begin SaveKey := ''; SaveAttr := 0; SaveSelected := 0; SavePath := ''; SaveFile := LastSelectedFile; if FormIsClosed then exit; if DBaseIsReadOnly then exit; QI_ClearSearchCol(DBaseHandle); QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); FormScanProgress.DBaseHandle := DBaseHandle; FormScanProgress.Drive := 'X'; FormScanProgress.ScanningQDir4 := true; FormScanProgress.ShowModal; if not FormScanProgress.Success then begin QI_ClearTreeStruct(DBaseHandle); QI_ClearSavedTreeStruct(DBaseHandle); JumpTo(SaveKey, SavePath, SaveFile); end else begin QI_ClearTreeStruct(DBaseHandle); QI_ClearSavedTreeStruct(DBaseHandle); QI_GoToKey(DBaseHandle, TmpKey); end; end; //-------------------------------------------------------------------- // Finds all filters available. Filters are DLLs with the extension renamed to q32 procedure TFormDBase.FindConvertDLLs; var FindMask : ShortString; QSearchRec : TSearchRec; OneFileName: ShortString; QResult : Integer; begin FindMask := GetProgramDir + '*.q32'; QResult := SysUtils.FindFirst (FindMask, faArchive or faReadOnly, QSearchRec); while QResult = 0 do begin OneFileName := QSearchRec.Name; Dec(OneFileName[0], 4); ConvertDLLs.Add(OneFileName); QResult := SysUtils.FindNext(QSearchRec); end; SysUtils.FindClose(QSearchRec); end; //-------------------------------------------------------------------- // Deletes a disk from the database procedure TFormDBase.DeleteRecord; var Key : ShortString; Attr : Word; KeyPos: Integer; MsgText, MsgCaption: array[0..256] of char; SelectedCount : longint; begin if FormIsClosed then exit; if DBaseIsReadOnly then exit; try if not QI_GetCurrentKey(DBaseHandle, Key, Attr, KeyPos) then exit; SelectedCount := QI_GetSelectedCount(DBaseHandle); if SelectedCount > 0 then begin if Application.MessageBox( StrPCopy(MsgText, lsRecordsSelected + IntToStr(SelectedCount) + lsDeleteAll), StrPCopy(MsgCaption, lsConfirmation), mb_YesNo) <> IdYes then exit; QI_DeleteSelectedDBaseEntries(DBaseHandle); end else begin if Attr and kaDeleted <> 0 then exit; //DBaseHandle is empty if Application.MessageBox( StrPCopy(MsgText, lsDeleteRecord + Key + '"?'), StrPCopy(MsgCaption, lsConfirmation), mb_YesNo) <> IdYes then exit; QI_DeleteDBaseEntry(DBaseHandle, KeyPos); end; QI_ClearTreeStruct(DBaseHandle); QI_GoToKey(DBaseHandle, Key); if QI_GetCountToShow(DBaseHandle) = 0 then begin QI_SetNeedUpdDiskWin (DBaseHandle); QI_SetNeedUpdTreeWin (DBaseHandle); QI_SetNeedUpdFileWin (DBaseHandle); end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Determines whether the current disk can be undeleted function TFormDBase.CanUndeleteRecord: boolean; var Key : ShortString; Attr : Word; KeyPos: Integer; begin Result := false; if FormIsClosed then exit; if DBaseIsEmpty then exit; if not QI_GetCurrentKey(DBaseHandle, Key, Attr, KeyPos) then exit; Result := Attr and kaDeleted <> 0; end; //-------------------------------------------------------------------- // Undeletes a disk procedure TFormDBase.UndeleteRecord; var Key : ShortString; Attr : Word; KeyPos: Integer; TmpKey : ShortString; TmpKeyPos : Integer; begin if FormIsClosed then exit; if DBaseIsReadOnly then exit; try if not QI_GetCurrentKey(DBaseHandle, Key, Attr, KeyPos) then exit; if Attr and kaDeleted = 0 then exit; TmpKey := Key; while QI_KeySearch(DBaseHandle, TmpKey, TmpKeyPos) do begin with FormRenameDlg do begin Caption := lsNewNameForUndeletedDisk; Edit1.Text := TmpKey; Label2.Caption := lsDiskWithName + TmpKey + lsAlreadyExists; if ShowModal <> mrOK then exit; TmpKey := Edit1.Text; end; end; QI_RenameDBaseEntry(DBaseHandle, KeyPos, TmpKey, true); QI_ClearTreeStruct(DBaseHandle); QI_GoToKey(DBaseHandle, TmpKey); if QI_GetCountToShow(DBaseHandle) = 0 then begin QI_SetNeedUpdDiskWin (DBaseHandle); QI_SetNeedUpdTreeWin (DBaseHandle); QI_SetNeedUpdFileWin (DBaseHandle); end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Changes the disk name in the database procedure TFormDBase.ChangeDiskName; var Key : ShortString; Attr : Word; KeyPos: Integer; TmpKey : ShortString; TmpKeyPos: Integer; begin if FormIsClosed then exit; try if not QI_GetCurrentKey(DBaseHandle, Key, Attr, KeyPos) then exit; if Attr and kaDeleted <> 0 then exit; with FormRenameDlg do begin Edit1.Text := Key; Caption := lsDiskNameChange; Label2.Caption := ''; if ShowModal <> mrOK then exit; TmpKey := Edit1.Text; while (AnsiUpperCase(Key) <> AnsiUpperCase(TmpKey)) and QI_KeySearch(DBaseHandle, TmpKey, TmpKeyPos) do begin Caption := lsNameMustBeUnique; Edit1.Text := TmpKey; Label2.Caption := lsDiskWithName + TmpKey + lsAlreadyExists; if ShowModal <> mrOK then exit; TmpKey := Edit1.Text; end; QI_RenameDBaseEntry(DBaseHandle, KeyPos, TmpKey, false); QI_ClearTreeStruct(DBaseHandle); QI_GoToKey(DBaseHandle, Key); end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Searches for the folder/file/description by the text procedure TFormDBase.SearchName; var FormFoundFileList: TFormFoundFileList; FoundTitle : ShortString; SaveKey : ShortString; SaveSelected: Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; DBaseInfo : TDBaseInfo; begin if FormIsClosed then exit; if FormSearchFileDlg.ShowModal <> mrOK then exit; // verify, whether the user wants to search in selected disks and // does not have any disk selected QI_GetDBaseInfo(DBaseHandle, DBaseInfo); if (DBaseInfo.iSelectedDisks = 0) and (FormSearchFileDlg.DlgData.SearchIn = siSelectedDisks) then begin Application.MessageBox(lsNoSelectedDisk, lsCannotSearch, mb_OK); exit; end; if (DBaseInfo.iNotSelectedDisks = 0) and (FormSearchFileDlg.DlgData.SearchIn = siNotSelectedDisks) then begin Application.MessageBox(lsAllDisksSelected, lsCannotSearch, mb_OK); exit; end; FormSearchName.DBaseHandle := DBaseHandle; try QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); SaveFile := LastSelectedFile; if FormSearchName.ShowModal = mrOk then begin if QGlobalOptions.FoundToNewWin then FormFoundFileList := nil else FormFoundFileList := TFormFoundFileList(MainForm.GetFoundForm(foFoundFile)); if FormFoundFileList = nil then begin FormFoundFileList := TFormFoundFileList.Create(Self); FormFoundFileList.Tag := Self.Tag; FormFoundFileList.DBaseWindow := Self; end else FormFoundFileList.BringToFront; FoundTitle := Caption + ': ' + FormSearchFileDlg.ComboBoxMask.Text; if length(FoundTitle) > 30 then FoundTitle := ShortCopy(FoundTitle, 1, 26) + ' ...'; FormFoundFileList.Caption := FoundTitle; FormFoundFileList.GetList(DBaseHandle); end; JumpTo(SaveKey, SavePath, SaveFile); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Search for the files selected in the file panel procedure TFormDBase.SearchSelected; var FormFoundFileList: TFormFoundFileList; FoundTitle : ShortString; SaveKey : ShortString; SaveSelected: Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; TmpS : ShortString; i : Integer; begin if FormIsClosed then exit; try with FormSearchFileDlg.DlgData do begin MaxLines := 10000; CaseSensitive:= false ; SearchIn := siWholedBase; ScanFileNames:= true; ScanDirNames := true; ScanDirLevel := -1; ScanDesc := false; MoreOptions := false; AddWildCards := false; AsPhrase := false; Mask := GetSelectedFileName; if pos(' ', Mask) > 0 then Mask := '"' + Mask + '" ' else Mask := Mask + ' '; for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do if ExtAttr and eaSelected <> 0 then begin TmpS := POneFile^.LongName + POneFile^.Ext; if pos(' ', TmpS) > 0 then TmpS := '"' + TmpS + '" ' else TmpS := TmpS + ' '; { --- ifdef DELPHI1} if (length(TmpS) + length(Mask)) < 255 then Mask := Mask + TmpS else begin Application.MessageBox(lsTooManyFilesSelected, lsNotification, mb_OK or mb_IconInformation); break; end; end; end; FormSearchName.DBaseHandle := DBaseHandle; QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); SaveFile := LastSelectedFile; if FormSearchName.ShowModal = mrOk then begin if QGlobalOptions.FoundToNewWin then FormFoundFileList := nil else FormFoundFileList := TFormFoundFileList(MainForm.GetFoundForm(foFoundFile)); if FormFoundFileList = nil then begin FormFoundFileList := TFormFoundFileList.Create(Self); FormFoundFileList.Tag := Self.Tag; FormFoundFileList.DBaseWindow := Self; end else FormFoundFileList.BringToFront; FoundTitle := Caption + ': ' + FormSearchFileDlg.DlgData.Mask; if length(FoundTitle) > 30 then FoundTitle := ShortCopy(FoundTitle, 1, 26) + ' ...'; FormFoundFileList.Caption := FoundTitle; FormFoundFileList.GetList(DBaseHandle); end; JumpTo(SaveKey, SavePath, SaveFile); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Search called when the user specifies it on the command line procedure TFormDBase.SearchParam(ParamFindFile: ShortString); var FormFoundFileList: TFormFoundFileList; FoundTitle : ShortString; SaveKey : ShortString; SaveSelected: Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; begin if FormIsClosed then exit; with FormSearchFileDlg.DlgData do begin SortArr[1] := soName; SortArr[2] := soTime; SortArr[3] := soKey; MaxLines := 1000; CaseSensitive:= false ; SearchIn := siWholedBase; ScanFileNames:= true; ScanDirNames := true; ScanDesc := false; ScanDirLevel := -1; MoreOptions := false; Mask := ParamFindFile; AddWildCards:= false; AsPhrase := false; end; FormSearchName.DBaseHandle := DBaseHandle; try QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); SaveFile := LastSelectedFile; if FormSearchName.ShowModal = mrOk then begin if QGlobalOptions.FoundToNewWin then FormFoundFileList := nil else FormFoundFileList := TFormFoundFileList(MainForm.GetFoundForm(foFoundFile)); if FormFoundFileList = nil then begin FormFoundFileList := TFormFoundFileList.Create(Self); FormFoundFileList.Tag := Self.Tag; FormFoundFileList.DBaseWindow := Self; end else FormFoundFileList.BringToFront; FoundTitle := Caption + ': ' + FormSearchFileDlg.DlgData.Mask; if length(FoundTitle) > 30 then FoundTitle := ShortCopy(FoundTitle, 1, 26) + ' ...'; FormFoundFileList.Caption := FoundTitle; FormFoundFileList.GetList(DBaseHandle); end; JumpTo(SaveKey, SavePath, SaveFile); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Search for disks according to the sizes procedure TFormDBase.SearchEmpty; var FormFoundEmptyList: TFormFoundEmptyList; FoundTitle : ShortString; SaveKey : ShortString; SaveSelected: Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; begin if FormIsClosed then exit; FormSearchEmpty.DBaseHandle := DBaseHandle; try QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); SaveFile := LastSelectedFile; if FormSearchEmpty.ShowModal = mrOk then begin if {QGlobalOptions.FoundToNewWin} false // not necessary at all then FormFoundEmptyList := nil else FormFoundEmptyList := TFormFoundEmptyList(MainForm.GetFoundForm(foFoundEmpty)); if FormFoundEmptyList = nil then begin FormFoundEmptyList := TFormFoundEmptyList.Create(Self); FormFoundEmptyList.Tag := Self.Tag; FormFoundEmptyList.DBaseWindow := Self; end else FormFoundEmptyList.BringToFront; FoundTitle := Caption + lsListOfFreeSpace; FormFoundEmptyList.Caption := FoundTitle; FormFoundEmptyList.GetList(DBaseHandle); end; JumpTo(SaveKey, SavePath, SaveFile); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Shows the window with the information about the disk procedure TFormDBase.ShowDiskInfo; var TreeInfo: TTreeInfo; begin if FormIsClosed then exit; try QI_GetTreeInfo(DBaseHandle, TreeInfo); FormDiskInfo.SetValues(TreeInfo); FormDiskInfo.ShowModal; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Shows the window with the information about the database procedure TFormDBase.ShowDBaseInfo; var DBaseInfo: TDBaseInfo; begin if FormIsClosed then exit; try QI_GetDBaseInfo(DBaseHandle, DBaseInfo); FormDBaseInfo.SetValues(DBaseInfo, ShortDBaseFileName); FormDBaseInfo.ShowModal; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Jumps to the selected disk-folder-file procedure TFormDBase.JumpTo(Disk, Dir, FileName: ShortString); var KeyIndex : Integer; Key : ShortString; Attr : Word; begin if FormIsClosed then exit; try QI_GoToKey(DBaseHandle, Disk); QI_ClearNeedUpdDiskWin(DBaseHandle); if QI_GetCurrentKey (DbaseHandle, Key, Attr, KeyIndex) then if DrawGridDisks.Row <> KeyIndex then if KeyIndex < DrawGridDisks.RowCount then DrawGridDisks.Row := KeyIndex; // the change of Row causes SelectCell call - need to reset the NeedUpdTree ReloadTree; QI_ClearNeedUpdTreeWin(DBaseHandle); QI_GoToDir(DBaseHandle, Dir); JumpInOutline(QI_GetCurDirCol(DBaseHandle)); ReloadFileCol(FileName); QI_ClearNeedUpdFileWin(DBaseHandle); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Shows the window for editing the description procedure TFormDBase.EditDescription; var Path, FileName: ShortString; i : Integer; Buf : PChar; Len : longint; FilePointer: TFilePointer; begin if FormIsClosed then exit; try if QGlobalOptions.FileDisplayType = fdBrief then i := DrawGridFiles.Selection.Left*DrawGridFiles.RowCount + DrawGridFiles.Selection.Top else i := pred(DrawGridFiles.Row); if i < FilesList.Count then with TOneFileLine(FilesList.Objects[i]) do begin if POneFile^.LongName = '..' then begin Application.MessageBox(lsDescriptionCannotBeByParentDir, lsNotification, mb_OK or mb_IconInformation); exit; end; FileName := POneFile^.LongName + POneFile^.Ext; QI_GetFullDirPath (DBaseHandle, Path); if ShortCopy(Path, length(Path), 1) <> '\' then Path := Path + '\'; with FormDescription do begin MemoDesc.ReadOnly := DBaseIsReadOnly; MenuExitAndSave.Enabled := not DBaseIsReadOnly; ButtonOK.Enabled := not DBaseIsReadOnly; LabelFile.Caption := Path + FileName; QI_LoadDescToBuf(DBaseHandle, POneFile^.Description, Buf); MemoDesc.SetTextBuf(Buf); StrDispose(Buf); if (ShowModal = mrOK) and MemoDesc.Modified and not DBaseIsReadOnly then begin Len := MemoDesc.GetTextLen; if Len = 0 then begin FilePointer := POneFile^.SelfFilePos; if not QI_SaveBufToDesc(DBaseHandle, FilePointer, nil) then Application.MessageBox(lsDescriptionCannotBeSaved, lsError, mb_OK or mb_IconStop) else begin POneFile^.Description := FilePointer; QI_UpdateDescInCurList(DBaseHandle, POneFile); end; end else begin Buf := StrAlloc(Len + 1); MemoDesc.GetTextBuf(Buf, Len + 1); FilePointer := POneFile^.SelfFilePos; if not QI_SaveBufToDesc(DBaseHandle, FilePointer, Buf) then Application.MessageBox(lsDescriptionCannotBeSaved, lsError, mb_OK or mb_IconStop) else begin POneFile^.Description := FilePointer; QI_UpdateDescInCurList(DBaseHandle, POneFile); end; StrDispose(Buf); end; end; end; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Returns the database handle function TFormDBase.GetDBaseHandle: PDBaseHandle; begin Result := DBaseHandle; end; //-------------------------------------------------------------------- // Handles event issued when the user clicks in the disk panel procedure TFormDBase.DrawGridDisksMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var i: Integer; begin if FormIsClosed then exit; try if Button = mbLeft then begin if LastDiskSelected >= DrawGridDisks.RowCount then LastDiskSelected := pred(DrawGridDisks.RowCount); if ssShift in Shift then begin for i := 0 to pred(DrawGridDisks.RowCount) do begin QI_SetSelectionFlag(DBaseHandle, false, i); end; if LastDiskSelected <= DrawGridDisks.Row then for i := LastDiskSelected to DrawGridDisks.Row do begin QI_ToggleSelectionFlag(DBaseHandle, i); end else for i := LastDiskSelected downto DrawGridDisks.Row do begin QI_ToggleSelectionFlag(DBaseHandle, i); end; DrawGridDisks.Repaint; end; if ssCtrl in Shift then begin QI_ToggleSelectionFlag(DBaseHandle, DrawGridDisks.Row); end; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Displays the dislaog box for selecting disks/files by a mask procedure TFormDBase.SelectDisksOrFiles(Disks: boolean); var i, j : Integer; MaskCol: TPQCollection; Key : ShortString; Attr : Word; Matching: boolean; begin if Disks then begin FormMaskSelect.Caption := lsSelectionOfDisks; FormMaskSelect.LabelMask.Caption := lsEnterMaskForSelectionOfDisks; FormMaskSelect.ComboBoxMaskFiles.Visible := false; FormMaskSelect.ComboBoxMaskDisks.Visible := true; FormMaskSelect.ActiveControl := FormMaskSelect.ComboBoxMaskDisks; end else begin FormMaskSelect.Caption := lsSelectionOfFiles; FormMaskSelect.LabelMask.Caption := lsEnterMaskForSelectionOfFiles; FormMaskSelect.ComboBoxMaskDisks.Visible := false; FormMaskSelect.ComboBoxMaskFiles.Visible := true; FormMaskSelect.ActiveControl := FormMaskSelect.ComboBoxMaskFiles; end; if FormMaskSelect.ShowModal <> mrOK then exit; MaskCol := New(TPQCollection, Init(30, 50)); try if Disks then begin if FormMaskSelect.ComboBoxMaskDisks.Text = '' then FormMaskSelect.ComboBoxMaskDisks.Text := '*'; TokenFindMask(FormMaskSelect.ComboBoxMaskDisks.Text, MaskCol, false, false, false); for i := 0 to pred(DrawGridDisks.RowCount) do begin if (QI_GetKeyAt(DBaseHandle, Key, Attr, i)) and (Attr and kaSelected = 0) then begin Matching := false; for j := 0 to pred(MaskCol^.Count) do if MaskCompare (GetPQString(POneMask(MaskCol^.At(j))^.MaskName), Key, false, false) then begin Matching := true; break; end; if Matching then begin QI_SetSelectionFlag(DBaseHandle, true, i); end; end; end; DrawGridDisks.Repaint; end else begin if FormMaskSelect.ComboBoxMaskFiles.Text = '' then FormMaskSelect.ComboBoxMaskFiles.Text := '*'; TokenFindMask(FormMaskSelect.ComboBoxMaskFiles.Text, MaskCol, false, false, false); for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do begin Matching := false; for j := 0 to pred(MaskCol^.Count) do if MaskCompare (GetPQString(POneMask(MaskCol^.At(j))^.MaskName), POneFile^.LongName + POneFile^.Ext, false, false) then begin Matching := true; break; end; if Matching then ExtAttr := ExtAttr or eaSelected; end; DrawGridFiles.Repaint; end; if MaskCol <> nil then Dispose(MaskCol, Done); MaskCol := nil; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Unselects all disks or files procedure TFormDBase.UnselectDisksOrFiles(Disks: boolean); var i: Integer; begin try if Disks then begin for i := 0 to pred(DrawGridDisks.RowCount) do QI_SetSelectionFlag(DBaseHandle, false, i); DrawGridDisks.Repaint; end else begin for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do ExtAttr := ExtAttr and not eaSelected; DrawGridFiles.Repaint; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Selects all disks or files procedure TFormDBase.SelectAllDisksOrFiles(Disks: boolean); var i: Integer; AlreadySelected: boolean; begin try if Disks then begin if UsePersistentBlocks then begin {first try if all files are already selected} AlreadySelected := true; for i := 0 to pred(DrawGridDisks.RowCount) do if not QI_GetSelectionFlag(DBaseHandle, i) then begin AlreadySelected := false; break; end; for i := 0 to pred(DrawGridDisks.RowCount) do QI_SetSelectionFlag(DBaseHandle, not AlreadySelected, i); end else begin for i := 0 to pred(DrawGridDisks.RowCount) do QI_SetSelectionFlag(DBaseHandle, true, i); end; DrawGridDisks.Repaint; end else begin if UsePersistentBlocks then begin AlreadySelected := true; for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do if (ExtAttr and eaSelected) = 0 then begin AlreadySelected := false; break; end; if AlreadySelected then for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do ExtAttr := ExtAttr and not eaSelected else for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do ExtAttr := ExtAttr or eaSelected; end else begin for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do ExtAttr := ExtAttr or eaSelected; end; DrawGridFiles.Repaint; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Jumps one level up in the tree to the parent of the current file procedure TFormDBase.GoToParent; var i : Integer; begin if FormIsClosed then exit; try for i := 0 to pred(FilesList.Count) do with TOneFileLine(FilesList.Objects[i]) do if FileType = ftParent then begin DirToScrollHandle := QI_GetCurDirCol(DBaseHandle); if (POneFile^.Attr and faDirectory <> 0) and (POneFile^.SubDirCol <> nil) then begin QI_SetCurDirCol (DBaseHandle, POneFile^.SubDirCol); QI_UpdateFileCol(DBaseHandle); UpdateHeader; JumpInOutline(POneFile^.SubDirCol); end; exit; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Handles event issued when the user clicks with the right mouse button // in the disk panel to get a pop-up menu. procedure TFormDBase.PopupMenuDiskPopup(Sender: TObject); begin MenuDeleteDisk.Enabled := not DBaseIsReadOnly; MenuRenameDisk.Enabled := not DBaseIsReadOnly; MenuUndeleteDisk.Enabled := CanUndeleteRecord and not DBaseIsReadOnly; end; //-------------------------------------------------------------------- // Menu handler - Rescans the current disk procedure TFormDBase.MenuRescanClick(Sender: TObject); begin RescanDisk; end; //-------------------------------------------------------------------- // Menu handler - deletes the current disk procedure TFormDBase.MenuDeleteDiskClick(Sender: TObject); begin DeleteRecord; end; //-------------------------------------------------------------------- // Menu handler - undeletes the disk procedure TFormDBase.MenuUndeleteDiskClick(Sender: TObject); begin UndeleteRecord; end; //-------------------------------------------------------------------- // Menu handler - renames disk in the database procedure TFormDBase.MenuRenameDiskClick(Sender: TObject); begin ChangeDiskName; end; //-------------------------------------------------------------------- // Menu handler - select disks by a mask procedure TFormDBase.MenuSelectDisksClick(Sender: TObject); begin SelectDisksOrFiles(true); end; //-------------------------------------------------------------------- // Menu handler - unselect disks procedure TFormDBase.MenuDeselectDiskClick(Sender: TObject); begin UnselectDisksOrFiles(true); end; //-------------------------------------------------------------------- // Menu handler - display disk info procedure TFormDBase.MenuInfoDiskClick(Sender: TObject); begin ShowDiskInfo; end; //-------------------------------------------------------------------- // Menu handler - print disks procedure TFormDBase.MenuPrintDisksClick(Sender: TObject); begin MakePrintDisk; end; //-------------------------------------------------------------------- // Menu handler - display help for disk panel procedure TFormDBase.MenuHelpDisksClick(Sender: TObject); begin Application.HelpContext(150); end; //-------------------------------------------------------------------- // Menu handler - called when the popup menu (on right mouse button) // is called for the tree panel procedure TFormDBase.PopupMenuTreePopup(Sender: TObject); begin MenuShowTree.Checked := QGlobalOptions.ShowTree; end; //-------------------------------------------------------------------- // Menu handler - shows or hides the tree procedure TFormDBase.MenuShowTreeClick(Sender: TObject); begin MenuShowTree.Checked := not MenuShowTree.Checked; QGlobalOptions.ShowTree := not QGlobalOptions.ShowTree; ShowOrHideTreePanel; end; //-------------------------------------------------------------------- // Menu handler - fully expands the tree procedure TFormDBase.MenuExpandTreeClick(Sender: TObject); begin OutlineTree.BeginUpdate; OutlineTree.FullExpand; OutlineTree.EndUpdate; end; //-------------------------------------------------------------------- // Menu handler - collapses the tree procedure TFormDBase.MenuCollapseTreeClick(Sender: TObject); begin OutlineTree.BeginUpdate; OutlineTree.FullCollapse; OutlineTree.Items[1].Expand(false); OutlineTree.EndUpdate; end; //-------------------------------------------------------------------- // Menu handler - displays the help for the tree panel procedure TFormDBase.MenuHelpTreeClick(Sender: TObject); begin Application.HelpContext(160); end; //-------------------------------------------------------------------- // Menu handler - called when the popup menu (on right mouse button) // is called for the files panel procedure TFormDBase.PopupMenuFilesPopup(Sender: TObject); begin MenuSortName.Checked := false; MenuSortExt.Checked := false; MenuSortTime.Checked := false; MenuSortSize.Checked := false; case QGlobalOptions.SortCrit of scName: MenuSortName.Checked := true; scExt : MenuSortExt.Checked := true; scTime: MenuSortTime.Checked := true; scSize: MenuSortSize.Checked := true; end; case QGlobalOptions.FileDisplayType of fdBrief: begin MenuBrief.Checked := true; MenuDetailed.Checked := false; end; fdDetailed: begin MenuDetailed.Checked := true; MenuBrief.Checked := false; end; end; end; //-------------------------------------------------------------------- // Menu handler - copy files to clipboard procedure TFormDBase.MenuCopyFileClick(Sender: TObject); begin MakeCopyFiles; end; //-------------------------------------------------------------------- // Menu handler - Delete File procedure TFormDBase.MenuDeleteFileClick(Sender: TObject); begin DeleteFiles; end; //-------------------------------------------------------------------- // Menu handler - edit the description procedure TFormDBase.MenuEditDescClick(Sender: TObject); begin EditDescription; end; //-------------------------------------------------------------------- // Menu handler - display files in brief list procedure TFormDBase.MenuBriefClick(Sender: TObject); begin SetBriefFileDisplay(true); PopupMenuFilesPopup(Sender); end; //-------------------------------------------------------------------- // Menu handler - display files in detailed list procedure TFormDBase.MenuDetailedClick(Sender: TObject); begin SetBriefFileDisplay(false); PopupMenuFilesPopup(Sender); end; //-------------------------------------------------------------------- // Menu handler - sort files by names procedure TFormDBase.MenuSortNameClick(Sender: TObject); begin SetNeedResort(scName); PopupMenuFilesPopup(Sender); end; //-------------------------------------------------------------------- // Menu handler - sort files by extension procedure TFormDBase.MenuSortExtClick(Sender: TObject); begin SetNeedResort(scExt); PopupMenuFilesPopup(Sender); end; //-------------------------------------------------------------------- // Menu handler - sort files by date/time procedure TFormDBase.MenuSortTimeClick(Sender: TObject); begin SetNeedResort(scTime); PopupMenuFilesPopup(Sender); end; //-------------------------------------------------------------------- // Menu handler - sort files by size procedure TFormDBase.MenuSortSizeClick(Sender: TObject); begin SetNeedResort(scSize); PopupMenuFilesPopup(Sender); end; //-------------------------------------------------------------------- // Menu handler - print files procedure TFormDBase.MenuPrintFilesClick(Sender: TObject); begin MakePrintFiles; end; //-------------------------------------------------------------------- // Menu handler - display help for file panel procedure TFormDBase.MenuHelpFilesClick(Sender: TObject); begin Application.HelpContext(170); end; //-------------------------------------------------------------------- // called when the user selects Mask Select from the Main Form menu procedure TFormDBase.DoSelection; begin if (ActiveControl is TDrawGrid) then begin if TDrawGrid(ActiveControl).Tag = 1 then SelectDisksOrFiles(true); if TDrawGrid(ActiveControl).Tag = 3 then SelectDisksOrFiles(false); end; end; //-------------------------------------------------------------------- // called when the user selects Select All from the Main Form menu procedure TFormDBase.SelectAll; begin if (ActiveControl is TDrawGrid) then begin if TDrawGrid(ActiveControl).Tag = 1 then SelectAllDisksOrFiles(true); if TDrawGrid(ActiveControl).Tag = 3 then SelectAllDisksOrFiles(false); end; end; //-------------------------------------------------------------------- // called when the user selects Unselect All from the Main Form menu procedure TFormDBase.UnselectAll; begin if (ActiveControl is TDrawGrid) then begin if TDrawGrid(ActiveControl).Tag = 1 then UnselectDisksOrFiles(true); if TDrawGrid(ActiveControl).Tag = 3 then UnselectDisksOrFiles(false); end; end; //-------------------------------------------------------------------- // Menu handler - select disks/files procedure TFormDBase.MenuSelectFilesClick(Sender: TObject); begin SelectDisksOrFiles(false); end; //-------------------------------------------------------------------- // Menu handler - unselect disks/files procedure TFormDBase.MenuUnselectFilesClick(Sender: TObject); begin UnselectDisksOrFiles(false); end; //-------------------------------------------------------------------- // Returns the tag of the active panel function TFormDBase.ActivePanel: Integer; begin Result := 0; if (ActiveControl is TDrawGrid) then Result := TDrawGrid(ActiveControl).Tag; if (ActiveControl is TTreeView) then Result := TTreeView(ActiveControl).Tag; end; //-------------------------------------------------------------------- // Menu handler - select all files procedure TFormDBase.MenuSelectAllFilesClick(Sender: TObject); begin SelectAllDisksOrFiles(false); end; //-------------------------------------------------------------------- // Menu handler - select all disks procedure TFormDBase.MenuSelectAllDisksClick(Sender: TObject); begin SelectAllDisksOrFiles(true); end; //-------------------------------------------------------------------- // Menu handler - copy disk to clipboard procedure TFormDBase.MenuCopyDiskClick(Sender: TObject); begin MakeCopyDisks; end; //-------------------------------------------------------------------- // called from the Main Form's menu - copies disks or files to clipboard procedure TFormDBase.MakeCopy; begin if (ActiveControl is TDrawGrid) then begin if TDrawGrid(ActiveControl).Tag = 1 then MakeCopyDisks; if TDrawGrid(ActiveControl).Tag = 3 then MakeCopyFiles; end; end; //-------------------------------------------------------------------- // Copies disks to clipboard procedure TFormDBase.MakeCopyDisks; var Key : ShortString; Attr : Word; Current, i : Integer; CopyBuffer : PChar; hCopyBuffer: THandle; TotalLength: longint; begin try TotalLength := 0; QI_GetCurrentKey(DBaseHandle, Key, Attr, Current); for i := 0 to pred(QI_GetCountToShow(DBaseHandle)) do if QI_GetKeyAt(DBaseHandle, Key, Attr, i) then if (Attr and kaSelected <> 0) or (i = Current) then AddToBuffer(true, Key + #13#10, CopyBuffer, TotalLength); ///hCopyBuffer := GlobalAlloc(GMEM_MOVEABLE or GMEM_ZEROINIT, TotalLength+1); ///CopyBuffer := GlobalLock(hCopyBuffer); for i := 0 to pred(QI_GetCountToShow(DBaseHandle)) do if QI_GetKeyAt(DBaseHandle, Key, Attr, i) then if (Attr and kaSelected <> 0) or (i = Current) then AddToBuffer(false, Key + #13#10, CopyBuffer, TotalLength); ///GlobalUnlock(hCopyBuffer); ///Clipboard.SetAsHandle(CF_TEXT, hCopyBuffer); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Copies files to clipboard procedure TFormDBase.MakeCopyFiles; var CopyBuffer : PChar; TotalLength : longint; hCopyBuffer : THandle; procedure Run(CalcOnly: boolean); var i: Integer; S: ShortString; OneFileLine: TOneFileLine; begin for i := 0 to pred(FilesList.Count) do begin OneFileLine := TOneFileLine(FilesList.Objects[i]); if (OneFileLine.ExtAttr and eaSelected <> 0) or (i = CurFileSelected) then begin S := OneFileLine.POneFile^.LongName + OneFileLine.POneFile^.Ext; AddToBuffer(CalcOnly, S + #9, CopyBuffer, TotalLength); if OneFileLine.POneFile^.Time <> 0 then S := DosDateToStr(OneFileLine.POneFile^.Time) + #9 + DosTimeToStr(OneFileLine.POneFile^.Time, QGlobalOptions.ShowSeconds) else S := #9; AddToBuffer(CalcOnly, S + #9, CopyBuffer, TotalLength); case OneFileLine.FileType of ftDir : S := lsFolder; ftParent: S := ''; else S := FormatSize(OneFileLine.POneFile^.Size, QGlobalOptions.ShowInKb); end; AddToBuffer(CalcOnly, S + #9, CopyBuffer, TotalLength); S := ''; if OneFileLine.POneFile^.Description <> 0 then QI_GetShortDesc(DBaseHandle, OneFileLine.POneFile^.Description, S); AddToBuffer(CalcOnly, S + #13#10, CopyBuffer, TotalLength); end; end; end; begin try TotalLength := 0; Run(true); // calculate the size needed ///CopyBuffer := GlobalAlloc(GMEM_MOVEABLE or GMEM_ZEROINIT, TotalLength+1); ///CopyBuffer := GlobalLock(hCopyBuffer); Run(false); ///GlobalUnlock(hCopyBuffer); ///Clipboard.SetAsHandle(CF_TEXT, hCopyBuffer); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Deletes files procedure TFormDBase.DeleteFiles; begin if (CurFileSelected >= 1) and (FilesList.count > CurFileSelected) then begin with TOneFileLine(FilesList.Objects[CurFileSelected]).POneFile^ do QI_DeleteFile(DBaseHandle,LongName); QI_UpdateFileCol(DBaseHandle); // FilesList.Delete(CurFileSelected); // UpdateFileWindowGrid(CurFileSelected-1); end; end; //-------------------------------------------------------------------- // Prints files procedure TFormDBase.MakePrintFiles; const NoOfColumns = 4; var AmountPrintedPx: Integer; PageCounter: Integer; ColWidthsPx: array [0..NoOfColumns-1] of Integer; TimeWidthPx: Integer; // Disk, Dir, Name, Size, Time, Desc //------ function CanPrintOnThisPage: boolean; begin Result := true; if PrintDialog.PrintRange <> prPageNums then exit; with PrintDialog do if (PageCounter >= FromPage) and (PageCounter <= ToPage) then exit; Result := false; end; //------ procedure GoToNewPage; begin if PrintDialog.PrintRange <> prPageNums then ///QPrinterNewPage else begin with PrintDialog do if (PageCounter >= FromPage) and (PageCounter < ToPage) then ///QPrinterNewPage; end; end; //------ procedure PrintHeaderAndFooter; var OutRect : TRect; S, S1 : ShortString; Attr : Word; TmpIndex: Integer; begin if FormAbortPrint.Aborted then exit; {$ifdef mswindows} QPrinterSaveAndSetFont(pfsItalic); // header OutRect.Left := LeftPrintAreaPx; OutRect.Right := RightPrintAreaPx; OutRect.Top := TopPrintAreaPx; OutRect.Bottom := OutRect.Top + LineHeightPx; if CanPrintOnThisPage then begin S := QGlobalOptions.PrintHeader; if S = '' then begin QI_GetCurrentKey(DBaseHandle, S, Attr, TmpIndex); S := lsDisk1 + S; end; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); QI_GetFullDirPath(DBaseHandle, S1); S1 := lsFolder2 + S1; OutRect.Left := OutRect.Right - QPrinterGetTextWidth(S1); if OutRect.Left < (LeftPrintAreaPx + QPrinterGetTextWidth(S)) then OutRect.Left := LeftPrintAreaPx + QPrinterGetTextWidth(S) + 3*YPxPer1mm; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S1); QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 50)); {0.2 mm}; QPrinterMoveTo(LeftPrintAreaPx, OutRect.Bottom + YPxPer1mm); QPrinterLineTo(RightPrintAreaPx, OutRect.Bottom + YPxPer1mm); end; // footer OutRect.Left := LeftPrintAreaPx; OutRect.Bottom := BottomPrintAreaPx; OutRect.Top := OutRect.Bottom - LineHeightPx; if CanPrintOnThisPage then begin QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, TimePrinted); S := lsPage + IntToStr(PageCounter); OutRect.Left := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 50)); {0.2 mm}; QPrinterMoveTo(LeftPrintAreaPx, OutRect.Top - YPxPer1mm); QPrinterLineTo(RightPrintAreaPx, OutRect.Top - YPxPer1mm); end; QPrinterRestoreFont; {$endif} end; //------ procedure PrintColumnNames; var OutRect : TRect; S : ShortString; i : Integer; StartX : Integer; begin if FormAbortPrint.Aborted then exit; {$ifdef mswindows} QPrinterSaveAndSetFont(pfsBold); OutRect.Left := LeftPrintAreaPx; OutRect.Top := AmountPrintedPx; OutRect.Bottom := OutRect.Top + LineHeightPx; for i := 0 to NoOfColumns-1 do if CanPrintOnThisPage then begin OutRect.Right := OutRect.Left + ColWidthsPx[i] - 3*XPxPer1mm; if (OutRect.Right > RightPrintAreaPx) or (i = NoOfColumns-1) then OutRect.Right := RightPrintAreaPx; if (OutRect.Left < OutRect.Right) then begin case i of 0: begin S := lsName; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; 1: begin S := lsSize; StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 2: begin S := lsDateAndTime; StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 3: begin S := lsDescription; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; end; end; inc(OutRect.Left,ColWidthsPx[i]); end; inc(AmountPrintedPx, LineHeightPx + YPxPer1mm); QPrinterRestoreFont; {$endif} end; //------ procedure PrintOneLine(Index: Integer); var OneLine : TOneFileLine; OutRect : TRect; TmpRect : TRect; S : ShortString; i : Integer; StartX : Integer; begin if FormAbortPrint.Aborted then exit; {$ifdef mswindows} OneLine := TOneFileLine(FilesList.Objects[Index]); if (PrintDialog.PrintRange = prSelection) and (OneLine.ExtAttr and eaSelected = 0) and (Index <> pred(DrawGridFiles.Row)) then exit; OutRect.Left := LeftPrintAreaPx; OutRect.Top := AmountPrintedPx; OutRect.Bottom := OutRect.Top + LineHeightPx; for i := 0 to NoOfColumns-1 do if CanPrintOnThisPage then begin OutRect.Right := OutRect.Left + ColWidthsPx[i] - 3*XPxPer1mm; if (OutRect.Right > RightPrintAreaPx) or (i = NoOfColumns-1) then OutRect.Right := RightPrintAreaPx; if OutRect.Left >= OutRect.Right then break; case i of 0: begin S := OneLine.POneFile^.LongName + OneLine.POneFile^.Ext; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; 1: begin case OneLine.FileType of ftDir : S := lsFolder; ftParent: S := ''; else S := FormatSize(OneLine.POneFile^.Size, QGlobalOptions.ShowInKb); end; StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 2: begin if OneLine.POneFile^.Time <> 0 then begin S := DosTimeToStr(OneLine.POneFile^.Time, QGlobalOptions.ShowSeconds); StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); S := DosDateToStr(OneLine.POneFile^.Time); TmpRect := OutRect; TmpRect.Right := TmpRect.Right - TimeWidthPx; if TmpRect.Right > TmpRect.Left then begin StartX := TmpRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(TmpRect, StartX, TmpRect.Top, S); end; end; end; 3: begin if OneLine.POneFile^.Description <> 0 then begin if QI_GetShortDesc(DBaseHandle, OneLine.POneFile^.Description, S) then QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end end; end; inc(OutRect.Left,ColWidthsPx[i]); end; inc(AmountPrintedPx, LineHeightPx); {$endif} end; //------ var i: Integer; TmpS: array[0..256] of char; Copies: Integer; PxWidth : integer; TmpInt : integer; OneFileLine: TOneFileLine; begin if PrintDialog.Execute then begin {$ifdef mswindows} QPrinterReset(QGlobalOptions); AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; TimeWidthPx := QPrinterGetTextWidth(DosTimeToStr(longint(23) shl 11, QGlobalOptions.ShowSeconds)); TimeWidthPx := TimeWidthPx + TimeWidthPx div 6; // calculate Pixel width PxWidth := 100; for i := 0 to pred (FilesList.Count) do begin OneFileLine := TOneFileLine(FilesList.Objects[i]); TmpInt := QPrinterGetTextWidth (OneFileLine.POneFile^.LongName + OneFileLine.POneFile^.Ext); if TmpInt > PxWidth then PxWidth := TmpInt; end; ColWidthsPx[0] := PxWidth + 3*XPxPer1mm; ColWidthsPx[1] := QPrinterGetTextWidth(FormatSize(2000000000, QGlobalOptions.ShowInKb)) + 3*XPxPer1mm; ColWidthsPx[2] := QPrinterGetTextWidth(' ' + DosDateToStr (694026240)) + TimeWidthPx + 3*XPxPer1mm; ColWidthsPx[3] := 25 * QPrinterGetTextWidth('Mmmmxxxxx '); FormAbortPrint.LabelProgress.Caption := lsPreparingToPrint; FormAbortPrint.Show; MainForm.Enabled :=false; try Application.ProcessMessages; for Copies := 1 to PrintDialog.Copies do begin PageCounter := 1; QPrinterBeginDoc(lsQuickDir); PrintHeaderAndFooter; PrintColumnNames; FormAbortPrint.LabelProgress.Caption := lsPrintingPage + IntToStr(PageCounter); for i := 0 to pred(FilesList.Count) do begin Application.ProcessMessages; if FormAbortPrint.Aborted then break; PrintOneLine(i); if (AmountPrintedPx + 3*LineHeightPx) > BottomPrintAreaPx then begin if not FormAbortPrint.Aborted then begin GoToNewPage; inc(PageCounter); end; FormAbortPrint.LabelProgress.Caption := lsPrintingPage + IntToStr(PageCounter); Application.ProcessMessages; AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; PrintHeaderAndFooter; PrintColumnNames; end; end; QPrinterEndDoc; if FormAbortPrint.Aborted then break; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; on EOther: Exception do Application.MessageBox(StrPCopy(TmpS, EOther.Message), lsError, mb_Ok or mb_IconExclamation); end; MainForm.Enabled :=true; FormAbortPrint.Hide; {$endif} end; end; //-------------------------------------------------------------------- // Prints the tree procedure TFormDBase.MakePrintTree; var AmountPrintedPx: Integer; PageCounter : Integer; TreeList : TQStringList; MWidthPx : Integer; ColumnWidthPx: Integer; Column : Integer; NoOfColumns : Integer; //------ function CanPrintOnThisPage: boolean; begin Result := true; if PrintDialog.PrintRange <> prPageNums then exit; with PrintDialog do if (PageCounter >= FromPage) and (PageCounter <= ToPage) then exit; Result := false; end; //------ procedure GoToNewPage; begin if PrintDialog.PrintRange <> prPageNums then ///QPrinterNewPage else begin with PrintDialog do if (PageCounter >= FromPage) and (PageCounter < ToPage) then ///QPrinterNewPage; end; end; //------ procedure PrintHeaderAndFooter; var OutRect : TRect; S, S1 : ShortString; Attr : Word; TmpIndex: Integer; begin if FormAbortPrint.Aborted then exit; {$ifdef mswindows} if CanPrintOnThisPage then begin QPrinterSaveAndSetFont(pfsItalic); // header OutRect.Left := LeftPrintAreaPx; OutRect.Right := RightPrintAreaPx; OutRect.Top := TopPrintAreaPx; OutRect.Bottom := OutRect.Top + LineHeightPx; S := QGlobalOptions.PrintHeader; if S = '' then S := lsDatabase + ShortDBaseFileName; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); QI_GetCurrentKey(DBaseHandle, S1, Attr, TmpIndex); S1 := lsDisk1 + S1; OutRect.Left := OutRect.Right - QPrinterGetTextWidth(S1); if OutRect.Left < (LeftPrintAreaPx + QPrinterGetTextWidth(S)) then OutRect.Left := LeftPrintAreaPx + QPrinterGetTextWidth(S) + 3*YPxPer1mm; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S1); QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 50)); {0.2 mm}; QPrinterMoveTo(LeftPrintAreaPx, OutRect.Bottom + YPxPer1mm); QPrinterLineTo(RightPrintAreaPx, OutRect.Bottom + YPxPer1mm); // footer OutRect.Left := LeftPrintAreaPx; OutRect.Bottom := BottomPrintAreaPx; OutRect.Top := OutRect.Bottom - LineHeightPx; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, TimePrinted); S := lsPage + IntToStr(PageCounter); OutRect.Left := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 50)); {0.2 mm}; QPrinterMoveTo(LeftPrintAreaPx, OutRect.Top - YPxPer1mm); QPrinterLineTo(RightPrintAreaPx, OutRect.Top - YPxPer1mm); QPrinterRestoreFont; end; {$endif} end; //------ procedure PrintOneLine(Index: Integer); var OneTreeLine : TOneTreeLine; OutRect : TRect; j : Integer; begin if FormAbortPrint.Aborted then exit; {$ifdef mswindows} OneTreeLine := TOneTreeLine(TreeList.Objects[Index]); OutRect.Top := AmountPrintedPx; OutRect.Right := LeftPrintAreaPx + succ(Column)*ColumnWidthPx; OutRect.Bottom := OutRect.Top + LineHeightPx; if CanPrintOnThisPage then begin QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 100)); {0.1 mm}; OutRect.Left := LeftPrintAreaPx + Column * ColumnWidthPx + MWidthPx div 2; for j := 1 to length(OneTreeLine.Line) do begin case OneTreeLine.Line[j] of '+': begin QPrinterMoveTo(OutRect.Left, OutRect.Top); QPrinterLineTo(OutRect.Left, OutRect.Bottom); QPrinterMoveTo(OutRect.Left, OutRect.Top + LineHeightPx div 2); QPrinterLineTo(OutRect.Left + MWidthPx, OutRect.Top + LineHeightPx div 2); end; 'L': begin QPrinterMoveTo(OutRect.Left, OutRect.Top); QPrinterLineTo(OutRect.Left, OutRect.Top + LineHeightPx div 2); QPrinterLineTo(OutRect.Left + MWidthPx, OutRect.Top + LineHeightPx div 2); end; 'I': begin QPrinterMoveTo(OutRect.Left, OutRect.Top); QPrinterLineTo(OutRect.Left, OutRect.Bottom); end; end; inc(OutRect.Left, 2*MWidthPx); end; dec(OutRect.Left, MWidthPx div 2); QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, TreeList.Strings[Index]); end; inc(AmountPrintedPx, LineHeightPx); {$endif} end; //------ var i, j: Integer; TmpS: array[0..256] of char; Copies: Integer; LastLine: string[MaxTreeLevels]; OneTreeLine, NextTreeLine: TOneTreeLine; StartLevel, StartItem: LongInt; MaxTextLengthPx: LongInt; MaxLevel : LongInt; TmpInt : LongInt; begin if PrintDialog.Execute then begin {$ifdef mswindows} QPrinterReset(QGlobalOptions); AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; MWidthPx := QPrinterGetTextWidth('M'); TreeList := TQStringList.Create; MaxTextLengthPx := 0; MaxLevel := 0; with OutlineTree do begin if PrintDialog.PrintRange = prSelection then StartItem := SelectedItem else StartItem := 1; if StartItem = 0 then StartItem := 1; StartLevel := Items[StartItem].Level; for i := StartItem to ItemCount do begin if (i > StartItem) and (PrintDialog.PrintRange = prSelection) and (longint(Items[i].Level) <= StartLevel) then break; OneTreeLine := TOneTreeLine.Create; OneTreeLine.Level := Items[i].Level - 1; fillchar(OneTreeLine.Line, sizeof(OneTreeLine.Line), ' '); OneTreeLine.Line[0] := char(OneTreeLine.Level); TreeList.AddObject(Items[i].Text, OneTreeLine); TmpInt := QPrinterGetTextWidth(Items[i].Text); if TmpInt > MaxTextLengthPx then MaxTextLengthPx := TmpInt; if OneTreeLine.Level > MaxLevel then MaxLevel := OneTreeLine.Level; end; end; FillChar(LastLine, sizeof(LastLine), ' '); for i := pred(TreeList.Count) downto 0 do begin OneTreeLine := TOneTreeLine(TreeList.Objects[i]); for j := 1 to OneTreeLine.Level-1 do if (LastLine[j]='I') or (LastLine[j]='L') then OneTreeLine.Line[j] := 'I'; if OneTreeLine.Level > 0 then OneTreeLine.Line[OneTreeLine.Level] := 'L'; LastLine := OneTreeLine.Line; for j := length(LastLine) + 1 to MaxTreeLevels do LastLine[j] := ' '; end; for i := 0 to TreeList.Count-2 do begin OneTreeLine := TOneTreeLine(TreeList.Objects[i]); NextTreeLine := TOneTreeLine(TreeList.Objects[i+1]); j := OneTreeLine.Level; if j > 0 then if (OneTreeLine.Line[j]='L') and ((NextTreeLine.Line[j]='I') or (NextTreeLine.Line[j]='L')) then OneTreeLine.Line[j] := '+'; end; MaxTextLengthPx := MaxTextLengthPx + MaxLevel*MWidthPx*2 + 3*XPxPer1mm; NoOfColumns := (RightPrintAreaPx - LeftPrintAreaPx) div MaxTextLengthPx; if NoOfColumns < 1 then NoOfColumns := 1; ColumnWidthPx := (RightPrintAreaPx - LeftPrintAreaPx) div NoOfColumns; Column := 0; FormAbortPrint.LabelProgress.Caption := lsPreparingToPrint; FormAbortPrint.Show; MainForm.Enabled :=false; try Application.ProcessMessages; for Copies := 1 to PrintDialog.Copies do begin PageCounter := 1; QPrinterBeginDoc(lsQuickDir); PrintHeaderAndFooter; FormAbortPrint.LabelProgress.Caption := lsPrintingPage + IntToStr(PageCounter); for i := 0 to pred(TreeList.Count) do begin Application.ProcessMessages; if FormAbortPrint.Aborted then break; PrintOneLine(i); if (AmountPrintedPx + 3*LineHeightPx) > BottomPrintAreaPx then begin if Column < pred(NoOfColumns) then begin AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; inc(Column); end else begin if not FormAbortPrint.Aborted then begin GoToNewPage; Column := 0; inc(PageCounter); end; FormAbortPrint.LabelProgress.Caption := lsPrintingPage + IntToStr(PageCounter); Application.ProcessMessages; AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; PrintHeaderAndFooter; end; end; end; QPrinterEndDoc; if FormAbortPrint.Aborted then break; end; except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; on E: Exception do Application.MessageBox(StrPCopy(TmpS, E.Message), lsError, mb_Ok or mb_IconExclamation); end; TreeList.Free; MainForm.Enabled :=true; FormAbortPrint.Hide; {$endif} end; end; //-------------------------------------------------------------------- // Menu handler - print the tree procedure TFormDBase.MenuPrintTreeClick(Sender: TObject); begin MakePrintTree; end; //-------------------------------------------------------------------- // Prints the disk procedure TFormDBase.MakePrintDisk; var SaveKey : ShortString; SaveSelected: Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; begin if FormIsClosed then exit; FormDiskPrint.DBaseHandle := DBaseHandle; try QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); SaveFile := LastSelectedFile; FormDiskPrint.ShortDBaseFileName := ShortDBaseFileName; FormDiskPrint.ShowModal; JumpTo(SaveKey, SavePath, SaveFile); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Called from the Main From to print the selected panel procedure TFormDBase.DoPrint(PrintWhat: TPrintWhat); begin case PrintWhat of prSelectedPanel: begin if (ActiveControl is TDrawGrid) then begin if TDrawGrid(ActiveControl).Tag = 1 then MakePrintDisk; if TDrawGrid(ActiveControl).Tag = 3 then MakePrintFiles; end; if (ActiveControl is TTreeView) then if TTreeView(ActiveControl).Tag = 2 then MakePrintTree; end; prDisks: MakePrintDisk; prTree: MakePrintFiles; prFiles: MakePrintFiles; end; end; //-------------------------------------------------------------------- // Handles the event issued when the mouse moves over the file panel // USed for displaying the bubbles with descriptions procedure TFormDBase.DrawGridFilesMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if (LastMouseXFiles <> X) or (LastMouseYFiles <> Y) then begin MousePosAlreadyChecked := false; EraseFileHint; LastMouseXFiles := X; LastMouseYFiles := Y; LastMouseMoveTime := GetTickCount; end; end; //-------------------------------------------------------------------- // Shows the bubble file hint procedure TFormDBase.ShowFileHint; var Point : TPoint; Rect : TRect; HintWidth : integer; LineHeight : integer; OneFileLine: TOneFileLine; // pointer S : ShortString; DosDateTime: longint; i, TmpInt : integer; PolygonPts : array[0..2] of TPoint; XPosition : integer; begin if MousePosAlreadyChecked then exit; if DisableHints <> 0 then exit; if FilesHintDisplayed then exit; MousePosAlreadyChecked := true; GetCursorPos(Point); Point := DrawGridFiles.ScreenToClient(Point); // is the mouse cursor still in the window? if (LastMouseXFiles <> Point.X) or (LastMouseYFiles <> Point.Y) then exit; OneFileLine := FindOneFileLine(Point, Rect); if OneFileLine = nil then exit; if OneFileLine.FileType = ftDir then exit; if OneFileLine.FileType = ftParent then exit; HiddenForm.MemoForHints.Lines.Clear; if OneFileLine.POneFile^.Description <> 0 then begin if QI_GetShortDesc(DBaseHandle, OneFileLine.POneFile^.Description, S) then HiddenForm.MemoForHints.Lines.Insert(0, S); end; if QGlobalOptions.FileDisplayType = fdBrief then begin DosDateTime := OneFileLine.POneFile^.Time; if DosDateTime <> 0 then HiddenForm.MemoForHints.Lines.Insert(0, DosDateToStr(DosDateTime) + ' ' + DosTimeToStr(DosDateTime, QGlobalOptions.ShowSeconds)); HiddenForm.MemoForHints.Lines.Insert(0, FormatSize(OneFileLine.POneFile^.Size, QGlobalOptions.ShowInKb)); HiddenForm.MemoForHints.Lines.Insert(0, OneFileLine.POneFile^.LongName+OneFileLine.POneFile^.Ext); end; if HiddenForm.MemoForHints.Lines.Count = 0 then exit; with DrawGridFiles.Canvas do begin HintWidth := 0; LineHeight := 0; for i := 0 to pred(HiddenForm.MemoForHints.Lines.Count) do begin TmpInt := TextWidth(HiddenForm.MemoForHints.Lines[i]); if HintWidth < TmpInt then HintWidth := TmpInt; TmpInt := TextHeight(HiddenForm.MemoForHints.Lines[i]); if LineHeight < TmpInt then LineHeight := TmpInt; end; // find the position XPosition := (Rect.Left + Rect.Right) div 2; if XPosition < (DrawGridFiles.Width div 2) then begin LastHintRect.Left := XPosition - 11; LastHintRect.Right := XPosition + HintWidth -5; if (LastHintRect.Right >= DrawGridFiles.Width) then OffsetRect(LastHintRect, DrawGridFiles.Width-LastHintRect.Right-3, 0); PolygonPts[0].X := LastHintRect.Left + 5; PolygonPts[1].X := LastHintRect.Left + 11; PolygonPts[2].X := LastHintRect.Left + 17; end else begin LastHintRect.Left := XPosition - HintWidth + 5; LastHintRect.Right := XPosition + 11; if (LastHintRect.Left <= 0) then OffsetRect(LastHintRect, -LastHintRect.Left+3, 0); PolygonPts[0].X := LastHintRect.Right - 17; PolygonPts[1].X := LastHintRect.Right - 11; PolygonPts[2].X := LastHintRect.Right - 5; end; if Rect.Top < (DrawGridFiles.Height div 2) then begin LastHintRect.Top := Rect.Bottom + 3; LastHintRect.Bottom := Rect.Bottom + HiddenForm.MemoForHints.Lines.Count * LineHeight + 5; PolygonPts[0].Y := LastHintRect.Top; PolygonPts[1].Y := LastHintRect.Top - 6; PolygonPts[2].Y := LastHintRect.Top; end else begin LastHintRect.Top := Rect.Top - HiddenForm.MemoForHints.Lines.Count * LineHeight - 5; LastHintRect.Bottom := Rect.Top - 3; PolygonPts[0].Y := LastHintRect.Bottom-1; PolygonPts[1].Y := LastHintRect.Bottom + 5; PolygonPts[2].Y := LastHintRect.Bottom-1; end; Brush.Color := $CFFFFF; Font.Color := clBlack; Pen.Color := clBlack; RoundRect(LastHintRect.Left, LastHintRect.Top, LastHintRect.Right, LastHintRect.Bottom, 4, 4); Polygon(PolygonPts); Pen.Color := $CFFFFF; MoveTo(PolygonPts[0].X+1, PolygonPts[0].Y); LineTo(PolygonPts[2].X, PolygonPts[2].Y); for i := 0 to pred(HiddenForm.MemoForHints.Lines.Count) do TextOut(LastHintRect.Left+3, LastHintRect.Top+1+i*LineHeight, HiddenForm.MemoForHints.Lines[i]); end; FilesHintDisplayed := true; end; //-------------------------------------------------------------------- // Locates the line in the file list according to the coordinates function TFormDBase.FindOneFileLine(Point: TPoint; var Rect: TRect): TOneFileLine; var i: integer; ACol, ARow: longint; begin DrawGridFiles.MouseToCell(Point.X, Point.Y, ACol, ARow); Rect := DrawGridFiles.CellRect(ACol, ARow); if QGlobalOptions.FileDisplayType = fdBrief then begin i := ACol*DrawGridFiles.RowCount + ARow; if (i >= 0) and (i < FilesList.Count) then begin Result := TOneFileLine(FilesList.Objects[i]); exit; end; end else begin Rect.Left := 0; Rect.Right := DrawGridFiles.Width; if (ARow > 0) and (ARow <= FilesList.Count) then begin Result := TOneFileLine(FilesList.Objects[ARow-1]); exit; end; end; Result := nil; end; //-------------------------------------------------------------------- // Erases the bubble file hint procedure TFormDBase.EraseFileHint; begin if FilesHintDisplayed then begin FilesHintDisplayed := false; InflateRect(LastHintRect, 0, 6); InvalidateRect(DrawGridFiles.Handle, @LastHintRect, false); end; end; //-------------------------------------------------------------------- // Exports to the text format procedure TFormDBase.ExportToOtherFormat; var SaveKey : ShortString; SaveSelected: Integer; SaveAttr : Word; SavePath : ShortString; SaveFile : ShortString; begin if FormIsClosed then exit; try QI_GetCurrentKey (DBaseHandle, SaveKey, SaveAttr, SaveSelected); QI_GetFullDirPath (DBaseHandle, SavePath); SaveFile := LastSelectedFile; FormDiskExport.DBaseHandle := DBaseHandle; FormDiskExport.ShowModal; JumpTo(SaveKey, SavePath, SaveFile); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //-------------------------------------------------------------------- // Menu handler - open file procedure TFormDBase.MenuOpenClick(Sender: TObject); begin ShiftState := [ssShift]; DrawGridFilesDblClick(Sender); end; //-------------------------------------------------------------------- // Handles keystrokes, enables user DLL commands procedure TFormDBase.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var i: integer; pUserCommand: TPUserCommand; begin for i:=1 to g_UserCommandList.Count do begin pUserCommand := TPUserCommand(g_UserCommandList.Items[i-1]); if (Key <> pUserCommand.m_wKey) then begin continue; end; if (pUserCommand.m_bShift and not (ssShift in ShiftState)) then continue; if (pUserCommand.m_bControl and not (ssCtrl in ShiftState)) then continue; if (pUserCommand.m_bAlt and not (ssAlt in ShiftState)) then continue; ExecuteUserCommand(pUserCommand.m_sDll, pUserCommand.m_sParams, pUserCommand.m_bTestExist); Key := 0; end; end; //----------------------------------------------------------------------------- // Executes a use command in the user DLL procedure TFormDBase.ExecuteUserCommand(sDll: AnsiString; sParams: AnsiString; bTestExist: boolean); var i: integer; sMsg : AnsiString; sBasePath : ShortString; // root path sRelativePath : ShortString; // path from root to the file sFullPath : AnsiString; // full path to the physical file, including file name sPathInArchive : AnsiString; // if the file is archive, the path in archive OrigDiskName : ShortString; OrigVolumeLabel: ShortString; Index : Integer; Attr : Word; FileSystem : TFileSystem; VolumeLabel : ShortString; DriveType : integer; Exists : boolean; InArchive : boolean; DriveAccessible: boolean; DriveRemovable : boolean; DriveNetwork : boolean; VolumeLabelDiffers: boolean; Retry : boolean; dwDiskBaseAttr : DWORD; pszDescription : PChar; begin LOG('ExecuteUserCommand(sDll=%s, sParams=%s)', [PChar(sDll), PChar(sParams)]); if QGlobalOptions.FileDisplayType = fdBrief then i := DrawGridFiles.Selection.Left*DrawGridFiles.RowCount + DrawGridFiles.Selection.Top else i := pred(DrawGridFiles.Row); if i < FilesList.Count then with TOneFileLine(FilesList.Objects[i]) do begin if ((POneFile^.Attr and faDirectory = 0) or (POneFile^.Attr and faQArchive <> 0)) then begin Retry := true; while Retry do begin Retry := false; sPathInArchive := ''; QI_GetCurrentKeyEx (DBaseHandle, OrigDiskName, OrigVolumeLabel, sBasePath, Attr, Index); if (length(sBasePath) > 0) and (sBasePath[length(sBasePath)] = '\') then SetLength(sBasePath, Length(sBasePath)-1); QI_GetFullDirPath(DBaseHandle, sRelativePath); InArchive := QI_IsInArchive (DBaseHandle); If InArchive then begin sPathInArchive := sRelativePath; sRelativePath := QI_GetArchivePath(DBaseHandle); Delete(sPathInArchive, 1, Length(sRelativePath)); if (Length(sPathInArchive) > 0) and (sPathInArchive[length(sPathInArchive)] <> '\') then sPathInArchive := sPathInArchive + '\'; sPathInArchive := sPathInArchive + POneFile^.LongName + POneFile^.Ext; end else begin if (Length(sRelativePath) > 0) and (sRelativePath[length(sRelativePath)] <> '\') then sRelativePath := sRelativePath + '\'; sRelativePath := sRelativePath + POneFile^.LongName + POneFile^.Ext; end; sFullPath := sBasePath + sRelativePath; LOG('sFullPath=%s', [sFullPath]); LOG('sPathInArchive=%s', [sPathInArchive]); Exists := FileExists(sFullPath); VolumeLabel := ''; DriveAccessible := ReadVolumeLabel (sBasePath[1] + ':', VolumeLabel, FileSystem, DriveType); ///DriveRemovable := (DriveType = DRIVE_REMOVABLE) or /// (DriveType = DRIVE_CDROM); ///DriveNetwork := DriveType = DRIVE_REMOTE; VolumeLabelDiffers := false; if (length(VolumeLabel) > 0) then VolumeLabelDiffers := AnsiUppercase(OrigVolumeLabel) <> AnsiUppercase(VolumeLabel); if (not Exists and bTestExist) then begin sMsg := sFullPath + lsFileCannotBeOpen; if not DriveAccessible then sMsg := sFullPath + lsDiskNotAccessible; if DriveRemovable then sMsg := sFullPath + lsDifferentDisk; if InArchive then sMsg := sFullPath + lsFileInArchive; if DriveNetwork then sMsg := sFullPath + lsDiskIsNetworkDrive; if VolumeLabelDiffers then sMsg := sFullPath + lsVolumeLabelDiffers; sMsg := sFullPath + lsFileProbablyDeleted; Retry := Application.MessageBox(PChar(sMsg), lsFileNotFound, MB_RETRYCANCEL) = IDRETRY; LOG('Does not exist: %s', [sFullPath]); end else begin dwDiskBaseAttr := 0; if (Exists ) then dwDiskBaseAttr := dwDiskBaseAttr or daExists; if (DriveAccessible ) then dwDiskBaseAttr := dwDiskBaseAttr or daDriveAccessible; if (DriveRemovable ) then dwDiskBaseAttr := dwDiskBaseAttr or daDriveRemovable; if (DriveNetwork ) then dwDiskBaseAttr := dwDiskBaseAttr or daDriveNetwork; if (VolumeLabelDiffers) then dwDiskBaseAttr := dwDiskBaseAttr or daVolumeLabelDiffers; if (InArchive ) then dwDiskBaseAttr := dwDiskBaseAttr or daInArchive; QI_LoadDescToBuf(DBaseHandle, POneFile^.Description, pszDescription); if Pos('\', sDll) = 0 then sDll := ExtractFilePath(ParamStr(0)) + sDll; if (LoadUserDll(sDll)) then begin UserCommand(MainForm.Handle, PChar(sParams), PChar(sFullPath), PChar(sPathInArchive), DWORD(POneFile^.Time), DWORD(POneFile^.Size), DWORD(POneFile^.Attr and $FF), pszDescription, PChar(g_sTempFolder), dwDiskBaseAttr, nil); StrDispose(pszDescription); FreeUserDll(); end; end; end; // while end; // if end; // with end; //----------------------------------------------------------------------------- procedure TFormDBase.DiscGearPrint(hWindow: HWND); var Key : ShortString; Attr : Word; sText: AnsiString; i: integer; begin if FormIsClosed then exit; sText := ''; try for i := 0 to pred(DrawGridDisks.RowCount) do begin if (QI_GetKeyAt(DBaseHandle, Key, Attr, i)) and (Attr and kaSelected <> 0) then sText := sText + Key + #13#10; end; DiscGearPrintRun(hWindow, sText); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin FormIsClosed := true; Close; FatalErrorMessage(EFatal.Message); end; end; end; //----------------------------------------------------------------------------- // initialization of the unit begin g_bShowHelpAfterClose := false; end.
(* * Copyright (c) 2004 * HouSisong@gmail.com * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * Permission to use or copy this software for any purpose is hereby granted * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. * *) //------------------------------------------------------------------------------ // 具现化的大小写不敏感的String类型的声明 // Create by HouSisong, 2005.10.13 //------------------------------------------------------------------------------ unit DGL_StringCaseInsensitive; interface uses SysUtils; {$I DGLCfg.inc_h} const _NULL_Value:string=''; type _ValueType = string; //大小写不敏感的String function _HashValue(const Key: _ValueType):Cardinal;{$ifdef _DGL_Inline} inline; {$endif}//Hash函数 {$define _DGL_Compare} //比较函数 function _IsEqual(const a,b :_ValueType):boolean;{$ifdef _DGL_Inline} inline; {$endif} //result:=(a=b); function _IsLess(const a,b :_ValueType):boolean; {$ifdef _DGL_Inline} inline; {$endif} //result:=(a<b); 默认排序准则 {$I DGL.inc_h} type TCIStrAlgorithms = _TAlgorithms; ICIStrIterator = _IIterator; ICIStrContainer = _IContainer; ICIStrSerialContainer = _ISerialContainer; ICIStrVector = _IVector; ICIStrList = _IList; ICIStrDeque = _IDeque; ICIStrStack = _IStack; ICIStrQueue = _IQueue; ICIStrPriorityQueue = _IPriorityQueue; TCIStrVector = _TVector; TCIStrDeque = _TDeque; TCIStrList = _TList; ICIStrVectorIterator = _IVectorIterator; //速度比_IIterator稍快一点:) ICIStrDequeIterator = _IDequeIterator; //速度比_IIterator稍快一点:) ICIStrListIterator = _IListIterator; //速度比_IIterator稍快一点:) TCIStrStack = _TStack; TCIStrQueue = _TQueue; TCIStrPriorityQueue = _TPriorityQueue; // ICIStrMapIterator = _IMapIterator; ICIStrMap = _IMap; ICIStrMultiMap = _IMultiMap; TCIStrSet = _TSet; TCIStrMultiSet = _TMultiSet; TCIStrMap = _TMap; TCIStrMultiMap = _TMultiMap; TCIStrHashSet = _THashSet; TCIStrHashMultiSet = _THashMultiSet; TCIStrHashMap = _THashMap; TCIStrHashMultiMap = _THashMultiMap; implementation uses HashFunctions; function _HashValue(const Key :_ValueType):Cardinal; overload; begin result:=HashValue_StrCaseInsensitive(Key); end; function _IsEqual(const a,b :_ValueType):boolean; //result:=(a=b); begin result:=IsEqual_StrCaseInsensitive(a,b); end; function _IsLess(const a,b :_ValueType):boolean; //result:=(a<b); 默认排序准则 begin result:=IsLess_StrCaseInsensitive(a,b); end; {$I DGL.inc_pas} end.
unit frmBaseData; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, frmBase, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxContainer, cxTextEdit, cxMaskEdit, cxDropDownEdit, StdCtrls, Buttons, ExtCtrls, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, DBClient; type TBaseDataForm = class(TBaseForm) cdsTable: TClientDataSet; dsTable: TDataSource; cxgtvTable: TcxGridDBTableView; cxglvTable: TcxGridLevel; cxg1: TcxGrid; pnl_Only: TPanel; btnQuery: TSpeedButton; btnSave: TSpeedButton; btn_Exit: TSpeedButton; btnDelete: TSpeedButton; btnAdd: TSpeedButton; btnCancel: TSpeedButton; cbbTableName: TcxComboBox; cdsTableName: TClientDataSet; procedure FormCreate(Sender: TObject); procedure btnQueryClick(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btn_ExitClick(Sender: TObject); procedure cxgtvTableFocusedItemChanged(Sender: TcxCustomGridTableView; APrevFocusedItem, AFocusedItem: TcxCustomGridTableItem); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private { Private declarations } sTableName, sKey:WideString; procedure DataSave; procedure DataCancel; procedure DataQuery; procedure GetTableList; function CloseQuery:Boolean; procedure SetBtnState; procedure UpdateActions; override; public { Public declarations } end; var BaseDataForm: TBaseDataForm; implementation uses ServerDllPub, uFNMArtInfo, uGlobal, uDictionary, uShowMessage, uLogin, uGridDecorator; {$R *.dfm} { TBaseDataForm } function TBaseDataForm.CloseQuery: Boolean; begin if not TGlobal.DeltaIsNull(cdsTable) then begin if TMsgDialog.ShowMsgDialog('数据未保存,是否保存!', mtConfirmation, [mebYes, mebNo], mebYes)= mrYes then Result := False; end else Result := True; end; procedure TBaseDataForm.DataCancel; begin if cdsTable.Active then begin cdsTable.CancelUpdates; SetBtnState; end; end; procedure TBaseDataForm.DataQuery; var vData: OleVariant; sErrMsg: WideString; begin try if not CloseQuery then Exit; if cdsTableName.locate('Table_CHN', cbbTableName.Text,[]) then begin sTableName := QuotedStr(cdsTableName.FieldByName('Table_Name').AsString); sKey := cdsTableName.FieldByName('Key_Fields').AsString; end; if sTableName= '' then Exit; FNMServerObj.GetBaseTableInfo(vData, sTableName, sErrMsg); if sErrMsg <> '' then begin TMsgDialog.ShowMsgDialog(sErrMsg, mtError); Exit; end; cdsTable.Data := vData; BaseForm.Caption := '字典维护 【'+ cbbTableName.Text+ '】'; cxg1.SetFocus; GridDecorator.BindCxViewWithDataSource(cxgtvTable, dsTable, true); //GridDecorator.SetcxTableView(cxgtvTable, ['Operator','Operate_Time','Dept'],[], False); finally SetBtnState; end; end; procedure TBaseDataForm.DataSave; var vData: OleVariant; sErrMsg: WideString; begin try ShowMsg('正在保存。。。', crHourGlass); if TGlobal.DeltaIsNull(cdsTable) then Exit; //保存数据 vData := cdsTable.Delta; FNMServerObj.SaveBaseTableInfo(vData, sTableName, sKey, sErrMsg); if sErrMsg<>'' then begin TMsgDialog.ShowMsgDialog(sErrMsg, mtError); Exit; end; cdsTable.MergeChangeLog; finally SetBtnState; ShowMsg('', crDefault); end; end; procedure TBaseDataForm.GetTableList; var vData: OleVariant; sSQL, sErrMsg: WideString; begin try sSQL := QuotedStr(login.CurrentDepartment); FNMServerObj.GetQueryData(vData, 'fnGetBaseTableName', sSQL, sErrMsg); if sErrMsg <> '' then begin TMsgDialog.ShowMsgDialog(sErrMsg, mtError); Exit; end; cdsTableName.Data := vData; FillItemsFromDataSet(cdsTableName,'Table_CHN','','','',cbbTableName.Properties.Items); finally SetBtnState; end; end; procedure TBaseDataForm.SetBtnState; begin btnQuery.Enabled := cbbTableName.Text<>''; btnSave.Enabled := not TGlobal.DeltaIsNull(cdsTable); btnDelete.Enabled := not cdsTable.IsEmpty; btnAdd.Enabled := cdsTable.Active; btnCancel.Enabled := btnSave.Enabled; end; procedure TBaseDataForm.UpdateActions; begin inherited; end; procedure TBaseDataForm.FormCreate(Sender: TObject); begin inherited; GetTableList; end; procedure TBaseDataForm.btnQueryClick(Sender: TObject); begin inherited; DataQuery; end; procedure TBaseDataForm.btnAddClick(Sender: TObject); begin inherited; cdsTable.Append; end; procedure TBaseDataForm.btnSaveClick(Sender: TObject); begin inherited; DataSave; end; procedure TBaseDataForm.btnDeleteClick(Sender: TObject); begin inherited; cdsTable.Delete; end; procedure TBaseDataForm.btnCancelClick(Sender: TObject); begin inherited; DataCancel; end; procedure TBaseDataForm.btn_ExitClick(Sender: TObject); begin inherited; Close; end; procedure TBaseDataForm.cxgtvTableFocusedItemChanged( Sender: TcxCustomGridTableView; APrevFocusedItem, AFocusedItem: TcxCustomGridTableItem); begin inherited; SetBtnState; end; procedure TBaseDataForm.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TBaseDataForm.FormDestroy(Sender: TObject); begin inherited; BaseDataForm := nil; end; procedure TBaseDataForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin inherited; CanClose := CloseQuery; end; end.
unit Aurelius.Schema.MySQL; {$I Aurelius.Inc} interface uses Aurelius.Drivers.Interfaces, Aurelius.Schema.AbstractImporter, Aurelius.Sql.Metadata; type TMySQLSchemaImporter = class(TAbstractSchemaImporter) strict protected procedure GetDatabaseMetadata(Connection: IDBConnection; Database: TDatabaseMetadata); override; end; TMySQLSchemaRetriever = class(TSchemaRetriever) strict private procedure GetTables; procedure GetColumns; procedure GetPrimaryKeys; procedure GetUniqueKeys; procedure GetForeignKeys; procedure GetFieldDefinition(Column: TColumnMetadata; ADataType: string; ASize, APrecision, AScale: integer); public constructor Create(AConnection: IDBConnection; ADatabase: TDatabaseMetadata); override; procedure RetrieveDatabase; override; end; implementation uses SysUtils, Aurelius.Schema.Register; { TMySQLSchemaImporter } procedure TMySQLSchemaImporter.GetDatabaseMetadata(Connection: IDBConnection; Database: TDatabaseMetadata); var Retriever: TSchemaRetriever; begin Retriever := TMySQLSchemaRetriever.Create(Connection, Database); try Retriever.RetrieveDatabase; finally Retriever.Free; end; end; { TMySQLSchemaRetriever } constructor TMySQLSchemaRetriever.Create(AConnection: IDBConnection; ADatabase: TDatabaseMetadata); begin inherited Create(AConnection, ADatabase); end; procedure TMySQLSchemaRetriever.GetColumns; begin RetrieveColumns( 'SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, '+ 'NUMERIC_PRECISION, NUMERIC_SCALE, IS_NULLABLE, EXTRA '+ 'FROM INFORMATION_SCHEMA.COLUMNS '+ 'WHERE TABLE_SCHEMA = DATABASE() '+ 'ORDER BY TABLE_NAME, ORDINAL_POSITION', procedure (Column: TColumnMetadata; ResultSet: IDBResultSet) begin Column.NotNull := (AsString(ResultSet.GetFieldValue('IS_NULLABLE')) = 'NO'); GetFieldDefinition(Column, AsString(ResultSet.GetFieldValue('DATA_TYPE')), AsInteger(ResultSet.GetFieldValue('CHARACTER_MAXIMUM_LENGTH')), AsInteger(ResultSet.GetFieldValue('NUMERIC_PRECISION')), AsInteger(ResultSet.GetFieldValue('NUMERIC_SCALE')) ); Column.AutoGenerated := (AsString(ResultSet.GetFieldValue('EXTRA')) = 'auto_increment'); end ); end; procedure TMySQLSchemaRetriever.GetFieldDefinition(Column: TColumnMetadata; ADataType: string; ASize, APrecision, AScale: integer); const vNoSizeTypes : array[0..21] of string = ( 'bigint', 'bit', 'blob', 'date', 'datetime', 'double precision', 'float', 'int', 'longblob', 'longtext', 'mediumblob', 'mediumint', 'mediumtext', 'real', 'smallint', 'text', 'time', 'timestamp', 'tinyblob', 'tinyint', 'tinytext', 'year' ); function NeedSize: Boolean; var I: Integer; begin for i := 0 to high(vNoSizeTypes) do if vNoSizeTypes[I] = ADataType then Exit(false); Result := true; end; begin ADataType := Trim(LowerCase(ADataType)); if ADataType = 'double' then begin Column.DataType := 'DOUBLE PRECISION'; Exit; end; Column.DataType := ADataType; if NeedSize then begin if (ADataType = 'binary') or (ADataType = 'char') or (ADataType = 'varbinary') or (ADataType = 'varchar') then Column.Length := ASize else begin Column.Precision := APrecision; Column.Scale := AScale; end; end; end; procedure TMySQLSchemaRetriever.GetForeignKeys; begin RetrieveForeignKeys( 'SELECT R.CONSTRAINT_NAME, R.TABLE_NAME AS FK_TABLE_NAME, R.REFERENCED_TABLE_NAME AS PK_TABLE_NAME, '+ 'KC.COLUMN_NAME AS FK_COLUMN_NAME, KC.REFERENCED_COLUMN_NAME AS PK_COLUMN_NAME '+ 'FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE KC, INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R '+ 'WHERE R.CONSTRAINT_NAME = KC.CONSTRAINT_NAME AND R.TABLE_NAME = KC.TABLE_NAME '+ 'AND KC.CONSTRAINT_SCHEMA = DATABASE() AND R.CONSTRAINT_SCHEMA = DATABASE() '+ 'ORDER BY R.CONSTRAINT_NAME, KC.POSITION_IN_UNIQUE_CONSTRAINT' ); end; procedure TMySQLSchemaRetriever.GetPrimaryKeys; begin RetrievePrimaryKeys( 'SELECT C.CONSTRAINT_NAME, C.TABLE_NAME, K.COLUMN_NAME, K.ORDINAL_POSITION '+ 'FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS C, INFORMATION_SCHEMA.KEY_COLUMN_USAGE K '+ 'WHERE C.CONSTRAINT_TYPE=''PRIMARY KEY'' '+ 'AND C.TABLE_NAME = K.TABLE_NAME AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME '+ 'AND C.CONSTRAINT_SCHEMA = DATABASE() AND K.CONSTRAINT_SCHEMA = DATABASE() '+ 'ORDER BY C.TABLE_NAME, C.CONSTRAINT_NAME, K.ORDINAL_POSITION' ); end; procedure TMySQLSchemaRetriever.GetTables; begin RetrieveTables( 'SELECT TABLE_NAME '+ 'FROM INFORMATION_SCHEMA.TABLES '+ 'WHERE TABLE_TYPE=''BASE TABLE'' '+ 'AND TABLE_SCHEMA = DATABASE() '+ 'ORDER BY TABLE_NAME' ); end; procedure TMySQLSchemaRetriever.GetUniqueKeys; begin RetrieveUniqueKeys( 'SELECT C.CONSTRAINT_NAME, C.TABLE_NAME, K.COLUMN_NAME, K.ORDINAL_POSITION '+ 'FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS C, INFORMATION_SCHEMA.KEY_COLUMN_USAGE K '+ 'WHERE C.CONSTRAINT_TYPE=''UNIQUE'' '+ 'AND C.TABLE_NAME = K.TABLE_NAME AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME '+ 'AND C.CONSTRAINT_SCHEMA = DATABASE() AND K.CONSTRAINT_SCHEMA = DATABASE() '+ 'ORDER BY C.TABLE_NAME, C.CONSTRAINT_NAME, K.ORDINAL_POSITION' ); end; procedure TMySQLSchemaRetriever.RetrieveDatabase; begin Database.Clear; GetTables; GetColumns; GetPrimaryKeys; GetUniqueKeys; GetForeignKeys; end; initialization TSchemaImporterRegister.GetInstance.RegisterImporter('MySQL', TMySQLSchemaImporter.Create); end.
// ----------- Parse::Easy::Runtime ----------- // https://github.com/MahdiSafsafi/Parse-Easy // -------------------------------------------- unit Parse.Easy.Lexer.CodePointStream; interface uses System.SysUtils, System.Classes; type TCodePointStream = class(TObject) private FChars: TCharArray; FPosition: Integer; FCharCount: Integer; FLine: Integer; FColumn: Integer; function GetPosition: Integer; procedure SetPosition(const Value: Integer); function GetColumn: Integer; function GetLine: Integer; procedure SetColumn(const Value: Integer); procedure SetLine(const Value: Integer); public constructor Create(AStream: TStringStream); virtual; destructor Destroy(); override; function Peek(): Integer; function Advance(): Integer; function EndOfFile: Boolean; property Position: Integer read GetPosition write SetPosition; property Line: Integer read GetLine write SetLine; property Column: Integer read GetColumn write SetColumn; property Chars: TCharArray read FChars; property CharCount: Integer read FCharCount; end; implementation const EOF = -1; { TCodePointStream } constructor TCodePointStream.Create(AStream: TStringStream); begin FChars := AStream.Encoding.GetChars(AStream.Bytes, AStream.Position, AStream.Size - AStream.Position); FCharCount := Length(FChars); FPosition := 0; FLine := 1; FColumn := 1; end; destructor TCodePointStream.Destroy; begin inherited; end; function TCodePointStream.GetPosition: Integer; begin Result := FPosition; end; function TCodePointStream.GetColumn: Integer; begin Result := FColumn; end; function TCodePointStream.GetLine: Integer; begin Result := FLine; end; procedure TCodePointStream.SetColumn(const Value: Integer); begin FColumn := Value; end; procedure TCodePointStream.SetLine(const Value: Integer); begin FLine := Value; end; procedure TCodePointStream.SetPosition(const Value: Integer); begin FPosition := Value; end; function TCodePointStream.EndOfFile: Boolean; begin Result := FPosition >= FCharCount; end; function TCodePointStream.Peek: Integer; begin if EndOfFile() then exit(EOF); Result := Ord(FChars[FPosition]); end; function TCodePointStream.Advance: Integer; var CP: Integer; begin Result := Peek(); Inc(FPosition); CP := Peek(); if (CP = $000A) then begin Inc(FLine); FColumn := 0; end else Inc(FColumn); end; end.
unit LandmarkPathCalculator; interface uses SysUtils, System.Generics.Collections, System.Generics.Defaults, Ils.Utils, Geo.Hash, Geo.Pos, AStar64.DynImport, AStar64.Typ, AStar64.FileStructs, AStar64.LandMark; type TLPC = class public class procedure Gen( const AFullPath: string; const AFileName: string; const ALandmarkCoords: TGeoPosArray ); class procedure InsertLightsFromGeoPosArray( const ARLandmarkMatrix: TLandMarkMatrix; const ALandmarkCoords: TGeoPosArray ); class procedure InsertLightsFromGeoHashArray( const ARLandmarkMatrix: TLandMarkMatrix; const ALandmarkCoords: TArray<Int64> ); end; implementation { TLPC } class procedure TLPC.Gen( const AFullPath: string; const AFileName: string; const ALandmarkCoords: TGeoPosArray ); function GetZones( const ALMPath: string; const AFormatStartPos: Integer; const AFormatIncrement: Integer ): Int64; var i: Integer; d: string; begin Result := 0; i := AFormatStartPos; repeat d := Copy(ALMPath, i + (12 + 1 + 2), 16); if (d = '') then Break; Result := Result or StrToInt64('$' + d); Inc(i, AFormatIncrement); until False; end; function CalcPath( const AVector: THashVector; const AZonesExcluded: UInt64; out RZonesVisited: UInt64 ): string; var ar: TAstarRequest4; begin Result := ''; LoadAStar64(); try FillChar(ar, SizeOf(ar), 0); with ar do begin // Version FromLatitude FromLongitude ToLatitude ToLongitude // ZonesLimit RoadTypeLimit OsmTypeLimit Feature FormatVariant // LenTreshold Timeout Distance Stat // RoadLengthAggregateBufferSize RoadLengthAggregate RoadLengthCount // BufferSize HashString SignsLimit Version := 1; FromLatitude := AVector.PointFrom.Latitude; FromLongitude := AVector.PointFrom.Longitude; ToLatitude := AVector.PointTo.Latitude; ToLongitude := AVector.PointTo.Longitude; ZonesLimit := AZonesExcluded; // исключаемые зоны FormatVariant := Ord(gfLandMark); LenTreshold := 15; Timeout := 900; BufferSize := 1024*1024; HashString := AllocMem(BufferSize); Feature := 0; end; if (AStarCalc4(@ar) = 0) then begin Result := string(AnsiString(ar.HashString)); Delete(Result, 3, 12 + 19); Delete(Result, Length(Result) + (1 - 12 - 19), 12 + 19); RZonesVisited := GetZones(Result, ar.FormatStartPos, ar.FormatIncrement); end; finally FreeMem(ar.HashString); // FreeMem(ar.RoadLengthAggregate); UnloadAStar64(); end; end; function IsBitsNotPresentedInList( ABits: UInt64; const AList: TDictionary<UInt64, Boolean> ): Boolean; var Iter: UInt64; begin for Iter in AList.Keys do begin ABits := ABits and not Iter; end; Result := ABits <> 0; end; procedure InsertNewBitsPackInList( const ABits: UInt64; const AList: TDictionary<UInt64, Boolean> ); var Mask: UInt64; OneBit: UInt64; InsSet: UInt64; Iter: UInt64; AllInserted: Boolean; begin Mask := 1; repeat OneBit := ABits and Mask; if (OneBit <> 0) then begin AllInserted := True; repeat for Iter in AList.Keys do begin if ((OneBit and Iter) <> 0) then Continue; AList.Add(OneBit or Iter, False); AllInserted := False; Break; end; until AllInserted; end; Mask := Mask shl 1; until (Mask = 0); end; var RezStr, RezStr1: string; // TempStr: string; // TempBegin: string; // TempEnd: string; // TempNode: string; // TempType: string; // TempZone: string; lmk, lmki: TLandMarkWayKey; LandMarkMatrix: TLandMarkMatrix; CrossedList: TDictionary<UInt64, Boolean>; CrossedIter: UInt64; AllWaysDone, AllZonesDone: Boolean; procedure WritePath( const AKey: TLandMarkWayKey; const APath: string ); begin if not LandMarkMatrix.ContainsKey(AKey) then LandMarkMatrix.Add(AKey, TLandMarkWay.Create(APath)) else LandMarkMatrix.Items[AKey].GeoHash := APath; end; begin CrossedList := nil; LandMarkMatrix := nil; try CrossedList := TDictionary<UInt64, Boolean>.Create(); LandMarkMatrix := TLandMarkMatrix.Create(AFullPath, AFileName); // // загрузка предыдущего файла // LandMarkMatrix.LoadIndex(); // !!! генерация маяков (-добавление новых, очистка загруженного пути у старых-) !!! InsertLightsFromGeoPosArray(LandMarkMatrix, ALandmarkCoords); // расчёт repeat // пока есть нерассчитанные пути в LandMarkMatrix AllWaysDone := True; for lmk in LandMarkMatrix.Keys do begin // lmk.z всегда 0 (как результат работы InsertLightsFromGeoPosArray) if (LandMarkMatrix.Items[lmk].GeoHash <> '') then Continue; AllWaysDone := False; RezStr := CalcPath(lmk.v, 0{без ограничений по зонам}, lmki.z); if (RezStr = '') then begin // не удалось посчитать путь // просто удалим из списка расчёта LandMarkMatrix.Remove(lmk); Break; end; if (lmki.z = 0) then begin // тривиально = вообще нет зон, по которым мы прошли // записать этот путь WritePath(lmk, RezStr); Break; end; // ... lmki.v := lmk.v; CrossedList.Clear(); InsertNewBitsPackInList(lmki.z, CrossedList); AllZonesDone := True; repeat for CrossedIter in CrossedList.Keys do begin if CrossedList[CrossedIter] then Continue; AllZonesDone := False; CrossedList[CrossedIter] := True; RezStr1 := CalcPath(lmk.v, CrossedIter, lmki.z); if (RezStr1 <> '') then begin WritePath(lmki, RezStr1); if IsBitsNotPresentedInList(lmki.z, CrossedList) then InsertNewBitsPackInList(lmki.z, CrossedList); end; // Break; end; until AllZonesDone; // Break; end; until AllWaysDone; LandMarkMatrix.Save(); finally LandMarkMatrix.Free(); CrossedList.Free(); end; end; class procedure TLPC.InsertLightsFromGeoPosArray( const ARLandmarkMatrix: TLandMarkMatrix; const ALandmarkCoords: TGeoPosArray ); var K: TLandMarkWayKey; I, J: Integer; begin K.z := 0; for I := Low(ALandmarkCoords) to High(ALandmarkCoords) do begin for J := Low(ALandmarkCoords) to High(ALandmarkCoords) do begin if (I = J) then Continue; K.v.HashFrom := TGeoHash.EncodePointBin(ALandmarkCoords[I].Latitude, ALandmarkCoords[I].Longitude); K.v.HashTo := TGeoHash.EncodePointBin(ALandmarkCoords[J].Latitude, ALandmarkCoords[J].Longitude); if not ARLandmarkMatrix.ContainsKey(K) then ARLandmarkMatrix.Add(K, TLandMarkWay.Create('')) else ARLandmarkMatrix.Items[K].Clear(); end; end; end; class procedure TLPC.InsertLightsFromGeoHashArray( const ARLandmarkMatrix: TLandMarkMatrix; const ALandmarkCoords: TArray<Int64> ); var K: TLandMarkWayKey; I, J: Integer; begin K.z := 0; for I := Low(ALandmarkCoords) to High(ALandmarkCoords) do begin for J := Low(ALandmarkCoords) to High(ALandmarkCoords) do begin if (I = J) then Continue; K.v.HashFrom := ALandmarkCoords[I]; K.v.HashTo := ALandmarkCoords[J]; if not ARLandmarkMatrix.ContainsKey(K) then ARLandmarkMatrix.Add(K, TLandMarkWay.Create('')) else ARLandmarkMatrix.Items[K].Clear(); end; end; end; end.
unit Objekt.DHLVersionBase; interface uses SysUtils, Classes, geschaeftskundenversand_api_2; type TDHLVersionBase = class protected fVersionAPI: Version; private fminorRelease: string; fmajorRelease: string; fBuild: string; procedure setmajorRelease(const Value: String); procedure setminorRelease(const Value: String); procedure setBuild(const Value: string); public constructor Create; virtual; destructor Destroy; override; function VersionAPI: Version; property majorRelease: string read fmajorRelease write setmajorRelease; property minorRelease: string read fminorRelease write setminorRelease; property Build: string read fBuild write setBuild; end; implementation { TDHLVersionBase } constructor TDHLVersionBase.Create; begin fVersionAPI := nil; end; destructor TDHLVersionBase.Destroy; begin inherited; end; procedure TDHLVersionBase.setBuild(const Value: string); begin fBuild := Value; if fVersionAPI <> nil then fVersionAPI.Build := Value; end; procedure TDHLVersionBase.setmajorRelease(const Value: String); begin fmajorRelease := Value; if fVersionAPI <> nil then fVersionAPI.majorRelease := Value; end; procedure TDHLVersionBase.setminorRelease(const Value: String); begin fminorRelease := Value; if fVersionAPI <> nil then fVersionAPI.minorRelease := Value; end; function TDHLVersionBase.VersionAPI: Version; begin Result := fVersionAPI; end; end.
unit UserScript; var kFile: IwbFile; // ----------------------------------------------------------------------------- // EVENTS // ----------------------------------------------------------------------------- function Initialize: Integer; begin kFile := FileByName('Fallout4.esm'); end; function Process(e: IInterface): Integer; begin if Signature(e) <> 'COBJ' then exit; FixScrapRecord(e); end; // ----------------------------------------------------------------------------- // FUNCTIONS // ----------------------------------------------------------------------------- // ripped from mteFunctions function FileByName(s: String): IInterface; var i: Integer; begin Result := nil; for i := 0 to FileCount - 1 do begin if GetFileName(FileByIndex(i)) = s then begin Result := FileByIndex(i); break; end; end; end; // ripped from mteFunctions function HexFormID(e: IInterface): String; var s: String; begin s := GetElementEditValues(e, 'Record Header\FormID'); if SameText(Signature(e), '') then Result := '00000000' else Result := Copy(s, Pos('[' + Signature(e) + ':', s) + Length(Signature(e)) + 2, 8); end; // ripped from dubhFunctions function HasString(const asNeedle, asHaystack: String; const abCaseSensitive: Boolean): Boolean; begin if abCaseSensitive then Result := Pos(asNeedle, asHaystack) > 0 else Result := Pos(Lowercase(asNeedle), Lowercase(asHaystack)) > 0; end; // Fix Scrap Record function FixScrapRecord(e: IInterface): Integer; var i: Integer; kComponents, kComponent, kComponentElement, kComponentRecord, kComponentScrap: IInterface; sComponentId, sScrapId: String; begin kComponents := ElementBySignature(e, 'FVPA'); for i := 0 to ElementCount(kComponents) - 1 do begin kComponent := ElementByIndex(kComponents, i); kComponentElement := ElementByIndex(kComponent, 0); kComponentRecord := LinksTo(kComponentElement); if Signature(kComponentRecord) <> 'CMPO' then continue; sComponentId := EditorID(kComponentRecord); if HasString('scrap', sComponentId, False) then continue; sScrapId := sComponentId + '_scrap'; kComponentScrap := MainRecordByEditorID(GroupBySignature(kFile, 'MISC'), sScrapId); SetEditValue(kComponentElement, HexFormID(kComponentScrap)); FixScrapRecord(e); end; end; end.
unit UDSubreports; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, UCrpe32; type TCrpeSubreportsDlg = class(TForm) pnlSubreports: TPanel; lbSubNames: TListBox; GroupBox1: TGroupBox; btnBorder: TButton; btnFormat: TButton; editTop: TEdit; lblTop: TLabel; lblLeft: TLabel; editLeft: TEdit; lblSection: TLabel; editWidth: TEdit; lblWidth: TLabel; lblHeight: TLabel; editHeight: TEdit; cbSection: TComboBox; btnOk: TButton; btnClear: TButton; FontDialog1: TFontDialog; editNLinks: TEdit; lblNLinks: TLabel; cbSubExecute: TCheckBox; rbMain: TRadioButton; rbSub: TRadioButton; imgReport: TImage; OpenDialog1: TOpenDialog; sbFormulaRed: TSpeedButton; sbFormulaBlue: TSpeedButton; GroupBox2: TGroupBox; cbIsExternal: TCheckBox; cbOnDemand: TCheckBox; sbOnDemandCaption: TSpeedButton; lblOnDemandCaption: TLabel; lblPreviewTabCaption: TLabel; sbPreviewTabCaption: TSpeedButton; cbReImportWhenOpening: TCheckBox; rgUnits: TRadioGroup; procedure btnClearClick(Sender: TObject); procedure lbSubNamesClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure UpdateSubreports; procedure btnOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure editSizeEnter(Sender: TObject); procedure editSizeExit(Sender: TObject); procedure cbSectionChange(Sender: TObject); procedure btnBorderClick(Sender: TObject); procedure rbMainClick(Sender: TObject); procedure rbSubClick(Sender: TObject); procedure InitializeControls(OnOff: boolean); procedure btnFormatClick(Sender: TObject); procedure sbOnDemandCaptionClick(Sender: TObject); procedure sbPreviewTabCaptionClick(Sender: TObject); procedure cbSubExecuteClick(Sender: TObject); procedure rgUnitsClick(Sender: TObject); private { Private declarations } public { Public declarations } Cr : TCrpe; SubIndex : integer; SubNameIndex : integer; PrevSize : string; OpenDir : string; end; var CrpeSubreportsDlg: TCrpeSubreportsDlg; bSubreports : boolean; implementation {$R *.DFM} uses UCrpeUtl, UDBorder, UDFormat, UDToolTipEdit; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.FormCreate(Sender: TObject); begin bSubreports := True; LoadFormPos(Self); btnOk.Tag := 1; OpenDir := 'C:\'; SubIndex := 0; SubNameIndex := -1; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.FormShow(Sender: TObject); begin UpdateSubreports; end; {------------------------------------------------------------------------------} { UpdateSubreports } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.UpdateSubreports; var OnOff : boolean; begin SubIndex := 0; SubNameIndex := -1; {Enable/Disable controls} if IsStrEmpty(Cr.ReportName) then OnOff := False else begin OnOff := (Cr.Subreports.Count >= 0); {Get Subreport Index} if OnOff then begin if Cr.Subreports.ItemIndex > -1 then begin SubIndex := Cr.Subreports.ItemIndex; if Cr.Subreports.ItemIndex > 0 then SubNameIndex := Cr.Subreports.ItemIndex - 1; end; end; end; InitializeControls(OnOff); {Update list box} if OnOff = True then begin rbSub.Enabled := Cr.Subreports.Count > 1; {Get Sections from Main Report} Cr.Subreports.ItemIndex := 0; cbSection.Clear; cbSection.Items.AddStrings(Cr.SectionFormat.Names); {Switch back to SubReport} Cr.Subreports.ItemIndex := SubIndex; lbSubNames.Clear; lbSubNames.Items.AddStrings(Cr.Subreports.Names); lbSubNames.ItemIndex := SubNameIndex; if SubIndex = 0 then rbMainClick(Self) else rbSubClick(Self); end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TCheckBox then TCheckBox(Components[i]).Enabled := OnOff; if Components[i] is TRadioGroup then TRadioGroup(Components[i]).Enabled := OnOff; if Components[i] is TRadioButton then TRadioButton(Components[i]).Enabled := OnOff; if Components[i] is TComboBox then begin TComboBox(Components[i]).Color := ColorState(OnOff); TComboBox(Components[i]).Enabled := OnOff; end; if Components[i] is TListBox then begin TListBox(Components[i]).Clear; TListBox(Components[i]).Color := ColorState(OnOff); TListBox(Components[i]).Enabled := OnOff; end; if Components[i] is TEdit then begin TEdit(Components[i]).Text := ''; if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { rbMainClick } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.rbMainClick(Sender: TObject); begin rbMain.Checked := True; SubIndex := 0; {Set VCL to Main Report} Cr.Subreports[SubIndex]; {Disable Subreports controls} rbSub.Checked := False; lbSubNames.Enabled := False; lbSubNames.Color := ColorState(False); cbSubExecute.Enabled := False; cbOnDemand.Checked := False; cbIsExternal.Checked := False; cbReImportWhenOpening.Checked := False; editNLinks.Text := ''; sbOnDemandCaption.Enabled := False; sbPreviewTabCaption.Enabled := False; {Disable Object properties} rgUnits.Enabled := False; btnBorder.Enabled := False; btnFormat.Enabled := False; editTop.Text := ''; editTop.Enabled := False; editTop.Color := ColorState(False); editLeft.Text := ''; editLeft.Enabled := False; editLeft.Color := ColorState(False); editWidth.Text := ''; editWidth.Enabled := False; editWidth.Color := ColorState(False); editHeight.Text := ''; editHeight.Enabled := False; editHeight.Color := ColorState(False); cbSection.ItemIndex := -1; cbSection.Enabled := False; cbSection.Color := ColorState(False); end; {------------------------------------------------------------------------------} { rbSubClick } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.rbSubClick(Sender: TObject); begin rbSub.Checked := True; rbMain.Checked := False; {Enable Subreport controls} lbSubNames.Enabled := True; lbSubNames.Color := ColorState(True); cbSubExecute.Enabled := True; cbSubExecute.Checked := Cr.Subreports.SubExecute; sbOnDemandCaption.Enabled := False; sbPreviewTabCaption.Enabled := False; {set the List Box to the first item} if SubNameIndex = -1 then SubNameIndex := 0; lbSubNames.SetFocus; lbSubNames.ItemIndex := SubNameIndex; lbSubNamesClick(Self); end; {------------------------------------------------------------------------------} { lbSubNamesClick } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.lbSubNamesClick(Sender: TObject); var OnOff : Boolean; begin rbSub.Checked := True; SubIndex := lbSubNames.ItemIndex + 1; SubNameIndex := lbSubNames.ItemIndex; {Enable Sub properties} cbIsExternal.Checked := Cr.Subreports[SubIndex].IsExternal; cbOnDemand.Enabled := Cr.Subreports.Item.OnDemand; cbReImportWhenOpening.Checked := Cr.Subreports.Item.ReImportWhenOpening; editNLinks.Text := IntToStr(Cr.Subreports.Item.NLinks); {OnDemandCaption} sbOnDemandCaption.Enabled := True; if IsStrEmpty(Cr.Subreports.Item.OnDemandCaption) then begin if sbOnDemandCaption.Glyph <> sbFormulaBlue.Glyph then sbOnDemandCaption.Glyph := sbFormulaBlue.Glyph; end else begin if sbOnDemandCaption.Glyph <> sbFormulaRed.Glyph then sbOnDemandCaption.Glyph := sbFormulaRed.Glyph; end; {PreviewTabCaption} sbPreviewTabCaption.Enabled := True; if IsStrEmpty(Cr.Subreports.Item.PreviewTabCaption) then begin if sbPreviewTabCaption.Glyph <> sbFormulaBlue.Glyph then sbPreviewTabCaption.Glyph := sbFormulaBlue.Glyph; end else begin if sbPreviewTabCaption.Glyph <> sbFormulaRed.Glyph then sbPreviewTabCaption.Glyph := sbFormulaRed.Glyph; end; {Update Object properties} OnOff := (Cr.Subreports.Item.Handle <> 0); rgUnits.Enabled := OnOff; btnBorder.Enabled := OnOff; btnFormat.Enabled := OnOff; editTop.Enabled := OnOff; editTop.Color := ColorState(OnOff); editLeft.Enabled := OnOff; editLeft.Color := ColorState(OnOff); editWidth.Enabled := OnOff; editWidth.Color := ColorState(OnOff); editHeight.Enabled := OnOff; editHeight.Color := ColorState(OnOff); cbSection.Enabled := OnOff; cbSection.Color := ColorState(OnOff); if OnOff then cbSection.ItemIndex := cbSection.Items.IndexOf(Cr.Subreports.Item.Section); rgUnitsClick(Self); lbSubNames.SetFocus; end; {------------------------------------------------------------------------------} { sbOnDemandCaptionClick } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.sbOnDemandCaptionClick(Sender: TObject); var s : string; begin CrpeToolTipEditDlg := TCrpeToolTipEditDlg.Create(Application); s := Cr.Subreports.Item.OnDemandCaption; {Display the edit dialog} CrpeToolTipEditDlg.pTip := Addr(s); CrpeToolTipEditDlg.Caption := 'OnDemandCaption'; CrpeToolTipEditDlg.ShowModal; Cr.Subreports.Item.OnDemandCaption := s; if IsStrEmpty(s) then begin if sbOnDemandCaption.Glyph <> sbFormulaBlue.Glyph then sbOnDemandCaption.Glyph := sbFormulaBlue.Glyph; end else begin if sbOnDemandCaption.Glyph <> sbFormulaRed.Glyph then sbOnDemandCaption.Glyph := sbFormulaRed.Glyph; end; end; {------------------------------------------------------------------------------} { sbPreviewTabCaptionClick } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.sbPreviewTabCaptionClick(Sender: TObject); var s : string; begin CrpeToolTipEditDlg := TCrpeToolTipEditDlg.Create(Application); s := Cr.Subreports.Item.PreviewTabCaption; {Display the edit dialog} CrpeToolTipEditDlg.pTip := Addr(s); CrpeToolTipEditDlg.Caption := 'PreviewTabCaption'; CrpeToolTipEditDlg.ShowModal; Cr.Subreports.Item.PreviewTabCaption := s; if IsStrEmpty(s) then begin if sbPreviewTabCaption.Glyph <> sbFormulaBlue.Glyph then sbPreviewTabCaption.Glyph := sbFormulaBlue.Glyph; end else begin if sbPreviewTabCaption.Glyph <> sbFormulaRed.Glyph then sbPreviewTabCaption.Glyph := sbFormulaRed.Glyph; end; end; {------------------------------------------------------------------------------} { cbSubExecuteClick } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.cbSubExecuteClick(Sender: TObject); begin Cr.Subreports.SubExecute := cbSubExecute.Checked; end; {------------------------------------------------------------------------------} { editSizeEnter } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.editSizeEnter(Sender: TObject); begin if Sender is TEdit then PrevSize := TEdit(Sender).Text; end; {------------------------------------------------------------------------------} { editSizeExit } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.editSizeExit(Sender: TObject); begin if rgUnits.ItemIndex = 0 then {inches} begin if not IsFloating(TEdit(Sender).Text) then TEdit(Sender).Text := PrevSize else begin if TEdit(Sender).Name = 'editTop' then Cr.Subreports.Item.Top := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editLeft' then Cr.Subreports.Item.Left := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editWidth' then Cr.Subreports.Item.Width := InchesStrToTwips(TEdit(Sender).Text); if TEdit(Sender).Name = 'editHeight' then Cr.Subreports.Item.Height := InchesStrToTwips(TEdit(Sender).Text); UpdateSubreports; {this will truncate any decimals beyond 3 places} end; end else {twips} begin if not IsNumeric(TEdit(Sender).Text) then TEdit(Sender).Text := PrevSize else begin if TEdit(Sender).Name = 'editTop' then Cr.Subreports.Item.Top := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editLeft' then Cr.Subreports.Item.Left := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editWidth' then Cr.Subreports.Item.Width := StrToInt(TEdit(Sender).Text); if TEdit(Sender).Name = 'editHeight' then Cr.Subreports.Item.Height := StrToInt(TEdit(Sender).Text); end; end; end; {------------------------------------------------------------------------------} { cbSectionChange } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.cbSectionChange(Sender: TObject); begin Cr.Subreports.Item.Section := cbSection.Items[cbSection.ItemIndex]; end; {------------------------------------------------------------------------------} { rgUnitsClick } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.rgUnitsClick(Sender: TObject); begin if rgUnits.ItemIndex = 0 then {inches} begin editTop.Text := TwipsToInchesStr(Cr.Subreports[SubIndex].Top); editLeft.Text := TwipsToInchesStr(Cr.Subreports[SubIndex].Left); editWidth.Text := TwipsToInchesStr(Cr.Subreports[SubIndex].Width); editHeight.Text := TwipsToInchesStr(Cr.Subreports[SubIndex].Height); end else {twips} begin editTop.Text := IntToStr(Cr.Subreports[SubIndex].Top); editLeft.Text := IntToStr(Cr.Subreports[SubIndex].Left); editWidth.Text := IntToStr(Cr.Subreports[SubIndex].Width); editHeight.Text := IntToStr(Cr.Subreports[SubIndex].Height); end; end; {------------------------------------------------------------------------------} { btnBorderClick } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.btnBorderClick(Sender: TObject); begin CrpeBorderDlg := TCrpeBorderDlg.Create(Application); CrpeBorderDlg.Border := Cr.Subreports.Item.Border; CrpeBorderDlg.ShowModal; end; {------------------------------------------------------------------------------} { btnFormatClick } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.btnFormatClick(Sender: TObject); begin CrpeFormatDlg := TCrpeFormatDlg.Create(Application); CrpeFormatDlg.Format := Cr.Subreports.Item.Format; CrpeFormatDlg.ShowModal; end; {------------------------------------------------------------------------------} { btnClearClick } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.btnClearClick(Sender: TObject); begin Cr.Subreports.Clear; UpdateSubreports; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.btnOkClick(Sender: TObject); begin rgUnits.ItemIndex := 1; {change to twips to avoid the Update call} if (not IsStrEmpty(Cr.ReportName)) and (SubNameIndex > -1) then begin editSizeExit(editTop); editSizeExit(editLeft); editSizeExit(editWidth); editSizeExit(editHeight); end; SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeSubreportsDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bSubreports := False; Release; end; end.
unit DAW.Adb; interface uses DAW.Model.Device.New, DAW.Utils.DosCMD, DAW.Adb.Parser; type TdawAdb = class private const TCPIP_PORT = '5555'; private FCommandLine: TDosCMD; FAdbParser: TdawAdbParser; function DisconnectDevice(ADeviceIp: string): Boolean; procedure enableTCPCommand(); function checkTCPCommandExecuted: Boolean; function connectDeviceByIP(deviceIp: string): Boolean; function connectDevice(ADevice: TdawDevice): Boolean; public procedure Upgrade(ADevice: TdawDevice); constructor Create(ACommandLine: TDosCMD; AAdbParser: TdawAdbParser); function IsInstalled: Boolean; function getDevicesConnectedByUSB: TArray<TdawDevice>; function connectDevices(ADevices: TArray<TdawDevice>): TArray<TdawDevice>; function disconnectDevices(ADevices: TArray<TdawDevice>): TArray<TdawDevice>; function getDeviceIp(ADevice: TdawDevice): string; end; implementation uses System.IOUtils, System.SysUtils, DAW.Tools; { TdawAdb } function TdawAdb.checkTCPCommandExecuted: Boolean; var getPropCommand: string; getPropOutput: string; adbTcpPort: string; begin getPropCommand := 'adb shell getprop | grep adb'; getPropOutput := FCommandLine.Execute(getPropCommand); adbTcpPort := FAdbParser.parseAdbServiceTcpPort(getPropOutput); Result := TCPIP_PORT.equals(adbTcpPort); end; function TdawAdb.connectDeviceByIP(deviceIp: string): Boolean; var enableTCPCommand: string; connectDeviceCommand: string; connectOutput: string; begin enableTCPCommand := 'adb tcpip 5555'; FCommandLine.Execute(enableTCPCommand); connectDeviceCommand := 'adb connect ' + deviceIp; connectOutput := FCommandLine.Execute(connectDeviceCommand); Result := connectOutput.contains('connected'); end; function TdawAdb.connectDevice(ADevice: TdawDevice): Boolean; begin if ADevice.IP.IsEmpty then ADevice.IP := getDeviceIp(ADevice); if ADevice.IP.isEmpty() then Result := False else begin ADevice.ID := ADevice.IP; Result := connectDeviceByIP(ADevice.IP); end; end; function TdawAdb.connectDevices(ADevices: TArray<TdawDevice>): TArray<TdawDevice>; var LDevice: TdawDevice; LConnected: Boolean; I: Integer; begin Result := ADevices; for I := Low(Result) to High(Result) do begin LConnected := connectDevice(Result[I]); Result[I].IsConnected := (LConnected); end; end; constructor TdawAdb.Create(ACommandLine: TDosCMD; AAdbParser: TdawAdbParser); begin FCommandLine := ACommandLine; FAdbParser := AAdbParser; end; function TdawAdb.DisconnectDevice(ADeviceIp: string): Boolean; var connectDeviceCommand: string; begin enableTCPCommand(); connectDeviceCommand := 'adb disconnect ' + ADeviceIp; Result := FCommandLine.Execute(connectDeviceCommand).isEmpty(); end; function TdawAdb.disconnectDevices(ADevices: TArray<TdawDevice>): TArray<TdawDevice>; var LDevice: TdawDevice; LDisconnected: Boolean; begin for LDevice in ADevices do begin LDisconnected := DisconnectDevice(LDevice.IP); LDevice.IsConnected := LDisconnected; end; Result := ADevices; end; procedure TdawAdb.enableTCPCommand; var LEnableTCPCommand: string; begin if not checkTCPCommandExecuted() then begin LEnableTCPCommand := ('adb tcpip ' + TCPIP_PORT); FCommandLine.Execute(LEnableTCPCommand); end; end; function TdawAdb.getDeviceIp(ADevice: TdawDevice): string; var getDeviceIpCommand: string; ipInfoOutput: string; begin getDeviceIpCommand := 'adb -s ' + ADevice.ID + ' shell ip -f inet addr show wlan0'; ipInfoOutput := FCommandLine.Execute(getDeviceIpCommand); Result := FAdbParser.parseGetDeviceIp(ipInfoOutput); end; function TdawAdb.getDevicesConnectedByUSB: TArray<TdawDevice>; var adbDevicesOutput: string; begin adbDevicesOutput := FCommandLine.Execute('adb devices -l'); Result := FAdbParser.parseGetDevicesOutput(adbDevicesOutput); end; function TdawAdb.IsInstalled: Boolean; begin Result := TFile.Exists(TDawTools.AdbExe); end; procedure TdawAdb.Upgrade(ADevice: TdawDevice); begin ADevice.IP := getDeviceIp(ADevice); end; end.
PROGRAM RevisedMoo (Input,Output, SumFile); {**************************************************************************** Author: Scott Janousek Due: Mon May 10, 1993 Instructor: Jeff Clouse Section: 1 MWF 10:10 Programming Assignment 6 Student ID: 4361106 The Story: Ronald, the manager of the Springfield Cow Vacation Spa, has been doing a lousy job. His boss thinks that cows are being turned away unnecess- arily and the billling has been questionable. Therefore, she hires you to this is a Pascal program that simulates the actions of Ronald. Program Desciption: This program maintains and controls business of a small Cow Vacation Spa. Every week, cows come to the these Stables to rest and relax, etc. The program allows the user to keep track of bookings at this Cow Spa. It also does weekly updates and a budget of profit made by the Spa. Input: How many Cows that check into the Spa (NumOfCows) The number of Weeks reserved for Stall (Weeks) The Breed of the Cow renting the Stall (Breed) Output: Weekly Report of Spa Activity ----------------------------- How many Departures occured in a week (Week) How many Empty Stalls there are (NumOfEmptyStalls) How much the Billing was for the Cow's Stay A Cows Breed and which Stall it Occupies TextFile which contains summary Info (SumFile) Summary ------- Profit made from Stalls (Profit) Number of EmptyStalls Projected Income (Income) OptionalSummaryFile (SumFile) Algorithm : (See my Program Design Document for Details) ****************************************************************************} CONST MaxLength = 13; {* Max Length Cow String *} NumofStalls = 10; {* Max Num of Stalls *} NumOfWeeks = 8; {* Num Weeks to Process *} Discharge = ' - (Discharging Cows From Spa) -'; Accepting = ' - (Accepting New Cows To the Spa) -'; NoDepartures = ' - (No Other Departures) -'; Cents = '.00'; BreedScheme = '(1-Ayrshire (2-Brown (3-Devon (4-Dexter (5-Jersey (6-Kerry'; TYPE BreedType = (Ayrshire, BrownSwiss, MilkingDevon, Dexter, Jersey, Kerry); CowString = packed array [1..MaxLength] OF char; Stalls = 1 .. NumOfStalls; {* Total Stalls in Spa *} Reservation = Integer; {* Weeks for a Cow *} PriceType = Integer; {* Price of Stall for Week *} CowType = RECORD {* Record for Cow Stall *} Breed : BreedType; {* Breed of Cow *} Week : Reservation; {* Weeks Cow will Stay *} Arrive : Reservation; {* Week of Cows Arrival *} Price : PriceType; {* Price of Stay in Stall *} Status : Boolean; {* Keep Track Empty Stall *} END; CowSpaType = ARRAY [Stalls] of CowType; {* Array of Cow Stalls *} VAR Week : Reservation; {* Weeks for CowSpa *} CowSpa : CowSpaType; {* Cow Stall Type *} Profit : Integer; {* Profit Made by Spa *} SumFile : Text; {* Summary Text File *} {***************************************************************************} PROCEDURE WeekHeading (Week : Integer); {* This Procedure Prints the Header for each Week *} BEGIN {** of Print the Current Week Heading **} Writeln; Writeln (' [ WEEK ', Week:1, ' ]'); Writeln ('----------------------------------------------'); Writeln; END; {** of Print the Current Week Heading **} {***************************************************************************} PROCEDURE WeekEnding (Week : Integer); {* This Procedure Prints the Header for each Ending Week *} BEGIN {** of Print the Header for Week Ending **} Writeln; Writeln (' [ FOR THE WEEK ', Week:1, ' ENDING ]'); Writeln ('----------------------------------------------'); Writeln; END; {** of Print the Header for Week Ending **} {***************************************************************************} PROCEDURE SummaryHeading; {* This Procedure Prints the Header for the Summary *} BEGIN {** of Print the Header for Summary **} Writeln; Writeln (' [ SUMMARY FOR THE COW SPA ]'); Writeln ('-----------------------------------------------'); Writeln; END; {** of Print the Header for Summary **} {***************************************************************************} PROCEDURE InitalizetheStable (VAR CowSpa : CowSpaType); {* This procedure initalizes the Stable and all the Stalls within to begin. An array is implemented here to keep track of which stalls are avaliable and those that new cows can rent for their weeks vacation. A boolean is used to indicate whether a stall is vacant or occupied. Profit is initalized to Zero because no money has been made from the Cow Spa yet. *} VAR Stall : integer; BEGIN {**** of Open all the Stalls ****} Writeln ('STABLE has been created.'); Profit := 0; {* No Profit Made *} FOR Stall := 1 TO NumofStalls DO {* For All Stalls *} BEGIN {*** Wipe All the Stalls ***} WITH CowSpa [Stall] DO BEGIN {** Initialize Whole Record **} Breed := MilkingDevon; {* Set to Default *} Price := 0; {* Set to Zero *} Arrive := 0; {* Not Arrived *} Week := 0; {* No Weeks *} Status := FALSE; {* No Cow in Stal *} END {** Initalize Whole Record **} END; {*** Wipe All the Stalls ***} END; {**** of Open all the Stalls *****} {***************************************************************************} PROCEDURE StallNowEmpty (VAR CowSpa : CowSpaType; Stall : Integer); {* This Procedure sets a Stall to Empty once a Cow has left *} BEGIN {** of Stall is Now Empty **} CowSpa [Stall].Status := FALSE; {* Sets to Empty Stall *} END; {** of Stall is Now Empty **} {***************************************************************************} PROCEDURE StallNowOccupied (VAR CowSpa : CowSpaType; Stall : Integer); {* This Procedure sets a Stall to Occupied for an Arriving Cow *} BEGIN {** of Stall is Now Occupied **} CowSpa [Stall].Status := TRUE; {* Sets to Occupied Stall *} END; {** of Stall is Now Occupied **} {***************************************************************************} PROCEDURE SetBreed (CowSpa : CowSpaType; Stall : Integer; VAR CowBreed : BreedType); {* Sets a Cows Breed for use in a few places in the Program *} BEGIN {** of Set Breed **} CowBreed := CowSpa [Stall].Breed; {* Sets to Vacant Stall *} END; {** of Set Breed **} {***************************************************************************} PROCEDURE FindEmptyStall (VAR OpenStall : integer; VAR FoundEmpty : Boolean); {* This Procedure will try to Find an Empty Stall within the Cow Spa and then return the Location of this place in the Array. If no Empty Stall can be found then FindEmptyStall returns FoundEmpty to be FALSE and no Cows may be accepted for that particular week. *} BEGIN {** of EmptyStall **} OpenStall := 1; {* Set to beginning *} FoundEmpty := FALSE; {* No Stall Found yet *} WHILE (NOT FoundEmpty) AND (OpenStall <= NumOfStalls) DO BEGIN {* Do the Search *} IF CowSpa [OpenStall].Status = FALSE THEN FoundEmpty := TRUE ELSE OpenStall := OpenStall + 1; END; {* Do the Search *} END; {** of EmptyStall **} {***************************************************************************} FUNCTION NumOfEmptyStalls : Integer; {* This Function will compute how many empty stalls there are in the Spa. Each Stall is checked whether it is occupied or vacant (Status) and then NumofEmptyStalls returns the count of Stalls. Zero indicates none Empty. *} VAR Stall, CountEmpty : integer; BEGIN {** of NumOfEmpty Stalls **} CountEmpty := 0; {* Count set to Zero *} FOR Stall := 1 TO NumOfStalls DO IF CowSpa [Stall].Status = FALSE THEN CountEmpty := CountEmpty + 1; NumOfEmptyStalls := CountEmpty; {* Set NumOfEmptyStalls *} END; {** of NumOfEmpty Stalls **} {***************************************************************************} FUNCTION NameOfCow (CowBreed : BreedType) : CowString; {* Prints out the enumerated Type of the Breed a Cow *} BEGIN {** of Print Cows Breed **} CASE CowBreed OF Ayrshire : NameOfCow := 'AYRSHIRE'; BrownSwiss : NameOfCow := 'BROWNSWISS'; MilkingDevon : NameOfCow := 'MILKING DEVON'; Dexter : NameOfCow := 'DEXTER'; Jersey : NameOfCow := 'JERSEY'; Kerry : NameOfCow := 'KERRY'; END; END; {** of Print Cows Breed **} {***************************************************************************} PROCEDURE UpdateCowDepartures (VAR CowSpa : CowSpaType; Week : integer); {* This procedure creates a list of all the Cows currently in the Spa, and information about their Departure Weeks. At the end of a Week, the number of empty stalls are given, and which Stalls still have Cows. This Updates the Spa for the User to Keep Track of Bookings. *} VAR Stall : integer; {* Number of Stalls *} CowBreed : BreedType; {* What Breed Cow is *} PROCEDURE CowDepartures (Stall : Integer); BEGIN {** of Cow Departure **} SetBreed (CowSpa, Stall, CowBreed); {* Set Correct Breed *} IF CowSpa [Stall].Status = TRUE THEN BEGIN {* Print Departure *} Write ('STALL: ',Stall:2, ' ',NameOfCow (CowBreed), ' will depart on WEEK '); Writeln (CowSpa [Stall].Week:1); {* Write the Week *} END; {* Print Departure *} END; {** of Cow Departure **} BEGIN {** of Update Cow Departures **} WeekEnding (Week); Writeln (NumOfEmptyStalls:15, ' EMPTY STALLS'); Writeln; FOR Stall := 1 TO NumOfStalls DO CowDepartures (Stall); END; {** of Update Cow Departures **} {***************************************************************************} PROCEDURE DischargeCows (VAR CowSpa : CowSpaType); {* This Procedure Searches all the Cows and Determines if a Cow has to Depart for the Week. Once a Cow leaves the money collected goes into Profit for the Vacation Spa and the Stall becomes Empty. Otherwise the Program continues for the remaining Weeks, trying to Book arriving Cows. *} VAR Stall : integer; {* Number of Stalls *} CowBreed : BreedType; {* Breed of Cow *} PROCEDURE ACowIsLeaving (VAR CowSpa : CowSpaType; Stall : Integer); VAR WeekStayed : integer; {* Number of Weeks Stay *} BEGIN {** of A Cow Is Leaving **} SetBreed (CowSpa, Stall, CowBreed); {* Set Correct Breed *} IF (CowSpa [Stall].Status = TRUE) {* If Stall and Week Then *} AND (CowSpa [Stall].Week = Week) THEN BEGIN {** Bill the Cow **} Writeln; Writeln ('STALL: ',Stall:2, ' ',NameOfCow (CowBreed), ' is departing'); WeekStayed := CowSpa [Stall].Week - CowSpa [Stall].Arrive; Write ('------ Billing for ', WeekStayed:1, ' Weeks Stayed is $ '); Writeln (CowSpa [Stall].Price:1,'.00'); {* Write the Stall Price *} Profit := Profit + CowSpa [Stall].Price; {* Compute the Profit *} StallNowEmpty (CowSpa, Stall); {* Set Stall to Empty *} Writeln; END {** Bill the Cow **} END; {** of A Cow Is Leaving **} BEGIN {**** Discharge Cow ****} Writeln; Writeln (Discharge); FOR Stall := 1 TO NumOfStalls DO ACowIsLeaving (CowSpa, Stall); Writeln; Writeln (NoDepartures); END; {**** Discharge Cow ****} {***************************************************************************} PROCEDURE Summary (Profit : Integer); {* Figures the profit of the Cow Spa for the 8 Weeks and gives a Projected income for the Cows still in the Stalls. Revenue returns the Total Income. *} VAR OutputOption : Integer; FUNCTION Revenue (CowSpa : CowSpaType) : Integer; VAR Stall, Projected : Integer; {* Computes the Projected Revenue for cows still in Stable *} BEGIN {** of Projected Revenue **} Projected := 0; {* Zero Projected *} FOR Stall := 1 TO NumOfStalls DO {* Num of Stalls *} IF CowSpa [Stall].Status = TRUE THEN {* If Occupied *} Projected := CowSpa [Stall].Price + Projected; {* Project Income *} Revenue := Projected; {* Assign Revenue *} END; {** of Projected Revenue **} PROCEDURE WriteSummaryToFile (VAR SumFile : Text); {* Writes summary information to a Text File *} BEGIN {*** Write the summary to file ***} Rewrite (SumFile); Writeln (SumFile); Writeln (SumFile, ' - Summary for Stables (8 weeks) - '); Writeln (SumFile); Writeln (SumFile, 'Stables made = $', profit:1,Cents); Writeln (SumFile, 'Empty Stalls left = ', NumOfEmptyStalls:1); Writeln (SumFile, 'Projected Money = $', Revenue (CowSpa):1, Cents); Writeln (SumFile); Writeln; Writeln ('Summary File has been created.'); Writeln; END; {*** write the summary to file ***} BEGIN {** of Print out the Summary **} SummaryHeading; {* Write the Summary Header *} Writeln ('Do wish to Output to ( 1 Screen )'); Writeln (' ( 2 Write to File )'); Writeln; Write ('Option: (1/2) => '); Readln (OutputOption); Writeln; IF OutputOption = 2 THEN WriteSummaryToFile (SumFile) ELSE BEGIN {*** Write the Output to Screen for User ***} Writeln (chr(27), '[2J'); Writeln (' - Summary for Stables (8 weeks) -'); Writeln; Writeln ('Overall, the Cow Stables made $', profit:1,Cents); Writeln ('There are ', NumOfEmptyStalls:1, ' Empty Stalls.'); Writeln ('Projected Revenue for Cow Spa is $ ', Revenue (CowSpa):1,Cents); Writeln; END; {*** Write the Output to Screen for User ***} END; {** of Print out the Summary **} {***************************************************************************} PROCEDURE GiveACowStall (VAR CowSpa : CowSpaType); VAR Stall, OpenStall, {* Which Stall is Empty *} NumOfCows, {* Number Specied Cows *} CowNum, {* Number Current Cow *} WeekStay : Integer; {* Total Weeks to Stay *} FoundEmpty, {* Stall Found Empty *} GotoNextWeek : Boolean; {* Check for more Cows *} MoreCows : Char; {* Read cow character *} {* Rents a Stall to a Cow if one is Avaliable. The Search for an Open Stall is done by Implementing a FindEmptyStall Procedure. If none can be found then the Cow(s) must be turned away, otherwise the Spa takes as many as it can. All Information about a Cow is done through the nested Procedure RecordCowReservation. *} FUNCTION PriceofStay (CowBreed : BreedType; WeekStay : integer) : Integer; {* Calculate the Price of the Stall for the Number of Weeks the Cow Stayed. Each Breed has a specified Value for the charge of Stay. *} BEGIN {** Compute Price Of Stay **} CASE CowBreed OF Ayrshire : PriceOfStay := 100 * WeekStay; BrownSwiss : PriceOfStay := 100 * WeekStay; MilkingDevon : PriceOfStay := 100 * WeekStay; Dexter : PriceOfStay := 150 * WeekStay; Jersey : PriceOfStay := 200 * WeekStay; Kerry : PriceOfStay := 1000 * WeekStay; END; END; {** Compute Price Of Stay **} PROCEDURE RecordCowReservation (VAR CowSpa : CowSpaType; Stall : Integer); {* Records Information about a Cow, such as Length of Stay and Breed *} VAR CowBreed : BreedType; BreedCh : Char; BEGIN {** of Cow Breed and Weeks Stay **} Writeln; Writeln ('Of What Breed is this Cow #', CowNum:1); Writeln; Writeln (BreedScheme); Writeln; Write ('= Breed (1 to 6) = Type # ==> '); Readln (Breedch); IF BreedCh IN ['1'..'6'] THEN BEGIN CASE Breedch OF '1': CowBreed := Ayrshire; '2': CowBreed := BrownSwiss; '3': CowBreed := MilkingDevon; '4': CowBreed := Dexter; '5': CowBreed := Jersey; '6': CowBreed := Kerry; END; END ELSE BEGIN {* Assume Cow to be a Devon *} Writeln; Writeln (chr(7),'Not a VALID Cow Breed, Milking Devon Assumed.'); CowBreed := MilkingDevon; END; {* Assume Cow to be a Devon *} Writeln; Writeln; Write ('How many WEEKS the ', NameOfCow (CowBreed),' Cow will = STAY ==> '); Readln (WeekStay); Writeln; Writeln; Writeln ('---- ',NameOfCow (CowBreed), ' Cow staying in stall #', Stall:1); Writeln; WeekStay := WeekStay + Week; {* Figure Number of Weeks *} {* Below the information for Cow is Saved into the Record *} WITH CowSpa [Stall] DO BEGIN Price := PriceOfStay (CowBreed, WeekStay); {* Compute the Price *} Arrive := Week; {* Record Arrival Time *} Week := WeekStay; {* Record Stay in Weeks *} Breed := CowBreed; {* Record the Cows Breed *} END; StallNowOccupied (CowSpa, Stall); {* Stall has Cow *} END; {** of Cow Breed and Weeks Stay **} BEGIN {** of Rent Cow Stall **} REPEAT GotoNextWeek := FALSE; Writeln; Writeln (Accepting); Writeln; Write ('How Many Total Cows for == WEEK', Week:2,' ==> '); Readln (NumOfCows); Writeln; IF (NumOfEmptyStalls < NumOfCows) THEN Writeln ('We can ONLY Accept ', NumOfEmptyStalls:1, ' Cows this Week.'); IF (NumOfEmptyStalls = 0) THEN BEGIN Writeln (chr(7), 'Sorry, We are Booked Up. No NEW Cows.'); GotoNextWeek := TRUE; END ELSE BEGIN {*** Rent a Cow a Stall ***} FOR Stall := 1 TO NumOfCows DO BEGIN {** of Search for a Stall and Book for Cow **} CowNum := Stall; FindEmptyStall (OpenStall, FoundEmpty); IF FoundEmpty = TRUE THEN RecordCowReservation (CowSpa, OpenStall) END; {** of Search for a Stall and Book for Cow **} END; {*** Rent a Cow Stall ***} IF NOT (NumOfCows = 0) AND (NumOfEmptyStalls <> 0) THEN BEGIN write ('Are you sure you don''t want to accept more cows? (Y/N): '); readln (MoreCows); writeln; END; IF NOT (MoreCows IN ['N', 'n']) THEN GotoNextWeek := TRUE; UNTIL GotoNextWeek = TRUE; END; {*** of Rent Cow Stall ***} {**************************************************************************} BEGIN {****** Main Program ******} {**************************} writeln (chr(27), '[2J'); {* Clear the Screen *} Writeln ('Welcome to Old McDonalds'' Farm Program'); Writeln; InitalizetheStable (CowSpa); {* Initialize the Stables *} FOR week := 1 TO NumOfWeeks DO {* Process for Eight Weeks *} BEGIN WeekHeading (Week); {* Print the Current Week *} DischargeCows(CowSpa); {* Discharge Cows from Spa *} GiveACowStall (CowSpa); {* Give Cow a Stall in Spa *} UpDateCowDepartures (CowSpa, Week); {* Update Departures for Week *} END; Summary (Profit); {* Print Statistics for Spa *} Writeln ('Hope you have a nice day,'); Writeln ('and Remember "Milk does the Body Good."'); END. {****** Main Program ******} {**************************}
unit Unit3; interface type TSession = class private SessionState : Boolean; RecvCallState : Boolean; HoldState : Boolean; ConferenceState : Boolean; SessionID : Integer; public function GetSessionID: Integer; function GetSessionState: Boolean; function GetRecvCallState: Boolean; function GetHoldState: Boolean; function GetConferenceState: Boolean; procedure SetSessionID(Value: Integer); procedure SetSessionState(Value: Boolean); procedure SetHoldState(Value: Boolean); procedure SetRecvCallState(Value: Boolean); procedure SetConferenceState(Value: Boolean); procedure Reset(); end; implementation { TClassData } function TSession.GetSessionID: Integer; begin Result := SessionID; end; function TSession.GetSessionState: Boolean; begin Result := SessionState; end; function TSession.GetRecvCallState: Boolean; begin Result := RecvCallState; end; function TSession.GetHoldState: Boolean; begin Result := HoldState; end; function TSession.GetConferenceState: Boolean; begin Result := ConferenceState; end; procedure TSession.SetSessionID(Value: Integer); begin SessionID := Value; end; procedure TSession.SetHoldState(Value: Boolean); begin HoldState := Value; end; procedure TSession.SetSessionState(Value: Boolean); begin SessionState := Value; end; procedure TSession.SetRecvCallState(Value: Boolean); begin RecvCallState := Value; end; procedure TSession.SetConferenceState(Value: Boolean); begin ConferenceState := Value; end; procedure TSession.Reset(); begin SessionID := 0; HoldState := False; SessionState := False; RecvCallState := False; ConferenceState := False; end; end.
unit ibSHDMLExporter; interface uses SysUtils, Classes, Dialogs, ExtCtrls, SHDesignIntf, ibSHDesignIntf, ibSHTool; type TibSHDMLExporter = class(TibBTTool, IibSHDMLExporter, IibSHBranch, IfbSHBranch) private FData: IibSHData; FOutput: string; FMode: string; FTablesForDumping: TStringList; FActive: Boolean; FExportAs: string; FHeader: Boolean; FPassword: Boolean; FCommitAfter: Integer; FCommitEachTable: Boolean; FDateFormat: string; FTimeFormat: string; FUseDateTimeANSIPrefix: Boolean; FNonPrintChar2Space: Boolean; FUseExecuteBlock: Boolean; protected { IibSHDMLExporter } function GetData: IibSHData; procedure SetData(Value: IibSHData); function GetMode: string; procedure SetMode(Value: string); function GetTablesForDumping: TStrings; procedure SetTablesForDumping(Value: TStrings); function GetActive: Boolean; procedure SetActive(Value: Boolean); function GetOutput: string; procedure SetOutput(Value: string); function GetStatementType: string; procedure SetStatementType(Value: string); function GetHeader: Boolean; procedure SetHeader(Value: Boolean); function GetPassword: Boolean; procedure SetPassword(Value: Boolean); function GetCommitAfter: Integer; procedure SetCommitAfter(Value: Integer); function GetCommitEachTable: Boolean; procedure SetCommitEachTable(Value: Boolean); function GetDateFormat: string; procedure SetDateFormat(Value: string); function GetTimeFormat: string; procedure SetTimeFormat(Value: string); function GetUseDateTimeANSIPrefix: Boolean; procedure SetUseDateTimeANSIPrefix(Value: Boolean); function GetNonPrintChar2Space: Boolean; procedure SetNonPrintChar2Space(Value: Boolean); function GetUseExecuteBlock:boolean; procedure SetUseExecuteBlock(Value:boolean); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; property Mode: string read GetMode write SetMode; published property StatementType: string read GetStatementType write SetStatementType; property Header: Boolean read GetHeader write SetHeader; property Password: Boolean read GetPassword write SetPassword; property CommitAfter: Integer read GetCommitAfter write SetCommitAfter; property CommitEachTable: Boolean read GetCommitEachTable write SetCommitEachTable; property DateFormat: string read GetDateFormat write SetDateFormat; property TimeFormat: string read GetTimeFormat write SetTimeFormat; property UseDateTimeANSIPrefix: Boolean read GetUseDateTimeANSIPrefix write SetUseDateTimeANSIPrefix; property NonPrintChar2Space: Boolean read GetNonPrintChar2Space write SetNonPrintChar2Space; property Output: string read GetOutput write SetOutput; property UseExecuteBlock:boolean read GetUseExecuteBlock write SetUseExecuteBlock; end; TibSHDMLExporterFactory = class(TibBTToolFactory, IibSHDMLExporterFactory) private FData: IibSHData; FMode: string; FTablesForDumping: TStringList; FSuspendedTimer: TTimer; FComponentForSuspendedDestroy: TSHComponent; procedure SuspendedTimerEvent(Sender: TObject); protected {IibSHDMLExporterFactory} function GetData: IibSHData; procedure SetData(Value: IibSHData); function GetMode: string; procedure SetMode(Value: string); function GetTablesForDumping: TStrings; procedure SetTablesForDumping(Value: TStrings); procedure SuspendedDestroyComponent(AComponent: TSHComponent); procedure DoBeforeChangeNotification(var ACallString: string; AComponent: TSHComponent); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function SupportComponent(const AClassIID: TGUID): Boolean; override; end; procedure Register(); implementation uses ibSHConsts, ibSHDMLExporterFrm, ibSHDMLExporterActions, ibSHDMLExporterEditors, ibSHComponent; procedure Register(); begin SHRegisterImage(GUIDToString(IibSHDMLExporter), 'DMLExporter.bmp'); SHRegisterImage(TibSHDMLExporterPaletteAction.ClassName, 'DMLExporter.bmp'); SHRegisterImage(TibSHDMLExporterFormAction.ClassName, 'Form_DDLText.bmp'); SHRegisterImage(TibSHDMLExporterToolbarAction_Run.ClassName, 'Button_Run.bmp'); SHRegisterImage(TibSHDMLExporterToolbarAction_Pause.ClassName, 'Button_Stop.bmp'); SHRegisterImage(TibSHDMLExporterToolbarAction_Region.ClassName, 'Button_Tree.bmp'); SHRegisterImage(TibSHDMLExporterToolbarAction_Refresh.ClassName, 'Button_Refresh.bmp'); SHRegisterImage(TibSHDMLExporterToolbarAction_SaveAs.ClassName, 'Button_SaveAs.bmp'); SHRegisterImage(TibSHDMLExporterToolbarAction_CheckAll.ClassName, 'Button_Check.bmp'); SHRegisterImage(TibSHDMLExporterToolbarAction_UnCheckAll.ClassName, 'Button_UnCheck.bmp'); SHREgisterImage(TibSHDMLExporterToolbarAction_MoveDown.ClassName, 'Button_Arrow_Down.bmp'); SHREgisterImage(TibSHDMLExporterToolbarAction_MoveUp.ClassName, 'Button_Arrow_Top.bmp'); SHRegisterImage(SCallTargetScript, 'Form_DDLText.bmp'); SHRegisterComponents([ TibSHDMLExporter, TibSHDMLExporterFactory]); SHRegisterActions([ // Palette TibSHDMLExporterPaletteAction, // Forms TibSHDMLExporterFormAction, // Toolbar TibSHDMLExporterToolbarAction_Run, TibSHDMLExporterToolbarAction_Pause, // TibSHDMLExporterToolbarAction_Region, TibSHDMLExporterToolbarAction_Refresh, TibSHDMLExporterToolbarAction_CheckAll, TibSHDMLExporterToolbarAction_UnCheckAll, TibSHDMLExporterToolbarAction_MoveDown, TibSHDMLExporterToolbarAction_MoveUp, TibSHDMLExporterToolbarAction_SaveAs, // Editors TibSHDMLExporterEditorAction_ExportIntoScript]); SHRegisterPropertyEditor(IibSHDMLExporter, 'StatementType', TibSHDMLExporterStatementTypePropEditor); SHRegisterPropertyEditor(IibSHDMLExporter, 'Output', TibSHDMLExporterOutputPropEditor); end; { TibBTDMLExporter } constructor TibSHDMLExporter.Create(AOwner: TComponent); begin inherited Create(AOwner); FTablesForDumping := TStringList.Create; FTablesForDumping.Sorted := True; FTablesForDumping.CaseSensitive := True; FActive := False; FOutput := ExtractorOutputs[0]; FMode := EmptyStr; FExportAs := ExtractorStatementType[0]; FHeader := False; FPassword := False; FCommitAfter := 500; FDateFormat := 'YYYY-MM-DD'; FTimeFormat := 'HH:NN:SS.ZZZ'; FUseDateTimeANSIPrefix := False; FNonPrintChar2Space := False; end; destructor TibSHDMLExporter.Destroy; begin FTablesForDumping.Free; inherited; end; function TibSHDMLExporter.GetData: IibSHData; begin Result := FData; end; procedure TibSHDMLExporter.SetData(Value: IibSHData); begin if FData <> Value then begin ReferenceInterface(FData, opRemove); FData := Value; ReferenceInterface(FData, opInsert); if Assigned(FData) then Mode := DMLExporterModes[1] else Mode := DMLExporterModes[0]; end; end; function TibSHDMLExporter.GetMode: string; begin Result := FMode; end; procedure TibSHDMLExporter.SetMode(Value: string); begin FMode := Value; end; function TibSHDMLExporter.GetTablesForDumping: TStrings; begin Result := FTablesForDumping; end; procedure TibSHDMLExporter.SetTablesForDumping(Value: TStrings); begin FTablesForDumping.Assign(Value); end; function TibSHDMLExporter.GetActive: Boolean; begin Result := FActive; end; procedure TibSHDMLExporter.SetActive(Value: Boolean); begin FActive := Value; end; function TibSHDMLExporter.GetOutput: string; begin Result := FOutput; end; procedure TibSHDMLExporter.SetOutput(Value: string); begin FOutput := Value; end; function TibSHDMLExporter.GetStatementType: string; begin Result := FExportAs; end; procedure TibSHDMLExporter.SetStatementType(Value: string); var vDMLExporterFormIntf: IibSHDMLExporterForm; begin if CompareStr(FExportAs, Value) <> 0 then begin FExportAs := Value; if GetComponentFormIntf(IibSHDMLExporterForm, vDMLExporterFormIntf) then vDMLExporterFormIntf.UpdateTree; end; end; function TibSHDMLExporter.GetHeader: Boolean; begin Result := FHeader; end; procedure TibSHDMLExporter.SetHeader(Value: Boolean); begin FHeader := Value; end; function TibSHDMLExporter.GetPassword: Boolean; begin Result := FPassword; end; procedure TibSHDMLExporter.SetPassword(Value: Boolean); begin FPassword := Value; end; function TibSHDMLExporter.GetCommitAfter: Integer; begin Result := FCommitAfter; end; procedure TibSHDMLExporter.SetCommitAfter(Value: Integer); begin FCommitAfter := Value; end; function TibSHDMLExporter.GetCommitEachTable: Boolean; begin Result := FCommitEachTable; end; procedure TibSHDMLExporter.SetCommitEachTable(Value: Boolean); begin FCommitEachTable := Value; end; function TibSHDMLExporter.GetDateFormat: string; begin Result := FDateFormat; end; procedure TibSHDMLExporter.SetDateFormat(Value: string); begin FDateFormat := Value; end; function TibSHDMLExporter.GetTimeFormat: string; begin Result := FTimeFormat; end; procedure TibSHDMLExporter.SetTimeFormat(Value: string); begin FTimeFormat := Value; end; function TibSHDMLExporter.GetUseDateTimeANSIPrefix: Boolean; begin Result := FUseDateTimeANSIPrefix; end; procedure TibSHDMLExporter.SetUseDateTimeANSIPrefix(Value: Boolean); begin FUseDateTimeANSIPrefix := Value; end; function TibSHDMLExporter.GetNonPrintChar2Space: Boolean; begin Result := FNonPrintChar2Space; end; procedure TibSHDMLExporter.SetNonPrintChar2Space(Value: Boolean); begin FNonPrintChar2Space := Value; end; procedure TibSHDMLExporter.Notification(AComponent: TComponent; Operation: TOperation); var vDMLExporterFactory: IibSHDMLExporterFactory; begin inherited Notification(AComponent, Operation); if (Operation = opRemove) then begin if AComponent.IsImplementorOf(FData) then begin FActive := False; FData := nil; if Supports(Designer.GetDemon(IibSHDMLExporterFactory), IibSHDMLExporterFactory, vDMLExporterFactory) then vDMLExporterFactory.SuspendedDestroyComponent(Self); end; end; end; { TibSHDMLExporterFactory } constructor TibSHDMLExporterFactory.Create(AOwner: TComponent); begin inherited Create(AOwner); FTablesForDumping := TStringList.Create; FSuspendedTimer := TTimer.Create(nil); FSuspendedTimer.Enabled := False; FSuspendedTimer.Interval := 1; FSuspendedTimer.OnTimer := SuspendedTimerEvent; end; destructor TibSHDMLExporterFactory.Destroy; begin FTablesForDumping.Free; inherited Destroy; end; procedure TibSHDMLExporterFactory.SuspendedTimerEvent(Sender: TObject); begin FSuspendedTimer.Enabled := False; if Assigned(FComponentForSuspendedDestroy) then begin DestroyComponent(FComponentForSuspendedDestroy); FComponentForSuspendedDestroy := nil; end; end; function TibSHDMLExporterFactory.GetData: IibSHData; begin Result := FData; end; procedure TibSHDMLExporterFactory.SetData(Value: IibSHData); begin FData := Value; end; function TibSHDMLExporterFactory.GetMode: string; begin Result := FMode; end; procedure TibSHDMLExporterFactory.SetMode(Value: string); begin FMode := Value; end; function TibSHDMLExporterFactory.GetTablesForDumping: TStrings; begin Result := FTablesForDumping; end; procedure TibSHDMLExporterFactory.SetTablesForDumping(Value: TStrings); begin FTablesForDumping.Assign(Value); end; procedure TibSHDMLExporterFactory.SuspendedDestroyComponent( AComponent: TSHComponent); begin if Assigned(AComponent) then begin FComponentForSuspendedDestroy := AComponent; FSuspendedTimer.Enabled := True; end; end; procedure TibSHDMLExporterFactory.DoBeforeChangeNotification( var ACallString: string; AComponent: TSHComponent); var DMLExporter: IibSHDMLExporter; begin if Supports(AComponent, IibSHDMLExporter, DMLExporter) then begin DMLExporter.Data := FData; DMLExporter.Mode := FMode; DMLExporter.TablesForDumping := FTablesForDumping; end; end; function TibSHDMLExporterFactory.SupportComponent( const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(AClassIID, IibSHDMLExporter); end; function TibSHDMLExporter.GetUseExecuteBlock: boolean; begin Result:=FUseExecuteBlock end; procedure TibSHDMLExporter.SetUseExecuteBlock(Value: boolean); begin FUseExecuteBlock:=Value end; initialization Register; end.
unit PropEditorsReg2; {- ******************************************************************************** ******* XLSReadWriteII V3.00 ******* ******* ******* ******* Copyright(C) 1999,2006 Lars Arvidsson, Axolot Data ******* ******* ******* ******* email: components@axolot.com ******* ******* URL: http://www.axolot.com ******* ******************************************************************************** ** Users of the XLSReadWriteII component must accept the following ** ** disclaimer of warranty: ** ** ** ** XLSReadWriteII is supplied as is. The author disclaims all warranties, ** ** expressedor implied, including, without limitation, the warranties of ** ** merchantability and of fitness for any purpose. The author assumes no ** ** liability for damages, direct or consequential, which may result from the ** ** use of XLSReadWriteII. ** ******************************************************************************** } {$B-} {$H+} {$R-} {$I XLSRWII2.inc} interface uses SysUtils, Classes, Dialogs, CellFormats2, XLSFonts2, Graphics, {$ifdef OLD_COMPILER} DsgnIntf; {$else} DesignEditors, DesignIntf; {$endif} type TPictureNameProperty = class(TStringProperty) private protected procedure GetValueList(List: TStrings); public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; end; type TFilenameProperty = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; implementation { TPictureNameProperty } function TPictureNameProperty.GetAttributes: TPropertyAttributes; begin Result := [paValueList, paSortList]; end; procedure TPictureNameProperty.GetValueList(List: TStrings); // var // i: integer; // XLSPictures: TXLSPictures; begin { XLSPictures := TSheetPictures(TSheetPicture(GetComponent(0)).Collection).XLSPictures; for i := 0 to XLSPictures.Count - 1 do List.Add(XLSPictures[i].Filename); } end; procedure TPictureNameProperty.GetValues(Proc: TGetStrProc); var I: Integer; Values: TStringList; begin Values := TStringList.Create; try GetValueList(Values); for I := 0 to Values.Count - 1 do Proc(Values[I]); finally Values.Free; end; end; { TFilenameProperty } procedure TFilenameProperty.Edit; var S: string; Dlg: TOpenDialog; begin S := GetStrValue; Dlg := TOpenDialog.Create(Nil); try Dlg.Filter := 'All (*.jpg, *.jpeg, *.png, *.bmp)|*.jpg; *.jpeg; *.png; *.bmp|JPEG Images (*.jpeg)|*.jpeg|JPG Images (*.jpg)|*.jpg|PNG Images (*.png)|*.png|Bitmap images (*.bmp)|*.bmp|All files (*.*)|*.*'; Dlg.Filename := S; if Dlg.Execute then S := Dlg.Filename; finally SetStrValue(S); Dlg.Free; end; end; function TFilenameProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog]; end; end.
unit Pospolite.View.Drawing.Renderer; { +-------------------------+ | Package: Pospolite View | | Author: Matek0611 | | Email: matiowo@wp.pl | | Version: 1.0p | +-------------------------+ Comments: ... } {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, Pospolite.View.Basics, Pospolite.View.CSS.Declaration, Pospolite.View.CSS.Basics, Pospolite.View.Drawing.Basics, Pospolite.View.Drawing.Drawer, Pospolite.View.Drawing.NativeDrawer {$ifdef windows}, Pospolite.View.Drawing.DrawerD2D1{$endif}; type { IPLDrawingDrawerFactory } IPLDrawingDrawerFactory = interface ['{8D3CFB7F-A8BF-4204-A5F0-8167F100C1DF}'] function NewMatrix: IPLDrawingMatrix; function NewFont(const AFontData: TPLDrawingFontData): IPLDrawingFont; function NewPen(const ABrush: IPLDrawingBrush; const AWidth: TPLFloat = 1): IPLDrawingPen; overload; function NewPen(const AColor: TPLColor; const AWidth: TPLFloat = 1): IPLDrawingPen; overload; function NewBrushSolid(const AColor: TPLColor): IPLDrawingBrushSolid; function NewBrushBitmap(const ABitmap: IPLDrawingBitmap): IPLDrawingBrushBitmap; function NewBrushGradientLinear(const A, B: TPLPointF): IPLDrawingBrushGradientLinear; function NewBrushGradientRadial(const ARect: TPLRectF): IPLDrawingBrushGradientRadial; function NewBitmap(const AWidth, AHeight: TPLInt): IPLDrawingBitmap; function NewSurface(const ACanvas: TCanvas): IPLDrawingSurface; end; { TPLDrawingDrawerCustomFactory } TPLDrawingDrawerCustomFactory = class(TInterfacedObject, IPLDrawingDrawerFactory) public function NewMatrix: IPLDrawingMatrix; virtual; abstract; function NewFont(const AFontData: TPLDrawingFontData): IPLDrawingFont; virtual; abstract; function NewPen(const ABrush: IPLDrawingBrush; const AWidth: TPLFloat = 1): IPLDrawingPen; overload; virtual; abstract; function NewPen(const AColor: TPLColor; const AWidth: TPLFloat = 1): IPLDrawingPen; overload; virtual; abstract; function NewBrushSolid(const AColor: TPLColor): IPLDrawingBrushSolid; virtual; abstract; function NewBrushBitmap(const ABitmap: IPLDrawingBitmap): IPLDrawingBrushBitmap; virtual; abstract; function NewBrushGradientLinear(const A, B: TPLPointF): IPLDrawingBrushGradientLinear; virtual; abstract; function NewBrushGradientRadial(const ARect: TPLRectF): IPLDrawingBrushGradientRadial; virtual; abstract; function NewBitmap(const AWidth, AHeight: TPLInt): IPLDrawingBitmap; virtual; abstract; function NewSurface(const ACanvas: TCanvas): IPLDrawingSurface; virtual; abstract; end; TPLDrawingDrawerClass = class of TPLAbstractDrawer; TPLDrawingDrawerKind = ( dkAbstract, dkNative, {$ifdef windows}dkDirect2D, {$endif} dkCustom ); const dkDefault = {$ifdef windows}dkDirect2D{$else}dkNative{$endif}; var PLDrawerKind: TPLDrawingDrawerKind = dkDefault; PLDrawerCustomClass: TPLDrawingDrawerClass = TPLAbstractDrawer; PLDrawerCustomFactoryInstance: TPLDrawingDrawerCustomFactory = nil; type { IPLDrawingRenderer } IPLDrawingRenderer = interface(IPLDrawingDrawerFactory) ['{23939734-BAA9-459A-91D0-FC34700E3833}'] function GetDebugMode: boolean; function GetDrawer: TPLAbstractDrawer; procedure SetDebugMode(AValue: boolean); procedure DrawHTMLObject(const AHTMLObject: TPLHTMLObject); property Drawer: TPLAbstractDrawer read GetDrawer; property DebugMode: boolean read GetDebugMode write SetDebugMode; end; { TPLDrawingRenderer } TPLDrawingRenderer = class(TInterfacedObject, IPLDrawingRenderer) private FDrawer: TPLAbstractDrawer; FDebugMode: boolean; function GetDebugMode: boolean; function GetDrawer: TPLAbstractDrawer; procedure SetDebugMode(AValue: boolean); public constructor Create(ACanvas: TCanvas); destructor Destroy; override; procedure DrawHTMLObject(const AHTMLObject: TPLHTMLObject); function NewMatrix: IPLDrawingMatrix; function NewFont(const AFontData: TPLDrawingFontData): IPLDrawingFont; function NewPen(const ABrush: IPLDrawingBrush; const AWidth: TPLFloat = 1): IPLDrawingPen; overload; function NewPen(const AColor: TPLColor; const AWidth: TPLFloat = 1): IPLDrawingPen; overload; function NewBrushSolid(const AColor: TPLColor): IPLDrawingBrushSolid; function NewBrushBitmap(const ABitmap: IPLDrawingBitmap): IPLDrawingBrushBitmap; function NewBrushGradientLinear(const A, B: TPLPointF): IPLDrawingBrushGradientLinear; function NewBrushGradientRadial(const ARect: TPLRectF): IPLDrawingBrushGradientRadial; function NewBitmap(const AWidth, AHeight: TPLInt): IPLDrawingBitmap; function NewSurface(const ACanvas: TCanvas): IPLDrawingSurface; property Drawer: TPLAbstractDrawer read GetDrawer; property DebugMode: boolean read GetDebugMode write SetDebugMode; end; function NewDrawingRenderer(ACanvas: TCanvas): IPLDrawingRenderer; type TPLDrawingRendererManager = class; { TPLDrawingRendererThread } TPLDrawingRendererThread = class(TThread) private FEnabled: TPLBool; FManager: TPLDrawingRendererManager; procedure UpdateRendering; public constructor Create(AManager: TPLDrawingRendererManager); procedure Execute; override; property Enabled: TPLBool read FEnabled write FEnabled; end; TPLDrawingRendererFPS = 1..120; { TPLDrawingRendererManager } TPLDrawingRendererManager = class private FControl: TPLCustomControl; FMaxFPS: TPLDrawingRendererFPS; FRenderingFlag: TPLBool; FThread: TPLDrawingRendererThread; FCS: TRTLCriticalSection; procedure SetRenderingFlag(AValue: TPLBool); public constructor Create(AControl: TPLCustomControl); destructor Destroy; override; procedure StartRendering; procedure StopRendering; function IsRendering: TPLBool; //inline; property Control: TPLCustomControl read FControl write FControl; property MaxFPS: TPLDrawingRendererFPS read FMaxFPS write FMaxFPS default 60; property RenderingFlag: TPLBool read FRenderingFlag write SetRenderingFlag; end; implementation uses {$ifdef windows}Windows,{$endif} math, Dialogs, Forms; function NewDrawingRenderer(ACanvas: TCanvas): IPLDrawingRenderer; begin Result := TPLDrawingRenderer.Create(ACanvas); end; { TPLDrawingRenderer } function TPLDrawingRenderer.GetDrawer: TPLAbstractDrawer; begin Result := FDrawer; end; function TPLDrawingRenderer.GetDebugMode: boolean; begin Result := FDebugMode; end; procedure TPLDrawingRenderer.SetDebugMode(AValue: boolean); begin if FDebugMode = AValue then exit; FDebugMode := AValue; end; constructor TPLDrawingRenderer.Create(ACanvas: TCanvas); begin inherited Create; case PLDrawerKind of dkAbstract: FDrawer := TPLAbstractDrawer.Create(ACanvas); dkNative: FDrawer := TPLNativeDrawer.Create(ACanvas); {$ifdef windows} dkDirect2D: FDrawer := TPLD2D1Drawer.Create(ACanvas); {$endif} dkCustom: FDrawer := PLDrawerCustomClass.Create(ACanvas); end; FDebugMode := false; end; destructor TPLDrawingRenderer.Destroy; begin FDrawer.Free; inherited Destroy; end; procedure TPLDrawingRenderer.DrawHTMLObject(const AHTMLObject: TPLHTMLObject); begin FDrawer.DrawObjectFully(AHTMLObject, FDebugMode); end; function TPLDrawingRenderer.NewMatrix: IPLDrawingMatrix; begin case PLDrawerKind of {$ifdef windows}dkDirect2D: Result := NewDrawingMatrixD2D;{$endif} dkNative: Result := NewDrawingMatrixNative; dkCustom: if Assigned(PLDrawerCustomFactoryInstance) then Result := PLDrawerCustomFactoryInstance.NewMatrix else Result := nil; else Result := nil; end; end; function TPLDrawingRenderer.NewFont(const AFontData: TPLDrawingFontData ): IPLDrawingFont; begin case PLDrawerKind of {$ifdef windows}dkDirect2D: Result := NewDrawingFontD2D(AFontData);{$endif} dkNative: Result := NewDrawingFontNative(AFontData); dkCustom: if Assigned(PLDrawerCustomFactoryInstance) then Result := PLDrawerCustomFactoryInstance.NewFont(AFontData) else Result := nil; else Result := nil; end; end; function TPLDrawingRenderer.NewPen(const ABrush: IPLDrawingBrush; const AWidth: TPLFloat): IPLDrawingPen; begin case PLDrawerKind of {$ifdef windows}dkDirect2D: Result := NewDrawingPenD2D(ABrush, AWidth);{$endif} dkNative: Result := NewDrawingPenNative(ABrush, AWidth); dkCustom: if Assigned(PLDrawerCustomFactoryInstance) then Result := PLDrawerCustomFactoryInstance.NewPen(ABrush, AWidth) else Result := nil; else Result := nil; end; end; function TPLDrawingRenderer.NewPen(const AColor: TPLColor; const AWidth: TPLFloat): IPLDrawingPen; begin case PLDrawerKind of {$ifdef windows}dkDirect2D: Result := NewDrawingPenD2D(AColor, AWidth);{$endif} dkNative: Result := NewDrawingPenNative(AColor, AWidth); dkCustom: if Assigned(PLDrawerCustomFactoryInstance) then Result := PLDrawerCustomFactoryInstance.NewPen(AColor, AWidth) else Result := nil; else Result := nil; end; end; function TPLDrawingRenderer.NewBrushSolid(const AColor: TPLColor ): IPLDrawingBrushSolid; begin case PLDrawerKind of {$ifdef windows}dkDirect2D: Result := NewDrawingSolidBrushD2D(AColor);{$endif} dkNative: Result := NewDrawingSolidBrushNative(AColor); dkCustom: if Assigned(PLDrawerCustomFactoryInstance) then Result := PLDrawerCustomFactoryInstance.NewBrushSolid(AColor) else Result := nil; else Result := nil; end; end; function TPLDrawingRenderer.NewBrushBitmap(const ABitmap: IPLDrawingBitmap ): IPLDrawingBrushBitmap; begin case PLDrawerKind of {$ifdef windows}dkDirect2D: Result := NewDrawingBitmapBrushD2D(ABitmap);{$endif} dkNative: Result := NewDrawingBitmapBrushNative(ABitmap); dkCustom: if Assigned(PLDrawerCustomFactoryInstance) then Result := PLDrawerCustomFactoryInstance.NewBrushBitmap(ABitmap) else Result := nil; else Result := nil; end; end; function TPLDrawingRenderer.NewBrushGradientLinear(const A, B: TPLPointF ): IPLDrawingBrushGradientLinear; begin case PLDrawerKind of {$ifdef windows}dkDirect2D: Result := NewDrawingLinearGradientBrushD2D(A, B);{$endif} dkNative: Result := NewDrawingLinearGradientBrushNative(A, B); dkCustom: if Assigned(PLDrawerCustomFactoryInstance) then Result := PLDrawerCustomFactoryInstance.NewBrushGradientLinear(A, B) else Result := nil; else Result := nil; end; end; function TPLDrawingRenderer.NewBrushGradientRadial(const ARect: TPLRectF ): IPLDrawingBrushGradientRadial; begin case PLDrawerKind of {$ifdef windows}dkDirect2D: Result := NewDrawingRadialGradientBrushD2D(ARect);{$endif} dkNative: Result := NewDrawingRadialGradientBrushNative(ARect); dkCustom: if Assigned(PLDrawerCustomFactoryInstance) then Result := PLDrawerCustomFactoryInstance.NewBrushGradientRadial(ARect) else Result := nil; else Result := nil; end; end; function TPLDrawingRenderer.NewBitmap(const AWidth, AHeight: TPLInt ): IPLDrawingBitmap; begin case PLDrawerKind of {$ifdef windows}dkDirect2D: Result := NewDrawingBitmapD2D(AWidth, AHeight);{$endif} dkNative: Result := NewDrawingBitmapNative(AWidth, AHeight); dkCustom: if Assigned(PLDrawerCustomFactoryInstance) then Result := PLDrawerCustomFactoryInstance.NewBitmap(AWidth, AHeight) else Result := nil; else Result := nil; end; end; function TPLDrawingRenderer.NewSurface(const ACanvas: TCanvas ): IPLDrawingSurface; begin case PLDrawerKind of {$ifdef windows}dkDirect2D: Result := NewDrawingSurfaceD2D(ACanvas);{$endif} dkNative: Result := NewDrawingSurfaceNative(ACanvas); dkCustom: if Assigned(PLDrawerCustomFactoryInstance) then Result := PLDrawerCustomFactoryInstance.NewSurface(ACanvas) else Result := nil; else Result := nil; end; end; { TPLDrawingRendererThread } procedure TPLDrawingRendererThread.UpdateRendering; begin if Assigned(FManager) and Assigned(FManager.FControl) and FManager.RenderingFlag then begin FManager.FControl.Repaint; end; end; constructor TPLDrawingRendererThread.Create(AManager: TPLDrawingRendererManager ); begin inherited Create(true); FManager := AManager; Suspended := true; FreeOnTerminate := false; FEnabled := false; end; procedure TPLDrawingRendererThread.Execute; var delay: Cardinal; begin delay := round(1000 / FManager.FMaxFPS); while FEnabled and not Suspended and not Terminated do begin if not FManager.Control.IsResizing then begin FManager.RenderingFlag := not FManager.RenderingFlag; if FManager.RenderingFlag then UpdateRendering else FManager.FControl.Redraw; end; if not FEnabled or Suspended or Terminated then break; Sleep(delay); end; end; { TPLDrawingRendererManager } procedure TPLDrawingRendererManager.SetRenderingFlag(AValue: TPLBool); begin if FRenderingFlag = AValue then exit; if TryEnterCriticalSection(FCS) then try FRenderingFlag := AValue; finally LeaveCriticalSection(FCS); end; end; constructor TPLDrawingRendererManager.Create(AControl: TPLCustomControl); begin inherited Create; InitializeCriticalSection(FCS); FRenderingFlag := false; FControl := AControl; FMaxFPS := 30; FThread := TPLDrawingRendererThread.Create(self); end; destructor TPLDrawingRendererManager.Destroy; begin DeleteCriticalSection(FCS); FThread.Enabled := false; FThread.Free; inherited Destroy; end; procedure TPLDrawingRendererManager.StartRendering; begin FThread.Enabled := true; FThread.Start; end; procedure TPLDrawingRendererManager.StopRendering; begin FThread.Enabled := false; FThread.Suspended := true; end; function TPLDrawingRendererManager.IsRendering: TPLBool; begin Result := not FThread.Finished and not FThread.Suspended; end; end.
unit UPMsgCoder; interface uses System.Classes, diocp_coder_baseObject, utils_buffer; type TUPMsgDecoder = class(TIOCPDecoder) public /// <summary> 解码收到的数据 </summary> function Decode(const AInBuffer: TBufferLink; AContext: TObject): TObject; override; end; TUPMsgEncoder = class(TIOCPEncoder) public /// <summary> 编码要发送的数据 </summary> procedure Encode(ADataObject: TObject; const AOutBuffer: TBufferLink); override; procedure EncodeToStream(const AInStream: TMemoryStream; const AOutStream: TMemoryStream); end; implementation uses System.SysUtils, UPMsgPack; { TUPMsgDecoder } function TUPMsgDecoder.Decode(const AInBuffer: TBufferLink; AContext: TObject): TObject; var vDataLen: Integer; vPackFlag: Word; vVerifyValue, vActVerifyValue: Cardinal; begin Result := nil; //如果缓存中的数据长度不够包头长度, vDataLen := AInBuffer.validCount; //pack_flag + head_len + buf_len if (vDataLen < SizeOf(Word) + SizeOf(Integer) + SizeOf(Integer)) then Exit; //记录读取位置 AInBuffer.MarkReaderIndex; AInBuffer.ReadBuffer(@vPackFlag, 2); if vPackFlag <> PACK_FLAG then begin //错误的包数据 Result := TObject(-1); Exit; end; AInBuffer.ReadBuffer(@vDataLen, SizeOf(vDataLen)); // 数据长度 AInBuffer.ReadBuffer(@vVerifyValue, SizeOf(vVerifyValue)); // 校验值 if vDataLen > 0 then begin if vDataLen > MAX_OBJECT_SIZE then //文件头不能过大 begin Result := TObject(-1); Exit; end; if AInBuffer.ValidCount < vDataLen then // 返回buf的读取位置 begin AInBuffer.restoreReaderIndex; Exit; end; Result := TMemoryStream.Create; TMemoryStream(Result).SetSize(vDataLen); AInBuffer.ReadBuffer(TMemoryStream(Result).Memory, vDataLen); TMemoryStream(Result).Position := 0; // 校验 vActVerifyValue := VerifyData(TMemoryStream(Result).Memory^, vDataLen); if vVerifyValue <> vActVerifyValue then raise Exception.Create(strRecvException_VerifyErr); end else Result := nil; end; { TUPMsgEncoder } procedure TUPMsgEncoder.Encode(ADataObject: TObject; const AOutBuffer: TBufferLink); var vPackFlag: Word; vDataLen: Integer; vBuffer: TBytes; vVerifyValue: Cardinal; begin vPackFlag := PACK_FLAG; TStream(ADataObject).Position := 0; if TStream(ADataObject).Size > MAX_OBJECT_SIZE then raise Exception.CreateFmt(strSendException_TooBig, [MAX_OBJECT_SIZE]); AOutBuffer.AddBuffer(@vPackFlag, 2); // 包头 vDataLen := TStream(ADataObject).Size; // 数据大小 //vDataLenSw := TByteTools.swap32(vDataLen); AOutBuffer.AddBuffer(@vDataLen, SizeOf(vDataLen)); // 数据长度 // stream data SetLength(vBuffer, vDataLen); TStream(ADataObject).Read(vBuffer[0], vDataLen); // 校验值 vVerifyValue := VerifyData(vBuffer[0], vDataLen); AOutBuffer.AddBuffer(@vVerifyValue, SizeOf(vVerifyValue)); // 写入校验值 AOutBuffer.AddBuffer(@vBuffer[0], vDataLen); // 数据 end; procedure TUPMsgEncoder.EncodeToStream(const AInStream: TMemoryStream; const AOutStream: TMemoryStream); var vPackFlag: Word; vDataLen: Integer; vVerifyValue: Cardinal; begin if AInStream.Size > MAX_OBJECT_SIZE then // 超过最大发送量 raise Exception.CreateFmt(strSendException_TooBig, [MAX_OBJECT_SIZE]); vPackFlag := PACK_FLAG; AOutStream.Write(vPackFlag, SizeOf(vPackFlag)); // 写包头 vDataLen := AInStream.Size; // 数据大小 AOutStream.Write(vDataLen, SizeOf(vDataLen)); // 写入数据大小的值 // 校验值 vVerifyValue := VerifyData(AInStream.Memory^, vDataLen); AOutStream.Write(vVerifyValue, SizeOf(vVerifyValue)); // 写入校验值 AInStream.Position := 0; AOutStream.Write(AInStream.Memory^, AInStream.Size); // 写入实际数据 end; end.
unit CustomScheme; interface uses BasicFunctions, SysUtils, Classes; type TCustomSchemeData = array[0..255] of integer; TCustomScheme = class private fName : string; fAuthor : string; fGameType : integer; fSplit : boolean; fWebsite : string; fImageIndex : integer; fSchemeType : integer; fData : TCustomSchemeData; // Gets function getName: string; function getAuthor: string; function getGameType: integer; function getSplit: boolean; function getWebsite: string; function getImageIndex: integer; function getSchemeType: integer; function getData: TCustomSchemeData; // Sets procedure setName(_Value: string); procedure setAuthor(_Value: string); procedure setGameType(_Value: integer); procedure setSplit(_Value: boolean); procedure setWebsite(_Value: string); procedure setImageIndex(_Value: integer); procedure setSchemeType(_Value: integer); procedure setData(_Value: TCustomSchemeData); // Text related operations function isLineTagEqual(const _Tag,_Line: string) : boolean; function getLineValue(const _Line : string): string; function getTagValue(const _StringList: TStringList; const _Tag: string): string; public // Constructors and Destructors constructor Create; overload; constructor Create(const _Filename: string); overload; constructor CreateForVXLSE(const _Filename: string); constructor CreateForData(const _Filename: string); destructor Destroy; override; // I/O procedure Load(const _Filename: string); procedure GatherInfoForVXLSE(const _Filename : string); procedure GatherData(const _Filename: string); procedure Save(const _Filename: string); // Properties property Name: string read getName write setName; property Author: string read getAuthor write setAuthor; property GameType: integer read getGameType write setGameType; property Split: boolean read getSplit write setSplit; property Website: string read getWebsite write setWebsite; property ImageIndex: integer read getImageIndex write setImageIndex; property SchemeType: integer read getSchemeType write setSchemeType; property Data: TCustomSchemeData read getData write setData; end; implementation // Constructors and Destructors constructor TCustomScheme.Create; begin fName := ''; fAuthor := ''; fWebsite := ''; fGameType := 0; fImageIndex := -1; fSchemeType := 1; Split := false; end; constructor TCustomScheme.Create(const _Filename: string); begin Load(_Filename); end; constructor TCustomScheme.CreateForVXLSE(const _Filename: string); begin GatherInfoForVXLSE(_Filename); fAuthor := ''; fWebsite := ''; fSchemeType := 1; end; constructor TCustomScheme.CreateForData(const _Filename: string); begin GatherData(_Filename); end; destructor TCustomScheme.Destroy; begin fName := ''; fAuthor := ''; fWebsite := ''; inherited Destroy; end; // I/O procedure TCustomScheme.Load(const _Filename : string); var s: TStringList; i,temp : integer; begin s := TStringList.Create; s.LoadFromFile(_Filename); fName := getTagValue(s,'name'); fAuthor := getTagValue(s,'by'); fWebsite := getTagValue(s,'website'); fImageIndex := StrToIntDef(getTagValue(s,'imageindex'),-1); fSplit := GetBool(getTagValue(s,'split')); fGameType := StrToIntDef(getTagValue(s,'gametype'),0); fSchemeType := StrToIntDef(getTagValue(s,'schemetype'),1); for i := 0 to 255 do begin temp := StrToIntDef(getTagValue(s,IntToStr(i)),-1); if temp <> -1 then begin fData[i] := temp; end else begin fData[i] := i; end; end; s.Free; end; procedure TCustomScheme.GatherInfoForVXLSE(const _Filename : string); var s: TStringList; begin s := TStringList.Create; s.LoadFromFile(_Filename); fName := getTagValue(s,'name'); fImageIndex := StrToIntDef(getTagValue(s,'imageindex'),-1); fSplit := GetBool(getTagValue(s,'split')); fGameType := StrToIntDef(getTagValue(s,'gametype'),0); s.Free; end; procedure TCustomScheme.GatherData(const _Filename : string); var s: TStringList; i, Temp : integer; begin s := TStringList.Create; s.LoadFromFile(_Filename); for i := 0 to 255 do begin temp := StrToIntDef(getTagValue(s,IntToStr(i)),-1); if temp <> -1 then begin fData[i] := temp; end else begin fData[i] := i; end; end; s.Free; end; procedure TCustomScheme.Save(const _Filename : string); var F: system.Text; i: integer; begin AssignFile(F,_Filename); Rewrite(F); Writeln(F,'[Info]'); if Length(fName) > 0 then Writeln(F,'Name=' + fName) else Writeln(F,'Name=Unnamed Custom Scheme'); if Length(fAuthor) > 0 then Writeln(F,'By=' + fAuthor) else Writeln(F,'By=Anonymous'); if Length(fWebsite) > 0 then Writeln(F,'Website=' + fWebsite) else Writeln(F,'Website=None'); Writeln(F,'ImageIndex=' + IntToStr(fImageIndex)); if Split then Writeln(F,'Split=true') else Writeln(F,'Split=false'); Writeln(F,'GameType=' + IntToStr(fGameType)); Writeln(F,'SchemeType=' + IntToStr(fSchemeType)); Writeln(F); Writeln(F,'[Data]'); for i := 0 to 255 do begin WriteLn(F,IntToStr(i) + '=' + IntToStr(fData[i])); end; Writeln(F); CloseFile(F); end; // Gets function TCustomScheme.getName: string; begin Result := fName; end; function TCustomScheme.getAuthor: string; begin Result := fAuthor; end; function TCustomScheme.getGameType: integer; begin Result := fGameType; end; function TCustomScheme.getSplit: boolean; begin Result := fSplit; end; function TCustomScheme.getWebsite: string; begin Result := fWebsite; end; function TCustomScheme.getImageIndex: integer; begin Result := fImageIndex; end; function TCustomScheme.getSchemeType: integer; begin Result := fSchemeType; end; function TCustomScheme.getData: TCustomSchemeData; begin Result := fData; end; // Sets procedure TCustomScheme.setName(_Value: string); begin fName := CopyString(_Value); end; procedure TCustomScheme.setAuthor(_Value: string); begin fAuthor := CopyString(_Value); end; procedure TCustomScheme.setGameType(_Value: integer); begin fGameType := _Value; end; procedure TCustomScheme.setSplit(_Value: boolean); begin fSplit := _Value; end; procedure TCustomScheme.setWebsite(_Value: string); begin fWebsite := CopyString(_Value); end; procedure TCustomScheme.setImageIndex(_Value: integer); begin fImageIndex := _Value; end; procedure TCustomScheme.setSchemeType(_Value: integer); begin fSchemeType := _Value; end; procedure TCustomScheme.setData(_Value: TCustomSchemeData); begin fData := _Value; end; // Text related operations // Check if a line (name=blahblah) has a value of a tag (i.e.: name, author, website) function TCustomScheme.isLineTagEqual(const _Tag,_Line: string) : boolean; var i: integer; Tag, Line: string; begin Result := false; if (Length(_Tag) > 0) and (Length(_Line) > 0) and (Length(_Tag) < Length(_Line)) then begin Tag := Lowercase(_Tag); Line := Lowercase(_Line); Result := true; i := 1; while Result and (i <= Length(Tag)) do begin if Tag[i] <> Line[i] then Result := false; inc(i); end; end; end; function TCustomScheme.getLineValue(const _Line : string): string; var i: integer; Found : boolean; begin Result := ''; i := 1; Found := false; while (i <= Length(_Line)) and (not Found) do begin if _Line[i] = '=' then Found := true; inc(i); end; if Found then Result := Copy(_Line,i,Length(_Line)-i+1); end; function TCustomScheme.getTagValue(const _StringList: TStringList; const _Tag: string): string; var i: integer; Found : boolean; begin Result := '!ERROR!'; i := 0; Found := false; while (i < _StringList.Count) and (not Found) do begin if isLineTagEqual(_Tag,_StringList.Strings[i]) then begin Found := true; Result := getLineValue(_StringList.Strings[i]); end; inc(i); end; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // { Cross platform support functions and types for GLScene. } unit GLCrossPlatform; interface {$I GLScene.inc} uses Windows, System.Types, System.Classes, System.SysUtils, System.StrUtils, VCL.Consts, VCL.Graphics, VCL.Controls, VCL.Forms, VCL.Dialogs; type THalfFloat = type Word; PHalfFloat = ^THalfFloat; TGLMouseEvent = procedure(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer) of object; EGLOSError = EOSError; TGLComponent = class(TComponent); TProjectTargetNameFunc = function(): string; const FONT_CHARS_COUNT = 2024; var IsDesignTime: Boolean = False; vProjectTargetName: TProjectTargetNameFunc; function GetGLRect(const aLeft, aTop, aRight, aBottom: Integer): TRect; { Increases or decreases the width and height of the specified rectangle. Adds dx units to the left and right ends of the rectangle and dy units to the top and bottom. } procedure InflateGLRect(var aRect: TRect; dx, dy: Integer); procedure IntersectGLRect(var aRect: TRect; const rect2: TRect); procedure RaiseLastOSError; {Number of pixels per logical inch along the screen width for the device. Under Win32 awaits a HDC and returns its LOGPIXELSX. } function GetDeviceLogicalPixelsX(device: HDC): Integer; {Number of bits per pixel for the current desktop resolution. } function GetCurrentColorDepth: Integer; {Returns the number of color bits associated to the given pixel format. } function PixelFormatToColorBits(aPixelFormat: TPixelFormat): Integer; {Replace path delimiter to delimiter of the current platform. } procedure FixPathDelimiter(var S: string); {Remove if possible part of path witch leads to project executable. } function RelativePath(const S: string): string; {Returns the current value of the highest-resolution counter. If the platform has none, should return a value derived from the highest precision time reference available, avoiding, if possible, timers that allocate specific system resources. } procedure QueryPerformanceCounter(out val: Int64); {Returns the frequency of the counter used by QueryPerformanceCounter. Return value is in ticks per second (Hz), returns False if no precision counter is available. } function QueryPerformanceFrequency(out val: Int64): Boolean; {Starts a precision timer. Returned value should just be considered as 'handle', even if it ain't so. Default platform implementation is to use QueryPerformanceCounter and QueryPerformanceFrequency, if higher precision references are available, they should be used. The timer will and must be stopped/terminated/released with StopPrecisionTimer. } function StartPrecisionTimer: Int64; {Computes time elapsed since timer start. Return time lap in seconds. } function PrecisionTimerLap(const precisionTimer: Int64): Double; {Computes time elapsed since timer start and stop timer. Return time lap in seconds. } function StopPrecisionTimer(const precisionTimer: Int64): Double; {Returns time in milisecond from application start. } function AppTime: Double; {Returns the number of CPU cycles since startup. Use the similarly named CPU instruction. } function GLOKMessageBox(const Text, Caption: string): Integer; procedure GLLoadBitmapFromInstance(Instance: LongInt; ABitmap: TBitmap; const AName: string); procedure ShowHTMLUrl(const Url: string); procedure SetExeDirectory; // StrUtils.pas function AnsiStartsText(const ASubText, AText: string): Boolean; // Classes.pas function IsSubComponent(const AComponent: TComponent): Boolean; inline; procedure MakeSubComponent(const AComponent: TComponent; const Value: Boolean); function FindUnitName(anObject: TObject): string; overload; function FindUnitName(aClass: TClass): string; overload; function FloatToHalf(Float: Single): THalfFloat; function HalfToFloat(Half: THalfFloat): Single; function GetValueFromStringsIndex(const AStrings: TStrings; const AIndex: Integer): string; {Determine if the directory is writable. } function IsDirectoryWriteable(const AName: string): Boolean; function CharToWideChar(const AChar: AnsiChar): WideChar; //----------------------------------------------------------- implementation //----------------------------------------------------------- uses ShellApi; var vInvPerformanceCounterFrequency: Double; vInvPerformanceCounterFrequencyReady: Boolean = False; vLastProjectTargetName: string; function IsSubComponent(const AComponent: TComponent): Boolean; begin Result := (csSubComponent in AComponent.ComponentStyle); end; procedure MakeSubComponent(const AComponent: TComponent; const Value: Boolean); begin AComponent.SetSubComponent(Value); end; function AnsiStartsText(const ASubText, AText: string): Boolean; begin Result := AnsiStartsText(ASubText, AText); end; function GLOKMessageBox(const Text, Caption: string): Integer; begin Result := Application.MessageBox(PChar(Text), PChar(Caption), MB_OK); end; procedure GLLoadBitmapFromInstance(Instance: LongInt; ABitmap: TBitmap; const AName: string); begin ABitmap.Handle := LoadBitmap(Instance, PChar(AName)); end; procedure ShowHTMLUrl(const Url: string); begin ShellExecute(0, 'open', PChar(Url), nil, nil, SW_SHOW); end; function GetGLRect(const aLeft, aTop, aRight, aBottom: Integer): TRect; begin Result.Left := aLeft; Result.Top := aTop; Result.Right := aRight; Result.Bottom := aBottom; end; procedure InflateGLRect(var aRect: TRect; dx, dy: Integer); begin aRect.Left := aRect.Left - dx; aRect.Right := aRect.Right + dx; if aRect.Right < aRect.Left then aRect.Right := aRect.Left; aRect.Top := aRect.Top - dy; aRect.Bottom := aRect.Bottom + dy; if aRect.Bottom < aRect.Top then aRect.Bottom := aRect.Top; end; procedure IntersectGLRect(var aRect: TRect; const rect2: TRect); var a: Integer; begin if (aRect.Left > rect2.Right) or (aRect.Right < rect2.Left) or (aRect.Top > rect2.Bottom) or (aRect.Bottom < rect2.Top) then begin // no intersection a := 0; aRect.Left := a; aRect.Right := a; aRect.Top := a; aRect.Bottom := a; end else begin if aRect.Left < rect2.Left then aRect.Left := rect2.Left; if aRect.Right > rect2.Right then aRect.Right := rect2.Right; if aRect.Top < rect2.Top then aRect.Top := rect2.Top; if aRect.Bottom > rect2.Bottom then aRect.Bottom := rect2.Bottom; end; end; procedure RaiseLastOSError; var e: EGLOSError; begin e := EGLOSError.Create('OS Error : ' + SysErrorMessage(GetLastError)); raise e; end; type TDeviceCapabilities = record Xdpi, Ydpi: integer; // Number of pixels per logical inch. Depth: integer; // The bit depth. NumColors: integer; // Number of entries in the device's color table. end; function GetDeviceCapabilities: TDeviceCapabilities; var Device: HDC; begin Device := GetDC(0); try result.Xdpi := GetDeviceCaps(Device, LOGPIXELSX); result.Ydpi := GetDeviceCaps(Device, LOGPIXELSY); result.Depth := GetDeviceCaps(Device, BITSPIXEL); result.NumColors := GetDeviceCaps(Device, NUMCOLORS); finally ReleaseDC(0, Device); end; end; function GetDeviceLogicalPixelsX(device: HDC): Integer; begin result := GetDeviceCapabilities().Xdpi; end; function GetCurrentColorDepth: Integer; begin result := GetDeviceCapabilities().Depth; end; function PixelFormatToColorBits(aPixelFormat: TPixelFormat): Integer; begin case aPixelFormat of pfCustom{$IFDEF WIN32}, pfDevice{$ENDIF}: // use current color depth Result := GetCurrentColorDepth; pf1bit: Result := 1; {$IFDEF WIN32} pf4bit: Result := 4; pf15bit: Result := 15; {$ENDIF} pf8bit: Result := 8; pf16bit: Result := 16; pf32bit: Result := 32; else Result := 24; end; end; procedure FixPathDelimiter(var S: string); var I: Integer; begin for I := Length(S) downto 1 do if (S[I] = '/') or (S[I] = '\') then S[I] := PathDelim; end; function RelativePath(const S: string): string; var path: string; begin Result := S; if IsDesignTime then begin if Assigned(vProjectTargetName) then begin path := vProjectTargetName(); if Length(path) = 0 then path := vLastProjectTargetName else vLastProjectTargetName := path; path := IncludeTrailingPathDelimiter(ExtractFilePath(path)); end else exit; end else begin path := ExtractFilePath(ParamStr(0)); path := IncludeTrailingPathDelimiter(path); end; if Pos(path, S) = 1 then Delete(Result, 1, Length(path)); end; procedure QueryPerformanceCounter(out val: Int64); begin Windows.QueryPerformanceCounter(val); end; function QueryPerformanceFrequency(out val: Int64): Boolean; begin Result := Boolean(Windows.QueryPerformanceFrequency(val)); end; function StartPrecisionTimer: Int64; begin QueryPerformanceCounter(Result); end; function PrecisionTimerLap(const precisionTimer: Int64): Double; begin // we can do this, because we don't really stop anything Result := StopPrecisionTimer(precisionTimer); end; function StopPrecisionTimer(const precisionTimer: Int64): Double; var cur, freq: Int64; begin QueryPerformanceCounter(cur); if not vInvPerformanceCounterFrequencyReady then begin QueryPerformanceFrequency(freq); vInvPerformanceCounterFrequency := 1.0 / freq; vInvPerformanceCounterFrequencyReady := True; end; Result := (cur - precisionTimer) * vInvPerformanceCounterFrequency; end; var vGLSStartTime : TDateTime; vLastTime: TDateTime; vDeltaMilliSecond: TDateTime; function AppTime: Double; var SystemTime: TSystemTime; begin GetLocalTime(SystemTime); with SystemTime do Result := (wHour * (MinsPerHour * SecsPerMin * MSecsPerSec) + wMinute * (SecsPerMin * MSecsPerSec) + wSecond * MSecsPerSec + wMilliSeconds) - vGLSStartTime; // Hack to fix time precession if Result - vLastTime = 0 then begin Result := Result + vDeltaMilliSecond; vDeltaMilliSecond := vDeltaMilliSecond + 0.1; end else begin vLastTime := Result; vDeltaMilliSecond := 0.1; end; end; function FindUnitName(anObject: TObject): string; begin if Assigned(anObject) then Result := anObject.UnitName else Result := ''; end; function FindUnitName(aClass: TClass): string; begin if Assigned(aClass) then Result := aClass.UnitName else Result := ''; end; procedure SetExeDirectory; var path: string; begin if IsDesignTime then begin if Assigned(vProjectTargetName) then begin path := vProjectTargetName(); if Length(path) = 0 then path := vLastProjectTargetName else vLastProjectTargetName := path; path := IncludeTrailingPathDelimiter(ExtractFilePath(path)); SetCurrentDir(path); end; end else begin path := ExtractFilePath(ParamStr(0)); path := IncludeTrailingPathDelimiter(path); SetCurrentDir(path); end; end; function HalfToFloat(Half: THalfFloat): Single; var Dst, Sign, Mantissa: LongWord; Exp: LongInt; begin // extract sign, exponent, and mantissa from half number Sign := Half shr 15; Exp := (Half and $7C00) shr 10; Mantissa := Half and 1023; if (Exp > 0) and (Exp < 31) then begin // common normalized number Exp := Exp + (127 - 15); Mantissa := Mantissa shl 13; Dst := (Sign shl 31) or (LongWord(Exp) shl 23) or Mantissa; // Result := Power(-1, Sign) * Power(2, Exp - 15) * (1 + Mantissa / 1024); end else if (Exp = 0) and (Mantissa = 0) then begin // zero - preserve sign Dst := Sign shl 31; end else if (Exp = 0) and (Mantissa <> 0) then begin // denormalized number - renormalize it while (Mantissa and $00000400) = 0 do begin Mantissa := Mantissa shl 1; Dec(Exp); end; Inc(Exp); Mantissa := Mantissa and not $00000400; // now assemble normalized number Exp := Exp + (127 - 15); Mantissa := Mantissa shl 13; Dst := (Sign shl 31) or (LongWord(Exp) shl 23) or Mantissa; // Result := Power(-1, Sign) * Power(2, -14) * (Mantissa / 1024); end else if (Exp = 31) and (Mantissa = 0) then begin // +/- infinity Dst := (Sign shl 31) or $7F800000; end else //if (Exp = 31) and (Mantisa <> 0) then begin // not a number - preserve sign and mantissa Dst := (Sign shl 31) or $7F800000 or (Mantissa shl 13); end; // reinterpret LongWord as Single Result := PSingle(@Dst)^; end; function FloatToHalf(Float: Single): THalfFloat; var Src: LongWord; Sign, Exp, Mantissa: LongInt; begin Src := PLongWord(@Float)^; // extract sign, exponent, and mantissa from Single number Sign := Src shr 31; Exp := LongInt((Src and $7F800000) shr 23) - 127 + 15; Mantissa := Src and $007FFFFF; if (Exp > 0) and (Exp < 30) then begin // simple case - round the significand and combine it with the sign and exponent Result := (Sign shl 15) or (Exp shl 10) or ((Mantissa + $00001000) shr 13); end else if Src = 0 then begin // input float is zero - return zero Result := 0; end else begin // difficult case - lengthy conversion if Exp <= 0 then begin if Exp < -10 then begin // input float's value is less than HalfMin, return zero Result := 0; end else begin // Float is a normalized Single whose magnitude is less than HalfNormMin. // We convert it to denormalized half. Mantissa := (Mantissa or $00800000) shr (1 - Exp); // round to nearest if (Mantissa and $00001000) > 0 then Mantissa := Mantissa + $00002000; // assemble Sign and Mantissa (Exp is zero to get denotmalized number) Result := (Sign shl 15) or (Mantissa shr 13); end; end else if Exp = 255 - 127 + 15 then begin if Mantissa = 0 then begin // input float is infinity, create infinity half with original sign Result := (Sign shl 15) or $7C00; end else begin // input float is NaN, create half NaN with original sign and mantissa Result := (Sign shl 15) or $7C00 or (Mantissa shr 13); end; end else begin // Exp is > 0 so input float is normalized Single // round to nearest if (Mantissa and $00001000) > 0 then begin Mantissa := Mantissa + $00002000; if (Mantissa and $00800000) > 0 then begin Mantissa := 0; Exp := Exp + 1; end; end; if Exp > 30 then begin // exponent overflow - return infinity half Result := (Sign shl 15) or $7C00; end else // assemble normalized half Result := (Sign shl 15) or (Exp shl 10) or (Mantissa shr 13); end; end; end; function GetValueFromStringsIndex(const AStrings: TStrings; const AIndex: Integer): string; begin Result := AStrings.ValueFromIndex[AIndex]; end; function IsDirectoryWriteable(const AName: string): Boolean; var LFileName: String; LHandle: THandle; begin LFileName := IncludeTrailingPathDelimiter(AName) + 'chk.tmp'; LHandle := CreateFile(PChar(LFileName), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_DELETE_ON_CLOSE, 0); Result := LHandle <> INVALID_HANDLE_VALUE; if Result then CloseHandle(LHandle); end; function CharToWideChar(const AChar: AnsiChar): WideChar; var lResult: PWideChar; begin GetMem(lResult, 2); MultiByteToWideChar(CP_ACP, 0, @AChar, 1, lResult, 2); Result := lResult^; FreeMem(lResult, 2); end; //---------------------------------------- initialization //---------------------------------------- vGLSStartTime := AppTime; end.
// // EE_CONVERT -- Conversion procedures and functions // unit ee_convert; {$MODE OBJFPC} interface uses Crt, Classes, DateUtils, // For SecondsBetween Process, SysUtils, USupportLibrary, UTextFile, ee_global; const LINE_SEPARATOR = '|'; type // Header Position Array definition THeaderPos = record lab: string; pos: integer; end; // of record THeaderPosArray = array of THeaderPos; // Event Record type definition TEventRecord = record eventId: integer; description: string; count: integer; osVersion: word; end; // of record TEventArray = array of TEventRecord; TEventDetailRecord = record eventId: integer; // eventId keyName: string; // KeyName in Splunk position: integer; // Position in the export file. isString: boolean; // Type of field, TRUE=String/FALSE=Number description: string; // Description of keyName end; // of record TEventDetailArray = array of TEventDetailRecord; var lpr: CTextFile; skv: CTextFile; headerPosArray: THeaderPosArray; eventArray: TEventArray; eventDetailArray: TEventDetailArray; function ProcessThisEvent(e: integer): boolean; procedure ReadEventDefinitions(); procedure EventAndEventDetailsShow(); procedure ConvertLpr(pathLpr: string; pathSkv: string); implementation procedure EventRecordAdd(newEventId: integer; newDescription: string); // // // Add a new record in the array of Event // // newEventId integer The event id to search for // newDescription string Description of the event // var size: integer; begin size := Length(eventArray); SetLength(eventArray, size + 1); eventArray[size].eventId := newEventId; eventArray[size].description := newDescription; end; // of procedure EventRecordAdd procedure EventDetailRecordAdd(newEventId: integer; newKeyName: string; newPosition: integer; newIsString: boolean; newDesc: string); // // Add a new record to the array of Event Details // // newEventId Event ID: 9999 // newKeyName Name of key in Splunk // newPosition Position of the value in the export LPR file. // newIsString Boolean for IsString (TRUE=String/FALSE=Number); determines enclosure with double quotes // newDesc Descripion // var size: integer; begin size := Length(eventDetailArray); SetLength(eventDetailArray, size + 1); eventDetailArray[size].eventId := newEventId; eventDetailArray[size].keyName := newKeyName; eventDetailArray[size].position := newPosition; eventDetailArray[size].isString := newIsString; eventDetailArray[size].description := newDesc; end; // of procedure EventDetailRecordAdd procedure EventAndEventDetailsShow(); // // Show the Events and Events Details. // var i: integer; j: integer; t: Ansistring; begin WriteLn(); WriteLn('EVENTS TO PROCESS'); WriteLn('================='); for i := 0 to High(eventArray) do begin //Writeln(IntToStr(i) + Chr(9) + ' ' + IntToStr(EventArray[i].eventId) + Chr(9), EventArray[i].isActive, Chr(9) + IntToStr(EventArray[i].osVersion) + Chr(9) + EventArray[i].description); Writeln(AlignRight(i, 6) + AlignRight(eventArray[i].eventId, 6) + ' ' + eventArray[i].description); for j := 0 to High(eventDetailArray) do begin if eventDetailArray[j].eventId = eventArray[i].eventId then begin t := ' '; t := t + AlignRight(j, 6); // Number of line t := t + ' ' + AlignRight(eventDetailArray[j].eventId, 6); // Number of event id t := t + ' ' + AlignLeft(eventDetailArray[j].keyName, 10); // Splunk Key Name t := t + ' ' + AlignRight(eventDetailArray[j].position, 3); // Position in the export file t := t + ' ' + AlignLeft(BoolToStr(eventDetailArray[j].IsString), 5); // Boolean of type (TRUE=String/FALSE=Number) t := t + ' ' + AlignLeft(eventDetailArray[j].description, 50); // Descripion of field. WriteLn(t); end; end; end; end; // of procedure EventAndEventDetailsShow procedure ReadEventDefinitions(); var a: TStringArray; aFields: TStringArray; eventDescription: string; eventId: integer; exportEvents: string; numberOfFields: integer; x: integer; y: integer; fieldValue: string; begin SetLength(a, 0); exportEvents := ReadSettingKey('Settings', 'ConvertEvents'); a := SplitString(exportEvents, ';'); for x := 0 to high(a) do begin //WriteLn(x, '>', a[x]); eventId := StrToInt(ReadSettingKey(a[x], 'Id')); eventDescription := ReadSettingKey(a[x], 'Description'); numberOfFields := StrToInt(ReadSettingKey(a[x], 'NumberOfFields')); EventRecordAdd(eventId, eventDescription); for y := 1 to numberOfFields do begin // Find the keys in the config with name FieldX. fieldValue := ReadSettingKey(IntToStr(eventId), 'Field' + IntToStr(y)); // Split the string into an array of strings. aFields := SplitString(fieldValue, ';'); // Add a new record to the EventDetailArray with the values from the line above. EventDetailRecordAdd(eventId, aFields[0], StrToInt(aFields[1]), StrToBool(aFields[2]), aFields[3]); end; // of for end // of for end; // of procedure ReadEventDefinitions function ProcessThisEvent(e: integer): boolean; { Read the events from the EventArray. Return the status for isActive. Returns TRUE Process this event. FALSE Do not process this event. } var i: integer; r: boolean; begin r := false; //WriteLn; //WriteLn('ProcessThisEvent(): e=', e); for i := 0 to High(EventArray) do begin //WriteLn(i, chr(9), EventArray[i].eventId, Chr(9), EventArray[i].isActive); if eventArray[i].eventId = e then begin r := true; //WriteLn('FOUND ', e, ' ON POS ', i); break; // Found the event e in the array, return the isActive state //r := EventArray[i].isActive; //break; end; end; //WriteLn('ShouldEventBeProcessed():', Chr(9), e, Chr(9), r); ProcessThisEvent := r; end; procedure ProcessHeader(l: Ansistring); // // Process the header line of a file. // // Place all labels in the headerPosArray with there postion number. Starting with 0. // var a: TStringArray; x: integer; sizeArray: integer; begin WriteLn('ProcessHeader():'); a := SplitString(l, LINE_SEPARATOR); for x := 0 to High(a) do begin //WriteLn(x, ': ', a[x]); sizeArray := Length(headerPosArray); SetLength(headerPosArray, sizeArray + 1); headerPosArray[sizeArray].lab := a[x]; headerPosArray[sizeArray].pos := x; end; // of for end; function FindHeaderPos(labSearch: string): integer; // // Find the postion of a header label in the headerPosArray array // // labSearch Search for the name in labSearch. // // Returns the position number of the found labSearch, returns -1 when not found. // var x: integer; r: integer; begin //WriteLn('headerPosArray contents:'); r := -1; // We can return a 0 when the found label is 0. for x := 0 to high(headerPosArray) do begin //WriteLn(x, ': ', headerPosArray[x].lab, '=', headerPosArray[x].pos); if labSearch = headerPosArray[x].lab then r := headerPosArray[x].pos end; // of for FindHeaderPos := r; end; // of function FindHeaderPos function GetEventType(eventType: integer): string; // // Returns the Event Type string for a EventType // // 1 ERROR // 2 WARNING // 3 INFO // 4 SUCCESS AUDIT // 5 FAILURE AUDIT // // Source: https://msdn.microsoft.com/en-us/library/aa394226%28v=vs.85%29.aspx // var r: string; begin r := ''; case eventType of 1: r := 'ERR'; // Error 2: r := 'WRN'; // Warning 4: r := 'INF'; // Information 8: r := 'AUS'; // Audit Success 16: r := 'AUF'; // Audit Failure else r := 'UKN'; // Unknown, note: should never be returned. end; GetEventType := r; end; // of function GetEventType procedure ProcessLineWithEvent(a: TStringArray); // // Only the lines that need to be converted are processed by this procedure. // var x: integer; buffer: Ansistring; eventId: string; keyName: string; keyPos: integer; keyValue: string; IsString: boolean; begin //WriteLn('ProcessLine() BEGIN========================================================='); {WriteLn('LINE TO TSTRINGARRAY:'); for x := 0 to high(a) do begin WriteLn(' ', x, ': ', a[x]); end; // of for } // Build the buffer string to write to the export SKV file. // Write the date and time to the buffer. buffer := a[FindHeaderPos('TimeGenerated')] + ' '; // Add the Event type to the buffer. buffer := buffer + GetEventType(StrToInt(a[FindHeaderPos('EventType')])); // Get the Event ID from the line. Use the label from the header to determine the position. eventId := a[FindHeaderPos('EventID')]; buffer := buffer + ' eid=' + eventId; for x := 0 to High(eventDetailArray) do begin if eventDetailArray[x].eventId = StrToInt(eventId) then begin Inc(giConvertedEvents); keyName := eventDetailArray[x].keyName; keyPos := eventDetailArray[x].position; isString := eventDetailArray[x].IsString; //WriteLn('KEY:', keyName, ' POS:', keyPos, ' ISSTR:', isString); // Get the keyvalue from the line array keyValue := a[keyPos]; if (RightStr(keyValue, 1) = '$') and (gbFlagIncludeComputer = false) then exit; if Length(keyValue) > 0 then begin buffer := buffer + ' ' + keyName + '='; if isString = true then buffer := buffer + EncloseDoubleQuote(keyValue) // STRING (isString=TRUE) else buffer := buffer + keyValue; // NUMBER (isString= FALSE) end; // of if end; // of if end; // of for //WriteLn('BUFFER: ', buffer); skv.WriteToFile(buffer); //WriteLn('ProcessLine() END========================================================='); end; procedure CheckForLineProcessing(l: Ansistring); // // Process a line with event log data that needs to be converted // var a: TStringArray; x: integer; begin //WriteLn('CheckForLineProcessing():'); // Extract the parts to the line to a StringArray. a := SplitString(l, LINE_SEPARATOR); for x := 0 to high(a) do begin if (x = FindHeaderPos('EventID')) and (ProcessThisEvent(StrToInt(a[x])) = true) then //WriteLn('*** PROCESS THIS EVENT: ', a[x], ' ***'); ProcessLineWithEvent(a); end; // of for end; procedure ConvertLpr(pathLpr: string; pathSkv: string); var strLine: Ansistring; intCurrentLine: integer; begin WriteLn('ConvertLpr()'); WriteLn(' file: ', pathLpr); WriteLn(' to: ', pathSkv); if GetFileSizeInBytes(pathLpr) = 0 then begin WriteLn('File ' + pathLpr + ' contains no data.'); Exit; end; // of if // Delete any existing output Splunk SKV file. if FileExists(pathSkv) = true then begin // File .skv already exists, delete it. Result from previous conversion. DeleteFile(pathSkv); end; skv := CTextFile.Create(pathSkv); skv.OpenFileWrite(); lpr := CTextFile.Create(pathLpr); lpr.OpenFileRead(); repeat strLine := lpr.ReadFromFile(); intCurrentLine := lpr.GetCurrentLine(); // WriteLn(AlignRight(intCurrentLine, 6) + ': ', strLine); WriteMod(intCurrentLine, STEP_MOD, 'lines'); // In USupport Library, write every STEP_MOD a line to the screen. if intCurrentLine = 1 then // When the current line = 1 it's the header, get the position of the labels. ProcessHeader(strLine) else // intCurrentLine <> 1 CheckForLineProcessing(strLine); until lpr.GetEof(); WriteLn; WriteLn('A total of ', intCurrentLine, ' lines are processed.'); lpr.CloseFile(); skv.CloseFile(); end; // of procedure ConvertLpr end. // of unit ee_convert
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmMemoryDataSet Purpose : To allow dataset like functionality with out an actual DB being attached. Date : 04-24-2000 Author : Ryan J. Mills Version : 1.92 Notes : This unit is originally based upon the work of Patrick O'Keeffe. It was at his request that I took the component over and rm'ified it. ================================================================================} unit rmMemoryDataSet; interface {$I CompilerDefines.INC} {$ifdef D6_or_higher} uses SysUtils, Windows, DB, Classes, Forms, Variants; {$else} uses SysUtils, Windows, DB, Classes, Forms; {$endif} type TSortType = (stAscending, stDescending, stAlternate); TSortArray = array of boolean; PIntArray = ^TIntArray; TIntArray = array[0..1000000] of Integer; PByteArray = ^TByteArray; TByteArray = array[0..1000000000] of Byte; TRecordBlob = packed record BlobData : PByteArray; BlobSize : LongInt; FieldNum : LongInt; end; TBlobArray = array[0..10] of TRecordBlob; TRecordData = packed record Bookmark : Integer; BookmarkFlag : TBookmarkFlag; ArraySize : Integer; Blobs : TBlobArray; Bytes : TByteArray; end; PRecordData = ^TRecordData; TFieldDefType = (fdtString, fdtInteger, fdtFloat, fdtDateTime, fdtBoolean, fdtMemo); TFieldDefItem = class(TCollectionItem) private FSize : Integer; FName : string; FFieldType : TFieldDefType; protected public procedure Assign(Source: TPersistent); override; published property Name : string read FName write FName; property Size : Integer read FSize write FSize; property FieldType : TFieldDefType read FFieldType write FFieldType; end; TFieldDefList = class(TCollection) private FInternalOwner : TComponent; function GetItem(Index : Integer) : TFieldDefItem; procedure SetItem(Index : Integer; Value : TFieldDefItem); public function Add : TFieldDefItem; constructor Create(AOwner : TComponent); property Items[Index : Integer] : TFieldDefItem read GetItem write SetItem; default; property InternalOwner : TComponent read FInternalOwner; end; // Collection item object for records TTextRecord = class(TCollectionItem) public destructor Destroy; override; protected Data : PRecordData; end; TrmLongStringField = class(TStringField) public class procedure CheckTypeSize(Value : Integer); override; function GetAsString : string; override; function GetAsVariant : Variant; override; function GetValue(var Value : string) : Boolean; procedure SetAsString(const Value : string); override; end; { TrmMemoryDataSet } TrmMemoryDataSet = class(TDataSet) private Records : TCollection; FieldOffSets : PIntArray; FFieldRoster : TFieldDefList; FRecBufSize : Integer; FCurRec : Integer; FLastBookmark : Integer; MaxFieldNo : Integer; FRecordSize : Integer; FFilterBuffer : PRecordData; FSortOrder : TSortArray; function GetRecBufSize : Integer; procedure QueryRecords; function FieldOffset(Field : TField) : Integer; function GetActiveRecBuf(var RecBuf : PRecordData) : Boolean; procedure InternalUpdate; procedure SaveRecordData(Buffer : PRecordData; Index : Integer); protected { Overriden abstract methods (required) } function AllocRecordBuffer : PChar; override; procedure FreeRecordBuffer(var Buffer : PChar); override; procedure GetBookmarkData(Buffer : PChar; Data : Pointer); override; function GetBookmarkFlag(Buffer : PChar) : TBookmarkFlag; override; function GetFieldClass(FieldType : TFieldType) : TFieldClass; override; function GetRecord(Buffer : PChar; GetMode : TGetMode; DoCheck : Boolean) : TGetResult; override; function GetRecordSize : Word; override; procedure InternalAddRecord(Buffer : Pointer; Append : Boolean); override; procedure InternalClose; override; procedure InternalDelete; override; procedure InternalFirst; override; procedure InternalGotoBookmark(Bookmark : Pointer); override; procedure InternalHandleException; override; procedure InternalInitFieldDefs; override; procedure InternalInitRecord(Buffer : PChar); override; procedure InternalLast; override; procedure InternalOpen; override; procedure InternalPost; override; procedure InternalSetToRecord(Buffer : PChar); override; function IsCursorOpen : Boolean; override; procedure SetBookmarkFlag(Buffer : PChar; Value : TBookmarkFlag); override; procedure SetBookmarkData(Buffer : PChar; Data : Pointer); override; procedure SetFieldData(Field : TField; Buffer : Pointer); override; procedure CloseBlob(Field : TField); override; protected { Additional overrides (optional) } function GetRecordCount : Integer; override; function GetRecNo : Integer; override; procedure SetRecNo(Value : Integer); override; public function CompareBookmarks(Bookmark1, Bookmark2: TBookmark): Integer; override; function CreateBlobStream(Field : TField; Mode : TBlobStreamMode) : TStream; override; constructor Create(AOwner : TComponent); override; destructor Destroy; override; function GetFieldData(Field : TField; Buffer : Pointer) : Boolean; override; procedure Sort(field : TField; direction : TSortType); function Lookup(const KeyFields : string; const KeyValues : Variant; const ResultFields : string) : Variant; override; function Locate(const KeyFields : string; const KeyValues : Variant; Options : TLocateOptions) : Boolean; override; property SortOrder : TSortArray read fSortOrder; published property FieldRoster : TFieldDefList read FFieldRoster write FFieldRoster; property Active; property OnNewRecord; property OnCalcFields; property BeforeOpen; property AfterOpen; property BeforeClose; property AfterClose; property BeforeInsert; property AfterInsert; property BeforeEdit; property AfterEdit; property BeforePost; property AfterPost; property BeforeCancel; property AfterCancel; property BeforeDelete; property AfterDelete; property BeforeScroll; property AfterScroll; property OnDeleteError; property OnEditError; property OnFilterRecord; property OnPostError; end; const RecInfoSize = SizeOf(TRecordData) - SizeOf(TByteArray); const DefaultFieldClasses : array[ftUnknown..ftTypedBinary] of TFieldClass = ( nil, (* ftUnknown *) TrmLongStringField, (* ftString *) TSmallintField, (* ftSmallint *) TIntegerField, (* ftInteger *) TWordField, (* ftWord *) TBooleanField, (* ftBoolean *) TFloatField, (* ftFloat *) TCurrencyField, (* ftCurrency *) TBCDField, (* ftBCD *) TDateField, (* ftDate *) TTimeField, (* ftTime *) TDateTimeField, (* ftDateTime *) TBytesField, (* ftBytes *) TVarBytesField, (* ftVarBytes *) TAutoIncField, (* ftAutoInc *) TBlobField, (* ftBlob *) TMemoField, (* ftMemo *) TGraphicField, (* ftGraphic *) TBlobField, (* ftFmtMemo *) TBlobField, (* ftParadoxOle *) TBlobField, (* ftDBaseOle *) TBlobField); (* ftTypedBinary *) implementation type // TResultSetBlobStream TResultSetBlobStream = class(TStream) private FField : TBlobField; FBlobIdx : LongInt; FDataSet : TrmMemoryDataSet; FBuffer : PRecordData; FMode : TBlobStreamMode; FOpened : Boolean; FModified : Boolean; FPosition : Longint; function GetBlobSize : Longint; function GetBlobOffset(FieldNum : LongInt) : LongInt; public constructor Create(Field : TBlobField; Mode : TBlobStreamMode); destructor Destroy; override; function Read(var Buffer; Count : Longint) : Longint; override; function Write(const Buffer; Count : Longint) : Longint; override; function Seek(Offset : Longint; Origin : Word) : Longint; override; procedure Truncate; end; procedure FreeBlob(Buffer : PRecordData); var Idx : LongInt; begin for Idx := 0 to 10 do begin with Buffer^.Blobs[Idx] do begin if (BlobData <> nil) and (BlobSize > 0) then FreeMem(BlobData, BlobSize); BlobData := nil; BlobSize := 0; FieldNum := 0; end; end; end; // TResultSetBlobStream // This stream is used to communicate between the Blob fields and the // underlying record collection constructor TResultSetBlobStream.Create(Field : TBlobField; Mode : TBlobStreamMode); begin FMode := Mode; FField := Field; FDataSet := FField.DataSet as TrmMemoryDataSet; if not FDataSet.GetActiveRecBuf(FBuffer) then Exit; FBlobIdx := GetBlobOffset(FField.FieldNo); if not FField.Modified then begin if Mode <> bmRead then if not (FDataSet.State in [dsEdit, dsInsert]) then DatabaseError('Not in Insert or Edit Mode'); end; FOpened := True; if Mode = bmWrite then begin Truncate; end; end; destructor TResultSetBlobStream.Destroy; begin if FOpened then begin if FModified then FField.Modified := True; end; if FModified then begin try FDataSet.DataEvent(deFieldChange, Longint(FField)); except Application.HandleException(Self); end; end; end; function TResultSetBlobStream.Read(var Buffer; Count : Longint) : Longint; begin Result := 0; if FOpened then begin if Count > Size - FPosition then begin Result := Size - FPosition end else begin Result := Count; end; if Result > 0 then begin Move(FBuffer^.Blobs[FBlobIdx].BlobData^[FPosition], Buffer, Result); Inc(FPosition, Result); end; end; end; function TResultSetBlobStream.Write(const Buffer; Count : Longint) : Longint; var Temp : Pointer; NewSize : LongInt; begin Result := 0; if FOpened then begin NewSize := FPosition + Count; if NewSize < FBuffer^.Blobs[FBlobIdx].BlobSize then begin NewSize := FBuffer^.Blobs[FBlobIdx].BlobSize; end; if (NewSize > FBuffer^.Blobs[FBlobIdx].BlobSize) or not (FModified or FField.Modified) then begin GetMem(Temp, NewSize); if (FBuffer^.Blobs[FBlobIdx].BlobData <> nil) and (FBuffer^.Blobs[FBlobIdx].BlobSize > 0) then begin Move(FBuffer^.Blobs[FBlobIdx].BlobData^, Temp^, FBuffer^.Blobs[FBlobIdx].BlobSize); if (FModified or FField.Modified) then begin FreeBlob(FBuffer); end; end; FBuffer^.Blobs[FBlobIdx].BlobData := Temp; end; Move(Buffer, FBuffer^.Blobs[FBlobIdx].BlobData^[FPosition], Count); Inc(FPosition, Count); if FPosition > FBuffer^.Blobs[FBlobIdx].BlobSize then begin FBuffer^.Blobs[FBlobIdx].BlobSize := FPosition; end; Result := Count; FModified := True; end; end; function TResultSetBlobStream.Seek(Offset : Longint; Origin : Word) : Longint; begin case Origin of soFromBeginning : FPosition := Offset; soFromCurrent : Inc(FPosition, Offset); soFromEnd : FPosition := GetBlobSize + Offset; end; Result := FPosition; end; procedure TResultSetBlobStream.Truncate; begin if FOpened then begin FPosition := 0; if FField.Modified then begin FreeBlob(FBuffer); end; FBuffer^.Blobs[FBlobIdx].BlobData := nil; FBuffer^.Blobs[FBlobIdx].BlobSize := 0; FModified := True; end; end; function TResultSetBlobStream.GetBlobSize : Longint; begin Result := 0; if FOpened then begin Result := FBuffer^.Blobs[FBlobIdx].BlobSize; end; end; function TResultSetBlobStream.GetBlobOffset(FieldNum : LongInt) : LongInt; var Idx : LongInt; begin Result := -1; for Idx := 0 to 10 do begin if FBuffer^.Blobs[Idx].FieldNum = FieldNum then begin Result := Idx; Break; end; end; if result < 0 then for idx := 0 to 10 do if FBuffer^.Blobs[Idx].FieldNum = -1 then begin FBuffer^.Blobs[Idx].FieldNum := FieldNum; result := idx; break; end; if result < 0 then DatabaseError('Too many blobs', self.FDataSet); end; (* * TrmLongStringField - implementation *) class procedure TrmLongStringField.CheckTypeSize(Value : Integer); begin (* * Just don't check. Any string size is valid. *) end; function TrmLongStringField.GetAsString : string; begin if not GetValue(Result) then Result := ''; end; function TrmLongStringField.GetAsVariant : Variant; var S : string; begin if GetValue(S) then Result := S else Result := Null; end; function TrmLongStringField.GetValue(var Value : string) : Boolean; var Buffer : PChar; begin GetMem(Buffer, Size + 1); try Result := GetData(Buffer); if Result then begin Value := Trim(string(Buffer)); if Transliterate and (Value <> '') then DataSet.Translate(PChar(Value), PChar(Value), False); end finally FreeMem(Buffer); end; end; procedure TrmLongStringField.SetAsString(const Value : string); var Buffer : PChar; begin GetMem(Buffer, Size + 1); try StrLCopy(Buffer, PChar(Value), Size); if Transliterate then DataSet.Translate(Buffer, Buffer, True); SetData(Buffer); finally FreeMem(Buffer); end; end; destructor TTextRecord.Destroy; begin if Data <> nil then begin FreeMem(Data, Data^.ArraySize + RecInfoSize); end; inherited; end; { TrmMemoryDataSet } { This method is called by TDataSet.Open and also when FieldDefs need to be updated (usually by the DataSet designer). Everything which is allocated or initialized in this method should also be freed or uninitialized in the InternalClose method. } constructor TrmMemoryDataSet.Create(AOwner : TComponent); begin inherited Create(AOwner); FFieldRoster := TFieldDefList.Create(Self); end; destructor TrmMemoryDataSet.Destroy; begin FFieldRoster.Free; inherited Destroy; end; function TrmMemoryDataSet.GetFieldClass(FieldType : TFieldType) : TFieldClass; begin Result := DefaultFieldClasses[FieldType]; end; // Calculate Buffer Size. Can only be called after BindFields function TrmMemoryDataSet.GetRecBufSize : Integer; var i : Integer; begin MaxFieldNo := 0; for i := 0 to FieldCount - 1 do with Fields[i] do if FieldNo > MaxFieldNo then MaxFieldNo := FieldNo; Inc(MaxFieldNo); GetMem(FieldOffsets, MaxFieldNo * SizeOf(Integer)); Result := 0; FRecordSize := 0; for i := 0 to FieldCount - 1 do with Fields[i] do begin if FieldNo >= 0 then FieldOffsets^[FieldNo] := FRecordSize; Inc(Result, DataSize + 1); Inc(FRecordSize, DataSize + 1); end; Inc(Result, RecInfoSize); end; procedure TrmMemoryDataSet.QueryRecords; begin // Clear the record collection Records.Clear; end; function TrmMemoryDataSet.FieldOffset(Field : TField) : Integer; begin Result := FieldOffsets[Field.FieldNo]; end; procedure TrmMemoryDataSet.InternalOpen; begin FieldOffsets := nil; // Initialize our internal position. // We use -1 to indicate the "crack" before the first record. FCurRec := -1; // Tell TDataSet how big our Bookmarks are BookmarkSize := SizeOf(Integer); InternalInitFieldDefs; // Create TField components when no persistent fields have been created if DefaultFields then CreateFields; // Bind the TField components to the physical fields BindFields(True); // Create collection for records Records := TCollection.Create(TTextRecord); // Calculate the size of the record buffers. // Note: This is NOT the same as the RecordSize property which // only gets the size of the data in the record buffer FRecBufSize := GetRecBufSize; // Query records to fill collection QueryRecords; SetLength(fSortOrder, fields.Count); end; procedure TrmMemoryDataSet.InternalClose; begin // Free the record collection Records.Free; Records := nil; // Destroy the TField components if no persistent fields if DefaultFields then DestroyFields; // Reset these internal flags FLastBookmark := 0; FCurRec := -1; // Free memory for Field offset array if FieldOffsets <> nil then FreeMem(FieldOffsets, MaxFieldNo * SizeOf(Integer)); FieldOffsets := nil; end; function TrmMemoryDataSet.IsCursorOpen : Boolean; begin Result := Assigned(Records); end; procedure TrmMemoryDataSet.InternalInitFieldDefs; var i : Integer; FieldName : string; FieldRequired : boolean; FieldSize : Integer; FieldType : TFieldType; FieldNo : Integer; begin FieldDefs.Clear; // Create a field in the dataset for each field in the query if FFieldRoster.Count = 0 then raise Exception.Create('There are no fields in the Field Roster'); FieldNo := 1; for i := 0 to FFieldRoster.Count - 1 do begin FieldName := FFieldRoster.Items[i].Name; FieldRequired := True; FieldSize := FFieldRoster.Items[i].Size; case FFieldRoster.Items[i].FieldType of fdtString : FieldType := ftString; fdtInteger : FieldType := ftInteger; fdtFloat : FieldType := ftFloat; fdtDateTime : FieldType := ftDateTime; fdtBoolean : FieldType := ftBoolean; fdtMemo : FieldType := ftMemo; else FieldType := ftString; end; if not (FieldType in [ftString]) then FieldSize := 0; TFieldDef.Create(FieldDefs, FieldName, FieldType, FieldSize, FieldRequired, FieldNo); Inc(FieldNo); end; end; procedure TrmMemoryDataSet.InternalHandleException; begin Application.HandleException(Self); end; procedure TrmMemoryDataSet.InternalGotoBookmark(Bookmark : Pointer); var i, b : Integer; begin b := PInteger(Bookmark)^; if (b - 1 > 0) and (b - 1 < Records.Count) then begin if b = TTextRecord(Records.Items[b - 1]).Data^.Bookmark then begin FCurRec := b - 1; Exit; end; end; for i := 0 to Records.Count - 1 do begin if PInteger(Bookmark)^ = TTextRecord(Records.Items[i]).Data^.Bookmark then begin FCurRec := i; Exit; end; end; DatabaseError('Bookmark not found'); end; procedure TrmMemoryDataSet.InternalSetToRecord(Buffer : PChar); begin InternalGotoBookmark(@PRecordData(Buffer).Bookmark); end; function TrmMemoryDataSet.GetBookmarkFlag(Buffer : PChar) : TBookmarkFlag; begin Result := PRecordData(Buffer).BookmarkFlag; end; procedure TrmMemoryDataSet.SetBookmarkFlag(Buffer : PChar; Value : TBookmarkFlag); begin PRecordData(Buffer).BookmarkFlag := Value; end; procedure TrmMemoryDataSet.GetBookmarkData(Buffer : PChar; Data : Pointer); begin PInteger(Data)^ := PRecordData(Buffer).Bookmark; end; procedure TrmMemoryDataSet.SetBookmarkData(Buffer : PChar; Data : Pointer); begin PRecordData(Buffer).Bookmark := PInteger(Data)^; end; function TrmMemoryDataSet.GetRecordSize : Word; begin Result := FRecordSize; end; function TrmMemoryDataSet.AllocRecordBuffer : PChar; var b : PRecordData; Idx : Integer; begin GetMem(Result, FRecBufSize); b := PRecordData(Result); b^.ArraySize := FRecBufSize - RecInfoSize; for Idx := 0 to 10 do begin b^.Blobs[Idx].BlobData := nil; b^.Blobs[Idx].BlobSize := 0; b^.Blobs[Idx].FieldNum := 0; end; end; procedure TrmMemoryDataSet.FreeRecordBuffer(var Buffer : PChar); begin FreeMem(Buffer, FRecBufSize); end; function TrmMemoryDataSet.GetRecord(Buffer : PChar; GetMode : TGetMode; DoCheck : Boolean) : TGetResult; begin Result := grOK; case GetMode of gmNext : if FCurRec < Records.Count - 1 then Inc(FCurRec) else Result := grEOF; gmPrior : if FCurRec <= 0 then Result := grBOF else Dec(FCurRec); gmCurrent : if (FCurRec < 0) or (FCurRec >= Records.Count) then begin Result := grError end; end; if Result = grOK then begin Move(TTextRecord(Records.Items[FCurRec]).Data^, Buffer^, FRecBufSize); with PRecordData(Buffer)^ do BookmarkFlag := bfCurrent; end else if (Result = grError) and DoCheck then DatabaseError('No Records'); end; procedure TrmMemoryDataSet.InternalInitRecord(Buffer : PChar); var Idx : Integer; begin FillChar(PRecordData(Buffer)^.Bytes[0], FRecordSize + CalcFieldsSize, 1); for Idx := 0 to 10 do begin PRecordData(Buffer)^.Blobs[Idx].BlobData := nil; PRecordData(Buffer)^.Blobs[Idx].BlobSize := 0; PRecordData(Buffer)^.Blobs[Idx].FieldNum := -1; end; end; function TrmMemoryDataSet.GetActiveRecBuf(var RecBuf : PRecordData) : Boolean; var i : Integer; begin case State of dsBrowse : if IsEmpty then RecBuf := nil else RecBuf := PRecordData(ActiveBuffer); dsEdit, dsInsert : RecBuf := PRecordData(ActiveBuffer); dsNewValue, dsCurValue : RecBuf := PRecordData(ActiveBuffer); dsFilter : RecBuf := PRecordData(FFilterBuffer); dsOldValue : begin i := FCurRec; if i < 0 then i := 0; if i < Records.Count then RecBuf := TTextRecord(Records.Items[i]).Data else RecBuf := nil; end; else RecBuf := nil; end; Result := RecBuf <> nil; end; function TrmMemoryDataSet.GetFieldData(Field : TField; Buffer : Pointer) : Boolean; var b : PRecordData; begin Result := False; if not GetActiveRecBuf(b) then Exit; if b^.Bytes[FieldOffset(Field)] = 0 then begin if Buffer <> nil then Move(b^.Bytes[FieldOffset(Field) + 1], Buffer^, Field.DataSize); Result := True; end; end; procedure TrmMemoryDataSet.SetFieldData(Field : TField; Buffer : Pointer); var b : PRecordData; begin if not GetActiveRecBuf(b) then Exit; if State in [dsEdit, dsInsert] then Field.Validate(Buffer); if Buffer = nil then b^.Bytes[FieldOffset(Field)] := 1 else begin b^.Bytes[FieldOffset(Field)] := 0; Move(Buffer^, b^.Bytes[FieldOffset(Field) + 1], Field.DataSize); end; if not (State in [dsCalcFields, dsFilter, dsNewValue]) then DataEvent(deFieldChange, Longint(Field)); end; procedure TrmMemoryDataSet.InternalFirst; begin FCurRec := -1; end; procedure TrmMemoryDataSet.InternalLast; begin FCurRec := Records.Count; end; procedure TrmMemoryDataSet.SaveRecordData(Buffer : PRecordData; Index : Integer); var b : PRecordData; Idx : LongInt; blobStore : TBlobArray; begin b := TTextRecord(Records.Items[Index]).Data; begin blobStore := b^.Blobs; Move(Buffer^, b^, FRecBufSize); for Idx := 0 to 10 do if Buffer^.Blobs[Idx].BlobData <> blobStore[Idx].BlobData then begin if blobStore[Idx].BlobData <> nil then freeMem(blobStore[Idx].BlobData); GetMem(b^.Blobs[Idx].BlobData, Buffer^.Blobs[Idx].BlobSize); Move(Buffer^.Blobs[Idx].BlobData^, b^.Blobs[Idx].BlobData^, Buffer^.Blobs[Idx].BlobSize); b^.Blobs[Idx].BlobSize := Buffer^.Blobs[Idx].BlobSize; b^.Blobs[Idx].FieldNum := Buffer^.Blobs[Idx].FieldNum; end end; end; procedure TrmMemoryDataSet.InternalUpdate; var b : PRecordData; begin if not GetActiveRecBuf(b) then Exit; // Update the record in the collection SaveRecordData(b, FCurRec); end; procedure TrmMemoryDataSet.InternalPost; var b : PRecordData; begin if State = dsEdit then InternalUpdate else begin GetActiveRecBuf(b); InternalAddRecord(b, False); end; end; procedure TrmMemoryDataSet.InternalAddRecord(Buffer : Pointer; Append : Boolean); var b : PRecordData; r : TTextRecord; begin if not GetActiveRecBuf(b) then Exit; if b <> Buffer then raise Exception.Create('InternalAddRecord: b <> buffer'); if Append then InternalLast; r := TTextRecord.Create(Records); if FCurRec >= 0 then r.Index := FCurRec; r.Data := PRecordData(AllocRecordBuffer); SaveRecordData(b, r.Index); Inc(FLastBookmark); r.Data^.Bookmark := FLastBookmark; r.Data^.BookmarkFlag := bfCurrent; end; procedure TrmMemoryDataSet.InternalDelete; var b : PRecordData; begin if not GetActiveRecBuf(b) then Exit; Records.Items[FCurRec].Free; end; function TrmMemoryDataSet.GetRecordCount : Longint; begin Result := Records.Count; end; function TrmMemoryDataSet.GetRecNo : Longint; begin UpdateCursorPos; if (FCurRec = -1) and (RecordCount > 0) then Result := 1 else Result := FCurRec + 1; end; procedure TrmMemoryDataSet.SetRecNo(Value : Integer); begin if (Value >= 0) and (Value < Records.Count) then begin FCurRec := Value - 1; Resync([]); end; end; function TrmMemoryDataSet.CompareBookmarks(Bookmark1, Bookmark2: TBookmark): Integer; begin if (PInteger(Bookmark1)^ = PInteger(Bookmark2)^) then Result := 0 else if (PInteger(Bookmark1)^ > PInteger(Bookmark2)^) then Result := 1 else Result := -1 end; procedure TrmMemoryDataSet.Sort(field : TField; direction : TSortType); var buffer : pointer; dir : boolean; function GetRecordValue(index : integer) : variant; var SaveState : TDataSetState; oldFilter : pointer; begin fCurRec := index; GetRecord(buffer, gmCurrent, FALSE); // Get the actual record oldFilter := FFilterBuffer; // Save off the old filter buffer SaveState := SetTempState(dsFilter); // Tell the dataset we are filtering try FFilterBuffer := pointer(buffer); // Point the filter buf to the supplied buf result := field.Value; finally RestoreState(SaveState); // Put the state back the way it was FFilterBuffer := oldFilter; // Put the old filter buffer back end; end; function CompareCell(c : integer; s2 : variant) : double; begin case field.DataType of ftString : result := CompareStr(GetRecordValue(c), s2); else result := GetRecordValue(c) - s2; end; if dir then result := -result; end; procedure QuickSort(iLo, iHi : Integer); var Lo, Hi : Integer; mid : variant; tempRec : PRecordData; begin Lo := iLo; Hi := iHi; Mid := GetRecordValue((Lo + Hi) div 2); repeat while (lo < RecordCount) and (CompareCell(Lo, Mid) < 0) do Inc(Lo); while (hi >= 0) and (CompareCell(Hi, Mid) > 0) do Dec(Hi); if Lo <= Hi then begin if lo <> hi then begin tempRec := TTextRecord(Records.Items[lo]).Data; TTextRecord(records.Items[lo]).Data := TTextRecord(records.Items[hi]).Data; TTextRecord(records.Items[hi]).Data := tempRec; end; inc(lo); dec(hi); end; until Lo > Hi; if Hi > iLo then QuickSort(iLo, Hi); if Lo < iHi then QuickSort(Lo, iHi); end; begin if (field.IsBlob) then raise Exception.Create('Sorting not supported on blob fields (Field: ' + field.name + ').'); case direction of stAscending : dir := FALSE; stDescending : dir := TRUE; stAlternate : begin dir := fSortOrder[field.Index]; fSortOrder[field.Index] := not fSortOrder[field.Index]; end; end; DisableControls; try GetMem(buffer, GetRecBufSize); try QuickSort(0, RecordCount - 1); except end; finally FreeMem(buffer); EnableControls; First; end; end; { TFieldDefList } function TFieldDefList.Add : TFieldDefItem; begin Result := TFieldDefItem(inherited Add); end; constructor TFieldDefList.Create(AOwner : TComponent); begin inherited Create(TFieldDefItem); FInternalOwner := AOwner; end; function TFieldDefList.GetItem(Index : Integer) : TFieldDefItem; begin Result := TFieldDefItem(inherited GetItem(Index)); end; procedure TFieldDefList.SetItem(Index : Integer; Value : TFieldDefItem); begin inherited SetItem(Index, Value); end; procedure TrmMemoryDataSet.CloseBlob(Field : TField); begin FreeBlob(PRecordData(ActiveBuffer)); end; function TrmMemoryDataSet.CreateBlobStream(Field : TField; Mode : TBlobStreamMode) : TStream; begin Result := TResultSetBlobStream.Create(Field as TBlobField, Mode); end; function VarEquals(const V1, V2 : Variant) : Boolean; begin Result := False; try Result := V1 = V2; except end; end; function TrmMemoryDataSet.Lookup(const KeyFields : string; const KeyValues : Variant; const ResultFields : string) : Variant; var b : TBookMark; keyf : TField; begin result := FALSE; b := GetBookmark; DisableControls; try keyf := fieldByName(KeyFields); first; while not eof do begin if VarEquals(keyf.value, keyValues) then begin result := fieldByName(resultFields).Value; break; end; moveBy(1); end; finally GotoBookmark(b); EnableControls; end; end; function TrmMemoryDataSet.Locate(const KeyFields : string; const KeyValues : Variant; Options : TLocateOptions) : Boolean; var b : TBookMark; keyf : TField; begin result := FALSE; b := GetBookmark; DisableControls; try keyf := fieldByName(KeyFields); first; while not eof do begin if VarEquals(keyf.value, KeyValues) then begin result := TRUE; b := nil; break; end; MoveBy(1); end; finally if b <> nil then GotoBookmark(b); EnableControls; end; end; { TFieldDefItem } procedure TFieldDefItem.Assign(Source: TPersistent); begin if (Source is TFieldDefItem) then begin FName := TFieldDefItem(Source).Name; FSize := TFieldDefItem(Source).Size; FFieldType := TFieldDefItem(Source).FieldType; end else inherited Assign(Source); end; initialization RegisterClass(TrmLongStringField); end.
{Используя подпрграммы составить прграмму. Даны 2 матрицы A(n,m) и B(n,m). Составить матрицу C(n,m) следующим образом: Cij=среднее геометрическое /Aij/и /Bij/} Program P3; type matrix = array[1..20, 1..20] of real; var n, m, i, j: integer; x, y, z: matrix; procedure SM(a, b: matrix; var c: matrix); var i, j: integer; begin for i := 1 to n do for j := 1 to m do begin c[i, j] := sqrt(abs(a[i, j]) * abs(b[i, j])); end; end; begin writeln('n='); readln(n); writeln('m='); readln(m); for i := 1 to n do for j := 1 to m do read(x[i, j]); writeln('n='); readln(n); writeln('m='); readln(m); for i := 1 to n do for j := 1 to m do read(y[i, j]); SM(x, y, z); for i := 1 to n do begin for j := 1 to m do write(x[i, j]:7:2); writeln; end; writeln('**********************'); for i := 1 to n do begin for j := 1 to m do write(y[i, j]:7:2); writeln; end; writeln('**********************'); for i := 1 to n do begin for j := 1 to m do write(z[i, j]:7:2); writeln; end; readln; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Support for Windows WAV format. } unit VXS.FileWAV; interface {$I VXScene.inc} uses System.Classes, {$IFDEF MSWINDOWS} MMSystem, {$ENDIF} VXS.ApplicationFileIO, VXS.SoundFileObjects; type { Support for Windows WAV format. } TVXWAVFile = class(TVXSoundFile) private {$IFDEF MSWINDOWS} waveFormat: TWaveFormatEx; pcmOffset: Integer; {$ENDIF} FPCMDataLength: Integer; data: array of Byte; // used to store WAVE bitstream protected public function CreateCopy(AOwner: TPersistent): TVXDataFile; override; class function Capabilities: TVXDataFileCapabilities; override; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; procedure PlayOnWaveOut; override; function WAVData: Pointer; override; function WAVDataSize: Integer; override; function PCMData: Pointer; override; function LengthInBytes: Integer; override; end; //================================================================= implementation //================================================================= {$IFDEF MSWINDOWS} type TRIFFChunkInfo = packed record ckID: FOURCC; ckSize: LongInt; end; const WAVE_Format_ADPCM = 2; {$ENDIF} // ------------------ // ------------------ TVXWAVFile ------------------ // ------------------ function TVXWAVFile.CreateCopy(AOwner: TPersistent): TVXDataFile; begin Result := inherited CreateCopy(AOwner); if Assigned(Result) then begin {$IFDEF MSWINDOWS} TVXWAVFile(Result).waveFormat := waveFormat; {$ENDIF} TVXWAVFile(Result).data := Copy(data); end; end; class function TVXWAVFile.Capabilities: TVXDataFileCapabilities; begin Result := [dfcRead, dfcWrite]; end; procedure TVXWAVFile.LoadFromStream(Stream: TStream); {$IFDEF MSWINDOWS} var ck: TRIFFChunkInfo; dw, bytesToGo, startPosition, totalSize: Integer; id: Cardinal; dwDataOffset, dwDataSamples, dwDataLength: Integer; begin // this WAVE loading code is an adaptation of the 'minimalist' sample from // the Microsoft DirectX SDK. Assert(Assigned(Stream)); dwDataOffset := 0; dwDataLength := 0; // Check RIFF Header startPosition := Stream.Position; Stream.Read(ck, SizeOf(TRIFFChunkInfo)); Assert((ck.ckID = mmioStringToFourCC('RIFF', 0)), 'RIFF required'); totalSize := ck.ckSize + SizeOf(TRIFFChunkInfo); Stream.Read(id, SizeOf(Integer)); Assert((id = mmioStringToFourCC('WAVE', 0)), 'RIFF-WAVE required'); // lookup for 'fmt ' repeat Stream.Read(ck, SizeOf(TRIFFChunkInfo)); bytesToGo := ck.ckSize; if (ck.ckID = mmioStringToFourCC('fmt ', 0)) then begin if waveFormat.wFormatTag = 0 then begin dw := ck.ckSize; if dw > SizeOf(TWaveFormatEx) then dw := SizeOf(TWaveFormatEx); Stream.Read(waveFormat, dw); bytesToGo := ck.ckSize - dw; end; // other 'fmt ' chunks are ignored (?) end else if (ck.ckID = mmioStringToFourCC('fact', 0)) then begin if (dwDataSamples = 0) and (waveFormat.wFormatTag = WAVE_Format_ADPCM) then begin Stream.Read(dwDataSamples, SizeOf(LongInt)); Dec(bytesToGo, SizeOf(LongInt)); end; // other 'fact' chunks are ignored (?) end else if (ck.ckID = mmioStringToFourCC('data', 0)) then begin dwDataOffset := Stream.Position - startPosition; dwDataLength := ck.ckSize; Break; end; // all other sub-chunks are ignored, move to the next chunk Stream.Seek(bytesToGo, soFromCurrent); until Stream.Position = 2048; // this should never be reached // Only PCM wave format is recognized // Assert((waveFormat.wFormatTag=Wave_Format_PCM), 'PCM required'); // seek start of data pcmOffset := dwDataOffset; FPCMDataLength := dwDataLength; SetLength(data, totalSize); Stream.Position := startPosition; if totalSize > 0 then Stream.Read(data[0], totalSize); // update Sampling data with waveFormat do begin Sampling.Frequency := nSamplesPerSec; Sampling.NbChannels := nChannels; Sampling.BitsPerSample := wBitsPerSample; end; {$ELSE} begin Assert(Assigned(Stream)); SetLength(data, Stream.Size); if Length(data) > 0 then Stream.Read(data[0], Length(data)); {$ENDIF} end; procedure TVXWAVFile.SaveToStream(Stream: TStream); begin if Length(data) > 0 then Stream.Write(data[0], Length(data)); end; procedure TVXWAVFile.PlayOnWaveOut; begin {$IFDEF MSWINDOWS} PlaySound(WAVData, 0, SND_ASYNC + SND_MEMORY); {$ENDIF} // GLSoundFileObjects.PlayOnWaveOut(PCMData, LengthInBytes, waveFormat); end; function TVXWAVFile.WAVData: Pointer; begin if Length(data) > 0 then Result := @data[0] else Result := nil; end; function TVXWAVFile.WAVDataSize: Integer; begin Result := Length(data); end; function TVXWAVFile.PCMData: Pointer; begin {$IFDEF MSWINDOWS} if Length(data) > 0 then Result := @data[pcmOffset] else Result := nil; {$ELSE} Result := nil; {$ENDIF} end; function TVXWAVFile.LengthInBytes: Integer; begin Result := FPCMDataLength; end; //------------------------------------------------- initialization //------------------------------------------------- RegisterSoundFileFormat('wav', 'Windows WAV files', TVXWAVFile); end.
inherited frmOptionsPatientSelection: TfrmOptionsPatientSelection Left = 345 Top = 133 HelpContext = 9060 BorderIcons = [biSystemMenu, biHelp] BorderStyle = bsDialog Caption = 'Patient Selection Defaults' ClientHeight = 413 ClientWidth = 414 HelpFile = 'CPRSWT.HLP' Position = poScreenCenter OnCreate = FormCreate OnShow = FormShow PixelsPerInch = 96 TextHeight = 13 object lblClinicDays: TLabel [0] Left = 179 Top = 162 Width = 101 Height = 13 Caption = 'Clinic for day of week' end object lblMonday: TLabel [1] Left = 179 Top = 184 Width = 41 Height = 13 Caption = 'Monday:' end object lblTuesday: TLabel [2] Left = 179 Top = 213 Width = 44 Height = 13 Caption = 'Tuesday:' end object lblWednesday: TLabel [3] Left = 179 Top = 241 Width = 60 Height = 13 Caption = 'Wednesday:' end object lblThursday: TLabel [4] Left = 179 Top = 270 Width = 47 Height = 13 Caption = 'Thursday:' end object lblFriday: TLabel [5] Left = 179 Top = 298 Width = 31 Height = 13 Caption = 'Friday:' end object lblSaturday: TLabel [6] Left = 179 Top = 327 Width = 45 Height = 13 Caption = 'Saturday:' end object lblSunday: TLabel [7] Left = 179 Top = 355 Width = 39 Height = 13 Caption = 'Sunday:' end object lblVisitStart: TLabel [8] Left = 20 Top = 321 Width = 25 Height = 13 Alignment = taRightJustify Caption = 'Start:' end object lblVisitStop: TLabel [9] Left = 20 Top = 352 Width = 25 Height = 13 Alignment = taRightJustify Caption = 'Stop:' end object lbWard: TLabel [10] Left = 179 Top = 136 Width = 29 Height = 13 Caption = 'Ward:' end object lblTeam: TLabel [11] Left = 179 Top = 107 Width = 51 Height = 13 Caption = 'Team/List:' end object lblTreating: TLabel [12] Left = 179 Top = 77 Width = 88 Height = 13 Caption = 'Treating Specialty:' end object lblProvider: TLabel [13] Left = 179 Top = 50 Width = 79 Height = 13 Caption = 'Primary Provider:' end object lblVisitDateRange: TMemo [14] Left = 20 Top = 255 Width = 133 Height = 61 TabStop = False BorderStyle = bsNone Color = clBtnFace Lines.Strings = ( 'Display patients that have ' 'clinic appointments within ' 'this date range.') ReadOnly = True TabOrder = 18 end object lblInfo: TMemo [15] Left = 8 Top = 6 Width = 393 Height = 27 TabStop = False BorderStyle = bsNone Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] Lines.Strings = ( 'The values on the right will be defaults for selecting patients ' + 'depending on the list ' 'source selected. Combination uses the criteria defined using Sou' + 'rce Combinations.') ParentFont = False ReadOnly = True TabOrder = 19 end object pnlBottom: TPanel [16] Left = 0 Top = 380 Width = 414 Height = 33 HelpContext = 9060 Align = alBottom BevelOuter = bvNone ParentColor = True TabOrder = 17 object bvlBottom: TBevel Left = 0 Top = 0 Width = 414 Height = 2 Align = alTop end object btnOK: TButton Left = 251 Top = 8 Width = 75 Height = 22 HelpContext = 9996 Caption = 'OK' ModalResult = 1 TabOrder = 0 OnClick = btnOKClick end object btnCancel: TButton Left = 331 Top = 8 Width = 75 Height = 22 HelpContext = 9997 Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 1 end end object cboProvider: TORComboBox [17] Left = 285 Top = 48 Width = 121 Height = 21 HelpContext = 9063 Style = orcsDropDown AutoSelect = True Caption = 'Primary Provider' Color = clWindow DropDownCount = 8 ItemHeight = 13 ItemTipColor = clWindow ItemTipEnable = True ListItemsOnly = True LongList = True LookupPiece = 2 MaxLength = 0 Pieces = '2,3' Sorted = True SynonymChars = '<>' TabOrder = 6 OnExit = cboProviderExit OnKeyUp = cboProviderKeyUp OnNeedData = cboProviderNeedData CharsNeedMatch = 1 end object cboTreating: TORComboBox [18] Left = 285 Top = 75 Width = 121 Height = 21 HelpContext = 9064 Style = orcsDropDown AutoSelect = True Caption = 'Treating Specialty' Color = clWindow DropDownCount = 8 ItemHeight = 13 ItemTipColor = clWindow ItemTipEnable = True ListItemsOnly = False LongList = False LookupPiece = 0 MaxLength = 0 Pieces = '2' Sorted = True SynonymChars = '<>' TabOrder = 7 OnExit = cboProviderExit OnKeyUp = cboProviderKeyUp CharsNeedMatch = 1 end object cboTeam: TORComboBox [19] Left = 285 Top = 104 Width = 121 Height = 21 HelpContext = 9065 Style = orcsDropDown AutoSelect = True Caption = 'Team/List' Color = clWindow DropDownCount = 8 ItemHeight = 13 ItemTipColor = clWindow ItemTipEnable = True ListItemsOnly = False LongList = False LookupPiece = 0 MaxLength = 0 Pieces = '2' Sorted = True SynonymChars = '<>' TabOrder = 8 OnExit = cboProviderExit OnKeyUp = cboProviderKeyUp CharsNeedMatch = 1 end object cboWard: TORComboBox [20] Left = 285 Top = 132 Width = 121 Height = 21 HelpContext = 9066 Style = orcsDropDown AutoSelect = True Caption = 'Ward' Color = clWindow DropDownCount = 8 ItemHeight = 13 ItemTipColor = clWindow ItemTipEnable = True ListItemsOnly = False LongList = False LookupPiece = 0 MaxLength = 0 Pieces = '2' Sorted = True SynonymChars = '<>' TabOrder = 9 OnExit = cboProviderExit OnKeyUp = cboProviderKeyUp CharsNeedMatch = 1 end object cboMonday: TORComboBox [21] Left = 285 Top = 181 Width = 121 Height = 21 HelpContext = 9067 Style = orcsDropDown AutoSelect = True Caption = 'Monday' Color = clWindow DropDownCount = 8 ItemHeight = 13 ItemTipColor = clWindow ItemTipEnable = True ListItemsOnly = True LongList = True LookupPiece = 0 MaxLength = 0 Pieces = '2' Sorted = True SynonymChars = '<>' TabOrder = 10 OnExit = cboProviderExit OnKeyUp = cboProviderKeyUp OnNeedData = cboMondayNeedData CharsNeedMatch = 1 end object cboTuesday: TORComboBox [22] Left = 285 Top = 210 Width = 121 Height = 21 HelpContext = 9067 Style = orcsDropDown AutoSelect = True Caption = 'Tuesday' Color = clWindow DropDownCount = 8 ItemHeight = 13 ItemTipColor = clWindow ItemTipEnable = True ListItemsOnly = True LongList = True LookupPiece = 0 MaxLength = 0 Pieces = '2' Sorted = True SynonymChars = '<>' TabOrder = 11 OnExit = cboProviderExit OnKeyUp = cboProviderKeyUp OnNeedData = cboTuesdayNeedData CharsNeedMatch = 1 end object cboWednesday: TORComboBox [23] Left = 285 Top = 238 Width = 121 Height = 21 HelpContext = 9067 Style = orcsDropDown AutoSelect = True Caption = 'Wednesday' Color = clWindow DropDownCount = 8 ItemHeight = 13 ItemTipColor = clWindow ItemTipEnable = True ListItemsOnly = True LongList = True LookupPiece = 0 MaxLength = 0 Pieces = '2' Sorted = True SynonymChars = '<>' TabOrder = 12 OnExit = cboProviderExit OnKeyUp = cboProviderKeyUp OnNeedData = cboWednesdayNeedData CharsNeedMatch = 1 end object cboThursday: TORComboBox [24] Left = 285 Top = 267 Width = 121 Height = 21 HelpContext = 9067 Style = orcsDropDown AutoSelect = True Caption = 'Thursday' Color = clWindow DropDownCount = 8 ItemHeight = 13 ItemTipColor = clWindow ItemTipEnable = True ListItemsOnly = True LongList = True LookupPiece = 0 MaxLength = 0 Pieces = '2' Sorted = True SynonymChars = '<>' TabOrder = 13 OnExit = cboProviderExit OnKeyUp = cboProviderKeyUp OnNeedData = cboThursdayNeedData CharsNeedMatch = 1 end object cboFriday: TORComboBox [25] Left = 285 Top = 295 Width = 121 Height = 21 HelpContext = 9067 Style = orcsDropDown AutoSelect = True Caption = 'Friday' Color = clWindow DropDownCount = 8 ItemHeight = 13 ItemTipColor = clWindow ItemTipEnable = True ListItemsOnly = True LongList = True LookupPiece = 0 MaxLength = 0 Pieces = '2' Sorted = True SynonymChars = '<>' TabOrder = 14 OnExit = cboProviderExit OnKeyUp = cboProviderKeyUp OnNeedData = cboFridayNeedData CharsNeedMatch = 1 end object cboSaturday: TORComboBox [26] Left = 285 Top = 324 Width = 121 Height = 21 HelpContext = 9067 Style = orcsDropDown AutoSelect = True Caption = 'Saturday' Color = clWindow DropDownCount = 8 ItemHeight = 13 ItemTipColor = clWindow ItemTipEnable = True ListItemsOnly = True LongList = True LookupPiece = 0 MaxLength = 0 Pieces = '2' Sorted = True SynonymChars = '<>' TabOrder = 15 OnExit = cboProviderExit OnKeyUp = cboProviderKeyUp OnNeedData = cboSaturdayNeedData CharsNeedMatch = 1 end object cboSunday: TORComboBox [27] Left = 285 Top = 352 Width = 121 Height = 21 HelpContext = 9067 Style = orcsDropDown AutoSelect = True Caption = 'Sunday' Color = clWindow DropDownCount = 8 ItemHeight = 13 ItemTipColor = clWindow ItemTipEnable = True ListItemsOnly = True LongList = True LookupPiece = 0 MaxLength = 0 Pieces = '2' Sorted = True SynonymChars = '<>' TabOrder = 16 OnExit = cboProviderExit OnKeyUp = cboProviderKeyUp OnNeedData = cboSundayNeedData CharsNeedMatch = 1 end object txtVisitStart: TCaptionEdit [28] Tag = -180 Left = 49 Top = 319 Width = 79 Height = 21 HelpContext = 9068 TabOrder = 2 Text = '0' OnExit = txtVisitStartExit OnKeyPress = txtVisitStartKeyPress OnKeyUp = txtVisitStartKeyUp Caption = 'Start' end object txtVisitStop: TCaptionEdit [29] Tag = 30 Left = 48 Top = 348 Width = 79 Height = 21 HelpContext = 9069 TabOrder = 4 Text = '0' OnExit = txtVisitStopExit OnKeyPress = txtVisitStopKeyPress OnKeyUp = txtVisitStopKeyUp Caption = 'Stop' end object spnVisitStart: TUpDown [30] Tag = -180 Left = 128 Top = 319 Width = 16 Height = 21 HelpContext = 9068 Associate = txtVisitStart Min = -999 Max = 999 TabOrder = 3 Thousands = False OnClick = spnVisitStartClick end object spnVisitStop: TUpDown [31] Tag = 30 Left = 127 Top = 348 Width = 16 Height = 21 HelpContext = 9069 Associate = txtVisitStop Min = -999 Max = 999 TabOrder = 5 Thousands = False OnClick = spnVisitStopClick end object radListSource: TRadioGroup [32] Left = 16 Top = 38 Width = 145 Height = 105 HelpContext = 9061 Caption = 'List Source ' ItemIndex = 0 Items.Strings = ( 'Primary &Provider' 'Treating &Specialty' 'Team/&List' '&Ward' '&Clinic' 'C&ombination') TabOrder = 0 OnClick = radListSourceClick end object grpSortOrder: TGroupBox [33] Left = 16 Top = 152 Width = 145 Height = 94 HelpContext = 9062 Caption = 'Sort Order ' TabOrder = 1 object radAlphabetical: TRadioButton Left = 8 Top = 16 Width = 113 Height = 17 HelpContext = 9062 Caption = '&Alphabetical' TabOrder = 0 end object radRoomBed: TRadioButton Left = 8 Top = 31 Width = 113 Height = 17 HelpContext = 9062 Caption = '&Room/Bed' TabOrder = 1 end object radAppointmentDate: TRadioButton Left = 8 Top = 46 Width = 113 Height = 17 HelpContext = 9062 Caption = 'Appointment &Date' TabOrder = 2 end object radTerminalDigit: TRadioButton Left = 8 Top = 60 Width = 113 Height = 17 HelpContext = 9062 Caption = '&Terminal Digit' TabOrder = 3 end object radSource: TRadioButton Left = 8 Top = 75 Width = 113 Height = 17 HelpContext = 9062 Caption = 'So&urce' TabOrder = 4 end end inherited amgrMain: TVA508AccessibilityManager Data = ( ( 'Component = lblVisitDateRange' 'Status = stsDefault') ( 'Component = lblInfo' 'Status = stsDefault') ( 'Component = pnlBottom' 'Status = stsDefault') ( 'Component = btnOK' 'Status = stsDefault') ( 'Component = btnCancel' 'Status = stsDefault') ( 'Component = cboProvider' 'Status = stsDefault') ( 'Component = cboTreating' 'Status = stsDefault') ( 'Component = cboTeam' 'Status = stsDefault') ( 'Component = cboWard' 'Status = stsDefault') ( 'Component = cboMonday' 'Status = stsDefault') ( 'Component = cboTuesday' 'Status = stsDefault') ( 'Component = cboWednesday' 'Status = stsDefault') ( 'Component = cboThursday' 'Status = stsDefault') ( 'Component = cboFriday' 'Status = stsDefault') ( 'Component = cboSaturday' 'Status = stsDefault') ( 'Component = cboSunday' 'Status = stsDefault') ( 'Component = txtVisitStart' 'Status = stsDefault') ( 'Component = txtVisitStop' 'Status = stsDefault') ( 'Component = spnVisitStart' 'Status = stsDefault') ( 'Component = spnVisitStop' 'Status = stsDefault') ( 'Component = radListSource' 'Status = stsDefault') ( 'Component = grpSortOrder' 'Status = stsDefault') ( 'Component = radAlphabetical' 'Status = stsDefault') ( 'Component = radRoomBed' 'Status = stsDefault') ( 'Component = radAppointmentDate' 'Status = stsDefault') ( 'Component = radTerminalDigit' 'Status = stsDefault') ( 'Component = radSource' 'Status = stsDefault') ( 'Component = frmOptionsPatientSelection' 'Status = stsDefault')) end end
unit UDExportWord; interface uses Classes, Controls, Forms, StdCtrls, ExtCtrls, UCrpe32; type TCrpeWordDlg = class(TForm) btnOk: TButton; btnCancel: TButton; pnlPDF: TPanel; pnlPageRange: TPanel; lblFirstPage: TLabel; lblLastPage: TLabel; cbUsePageRange: TCheckBox; editFirstPage: TEdit; editLastPage: TEdit; cbPrompt: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cbUsePageRangeClick(Sender: TObject); procedure cbPromptClick(Sender: TObject); private { Private declarations } public { Public declarations } Cr : TCrpe; end; var CrpeWordDlg: TCrpeWordDlg; implementation {$R *.DFM} uses SysUtils, UDExportOptions, UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeWordDlg.FormCreate(Sender: TObject); begin LoadFormPos(Self); end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeWordDlg.FormShow(Sender: TObject); begin cbPrompt.Checked := Cr.ExportOptions.Word.Prompt; cbUsePageRange.Checked := Cr.ExportOptions.Word.UsePageRange; editFirstPage.Text := IntToStr(Cr.ExportOptions.Word.FirstPage); editLastPage.Text := IntToStr(Cr.ExportOptions.Word.LastPage); editFirstPage.Enabled := cbUsePageRange.Checked; editLastPage.Enabled := cbUsePageRange.Checked; editFirstPage.Color := ColorState(cbUsePageRange.Checked); editLastPage.Color := ColorState(cbUsePageRange.Checked); {Activate/Deactivate controls} cbPromptClick(Self); cbUsePageRangeClick(Self); end; {------------------------------------------------------------------------------} { cbPromptClick } {------------------------------------------------------------------------------} procedure TCrpeWordDlg.cbPromptClick(Sender: TObject); var OnOff : Boolean; begin {Activate/Deactivate controls} OnOff := not cbPrompt.Checked; cbUsePageRange.Enabled := OnOff; if OnOff then OnOff := cbUsePageRange.Checked; editFirstPage.Enabled := OnOff; editLastPage.Enabled := OnOff; editFirstPage.Color := ColorState(OnOff); editLastPage.Color := ColorState(OnOff); end; {------------------------------------------------------------------------------} { cbUsePageRangeClick } {------------------------------------------------------------------------------} procedure TCrpeWordDlg.cbUsePageRangeClick(Sender: TObject); begin editFirstPage.Enabled := cbUsePageRange.Checked; editLastPage.Enabled := cbUsePageRange.Checked; editFirstPage.Color := ColorState(cbUsePageRange.Checked); editLastPage.Color := ColorState(cbUsePageRange.Checked); end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeWordDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Cr.ExportOptions.Word.Prompt := cbPrompt.Checked; Cr.ExportOptions.Word.UsePageRange := cbUsePageRange.Checked; if IsNumeric(editFirstPage.Text) then Cr.ExportOptions.Word.FirstPage := StrToInt(editFirstPage.Text); if IsNumeric(editLastPage.Text) then Cr.ExportOptions.Word.LastPage := StrToInt(editLastPage.Text); end; {------------------------------------------------------------------------------} { btnCancelClick } {------------------------------------------------------------------------------} procedure TCrpeWordDlg.btnCancelClick(Sender: TObject); begin Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeWordDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin Release; end; end.