code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package com.riphtix.mem.client.forgeobjmodelported.obj; import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.util.Vec3; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class Face { public Vertex[] vertices; public Vertex[] vertexNormals; public Vertex faceNormal; public TextureCoordinate[] textureCoordinates; @SideOnly(Side.CLIENT) public void addFaceForRender(WorldRenderer worldRenderer) { addFaceForRender(worldRenderer, 0.0005F); } @SideOnly(Side.CLIENT) public void addFaceForRender(WorldRenderer worldRenderer, float textureOffset) { if (faceNormal == null) { faceNormal = this.calculateFaceNormal(); } worldRenderer.setNormal(faceNormal.x, faceNormal.y, faceNormal.z); float averageU = 0F; float averageV = 0F; if ((textureCoordinates != null) && (textureCoordinates.length > 0)) { for (int i = 0; i < textureCoordinates.length; ++i) { averageU += textureCoordinates[i].u; averageV += textureCoordinates[i].v; } averageU = averageU / textureCoordinates.length; averageV = averageV / textureCoordinates.length; } float offsetU, offsetV; for (int i = 0; i < vertices.length; ++i) { if ((textureCoordinates != null) && (textureCoordinates.length > 0)) { offsetU = textureOffset; offsetV = textureOffset; if (textureCoordinates[i].u > averageU) { offsetU = -offsetU; } if (textureCoordinates[i].v > averageV) { offsetV = -offsetV; } worldRenderer.addVertexWithUV(vertices[i].x, vertices[i].y, vertices[i].z, textureCoordinates[i].u + offsetU, textureCoordinates[i].v + offsetV); } else { worldRenderer.addVertex(vertices[i].x, vertices[i].y, vertices[i].z); } } } public Vertex calculateFaceNormal() { Vec3 v1 = new Vec3(vertices[1].x - vertices[0].x, vertices[1].y - vertices[0].y, vertices[1].z - vertices[0].z); Vec3 v2 = new Vec3(vertices[2].x - vertices[0].x, vertices[2].y - vertices[0].y, vertices[2].z - vertices[0].z); Vec3 normalVector = null; normalVector = v1.crossProduct(v2).normalize(); return new Vertex((float) normalVector.xCoord, (float) normalVector.yCoord, (float) normalVector.zCoord); } }
StingStriker353/More-Everything-Mod
src/main/java/com/riphtix/mem/client/forgeobjmodelported/obj/Face.java
Java
lgpl-2.1
2,439
/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2006 - 2017 Hitachi Vantara and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.repository.zip; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.reporting.libraries.base.util.IOUtils; import org.pentaho.reporting.libraries.repository.ContentCreationException; import org.pentaho.reporting.libraries.repository.ContentEntity; import org.pentaho.reporting.libraries.repository.ContentIOException; import org.pentaho.reporting.libraries.repository.ContentItem; import org.pentaho.reporting.libraries.repository.ContentLocation; import org.pentaho.reporting.libraries.repository.LibRepositoryBoot; import org.pentaho.reporting.libraries.repository.Repository; import org.pentaho.reporting.libraries.repository.RepositoryUtilities; import java.util.Date; import java.util.HashMap; import java.util.zip.ZipEntry; public class ZipContentLocation implements ContentLocation { private static final Log logger = LogFactory.getLog( ZipContentLocation.class ); private ZipRepository repository; private ZipContentLocation parent; private String comment; private String name; private long size; private long time; private String entryName; private HashMap entries; public ZipContentLocation( final ZipRepository repository, final ZipContentLocation parent, final String entryName ) { if ( repository == null ) { throw new NullPointerException(); } if ( entryName == null ) { throw new NullPointerException(); } this.repository = repository; this.parent = parent; this.entryName = entryName; this.entries = new HashMap(); this.name = RepositoryUtilities.buildName( this, "/" ) + '/'; this.time = System.currentTimeMillis(); } public ZipContentLocation( ZipRepository repository, ZipContentLocation parent, ZipEntry zipEntry ) { if ( repository == null ) { throw new NullPointerException(); } if ( parent == null ) { throw new NullPointerException(); } if ( zipEntry == null ) { throw new NullPointerException(); } this.repository = repository; this.parent = parent; this.entryName = IOUtils.getInstance().getFileName( zipEntry.getName() ); this.comment = zipEntry.getComment(); this.size = zipEntry.getSize(); this.time = zipEntry.getTime(); this.entries = new HashMap(); this.name = RepositoryUtilities.buildName( this, "/" ) + '/'; } private void updateMetaData( final ZipEntry zipEntry ) { this.comment = zipEntry.getComment(); this.size = zipEntry.getSize(); this.time = zipEntry.getTime(); } public void updateDirectoryEntry( final String[] name, final int index, final ZipEntry zipEntry ) { if ( name == null ) { throw new NullPointerException(); } if ( zipEntry == null ) { throw new NullPointerException(); } final String path = name[ index ]; final Object entry = entries.get( path ); if ( entry instanceof ContentItem ) { logger.warn( "Directory-Entry with the same name as a Content-Entry encountered: " + path ); return; } final ZipContentLocation location; if ( entry == null ) { location = new ZipContentLocation( repository, this, path ); entries.put( path, location ); } else { location = (ZipContentLocation) entry; } final int nextNameIdx = index + 1; if ( nextNameIdx < name.length ) { location.updateDirectoryEntry( name, nextNameIdx, zipEntry ); } else if ( nextNameIdx == name.length ) { location.updateMetaData( zipEntry ); } } public void updateEntry( final String[] name, final int index, final ZipEntry zipEntry, final byte[] data ) { if ( name == null ) { throw new NullPointerException(); } if ( zipEntry == null ) { throw new NullPointerException(); } if ( data == null ) { throw new NullPointerException(); } final String path = name[ index ]; final Object entry = entries.get( path ); final int nextNameIdx = index + 1; if ( nextNameIdx < name.length ) { if ( entry instanceof ContentItem ) { logger.warn( "Directory-Entry with the same name as a Content-Entry encountered: " + path ); return; } final ZipContentLocation location; if ( entry == null ) { location = new ZipContentLocation( repository, this, path ); entries.put( path, location ); } else { location = (ZipContentLocation) entry; } if ( nextNameIdx < name.length ) { location.updateEntry( name, nextNameIdx, zipEntry, data ); } } else if ( nextNameIdx == name.length ) { if ( entry instanceof ContentItem ) { logger.warn( "Duplicate Content-Entry encountered: " + path ); return; } else if ( entry != null ) { logger.warn( "Replacing Directory-Entry with the same name as a Content-Entry: " + path ); } final ZipContentItem contentItem = new ZipContentItem( repository, this, zipEntry, data ); entries.put( path, contentItem ); } } public ContentEntity[] listContents() throws ContentIOException { return (ContentEntity[]) entries.values().toArray( new ContentEntity[ entries.size() ] ); } public ContentEntity getEntry( final String name ) throws ContentIOException { return (ContentEntity) entries.get( name ); } public boolean exists( final String name ) { return entries.containsKey( name ); } public ContentItem createItem( final String name ) throws ContentCreationException { if ( entries.containsKey( name ) ) { throw new ContentCreationException( "An entry with name '" + name + "' already exists." ); } if ( name.indexOf( '/' ) != -1 ) { throw new ContentCreationException( "The entry-name '" + name + "' is invalid." ); } if ( "".equals( name ) || ".".equals( name ) || "..".equals( name ) ) { throw new ContentCreationException( "The entry-name '" + name + "' is invalid." ); } final ZipContentItem value = new ZipContentItem( repository, this, name ); entries.put( name, value ); return value; } public ContentLocation createLocation( final String name ) throws ContentCreationException { if ( entries.containsKey( name ) ) { throw new ContentCreationException( "An entry with name '" + name + "' already exists." ); } if ( entries.containsKey( name ) ) { throw new ContentCreationException( "An entry with name '" + name + "' already exists." ); } if ( name.indexOf( '/' ) != -1 ) { throw new ContentCreationException( "The entry-name '" + name + "' is invalid." ); } if ( "".equals( name ) || ".".equals( name ) || "..".equals( name ) ) { throw new ContentCreationException( "The entry-name '" + name + "' is invalid." ); } final ZipContentLocation value = new ZipContentLocation( repository, this, name ); entries.put( name, value ); return value; } public String getName() { return entryName; } public Object getContentId() { return name; } public Object getAttribute( final String domain, final String key ) { if ( LibRepositoryBoot.REPOSITORY_DOMAIN.equals( domain ) ) { if ( LibRepositoryBoot.SIZE_ATTRIBUTE.equals( key ) ) { return new Long( size ); } else if ( LibRepositoryBoot.VERSION_ATTRIBUTE.equals( key ) ) { return new Date( time ); } } else if ( LibRepositoryBoot.ZIP_DOMAIN.equals( domain ) ) { if ( LibRepositoryBoot.ZIP_COMMENT_ATTRIBUTE.equals( key ) ) { return comment; } } return null; } public boolean setAttribute( final String domain, final String key, final Object value ) { if ( LibRepositoryBoot.REPOSITORY_DOMAIN.equals( domain ) ) { if ( LibRepositoryBoot.VERSION_ATTRIBUTE.equals( key ) ) { if ( value instanceof Date ) { final Date n = (Date) value; time = n.getTime(); return true; } else if ( value instanceof Number ) { final Number n = (Number) value; time = n.longValue(); return true; } } } else if ( LibRepositoryBoot.ZIP_DOMAIN.equals( domain ) ) { if ( LibRepositoryBoot.ZIP_COMMENT_ATTRIBUTE.equals( key ) ) { if ( value != null ) { comment = String.valueOf( value ); return true; } else { comment = null; return true; } } } return false; } public ContentLocation getParent() { return parent; } public Repository getRepository() { return repository; } public boolean delete() { if ( parent == null ) { return false; } return parent.removeEntity( this ); } public boolean removeEntity( final ContentEntity entity ) { return ( entries.remove( entity.getName() ) != null ); } }
mbatchelor/pentaho-reporting
libraries/librepository/src/main/java/org/pentaho/reporting/libraries/repository/zip/ZipContentLocation.java
Java
lgpl-2.1
9,822
package codechicken.lib.vec; import codechicken.lib.math.MathHelper; import codechicken.lib.util.Copyable; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.util.vector.Vector3f; import org.lwjgl.util.vector.Vector4f; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; public class Vector3 implements Copyable<Vector3> { public static Vector3 zero = new Vector3(); public static Vector3 one = new Vector3(1, 1, 1); public static Vector3 center = new Vector3(0.5, 0.5, 0.5); public double x; public double y; public double z; public Vector3() { } public Vector3(double d, double d1, double d2) { x = d; y = d1; z = d2; } public Vector3(Vector3 vec) { x = vec.x; y = vec.y; z = vec.z; } public Vector3(double[] da) { this(da[0], da[1], da[2]); } public Vector3(float[] fa) { this(fa[0], fa[1], fa[2]); } public Vector3(Vec3d vec) { x = vec.xCoord; y = vec.yCoord; z = vec.zCoord; } @Deprecated // use Vector3.fromBlockPos //TODO, 1.11 move this to Vec3i public Vector3(BlockPos pos) { x = pos.getX(); y = pos.getY(); z = pos.getZ(); } public static Vector3 fromBlockPos(BlockPos pos) { return new Vector3(pos.getX(), pos.getY(), pos.getZ()); } public static Vector3 fromBlockPosCenter(BlockPos pos) { return fromBlockPos(pos).add(0.5); } public static Vector3 fromEntity(Entity e) { return new Vector3(e.posX, e.posY, e.posZ); } public static Vector3 fromEntityCenter(Entity e) { return new Vector3(e.posX, e.posY - e.getYOffset() + e.height / 2, e.posZ); } public static Vector3 fromTile(TileEntity tile) { return fromBlockPos(tile.getPos()); } public static Vector3 fromTileCenter(TileEntity tile) { return fromTile(tile).add(0.5); } public static Vector3 fromAxes(double[] da) { return new Vector3(da[2], da[0], da[1]); } public static Vector3 fromAxes(float[] fa) { return new Vector3(fa[2], fa[0], fa[1]); } public static Vector3 fromArray(double[] da) { return new Vector3(da[0], da[1], da[2]); } public static Vector3 fromArray(float[] fa) { return new Vector3(fa[0], fa[1], fa[2]); } public Vec3d vec3() { return new Vec3d(x, y, z); } public BlockPos pos() { return new BlockPos(x, y, z); } @SideOnly (Side.CLIENT) public Vector3f vector3f() { return new Vector3f((float) x, (float) y, (float) z); } @SideOnly (Side.CLIENT) public Vector4f vector4f() { return new Vector4f((float) x, (float) y, (float) z, 1); } @SideOnly (Side.CLIENT) public void glVertex() { GlStateManager.glVertex3f((float) x, (float) y, (float) z); } public Vector3 set(double x1, double y1, double z1) { x = x1; y = y1; z = z1; return this; } public Vector3 set(double d) { return set(d, d, d); } public Vector3 set(Vector3 vec) { return set(vec.x, vec.y, vec.z); } public Vector3 set(double[] da) { return set(da[0], da[1], da[2]); } public Vector3 set(float[] fa) { return set(fa[0], fa[1], fa[2]); } public Vector3 add(double dx, double dy, double dz) { x += dx; y += dy; z += dz; return this; } public Vector3 add(double d) { return add(d, d, d); } public Vector3 add(Vector3 vec) { return add(vec.x, vec.y, vec.z); } public Vector3 add(BlockPos pos) { return add(pos.getX(), pos.getY(), pos.getZ()); } public Vector3 subtract(double dx, double dy, double dz) { x -= dx; y -= dy; z -= dz; return this; } public Vector3 subtract(double d) { return subtract(d, d, d); } public Vector3 subtract(Vector3 vec) { return subtract(vec.x, vec.y, vec.z); } public Vector3 subtract(BlockPos pos) { return subtract(pos.getX(), pos.getY(), pos.getZ()); } @Deprecated //Use subtract public Vector3 sub(Vector3 vec) { return subtract(vec); } @Deprecated //Use subtract public Vector3 sub(BlockPos pos) { return subtract(pos); } public Vector3 multiply(double fx, double fy, double fz) { x *= fx; y *= fy; z *= fz; return this; } public Vector3 multiply(double f) { return multiply(f, f, f); } public Vector3 multiply(Vector3 f) { return multiply(f.x, f.y, f.z); } public Vector3 divide(double fx, double fy, double fz) { x /= fx; y /= fy; z /= fz; return this; } public Vector3 divide(double f) { return divide(f, f, f); } public Vector3 divide(Vector3 vec) { return divide(vec.x, vec.y, vec.z); } public Vector3 divide(BlockPos pos) { return divide(pos.getX(), pos.getY(), pos.getZ()); } public Vector3 floor() { x = MathHelper.floor(x); y = MathHelper.floor(y); z = MathHelper.floor(z); return this; } public Vector3 celi() { x = MathHelper.ceil(x); y = MathHelper.ceil(y); z = MathHelper.ceil(z); return this; } public double mag() { return Math.sqrt(x * x + y * y + z * z); } public double magSquared() { return x * x + y * y + z * z; } public Vector3 negate() { x = -x; y = -y; z = -z; return this; } public Vector3 normalize() { double d = mag(); if (d != 0) { multiply(1 / d); } return this; } public double dotProduct(double x1, double y1, double z1) { return x1 * x + y1 * y + z1 * z; } public double dotProduct(Vector3 vec) { double d = vec.x * x + vec.y * y + vec.z * z; if (d > 1 && d < 1.00001) { d = 1; } else if (d < -1 && d > -1.00001) { d = -1; } return d; } public Vector3 crossProduct(Vector3 vec) { double d = y * vec.z - z * vec.y; double d1 = z * vec.x - x * vec.z; double d2 = x * vec.y - y * vec.x; x = d; y = d1; z = d2; return this; } public Vector3 perpendicular() { if (z == 0) { return zCrossProduct(); } return xCrossProduct(); } public Vector3 xCrossProduct() { double d = z; double d1 = -y; x = 0; y = d; z = d1; return this; } public Vector3 zCrossProduct() { double d = y; double d1 = -x; x = d; y = d1; z = 0; return this; } public Vector3 yCrossProduct() { double d = -z; double d1 = x; x = d; y = 0; z = d1; return this; } public double scalarProject(Vector3 b) { double l = b.mag(); return l == 0 ? 0 : dotProduct(b) / l; } public Vector3 project(Vector3 b) { double l = b.magSquared(); if (l == 0) { set(0, 0, 0); return this; } double m = dotProduct(b) / l; set(b).multiply(m); return this; } public Vector3 rotate(double angle, Vector3 axis) { Quat.aroundAxis(axis.copy().normalize(), angle).rotate(this); return this; } public Vector3 rotate(Quat rotator) { rotator.rotate(this); return this; } public double angle(Vector3 vec) { return Math.acos(copy().normalize().dotProduct(vec.copy().normalize())); } public Vector3 YZintercept(Vector3 end, double px) { double dx = end.x - x; double dy = end.y - y; double dz = end.z - z; if (dx == 0) { return null; } double d = (px - x) / dx; if (MathHelper.between(-1E-5, d, 1E-5)) { return this; } if (!MathHelper.between(0, d, 1)) { return null; } x = px; y += d * dy; z += d * dz; return this; } public Vector3 XZintercept(Vector3 end, double py) { double dx = end.x - x; double dy = end.y - y; double dz = end.z - z; if (dy == 0) { return null; } double d = (py - y) / dy; if (MathHelper.between(-1E-5, d, 1E-5)) { return this; } if (!MathHelper.between(0, d, 1)) { return null; } x += d * dx; y = py; z += d * dz; return this; } public Vector3 XYintercept(Vector3 end, double pz) { double dx = end.x - x; double dy = end.y - y; double dz = end.z - z; if (dz == 0) { return null; } double d = (pz - z) / dz; if (MathHelper.between(-1E-5, d, 1E-5)) { return this; } if (!MathHelper.between(0, d, 1)) { return null; } x += d * dx; y += d * dy; z = pz; return this; } public boolean isZero() { return x == 0 && y == 0 && z == 0; } public boolean isAxial() { return x == 0 ? (y == 0 || z == 0) : (y == 0 && z == 0); } public double getSide(int side) { switch (side) { case 0: case 1: return y; case 2: case 3: return z; case 4: case 5: return x; } throw new IndexOutOfBoundsException("Switch Falloff"); } public Vector3 setSide(int s, double v) { switch (s) { case 0: case 1: y = v; break; case 2: case 3: z = v; break; case 4: case 5: x = v; break; default: throw new IndexOutOfBoundsException("Switch Falloff"); } return this; } @Override public boolean equals(Object o) { if (!(o instanceof Vector3)) { return false; } Vector3 v = (Vector3) o; return x == v.x && y == v.y && z == v.z; } /** * Equals method with tolerance * * @return true if this is equal to v within +-1E-5 */ public boolean equalsT(Vector3 v) { return MathHelper.between(x - 1E-5, v.x, x + 1E-5) && MathHelper.between(y - 1E-5, v.y, y + 1E-5) && MathHelper.between(z - 1E-5, v.z, z + 1E-5); } public Vector3 copy() { return new Vector3(this); } public String toString() { MathContext cont = new MathContext(4, RoundingMode.HALF_UP); return "Vector3(" + new BigDecimal(x, cont) + ", " + new BigDecimal(y, cont) + ", " + new BigDecimal(z, cont) + ")"; } public Translation translation() { return new Translation(this); } public Vector3 apply(Transformation t) { t.apply(this); return this; } public Vector3 $tilde() { return normalize(); } public Vector3 unary_$tilde() { return normalize(); } public Vector3 $plus(Vector3 v) { return add(v); } public Vector3 $minus(Vector3 v) { return subtract(v); } public Vector3 $times(double d) { return multiply(d); } public Vector3 $div(double d) { return multiply(1 / d); } public Vector3 $times(Vector3 v) { return crossProduct(v); } public double $dot$times(Vector3 v) { return dotProduct(v); } }
darkeports/tc5-port
src/main/java/thaumcraft/codechicken/lib/vec/Vector3.java
Java
lgpl-2.1
12,227
package java.lang; public final class Float extends Number { public static final float MIN_VALUE = 1.4e-45f; public static final float MAX_VALUE = 3.4028235e+38f; public static final float NEGATIVE_INFINITY = -1.0f/0.0f; public static final float POSITIVE_INFINITY = 1.0f/0.0f; public static final float NaN = 0.0f/0.0f; public static final int WIDEFP_SIGNIFICAND_BITS = 24; public static final int WIDEFP_MIN_EXPONENT = -126; public static final int WIDEFP_MAX_EXPONENT = 127; public static final Class TYPE = float.class; private float value; static { System.loadLibrary("javalang"); } public Float(float value) { this.value = value; } public Float(double value) { this((float)value); } public Float(String s) throws NullPointerException, NumberFormatException { value = parseFloat(s); } public String toString() { return toString(value); } public boolean equals(Object obj) { return (obj instanceof Float && ((Float)obj).value == value); } public int hashCode() { return floatToIntBits(value); } public int intValue() { return (int)value; } public long longValue() { return (long)value; } public float floatValue() { return value; } public double doubleValue() { return value; } public native static String toString(float f); public static Float valueOf(String s) throws NullPointerException, NumberFormatException { if (s == null) throw new NullPointerException("Float.valueOf(String) passed null as argument"); return new Float(Float.parseFloat(s)); } public boolean isNaN() { return isNaN(value); } public static boolean isNaN(float v) { return (floatToIntBits(v) == 0x7fc00000); } public boolean isInfinite() { return isInfinite(value); } public static boolean isInfinite(float v) { return (v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY); } public native static int floatToIntBits(float value); public native static float intBitsToFloat(int bits); public native static float parseFloat(String s); }
sehugg/SSBT
fastjlib/java/lang/Float.java
Java
lgpl-2.1
2,269
/* * Lightmare-criteria, JPA-QL query generator using lambda expressions * * Copyright (c) 2013, Levan Tsinadze, or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.lightmare.criteria.tuples; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Method; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.lightmare.criteria.query.orm.links.Parts; import org.lightmare.criteria.utils.ObjectUtils; import org.lightmare.criteria.utils.StringUtils; /** * Query field and entity type container class * * @author Levan Tsinadze * */ public class QueryTuple implements Serializable, Cloneable { private static final long serialVersionUID = 1L; private String entityName; private final String methodName; private String fieldName; private String paramName; private Class<?> entityType; private Method method; private Field field; private Class<?> fieldType; private TemporalType temporalType; private Class<?> genericType; private String alias; private static final String ALIAS_PREFIX = "c"; private static final String FORMATTER = "%s %s %s"; protected QueryTuple(final String entityName, final String methodName, final String fieldName) { this.entityName = entityName; this.methodName = methodName; this.setFieldName(fieldName); } /** * Initializes {@link org.lightmare.criteria.tuples.QueryTuple} by method * description * * @param entityName * @param methodName * @param fieldName * @return {@link org.lightmare.criteria.tuples.QueryTuple} instance */ public static QueryTuple of(final String entityName, final String methodName, final String fieldName) { return new QueryTuple(entityName, methodName, fieldName); } /** * Initializes {@link org.lightmare.criteria.tuples.QueryTuple} by field * name * * @param fieldName * @return {@link org.lightmare.criteria.tuples.QueryTuple} instance */ public static QueryTuple of(final String fieldName) { return new QueryTuple(null, null, fieldName); } public String getEntityName() { return entityName; } private void setEntityName(String entityName) { this.entityName = entityName; } public String getMethodName() { return methodName; } /** * Sets field and parameter names * * @param fieldName */ public void setFieldName(String fieldName) { this.fieldName = fieldName; this.paramName = Parts.refineName(fieldName); } public String getFieldName() { return fieldName; } public String getParamName() { return paramName; } public Class<?> getEntityType() { return entityType; } public void setEntityType(Class<?> entityType) { this.entityType = entityType; } public void setTypeAndName(Class<?> entityType) { setEntityType(entityType); setEntityName(entityType.getName()); } public Method getMethod() { return method; } public void setMethod(Method method) { this.method = method; } public Field getField() { return field; } public void setField(Field field) { this.field = field; this.fieldType = ObjectUtils.ifIsNotNull(field, Field::getType); } public Class<?> getFieldType() { return fieldType; } public TemporalType getTemporalType() { return temporalType; } public void setTemporalType(TemporalType temporalType) { this.temporalType = temporalType; } public void setTemporalType(Temporal temporal) { ObjectUtils.nonNull(temporal, c -> setTemporalType(c.value())); } public Class<?> getGenericType() { return ObjectUtils.thisOrDefault(genericType, field::getType, this::setGenericType); } public void setGenericType(Class<?> genericType) { this.genericType = genericType; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public boolean hasNoAlias() { return StringUtils.isEmpty(alias); } public void setAlias(int index) { this.alias = StringUtils.thisOrDefault(alias, () -> ALIAS_PREFIX.concat(String.valueOf(index))); } public <F> Class<F> getCollectionType() { return ObjectUtils.getAndCast(this::getGenericType); } public <F> Class<F> getFieldGenericType() { return ObjectUtils.getAndCast(this::getFieldType); } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } @Override public String toString() { return String.format(FORMATTER, entityName, methodName, fieldName); } }
levants/lightmare
lightmare-criteria/src/main/java/org/lightmare/criteria/tuples/QueryTuple.java
Java
lgpl-2.1
5,968
/*---------------------------------------------------------------------------*\ * OpenSG * * * * * * Copyright (C) 2000-2006 by the OpenSG Forum * * * * www.opensg.org * * * * contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library 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 * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include <cstdlib> #include <cstdio> #include "OSGConfig.h" #include "OSGCSMLogger.h" #include "OSGNameAttachment.h" OSG_BEGIN_NAMESPACE // Documentation for this class is emitted in the // OSGCSMLoggerBase.cpp file. // To modify it, please change the .fcd file (OSGCSMLogger.fcd) and // regenerate the base file. /***************************************************************************\ * Class variables * \***************************************************************************/ /***************************************************************************\ * Class methods * \***************************************************************************/ void CSMLogger::initMethod(InitPhase ePhase) { Inherited::initMethod(ePhase); if(ePhase == TypeObject::SystemPost) { } } /***************************************************************************\ * Instance methods * \***************************************************************************/ /*-------------------------------------------------------------------------*\ - private - \*-------------------------------------------------------------------------*/ /*----------------------- constructors & destructors ----------------------*/ CSMLogger::CSMLogger(void) : Inherited() { } CSMLogger::CSMLogger(const CSMLogger &source) : Inherited(source) { } CSMLogger::~CSMLogger(void) { } /*----------------------------- class specific ----------------------------*/ void CSMLogger::changed(ConstFieldMaskArg whichField, UInt32 origin, BitVector details) { Inherited::changed(whichField, origin, details); if(0x0000 != (whichField & (ContainersFieldMask | FieldsFieldMask))) { } } void CSMLogger::dump( UInt32 , const BitVector ) const { SLOG << "Dump CSMLogger NI" << std::endl; } void CSMLogger::postOSGLoading(FileContextAttachment * const pContext) { MFContainersType::const_iterator cIt = _mfContainers.begin(); MFContainersType::const_iterator cEnd = _mfContainers.end (); MFString ::const_iterator fIt = _mfFields.begin (); MFString ::const_iterator fEnd = _mfFields.end (); for(; cIt != cEnd && fIt != fEnd; ++cIt, ++fIt) { fprintf(stderr, "log : %p (%s).%s\n", static_cast<void *>(*cIt), (*cIt) != NULL ? (*cIt)->getType().getCName() : "---", fIt->c_str() ); const FieldDescriptionBase *pDesc = (*cIt)->getFieldDescription(fIt->c_str()); if(pDesc != NULL) { ChangedFunctor logCB = boost::bind(&CSMLogger::doLog, this, _1, _2, _3, pDesc->getFieldId(), pDesc->getFieldMask()); (*cIt)->addChangedFunctor(logCB, ""); } } } void CSMLogger::doLog(FieldContainer *pContainer, BitVector bvFlags , UInt32 origin , UInt32 uiRefFieldId, BitVector uiRefFieldMask) { if(0x0000 != (bvFlags & uiRefFieldMask) && _sfEnabled.getValue() == true) { GetFieldHandlePtr pFH = pContainer->getField(uiRefFieldId); if(pFH && pFH->isValid() == true) { static CErrOutStream cerrStream; const FieldDescriptionBase *pDesc = pContainer->getFieldDescription(uiRefFieldId); AttachmentContainer *pAtt = dynamic_cast<AttachmentContainer *>(pContainer); if(pAtt != NULL) { const Char8 *szName = getName(pAtt); if(szName != NULL) { cerrStream << "[" << szName << "]:"; } } cerrStream << pContainer->getType().getName() << "." << pDesc->getName() << " : "; pFH->pushValueToStream(cerrStream); cerrStream << std::endl; } } } OSG_END_NAMESPACE
jondo2010/OpenSG
Source/Contrib/ComplexSceneManager/Helper/OSGCSMLogger.cpp
C++
lgpl-2.1
7,775
/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mlabelview.h" #include "mlabelview_p.h" #include "mlabelmodel.h" #include "mlabel.h" #include "mviewcreator.h" #include "mlocale.h" #include <QTextDocument> #include <QPixmapCache> #include <QAbstractTextDocumentLayout> #include <QGraphicsSceneMouseEvent> #include <QGraphicsSceneResizeEvent> #include <QTimer> MLabelViewPrivate::MLabelViewPrivate() : MWidgetViewPrivate(), highlighterUpdateTimer(0) { impl = new MLabelViewSimple(this); } MLabelViewPrivate::~MLabelViewPrivate() { delete impl; delete highlighterUpdateTimer; } const MLabelModel *MLabelViewPrivate::model() const { Q_Q(const MLabelView); return q->model(); } const MLabelStyle *MLabelViewPrivate::style() const { Q_Q(const MLabelView); return q->style().operator ->(); } const QRectF MLabelViewPrivate::boundingRect() const { Q_Q(const MLabelView); return q->boundingRect(); } void MLabelViewPrivate::requestHighlighterUpdate(int interval) { Q_Q(MLabelView); if (!highlighterUpdateTimer) { highlighterUpdateTimer = new QTimer(); highlighterUpdateTimer->setSingleShot(true); QObject::connect(highlighterUpdateTimer, SIGNAL(timeout()), q, SLOT(_q_highlighterUpdateTimerExceeded())); } highlighterUpdateTimer->start(interval); } void MLabelViewPrivate::_q_highlighterUpdateTimerExceeded() { MLabelViewRich *labelViewRich = static_cast<MLabelViewRich*>(impl); labelViewRich->cleanupTiles(); controller->update(); } bool MLabelViewPrivate::displayAsRichText(QString text, Qt::TextFormat textFormat, int numberOfHighlighters) const { if (textFormat == Qt::RichText) { return true; } else if (textFormat == Qt::PlainText) { return false; } //Qt::mightBeRichText stops at the first line break text.replace("\n", " "); return Qt::mightBeRichText(text) || (numberOfHighlighters > 0); } void MLabelViewPrivate::autoSetTextDirection() { // Set text direction Qt::LayoutDirection textDirection = model()->textDirection(); if (textDirection == Qt::LayoutDirectionAuto) { switch (MLocale::defaultLayoutDirection()) { case Qt::LeftToRight: textDirection = Qt::LeftToRight; break; case Qt::RightToLeft: textDirection = Qt::RightToLeft; break; case Qt::LayoutDirectionAuto: default: textDirection = MLocale::directionForText(model()->text()); // look at the text content break; } } textOptions.setTextDirection(textDirection); // Set alignment Qt::Alignment alignment = model()->alignment(); if (textDirection == Qt::RightToLeft && !(alignment & Qt::AlignAbsolute)) { // Mirror horizontal alignment Qt::Alignment horAlignment = (alignment & Qt::AlignHorizontal_Mask); if (horAlignment & Qt::AlignRight) { horAlignment = Qt::AlignLeft; } else if (!(horAlignment & Qt::AlignHCenter)) { horAlignment = Qt::AlignRight; } alignment = (alignment & ~Qt::AlignHorizontal_Mask) | horAlignment; } textOptions.setAlignment(alignment); } MLabelView::MLabelView(MLabel *controller) : MWidgetView(new MLabelViewPrivate) { Q_D(MLabelView); d->controller = controller; } MLabelView::~MLabelView() { } void MLabelView::applyStyle() { MWidgetView::applyStyle(); Q_D(MLabelView); d->impl->markDirty(); d->impl->applyStyle(); const MLabelStyle* labelStyle = d->style(); d->paddedSize = size() - QSizeF(labelStyle->paddingLeft() + labelStyle->paddingRight(), labelStyle->paddingTop() + labelStyle->paddingBottom()); updateGeometry(); } void MLabelView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const { Q_D(const MLabelView); Q_UNUSED(option); //Opacity for the label qreal oldOpacity = painter->opacity(); const MLabelStyle* labelStyle = d->style(); if (labelStyle->textOpacity() >= 0.0) painter->setOpacity(d->controller->effectiveOpacity() * labelStyle->textOpacity()); //give size adjusted with padding to the actual implementation class d->impl->drawContents(painter, d->paddedSize); painter->setOpacity(oldOpacity); } void MLabelView::resizeEvent(QGraphicsSceneResizeEvent *event) { MWidgetView::resizeEvent(event); Q_D(MLabelView); d->impl->markDirty(); const MLabelStyle* labelStyle = d->style(); QSizeF padding(labelStyle->paddingLeft() + labelStyle->paddingRight(), labelStyle->paddingTop() + labelStyle->paddingBottom()); d->paddedSize = event->newSize() - QSizeF(labelStyle->paddingLeft() + labelStyle->paddingRight(), labelStyle->paddingTop() + labelStyle->paddingBottom()); event->setOldSize(event->oldSize() - padding); event->setNewSize(d->paddedSize); if (d->impl->resizeEvent(event)) { updateGeometry(); } } QFont MLabelView::font() const { return style()->font(); } QSizeF MLabelView::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const { Q_D(const MLabelView); const MLabelStyle *s = static_cast<const MLabelStyle *>(style().operator ->()); QSizeF padding(s->paddingLeft() + s->paddingRight(), s->paddingTop() + s->paddingBottom()); return d->impl->sizeHint(which, constraint - padding) + padding; } void MLabelView::setupModel() { MWidgetView::setupModel(); Q_D(MLabelView); bool shouldBeRich = d->displayAsRichText(model()->text(), model()->textFormat(), model()->highlighters().size()); // Check has label type changed since last call to this method. Re-allocate label with correct type. if (d->impl->isRich() != shouldBeRich) { MLabelViewSimple* oldView = d->impl; if (shouldBeRich) d->impl = new MLabelViewRich(d); else d->impl = new MLabelViewSimple(d); delete oldView; } d->impl->setupModel(); d->impl->markDirty(); } void MLabelView::updateData(const QList<const char *>& modifications) { MWidgetView::updateData(modifications); Q_D(MLabelView); if (modifications.contains(MLabelModel::Text) || modifications.contains(MLabelModel::Highlighters) || modifications.contains(MLabelModel::TextFormat)) { // Check has label type changed since last call to this method. Re-allocate label with correct type. bool shouldBeRich = d->displayAsRichText(model()->text(), model()->textFormat(), model()->highlighters().size()); bool shouldBeSimple = !shouldBeRich; if ((shouldBeRich && !d->impl->isRich()) || (shouldBeSimple && d->impl->isRich())) { MLabelViewSimple* oldView = d->impl; if (shouldBeRich) d->impl = new MLabelViewRich(d); else d->impl = new MLabelViewSimple(d); delete oldView; d->impl->setupModel(); } } if (d->impl->updateData(modifications)) updateGeometry(); d->impl->markDirty(); update(); } void MLabelView::mousePressEvent(QGraphicsSceneMouseEvent *event) { Q_D(MLabelView); d->impl->mousePressEvent(event); } void MLabelView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { Q_D(MLabelView); d->impl->mouseReleaseEvent(event); } void MLabelView::cancelEvent(MCancelEvent *event) { Q_D(MLabelView); d->impl->cancelEvent(event); } void MLabelView::longPressEvent(QGraphicsSceneContextMenuEvent *event) { event->ignore(); } void MLabelView::tapAndHoldGestureEvent(QGestureEvent *event, QTapAndHoldGesture* gesture) { Q_D(MLabelView); d->impl->longPressEvent(event,gesture); } void MLabelView::orientationChangeEvent(MOrientationChangeEvent *event) { Q_D(MLabelView); MWidgetView::orientationChangeEvent(event); d->impl->orientationChangeEvent(event); } M_REGISTER_VIEW_NEW(MLabelView, MLabel) #include "moc_mlabelview.cpp"
dudochkin-victor/libgogootouch
src/views/mlabelview.cpp
C++
lgpl-2.1
8,685
# Copyright (C)2016 D. Plaindoux. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 2, or (at your option) any # later version. class WebException(Exception): def __init__(self, status, message=None): Exception.__init__(self) self.status = status self.message = message @staticmethod def get(status): switcher = { 400: WebException.badRequest, 401: WebException.unauthorized, 402: WebException.paymentRequired, 404: WebException.notFound, 406: WebException.notAcceptable } return switcher.get(status, lambda m: WebException(status, m)) @staticmethod def badRequest(message=None): return WebException(400, "Bad request" if message is None else message) @staticmethod def unauthorized(message=None): return WebException(401, "Unauthorized" if message is None else message) @staticmethod def paymentRequired(message=None): return WebException(402, "Payment Required" if message is None else message) @staticmethod def notFound(message=None): return WebException(404, "Not found" if message is None else message) @staticmethod def notAcceptable(message=None): return WebException(406, "Not acceptable" if message is None else message)
d-plaindoux/fluent-rest
fluent_rest/runtime/response.py
Python
lgpl-2.1
1,628
/* Copyright 2005-2007 Adobe Systems Incorporated Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt or a copy at http://stlab.adobe.com/licenses.html) */ /*************************************************************************************************/ #include <GG/adobe/basic_sheet.hpp> #include <GG/adobe/dictionary.hpp> #include <GG/adobe/string.hpp> #include <GG/adobe/algorithm/for_each.hpp> #include <GG/adobe/future/widgets/headers/widget_tokens.hpp> #include <GG/adobe/future/widgets/headers/factory.hpp> #include <GG/ExpressionWriter.h> #include <stdexcept> /*************************************************************************************************/ namespace { /*************************************************************************************************/ bool is_container(adobe::name_t wnd_type) { return wnd_type == adobe::name_dialog || wnd_type == adobe::name_group || wnd_type == adobe::name_radio_button_group || wnd_type == adobe::name_tab_group || wnd_type == adobe::name_overlay || wnd_type == adobe::name_panel || wnd_type == adobe::name_row || wnd_type == adobe::name_column; } /*************************************************************************************************/ } /*************************************************************************************************/ namespace adobe { /*************************************************************************************************/ void basic_sheet_t::add_constant(name_t name, const line_position_t& position, const array_t& initializer, const any_regular_t& value) { if (added_elements_m.empty() || added_elements_m.back().which() != 0 || boost::get<added_cell_set_t>(added_elements_m.back()).access_m != access_constant) { added_elements_m.push_back(added_cell_set_t(access_constant)); } boost::get<added_cell_set_t>(added_elements_m.back()).added_cells_m.push_back( cell_parameters_t(name, position, initializer) ); constant_cell_set_m.push_back(cell_t(value)); const cell_t* cell(&constant_cell_set_m.back()); variable_index_m.insert(std::make_pair(name.c_str(), cell)); } /*************************************************************************************************/ void basic_sheet_t::add_interface(name_t name, const line_position_t& position, const array_t& initializer, const any_regular_t& value) { if (added_elements_m.empty() || added_elements_m.back().which() != 0 || boost::get<added_cell_set_t>(added_elements_m.back()).access_m != access_interface) { added_elements_m.push_back(added_cell_set_t(access_constant)); } boost::get<added_cell_set_t>(added_elements_m.back()).added_cells_m.push_back( cell_parameters_t(name, position, initializer) ); interface_cell_set_m.push_back(interface_cell_t(value)); interface_cell_t* cell(&interface_cell_set_m.back()); variable_index_m.insert(std::make_pair(name.c_str(), cell)); interface_index_m.insert(std::make_pair(name.c_str(), cell)); } /*************************************************************************************************/ void basic_sheet_t::add_view(const boost::any& parent_, name_t name, const line_position_t& position, const array_t& initializer, const boost::any& view_) { if (added_elements_m.empty() || added_elements_m.back().which() != 1) added_elements_m.push_back(added_view_set_t()); added_view_set_t& added_view_set = boost::get<added_view_set_t>(added_elements_m.back()); GG::Wnd* parent = boost::any_cast<widget_node_t>(parent_).display_token_m; GG::Wnd* view = boost::any_cast<widget_node_t>(view_).display_token_m; view_parameters_t params(view, position, name, initializer); if (!added_view_set.m_current_nested_view) { added_view_set.m_nested_views = nested_views_t(params, 0); added_view_set.m_current_nested_view = &added_view_set.m_nested_views; } else { while (added_view_set.m_current_nested_view->m_view_parameters.m_parent != parent && added_view_set.m_current_nested_view->m_nested_view_parent) { added_view_set.m_current_nested_view = added_view_set.m_current_nested_view->m_nested_view_parent; } assert(added_view_set.m_current_nested_view); const bool container = is_container(name); if (container) params.m_parent = parent; added_view_set.m_current_nested_view->m_children.push_back( nested_views_t(params, added_view_set.m_current_nested_view) ); if (container) { added_view_set.m_current_nested_view = &added_view_set.m_current_nested_view->m_children.back(); } } } /*************************************************************************************************/ std::size_t basic_sheet_t::count_interface(name_t name) const { return interface_index_m.count(name.c_str()); } /*************************************************************************************************/ basic_sheet_t::connection_t basic_sheet_t::monitor_value(name_t name, const monitor_value_t& monitor) { interface_cell_t* cell(lookup_interface(name)); monitor(cell->value_m); return (cell->monitor_value_m.connect(monitor)); } /*************************************************************************************************/ void basic_sheet_t::set(const dictionary_t& cell_set) { dictionary_t::const_iterator iter(cell_set.begin()); dictionary_t::const_iterator last(cell_set.end()); for (; iter != last; ++iter) set(iter->first, iter->second); } /*************************************************************************************************/ void basic_sheet_t::set(name_t name, const any_regular_t& value) { interface_cell_t* cell(lookup_interface(name)); cell->value_m = value; cell->monitor_value_m(value); } /*************************************************************************************************/ const any_regular_t& basic_sheet_t::operator[](name_t name) const { variable_index_t::const_iterator iter(variable_index_m.find(name.c_str())); if (iter == variable_index_m.end()) { std::string error("basic_sheet_t variable cell does not exist: "); error << name.c_str(); throw std::logic_error(error); } return iter->second->value_m; } /*************************************************************************************************/ adobe::dictionary_t basic_sheet_t::contributing() const { interface_index_t::const_iterator iter(interface_index_m.begin()); interface_index_t::const_iterator last(interface_index_m.end()); adobe::dictionary_t result; for (; iter != last; ++iter) result.insert(std::make_pair(adobe::name_t(iter->first), iter->second->value_m)); return result; } /*************************************************************************************************/ void basic_sheet_t::print(std::ostream& os) const { os << "layout name_ignored\n" << "{\n"; for (std::size_t i = 0; i < added_elements_m.size(); ++i) { if (i) os << '\n'; if (added_elements_m[i].which() == 0) { const added_cell_set_t& cell_set = boost::get<added_cell_set_t>(added_elements_m[i]); switch (cell_set.access_m) { case access_constant: os << "constant:\n"; break; case access_interface: os << "interface:\n"; break; } for (std::size_t j = 0; j < cell_set.added_cells_m.size(); ++j) { const cell_parameters_t& params = cell_set.added_cells_m[j]; // TODO: print detailed comment os << " " << params.name_m << " : " << GG::WriteExpression(params.initializer_m) << ";\n"; // TODO: print brief comment } } else { const added_view_set_t& view_set = boost::get<added_view_set_t>(added_elements_m[i]); os << " view "; print_nested_view(os, view_set.m_nested_views, 1); } } os << "}\n"; } /*************************************************************************************************/ void basic_sheet_t::print_nested_view(std::ostream& os, const nested_views_t& nested_view, unsigned int indent) const { const view_parameters_t& params = nested_view.m_view_parameters; // TODO: print detailed comment std::string initial_indent(indent * 4, ' '); if (indent == 1u) initial_indent.clear(); std::string param_string = GG::WriteExpression(params.m_parameters); os << initial_indent << params.m_name << '(' << param_string.substr(1, param_string.size() - 3) << ')'; if (nested_view.m_children.empty()) { if (indent == 1u) { os << "\n" // TODO: print brief comment << " {}\n"; } else { os << ";\n"; // TODO: print brief comment } } else { // TODO: print brief comment os << '\n' << std::string(indent * 4, ' ') << "{\n"; for (std::size_t i = 0; i < nested_view.m_children.size(); ++i) { print_nested_view(os, nested_view.m_children[i], indent + 1); } os << std::string(indent * 4, ' ') << "}\n"; } } /*************************************************************************************************/ basic_sheet_t::interface_cell_t* basic_sheet_t::lookup_interface(name_t name) { interface_index_t::iterator iter(interface_index_m.find(name.c_str())); if (iter == interface_index_m.end()) { std::string error("basic_sheet_t interface cell does not exist: "); error << name.c_str(); throw std::logic_error(error); } return iter->second; } /*************************************************************************************************/ } // namespace adobe /*************************************************************************************************/
tzlaine/GG
src/adobe/basic_sheet.cpp
C++
lgpl-2.1
10,637
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.loader.plan.build.spi; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import org.hibernate.internal.util.StringHelper; import org.hibernate.loader.EntityAliases; import org.hibernate.loader.plan.exec.spi.AliasResolutionContext; import org.hibernate.loader.plan.exec.spi.CollectionReferenceAliases; import org.hibernate.loader.plan.exec.spi.EntityReferenceAliases; import org.hibernate.loader.plan.spi.CollectionQuerySpace; import org.hibernate.loader.plan.spi.CompositeQuerySpace; import org.hibernate.loader.plan.spi.EntityQuerySpace; import org.hibernate.loader.plan.spi.Join; import org.hibernate.loader.plan.spi.JoinDefinedByMetadata; import org.hibernate.loader.plan.spi.QuerySpace; import org.hibernate.loader.plan.spi.QuerySpaces; /** * Prints a {@link QuerySpaces} graph as a tree structure. * <p/> * Intended for use in debugging, logging, etc. * * @author Steve Ebersole */ public class QuerySpaceTreePrinter { /** * Singleton access */ public static final QuerySpaceTreePrinter INSTANCE = new QuerySpaceTreePrinter(); private QuerySpaceTreePrinter() { } /** * Returns a String containing the {@link QuerySpaces} graph as a tree structure. * * @param spaces The {@link QuerySpaces} object. * @param aliasResolutionContext The context for resolving table and column aliases * for the {@link QuerySpace} references in <code>spaces</code>; if null, * table and column aliases are not included in returned value.. * @return the String containing the {@link QuerySpaces} graph as a tree structure. */ public String asString(QuerySpaces spaces, AliasResolutionContext aliasResolutionContext) { return asString( spaces, 0, aliasResolutionContext ); } /** * Returns a String containing the {@link QuerySpaces} graph as a tree structure, starting * at a particular depth. * * The value for depth indicates the number of indentations that will * prefix all lines in the returned String. Root query spaces will be written with depth + 1 * and the depth will be further incremented as joined query spaces are traversed. * * An indentation is defined as the number of characters defined by {@link TreePrinterHelper#INDENTATION}. * * @param spaces The {@link QuerySpaces} object. * @param depth The intial number of indentations * @param aliasResolutionContext The context for resolving table and column aliases * for the {@link QuerySpace} references in <code>spaces</code>; if null, * table and column aliases are not included in returned value.. * @return the String containing the {@link QuerySpaces} graph as a tree structure. */ public String asString(QuerySpaces spaces, int depth, AliasResolutionContext aliasResolutionContext) { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); final PrintStream printStream = new PrintStream( byteArrayOutputStream ); write( spaces, depth, aliasResolutionContext, printStream ); printStream.flush(); return new String( byteArrayOutputStream.toByteArray() ); } /** * Returns a String containing the {@link QuerySpaces} graph as a tree structure, starting * at a particular depth. * * The value for depth indicates the number of indentations that will * prefix all lines in the returned String. Root query spaces will be written with depth + 1 * and the depth will be further incremented as joined query spaces are traversed. * * An indentation is defined as the number of characters defined by {@link TreePrinterHelper#INDENTATION}. * * @param spaces The {@link QuerySpaces} object. * @param depth The intial number of indentations * @param aliasResolutionContext The context for resolving table and column aliases * for the {@link QuerySpace} references in <code>spaces</code>; if null, * table and column aliases are not included in returned value. * @param printStream The print stream for writing. */ public void write( QuerySpaces spaces, int depth, AliasResolutionContext aliasResolutionContext, PrintStream printStream) { write( spaces, depth, aliasResolutionContext, new PrintWriter( printStream ) ); } /** * Returns a String containing the {@link QuerySpaces} graph as a tree structure, starting * at a particular depth. * * The value for depth indicates the number of indentations that will * prefix all lines in the returned String. Root query spaces will be written with depth + 1 * and the depth will be further incremented as joined query spaces are traversed. * * An indentation is defined as the number of characters defined by {@link TreePrinterHelper#INDENTATION}. * * @param spaces The {@link QuerySpaces} object. * @param depth The intial number of indentations * @param aliasResolutionContext The context for resolving table and column aliases * for the {@link QuerySpace} references in <code>spaces</code>; if null, * table and column aliases are not included in returned value. * @param printWriter The print writer for writing. */ public void write( QuerySpaces spaces, int depth, AliasResolutionContext aliasResolutionContext, PrintWriter printWriter) { if ( spaces == null ) { printWriter.println( "QuerySpaces is null!" ); return; } printWriter.println( TreePrinterHelper.INSTANCE.generateNodePrefix( depth ) + "QuerySpaces" ); for ( QuerySpace querySpace : spaces.getRootQuerySpaces() ) { writeQuerySpace( querySpace, depth + 1, aliasResolutionContext, printWriter ); } printWriter.flush(); } private void writeQuerySpace( QuerySpace querySpace, int depth, AliasResolutionContext aliasResolutionContext, PrintWriter printWriter) { generateDetailLines( querySpace, depth, aliasResolutionContext, printWriter ); writeJoins( querySpace.getJoins(), depth + 1, aliasResolutionContext, printWriter ); } final int detailDepthOffset = 1; private void generateDetailLines( QuerySpace querySpace, int depth, AliasResolutionContext aliasResolutionContext, PrintWriter printWriter) { printWriter.println( TreePrinterHelper.INSTANCE.generateNodePrefix( depth ) + extractDetails( querySpace ) ); if ( aliasResolutionContext == null ) { return; } printWriter.println( TreePrinterHelper.INSTANCE.generateNodePrefix( depth + detailDepthOffset ) + "SQL table alias mapping - " + aliasResolutionContext.resolveSqlTableAliasFromQuerySpaceUid( querySpace.getUid() ) ); final EntityReferenceAliases entityAliases = aliasResolutionContext.resolveEntityReferenceAliases( querySpace.getUid() ); final CollectionReferenceAliases collectionReferenceAliases = aliasResolutionContext.resolveCollectionReferenceAliases( querySpace.getUid() ); if ( entityAliases != null ) { printWriter.println( TreePrinterHelper.INSTANCE.generateNodePrefix( depth + detailDepthOffset ) + "alias suffix - " + entityAliases.getColumnAliases().getSuffix() ); printWriter.println( TreePrinterHelper.INSTANCE.generateNodePrefix( depth + detailDepthOffset ) + "suffixed key columns - {" + StringHelper.join( ", ", entityAliases.getColumnAliases().getSuffixedKeyAliases() ) + "}" ); } if ( collectionReferenceAliases != null ) { printWriter.println( TreePrinterHelper.INSTANCE.generateNodePrefix( depth + detailDepthOffset ) + "alias suffix - " + collectionReferenceAliases.getCollectionColumnAliases().getSuffix() ); printWriter.println( TreePrinterHelper.INSTANCE.generateNodePrefix( depth + detailDepthOffset ) + "suffixed key columns - {" + StringHelper.join( ", ", collectionReferenceAliases.getCollectionColumnAliases().getSuffixedKeyAliases() ) + "}" ); final EntityAliases elementAliases = collectionReferenceAliases.getEntityElementAliases() == null ? null : collectionReferenceAliases.getEntityElementAliases().getColumnAliases(); if ( elementAliases != null ) { printWriter.println( TreePrinterHelper.INSTANCE.generateNodePrefix( depth + detailDepthOffset ) + "entity-element alias suffix - " + elementAliases.getSuffix() ); printWriter.println( TreePrinterHelper.INSTANCE.generateNodePrefix( depth + detailDepthOffset ) + elementAliases.getSuffix() + "entity-element suffixed key columns - " + StringHelper.join( ", ", elementAliases.getSuffixedKeyAliases() ) ); } } } private void writeJoins( Iterable<Join> joins, int depth, AliasResolutionContext aliasResolutionContext, PrintWriter printWriter) { for ( Join join : joins ) { printWriter.println( TreePrinterHelper.INSTANCE.generateNodePrefix( depth ) + extractDetails( join ) ); writeQuerySpace( join.getRightHandSide(), depth+1, aliasResolutionContext, printWriter ); } } /** * Returns a String containing high-level details about the {@link QuerySpace}, such as: * <ul> * <li>query space class name</li> * <li>unique ID</li> * <li>entity name (for {@link EntityQuerySpace}</li> * <li>collection role (for {@link CollectionQuerySpace}</li> * * </ul> * @param space The query space * @return a String containing details about the {@link QuerySpace} */ public String extractDetails(QuerySpace space) { if ( EntityQuerySpace.class.isInstance( space ) ) { final EntityQuerySpace entityQuerySpace = (EntityQuerySpace) space; return String.format( "%s(uid=%s, entity=%s)", entityQuerySpace.getClass().getSimpleName(), entityQuerySpace.getUid(), entityQuerySpace.getEntityPersister().getEntityName() ); } else if ( CompositeQuerySpace.class.isInstance( space ) ) { final CompositeQuerySpace compositeQuerySpace = (CompositeQuerySpace) space; return String.format( "%s(uid=%s)", compositeQuerySpace.getClass().getSimpleName(), compositeQuerySpace.getUid() ); } else if ( CollectionQuerySpace.class.isInstance( space ) ) { final CollectionQuerySpace collectionQuerySpace = (CollectionQuerySpace) space; return String.format( "%s(uid=%s, collection=%s)", collectionQuerySpace.getClass().getSimpleName(), collectionQuerySpace.getUid(), collectionQuerySpace.getCollectionPersister().getRole() ); } return space.toString(); } private String extractDetails(Join join) { return String.format( "JOIN (%s) : %s -> %s", determineJoinType( join ), join.getLeftHandSide().getUid(), join.getRightHandSide().getUid() ); } private String determineJoinType(Join join) { if ( JoinDefinedByMetadata.class.isInstance( join ) ) { return "JoinDefinedByMetadata(" + ( (JoinDefinedByMetadata) join ).getJoinedPropertyName() + ")"; } return join.getClass().getSimpleName(); } }
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/loader/plan/build/spi/QuerySpaceTreePrinter.java
Java
lgpl-2.1
11,114
// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License version 2.1 as published by the Free Software Foundation. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #ifndef JUBATUS_CORE_FV_CONVERTER_NUM_FILTER_FACTORY_HPP_ #define JUBATUS_CORE_FV_CONVERTER_NUM_FILTER_FACTORY_HPP_ #include <string> #include <map> namespace jubatus { namespace core { namespace fv_converter { class num_filter; class num_filter_factory { public: num_filter* create( const std::string& name, const std::map<std::string, std::string>& params) const; }; } // namespace fv_converter } // namespace core } // namespace jubatus #endif // JUBATUS_CORE_FV_CONVERTER_NUM_FILTER_FACTORY_HPP_
abetv/jubatus
jubatus/core/fv_converter/num_filter_factory.hpp
C++
lgpl-2.1
1,374
<?php /* Copyright (C) 2008-2010 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2008-2009 Regis Houssin <regis@dolibarr.fr> * * 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, see <http://www.gnu.org/licenses/>. */ /** * \file htdocs/ecm/index.php * \ingroup ecm * \brief Main page for ECM section area * \version $Id: search.php,v 1.19 2011/07/31 23:50:55 eldy Exp $ * \author Laurent Destailleur */ require("../main.inc.php"); require_once(DOL_DOCUMENT_ROOT."/core/class/html.formfile.class.php"); require_once(DOL_DOCUMENT_ROOT."/lib/ecm.lib.php"); require_once(DOL_DOCUMENT_ROOT."/lib/files.lib.php"); require_once(DOL_DOCUMENT_ROOT."/lib/treeview.lib.php"); require_once(DOL_DOCUMENT_ROOT."/ecm/class/ecmdirectory.class.php"); // Load traductions files $langs->load("ecm"); $langs->load("companies"); $langs->load("other"); $langs->load("users"); $langs->load("orders"); $langs->load("propal"); $langs->load("bills"); $langs->load("contracts"); // Security check if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'ecm',''); // Load permissions $user->getrights('ecm'); // Get parameters $socid = isset($_GET["socid"])?$_GET["socid"]:''; $action = isset($_GET["action"])?$_GET["action"]:$_POST['action']; $section=isset($_GET["section"])?$_GET["section"]:$_POST['section']; if (! $section) $section=0; $upload_dir = $conf->ecm->dir_output.'/'.$section; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); if ($page == -1) { $page = 0; } $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="label"; $ecmdir = new ECMDirectory($db); if (! empty($_REQUEST["section"])) { $result=$ecmdir->fetch($_REQUEST["section"]); if (! $result > 0) { dol_print_error($db,$ecmdir->error); exit; } } /******************************************************************* * ACTIONS * * Put here all code to do according to value of "action" parameter ********************************************************************/ /******************************************************************* * PAGE * * Put here all code to do according to value of "action" parameter ********************************************************************/ llxHeader(); $form=new Form($db); $ecmdirstatic = new ECMDirectory($db); $userstatic = new User($db); // Ajout rubriques automatiques $rowspan=0; $sectionauto=array(); if ($conf->product->enabled || $conf->service->enabled) { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'product', 'test'=>$conf->product->enabled, 'label'=>$langs->trans("ProductsAndServices"), 'desc'=>$langs->trans("ECMDocsByProducts")); } if ($conf->societe->enabled) { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'company', 'test'=>$conf->societe->enabled, 'label'=>$langs->trans("ThirdParties"), 'desc'=>$langs->trans("ECMDocsByThirdParties")); } if ($conf->propal->enabled) { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'propal', 'test'=>$conf->propal->enabled, 'label'=>$langs->trans("Prop"), 'desc'=>$langs->trans("ECMDocsByProposals")); } if ($conf->contrat->enabled) { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'contract','test'=>$conf->contrat->enabled, 'label'=>$langs->trans("Contracts"), 'desc'=>$langs->trans("ECMDocsByContracts")); } if ($conf->commande->enabled) { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'order', 'test'=>$conf->commande->enabled,'label'=>$langs->trans("CustomersOrders"), 'desc'=>$langs->trans("ECMDocsByOrders")); } if ($conf->fournisseur->enabled) { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'order_supplier', 'test'=>$conf->fournisseur->enabled, 'label'=>$langs->trans("SuppliersInvoices"), 'desc'=>$langs->trans("ECMDocsByOrders")); } if ($conf->facture->enabled) { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'invoice', 'test'=>$conf->facture->enabled, 'label'=>$langs->trans("CustomersInvoices"), 'desc'=>$langs->trans("ECMDocsByInvoices")); } if ($conf->fournisseur->enabled) { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'invoice_supplier', 'test'=>$conf->fournisseur->enabled, 'label'=>$langs->trans("SuppliersOrders"), 'desc'=>$langs->trans("ECMDocsByOrders")); } //*********************** // List //*********************** print_fiche_titre($langs->trans("ECMArea").' - '.$langs->trans("Search")); //print $langs->trans("ECMAreaDesc")."<br>"; //print $langs->trans("ECMAreaDesc2")."<br>"; //print "<br>\n"; print $langs->trans("FeatureNotYetAvailable").'.<br><br>'; if ($mesg) { print $mesg."<br>"; } // Tool bar $head = ecm_prepare_head_fm($fac); //dol_fiche_head($head, 'search_form', '', 1); print '<table class="border" width="100%"><tr><td width="40%" valign="top">'; // Left area //print_fiche_titre($langs->trans("ECMSectionsManual")); print '<form method="post" action="'.DOL_URL_ROOT.'/ecm/search.php">'; print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<table class="nobordernopadding" width="100%">'; print "<tr class=\"liste_titre\">"; print '<td colspan="2">'.$langs->trans("ECMSearchByKeywords").'</td></tr>'; print "<tr ".$bc[false]."><td>".$langs->trans("Ref").':</td><td align="right"><input type="text" name="search_ref" class="flat" size="14"></td></tr>'; print "<tr ".$bc[false]."><td>".$langs->trans("Title").':</td><td align="right"><input type="text" name="search_title" class="flat" size="14"></td></tr>'; print "<tr ".$bc[false]."><td>".$langs->trans("Keyword").':</td><td align="right"><input type="text" name="search_keyword" class="flat" size="14"></td></tr>'; print "<tr ".$bc[false].'><td colspan="2" align="center"><input type="submit" class="button" value="'.$langs->trans("Search").'"></td></tr>'; print "</table></form>"; //print $langs->trans("ECMSectionManualDesc"); //print_fiche_titre($langs->trans("ECMSectionAuto")); print '<form method="post" action="'.DOL_URL_ROOT.'/ecm/search.php">'; print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<table class="nobordernopadding" width="100%">'; print "<tr class=\"liste_titre\">"; print '<td colspan="4">'.$langs->trans("ECMSearchByEntity").'</td></tr>'; $buthtml='<td rowspan="'.$rowspan.'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>'; $butshown=0; foreach($sectionauto as $sectioncur) { if (! $sectioncur['test']) continue; //if ($butshown % 2 == 0) print '<tr '. $bc[false].'>'; print "<td>".$sectioncur['label'].':</td>'; print '<td'; //if ($butshown % 2 == 1) print ' align="right"'; print '>'; print '<input type="text" name="search_'.$sectioncur['module'].'" class="flat" size="14">'; print '</td>'; //if ($butshown % 2 == 1) print '</tr>'; $butshown++; } //if ($butshown % 2 == 1) // print '<td>&nbsp;</td><td>&nbsp;</td></tr>'; print '<tr '. $bc[false].'><td colspan="4" align="center"><input type="submit" class="button" value="'.$langs->trans("Search").'"></td></tr>'; print "</table></form>"; //print $langs->trans("ECMSectionAutoDesc"); print '</td><td valign="top">'; // Right area $relativepath=$ecmdir->getRelativePath(); $upload_dir = $conf->ecm->dir_output.'/'.$relativepath; $filearray=dol_dir_list($upload_dir,"files",0,'','\.meta$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1); $formfile=new FormFile($db); $param='&amp;section='.$section; $textifempty=($section?$langs->trans("NoFileFound"):$langs->trans("ECMSelectASection")); $formfile->list_of_documents($filearray,'','ecm',$param,1,$relativepath,$user->rights->ecm->upload,1,$textifempty); // print '<table width="100%" class="border">'; // print '<tr><td> </td></tr></table>'; print '</td></tr>'; print '</table>'; print '<br>'; // End of page $db->close(); llxFooter('$Date: 2011/07/31 23:50:55 $ - $Revision: 1.19 $'); ?>
gambess/ERP-Arica
htdocs/ecm/search.php
PHP
lgpl-2.1
8,580
import { ValueSchema, FieldSchema } from '@ephox/boulder'; import { Result } from '@ephox/katamari'; import { BaseMenuButton, BaseMenuButtonApi, baseMenuButtonFields, BaseMenuButtonInstanceApi, MenuButtonItemTypes } from '../../core/MenuButton'; export type ToolbarMenuButtonItemTypes = MenuButtonItemTypes; export type SuccessCallback = (menu: string | ToolbarMenuButtonItemTypes[]) => void; export interface ToolbarMenuButtonApi extends BaseMenuButtonApi { type?: 'menubutton'; onSetup?: (api: ToolbarMenuButtonInstanceApi) => (api: ToolbarMenuButtonInstanceApi) => void; } export interface ToolbarMenuButton extends BaseMenuButton { type: 'menubutton'; onSetup: (api: ToolbarMenuButtonInstanceApi) => (api: ToolbarMenuButtonInstanceApi) => void; } export interface ToolbarMenuButtonInstanceApi extends BaseMenuButtonInstanceApi { } export const MenuButtonSchema = ValueSchema.objOf([ FieldSchema.strictString('type'), ...baseMenuButtonFields ]); export const isMenuButtonButton = (spec: any): spec is ToolbarMenuButton => spec.type === 'menubutton'; export const createMenuButton = (spec: any): Result<ToolbarMenuButton, ValueSchema.SchemaError<any>> => { return ValueSchema.asRaw<ToolbarMenuButton>('menubutton', MenuButtonSchema, spec); };
FernCreek/tinymce
modules/bridge/src/main/ts/ephox/bridge/components/toolbar/ToolbarMenuButton.ts
TypeScript
lgpl-2.1
1,266
// Projeto: Motor Tributario // Biblioteca C# para Cálculos Tributários Do Brasil // NF-e, NFC-e, CT-e, SAT-Fiscal // // Esta biblioteca é software livre; você pode redistribuí-la e/ou modificá-la // sob os termos da Licença Pública Geral Menor do GNU conforme publicada pela // Free Software Foundation; tanto a versão 2.1 da Licença, ou (a seu critério) // qualquer versão posterior. // // Esta biblioteca é distribuída na expectativa de que seja útil, porém, SEM // NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU // ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral Menor // do GNU para mais detalhes. (Arquivo LICENÇA.TXT ou LICENSE.TXT) // // Você deve ter recebido uma cópia da Licença Pública Geral Menor do GNU junto // com esta biblioteca; se não, escreva para a Free Software Foundation, Inc., // no endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. // Você também pode obter uma copia da licença em: // https://github.com/AutomacaoNet/MotorTributarioNet/blob/master/LICENSE using MotorTributarioNet.Impostos.Implementacoes; namespace MotorTributarioNet.Impostos.Tributacoes { public class TributacaoIbpt { private readonly ITributavel _tributavel; private readonly IIbpt _ibpt; public TributacaoIbpt(ITributavel tributavel, IIbpt ibpt) { _tributavel = tributavel; _ibpt = ibpt; } public IResultadoCalculoIbpt Calcula() { var baseCalculo = _tributavel.ValorProduto * _tributavel.QuantidadeProduto - _tributavel.Desconto; var impostoAproximadoFederal = baseCalculo * _ibpt.PercentualFederal / 100; var impostoAproximadoMunicipio = baseCalculo * _ibpt.PercentualMunicipal / 100; var impostoAproximadoEstadual = baseCalculo * _ibpt.PercentualEstadual / 100; var impostoAproximadoImportados = baseCalculo * _ibpt.PercentualFederalImportados / 100; return new ResultadoCalculoIbpt(impostoAproximadoFederal, impostoAproximadoMunicipio, impostoAproximadoEstadual, impostoAproximadoImportados, baseCalculo); } } }
AutomacaoNet/MotorTributarioNet
src/Shared.MotorTributarioNet/Impostos/Tributacoes/TributacaoIbpt.cs
C#
lgpl-2.1
2,720
#include "osgSim/VisibilityGroup" #include "osgDB/Registry" #include "osgDB/Input" #include "osgDB/Output" using namespace osg; using namespace osgSim; using namespace osgDB; // forward declare functions to use later. bool VisibilityGroup_readLocalData(Object& obj, Input& fr); bool VisibilityGroup_writeLocalData(const Object& obj, Output& fw); // register the read and write functions with the osgDB::Registry. RegisterDotOsgWrapperProxy g_VisibilityGroupProxy ( new VisibilityGroup, "VisibilityGroup", "Object Node VisibilityGroup Group", &VisibilityGroup_readLocalData, &VisibilityGroup_writeLocalData ); bool VisibilityGroup_readLocalData(Object& obj, Input& fr) { bool iteratorAdvanced = false; VisibilityGroup& vg = static_cast<VisibilityGroup&>(obj); unsigned int mask = vg.getVolumeIntersectionMask(); if (fr[0].matchWord("volumeIntersectionMask") && fr[1].getUInt(mask)) { vg.setNodeMask(mask); fr+=2; iteratorAdvanced = true; } if (fr[0].matchWord("segmentLength")) { if (fr[1].isFloat()) { float value; fr[1].getFloat(value); vg.setSegmentLength(value); iteratorAdvanced = true; fr += 2; } } if (fr.matchSequence("visibilityVolume")) { // int entry = fr[0].getNoNestedBrackets(); ++fr; Node* node = NULL; if((node=fr.readNode())!=NULL) { vg.setVisibilityVolume(node); iteratorAdvanced = true; } } return iteratorAdvanced; } bool VisibilityGroup_writeLocalData(const Object& obj, Output& fw) { const VisibilityGroup& vg = static_cast<const VisibilityGroup&>(obj); fw.indent()<<"volumeIntersectionMask 0x"<<std::hex<<vg.getVolumeIntersectionMask()<<std::dec<<std::endl; fw.indent()<<"segmentLength "<<vg.getSegmentLength()<<std::endl; fw.indent()<<"visibilityVolume" <<std::endl; fw.moveIn(); fw.writeObject(*vg.getVisibilityVolume()); fw.moveOut(); return true; }
joevandyk/osg
src/osgPlugins/osgSim/IO_VisibilityGroup.cpp
C++
lgpl-2.1
2,072
package net.darkaqua.blacksmith.api.client.particle; /** * Created by cout970 on 18/01/2016. */ public interface IParticle { String getName(); }
Darkaqua/Blacksmith-Api
src/main/java/api/net/darkaqua/blacksmith/api/client/particle/IParticle.java
Java
lgpl-2.1
153
/* _______________________________________________________________________ DAKOTA: Design Analysis Kit for Optimization and Terascale Applications Copyright (c) 2010, Sandia National Laboratories. This software is distributed under the GNU Lesser General Public License. For more information, see the README file in the top Dakota directory. _______________________________________________________________________ */ //- Class: DataModel //- Description: Class implementation //- Owner: Mike Eldred #include "DataModel.hpp" #include "dakota_data_io.hpp" namespace Dakota { DataModelRep::DataModelRep(): modelType("single"), //approxPointReuse("none"), hierarchicalTags(false), pointsTotal(0), pointsManagement(DEFAULT_POINTS), approxImportAnnotated(true), approxExportAnnotated(true), approxCorrectionType(NO_CORRECTION), approxCorrectionOrder(0), modelUseDerivsFlag(false), polynomialOrder(2), krigingMaxTrials(0), krigingNugget(0.0), krigingFindNugget(0), mlsPolyOrder(0), mlsWeightFunction(0), rbfBases(0), rbfMaxPts(0), rbfMaxSubsets(0), rbfMinPartition(0), marsMaxBases(0), annRandomWeight(0),annNodes(0), annRange(0.0), trendOrder("reduced_quadratic"), pointSelection(false), crossValidateFlag(false), numFolds(0), percentFold(0.0), pressFlag(false), approxChallengeAnnotated(true), referenceCount(1) { } void DataModelRep::write(MPIPackBuffer& s) const { s << idModel << modelType << variablesPointer << interfacePointer << responsesPointer << hierarchicalTags << subMethodPointer << surrogateFnIndices << surrogateType << truthModelPointer << lowFidelityModelPointer << pointsTotal << pointsManagement << approxPointReuse << approxImportFile << approxImportAnnotated << approxExportFile << approxExportAnnotated << approxExportModelFile << approxCorrectionType << approxCorrectionOrder << modelUseDerivsFlag << polynomialOrder << krigingCorrelations << krigingOptMethod << krigingMaxTrials << krigingMaxCorrelations << krigingMinCorrelations << krigingNugget << krigingFindNugget << mlsPolyOrder << mlsWeightFunction << rbfBases << rbfMaxPts << rbfMaxSubsets << rbfMinPartition << marsMaxBases << marsInterpolation << annRandomWeight << annNodes << annRange << trendOrder << pointSelection << diagMetrics << crossValidateFlag << numFolds << percentFold << pressFlag << approxChallengeFile << approxChallengeAnnotated << optionalInterfRespPointer << primaryVarMaps << secondaryVarMaps << primaryRespCoeffs << secondaryRespCoeffs; } void DataModelRep::read(MPIUnpackBuffer& s) { s >> idModel >> modelType >> variablesPointer >> interfacePointer >> responsesPointer >> hierarchicalTags >> subMethodPointer >> surrogateFnIndices >> surrogateType >> truthModelPointer >> lowFidelityModelPointer >> pointsTotal >> pointsManagement >> approxPointReuse >> approxImportFile >> approxImportAnnotated >> approxExportFile >> approxExportAnnotated >> approxExportModelFile >> approxCorrectionType >> approxCorrectionOrder >> modelUseDerivsFlag >> polynomialOrder >> krigingCorrelations >> krigingOptMethod >> krigingMaxTrials >> krigingMaxCorrelations >> krigingMinCorrelations >> krigingNugget >> krigingFindNugget >> mlsPolyOrder >> mlsWeightFunction >> rbfBases >> rbfMaxPts >> rbfMaxSubsets >> rbfMinPartition >> marsMaxBases >> marsInterpolation >> annRandomWeight >> annNodes >> annRange >> trendOrder >> pointSelection >> diagMetrics >> crossValidateFlag >> numFolds >> percentFold >> pressFlag >> approxChallengeFile >> approxChallengeAnnotated >> optionalInterfRespPointer >> primaryVarMaps >> secondaryVarMaps >> primaryRespCoeffs >> secondaryRespCoeffs; } void DataModelRep::write(std::ostream& s) const { s << idModel << modelType << variablesPointer << interfacePointer << responsesPointer << hierarchicalTags << subMethodPointer << surrogateFnIndices << surrogateType << truthModelPointer << lowFidelityModelPointer << pointsTotal << pointsManagement << approxPointReuse << approxImportFile << approxImportAnnotated << approxExportFile << approxExportAnnotated << approxExportModelFile << approxCorrectionType << approxCorrectionOrder << modelUseDerivsFlag << polynomialOrder << krigingCorrelations << krigingOptMethod << krigingMaxTrials << krigingMaxCorrelations << krigingMinCorrelations << krigingNugget << krigingFindNugget << mlsPolyOrder << mlsWeightFunction << rbfBases << rbfMaxPts << rbfMaxSubsets << rbfMinPartition << marsMaxBases << marsInterpolation << annRandomWeight << annNodes << annRange << trendOrder << pointSelection << diagMetrics << crossValidateFlag << numFolds << percentFold << pressFlag << approxChallengeFile << approxChallengeAnnotated << optionalInterfRespPointer << primaryVarMaps << secondaryVarMaps << primaryRespCoeffs << secondaryRespCoeffs; } DataModel::DataModel(): dataModelRep(new DataModelRep()) { #ifdef REFCOUNT_DEBUG Cout << "DataModel::DataModel(), dataModelRep referenceCount = " << dataModelRep->referenceCount << std::endl; #endif } DataModel::DataModel(const DataModel& data_model) { // Increment new (no old to decrement) dataModelRep = data_model.dataModelRep; if (dataModelRep) // Check for an assignment of NULL dataModelRep->referenceCount++; #ifdef REFCOUNT_DEBUG Cout << "DataModel::DataModel(DataModel&)" << std::endl; if (dataModelRep) Cout << "dataModelRep referenceCount = " << dataModelRep->referenceCount << std::endl; #endif } DataModel& DataModel::operator=(const DataModel& data_model) { if (dataModelRep != data_model.dataModelRep) { // normal case: old != new // Decrement old if (dataModelRep) // Check for NULL if ( --dataModelRep->referenceCount == 0 ) delete dataModelRep; // Assign and increment new dataModelRep = data_model.dataModelRep; if (dataModelRep) // Check for NULL dataModelRep->referenceCount++; } // else if assigning same rep, then do nothing since referenceCount // should already be correct #ifdef REFCOUNT_DEBUG Cout << "DataModel::operator=(DataModel&)" << std::endl; if (dataModelRep) Cout << "dataModelRep referenceCount = " << dataModelRep->referenceCount << std::endl; #endif return *this; } DataModel::~DataModel() { if (dataModelRep) { // Check for NULL --dataModelRep->referenceCount; // decrement #ifdef REFCOUNT_DEBUG Cout << "dataModelRep referenceCount decremented to " << dataModelRep->referenceCount << std::endl; #endif if (dataModelRep->referenceCount == 0) { #ifdef REFCOUNT_DEBUG Cout << "deleting dataModelRep" << std::endl; #endif delete dataModelRep; } } } } // namespace Dakota
pemryan/DAKOTA
src/DataModel.cpp
C++
lgpl-2.1
6,824
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "customcolordialog.h" #include "huecontrol.h" #include "colorbox.h" #include <QtGui/QHBoxLayout> #include <QtGui/QLabel> #include <QtGui/QPainter> #include <QtGui/QDoubleSpinBox> #include <QtGui/QGridLayout> #include <QtGui/QPushButton> #include <QtGui/QDialogButtonBox> #include <QtGui/QGraphicsEffect> namespace QmlEditorWidgets { CustomColorDialog::CustomColorDialog(QWidget *parent) : QFrame(parent ) { setFrameStyle(QFrame::NoFrame); setFrameShape(QFrame::StyledPanel); setFrameShadow(QFrame::Sunken); QGraphicsDropShadowEffect *dropShadowEffect = new QGraphicsDropShadowEffect; dropShadowEffect->setBlurRadius(6); dropShadowEffect->setOffset(2, 2); setGraphicsEffect(dropShadowEffect); setAutoFillBackground(true); m_hueControl = new HueControl(this); m_colorBox = new ColorBox(this); QWidget *colorFrameWidget = new QWidget(this); QVBoxLayout* vBox = new QVBoxLayout(colorFrameWidget); colorFrameWidget->setLayout(vBox); vBox->setSpacing(0); vBox->setMargin(0); vBox->setContentsMargins(0,5,0,28); m_beforeColorWidget = new QFrame(colorFrameWidget); m_beforeColorWidget->setFixedSize(30, 18); m_beforeColorWidget->setAutoFillBackground(true); m_currentColorWidget = new QFrame(colorFrameWidget); m_currentColorWidget->setFixedSize(30, 18); m_currentColorWidget->setAutoFillBackground(true); vBox->addWidget(m_beforeColorWidget); vBox->addWidget(m_currentColorWidget); m_rSpinBox = new QDoubleSpinBox(this); m_gSpinBox = new QDoubleSpinBox(this); m_bSpinBox = new QDoubleSpinBox(this); m_alphaSpinBox = new QDoubleSpinBox(this); QGridLayout *gridLayout = new QGridLayout(this); gridLayout->setSpacing(4); gridLayout->setVerticalSpacing(4); gridLayout->setMargin(4); setLayout(gridLayout); gridLayout->addWidget(m_colorBox, 0, 0, 4, 1); gridLayout->addWidget(m_hueControl, 0, 1, 4, 1); gridLayout->addWidget(colorFrameWidget, 0, 2, 2, 1); gridLayout->addWidget(new QLabel("R", this), 0, 3, 1, 1); gridLayout->addWidget(new QLabel("G", this), 1, 3, 1, 1); gridLayout->addWidget(new QLabel("B", this), 2, 3, 1, 1); gridLayout->addWidget(new QLabel("A", this), 3, 3, 1, 1); gridLayout->addWidget(m_rSpinBox, 0, 4, 1, 1); gridLayout->addWidget(m_gSpinBox, 1, 4, 1, 1); gridLayout->addWidget(m_bSpinBox, 2, 4, 1, 1); gridLayout->addWidget(m_alphaSpinBox, 3, 4, 1, 1); QDialogButtonBox *buttonBox = new QDialogButtonBox(this); QPushButton *cancelButton = buttonBox->addButton(QDialogButtonBox::Cancel); QPushButton *applyButton = buttonBox->addButton(QDialogButtonBox::Apply); gridLayout->addWidget(buttonBox, 4, 0, 1, 2); resize(sizeHint()); connect(m_colorBox, SIGNAL(colorChanged()), this, SLOT(onColorBoxChanged())); connect(m_alphaSpinBox, SIGNAL(valueChanged(double)), this, SLOT(spinBoxChanged())); connect(m_rSpinBox, SIGNAL(valueChanged(double)), this, SLOT(spinBoxChanged())); connect(m_gSpinBox, SIGNAL(valueChanged(double)), this, SLOT(spinBoxChanged())); connect(m_bSpinBox, SIGNAL(valueChanged(double)), this, SLOT(spinBoxChanged())); connect(m_hueControl, SIGNAL(hueChanged(int)), this, SLOT(onHueChanged(int))); connect(applyButton, SIGNAL(pressed()), this, SLOT(onAccept())); connect(cancelButton, SIGNAL(pressed()), this, SIGNAL(rejected())); m_alphaSpinBox->setMaximum(1); m_rSpinBox->setMaximum(1); m_gSpinBox->setMaximum(1); m_bSpinBox->setMaximum(1); m_alphaSpinBox->setSingleStep(0.1); m_rSpinBox->setSingleStep(0.1); m_gSpinBox->setSingleStep(0.1); m_bSpinBox->setSingleStep(0.1); m_blockUpdate = false; } void CustomColorDialog::setupColor(const QColor &color) { QPalette pal = m_beforeColorWidget->palette(); pal.setColor(QPalette::Background, color); m_beforeColorWidget->setPalette(pal); setColor(color); } void CustomColorDialog::spinBoxChanged() { if (m_blockUpdate) return; QColor newColor; newColor.setAlphaF(m_alphaSpinBox->value()); newColor.setRedF(m_rSpinBox->value()); newColor.setGreenF(m_gSpinBox->value()); newColor.setBlueF(m_bSpinBox->value()); setColor(newColor); } void CustomColorDialog::onColorBoxChanged() { if (m_blockUpdate) return; setColor(m_colorBox->color()); } void CustomColorDialog::setupWidgets() { m_blockUpdate = true; m_hueControl->setHue(m_color.hsvHue()); m_alphaSpinBox->setValue(m_color.alphaF()); m_rSpinBox->setValue(m_color.redF()); m_gSpinBox->setValue(m_color.greenF()); m_bSpinBox->setValue(m_color.blueF()); m_colorBox->setColor(m_color); QPalette pal = m_currentColorWidget->palette(); pal.setColor(QPalette::Background, m_color); m_currentColorWidget->setPalette(pal); m_blockUpdate = false; } void CustomColorDialog::leaveEvent(QEvent *) { #ifdef Q_WS_MAC unsetCursor(); #endif } void CustomColorDialog::enterEvent(QEvent *) { #ifdef Q_WS_MAC setCursor(Qt::ArrowCursor); #endif } } //QmlEditorWidgets
bakaiadam/collaborative_qt_creator
src/libs/qmleditorwidgets/customcolordialog.cpp
C++
lgpl-2.1
6,384
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "qt4maemotarget.h" #include "maemoglobal.h" #include "maemopackagecreationstep.h" #include "maemorunconfiguration.h" #include "maemotoolchain.h" #include "qt4maemodeployconfiguration.h" #include <coreplugin/filemanager.h> #include <coreplugin/icore.h> #include <coreplugin/iversioncontrol.h> #include <coreplugin/vcsmanager.h> #include <projectexplorer/abi.h> #include <projectexplorer/customexecutablerunconfiguration.h> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/projectnodes.h> #include <projectexplorer/toolchain.h> #include <qt4projectmanager/qt4project.h> #include <qt4projectmanager/qt4buildconfiguration.h> #include <qt4projectmanager/qt4nodes.h> #include <qtsupport/baseqtversion.h> #include <utils/fileutils.h> #include <utils/filesystemwatcher.h> #include <utils/qtcassert.h> #include <QtGui/QApplication> #include <QtGui/QMainWindow> #include <QtCore/QBuffer> #include <QtCore/QDateTime> #include <QtCore/QLocale> #include <QtCore/QRegExp> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QFileInfo> #include <QtCore/QProcess> #include <QtCore/QStringList> #include <QtGui/QIcon> #include <QtGui/QMessageBox> #include <cctype> using namespace Qt4ProjectManager; namespace Madde { namespace Internal { namespace { const QByteArray NameFieldName("Package"); const QByteArray IconFieldName("XB-Maemo-Icon-26"); const QByteArray ShortDescriptionFieldName("Description"); const QByteArray PackageFieldName("Package"); const QLatin1String PackagingDirName("qtc_packaging"); const QByteArray NameTag("Name"); const QByteArray SummaryTag("Summary"); const QByteArray VersionTag("Version"); const QByteArray ReleaseTag("Release"); bool adaptTagValue(QByteArray &document, const QByteArray &fieldName, const QByteArray &newFieldValue, bool caseSensitive) { QByteArray adaptedLine = fieldName + ": " + newFieldValue; const QByteArray completeTag = fieldName + ':'; const int lineOffset = caseSensitive ? document.indexOf(completeTag) : document.toLower().indexOf(completeTag.toLower()); if (lineOffset == -1) { document.append(adaptedLine).append('\n'); return true; } int newlineOffset = document.indexOf('\n', lineOffset); bool updated = false; if (newlineOffset == -1) { newlineOffset = document.length(); adaptedLine += '\n'; updated = true; } const int replaceCount = newlineOffset - lineOffset; if (!updated && document.mid(lineOffset, replaceCount) != adaptedLine) updated = true; if (updated) document.replace(lineOffset, replaceCount, adaptedLine); return updated; } } // anonymous namespace AbstractQt4MaemoTarget::AbstractQt4MaemoTarget(Qt4Project *parent, const QString &id) : Qt4BaseTarget(parent, id), m_filesWatcher(new Utils::FileSystemWatcher(this)), m_buildConfigurationFactory(new Qt4BuildConfigurationFactory(this)), m_isInitialized(false) { m_filesWatcher->setObjectName(QLatin1String("Qt4MaemoTarget")); setIcon(QIcon(":/projectexplorer/images/MaemoDevice.png")); connect(parent, SIGNAL(addedTarget(ProjectExplorer::Target*)), this, SLOT(handleTargetAdded(ProjectExplorer::Target*))); connect(parent, SIGNAL(fromMapFinished()), this, SLOT(handleFromMapFinished())); } AbstractQt4MaemoTarget::~AbstractQt4MaemoTarget() { } QList<ProjectExplorer::ToolChain *> AbstractQt4MaemoTarget::possibleToolChains(ProjectExplorer::BuildConfiguration *bc) const { QList<ProjectExplorer::ToolChain *> result; Qt4BuildConfiguration *qt4Bc = qobject_cast<Qt4BuildConfiguration *>(bc); if (!qt4Bc) return result; QList<ProjectExplorer::ToolChain *> candidates = Qt4BaseTarget::possibleToolChains(bc); foreach (ProjectExplorer::ToolChain *i, candidates) { MaemoToolChain *tc = dynamic_cast<MaemoToolChain *>(i); if (!tc || !qt4Bc->qtVersion()) continue; if (tc->qtVersionId() == qt4Bc->qtVersion()->uniqueId()) result.append(tc); } return result; } ProjectExplorer::IBuildConfigurationFactory *AbstractQt4MaemoTarget::buildConfigurationFactory() const { return m_buildConfigurationFactory; } void AbstractQt4MaemoTarget::createApplicationProFiles() { removeUnconfiguredCustomExectutableRunConfigurations(); QList<Qt4ProFileNode *> profiles = qt4Project()->applicationProFiles(); QSet<QString> paths; foreach (Qt4ProFileNode *pro, profiles) paths << pro->path(); foreach (ProjectExplorer::RunConfiguration *rc, runConfigurations()) if (MaemoRunConfiguration *qt4rc = qobject_cast<MaemoRunConfiguration *>(rc)) paths.remove(qt4rc->proFilePath()); // Only add new runconfigurations if there are none. foreach (const QString &path, paths) addRunConfiguration(new MaemoRunConfiguration(this, path)); // Oh still none? Add a custom executable runconfiguration if (runConfigurations().isEmpty()) { addRunConfiguration(new ProjectExplorer::CustomExecutableRunConfiguration(this)); } } QList<ProjectExplorer::RunConfiguration *> AbstractQt4MaemoTarget::runConfigurationsForNode(ProjectExplorer::Node *n) { QList<ProjectExplorer::RunConfiguration *> result; foreach (ProjectExplorer::RunConfiguration *rc, runConfigurations()) if (MaemoRunConfiguration *mrc = qobject_cast<MaemoRunConfiguration *>(rc)) if (mrc->proFilePath() == n->path()) result << rc; return result; } bool AbstractQt4MaemoTarget::setProjectVersion(const QString &version, QString *error) { bool success = true; foreach (Target * const target, project()->targets()) { AbstractQt4MaemoTarget * const maemoTarget = qobject_cast<AbstractQt4MaemoTarget *>(target); if (maemoTarget) { if (!maemoTarget->setProjectVersionInternal(version, error)) success = false; } } return success; } bool AbstractQt4MaemoTarget::setPackageName(const QString &name) { bool success = true; foreach (Target * const target, project()->targets()) { AbstractQt4MaemoTarget * const maemoTarget = qobject_cast<AbstractQt4MaemoTarget *>(target); if (maemoTarget) { if (!maemoTarget->setPackageNameInternal(name)) success = false; } } return success; } bool AbstractQt4MaemoTarget::setShortDescription(const QString &description) { bool success = true; foreach (Target * const target, project()->targets()) { AbstractQt4MaemoTarget * const maemoTarget = qobject_cast<AbstractQt4MaemoTarget *>(target); if (maemoTarget) { if (!maemoTarget->setShortDescriptionInternal(description)) success = false; } } return success; } QSharedPointer<QFile> AbstractQt4MaemoTarget::openFile(const QString &filePath, QIODevice::OpenMode mode, QString *error) const { const QString nativePath = QDir::toNativeSeparators(filePath); QSharedPointer<QFile> file(new QFile(filePath)); if (!file->open(mode)) { if (error) { *error = tr("Cannot open file '%1': %2") .arg(nativePath, file->errorString()); } file.clear(); } return file; } void AbstractQt4MaemoTarget::handleFromMapFinished() { handleTargetAdded(this); } void AbstractQt4MaemoTarget::handleTargetAdded(ProjectExplorer::Target *target) { if (target != this) return; if (!project()->rootProjectNode()) { // Project is not fully setup yet, happens on new project // we wait for the fromMapFinished that comes afterwards return; } disconnect(project(), SIGNAL(fromMapFinished()), this, SLOT(handleFromMapFinished())); disconnect(project(), SIGNAL(addedTarget(ProjectExplorer::Target*)), this, SLOT(handleTargetAdded(ProjectExplorer::Target*))); connect(project(), SIGNAL(aboutToRemoveTarget(ProjectExplorer::Target*)), SLOT(handleTargetToBeRemoved(ProjectExplorer::Target*))); const ActionStatus status = createTemplates(); if (status == ActionFailed) return; if (status == ActionSuccessful) // Don't do this when the packaging data already exists. initPackagingSettingsFromOtherTarget(); handleTargetAddedSpecial(); if (status == ActionSuccessful) { const QStringList &files = packagingFilePaths(); if (!files.isEmpty()) { const QString list = QLatin1String("<ul><li>") + files.join(QLatin1String("</li><li>")) + QLatin1String("</li></ul>"); QMessageBox::StandardButton button = QMessageBox::question(Core::ICore::instance()->mainWindow(), tr("Add Packaging Files to Project"), tr("<html>Qt Creator has set up the following files to enable " "packaging:\n %1\nDo you want to add them to the project?</html>") .arg(list), QMessageBox::Yes | QMessageBox::No); if (button == QMessageBox::Yes) { ProjectExplorer::ProjectExplorerPlugin::instance() ->addExistingFiles(project()->rootProjectNode(), files); } } } m_isInitialized = true; } void AbstractQt4MaemoTarget::handleTargetToBeRemoved(ProjectExplorer::Target *target) { if (target != this) return; if (!targetCanBeRemoved()) return; Core::ICore * const core = Core::ICore::instance(); const int answer = QMessageBox::warning(core->mainWindow(), tr("Qt Creator"), tr("Do you want to remove the packaging file(s) " "associated with the target '%1'?").arg(displayName()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (answer == QMessageBox::No) return; const QStringList pkgFilePaths = packagingFilePaths(); if (!pkgFilePaths.isEmpty()) { project()->rootProjectNode()->removeFiles(ProjectExplorer::UnknownFileType, pkgFilePaths); Core::IVersionControl * const vcs = core->vcsManager() ->findVersionControlForDirectory(QFileInfo(pkgFilePaths.first()).dir().path()); if (vcs && vcs->supportsOperation(Core::IVersionControl::DeleteOperation)) { foreach (const QString &filePath, pkgFilePaths) vcs->vcsDelete(filePath); } } delete m_filesWatcher; removeTarget(); QString error; const QString packagingPath = project()->projectDirectory() + QLatin1Char('/') + PackagingDirName; const QStringList otherContents = QDir(packagingPath).entryList(QDir::Dirs | QDir::Files | QDir::Hidden | QDir::NoDotAndDotDot); if (otherContents.isEmpty()) { if (!Utils::FileUtils::removeRecursively(packagingPath, &error)) qDebug("%s", qPrintable(error)); } } AbstractQt4MaemoTarget::ActionStatus AbstractQt4MaemoTarget::createTemplates() { QDir projectDir(project()->projectDirectory()); if (!projectDir.exists(PackagingDirName) && !projectDir.mkdir(PackagingDirName)) { raiseError(tr("Error creating packaging directory '%1'.") .arg(PackagingDirName)); return ActionFailed; } return createSpecialTemplates(); } bool AbstractQt4MaemoTarget::initPackagingSettingsFromOtherTarget() { bool success = true; foreach (const Target * const target, project()->targets()) { const AbstractQt4MaemoTarget * const maemoTarget = qobject_cast<const AbstractQt4MaemoTarget *>(target); if (maemoTarget && maemoTarget != this && maemoTarget->m_isInitialized) { if (!setProjectVersionInternal(maemoTarget->projectVersion())) success = false; if (!setPackageNameInternal(maemoTarget->packageName())) success = false; if (!setShortDescriptionInternal(maemoTarget->shortDescription())) success = false; break; } } return initAdditionalPackagingSettingsFromOtherTarget() && success; } void AbstractQt4MaemoTarget::raiseError(const QString &reason) { QMessageBox::critical(0, tr("Error creating MeeGo templates"), reason); } AbstractDebBasedQt4MaemoTarget::AbstractDebBasedQt4MaemoTarget(Qt4Project *parent, const QString &id) : AbstractQt4MaemoTarget(parent, id) { } AbstractDebBasedQt4MaemoTarget::~AbstractDebBasedQt4MaemoTarget() {} QString AbstractDebBasedQt4MaemoTarget::projectVersion(QString *error) const { QSharedPointer<QFile> changeLog = openFile(changeLogFilePath(), QIODevice::ReadOnly, error); if (!changeLog) return QString(); const QByteArray &firstLine = changeLog->readLine(); const int openParenPos = firstLine.indexOf('('); if (openParenPos == -1) { if (error) { *error = tr("Debian changelog file '%1' has unexpected format.") .arg(QDir::toNativeSeparators(changeLog->fileName())); } return QString(); } const int closeParenPos = firstLine.indexOf(')', openParenPos); if (closeParenPos == -1) { if (error) { *error = tr("Debian changelog file '%1' has unexpected format.") .arg(QDir::toNativeSeparators(changeLog->fileName())); } return QString(); } return QString::fromUtf8(firstLine.mid(openParenPos + 1, closeParenPos - openParenPos - 1).data()); } bool AbstractDebBasedQt4MaemoTarget::setProjectVersionInternal(const QString &version, QString *error) { const QString filePath = changeLogFilePath(); Utils::FileReader reader; if (!reader.fetch(filePath, error)) return false; QString content = QString::fromUtf8(reader.data()); if (content.contains(QLatin1Char('(') + version + QLatin1Char(')'))) { if (error) { *error = tr("Refusing to update changelog file: Already contains version '%1'.") .arg(version); } return false; } int maintainerOffset = content.indexOf(QLatin1String("\n -- ")); const int eolOffset = content.indexOf(QLatin1Char('\n'), maintainerOffset+1); if (maintainerOffset == -1 || eolOffset == -1) { if (error) { *error = tr("Cannot update changelog: Invalid format (no maintainer entry found)."); } return false; } ++maintainerOffset; const QDateTime currentDateTime = QDateTime::currentDateTime(); QDateTime utcDateTime = QDateTime(currentDateTime); utcDateTime.setTimeSpec(Qt::UTC); int utcOffsetSeconds = currentDateTime.secsTo(utcDateTime); QChar sign; if (utcOffsetSeconds < 0) { utcOffsetSeconds = -utcOffsetSeconds; sign = QLatin1Char('-'); } else { sign = QLatin1Char('+'); } const int utcOffsetMinutes = (utcOffsetSeconds / 60) % 60; const int utcOffsetHours = utcOffsetSeconds / 3600; const QString dateString = QString::fromLatin1("%1, %2 %3 %4 %5%6%7") .arg(shortDayOfWeekName(currentDateTime)) .arg(currentDateTime.toString(QLatin1String("dd"))) .arg(shortMonthName(currentDateTime)) .arg(currentDateTime.toString(QLatin1String("yyyy hh:mm:ss"))).arg(sign) .arg(utcOffsetHours, 2, 10, QLatin1Char('0')) .arg(utcOffsetMinutes, 2, 10, QLatin1Char('0')); const QString maintainerLine = content.mid(maintainerOffset, eolOffset - maintainerOffset + 1) .replace(QRegExp(QLatin1String("> [^\\n]*\n")), QString::fromLocal8Bit("> %1").arg(dateString)); QString versionLine = content.left(content.indexOf(QLatin1Char('\n'))) .replace(QRegExp(QLatin1String("\\([a-zA-Z0-9_\\.]+\\)")), QLatin1Char('(') + version + QLatin1Char(')')); const QString newEntry = versionLine + QLatin1String("\n * <Add change description here>\n\n") + maintainerLine + QLatin1String("\n\n"); content.prepend(newEntry); Core::FileChangeBlocker update(filePath); Utils::FileSaver saver(filePath); saver.write(content.toUtf8()); return saver.finalize(error); } QIcon AbstractDebBasedQt4MaemoTarget::packageManagerIcon(QString *error) const { const QByteArray &base64Icon = controlFileFieldValue(IconFieldName, true); if (base64Icon.isEmpty()) return QIcon(); QPixmap pixmap; if (!pixmap.loadFromData(QByteArray::fromBase64(base64Icon))) { if (error) *error = tr("Invalid icon data in Debian control file."); return QIcon(); } return QIcon(pixmap); } bool AbstractDebBasedQt4MaemoTarget::setPackageManagerIconInternal(const QString &iconFilePath, QString *error) { const QString filePath = controlFilePath(); Utils::FileReader reader; if (!reader.fetch(filePath, error)) return false; const QPixmap pixmap(iconFilePath); if (pixmap.isNull()) { if (error) *error = tr("Could not read image file '%1'.").arg(iconFilePath); return false; } QByteArray iconAsBase64; QBuffer buffer(&iconAsBase64); buffer.open(QIODevice::WriteOnly); if (!pixmap.scaled(packageManagerIconSize()).save(&buffer, QFileInfo(iconFilePath).suffix().toAscii())) { if (error) *error = tr("Could not export image file '%1'.").arg(iconFilePath); return false; } buffer.close(); iconAsBase64 = iconAsBase64.toBase64(); QByteArray contents = reader.data(); const QByteArray iconFieldNameWithColon = IconFieldName + ':'; const int iconFieldPos = contents.startsWith(iconFieldNameWithColon) ? 0 : contents.indexOf('\n' + iconFieldNameWithColon); if (iconFieldPos == -1) { if (!contents.endsWith('\n')) contents += '\n'; contents.append(iconFieldNameWithColon).append(' ').append(iconAsBase64) .append('\n'); } else { const int oldIconStartPos = (iconFieldPos != 0) + iconFieldPos + iconFieldNameWithColon.length(); int nextEolPos = contents.indexOf('\n', oldIconStartPos); while (nextEolPos != -1 && nextEolPos != contents.length() - 1 && contents.at(nextEolPos + 1) != '\n' && (contents.at(nextEolPos + 1) == '#' || std::isspace(contents.at(nextEolPos + 1)))) nextEolPos = contents.indexOf('\n', nextEolPos + 1); if (nextEolPos == -1) nextEolPos = contents.length(); contents.replace(oldIconStartPos, nextEolPos - oldIconStartPos, ' ' + iconAsBase64); } Core::FileChangeBlocker update(filePath); Utils::FileSaver saver(filePath); saver.write(contents); return saver.finalize(error); } QString AbstractDebBasedQt4MaemoTarget::packageName() const { return QString::fromUtf8(controlFileFieldValue(NameFieldName, false)); } bool AbstractDebBasedQt4MaemoTarget::setPackageNameInternal(const QString &packageName) { const QString oldPackageName = this->packageName(); if (!setControlFieldValue(NameFieldName, packageName.toUtf8())) return false; if (!setControlFieldValue("Source", packageName.toUtf8())) return false; Utils::FileReader reader; if (!reader.fetch(changeLogFilePath())) return false; QString changelogContents = QString::fromUtf8(reader.data()); QRegExp pattern(QLatin1String("[^\\s]+( \\(\\d\\.\\d\\.\\d\\))")); changelogContents.replace(pattern, packageName + QLatin1String("\\1")); Utils::FileSaver saver(changeLogFilePath()); saver.write(changelogContents.toUtf8()); if (!saver.finalize()) return false; if (!reader.fetch(rulesFilePath())) return false; QByteArray rulesContents = reader.data(); const QString oldString = QLatin1String("debian/") + oldPackageName; const QString newString = QLatin1String("debian/") + packageName; rulesContents.replace(oldString.toUtf8(), newString.toUtf8()); Utils::FileSaver rulesSaver(rulesFilePath()); rulesSaver.write(rulesContents); return rulesSaver.finalize(); } QString AbstractDebBasedQt4MaemoTarget::packageManagerName() const { return QString::fromUtf8(controlFileFieldValue(packageManagerNameFieldName(), false)); } bool AbstractDebBasedQt4MaemoTarget::setPackageManagerName(const QString &name, QString *error) { bool success = true; foreach (Target * const t, project()->targets()) { AbstractDebBasedQt4MaemoTarget * const target = qobject_cast<AbstractDebBasedQt4MaemoTarget *>(t); if (target) { if (!target->setPackageManagerNameInternal(name, error)) success = false; } } return success; } bool AbstractDebBasedQt4MaemoTarget::setPackageManagerNameInternal(const QString &name, QString *error) { Q_UNUSED(error); return setControlFieldValue(packageManagerNameFieldName(), name.toUtf8()); } QString AbstractDebBasedQt4MaemoTarget::shortDescription() const { return QString::fromUtf8(controlFileFieldValue(ShortDescriptionFieldName, false)); } QString AbstractDebBasedQt4MaemoTarget::packageFileName() const { return QString::fromUtf8(controlFileFieldValue(PackageFieldName, false)) + QLatin1Char('_') + projectVersion() + QLatin1String("_armel.deb"); } bool AbstractDebBasedQt4MaemoTarget::setShortDescriptionInternal(const QString &description) { return setControlFieldValue(ShortDescriptionFieldName, description.toUtf8()); } QString AbstractDebBasedQt4MaemoTarget::debianDirPath() const { return project()->projectDirectory() + QLatin1Char('/') + PackagingDirName + QLatin1Char('/') + debianDirName(); } QStringList AbstractDebBasedQt4MaemoTarget::debianFiles() const { return QDir(debianDirPath()) .entryList(QDir::Files, QDir::Name | QDir::IgnoreCase); } QString AbstractDebBasedQt4MaemoTarget::changeLogFilePath() const { return debianDirPath() + QLatin1String("/changelog"); } QString AbstractDebBasedQt4MaemoTarget::controlFilePath() const { return debianDirPath() + QLatin1String("/control"); } QString AbstractDebBasedQt4MaemoTarget::rulesFilePath() const { return debianDirPath() + QLatin1String("/rules"); } QByteArray AbstractDebBasedQt4MaemoTarget::controlFileFieldValue(const QString &key, bool multiLine) const { QByteArray value; Utils::FileReader reader; if (!reader.fetch(controlFilePath())) return value; const QByteArray &contents = reader.data(); const int keyPos = contents.indexOf(key.toUtf8() + ':'); if (keyPos == -1) return value; int valueStartPos = keyPos + key.length() + 1; int valueEndPos = contents.indexOf('\n', keyPos); if (valueEndPos == -1) valueEndPos = contents.count(); value = contents.mid(valueStartPos, valueEndPos - valueStartPos).trimmed(); if (multiLine) { Q_FOREVER { valueStartPos = valueEndPos + 1; if (valueStartPos >= contents.count()) break; const char firstChar = contents.at(valueStartPos); if (firstChar == '#' || isspace(firstChar)) { valueEndPos = contents.indexOf('\n', valueStartPos); if (valueEndPos == -1) valueEndPos = contents.count(); if (firstChar != '#') { value += contents.mid(valueStartPos, valueEndPos - valueStartPos).trimmed(); } } else { break; } } } return value; } bool AbstractDebBasedQt4MaemoTarget::setControlFieldValue(const QByteArray &fieldName, const QByteArray &fieldValue) { Utils::FileReader reader; if (!reader.fetch(controlFilePath())) return false; QByteArray contents = reader.data(); if (adaptControlFileField(contents, fieldName, fieldValue)) { Core::FileChangeBlocker update(controlFilePath()); Utils::FileSaver saver(controlFilePath()); saver.write(contents); return saver.finalize(); } return true; } bool AbstractDebBasedQt4MaemoTarget::adaptControlFileField(QByteArray &document, const QByteArray &fieldName, const QByteArray &newFieldValue) { return adaptTagValue(document, fieldName, newFieldValue, true); } void AbstractDebBasedQt4MaemoTarget::handleTargetAddedSpecial() { if (controlFileFieldValue(IconFieldName, true).isEmpty()) { // Such a file is created by the mobile wizards. const QString iconPath = project()->projectDirectory() + QLatin1Char('/') + project()->displayName() + QLatin1String("64.png"); if (QFileInfo(iconPath).exists()) setPackageManagerIcon(iconPath); } m_filesWatcher->addDirectory(debianDirPath(), Utils::FileSystemWatcher::WatchAllChanges); m_controlFile = new WatchableFile(controlFilePath(), this); connect(m_controlFile, SIGNAL(modified()), SIGNAL(controlChanged())); m_changeLogFile = new WatchableFile(changeLogFilePath(), this); connect(m_changeLogFile, SIGNAL(modified()), SIGNAL(changeLogChanged())); Core::FileManager::instance()->addFiles(QList<Core::IFile *>() << m_controlFile << m_changeLogFile); connect(m_filesWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(handleDebianDirContentsChanged())); handleDebianDirContentsChanged(); emit controlChanged(); emit changeLogChanged(); } bool AbstractDebBasedQt4MaemoTarget::targetCanBeRemoved() const { return QFileInfo(debianDirPath()).exists(); } void AbstractDebBasedQt4MaemoTarget::removeTarget() { QString error; if (!Utils::FileUtils::removeRecursively(debianDirPath(), &error)) qDebug("%s", qPrintable(error)); } void AbstractDebBasedQt4MaemoTarget::handleDebianDirContentsChanged() { emit debianDirContentsChanged(); } AbstractQt4MaemoTarget::ActionStatus AbstractDebBasedQt4MaemoTarget::createSpecialTemplates() { if (QFileInfo(debianDirPath()).exists()) return NoActionRequired; QDir projectDir(project()->projectDirectory()); QProcess dh_makeProc; QString error; const Qt4BuildConfiguration * const bc = qobject_cast<Qt4BuildConfiguration * >(activeBuildConfiguration()); AbstractMaemoPackageCreationStep::preparePackagingProcess(&dh_makeProc, bc, projectDir.path() + QLatin1Char('/') + PackagingDirName); const QString dhMakeDebianDir = projectDir.path() + QLatin1Char('/') + PackagingDirName + QLatin1String("/debian"); Utils::FileUtils::removeRecursively(dhMakeDebianDir, &error); const QStringList dh_makeArgs = QStringList() << QLatin1String("dh_make") << QLatin1String("-s") << QLatin1String("-n") << QLatin1String("-p") << (defaultPackageFileName() + QLatin1Char('_') + AbstractMaemoPackageCreationStep::DefaultVersionNumber); QtSupport::BaseQtVersion *lqt = activeQt4BuildConfiguration()->qtVersion(); if (!lqt) { raiseError(tr("Unable to create Debian templates: No Qt version set")); return ActionFailed; } if (!MaemoGlobal::callMad(dh_makeProc, dh_makeArgs, lqt->qmakeCommand().toString(), true) || !dh_makeProc.waitForStarted()) { raiseError(tr("Unable to create Debian templates: dh_make failed (%1)") .arg(dh_makeProc.errorString())); return ActionFailed; } dh_makeProc.write("\n"); // Needs user input. dh_makeProc.waitForFinished(-1); if (dh_makeProc.error() != QProcess::UnknownError || dh_makeProc.exitCode() != 0) { raiseError(tr("Unable to create debian templates: dh_make failed (%1)") .arg(dh_makeProc.errorString())); return ActionFailed; } if (!QFile::rename(dhMakeDebianDir, debianDirPath())) { raiseError(tr("Unable to move new debian directory to '%1'.") .arg(QDir::toNativeSeparators(debianDirPath()))); Utils::FileUtils::removeRecursively(dhMakeDebianDir, &error); return ActionFailed; } QDir debianDir(debianDirPath()); const QStringList &files = debianDir.entryList(QDir::Files); foreach (const QString &fileName, files) { if (fileName.endsWith(QLatin1String(".ex"), Qt::CaseInsensitive) || fileName.compare(QLatin1String("README.debian"), Qt::CaseInsensitive) == 0 || fileName.compare(QLatin1String("dirs"), Qt::CaseInsensitive) == 0 || fileName.compare(QLatin1String("docs"), Qt::CaseInsensitive) == 0) { debianDir.remove(fileName); } } return adaptRulesFile() && adaptControlFile() ? ActionSuccessful : ActionFailed; } bool AbstractDebBasedQt4MaemoTarget::adaptRulesFile() { Utils::FileReader reader; if (!reader.fetch(rulesFilePath())) { raiseError(reader.errorString()); return false; } QByteArray rulesContents = reader.data(); const QByteArray comment("# Uncomment this line for use without Qt Creator"); rulesContents.replace("DESTDIR", "INSTALL_ROOT"); rulesContents.replace("dh_shlibdeps", "# dh_shlibdeps " + comment); rulesContents.replace("# Add here commands to configure the package.", "# qmake PREFIX=/usr" + comment); rulesContents.replace("$(MAKE)\n", "# $(MAKE) " + comment + '\n'); // Would be the right solution, but does not work (on Windows), // because dpkg-genchanges doesn't know about it (and can't be told). // rulesContents.replace("dh_builddeb", "dh_builddeb --destdir=."); Utils::FileSaver saver(rulesFilePath()); saver.write(rulesContents); if (!saver.finalize()) { raiseError(saver.errorString()); return false; } return true; } bool AbstractDebBasedQt4MaemoTarget::adaptControlFile() { Utils::FileReader reader; if (!reader.fetch(controlFilePath())) { raiseError(reader.errorString()); return false; } QByteArray controlContents = reader.data(); adaptControlFileField(controlContents, "Section", defaultSection()); adaptControlFileField(controlContents, "Priority", "optional"); adaptControlFileField(controlContents, packageManagerNameFieldName(), project()->displayName().toUtf8()); const int buildDependsOffset = controlContents.indexOf("Build-Depends:"); if (buildDependsOffset == -1) { qDebug("Unexpected: no Build-Depends field in debian control file."); } else { int buildDependsNewlineOffset = controlContents.indexOf('\n', buildDependsOffset); if (buildDependsNewlineOffset == -1) { controlContents += '\n'; buildDependsNewlineOffset = controlContents.length() - 1; } controlContents.insert(buildDependsNewlineOffset, ", libqt4-dev"); } addAdditionalControlFileFields(controlContents); Utils::FileSaver saver(controlFilePath()); saver.write(controlContents); if (!saver.finalize()) { raiseError(saver.errorString()); return false; } return true; } bool AbstractDebBasedQt4MaemoTarget::initAdditionalPackagingSettingsFromOtherTarget() { foreach (const Target * const t, project()->targets()) { const AbstractDebBasedQt4MaemoTarget *target = qobject_cast<const AbstractDebBasedQt4MaemoTarget *>(t); if (target && target != this) { return setControlFieldValue(IconFieldName, target->controlFileFieldValue(IconFieldName, true)); } } return true; } QStringList AbstractDebBasedQt4MaemoTarget::packagingFilePaths() const { QStringList filePaths; const QString parentDir = debianDirPath(); foreach (const QString &fileName, debianFiles()) filePaths << parentDir + QLatin1Char('/') + fileName; return filePaths; } QString AbstractDebBasedQt4MaemoTarget::defaultPackageFileName() const { QString packageName = project()->displayName().toLower(); // We also replace dots, because OVI store chokes on them. const QRegExp legalLetter(QLatin1String("[a-z0-9+-]"), Qt::CaseSensitive, QRegExp::WildcardUnix); for (int i = 0; i < packageName.length(); ++i) { if (!legalLetter.exactMatch(packageName.mid(i, 1))) packageName[i] = QLatin1Char('-'); } return packageName; } bool AbstractDebBasedQt4MaemoTarget::setPackageManagerIcon(const QString &iconFilePath, QString *error) { bool success = true; foreach (Target * const target, project()->targets()) { AbstractDebBasedQt4MaemoTarget* const maemoTarget = qobject_cast<AbstractDebBasedQt4MaemoTarget*>(target); if (maemoTarget) { if (!maemoTarget->setPackageManagerIconInternal(iconFilePath, error)) success = false; } } return success; } // The QDateTime API can only deliver these in localized form... QString AbstractDebBasedQt4MaemoTarget::shortMonthName(const QDateTime &dt) const { switch (dt.date().month()) { case 1: return QLatin1String("Jan"); case 2: return QLatin1String("Feb"); case 3: return QLatin1String("Mar"); case 4: return QLatin1String("Apr"); case 5: return QLatin1String("May"); case 6: return QLatin1String("Jun"); case 7: return QLatin1String("Jul"); case 8: return QLatin1String("Aug"); case 9: return QLatin1String("Sep"); case 10: return QLatin1String("Oct"); case 11: return QLatin1String("Nov"); case 12: return QLatin1String("Dec"); default: QTC_ASSERT(false, return QString()); } } QString AbstractDebBasedQt4MaemoTarget::shortDayOfWeekName(const QDateTime &dt) const { switch (dt.date().dayOfWeek()) { case Qt::Monday: return QLatin1String("Mon"); case Qt::Tuesday: return QLatin1String("Tue"); case Qt::Wednesday: return QLatin1String("Wed"); case Qt::Thursday: return QLatin1String("Thu"); case Qt::Friday: return QLatin1String("Fri"); case Qt::Saturday: return QLatin1String("Sat"); case Qt::Sunday: return QLatin1String("Sun"); default: QTC_ASSERT(false, return QString()); } } AbstractRpmBasedQt4MaemoTarget::AbstractRpmBasedQt4MaemoTarget(Qt4Project *parent, const QString &id) : AbstractQt4MaemoTarget(parent, id) { } AbstractRpmBasedQt4MaemoTarget::~AbstractRpmBasedQt4MaemoTarget() { } QString AbstractRpmBasedQt4MaemoTarget::specFilePath() const { const QLatin1Char sep('/'); return project()->projectDirectory() + sep + PackagingDirName + sep + specFileName(); } QString AbstractRpmBasedQt4MaemoTarget::projectVersion(QString *error) const { return QString::fromUtf8(getValueForTag(VersionTag, error)); } bool AbstractRpmBasedQt4MaemoTarget::setProjectVersionInternal(const QString &version, QString *error) { return setValueForTag(VersionTag, version.toUtf8(), error); } QString AbstractRpmBasedQt4MaemoTarget::packageName() const { return QString::fromUtf8(getValueForTag(NameTag, 0)); } bool AbstractRpmBasedQt4MaemoTarget::setPackageNameInternal(const QString &name) { return setValueForTag(NameTag, name.toUtf8(), 0); } QString AbstractRpmBasedQt4MaemoTarget::shortDescription() const { return QString::fromUtf8(getValueForTag(SummaryTag, 0)); } QString AbstractRpmBasedQt4MaemoTarget::packageFileName() const { QtSupport::BaseQtVersion *lqt = activeQt4BuildConfiguration()->qtVersion(); if (!lqt) return QString(); return packageName() + QLatin1Char('-') + projectVersion() + QLatin1Char('-') + QString::fromUtf8(getValueForTag(ReleaseTag, 0)) + QLatin1Char('.') + MaemoGlobal::architecture(lqt->qmakeCommand().toString()) + QLatin1String(".rpm"); } bool AbstractRpmBasedQt4MaemoTarget::setShortDescriptionInternal(const QString &description) { return setValueForTag(SummaryTag, description.toUtf8(), 0); } AbstractQt4MaemoTarget::ActionStatus AbstractRpmBasedQt4MaemoTarget::createSpecialTemplates() { if (QFileInfo(specFilePath()).exists()) return NoActionRequired; QByteArray initialContent( "Name: %%name%%\n" "Summary: <insert short description here>\n" "Version: 0.0.1\n" "Release: 1\n" "License: <Enter your application's license here>\n" "Group: <Set your application's group here>\n" "%description\n" "<Insert longer, multi-line description\n" "here.>\n" "\n" "%prep\n" "%setup -q\n" "\n" "%build\n" "# You can leave this empty for use with Qt Creator." "\n" "%install\n" "rm -rf %{buildroot}\n" "make INSTALL_ROOT=%{buildroot} install\n" "\n" "%clean\n" "rm -rf %{buildroot}\n" "\n" "BuildRequires: \n" "# %define _unpackaged_files_terminate_build 0\n" "%files\n" "%defattr(-,root,root,-)" "/usr\n" "/opt\n" "# Add additional files to be included in the package here.\n" "%pre\n" "# Add pre-install scripts here." "%post\n" "/sbin/ldconfig # For shared libraries\n" "%preun\n" "# Add pre-uninstall scripts here." "%postun\n" "# Add post-uninstall scripts here." ); initialContent.replace("%%name%%", project()->displayName().toUtf8()); Utils::FileSaver saver(specFilePath()); saver.write(initialContent); return saver.finalize() ? ActionSuccessful : ActionFailed; } void AbstractRpmBasedQt4MaemoTarget::handleTargetAddedSpecial() { m_specFile = new WatchableFile(specFilePath(), this); connect(m_specFile, SIGNAL(modified()), SIGNAL(specFileChanged())); Core::FileManager::instance()->addFile(m_specFile); emit specFileChanged(); } bool AbstractRpmBasedQt4MaemoTarget::targetCanBeRemoved() const { return QFileInfo(specFilePath()).exists(); } void AbstractRpmBasedQt4MaemoTarget::removeTarget() { QFile::remove(specFilePath()); } bool AbstractRpmBasedQt4MaemoTarget::initAdditionalPackagingSettingsFromOtherTarget() { // Nothing to do here for now. return true; } QByteArray AbstractRpmBasedQt4MaemoTarget::getValueForTag(const QByteArray &tag, QString *error) const { Utils::FileReader reader; if (!reader.fetch(specFilePath(), error)) return QByteArray(); const QByteArray &content = reader.data(); const QByteArray completeTag = tag.toLower() + ':'; int index = content.toLower().indexOf(completeTag); if (index == -1) return QByteArray(); index += completeTag.count(); int endIndex = content.indexOf('\n', index); if (endIndex == -1) endIndex = content.count(); return content.mid(index, endIndex - index).trimmed(); } bool AbstractRpmBasedQt4MaemoTarget::setValueForTag(const QByteArray &tag, const QByteArray &value, QString *error) { Utils::FileReader reader; if (!reader.fetch(specFilePath(), error)) return false; QByteArray content = reader.data(); if (adaptTagValue(content, tag, value, false)) { Utils::FileSaver saver(specFilePath()); saver.write(content); return saver.finalize(error); } return true; } Qt4Maemo5Target::Qt4Maemo5Target(Qt4Project *parent, const QString &id) : AbstractDebBasedQt4MaemoTarget(parent, id) { setDisplayName(defaultDisplayName()); } Qt4Maemo5Target::~Qt4Maemo5Target() {} QString Qt4Maemo5Target::defaultDisplayName() { return QApplication::translate("Qt4ProjectManager::Qt4Target", "Maemo5", "Qt4 Maemo5 target display name"); } void Qt4Maemo5Target::addAdditionalControlFileFields(QByteArray &controlContents) { Q_UNUSED(controlContents); } QString Qt4Maemo5Target::debianDirName() const { return QLatin1String("debian_fremantle"); } QByteArray Qt4Maemo5Target::packageManagerNameFieldName() const { return "XB-Maemo-Display-Name"; } QSize Qt4Maemo5Target::packageManagerIconSize() const { return QSize(48, 48); } QByteArray Qt4Maemo5Target::defaultSection() const { return "user/hidden"; } Qt4HarmattanTarget::Qt4HarmattanTarget(Qt4Project *parent, const QString &id) : AbstractDebBasedQt4MaemoTarget(parent, id) { setDisplayName(defaultDisplayName()); } Qt4HarmattanTarget::~Qt4HarmattanTarget() {} QString Qt4HarmattanTarget::defaultDisplayName() { return QApplication::translate("Qt4ProjectManager::Qt4Target", "Harmattan", "Qt4 Harmattan target display name"); } QString Qt4HarmattanTarget::aegisManifestFileName() { return QLatin1String("manifest.aegis"); } void Qt4HarmattanTarget::handleTargetAddedSpecial() { AbstractDebBasedQt4MaemoTarget::handleTargetAddedSpecial(); const QFile aegisFile(debianDirPath() + QLatin1Char('/') + aegisManifestFileName()); if (aegisFile.exists()) return; Utils::FileReader reader; if (!reader.fetch(Core::ICore::instance()->resourcePath() + QLatin1String("/templates/shared/") + aegisManifestFileName())) { qDebug("Reading manifest template failed."); return; } QString content = QString::fromUtf8(reader.data()); content.replace(QLatin1String("%%PROJECTNAME%%"), project()->displayName()); Utils::FileSaver writer(aegisFile.fileName(), QIODevice::WriteOnly); writer.write(content.toUtf8()); if (!writer.finalize()) { qDebug("Failure writing manifest file."); return; } } void Qt4HarmattanTarget::addAdditionalControlFileFields(QByteArray &controlContents) { Q_UNUSED(controlContents); } QString Qt4HarmattanTarget::debianDirName() const { return QLatin1String("debian_harmattan"); } QByteArray Qt4HarmattanTarget::packageManagerNameFieldName() const { return "XSBC-Maemo-Display-Name"; } QSize Qt4HarmattanTarget::packageManagerIconSize() const { return QSize(64, 64); } QByteArray Qt4HarmattanTarget::defaultSection() const { return "user/other"; } Qt4MeegoTarget::Qt4MeegoTarget(Qt4Project *parent, const QString &id) : AbstractRpmBasedQt4MaemoTarget(parent, id) { setDisplayName(defaultDisplayName()); } Qt4MeegoTarget::~Qt4MeegoTarget() {} QString Qt4MeegoTarget::defaultDisplayName() { return QApplication::translate("Qt4ProjectManager::Qt4Target", "MeeGo", "Qt4 MeeGo target display name"); } QString Qt4MeegoTarget::specFileName() const { return QLatin1String("meego.spec"); } } // namespace Internal } // namespace Madde
bakaiadam/collaborative_qt_creator
src/plugins/madde/qt4maemotarget.cpp
C++
lgpl-2.1
43,717
/**************************************************************************** * * * NOA (Nice Office Access) * * ------------------------------------------------------------------------ * * * * The Contents of this file are made available subject to * * the terms of GNU Lesser General Public License Version 2.1. * * * * GNU Lesser General Public License Version 2.1 * * ======================================================================== * * Copyright 2003-2007 by IOn AG * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License version 2.1, as published by the Free Software Foundation. * * * * This library 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 * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * * MA 02111-1307 USA * * * * Contact us: * * http://www.ion.ag * * http://ubion.ion.ag * * info@ion.ag * * * ****************************************************************************/ /* * Last changes made by $Author: andreas $, $Date: 2006-11-06 07:24:57 +0100 (Mo, 06 Nov 2006) $ */ package ag.ion.noa.internal.printing; import ag.ion.bion.officelayer.document.DocumentException; import ag.ion.bion.officelayer.document.IDocument; import ag.ion.noa.NOAException; import ag.ion.noa.printing.IPrintProperties; import ag.ion.noa.printing.IPrintService; import ag.ion.noa.printing.IPrinter; import com.sun.star.beans.PropertyValue; import com.sun.star.uno.UnoRuntime; import com.sun.star.view.XPrintable; /** * Service for printing documents. * * @author Markus Krüger * @version $Revision: 10398 $ */ public class PrintService implements IPrintService { private IDocument document = null; //---------------------------------------------------------------------------- /** * Constructs new PrintService. * * @param document the document using this print service * * @author Markus Krüger * @date 16.08.2007 */ public PrintService(IDocument document) { if(document == null) throw new NullPointerException("Invalid document for print service."); this.document = document; } //---------------------------------------------------------------------------- /** * Prints the document to the active printer. * * @throws DocumentException if printing fails * * @author Markus Krüger * @date 16.08.2007 */ public void print() throws DocumentException { print(null); } //---------------------------------------------------------------------------- /** * Prints the document to the active printer with the given print properties. * * @param printProperties the properties to print with, or null to use default settings * * @throws DocumentException if printing fails * * @author Markus Krüger * @date 16.08.2007 */ public void print(IPrintProperties printProperties) throws DocumentException { try { XPrintable xPrintable = (XPrintable)UnoRuntime.queryInterface(XPrintable.class, document.getXComponent()); PropertyValue[] printOpts = null; if(printProperties != null) { if(printProperties.getPages() != null) printOpts = new PropertyValue[2]; else printOpts = new PropertyValue[1]; printOpts[0] = new PropertyValue(); printOpts[0].Name = "CopyCount"; printOpts[0].Value = printProperties.getCopyCount(); if(printProperties.getPages() != null) { printOpts[1] = new PropertyValue(); printOpts[1].Name = "Pages"; printOpts[1].Value = printProperties.getPages(); } } else printOpts = new PropertyValue[0]; xPrintable.print(printOpts); } catch(Throwable throwable) { throw new DocumentException(throwable); } } //---------------------------------------------------------------------------- /** * Returns if the active printer is busy. * * @return if the active printer is busy * * @throws NOAException if the busy state could not be retrieved * * @author Markus Krüger * @date 16.08.2007 */ public boolean isActivePrinterBusy() throws NOAException { try { XPrintable xPrintable = (XPrintable)UnoRuntime.queryInterface(XPrintable.class, document.getXComponent()); PropertyValue[] printerProps = xPrintable.getPrinter(); Boolean busy = new Boolean(false); for(int i = 0; i < printerProps.length; i++) { if(printerProps[i].Name.equals("IsBusy")) busy = (Boolean)printerProps[i].Value; } return busy.booleanValue(); } catch(Throwable throwable) { throw new NOAException(throwable); } } //---------------------------------------------------------------------------- /** * Returns the active printer. * * @return the active printer * * @throws NOAException if printer could not be retrieved * * @author Markus Krüger * @date 16.08.2007 */ public IPrinter getActivePrinter() throws NOAException { try { XPrintable xPrintable = (XPrintable)UnoRuntime.queryInterface(XPrintable.class, document.getXComponent()); PropertyValue[] printerProps = xPrintable.getPrinter(); String name = null; for(int i = 0; i < printerProps.length; i++) { if(printerProps[i].Name.equals("Name")) name = (String)printerProps[i].Value; } return new Printer(name); } catch(Throwable throwable) { throw new NOAException(throwable); } } //---------------------------------------------------------------------------- /** * Sets the active printer. * * @param printer the printer to be set to be active * * @throws NOAException if printer could not be set * * @author Markus Krüger * @date 16.08.2007 */ public void setActivePrinter(IPrinter printer) throws NOAException { try { if(printer == null) throw new NullPointerException("Invalid printer to be set"); XPrintable xPrintable = (XPrintable)UnoRuntime.queryInterface(XPrintable.class, document.getXComponent()); PropertyValue[] printerDesc = new PropertyValue[1]; printerDesc[0] = new PropertyValue(); printerDesc[0].Name = "Name"; printerDesc[0].Value = printer.getName(); xPrintable.setPrinter(printerDesc); } catch(Throwable throwable) { throw new NOAException(throwable); } } //---------------------------------------------------------------------------- /** * Constructs a printer with the given properties and returns it. * * @param name the name of the printer cue to be used * * @return the constructed printer * * @throws NOAException if printer could not be constructed * * @author Markus Krüger * @date 16.08.2007 */ public IPrinter createPrinter(String name) throws NOAException { return new Printer(name); } //---------------------------------------------------------------------------- }
LibreOffice/noa-libre
src/ag/ion/noa/internal/printing/PrintService.java
Java
lgpl-2.1
8,706
#region Disclaimer / License // Copyright (C) 2015, The Duplicati Team // http://www.duplicati.com, info@duplicati.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #endregion using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Duplicati.Library.Common.IO; using Duplicati.Library.Interface; using Duplicati.Library.Utility; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; namespace Duplicati.Library.Backend.AzureBlob { /// <summary> /// Azure blob storage facade. /// </summary> public class AzureBlobWrapper { private readonly string _containerName; private readonly CloudBlobContainer _container; public string[] DnsNames { get { var lst = new List<string>(); if (_container != null) { if (_container.Uri != null) lst.Add(_container.Uri.Host); if (_container.StorageUri != null) { if (_container.StorageUri.PrimaryUri != null) lst.Add(_container.StorageUri.PrimaryUri.Host); if (_container.StorageUri.SecondaryUri != null) lst.Add(_container.StorageUri.SecondaryUri.Host); } } return lst.ToArray(); } } public AzureBlobWrapper(string accountName, string accessKey, string containerName) { OperationContext.GlobalSendingRequest += (sender, args) => { args.Request.UserAgent = string.Format( "APN/1.0 Duplicati/{0} AzureBlob/2.0 {1}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version, Microsoft.WindowsAzure.Storage.Shared.Protocol.Constants.HeaderConstants.UserAgent ); }; var connectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", accountName, accessKey); var storageAccount = CloudStorageAccount.Parse(connectionString); var blobClient = storageAccount.CreateCloudBlobClient(); _containerName = containerName; _container = blobClient.GetContainerReference(containerName); } public void AddContainer() { _container.Create(BlobContainerPublicAccessType.Off); } public virtual void GetFileStream(string keyName, Stream target) { _container.GetBlockBlobReference(keyName).DownloadToStream(target); } public virtual async Task AddFileStream(string keyName, Stream source, CancellationToken cancelToken) { await _container.GetBlockBlobReference(keyName).UploadFromStreamAsync(source, cancelToken); } public void DeleteObject(string keyName) { _container.GetBlockBlobReference(keyName).DeleteIfExists(); } public virtual List<IFileEntry> ListContainerEntries() { var listBlobItems = _container.ListBlobs(blobListingDetails: BlobListingDetails.Metadata); try { return listBlobItems.Select(x => { var absolutePath = x.StorageUri.PrimaryUri.AbsolutePath; var containerSegment = string.Concat("/", _containerName, "/"); var blobName = absolutePath.Substring(absolutePath.IndexOf( containerSegment, System.StringComparison.Ordinal) + containerSegment.Length); try { if (x is CloudBlockBlob) { var cb = (CloudBlockBlob)x; var lastModified = new System.DateTime(); if (cb.Properties.LastModified != null) lastModified = new System.DateTime(cb.Properties.LastModified.Value.Ticks, System.DateTimeKind.Utc); return new FileEntry(Uri.UrlDecode(blobName.Replace("+", "%2B")), cb.Properties.Length, lastModified, lastModified); } } catch { // If the metadata fails to parse, return the basic entry } return new FileEntry(Uri.UrlDecode(blobName.Replace("+", "%2B"))); }) .Cast<IFileEntry>() .ToList(); } catch (StorageException ex) { if (ex.RequestInformation.HttpStatusCode == 404) { throw new FolderMissingException(ex); } throw; } } } }
sitofabi/duplicati
Duplicati/Library/Backend/AzureBlob/AzureBlobWrapper.cs
C#
lgpl-2.1
5,715
/* * eXist Open Source Native XML Database * Copyright (C) 2001-07 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * $Id$ */ package org.exist.storage; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.List; import java.util.Properties; import org.exist.EXistException; import org.exist.backup.ConsistencyCheck; import org.exist.backup.ErrorReport; import org.exist.backup.SystemExport; import org.exist.management.Agent; import org.exist.management.AgentFactory; import org.exist.management.TaskStatus; import org.exist.security.PermissionDeniedException; import org.exist.util.Configuration; import org.exist.xquery.TerminatedException; import static java.nio.charset.StandardCharsets.UTF_8; public class ConsistencyCheckTask implements SystemTask { private String exportDir; private boolean createBackup = false; private boolean createZip = true; private boolean paused = false; private boolean incremental = false; private boolean incrementalCheck = false; private boolean checkDocs = false; private int maxInc = -1; private File lastExportedBackup = null; private ProcessMonitor.Monitor monitor = new ProcessMonitor.Monitor(); public final static String OUTPUT_PROP_NAME = "output"; public final static String ZIP_PROP_NAME = "zip"; public final static String BACKUP_PROP_NAME = "backup"; public final static String INCREMENTAL_PROP_NAME = "incremental"; public final static String INCREMENTAL_CHECK_PROP_NAME = "incremental-check"; public final static String MAX_PROP_NAME = "max"; public final static String CHECK_DOCS_PROP_NAME = "check-documents"; private final static LoggingCallback logCallback = new LoggingCallback(); @Override public boolean afterCheckpoint() { return false; } public void configure(Configuration config, Properties properties) throws EXistException { exportDir = properties.getProperty(OUTPUT_PROP_NAME, "export"); File dir = new File(exportDir); if (!dir.isAbsolute()) { dir = new File((String) config.getProperty(BrokerPool.PROPERTY_DATA_DIR), exportDir); } dir.mkdirs(); exportDir = dir.getAbsolutePath(); if (LOG.isDebugEnabled()) { LOG.debug("Using output directory " + exportDir); } final String backup = properties.getProperty(BACKUP_PROP_NAME, "no"); createBackup = backup.equalsIgnoreCase("YES"); final String zip = properties.getProperty(ZIP_PROP_NAME, "yes"); createZip = zip.equalsIgnoreCase("YES"); final String inc = properties.getProperty(INCREMENTAL_PROP_NAME, "no"); incremental = inc.equalsIgnoreCase("YES"); final String incCheck = properties.getProperty(INCREMENTAL_CHECK_PROP_NAME, "yes"); incrementalCheck = incCheck.equalsIgnoreCase("YES"); final String max = properties.getProperty(MAX_PROP_NAME, "5"); try { maxInc = Integer.parseInt(max); } catch (final NumberFormatException e) { throw new EXistException("Parameter 'max' has to be an integer"); } final String check = properties.getProperty(CHECK_DOCS_PROP_NAME, "no"); checkDocs = check.equalsIgnoreCase("YES"); } @Override public void execute(DBBroker broker) throws EXistException { final Agent agentInstance = AgentFactory.getInstance(); final BrokerPool brokerPool = broker.getBrokerPool(); final TaskStatus endStatus = new TaskStatus(TaskStatus.Status.STOPPED_OK); agentInstance.changeStatus(brokerPool, new TaskStatus(TaskStatus.Status.INIT)); if (paused) { LOG.info("Consistency check is paused."); agentInstance.changeStatus(brokerPool, new TaskStatus(TaskStatus.Status.PAUSED)); return; } brokerPool.getProcessMonitor().startJob(ProcessMonitor.ACTION_BACKUP, null, monitor); PrintWriter report = null; try { boolean doBackup = createBackup; // TODO: don't use the direct access feature for now. needs more testing List<ErrorReport> errors = null; if (!incremental || incrementalCheck) { LOG.info("Starting consistency check..."); report = openLog(); final CheckCallback cb = new CheckCallback(report); final ConsistencyCheck check = new ConsistencyCheck(broker, false, checkDocs); agentInstance.changeStatus(brokerPool, new TaskStatus(TaskStatus.Status.RUNNING_CHECK)); errors = check.checkAll(cb); if (!errors.isEmpty()) { endStatus.setStatus(TaskStatus.Status.STOPPED_ERROR); endStatus.setReason(errors); LOG.error("Errors found: " + errors.size()); doBackup = true; if (fatalErrorsFound(errors)) { LOG.error("Fatal errors were found: pausing the consistency check task."); paused = true; } } LOG.info("Finished consistency check"); } if (doBackup) { LOG.info("Starting backup..."); final SystemExport sysexport = new SystemExport(broker, logCallback, monitor, false); lastExportedBackup = sysexport.export(exportDir, incremental, maxInc, createZip, errors); agentInstance.changeStatus(brokerPool, new TaskStatus(TaskStatus.Status.RUNNING_BACKUP)); if (lastExportedBackup != null) { LOG.info("Created backup to file: " + lastExportedBackup.getAbsolutePath()); } LOG.info("Finished backup"); } } catch (final TerminatedException e) { throw new EXistException(e.getMessage(), e); } catch (final PermissionDeniedException e) { //TODO should maybe throw PermissionDeniedException instead! throw new EXistException(e.getMessage(), e); } finally { if (report != null) { report.close(); } agentInstance.changeStatus(brokerPool, endStatus); brokerPool.getProcessMonitor().endJob(); } } /** * Gets the last exported backup */ public File getLastExportedBackup() { return lastExportedBackup; } private boolean fatalErrorsFound(List<ErrorReport> errors) { for (final ErrorReport error : errors) { switch (error.getErrcode()) { // the following errors are considered fatal: export the db and // stop the task case ErrorReport.CHILD_COLLECTION: case ErrorReport.RESOURCE_ACCESS_FAILED: return true; } } // no fatal errors return false; } private PrintWriter openLog() throws EXistException { try { final File file = SystemExport.getUniqueFile("report", ".log", exportDir); final OutputStream os = new BufferedOutputStream(new FileOutputStream(file)); return new PrintWriter(new OutputStreamWriter(os, UTF_8)); } catch (final FileNotFoundException e) { throw new EXistException("ERROR: failed to create report file in " + exportDir, e); } } private static class LoggingCallback implements SystemExport.StatusCallback { public void startCollection(String path) throws TerminatedException { } public void startDocument(String name, int current, int count) throws TerminatedException { } public void error(String message, Throwable exception) { LOG.error(message, exception); } } private class CheckCallback implements ConsistencyCheck.ProgressCallback, SystemExport.StatusCallback { private PrintWriter log; private boolean errorFound = false; private CheckCallback(PrintWriter log) { this.log = log; } // public void startDocument(String path) { // } public void startDocument(String name, int current, int count) throws TerminatedException { if (!monitor.proceed()) { throw new TerminatedException("consistency check terminated"); } if ((current % 1000 == 0) || (current == count)) { log.write(" DOCUMENT: "); log.write(Integer.valueOf(current).toString()); log.write(" of "); log.write(Integer.valueOf(count).toString()); log.write('\n'); log.flush(); } } public void startCollection(String path) throws TerminatedException { if (!monitor.proceed()) { throw new TerminatedException("consistency check terminated"); } if (errorFound) { log.write("----------------------------------------------\n"); } errorFound = false; log.write("COLLECTION: "); log.write(path); log.write('\n'); log.flush(); } public void error(ErrorReport error) { log.write("----------------------------------------------\n"); log.write(error.toString()); log.write('\n'); log.flush(); } public void error(String message, Throwable exception) { log.write("----------------------------------------------\n"); log.write("EXPORT ERROR: "); log.write(message); log.write('\n'); exception.printStackTrace(log); log.flush(); } } }
shabanovd/exist
src/org/exist/storage/ConsistencyCheckTask.java
Java
lgpl-2.1
10,914
/* * ///////////////////////////////////////////////////////////////////////////// * // This file is part of the "Hyrax Data Server" project. * // * // * // Copyright (c) 2013 OPeNDAP, Inc. * // Author: Nathan David Potter <ndp@opendap.org> * // * // This library is free software; you can redistribute it and/or * // modify it under the terms of the GNU Lesser General Public * // License as published by the Free Software Foundation; either * // version 2.1 of the License, or (at your option) any later version. * // * // This library 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 * // Lesser General Public License for more details. * // * // You should have received a copy of the GNU Lesser General Public * // License along with this library; if not, write to the Free Software * // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * // * // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. * ///////////////////////////////////////////////////////////////////////////// */ package opendap.hai; import opendap.bes.BES; import opendap.bes.BESManager; import opendap.bes.BesAdminFail; import opendap.bes.BesGroup; import opendap.coreServlet.HttpResponder; import opendap.coreServlet.ResourceInfo; import opendap.coreServlet.Scrub; import opendap.io.HyraxStringEncoding; import org.apache.commons.lang.StringEscapeUtils; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.*; public class BesControlApi extends HttpResponder { private Logger log; private static String defaultRegex = ".*\\/besctl"; public void init() { log = LoggerFactory.getLogger(getClass()); log.debug("Initializing BES Controller."); } public BesControlApi(String sysPath) { super(sysPath, null, defaultRegex); init(); } public BesControlApi(String sysPath, String pathPrefix) { super(sysPath, pathPrefix, defaultRegex); init(); } @Override public ResourceInfo getResourceInfo(String resourceName) throws Exception { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public long getLastModified(HttpServletRequest request) throws Exception { return new Date().getTime(); //To change body of implemented methods use File | Settings | File Templates. } public void respondToHttpGetRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { controlApi(request,response,false); } @Override public void respondToHttpPostRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { controlApi(request,response,true); } private void controlApi(HttpServletRequest request, HttpServletResponse response, boolean isPost) throws IOException { StringBuilder sb = new StringBuilder(); Enumeration headers = request.getHeaderNames(); while(headers.hasMoreElements()){ String headerName = (String) headers.nextElement(); String headerValue = request.getHeader(headerName); sb.append(" ").append(headerName).append(" = '").append(headerValue).append("'\n"); } log.debug("\nHTTP HEADERS:\n{}",sb); //log.debug("\nBODY:\n{}",getRequestBodyAsString(request)); HashMap<String,String> kvp = Util.processQuery(request); String status = null; try { status = processBesCommand(kvp, isPost); } catch (BesAdminFail baf){ status = baf.getMessage(); } PrintWriter output = response.getWriter(); //@todo work this out to not escape everything. //output.append(StringEscapeUtils.escapeHtml(status)); //String s = processStatus(status); output.append(status); output.flush(); } public String processStatus(String status){ StringBuilder s = new StringBuilder(); SAXBuilder sb = new SAXBuilder(false); ByteArrayInputStream bais = new ByteArrayInputStream(status.getBytes(HyraxStringEncoding.getCharset())); try { Document besResponseDoc = sb.build(bais); Element besResponse = besResponseDoc.getRootElement(); String errorResponse = processBesErrors(besResponse); if(errorResponse.length()==0){ Element ok = besResponse.getChild("OK",opendap.namespaces.BES.BES_ADMIN_NS); if(ok!=null){ s.append("OK"); } else { s.append("ERROR! Unrecognized BES response."); } } else { s.append(errorResponse); } } catch (JDOMException e) { s.append("Failed to parse BES response! Msg: ").append(e.getMessage()); log.error(s.toString()); } catch (IOException e) { s.append("Failed to ingest BES response! Msg: ").append(e.getMessage()); log.error(s.toString()); } return s.toString(); } public String besLogTailResponse(String logResponse){ StringBuilder s = new StringBuilder(); SAXBuilder sb = new SAXBuilder(false); ByteArrayInputStream bais = new ByteArrayInputStream(logResponse.getBytes(HyraxStringEncoding.getCharset())); try { Document besResponseDoc = sb.build(bais); Element besResponse = besResponseDoc.getRootElement(); String errorResponse = processBesErrors(besResponse); if(errorResponse.length()==0){ Element besLog = besResponse.getChild("BesLog",opendap.namespaces.BES.BES_ADMIN_NS); if(besLog!=null){ s.append(besLog.getText()); } else { s.append("ERROR! Unrecognized BES response."); } } else { s.append(errorResponse); } } catch (JDOMException e) { s.append("Failed to parse BES response! Msg: ").append(e.getMessage()); log.error(s.toString()); } catch (IOException e) { s.append("Failed to ingest BES response! Msg: ").append(e.getMessage()); log.error(s.toString()); } return s.toString(); } private String processBesErrors(Element topElem){ StringBuilder s = new StringBuilder(); List errors = topElem.getChildren("BESError", opendap.namespaces.BES.BES_ADMIN_NS); if(!errors.isEmpty()) { for(Object o: errors){ Element error = (Element) o; Element msgElem = error.getChild("Message",opendap.namespaces.BES.BES_ADMIN_NS); Element typeElem = error.getChild("Type",opendap.namespaces.BES.BES_ADMIN_NS); String msg = "BES ERROR Message Is Missing"; if(msgElem!=null) msg = msgElem.getTextNormalize(); String type = "BES ERROR Type Is Missing"; if(typeElem!=null) type = typeElem.getTextNormalize(); s.append("Error[").append(type).append("]: ").append(msg).append("\n"); } } return s.toString(); } private enum besCmds { cmd, prefix, Start, StopNice, StopNow, getConfig, module, setConfig, CONFIGURATION, getLog, lines, getLoggerState, setLoggerState, logger, state, setLoggerStates, enable, disable, on, off } /** * * @param kvp * @return */ public String processBesCommand(HashMap<String, String> kvp, boolean isPost) throws BesAdminFail { StringBuilder sb = new StringBuilder(); StringBuilder status = new StringBuilder(); String module, loggerName, loggerState; String besCmd = kvp.get("cmd"); String currentPrefix = kvp.get("prefix"); String currentBesName = kvp.get("besName"); if (currentPrefix!=null && currentBesName!=null && besCmd != null) { BesGroup besGroup = BESManager.getBesGroup(currentPrefix); BES bes = besGroup.get(currentBesName); if(bes!=null){ switch(besCmds.valueOf(besCmd)){ case Start: sb.append(processStatus(bes.start())); break; case StopNice: sb.append(processStatus(bes.stopNice(3000))); break; case StopNow: sb.append(processStatus(bes.stopNow())); break; case getConfig: module = kvp.get(besCmds.module.toString()); /* sb.append("You issued a getConfig command"); if(module!=null) sb.append(" for module '").append(module).append("'.\n"); else sb.append(".\n"); */ status.append(bes.getConfiguration(module)); sb.append(status); break; case setConfig: String submittedConfiguration = kvp.get(besCmds.CONFIGURATION.toString()); if(isPost && submittedConfiguration!=null ){ module = kvp.get(besCmds.module.toString()); /* sb.append("You issued a setConfig command"); if(module!=null) sb.append(" for module '").append(module).append("'.\n"); else sb.append(".\n"); sb.append("Your Configuration: \n"); sb.append(submittedConfiguration); */ status.append(bes.setConfiguration(module, submittedConfiguration)); sb.append(processStatus(status.toString())); } else { sb.append("In order to use the setConfig command you MUST supply a configuration via HTTP POST content.\n"); } break; case getLog: String logLines = kvp.get("lines"); String logContent = bes.getLog(logLines); logContent = besLogTailResponse(logContent); logContent = StringEscapeUtils.escapeXml(logContent); sb.append(logContent); break; case getLoggerState: loggerName = getValidLoggerName(bes, kvp.get(besCmds.logger.toString())); status.append(bes.getLoggerState(loggerName)); sb.append(status); break; case setLoggerState: loggerName = getValidLoggerName(bes, kvp.get(besCmds.logger.toString())); if(loggerName != null){ loggerState = getValidLoggerState(kvp.get(besCmds.state.toString())); status = new StringBuilder(); status.append(bes.setLoggerState(loggerName,loggerState)).append("\n"); sb.append(status); } else { sb.append("User requested an unknown logger."); } break; case setLoggerStates: String enabledLoggers = kvp.get(besCmds.enable.toString()); String disabledLoggers = kvp.get(besCmds.disable.toString()); status = new StringBuilder(); for (String enabledLoggerName : enabledLoggers.split(",")) { loggerName = getValidLoggerName(bes, enabledLoggerName); if (loggerName != null) status.append(bes.setLoggerState(loggerName, besCmds.on.toString())).append("\n"); } for (String disabledLoggerName : disabledLoggers.split(",")) { loggerName = getValidLoggerName(bes, disabledLoggerName); if (loggerName != null) status.append(bes.setLoggerState(loggerName, besCmds.off.toString())).append("\n"); } sb.append(status); break; default: sb.append(" Unrecognized BES command: ").append(Scrub.simpleString(besCmd)); break; } } else { String cleanPrefix = Scrub.fileName(currentPrefix); String cleanBesName= Scrub.fileName(currentBesName); sb.append("The BES group associated with the prefix '").append(cleanPrefix).append("' "); sb.append("does not contain a BES associated with the name '").append(cleanBesName).append("' "); log.error("OUCH!! The BESManager failed to locate a BES named '{}' in the BesGroup associated " + "with the prefix '{}'",cleanBesName,cleanPrefix); } } else { sb.append(" Waiting for you to do something..."); } return sb.toString(); } private String getValidLoggerName(BES bes, String loggerName) throws BesAdminFail { TreeMap<String,BES.BesLogger> validLoggers = bes.getBesLoggers(); if(validLoggers.containsKey(loggerName)){ BES.BesLogger besLogger = validLoggers.get(loggerName); return besLogger.getName(); } log.debug("User requested unknown BES logger: '{}'", loggerName); return null; } private String getValidLoggerState(String loggerState) throws BesAdminFail { if(!loggerState.equals(besCmds.on.toString())) loggerState = besCmds.off.toString(); return loggerState; } }
OPENDAP/olfs
src/opendap/hai/BesControlApi.java
Java
lgpl-2.1
15,055
require 'torquebox/logger' require 'fileutils' require 'logger' shared_examples_for 'a torquebox logger' do it "should look nice for class objects" do require 'torquebox/service_registry' logger = TorqueBox::Logger.new(TorqueBox::ServiceRegistry) logger.error("JC: log for cache store") end it "should support the various boolean methods" do logger.should respond_to(:debug?) logger.should respond_to(:info?) logger.should respond_to(:warn?) logger.should respond_to(:error?) logger.should respond_to(:fatal?) end it "should not barf on meaningless level setting" do logger.level = Logger::WARN logger.level.should == Logger::WARN end it "should deal with blocks correctly" do logger.error "JC: message zero" logger.error { "JC: message" } logger.error "JC: message too" end it "should handle nil parameters" do logger.info(nil) end it "should support the rack.errors interface" do logger.should respond_to(:puts) logger.should respond_to(:write) logger.should respond_to(:flush) end it "should have a formatter" do logger.should respond_to(:formatter) logger.formatter.should_not be_nil end end describe TorqueBox::Logger do let(:logger) { TorqueBox::Logger.new } it_should_behave_like 'a torquebox logger' it "should support the trace boolean method" do logger.should respond_to(:trace?) end it "should support the add method" do fake_logger = mock('logger') org.jboss.logging::Logger.stub!(:getLogger).and_return(fake_logger) logger = TorqueBox::Logger.new fake_logger.should_receive(:debug).with('debug') logger.add(Logger::DEBUG, 'debug', nil) fake_logger.should_receive(:info).with('info') logger.add(Logger::INFO, 'info', nil) fake_logger.should_receive(:warn).with('warning') logger.add(Logger::WARN, 'warning', nil) fake_logger.should_receive(:error).with('error') logger.add(Logger::ERROR, 'error', nil) fake_logger.should_receive(:warn).with('unknown') logger.add(Logger::UNKNOWN, 'unknown', nil) fake_logger.should_receive(:warn).with('block') logger.add(Logger::WARN, nil, nil) { 'block' } end end describe TorqueBox::FallbackLogger do before(:each) do @log_path = File.expand_path(File.join(File.dirname(__FILE__), '..', 'target', 'logger_spec_output.log')) ENV['TORQUEBOX_FALLBACK_LOGFILE'] = @log_path end after(:each) do FileUtils.rm_f(@log_path) end let(:logger) { TorqueBox::FallbackLogger.new } it_should_behave_like 'a torquebox logger' it "should let users override the fallback log file" do logger.info('testing fallback log file') File.read(@log_path).should include('testing fallback log file') end end
developwith/wildfly-torquebox
jruby/lib/ruby/gems/shared/gems/torquebox-core-3.1.0-java/spec/logger_spec.rb
Ruby
lgpl-2.1
2,854
import cplugin.CpluginEntryAPI; import cplugin.CpluginModule; /** * We need to follow the Java coding style and keep the main class with the * same name as the source file. This is required by the libcollections. * * Another requirement is the class constructor, it must receive no arguments. */ public class Jplugin implements CpluginEntryAPI, CpluginModule { private final String name = "jplugin"; private final String version = "0.1"; private final String creator = "Rodrigo Freitas"; private final String description = "Java plugin example"; private final String API = "{" + "\"API\": [" + "{ \"name\": \"foo_int\", \"return_type\": \"int\" }," + "{ \"name\": \"foo_uint\", \"return_type\": \"uint\" }," + "{ \"name\": \"foo_char\", \"return_type\": \"char\" }," + "{ \"name\": \"foo_uchar\", \"return_type\": \"uchar\" }," + "{ \"name\": \"foo_sint\", \"return_type\": \"sint\" }," + "{ \"name\": \"foo_usint\", \"return_type\": \"usint\" }," + "{ \"name\": \"foo_float\", \"return_type\": \"float\" }," + "{ \"name\": \"foo_double\", \"return_type\": \"double\" }," + "{ \"name\": \"foo_long\", \"return_type\": \"long\" }," + "{ \"name\": \"foo_ulong\", \"return_type\": \"ulong\" }," + "{ \"name\": \"foo_llong\", \"return_type\": \"llong\" }," + "{ \"name\": \"foo_ullong\", \"return_type\": \"ullong\" }," + "{ \"name\": \"foo_boolean\", \"return_type\": \"boolean\" }," + "{ \"name\": \"foo_args\", \"return_type\": \"void\", \"arguments\": [" + "{ \"name\": \"arg1\", \"type\": \"int\" }," + "{ \"name\": \"arg2\", \"type\": \"uint\" }," + "{ \"name\": \"arg3\", \"type\": \"sint\" }," + "{ \"name\": \"arg4\", \"type\": \"usint\" }," + "{ \"name\": \"arg5\", \"type\": \"char\" }," + "{ \"name\": \"arg6\", \"type\": \"uchar\" }," + "{ \"name\": \"arg7\", \"type\": \"float\" }," + "{ \"name\": \"arg8\", \"type\": \"double\" }," + "{ \"name\": \"arg9\", \"type\": \"long\" }," + "{ \"name\": \"arg10\", \"type\": \"ulong\" }," + "{ \"name\": \"arg11\", \"type\": \"llong\" }," + "{ \"name\": \"arg12\", \"type\": \"ullong\" }," + "{ \"name\": \"arg13\", \"type\": \"boolean\" }," + "{ \"name\": \"arg14\", \"type\": \"string\" }" + "] }" + "]"+ "}"; /** Module info functions */ @Override public String getName() { System.out.println("getName"); return name; } @Override public String getVersion() { System.out.println("getVersion"); return version; } @Override public String getAuthor() { System.out.println("getAuthor"); return creator; } @Override public String getDescription() { System.out.println("getDescription"); return description; } @Override public String getAPI() { System.out.println("getAPI"); return API; } /** Module init/uninit functions */ @Override public int module_init() { System.out.println("module init"); return 0; } @Override public void module_uninit() { System.out.println("module uninit"); } Jplugin() { System.out.println("Constructor"); } /** Module API Examples */ public int foo_int() { System.out.println("foo_int"); return 42; } public int foo_uint() { System.out.println("foo_uint"); return 420; } public short foo_sint() { System.out.println("foo_sint"); return 421; } public short foo_usint() { System.out.println("foo_usint"); return 4201; } public byte foo_char() { System.out.println("foo_char"); return 'a'; } public byte foo_uchar() { System.out.println("foo_uchar"); return (byte)230; } public float foo_float() { System.out.println("foo_float"); return 42.5f; } public double foo_double() { System.out.println("foo_double"); return 4.2; } public boolean foo_boolean() { System.out.println("foo_boolean"); return true; } public int foo_long() { System.out.println("foo_long"); return 42000; } public int foo_ulong() { System.out.println("foo_ulong"); return 420001; } public long foo_llong() { System.out.println("foo_llong"); return 420009; } public long foo_ullong() { System.out.println("foo_ullong"); return 4200019; } /* With arguments, with return */ public void foo_args(String args) { /* XXX: The arguments are in a JSON format. */ System.out.println("Arguments: " + args); } public void outside_api() { System.out.println("I'm outside the API"); } }
rsfreitas/libcollections
examples/plugin/java/Jplugin.java
Java
lgpl-2.1
5,169
#include <iostream> #include <map> #include <string> #include "module.hpp" #include "core/log.hpp" namespace eedit { std::map<std::string, ::module_fn> modfunc_table; int register_module_function(const char * name, module_fn fn) { auto ret = modfunc_table.insert(std::pair<std::string, module_fn>(std::string(name), fn)); if (ret.second == false) { app_log << "function '" << name << "' already existed\n"; app_log << " with a value of " << ret.first->second << '\n'; return -1; } return 0; } ::module_fn get_module_function(const char * name) { auto ret = modfunc_table.find(std::string(name)); if (ret != modfunc_table.end()) { return *ret->second; } app_log << __PRETTY_FUNCTION__ << " function '" << name << "' not found\n"; return nullptr; } } extern "C" { int eedit_register_module_function(const char * name, module_fn fn) { return eedit::register_module_function(name, fn); } module_fn eedit_get_module_function(const char * name) { return eedit::get_module_function(name); } }
BackupGGCode/ewlibs
app/eedit/core/module/module.cpp
C++
lgpl-2.1
1,025
class Notifier < ActionMailer::Base default :from => "contato@agendatech.com.br", :to => ["andersonlfl@gmail.com", "alots.ssa@gmail.com"] def envia_email(contato) @contato = contato mail(:subject => "Contato agendatech") end end
britto/agendatech
app/models/notifier.rb
Ruby
lgpl-2.1
246
<?php /** * @package copix * @subpackage core * @author Croës Gérald * @copyright CopixTeam * @link http://copix.org * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public Licence, see LICENCE file */ /** * Filtres pour récupérer des données sous une certaine forme * @package copix * @subpackage utils */ class CopixFilter { /** * Récupération d'un entier à partir de la variable * @param mixed $pInt la variable à récupérer sous la forme d'un entier * @return int */ public static function getInt ($pInt) { return intval (self::getNumeric ($pInt, true)); } /** * Récupération d'un numérique à partir de la variable * @param mixed $pNumeric la variable à récupérer sous la forme d'un numérique * @param boolean $pWithComma si l'on souhaite inclure les virgules et points dans l'élément * @return numeric */ public static function getNumeric ($pNumeric, $pWithComma = false) { if ($pWithComma){ return preg_replace('/[-+]?[^\d.]/', '', str_replace (',', '.', _toString($pNumeric))); }else{ return preg_replace('/[-+]?[^\d]/', '', _toString($pNumeric)); } } /** * Récupération des caractères d'une chaine * @param string $pAlpha chaine de caractère à traiter * @return string */ public static function getAlpha ($pAlpha, $pWithSpaces=true) { if ($pWithSpaces){ return preg_replace('/[^a-zA-ZàâäéèêëîïÿôöùüçñÀÂÄÉÈÊËÎÏŸÔÖÙÜÇÑ ]/', '', _toString($pAlpha)); }else{ return preg_replace('/[^a-zA-ZàâäéèêëîïÿôöùüçñÀÂÄÉÈÊËÎÏŸÔÖÙÜÇÑ]/', '', _toString($pAlpha)); } } /** * Récupération d'une chaine alphanumérique * @param string $pAlphaNum la chaine ou l'on va récupérer les éléments * @param boolean * @return string */ public static function getAlphaNum ($pAlphaNum, $pWithSpaces=true) { // \w <=> [a-zA-Z0-9_] et a-z contient les accent si système est en fr. // \W tout ce qui n'est pas \w if ($pWithSpaces){ return preg_replace('/[^a-zA-Z0-9àâäéèêëîïÿôöùüçñÀÂÄÉÈÊËÎÏŸÔÖÙÜÇÑ ]/', '', _toString($pAlphaNum)); }else{ return preg_replace('/[^a-zA-Z0-9àâäéèêëîïÿôöùüçñÀÂÄÉÈÊËÎÏŸÔÖÙÜÇÑ]/', '', _toString($pAlphaNum)); } } /** * Retourne une décimal à partir d'une entrée * @param mixed $pFloat l'élément à transformer * @return float */ public static function getFloat ($pFloat) { return floatval (str_replace (',', '.', self::getNumeric ($pFloat, true))); } /** * Retourne un booléen à partir d'une entrée. * * Evalue les chaînes suivantes comme vrai : yes, true, enable, enabled, 1. * Evalue les chaînes suivantes comme faux: no, false, disable, disabled, 0. * Si cela ne colle pas, transforme la chaîne en entier, 0 s'évalue comme faux et tout le reste comme vrai. * * @param mixed $pBoolean L'élément à transformer. * @return boolean */ public static function getBoolean ($pBoolean) { switch(strtolower(_toString ($pBoolean))) { case 'yes': case 'true': case 'enable': case 'enabled': case '1': return true; case 'no': case 'false': case 'disable': case 'disabled': case '0': case '': return false; default: return self::getInt($pBoolean) != 0; } } }
lilobase/ICONTO-EcoleNumerique
utils/copix/utils/CopixFilter.class.php
PHP
lgpl-2.1
3,688
#ifndef FILEREADER_HPP #define FILEREADER_HPP #include "Block.hpp" #include <QFile> class FileReader : public Block { friend class FileReaderUI; public: FileReader(); bool start(); void exec( Array< Sample > &samples ); void stop(); Block *createInstance(); private: void serialize( QDataStream &ds ) const; void deSerialize( QDataStream &ds ); bool loop, textMode, pcm_s16; QFile f; }; #include "Settings.hpp" class QPushButton; class QLineEdit; class QCheckBox; class FileReaderUI : public AdditionalSettings { Q_OBJECT public: FileReaderUI( FileReader &block ); void prepare(); void setRunMode( bool b ); private slots: void setValue(); void setLoop(); void setFileName(); void browseFile(); private: FileReader &block; QLineEdit *fileE; QCheckBox *loopB, *textModeB, *pcmB; QPushButton *applyB; }; #endif // FILEREADER_HPP
zaps166/DSPBlocks
Blocks/General/FileReader.hpp
C++
lgpl-2.1
861
/*************************************************************************** * Copyright (c) 2009 Juergen Riegel <juergen.riegel@web.de> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library 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 Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <Standard_math.hxx> # include <Poly_Polygon3D.hxx> # include <Geom_BSplineCurve.hxx> # include <Geom_Circle.hxx> # include <Geom_Ellipse.hxx> # include <Geom_TrimmedCurve.hxx> # include <Inventor/actions/SoGetBoundingBoxAction.h> # include <Inventor/SoPath.h> # include <Inventor/SbBox3f.h> # include <Inventor/SbImage.h> # include <Inventor/SoPickedPoint.h> # include <Inventor/details/SoLineDetail.h> # include <Inventor/details/SoPointDetail.h> # include <Inventor/nodes/SoBaseColor.h> # include <Inventor/nodes/SoCoordinate3.h> # include <Inventor/nodes/SoDrawStyle.h> # include <Inventor/nodes/SoImage.h> # include <Inventor/nodes/SoInfo.h> # include <Inventor/nodes/SoLineSet.h> # include <Inventor/nodes/SoPointSet.h> # include <Inventor/nodes/SoMarkerSet.h> # include <Inventor/nodes/SoMaterial.h> # include <Inventor/nodes/SoAsciiText.h> # include <Inventor/nodes/SoTransform.h> # include <Inventor/nodes/SoSeparator.h> # include <Inventor/nodes/SoAnnotation.h> # include <Inventor/nodes/SoVertexProperty.h> # include <Inventor/nodes/SoTranslation.h> # include <Inventor/nodes/SoText2.h> # include <Inventor/nodes/SoFont.h> # include <Inventor/nodes/SoPickStyle.h> # include <Inventor/nodes/SoCamera.h> /// Qt Include Files # include <QAction> # include <QApplication> # include <QColor> # include <QDialog> # include <QFont> # include <QImage> # include <QMenu> # include <QMessageBox> # include <QPainter> # include <QTextStream> #endif #ifndef _PreComp_ # include <boost/bind.hpp> #endif #include <Inventor/SbTime.h> #include <boost/scoped_ptr.hpp> /// Here the FreeCAD includes sorted by Base,App,Gui...... #include <Base/Tools.h> #include <Base/Parameter.h> #include <Base/Console.h> #include <Base/Vector3D.h> #include <Gui/Application.h> #include <Gui/BitmapFactory.h> #include <Gui/Document.h> #include <Gui/Command.h> #include <Gui/Control.h> #include <Gui/Selection.h> #include <Gui/Utilities.h> #include <Gui/MainWindow.h> #include <Gui/MenuManager.h> #include <Gui/View3DInventor.h> #include <Gui/View3DInventorViewer.h> #include <Gui/DlgEditFileIncludeProptertyExternal.h> #include <Gui/SoFCBoundingBox.h> #include <Gui/SoFCUnifiedSelection.h> #include <Gui/Inventor/MarkerBitmaps.h> #include <Mod/Part/App/Geometry.h> #include <Mod/Sketcher/App/SketchObject.h> #include <Mod/Sketcher/App/Sketch.h> #include "SoZoomTranslation.h" #include "SoDatumLabel.h" #include "EditDatumDialog.h" #include "ViewProviderSketch.h" #include "DrawSketchHandler.h" #include "TaskDlgEditSketch.h" #include "TaskSketcherValidation.h" // The first is used to point at a SoDatumLabel for some // constraints, and at a SoMaterial for others... #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 #define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2 #define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3 #define CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION 4 #define CONSTRAINT_SEPARATOR_INDEX_SECOND_ICON 5 #define CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID 6 using namespace SketcherGui; using namespace Sketcher; SbColor ViewProviderSketch::VertexColor (1.0f,0.149f,0.0f); // #FF2600 -> (255, 38, 0) SbColor ViewProviderSketch::CurveColor (1.0f,1.0f,1.0f); // #FFFFFF -> (255,255,255) SbColor ViewProviderSketch::CurveDraftColor (0.0f,0.0f,0.86f); // #0000DC -> ( 0, 0,220) SbColor ViewProviderSketch::CurveExternalColor (0.8f,0.2f,0.6f); // #CC3399 -> (204, 51,153) SbColor ViewProviderSketch::CrossColorH (0.8f,0.4f,0.4f); // #CC6666 -> (204,102,102) SbColor ViewProviderSketch::CrossColorV (0.4f,0.8f,0.4f); // #66CC66 -> (102,204,102) SbColor ViewProviderSketch::FullyConstrainedColor (0.0f,1.0f,0.0f); // #00FF00 -> ( 0,255, 0) SbColor ViewProviderSketch::ConstrDimColor (1.0f,0.149f,0.0f); // #FF2600 -> (255, 38, 0) SbColor ViewProviderSketch::ConstrIcoColor (1.0f,0.149f,0.0f); // #FF2600 -> (255, 38, 0) SbColor ViewProviderSketch::NonDrivingConstrDimColor (0.0f,0.149f,1.0f); // #0026FF -> ( 0, 38,255) SbColor ViewProviderSketch::PreselectColor (0.88f,0.88f,0.0f); // #E1E100 -> (225,225, 0) SbColor ViewProviderSketch::SelectColor (0.11f,0.68f,0.11f); // #1CAD1C -> ( 28,173, 28) SbColor ViewProviderSketch::PreselectSelectedColor (0.36f,0.48f,0.11f); // #5D7B1C -> ( 93,123, 28) // Variables for holding previous click SbTime ViewProviderSketch::prvClickTime; SbVec3f ViewProviderSketch::prvClickPoint; SbVec2s ViewProviderSketch::prvCursorPos; SbVec2s ViewProviderSketch::newCursorPos; //************************************************************************** // Edit data structure /// Data structure while editing the sketch struct EditData { EditData(): sketchHandler(0), editDatumDialog(false), buttonPress(false), DragPoint(-1), DragCurve(-1), PreselectPoint(-1), PreselectCurve(-1), PreselectCross(-1), MarkerSize(7), blockedPreselection(false), FullyConstrained(false), //ActSketch(0), // if you are wondering, it went to SketchObject, accessible via getSketchObject()->getSolvedSketch() EditRoot(0), PointsMaterials(0), CurvesMaterials(0), PointsCoordinate(0), CurvesCoordinate(0), CurveSet(0), RootCrossSet(0), EditCurveSet(0), PointSet(0), pickStyleAxes(0) {} // pointer to the active handler for new sketch objects DrawSketchHandler *sketchHandler; bool editDatumDialog; bool buttonPress; // dragged point int DragPoint; // dragged curve int DragCurve; // dragged constraints std::set<int> DragConstraintSet; SbColor PreselectOldColor; int PreselectPoint; int PreselectCurve; int PreselectCross; int MarkerSize; std::set<int> PreselectConstraintSet; bool blockedPreselection; bool FullyConstrained; bool visibleBeforeEdit; // container to track our own selected parts std::set<int> SelPointSet; std::set<int> SelCurvSet; // also holds cross axes at -1 and -2 std::set<int> SelConstraintSet; std::vector<int> CurvIdToGeoId; // conversion of SoLineSet index to GeoId // helper data structures for the constraint rendering std::vector<ConstraintType> vConstrType; // For each of the combined constraint icons drawn, also create a vector // of bounding boxes and associated constraint IDs, to go from the icon's // pixel coordinates to the relevant constraint IDs. // // The outside map goes from a string representation of a set of constraint // icons (like the one used by the constraint IDs we insert into the Coin // rendering tree) to a vector of those bounding boxes paired with relevant // constraint IDs. std::map<QString, ViewProviderSketch::ConstrIconBBVec> combinedConstrBoxes; // nodes for the visuals SoSeparator *EditRoot; SoMaterial *PointsMaterials; SoMaterial *CurvesMaterials; SoMaterial *RootCrossMaterials; SoMaterial *EditCurvesMaterials; SoCoordinate3 *PointsCoordinate; SoCoordinate3 *CurvesCoordinate; SoCoordinate3 *RootCrossCoordinate; SoCoordinate3 *EditCurvesCoordinate; SoLineSet *CurveSet; SoLineSet *RootCrossSet; SoLineSet *EditCurveSet; SoMarkerSet *PointSet; SoText2 *textX; SoTranslation *textPos; SoGroup *constrGroup; SoPickStyle *pickStyleAxes; }; // this function is used to simulate cyclic periodic negative geometry indices (for external geometry) const Part::Geometry* GeoById(const std::vector<Part::Geometry*> GeoList, int Id) { if (Id >= 0) return GeoList[Id]; else return GeoList[GeoList.size()+Id]; } //************************************************************************** // Construction/Destruction /* TRANSLATOR SketcherGui::ViewProviderSketch */ PROPERTY_SOURCE(SketcherGui::ViewProviderSketch, PartGui::ViewProvider2DObject) ViewProviderSketch::ViewProviderSketch() : edit(0), Mode(STATUS_NONE) { // FIXME Should this be placed in here? ADD_PROPERTY_TYPE(Autoconstraints,(true),"Auto Constraints",(App::PropertyType)(App::Prop_None),"Create auto constraints"); sPixmap = "Sketcher_Sketch"; LineColor.setValue(1,1,1); PointColor.setValue(1,1,1); PointSize.setValue(4); zCross=0.001f; zLines=0.005f; zConstr=0.006f; // constraint not construction zHighLine=0.007f; zPoints=0.008f; zHighlight=0.009f; zText=0.011f; zEdit=0.001f; xInit=0; yInit=0; relative=false; unsigned long color; ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); // edge color App::Color edgeColor = LineColor.getValue(); color = (unsigned long)(edgeColor.getPackedValue()); color = hGrp->GetUnsigned("SketchEdgeColor", color); edgeColor.setPackedValue((uint32_t)color); LineColor.setValue(edgeColor); // vertex color App::Color vertexColor = PointColor.getValue(); color = (unsigned long)(vertexColor.getPackedValue()); color = hGrp->GetUnsigned("SketchVertexColor", color); vertexColor.setPackedValue((uint32_t)color); PointColor.setValue(vertexColor); //rubberband selection rubberband = new Gui::Rubberband(); } ViewProviderSketch::~ViewProviderSketch() { delete rubberband; } void ViewProviderSketch::slotUndoDocument(const Gui::Document& doc) { if(getSketchObject()->noRecomputes) getSketchObject()->solve(); // the sketch must be solved to update the DoF of the solver else getSketchObject()->getDocument()->recompute(); // or fully recomputed if applicable } void ViewProviderSketch::slotRedoDocument(const Gui::Document& doc) { if(getSketchObject()->noRecomputes) getSketchObject()->solve(); // the sketch must be solved to update the DoF of the solver else getSketchObject()->getDocument()->recompute(); // or fully recomputed if applicable } // handler management *************************************************************** void ViewProviderSketch::activateHandler(DrawSketchHandler *newHandler) { assert(edit); assert(edit->sketchHandler == 0); edit->sketchHandler = newHandler; Mode = STATUS_SKETCH_UseHandler; edit->sketchHandler->sketchgui = this; edit->sketchHandler->activated(this); } void ViewProviderSketch::deactivateHandler() { assert(edit); if(edit->sketchHandler != 0){ std::vector<Base::Vector2D> editCurve; editCurve.clear(); drawEdit(editCurve); // erase any line edit->sketchHandler->deactivated(this); edit->sketchHandler->unsetCursor(); delete(edit->sketchHandler); } edit->sketchHandler = 0; Mode = STATUS_NONE; } /// removes the active handler void ViewProviderSketch::purgeHandler(void) { deactivateHandler(); // ensure that we are in sketch only selection mode Gui::MDIView *mdi = Gui::Application::Instance->activeDocument()->getActiveView(); Gui::View3DInventorViewer *viewer; viewer = static_cast<Gui::View3DInventor *>(mdi)->getViewer(); SoNode* root = viewer->getSceneGraph(); static_cast<Gui::SoFCUnifiedSelection*>(root)->selectionRole.setValue(false); } void ViewProviderSketch::setAxisPickStyle(bool on) { assert(edit); if (on) edit->pickStyleAxes->style = SoPickStyle::SHAPE; else edit->pickStyleAxes->style = SoPickStyle::UNPICKABLE; } // ********************************************************************************** bool ViewProviderSketch::keyPressed(bool pressed, int key) { switch (key) { case SoKeyboardEvent::ESCAPE: { // make the handler quit but not the edit mode if (edit && edit->sketchHandler) { if (!pressed) edit->sketchHandler->quit(); return true; } if (edit && edit->editDatumDialog) { edit->editDatumDialog = false; return true; } if (edit && (edit->DragConstraintSet.empty() == false)) { if (!pressed) { edit->DragConstraintSet.clear(); } return true; } if (edit && edit->DragCurve >= 0) { if (!pressed) { getSketchObject()->movePoint(edit->DragCurve, Sketcher::none, Base::Vector3d(0,0,0), true); edit->DragCurve = -1; resetPositionText(); Mode = STATUS_NONE; } return true; } if (edit && edit->DragPoint >= 0) { if (!pressed) { int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(edit->DragPoint, GeoId, PosId); getSketchObject()->movePoint(GeoId, PosId, Base::Vector3d(0,0,0), true); edit->DragPoint = -1; resetPositionText(); Mode = STATUS_NONE; } return true; } if (edit) { // #0001479: 'Escape' key dismissing dialog cancels Sketch editing // If we receive a button release event but not a press event before // then ignore this one. if (!pressed && !edit->buttonPress) return true; edit->buttonPress = pressed; } return false; } default: { if (edit && edit->sketchHandler) edit->sketchHandler->registerPressedKey(pressed,key); } } return true; // handle all other key events } void ViewProviderSketch::snapToGrid(double &x, double &y) { if (GridSnap.getValue() != false) { // Snap Tolerance in pixels const double snapTol = GridSize.getValue() / 5; double tmpX = x, tmpY = y; // Find Nearest Snap points tmpX = tmpX / GridSize.getValue(); tmpX = tmpX < 0.0 ? ceil(tmpX - 0.5) : floor(tmpX + 0.5); tmpX *= GridSize.getValue(); tmpY = tmpY / GridSize.getValue(); tmpY = tmpY < 0.0 ? ceil(tmpY - 0.5) : floor(tmpY + 0.5); tmpY *= GridSize.getValue(); // Check if x within snap tolerance if (x < tmpX + snapTol && x > tmpX - snapTol) x = tmpX; // Snap X Mouse Position // Check if y within snap tolerance if (y < tmpY + snapTol && y > tmpY - snapTol) y = tmpY; // Snap Y Mouse Position } } void ViewProviderSketch::getProjectingLine(const SbVec2s& pnt, const Gui::View3DInventorViewer *viewer, SbLine& line) const { const SbViewportRegion& vp = viewer->getSoRenderManager()->getViewportRegion(); short x,y; pnt.getValue(x,y); SbVec2f siz = vp.getViewportSize(); float dX, dY; siz.getValue(dX, dY); float fRatio = vp.getViewportAspectRatio(); float pX = (float)x / float(vp.getViewportSizePixels()[0]); float pY = (float)y / float(vp.getViewportSizePixels()[1]); // now calculate the real points respecting aspect ratio information // if (fRatio > 1.0f) { pX = (pX - 0.5f*dX) * fRatio + 0.5f*dX; } else if (fRatio < 1.0f) { pY = (pY - 0.5f*dY) / fRatio + 0.5f*dY; } SoCamera* pCam = viewer->getSoRenderManager()->getCamera(); if (!pCam) return; SbViewVolume vol = pCam->getViewVolume(); vol.projectPointToLine(SbVec2f(pX,pY), line); } void ViewProviderSketch::getCoordsOnSketchPlane(double &u, double &v,const SbVec3f &point, const SbVec3f &normal) { // Plane form Base::Vector3d R0(0,0,0),RN(0,0,1),RX(1,0,0),RY(0,1,0); // move to position of Sketch Base::Placement Plz = getSketchObject()->Placement.getValue(); R0 = Plz.getPosition() ; Base::Rotation tmp(Plz.getRotation()); tmp.multVec(RN,RN); tmp.multVec(RX,RX); tmp.multVec(RY,RY); Plz.setRotation(tmp); // line Base::Vector3d R1(point[0],point[1],point[2]),RA(normal[0],normal[1],normal[2]); if (fabs(RN*RA) < FLT_EPSILON) throw Base::DivisionByZeroError("View direction is parallel to sketch plane"); // intersection point on plane Base::Vector3d S = R1 + ((RN * (R0-R1))/(RN*RA))*RA; // distance to x Axle of the sketch S.TransformToCoordinateSystem(R0,RX,RY); u = S.x; v = S.y; } bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVec2s &cursorPos, const Gui::View3DInventorViewer *viewer) { assert(edit); // Calculate 3d point to the mouse position SbLine line; getProjectingLine(cursorPos, viewer, line); SbVec3f point = line.getPosition(); SbVec3f normal = line.getDirection(); // use scoped_ptr to make sure that instance gets deleted in all cases boost::scoped_ptr<SoPickedPoint> pp(this->getPointOnRay(cursorPos, viewer)); // Radius maximum to allow double click event const int dblClickRadius = 5; double x,y; SbVec3f pos = point; if (pp) { const SoDetail *detail = pp->getDetail(); if (detail && detail->getTypeId() == SoPointDetail::getClassTypeId()) { pos = pp->getPoint(); } } try { getCoordsOnSketchPlane(x,y,pos,normal); snapToGrid(x, y); } catch (const Base::DivisionByZeroError&) { return false; } // Left Mouse button **************************************************** if (Button == 1) { if (pressed) { // Do things depending on the mode of the user interaction switch (Mode) { case STATUS_NONE:{ bool done=false; if (edit->PreselectPoint != -1) { //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Point; done = true; } else if (edit->PreselectCurve != -1) { //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Edge; done = true; } else if (edit->PreselectCross != -1) { //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Cross; done = true; } else if (edit->PreselectConstraintSet.empty() != true) { //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Constraint; done = true; } // Double click events variables float dci = (float) QApplication::doubleClickInterval()/1000.0f; if (done && (point - prvClickPoint).length() < dblClickRadius && (SbTime::getTimeOfDay() - prvClickTime).getValue() < dci) { // Double Click Event Occured editDoubleClicked(); // Reset Double Click Static Variables prvClickTime = SbTime(); prvClickPoint = SbVec3f(0.0f, 0.0f, 0.0f); Mode = STATUS_NONE; } else { prvClickTime = SbTime::getTimeOfDay(); prvClickPoint = point; prvCursorPos = cursorPos; newCursorPos = cursorPos; if (!done) Mode = STATUS_SKETCH_StartRubberBand; } return done; } case STATUS_SKETCH_UseHandler: return edit->sketchHandler->pressButton(Base::Vector2D(x,y)); default: return false; } } else { // Button 1 released // Do things depending on the mode of the user interaction switch (Mode) { case STATUS_SELECT_Point: if (pp) { //Base::Console().Log("Select Point:%d\n",this->DragPoint); // Do selection std::stringstream ss; ss << "Vertex" << edit->PreselectPoint + 1; if (Gui::Selection().isSelected(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(),ss.str().c_str()) ) { Gui::Selection().rmvSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(), ss.str().c_str()); } else { Gui::Selection().addSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,pp->getPoint()[0] ,pp->getPoint()[1] ,pp->getPoint()[2]); this->edit->DragPoint = -1; this->edit->DragCurve = -1; this->edit->DragConstraintSet.clear(); } } Mode = STATUS_NONE; return true; case STATUS_SELECT_Edge: if (pp) { //Base::Console().Log("Select Point:%d\n",this->DragPoint); std::stringstream ss; if (edit->PreselectCurve >= 0) ss << "Edge" << edit->PreselectCurve + 1; else // external geometry ss << "ExternalEdge" << -edit->PreselectCurve - 2; // If edge already selected move from selection if (Gui::Selection().isSelected(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(),ss.str().c_str()) ) { Gui::Selection().rmvSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(), ss.str().c_str()); } else { // Add edge to the selection Gui::Selection().addSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,pp->getPoint()[0] ,pp->getPoint()[1] ,pp->getPoint()[2]); this->edit->DragPoint = -1; this->edit->DragCurve = -1; this->edit->DragConstraintSet.clear(); } } Mode = STATUS_NONE; return true; case STATUS_SELECT_Cross: if (pp) { //Base::Console().Log("Select Point:%d\n",this->DragPoint); std::stringstream ss; switch(edit->PreselectCross){ case 0: ss << "RootPoint" ; break; case 1: ss << "H_Axis" ; break; case 2: ss << "V_Axis" ; break; } // If cross already selected move from selection if (Gui::Selection().isSelected(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(),ss.str().c_str()) ) { Gui::Selection().rmvSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(), ss.str().c_str()); } else { // Add cross to the selection Gui::Selection().addSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,pp->getPoint()[0] ,pp->getPoint()[1] ,pp->getPoint()[2]); this->edit->DragPoint = -1; this->edit->DragCurve = -1; this->edit->DragConstraintSet.clear(); } } Mode = STATUS_NONE; return true; case STATUS_SELECT_Constraint: if (pp) { for(std::set<int>::iterator it = edit->PreselectConstraintSet.begin(); it != edit->PreselectConstraintSet.end(); ++it) { std::string constraintName(Sketcher::PropertyConstraintList::getConstraintName(*it)); // If the constraint already selected remove if (Gui::Selection().isSelected(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(),constraintName.c_str()) ) { Gui::Selection().rmvSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(), constraintName.c_str()); } else { // Add constraint to current selection Gui::Selection().addSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,constraintName.c_str() ,pp->getPoint()[0] ,pp->getPoint()[1] ,pp->getPoint()[2]); this->edit->DragPoint = -1; this->edit->DragCurve = -1; this->edit->DragConstraintSet.clear(); } } } Mode = STATUS_NONE; return true; case STATUS_SKETCH_DragPoint: if (edit->DragPoint != -1) { int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(edit->DragPoint, GeoId, PosId); if (GeoId != Sketcher::Constraint::GeoUndef && PosId != Sketcher::none) { Gui::Command::openCommand("Drag Point"); try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.movePoint(%i,%i,App.Vector(%f,%f,0),%i)" ,getObject()->getNameInDocument() ,GeoId, PosId, x-xInit, y-yInit, relative ? 1 : 0 ); Gui::Command::commitCommand(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); bool autoRecompute = hGrp->GetBool("AutoRecompute",false); if(autoRecompute) Gui::Command::updateActive(); } catch (const Base::Exception& e) { Gui::Command::abortCommand(); Base::Console().Error("Drag point: %s\n", e.what()); } } setPreselectPoint(edit->DragPoint); edit->DragPoint = -1; //updateColor(); } resetPositionText(); Mode = STATUS_NONE; return true; case STATUS_SKETCH_DragCurve: if (edit->DragCurve != -1) { const Part::Geometry *geo = getSketchObject()->getGeometry(edit->DragCurve); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId() || geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() || geo->getTypeId() == Part::GeomCircle::getClassTypeId() || geo->getTypeId() == Part::GeomEllipse::getClassTypeId()|| geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { Gui::Command::openCommand("Drag Curve"); try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.movePoint(%i,%i,App.Vector(%f,%f,0),%i)" ,getObject()->getNameInDocument() ,edit->DragCurve, Sketcher::none, x-xInit, y-yInit, relative ? 1 : 0 ); Gui::Command::commitCommand(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); bool autoRecompute = hGrp->GetBool("AutoRecompute",false); if(autoRecompute) Gui::Command::updateActive(); } catch (const Base::Exception& e) { Gui::Command::abortCommand(); Base::Console().Error("Drag curve: %s\n", e.what()); } } edit->PreselectCurve = edit->DragCurve; edit->DragCurve = -1; //updateColor(); } resetPositionText(); Mode = STATUS_NONE; return true; case STATUS_SKETCH_DragConstraint: if (edit->DragConstraintSet.empty() == false) { Gui::Command::openCommand("Drag Constraint"); for(std::set<int>::iterator it = edit->DragConstraintSet.begin(); it != edit->DragConstraintSet.end(); ++it) { moveConstraint(*it, Base::Vector2D(x, y)); //updateColor(); } edit->PreselectConstraintSet = edit->DragConstraintSet; edit->DragConstraintSet.clear(); } Mode = STATUS_NONE; return true; case STATUS_SKETCH_StartRubberBand: // a single click happened, so clear selection Mode = STATUS_NONE; Gui::Selection().clearSelection(); return true; case STATUS_SKETCH_UseRubberBand: doBoxSelection(prvCursorPos, cursorPos, viewer); rubberband->setWorking(false); //disable framebuffer drawing in viewer const_cast<Gui::View3DInventorViewer *>(viewer)->setRenderType(Gui::View3DInventorViewer::Native); // a redraw is required in order to clear the rubberband draw(true); Mode = STATUS_NONE; return true; case STATUS_SKETCH_UseHandler: return edit->sketchHandler->releaseButton(Base::Vector2D(x,y)); case STATUS_NONE: default: return false; } } } // Right mouse button **************************************************** else if (Button == 2) { if (!pressed) { switch (Mode) { case STATUS_SKETCH_UseHandler: // make the handler quit edit->sketchHandler->quit(); return true; case STATUS_NONE: { // A right click shouldn't change the Edit Mode if (edit->PreselectPoint != -1) { return true; } else if (edit->PreselectCurve != -1) { return true; } else if (edit->PreselectConstraintSet.empty() != true) { return true; } else { Gui::MenuItem *geom = new Gui::MenuItem(); geom->setCommand("Sketcher geoms"); *geom << "Sketcher_CreatePoint" << "Sketcher_CreateArc" << "Sketcher_Create3PointArc" << "Sketcher_CreateCircle" << "Sketcher_Create3PointCircle" << "Sketcher_CreateLine" << "Sketcher_CreatePolyline" << "Sketcher_CreateRectangle" << "Sketcher_CreateHexagon" << "Sketcher_CreateFillet" << "Sketcher_Trimming" << "Sketcher_External" << "Sketcher_ToggleConstruction" /*<< "Sketcher_CreateText"*/ /*<< "Sketcher_CreateDraftLine"*/ << "Separator"; Gui::Application::Instance->setupContextMenu("View", geom); //Create the Context Menu using the Main View Qt Widget QMenu contextMenu(viewer->getGLWidget()); Gui::MenuManager::getInstance()->setupContextMenu(geom, contextMenu); contextMenu.exec(QCursor::pos()); return true; } } case STATUS_SELECT_Point: break; case STATUS_SELECT_Edge: { Gui::MenuItem *geom = new Gui::MenuItem(); geom->setCommand("Sketcher constraints"); *geom << "Sketcher_ConstrainVertical" << "Sketcher_ConstrainHorizontal"; // Gets a selection vector std::vector<Gui::SelectionObject> selection = Gui::Selection().getSelectionEx(); bool rightClickOnSelectedLine = false; /* * Add Multiple Line Constraints to the menu */ // only one sketch with its subelements are allowed to be selected if (selection.size() == 1) { // get the needed lists and objects const std::vector<std::string> &SubNames = selection[0].getSubNames(); // Two Objects are selected if (SubNames.size() == 2) { // go through the selected subelements for (std::vector<std::string>::const_iterator it=SubNames.begin(); it!=SubNames.end();++it) { // If the object selected is of type edge if (it->size() > 4 && it->substr(0,4) == "Edge") { // Get the index of the object selected int GeoId = std::atoi(it->substr(4,4000).c_str()) - 1; if (edit->PreselectCurve == GeoId) rightClickOnSelectedLine = true; } else { // The selection is not exclusively edges rightClickOnSelectedLine = false; } } // End of Iteration } } if (rightClickOnSelectedLine) { *geom << "Sketcher_ConstrainParallel" << "Sketcher_ConstrainPerpendicular"; } Gui::Application::Instance->setupContextMenu("View", geom); //Create the Context Menu using the Main View Qt Widget QMenu contextMenu(viewer->getGLWidget()); Gui::MenuManager::getInstance()->setupContextMenu(geom, contextMenu); contextMenu.exec(QCursor::pos()); return true; } case STATUS_SELECT_Cross: case STATUS_SELECT_Constraint: case STATUS_SKETCH_DragPoint: case STATUS_SKETCH_DragCurve: case STATUS_SKETCH_DragConstraint: case STATUS_SKETCH_StartRubberBand: case STATUS_SKETCH_UseRubberBand: break; } } } return false; } void ViewProviderSketch::editDoubleClicked(void) { if (edit->PreselectPoint != -1) { Base::Console().Log("double click point:%d\n",edit->PreselectPoint); } else if (edit->PreselectCurve != -1) { Base::Console().Log("double click edge:%d\n",edit->PreselectCurve); } else if (edit->PreselectCross != -1) { Base::Console().Log("double click cross:%d\n",edit->PreselectCross); } else if (edit->PreselectConstraintSet.empty() != true) { // Find the constraint const std::vector<Sketcher::Constraint *> &constrlist = getSketchObject()->Constraints.getValues(); for(std::set<int>::iterator it = edit->PreselectConstraintSet.begin(); it != edit->PreselectConstraintSet.end(); ++it) { Constraint *Constr = constrlist[*it]; // if its the right constraint if ((Constr->Type == Sketcher::Distance || Constr->Type == Sketcher::DistanceX || Constr->Type == Sketcher::DistanceY || Constr->Type == Sketcher::Radius || Constr->Type == Sketcher::Angle || Constr->Type == Sketcher::SnellsLaw) && Constr->isDriving ) { // Coin's SoIdleSensor causes problems on some platform while Qt seems to work properly (#0001517) EditDatumDialog *editDatumDialog = new EditDatumDialog(this, *it); QCoreApplication::postEvent(editDatumDialog, new QEvent(QEvent::User)); edit->editDatumDialog = true; // avoid to double handle "ESC" } } } } bool ViewProviderSketch::mouseMove(const SbVec2s &cursorPos, Gui::View3DInventorViewer *viewer) { // maximum radius for mouse moves when selecting a geometry before switching to drag mode const int dragIgnoredDistance = 3; if (!edit) return false; // ignore small moves after selection switch (Mode) { case STATUS_SELECT_Point: case STATUS_SELECT_Edge: case STATUS_SELECT_Constraint: case STATUS_SKETCH_StartRubberBand: short dx, dy; (cursorPos - prvCursorPos).getValue(dx, dy); if(std::abs(dx) < dragIgnoredDistance && std::abs(dy) < dragIgnoredDistance) return false; default: break; } // Calculate 3d point to the mouse position SbLine line; getProjectingLine(cursorPos, viewer, line); double x,y; try { getCoordsOnSketchPlane(x,y,line.getPosition(),line.getDirection()); snapToGrid(x, y); } catch (const Base::DivisionByZeroError&) { return false; } bool preselectChanged = false; if (Mode != STATUS_SELECT_Point && Mode != STATUS_SELECT_Edge && Mode != STATUS_SELECT_Constraint && Mode != STATUS_SKETCH_DragPoint && Mode != STATUS_SKETCH_DragCurve && Mode != STATUS_SKETCH_DragConstraint && Mode != STATUS_SKETCH_UseRubberBand) { boost::scoped_ptr<SoPickedPoint> pp(this->getPointOnRay(cursorPos, viewer)); preselectChanged = detectPreselection(pp.get(), viewer, cursorPos); } switch (Mode) { case STATUS_NONE: if (preselectChanged) { this->drawConstraintIcons(); this->updateColor(); return true; } return false; case STATUS_SELECT_Point: if (!getSketchObject()->getSolvedSketch().hasConflicts() && edit->PreselectPoint != -1 && edit->DragPoint != edit->PreselectPoint) { Mode = STATUS_SKETCH_DragPoint; edit->DragPoint = edit->PreselectPoint; int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(edit->DragPoint, GeoId, PosId); if (GeoId != Sketcher::Constraint::GeoUndef && PosId != Sketcher::none) { getSketchObject()->getSolvedSketch().initMove(GeoId, PosId, false); relative = false; xInit = 0; yInit = 0; } } else { Mode = STATUS_NONE; } resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); return true; case STATUS_SELECT_Edge: if (!getSketchObject()->getSolvedSketch().hasConflicts() && edit->PreselectCurve != -1 && edit->DragCurve != edit->PreselectCurve) { Mode = STATUS_SKETCH_DragCurve; edit->DragCurve = edit->PreselectCurve; getSketchObject()->getSolvedSketch().initMove(edit->DragCurve, Sketcher::none, false); const Part::Geometry *geo = getSketchObject()->getGeometry(edit->DragCurve); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { relative = true; //xInit = x; //yInit = y; // Since the cursor moved from where it was clicked, and this is a relative move, // calculate the click position and use it as initial point. SbLine line2; getProjectingLine(prvCursorPos, viewer, line2); getCoordsOnSketchPlane(xInit,yInit,line2.getPosition(),line2.getDirection()); snapToGrid(xInit, yInit); } else { relative = false; xInit = 0; yInit = 0; } } else { Mode = STATUS_NONE; } resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); return true; case STATUS_SELECT_Constraint: Mode = STATUS_SKETCH_DragConstraint; edit->DragConstraintSet = edit->PreselectConstraintSet; resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); return true; case STATUS_SKETCH_DragPoint: if (edit->DragPoint != -1) { //Base::Console().Log("Drag Point:%d\n",edit->DragPoint); int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(edit->DragPoint, GeoId, PosId); Base::Vector3d vec(x-xInit,y-yInit,0); if (GeoId != Sketcher::Constraint::GeoUndef && PosId != Sketcher::none) { if (getSketchObject()->getSolvedSketch().movePoint(GeoId, PosId, vec, relative) == 0) { setPositionText(Base::Vector2D(x,y)); draw(true); signalSolved(QString::fromLatin1("Solved in %1 sec").arg(getSketchObject()->getSolvedSketch().SolveTime)); } else { signalSolved(QString::fromLatin1("Unsolved (%1 sec)").arg(getSketchObject()->getSolvedSketch().SolveTime)); //Base::Console().Log("Error solving:%d\n",ret); } } } return true; case STATUS_SKETCH_DragCurve: if (edit->DragCurve != -1) { Base::Vector3d vec(x-xInit,y-yInit,0); if (getSketchObject()->getSolvedSketch().movePoint(edit->DragCurve, Sketcher::none, vec, relative) == 0) { setPositionText(Base::Vector2D(x,y)); draw(true); signalSolved(QString::fromLatin1("Solved in %1 sec").arg(getSketchObject()->getSolvedSketch().SolveTime)); } else { signalSolved(QString::fromLatin1("Unsolved (%1 sec)").arg(getSketchObject()->getSolvedSketch().SolveTime)); } } return true; case STATUS_SKETCH_DragConstraint: if (edit->DragConstraintSet.empty() == false) { for(std::set<int>::iterator it = edit->DragConstraintSet.begin(); it != edit->DragConstraintSet.end(); ++it) moveConstraint(*it, Base::Vector2D(x,y)); } return true; case STATUS_SKETCH_UseHandler: edit->sketchHandler->mouseMove(Base::Vector2D(x,y)); if (preselectChanged) { this->drawConstraintIcons(); this->updateColor(); } return true; case STATUS_SKETCH_StartRubberBand: { Mode = STATUS_SKETCH_UseRubberBand; rubberband->setWorking(true); viewer->setRenderType(Gui::View3DInventorViewer::Image); return true; } case STATUS_SKETCH_UseRubberBand: { newCursorPos = cursorPos; rubberband->setCoords(prvCursorPos.getValue()[0], viewer->getGLWidget()->height() - prvCursorPos.getValue()[1], newCursorPos.getValue()[0], viewer->getGLWidget()->height() - newCursorPos.getValue()[1]); viewer->redraw(); return true; } default: return false; } return false; } void ViewProviderSketch::moveConstraint(int constNum, const Base::Vector2D &toPos) { // are we in edit? if (!edit) return; const std::vector<Sketcher::Constraint *> &constrlist = getSketchObject()->Constraints.getValues(); Constraint *Constr = constrlist[constNum]; #ifdef _DEBUG int intGeoCount = getSketchObject()->getHighestCurveIndex() + 1; int extGeoCount = getSketchObject()->getExternalGeometryCount(); #endif // with memory allocation const std::vector<Part::Geometry *> geomlist = getSketchObject()->getSolvedSketch().extractGeometry(true, true); #ifdef _DEBUG assert(int(geomlist.size()) == extGeoCount + intGeoCount); assert((Constr->First >= -extGeoCount && Constr->First < intGeoCount) || Constr->First != Constraint::GeoUndef); #endif if (Constr->Type == Distance || Constr->Type == DistanceX || Constr->Type == DistanceY || Constr->Type == Radius) { Base::Vector3d p1(0.,0.,0.), p2(0.,0.,0.); if (Constr->SecondPos != Sketcher::none) { // point to point distance p1 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); p2 = getSketchObject()->getSolvedSketch().getPoint(Constr->Second, Constr->SecondPos); } else if (Constr->Second != Constraint::GeoUndef) { // point to line distance p1 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); const Part::Geometry *geo = GeoById(geomlist, Constr->Second); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo); Base::Vector3d l2p1 = lineSeg->getStartPoint(); Base::Vector3d l2p2 = lineSeg->getEndPoint(); // calculate the projection of p1 onto line2 p2.ProjToLine(p1-l2p1, l2p2-l2p1); p2 += p1; } else return; } else if (Constr->FirstPos != Sketcher::none) { p2 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); } else if (Constr->First != Constraint::GeoUndef) { const Part::Geometry *geo = GeoById(geomlist, Constr->First); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo); p1 = lineSeg->getStartPoint(); p2 = lineSeg->getEndPoint(); } else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo); double radius = arc->getRadius(); p1 = arc->getCenter(); double angle = Constr->LabelPosition; if (angle == 10) { double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); angle = (startangle + endangle)/2; } else { Base::Vector3d tmpDir = Base::Vector3d(toPos.fX, toPos.fY, 0) - p1; angle = atan2(tmpDir.y, tmpDir.x); } p2 = p1 + radius * Base::Vector3d(cos(angle),sin(angle),0.); } else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo); double radius = circle->getRadius(); p1 = circle->getCenter(); Base::Vector3d tmpDir = Base::Vector3d(toPos.fX, toPos.fY, 0) - p1; double angle = atan2(tmpDir.y, tmpDir.x); p2 = p1 + radius * Base::Vector3d(cos(angle),sin(angle),0.); } else return; } else return; Base::Vector3d vec = Base::Vector3d(toPos.fX, toPos.fY, 0) - p2; Base::Vector3d dir; if (Constr->Type == Distance || Constr->Type == Radius) dir = (p2-p1).Normalize(); else if (Constr->Type == DistanceX) dir = Base::Vector3d( (p2.x - p1.x >= FLT_EPSILON) ? 1 : -1, 0, 0); else if (Constr->Type == DistanceY) dir = Base::Vector3d(0, (p2.y - p1.y >= FLT_EPSILON) ? 1 : -1, 0); if (Constr->Type == Radius) { Constr->LabelDistance = vec.x * dir.x + vec.y * dir.y; Constr->LabelPosition = atan2(dir.y, dir.x); } else { Base::Vector3d norm(-dir.y,dir.x,0); Constr->LabelDistance = vec.x * norm.x + vec.y * norm.y; if (Constr->Type == Distance || Constr->Type == DistanceX || Constr->Type == DistanceY) { vec = Base::Vector3d(toPos.fX, toPos.fY, 0) - (p2 + p1) / 2; Constr->LabelPosition = vec.x * dir.x + vec.y * dir.y; } } } else if (Constr->Type == Angle) { Base::Vector3d p0(0.,0.,0.); if (Constr->Second != Constraint::GeoUndef) { // line to line angle Base::Vector3d dir1, dir2; if(Constr->Third == Constraint::GeoUndef) { //angle between two lines const Part::Geometry *geo1 = GeoById(geomlist, Constr->First); const Part::Geometry *geo2 = GeoById(geomlist, Constr->Second); if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() || geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) return; const Part::GeomLineSegment *lineSeg1 = dynamic_cast<const Part::GeomLineSegment *>(geo1); const Part::GeomLineSegment *lineSeg2 = dynamic_cast<const Part::GeomLineSegment *>(geo2); bool flip1 = (Constr->FirstPos == end); bool flip2 = (Constr->SecondPos == end); dir1 = (flip1 ? -1. : 1.) * (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()); dir2 = (flip2 ? -1. : 1.) * (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()); Base::Vector3d pnt1 = flip1 ? lineSeg1->getEndPoint() : lineSeg1->getStartPoint(); Base::Vector3d pnt2 = flip2 ? lineSeg2->getEndPoint() : lineSeg2->getStartPoint(); // line-line intersection { double det = dir1.x*dir2.y - dir1.y*dir2.x; if ((det > 0 ? det : -det) < 1e-10) return;// lines are parallel - constraint unmoveable (DeepSOIC: why?..) double c1 = dir1.y*pnt1.x - dir1.x*pnt1.y; double c2 = dir2.y*pnt2.x - dir2.x*pnt2.y; double x = (dir1.x*c2 - dir2.x*c1)/det; double y = (dir1.y*c2 - dir2.y*c1)/det; p0 = Base::Vector3d(x,y,0); } } else {//angle-via-point Base::Vector3d p = getSketchObject()->getSolvedSketch().getPoint(Constr->Third, Constr->ThirdPos); p0 = Base::Vector3d(p.x, p.y, 0); dir1 = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->First, p.x, p.y); dir1.RotateZ(-M_PI/2);//convert to vector of tangency by rotating dir2 = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->Second, p.x, p.y); dir2.RotateZ(-M_PI/2); } } else if (Constr->First != Constraint::GeoUndef) { // line/arc angle const Part::Geometry *geo = GeoById(geomlist, Constr->First); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo); p0 = (lineSeg->getEndPoint()+lineSeg->getStartPoint())/2; } else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo); p0 = arc->getCenter(); } else { return; } } else return; Base::Vector3d vec = Base::Vector3d(toPos.fX, toPos.fY, 0) - p0; Constr->LabelDistance = vec.Length()/2; } // delete the cloned objects for (std::vector<Part::Geometry *>::const_iterator it=geomlist.begin(); it != geomlist.end(); ++it) if (*it) delete *it; draw(true); } Base::Vector3d ViewProviderSketch::seekConstraintPosition(const Base::Vector3d &origPos, const Base::Vector3d &norm, const Base::Vector3d &dir, float step, const SoNode *constraint) { assert(edit); Gui::MDIView *mdi = this->getEditingView(); if (!(mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId()))) return Base::Vector3d(0, 0, 0); Gui::View3DInventorViewer *viewer = static_cast<Gui::View3DInventor *>(mdi)->getViewer(); SoRayPickAction rp(viewer->getSoRenderManager()->getViewportRegion()); float scaled_step = step * getScaleFactor(); int multiplier = 0; Base::Vector3d relPos, freePos; bool isConstraintAtPosition = true; while (isConstraintAtPosition && multiplier < 10) { // Calculate new position of constraint relPos = norm * 0.5f + dir * multiplier; freePos = origPos + relPos * scaled_step; rp.setRadius(0.1f); rp.setPickAll(true); rp.setRay(SbVec3f(freePos.x, freePos.y, -1.f), SbVec3f(0, 0, 1) ); //problem rp.apply(edit->constrGroup); // We could narrow it down to just the SoGroup containing the constraints // returns a copy of the point SoPickedPoint *pp = rp.getPickedPoint(); const SoPickedPointList ppl = rp.getPickedPointList(); if (ppl.getLength() <= 1 && pp) { SoPath *path = pp->getPath(); int length = path->getLength(); SoNode *tailFather1 = path->getNode(length-2); SoNode *tailFather2 = path->getNode(length-3); // checking if a constraint is the same as the one selected if (tailFather1 == constraint || tailFather2 == constraint) isConstraintAtPosition = false; } else { isConstraintAtPosition = false; } multiplier *= -1; // search in both sides if (multiplier >= 0) multiplier++; // Increment the multiplier } if (multiplier == 10) relPos = norm * 0.5f; // no free position found return relPos * step; } bool ViewProviderSketch::isSelectable(void) const { if (isEditing()) return false; else return PartGui::ViewProvider2DObject::isSelectable(); } void ViewProviderSketch::onSelectionChanged(const Gui::SelectionChanges& msg) { // are we in edit? if (edit) { bool handled=false; if (Mode == STATUS_SKETCH_UseHandler) { handled = edit->sketchHandler->onSelectionChanged(msg); } if (handled) return; std::string temp; if (msg.Type == Gui::SelectionChanges::ClrSelection) { // if something selected in this object? if (edit->SelPointSet.size() > 0 || edit->SelCurvSet.size() > 0 || edit->SelConstraintSet.size() > 0) { // clear our selection and update the color of the viewed edges and points clearSelectPoints(); edit->SelCurvSet.clear(); edit->SelConstraintSet.clear(); this->drawConstraintIcons(); this->updateColor(); } } else if (msg.Type == Gui::SelectionChanges::AddSelection) { // is it this object?? if (strcmp(msg.pDocName,getSketchObject()->getDocument()->getName())==0 && strcmp(msg.pObjectName,getSketchObject()->getNameInDocument())== 0) { if (msg.pSubName) { std::string shapetype(msg.pSubName); if (shapetype.size() > 4 && shapetype.substr(0,4) == "Edge") { int GeoId = std::atoi(&shapetype[4]) - 1; edit->SelCurvSet.insert(GeoId); this->updateColor(); } else if (shapetype.size() > 12 && shapetype.substr(0,12) == "ExternalEdge") { int GeoId = std::atoi(&shapetype[12]) - 1; GeoId = -GeoId - 3; edit->SelCurvSet.insert(GeoId); this->updateColor(); } else if (shapetype.size() > 6 && shapetype.substr(0,6) == "Vertex") { int VtId = std::atoi(&shapetype[6]) - 1; addSelectPoint(VtId); this->updateColor(); } else if (shapetype == "RootPoint") { addSelectPoint(-1); this->updateColor(); } else if (shapetype == "H_Axis") { edit->SelCurvSet.insert(-1); this->updateColor(); } else if (shapetype == "V_Axis") { edit->SelCurvSet.insert(-2); this->updateColor(); } else if (shapetype.size() > 10 && shapetype.substr(0,10) == "Constraint") { int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(shapetype); edit->SelConstraintSet.insert(ConstrId); this->drawConstraintIcons(); this->updateColor(); } } } } else if (msg.Type == Gui::SelectionChanges::RmvSelection) { // Are there any objects selected if (edit->SelPointSet.size() > 0 || edit->SelCurvSet.size() > 0 || edit->SelConstraintSet.size() > 0) { // is it this object?? if (strcmp(msg.pDocName,getSketchObject()->getDocument()->getName())==0 && strcmp(msg.pObjectName,getSketchObject()->getNameInDocument())== 0) { if (msg.pSubName) { std::string shapetype(msg.pSubName); if (shapetype.size() > 4 && shapetype.substr(0,4) == "Edge") { int GeoId = std::atoi(&shapetype[4]) - 1; edit->SelCurvSet.erase(GeoId); this->updateColor(); } else if (shapetype.size() > 12 && shapetype.substr(0,12) == "ExternalEdge") { int GeoId = std::atoi(&shapetype[12]) - 1; GeoId = -GeoId - 3; edit->SelCurvSet.erase(GeoId); this->updateColor(); } else if (shapetype.size() > 6 && shapetype.substr(0,6) == "Vertex") { int VtId = std::atoi(&shapetype[6]) - 1; removeSelectPoint(VtId); this->updateColor(); } else if (shapetype == "RootPoint") { removeSelectPoint(-1); this->updateColor(); } else if (shapetype == "H_Axis") { edit->SelCurvSet.erase(-1); this->updateColor(); } else if (shapetype == "V_Axis") { edit->SelCurvSet.erase(-2); this->updateColor(); } else if (shapetype.size() > 10 && shapetype.substr(0,10) == "Constraint") { int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(shapetype); edit->SelConstraintSet.erase(ConstrId); this->drawConstraintIcons(); this->updateColor(); } } } } } else if (msg.Type == Gui::SelectionChanges::SetSelection) { // remove all items //selectionView->clear(); //std::vector<SelectionSingleton::SelObj> objs = Gui::Selection().getSelection(Reason.pDocName); //for (std::vector<SelectionSingleton::SelObj>::iterator it = objs.begin(); it != objs.end(); ++it) { // // build name // temp = it->DocName; // temp += "."; // temp += it->FeatName; // if (it->SubName && it->SubName[0] != '\0') { // temp += "."; // temp += it->SubName; // } // new QListWidgetItem(QString::fromLatin1(temp.c_str()), selectionView); //} } else if (msg.Type == Gui::SelectionChanges::SetPreselect) { if (strcmp(msg.pDocName,getSketchObject()->getDocument()->getName())==0 && strcmp(msg.pObjectName,getSketchObject()->getNameInDocument())== 0) { if (msg.pSubName) { std::string shapetype(msg.pSubName); if (shapetype.size() > 4 && shapetype.substr(0,4) == "Edge") { int GeoId = std::atoi(&shapetype[4]) - 1; resetPreselectPoint(); edit->PreselectCurve = GeoId; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); this->updateColor(); } else if (shapetype.size() > 6 && shapetype.substr(0,6) == "Vertex") { int PtIndex = std::atoi(&shapetype[6]) - 1; setPreselectPoint(PtIndex); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); this->updateColor(); } } } } else if (msg.Type == Gui::SelectionChanges::RmvPreselect) { resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); this->updateColor(); } } } std::set<int> ViewProviderSketch::detectPreselectionConstr(const SoPickedPoint *Point, const Gui::View3DInventorViewer *viewer, const SbVec2s &cursorPos) { std::set<int> constrIndices; SoPath *path = Point->getPath(); SoNode *tail = path->getTail(); SoNode *tailFather = path->getNode(path->getLength()-2); for (int i=0; i < edit->constrGroup->getNumChildren(); ++i) if (edit->constrGroup->getChild(i) == tailFather) { SoSeparator *sep = static_cast<SoSeparator *>(tailFather); if(sep->getNumChildren() > CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID) { SoInfo *constrIds = NULL; if(tail == sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON)) { // First icon was hit constrIds = static_cast<SoInfo *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID)); } else { // Assume second icon was hit if(CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID<sep->getNumChildren()){ constrIds = static_cast<SoInfo *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID)); } } if(constrIds) { QString constrIdsStr = QString::fromLatin1(constrIds->string.getValue().getString()); if(edit->combinedConstrBoxes.count(constrIdsStr) && dynamic_cast<SoImage *>(tail)) { // If it's a combined constraint icon // Screen dimensions of the icon SbVec3s iconSize = getDisplayedSize(static_cast<SoImage *>(tail)); // Center of the icon SbVec2f iconCoords = viewer->screenCoordsOfPath(path); // Coordinates of the mouse cursor on the icon, origin at top-left int iconX = cursorPos[0] - iconCoords[0] + iconSize[0]/2, iconY = iconCoords[1] - cursorPos[1] + iconSize[1]/2; for(ConstrIconBBVec::iterator b = edit->combinedConstrBoxes[constrIdsStr].begin(); b != edit->combinedConstrBoxes[constrIdsStr].end(); ++b) { if(b->first.contains(iconX, iconY)) // We've found a bounding box that contains the mouse pointer! for(std::set<int>::iterator k = b->second.begin(); k != b->second.end(); ++k) constrIndices.insert(*k); } } else { // It's a constraint icon, not a combined one QStringList constrIdStrings = constrIdsStr.split(QString::fromLatin1(",")); while(!constrIdStrings.empty()) constrIndices.insert(constrIdStrings.takeAt(0).toInt()); } } } else { // other constraint icons - eg radius... constrIndices.clear(); constrIndices.insert(i); } break; } return constrIndices; } bool ViewProviderSketch::detectPreselection(const SoPickedPoint *Point, const Gui::View3DInventorViewer *viewer, const SbVec2s &cursorPos) { assert(edit); int PtIndex = -1; int GeoIndex = -1; // valid values are 0,1,2,... for normal geometry and -3,-4,-5,... for external geometry int CrossIndex = -1; std::set<int> constrIndices; if (Point) { //Base::Console().Log("Point pick\n"); SoPath *path = Point->getPath(); SoNode *tail = path->getTail(); SoNode *tailFather2 = path->getNode(path->getLength()-3); // checking for a hit in the points if (tail == edit->PointSet) { const SoDetail *point_detail = Point->getDetail(edit->PointSet); if (point_detail && point_detail->getTypeId() == SoPointDetail::getClassTypeId()) { // get the index PtIndex = static_cast<const SoPointDetail *>(point_detail)->getCoordinateIndex(); PtIndex -= 1; // shift corresponding to RootPoint if (PtIndex == -1) CrossIndex = 0; // RootPoint was hit } } else { // checking for a hit in the curves if (tail == edit->CurveSet) { const SoDetail *curve_detail = Point->getDetail(edit->CurveSet); if (curve_detail && curve_detail->getTypeId() == SoLineDetail::getClassTypeId()) { // get the index int curveIndex = static_cast<const SoLineDetail *>(curve_detail)->getLineIndex(); GeoIndex = edit->CurvIdToGeoId[curveIndex]; } // checking for a hit in the cross } else if (tail == edit->RootCrossSet) { const SoDetail *cross_detail = Point->getDetail(edit->RootCrossSet); if (cross_detail && cross_detail->getTypeId() == SoLineDetail::getClassTypeId()) { // get the index (reserve index 0 for root point) CrossIndex = 1 + static_cast<const SoLineDetail *>(cross_detail)->getLineIndex(); } } else { // checking if a constraint is hit if (tailFather2 == edit->constrGroup) constrIndices = detectPreselectionConstr(Point, viewer, cursorPos); } } if (PtIndex != -1 && PtIndex != edit->PreselectPoint) { // if a new point is hit std::stringstream ss; ss << "Vertex" << PtIndex + 1; bool accepted = Gui::Selection().setPreselect(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,Point->getPoint()[0] ,Point->getPoint()[1] ,Point->getPoint()[2]); edit->blockedPreselection = !accepted; if (accepted) { setPreselectPoint(PtIndex); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true; } } else if (GeoIndex != -1 && GeoIndex != edit->PreselectCurve) { // if a new curve is hit std::stringstream ss; if (GeoIndex >= 0) ss << "Edge" << GeoIndex + 1; else // external geometry ss << "ExternalEdge" << -GeoIndex - 2; // convert index start from -3 to 1 bool accepted = Gui::Selection().setPreselect(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,Point->getPoint()[0] ,Point->getPoint()[1] ,Point->getPoint()[2]); edit->blockedPreselection = !accepted; if (accepted) { resetPreselectPoint(); edit->PreselectCurve = GeoIndex; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true; } } else if (CrossIndex != -1 && CrossIndex != edit->PreselectCross) { // if a cross line is hit std::stringstream ss; switch(CrossIndex){ case 0: ss << "RootPoint" ; break; case 1: ss << "H_Axis" ; break; case 2: ss << "V_Axis" ; break; } bool accepted = Gui::Selection().setPreselect(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,Point->getPoint()[0] ,Point->getPoint()[1] ,Point->getPoint()[2]); edit->blockedPreselection = !accepted; if (accepted) { if (CrossIndex == 0) setPreselectPoint(-1); else resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = CrossIndex; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true; } } else if (constrIndices.empty() == false && constrIndices != edit->PreselectConstraintSet) { // if a constraint is hit bool accepted = true; for(std::set<int>::iterator it = constrIndices.begin(); it != constrIndices.end(); ++it) { std::string constraintName(Sketcher::PropertyConstraintList::getConstraintName(*it)); accepted &= Gui::Selection().setPreselect(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,constraintName.c_str() ,Point->getPoint()[0] ,Point->getPoint()[1] ,Point->getPoint()[2]); edit->blockedPreselection = !accepted; //TODO: Should we clear preselections that went through, if one fails? } if (accepted) { resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet = constrIndices; if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true;//Preselection changed } } else if ((PtIndex == -1 && GeoIndex == -1 && CrossIndex == -1 && constrIndices.empty()) && (edit->PreselectPoint != -1 || edit->PreselectCurve != -1 || edit->PreselectCross != -1 || edit->PreselectConstraintSet.empty() != true || edit->blockedPreselection)) { // we have just left a preselection resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); edit->blockedPreselection = false; if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true; } Gui::Selection().setPreselectCoord(Point->getPoint()[0] ,Point->getPoint()[1] ,Point->getPoint()[2]); // if(Point) } else if (edit->PreselectCurve != -1 || edit->PreselectPoint != -1 || edit->PreselectConstraintSet.empty() != true || edit->PreselectCross != -1 || edit->blockedPreselection) { resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); edit->blockedPreselection = false; if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true; } return false; } SbVec3s ViewProviderSketch::getDisplayedSize(const SoImage *iconPtr) const { #if (COIN_MAJOR_VERSION >= 3) SbVec3s iconSize = iconPtr->image.getValue().getSize(); #else SbVec2s size; int nc; const unsigned char * bytes = iconPtr->image.getValue(size, nc); SbImage img (bytes, size, nc); SbVec3s iconSize = img.getSize(); #endif if (iconPtr->width.getValue() != -1) iconSize[0] = iconPtr->width.getValue(); if (iconPtr->height.getValue() != -1) iconSize[1] = iconPtr->height.getValue(); return iconSize; } void ViewProviderSketch::centerSelection() { Gui::MDIView *mdi = this->getActiveView(); Gui::View3DInventor *view = qobject_cast<Gui::View3DInventor*>(mdi); if (!view || !edit) return; SoGroup* group = new SoGroup(); group->ref(); for (int i=0; i < edit->constrGroup->getNumChildren(); i++) { if (edit->SelConstraintSet.find(i) != edit->SelConstraintSet.end()) { SoSeparator *sep = dynamic_cast<SoSeparator *>(edit->constrGroup->getChild(i)); group->addChild(sep); } } Gui::View3DInventorViewer* viewer = view->getViewer(); SoGetBoundingBoxAction action(viewer->getSoRenderManager()->getViewportRegion()); action.apply(group); group->unref(); SbBox3f box = action.getBoundingBox(); if (!box.isEmpty()) { SoCamera* camera = viewer->getSoRenderManager()->getCamera(); SbVec3f direction; camera->orientation.getValue().multVec(SbVec3f(0, 0, 1), direction); SbVec3f box_cnt = box.getCenter(); SbVec3f cam_pos = box_cnt + camera->focalDistance.getValue() * direction; camera->position.setValue(cam_pos); } } void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s &endPos, const Gui::View3DInventorViewer *viewer) { std::vector<SbVec2s> corners0; corners0.push_back(startPos); corners0.push_back(endPos); std::vector<SbVec2f> corners = viewer->getGLPolygon(corners0); // all calculations with polygon and proj are in dimensionless [0 1] screen coordinates Base::Polygon2D polygon; polygon.Add(Base::Vector2D(corners[0].getValue()[0], corners[0].getValue()[1])); polygon.Add(Base::Vector2D(corners[0].getValue()[0], corners[1].getValue()[1])); polygon.Add(Base::Vector2D(corners[1].getValue()[0], corners[1].getValue()[1])); polygon.Add(Base::Vector2D(corners[1].getValue()[0], corners[0].getValue()[1])); Gui::ViewVolumeProjection proj(viewer->getSoRenderManager()->getCamera()->getViewVolume()); Sketcher::SketchObject *sketchObject = getSketchObject(); App::Document *doc = sketchObject->getDocument(); Base::Placement Plm = sketchObject->Placement.getValue(); int intGeoCount = sketchObject->getHighestCurveIndex() + 1; int extGeoCount = sketchObject->getExternalGeometryCount(); const std::vector<Part::Geometry *> geomlist = sketchObject->getCompleteGeometry(); // without memory allocation assert(int(geomlist.size()) == extGeoCount + intGeoCount); assert(int(geomlist.size()) >= 2); Base::Vector3d pnt0, pnt1, pnt2, pnt; int VertexId = -1; // the loop below should be in sync with the main loop in ViewProviderSketch::draw // so that the vertex indices are calculated correctly int GeoId = 0; for (std::vector<Part::Geometry *>::const_iterator it = geomlist.begin(); it != geomlist.end()-2; ++it, ++GeoId) { if (GeoId >= intGeoCount) GeoId = -extGeoCount; if ((*it)->getTypeId() == Part::GeomPoint::getClassTypeId()) { // ----- Check if single point lies inside box selection -----/ const Part::GeomPoint *point = dynamic_cast<const Part::GeomPoint *>(*it); Plm.multVec(point->getPoint(), pnt0); pnt0 = proj(pnt0); VertexId += 1; if (polygon.Contains(Base::Vector2D(pnt0.x, pnt0.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } } else if ((*it)->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { // ----- Check if line segment lies inside box selection -----/ const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(*it); Plm.multVec(lineSeg->getStartPoint(), pnt1); Plm.multVec(lineSeg->getEndPoint(), pnt2); pnt1 = proj(pnt1); pnt2 = proj(pnt2); VertexId += 2; bool pnt1Inside = polygon.Contains(Base::Vector2D(pnt1.x, pnt1.y)); bool pnt2Inside = polygon.Contains(Base::Vector2D(pnt2.x, pnt2.y)); if (pnt1Inside) { std::stringstream ss; ss << "Vertex" << VertexId; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (pnt2Inside) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (pnt1Inside && pnt2Inside) { std::stringstream ss; ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } } else if ((*it)->getTypeId() == Part::GeomCircle::getClassTypeId()) { // ----- Check if circle lies inside box selection -----/ const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(*it); pnt0 = circle->getCenter(); VertexId += 1; Plm.multVec(pnt0, pnt0); pnt0 = proj(pnt0); if (polygon.Contains(Base::Vector2D(pnt0.x, pnt0.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); int countSegments = 12; float segment = float(2 * M_PI) / countSegments; // circumscribed polygon radius float radius = float(circle->getRadius()) / cos(segment/2); bool bpolyInside = true; pnt0 = circle->getCenter(); float angle = 0.f; for (int i = 0; i < countSegments; ++i, angle += segment) { pnt = Base::Vector3d(pnt0.x + radius * cos(angle), pnt0.y + radius * sin(angle), 0.f); Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2D(pnt.x, pnt.y))) { bpolyInside = false; break; } } if (bpolyInside) { ss.clear(); ss.str(""); ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(),ss.str().c_str()); } } } else if ((*it)->getTypeId() == Part::GeomEllipse::getClassTypeId()) { // ----- Check if circle lies inside box selection -----/ const Part::GeomEllipse *ellipse = dynamic_cast<const Part::GeomEllipse *>(*it); pnt0 = ellipse->getCenter(); VertexId += 1; Plm.multVec(pnt0, pnt0); pnt0 = proj(pnt0); if (polygon.Contains(Base::Vector2D(pnt0.x, pnt0.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); int countSegments = 12; double segment = (2 * M_PI) / countSegments; // circumscribed polygon radius double a = (ellipse->getMajorRadius()) / cos(segment/2); double b = (ellipse->getMinorRadius()) / cos(segment/2); Base::Vector3d majdir = ellipse->getMajorAxisDir(); Base::Vector3d mindir = Base::Vector3d(-majdir.y, majdir.x, 0.0); bool bpolyInside = true; pnt0 = ellipse->getCenter(); double angle = 0.; for (int i = 0; i < countSegments; ++i, angle += segment) { pnt = pnt0 + (cos(angle)*a)*majdir + sin(angle)*b*mindir; Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2D(pnt.x, pnt.y))) { bpolyInside = false; break; } } if (bpolyInside) { ss.clear(); ss.str(""); ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(),ss.str().c_str()); } } } else if ((*it)->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { // Check if arc lies inside box selection const Part::GeomArcOfCircle *aoc = dynamic_cast<const Part::GeomArcOfCircle *>(*it); pnt0 = aoc->getStartPoint(/*emulateCCW=*/true); pnt1 = aoc->getEndPoint(/*emulateCCW=*/true); pnt2 = aoc->getCenter(); VertexId += 3; Plm.multVec(pnt0, pnt0); Plm.multVec(pnt1, pnt1); Plm.multVec(pnt2, pnt2); pnt0 = proj(pnt0); pnt1 = proj(pnt1); pnt2 = proj(pnt2); bool pnt0Inside = polygon.Contains(Base::Vector2D(pnt0.x, pnt0.y)); if (pnt0Inside) { std::stringstream ss; ss << "Vertex" << VertexId - 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } bool pnt1Inside = polygon.Contains(Base::Vector2D(pnt1.x, pnt1.y)); if (pnt1Inside) { std::stringstream ss; ss << "Vertex" << VertexId; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (polygon.Contains(Base::Vector2D(pnt2.x, pnt2.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (pnt0Inside && pnt1Inside) { double startangle, endangle; aoc->getRange(startangle, endangle, /*emulateCCW=*/true); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(2, int(12.0 * range / (2 * M_PI))); float segment = float(range) / countSegments; // circumscribed polygon radius float radius = float(aoc->getRadius()) / cos(segment/2); bool bpolyInside = true; pnt0 = aoc->getCenter(); float angle = float(startangle) + segment/2; for (int i = 0; i < countSegments; ++i, angle += segment) { pnt = Base::Vector3d(pnt0.x + radius * cos(angle), pnt0.y + radius * sin(angle), 0.f); Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2D(pnt.x, pnt.y))) { bpolyInside = false; break; } } if (bpolyInside) { std::stringstream ss; ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } } } else if ((*it)->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { // Check if arc lies inside box selection const Part::GeomArcOfEllipse *aoe = dynamic_cast<const Part::GeomArcOfEllipse *>(*it); pnt0 = aoe->getStartPoint(/*emulateCCW=*/true); pnt1 = aoe->getEndPoint(/*emulateCCW=*/true); pnt2 = aoe->getCenter(); VertexId += 3; Plm.multVec(pnt0, pnt0); Plm.multVec(pnt1, pnt1); Plm.multVec(pnt2, pnt2); pnt0 = proj(pnt0); pnt1 = proj(pnt1); pnt2 = proj(pnt2); bool pnt0Inside = polygon.Contains(Base::Vector2D(pnt0.x, pnt0.y)); if (pnt0Inside) { std::stringstream ss; ss << "Vertex" << VertexId - 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } bool pnt1Inside = polygon.Contains(Base::Vector2D(pnt1.x, pnt1.y)); if (pnt1Inside) { std::stringstream ss; ss << "Vertex" << VertexId; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (polygon.Contains(Base::Vector2D(pnt2.x, pnt2.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (pnt0Inside && pnt1Inside) { double startangle, endangle; aoe->getRange(startangle, endangle, /*emulateCCW=*/true); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(2, int(12.0 * range / (2 * M_PI))); double segment = (range) / countSegments; // circumscribed polygon radius double a = (aoe->getMajorRadius()) / cos(segment/2); double b = (aoe->getMinorRadius()) / cos(segment/2); Base::Vector3d majdir = aoe->getMajorAxisDir(); Base::Vector3d mindir = Base::Vector3d(-majdir.y, majdir.x, 0.0); bool bpolyInside = true; pnt0 = aoe->getCenter(); double angle = (startangle) + segment/2; for (int i = 0; i < countSegments; ++i, angle += segment) { pnt = pnt0 + cos(angle)*a*majdir + sin(angle)*b*mindir; Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2D(pnt.x, pnt.y))) { bpolyInside = false; break; } } if (bpolyInside) { std::stringstream ss; ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } } } else if ((*it)->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { const Part::GeomBSplineCurve *spline = dynamic_cast<const Part::GeomBSplineCurve *>(*it); std::vector<Base::Vector3d> poles = spline->getPoles(); VertexId += poles.size(); // TODO } } pnt0 = proj(Plm.getPosition()); if (polygon.Contains(Base::Vector2D(pnt0.x, pnt0.y))) Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), "RootPoint"); } void ViewProviderSketch::updateColor(void) { assert(edit); //Base::Console().Log("Draw preseletion\n"); int PtNum = edit->PointsMaterials->diffuseColor.getNum(); SbColor *pcolor = edit->PointsMaterials->diffuseColor.startEditing(); int CurvNum = edit->CurvesMaterials->diffuseColor.getNum(); SbColor *color = edit->CurvesMaterials->diffuseColor.startEditing(); SbColor *crosscolor = edit->RootCrossMaterials->diffuseColor.startEditing(); SbVec3f *verts = edit->CurvesCoordinate->point.startEditing(); //int32_t *index = edit->CurveSet->numVertices.startEditing(); // colors of the point set if (edit->FullyConstrained) { for (int i=0; i < PtNum; i++) pcolor[i] = FullyConstrainedColor; } else { for (int i=0; i < PtNum; i++) pcolor[i] = VertexColor; } if (edit->PreselectCross == 0) { pcolor[0] = PreselectColor; } else if (edit->PreselectPoint != -1) { if (edit->PreselectPoint + 1 < PtNum) pcolor[edit->PreselectPoint + 1] = PreselectColor; } for (std::set<int>::iterator it = edit->SelPointSet.begin(); it != edit->SelPointSet.end(); ++it) { if (*it < PtNum) { pcolor[*it] = (*it==(edit->PreselectPoint + 1) && (edit->PreselectPoint != -1)) ? PreselectSelectedColor : SelectColor; } } // colors of the curves //int intGeoCount = getSketchObject()->getHighestCurveIndex() + 1; //int extGeoCount = getSketchObject()->getExternalGeometryCount(); float x,y,z; int j=0; // vertexindex for (int i=0; i < CurvNum; i++) { int GeoId = edit->CurvIdToGeoId[i]; // CurvId has several vertex a ssociated to 1 material //edit->CurveSet->numVertices => [i] indicates number of vertex for line i. int indexes = (edit->CurveSet->numVertices[i]); bool selected = (edit->SelCurvSet.find(GeoId) != edit->SelCurvSet.end()); bool preselected = (edit->PreselectCurve == GeoId); if (selected && preselected) { color[i] = PreselectSelectedColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zHighLine); } } else if (selected){ color[i] = SelectColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zHighLine); } } else if (preselected){ color[i] = PreselectColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zHighLine); } } else if (GeoId < -2) { // external Geometry color[i] = CurveExternalColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zConstr); } } else if (getSketchObject()->getGeometry(GeoId)->Construction) { color[i] = CurveDraftColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zLines); } } else if (edit->FullyConstrained) { color[i] = FullyConstrainedColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zLines); } } else { color[i] = CurveColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zLines); } } } // colors of the cross if (edit->SelCurvSet.find(-1) != edit->SelCurvSet.end()) crosscolor[0] = SelectColor; else if (edit->PreselectCross == 1) crosscolor[0] = PreselectColor; else crosscolor[0] = CrossColorH; if (edit->SelCurvSet.find(-2) != edit->SelCurvSet.end()) crosscolor[1] = SelectColor; else if (edit->PreselectCross == 2) crosscolor[1] = PreselectColor; else crosscolor[1] = CrossColorV; // colors of the constraints for (int i=0; i < edit->constrGroup->getNumChildren(); i++) { SoSeparator *s = dynamic_cast<SoSeparator *>(edit->constrGroup->getChild(i)); // Check Constraint Type Sketcher::Constraint* constraint = getSketchObject()->Constraints.getValues()[i]; ConstraintType type = constraint->Type; bool hasDatumLabel = (type == Sketcher::Angle || type == Sketcher::Radius || type == Sketcher::Symmetric || type == Sketcher::Distance || type == Sketcher::DistanceX || type == Sketcher::DistanceY); // Non DatumLabel Nodes will have a material excluding coincident bool hasMaterial = false; SoMaterial *m = 0; if (!hasDatumLabel && type != Sketcher::Coincident && type != Sketcher::InternalAlignment) { hasMaterial = true; m = dynamic_cast<SoMaterial *>(s->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); } if (edit->SelConstraintSet.find(i) != edit->SelConstraintSet.end()) { if (hasDatumLabel) { SoDatumLabel *l = dynamic_cast<SoDatumLabel *>(s->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); l->textColor = SelectColor; } else if (hasMaterial) { m->diffuseColor = SelectColor; } else if (type == Sketcher::Coincident) { int index; index = getSketchObject()->getSolvedSketch().getPointId(constraint->First, constraint->FirstPos) + 1; if (index >= 0 && index < PtNum) pcolor[index] = SelectColor; index = getSketchObject()->getSolvedSketch().getPointId(constraint->Second, constraint->SecondPos) + 1; if (index >= 0 && index < PtNum) pcolor[index] = SelectColor; } else if (type == Sketcher::InternalAlignment) { switch(constraint->AlignmentType) { case EllipseMajorDiameter: case EllipseMinorDiameter: { // color line int CurvNum = edit->CurvesMaterials->diffuseColor.getNum(); for (int i=0; i < CurvNum; i++) { int cGeoId = edit->CurvIdToGeoId[i]; if(cGeoId == constraint->First) { color[i] = SelectColor; break; } } } break; case EllipseFocus1: case EllipseFocus2: { int index = getSketchObject()->getSolvedSketch().getPointId(constraint->First, constraint->FirstPos) + 1; if (index >= 0 && index < PtNum) pcolor[index] = SelectColor; } break; default: break; } } } else if (edit->PreselectConstraintSet.count(i)) { if (hasDatumLabel) { SoDatumLabel *l = dynamic_cast<SoDatumLabel *>(s->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); l->textColor = PreselectColor; } else if (hasMaterial) { m->diffuseColor = PreselectColor; } } else { if (hasDatumLabel) { SoDatumLabel *l = dynamic_cast<SoDatumLabel *>(s->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); l->textColor = constraint->isDriving?ConstrDimColor:NonDrivingConstrDimColor; } else if (hasMaterial) { m->diffuseColor = constraint->isDriving?ConstrDimColor:NonDrivingConstrDimColor; } } } // end editing edit->CurvesMaterials->diffuseColor.finishEditing(); edit->PointsMaterials->diffuseColor.finishEditing(); edit->RootCrossMaterials->diffuseColor.finishEditing(); edit->CurvesCoordinate->point.finishEditing(); edit->CurveSet->numVertices.finishEditing(); } bool ViewProviderSketch::isPointOnSketch(const SoPickedPoint *pp) const { // checks if we picked a point on the sketch or any other nodes like the grid SoPath *path = pp->getPath(); return path->containsNode(edit->EditRoot); } bool ViewProviderSketch::doubleClicked(void) { Gui::Application::Instance->activeDocument()->setEdit(this); return true; } QString ViewProviderSketch::iconTypeFromConstraint(Constraint *constraint) { /*! TODO: Consider pushing this functionality up into Constraint */ switch(constraint->Type) { case Horizontal: return QString::fromLatin1("small/Constraint_Horizontal_sm"); case Vertical: return QString::fromLatin1("small/Constraint_Vertical_sm"); case PointOnObject: return QString::fromLatin1("small/Constraint_PointOnObject_sm"); case Tangent: return QString::fromLatin1("small/Constraint_Tangent_sm"); case Parallel: return QString::fromLatin1("small/Constraint_Parallel_sm"); case Perpendicular: return QString::fromLatin1("small/Constraint_Perpendicular_sm"); case Equal: return QString::fromLatin1("small/Constraint_EqualLength_sm"); case Symmetric: return QString::fromLatin1("small/Constraint_Symmetric_sm"); case SnellsLaw: return QString::fromLatin1("small/Constraint_SnellsLaw_sm"); default: return QString(); } } void ViewProviderSketch::sendConstraintIconToCoin(const QImage &icon, SoImage *soImagePtr) { SoSFImage icondata = SoSFImage(); Gui::BitmapFactory().convert(icon, icondata); SbVec2s iconSize(icon.width(), icon.height()); int four = 4; soImagePtr->image.setValue(iconSize, 4, icondata.getValue(iconSize, four)); //Set Image Alignment to Center soImagePtr->vertAlignment = SoImage::HALF; soImagePtr->horAlignment = SoImage::CENTER; } void ViewProviderSketch::clearCoinImage(SoImage *soImagePtr) { soImagePtr->setToDefaults(); } QColor ViewProviderSketch::constrColor(int constraintId) { static QColor constrIcoColor((int)(ConstrIcoColor [0] * 255.0f), (int)(ConstrIcoColor[1] * 255.0f), (int)(ConstrIcoColor[2] * 255.0f)); static QColor nonDrivingConstrIcoColor((int)(NonDrivingConstrDimColor[0] * 255.0f), (int)(NonDrivingConstrDimColor[1] * 255.0f), (int)(NonDrivingConstrDimColor[2] * 255.0f)); static QColor constrIconSelColor ((int)(SelectColor[0] * 255.0f), (int)(SelectColor[1] * 255.0f), (int)(SelectColor[2] * 255.0f)); static QColor constrIconPreselColor ((int)(PreselectColor[0] * 255.0f), (int)(PreselectColor[1] * 255.0f), (int)(PreselectColor[2] * 255.0f)); const std::vector<Sketcher::Constraint *> &constraints = getSketchObject()->Constraints.getValues(); if (edit->PreselectConstraintSet.count(constraintId)) return constrIconPreselColor; else if (edit->SelConstraintSet.find(constraintId) != edit->SelConstraintSet.end()) return constrIconSelColor; else if(!constraints[constraintId]->isDriving) return nonDrivingConstrIcoColor; else return constrIcoColor; } int ViewProviderSketch::constrColorPriority(int constraintId) { if (edit->PreselectConstraintSet.count(constraintId)) return 3; else if (edit->SelConstraintSet.find(constraintId) != edit->SelConstraintSet.end()) return 2; else return 1; } // public function that triggers drawing of most constraint icons void ViewProviderSketch::drawConstraintIcons() { const std::vector<Sketcher::Constraint *> &constraints = getSketchObject()->Constraints.getValues(); int constrId = 0; std::vector<constrIconQueueItem> iconQueue; for (std::vector<Sketcher::Constraint *>::const_iterator it=constraints.begin(); it != constraints.end(); ++it, ++constrId) { // Check if Icon Should be created bool multipleIcons = false; QString icoType = iconTypeFromConstraint(*it); if(icoType.isEmpty()) continue; switch((*it)->Type) { case Tangent: { // second icon is available only for colinear line segments const Part::Geometry *geo1 = getSketchObject()->getGeometry((*it)->First); const Part::Geometry *geo2 = getSketchObject()->getGeometry((*it)->Second); if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { multipleIcons = true; } } break; case Parallel: multipleIcons = true; break; case Perpendicular: // second icon is available only when there is no common point if ((*it)->FirstPos == Sketcher::none && (*it)->Third == Constraint::GeoUndef) multipleIcons = true; break; case Equal: multipleIcons = true; break; default: break; } // Find the Constraint Icon SoImage Node SoSeparator *sep = static_cast<SoSeparator *>(edit->constrGroup->getChild(constrId)); SbVec3f absPos; // Somewhat hacky - we use SoZoomTranslations for most types of icon, // but symmetry icons use SoTranslations... SoTranslation *translationPtr = static_cast<SoTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION)); if(dynamic_cast<SoZoomTranslation *>(translationPtr)) absPos = static_cast<SoZoomTranslation *>(translationPtr)->abPos.getValue(); else absPos = translationPtr->translation.getValue(); SoImage *coinIconPtr = dynamic_cast<SoImage *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON)); SoInfo *infoPtr = static_cast<SoInfo *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID)); constrIconQueueItem thisIcon; thisIcon.type = icoType; thisIcon.constraintId = constrId; thisIcon.position = absPos; thisIcon.destination = coinIconPtr; thisIcon.infoPtr = infoPtr; if ((*it)->Type==Symmetric) { Base::Vector3d startingpoint = getSketchObject()->getPoint((*it)->First,(*it)->FirstPos); Base::Vector3d endpoint = getSketchObject()->getPoint((*it)->Second,(*it)->SecondPos); double x0,y0,x1,y1; SbVec3f pos0(startingpoint.x,startingpoint.y,startingpoint.z); SbVec3f pos1(endpoint.x,endpoint.y,endpoint.z); Gui::MDIView *mdi = this->getEditingView(); if (!(mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId()))) return; Gui::View3DInventorViewer *viewer = static_cast<Gui::View3DInventor *>(mdi)->getViewer(); SoCamera* pCam = viewer->getSoRenderManager()->getCamera(); if (!pCam) return; try { SbViewVolume vol = pCam->getViewVolume(); getCoordsOnSketchPlane(x0,y0,pos0,vol.getProjectionDirection()); getCoordsOnSketchPlane(x1,y1,pos1,vol.getProjectionDirection()); thisIcon.iconRotation = -atan2((y1-y0),(x1-x0))*180/M_PI; } catch (const Base::DivisionByZeroError&) { thisIcon.iconRotation = 0; } } else { thisIcon.iconRotation = 0; } if (multipleIcons) { if((*it)->Name.empty()) thisIcon.label = QString::number(constrId + 1); else thisIcon.label = QString::fromLatin1((*it)->Name.c_str()); iconQueue.push_back(thisIcon); // Note that the second translation is meant to be applied after the first. // So, to get the position of the second icon, we add the two translations together // // See note ~30 lines up. translationPtr = static_cast<SoTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION)); if(dynamic_cast<SoZoomTranslation *>(translationPtr)) thisIcon.position += static_cast<SoZoomTranslation *>(translationPtr)->abPos.getValue(); else thisIcon.position += translationPtr->translation.getValue(); thisIcon.destination = dynamic_cast<SoImage *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_ICON)); thisIcon.infoPtr = static_cast<SoInfo *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID)); } else if ((*it)->Name.empty()) thisIcon.label = QString(); else thisIcon.label = QString::fromLatin1((*it)->Name.c_str()); iconQueue.push_back(thisIcon); } combineConstraintIcons(iconQueue); } void ViewProviderSketch::combineConstraintIcons(IconQueue iconQueue) { // getScaleFactor gives us a ratio of pixels per some kind of real units // (Translation: this number is somewhat made-up.) float maxDistSquared = pow(0.05 * getScaleFactor(), 2); // There's room for optimisation here; we could reuse the combined icons... edit->combinedConstrBoxes.clear(); while(!iconQueue.empty()) { // A group starts with an item popped off the back of our initial queue IconQueue thisGroup; thisGroup.push_back(iconQueue.back()); ViewProviderSketch::constrIconQueueItem init = iconQueue.back(); iconQueue.pop_back(); // we group only icons not being Symmetry icons, because we want those on the line if(init.type != QString::fromLatin1("small/Constraint_Symmetric_sm")){ IconQueue::iterator i = iconQueue.begin(); while(i != iconQueue.end()) { bool addedToGroup = false; for(IconQueue::iterator j = thisGroup.begin(); j != thisGroup.end(); ++j) if(i->position.equals(j->position, maxDistSquared) && (*i).type != QString::fromLatin1("small/Constraint_Symmetric_sm")) { // Found an icon in iconQueue that's close enough to // a member of thisGroup, so move it into thisGroup thisGroup.push_back(*i); i = iconQueue.erase(i); addedToGroup = true; break; } if(addedToGroup) { if(i == iconQueue.end()) // We just got the last icon out of iconQueue break; else // Start looking through the iconQueue again, in case // we have an icon that's now close enough to thisGroup i = iconQueue.begin(); } else ++i; } } if(thisGroup.size() == 1) { drawTypicalConstraintIcon(thisGroup[0]); } else { drawMergedConstraintIcons(thisGroup); } } } void ViewProviderSketch::drawMergedConstraintIcons(IconQueue iconQueue) { SbVec3f avPos(0, 0, 0); for(IconQueue::iterator i = iconQueue.begin(); i != iconQueue.end(); ++i) { clearCoinImage(i->destination); avPos = avPos + i->position; } avPos = avPos/iconQueue.size(); QImage compositeIcon; float closest = FLT_MAX; // Closest distance between avPos and any icon SoImage *thisDest = 0; SoInfo *thisInfo = 0; // Tracks all constraint IDs that are combined into this icon QString idString; int lastVPad; QStringList labels; std::vector<int> ids; QString thisType; QColor iconColor; QList<QColor> labelColors; int maxColorPriority; double iconRotation; ConstrIconBBVec boundingBoxes; while(!iconQueue.empty()) { IconQueue::iterator i = iconQueue.begin(); labels.clear(); labels.append(i->label); ids.clear(); ids.push_back(i->constraintId); thisType = i->type; iconColor = constrColor(i->constraintId); labelColors.clear(); labelColors.append(iconColor); iconRotation= i->iconRotation; maxColorPriority = constrColorPriority(i->constraintId); if(idString.length()) idString.append(QString::fromLatin1(",")); idString.append(QString::number(i->constraintId)); if((avPos - i->position).length() < closest) { thisDest = i->destination; thisInfo = i->infoPtr; closest = (avPos - i->position).length(); } i = iconQueue.erase(i); while(i != iconQueue.end()) { if(i->type != thisType) { ++i; continue; } if((avPos - i->position).length() < closest) { thisDest = i->destination; thisInfo = i->infoPtr; closest = (avPos - i->position).length(); } labels.append(i->label); ids.push_back(i->constraintId); labelColors.append(constrColor(i->constraintId)); if(constrColorPriority(i->constraintId) > maxColorPriority) { maxColorPriority = constrColorPriority(i->constraintId); iconColor= constrColor(i->constraintId); } idString.append(QString::fromLatin1(",") + QString::number(i->constraintId)); i = iconQueue.erase(i); } // To be inserted into edit->combinedConstBoxes std::vector<QRect> boundingBoxesVec; int oldHeight = 0; // Render the icon here. if(compositeIcon.isNull()) { compositeIcon = renderConstrIcon(thisType, iconColor, labels, labelColors, iconRotation, &boundingBoxesVec, &lastVPad); } else { int thisVPad; QImage partialIcon = renderConstrIcon(thisType, iconColor, labels, labelColors, iconRotation, &boundingBoxesVec, &thisVPad); // Stack vertically for now. Down the road, it might make sense // to figure out the best orientation automatically. oldHeight = compositeIcon.height(); // This is overkill for the currently used (20 July 2014) font, // since it always seems to have the same vertical pad, but this // might not always be the case. The 3 pixel buffer might need // to vary depending on font size too... oldHeight -= std::max(lastVPad - 3, 0); compositeIcon = compositeIcon.copy(0, 0, std::max(partialIcon.width(), compositeIcon.width()), partialIcon.height() + compositeIcon.height()); QPainter qp(&compositeIcon); qp.drawImage(0, oldHeight, partialIcon); lastVPad = thisVPad; } // Add bounding boxes for the icon we just rendered to boundingBoxes std::vector<int>::iterator id = ids.begin(); std::set<int> nextIds; for(std::vector<QRect>::iterator bb = boundingBoxesVec.begin(); bb != boundingBoxesVec.end(); ++bb) { nextIds.clear(); if(bb == boundingBoxesVec.begin()) { // The first bounding box is for the icon at left, so assign // all IDs for that type of constraint to the icon. for(std::vector<int>::iterator j = ids.begin(); j != ids.end(); ++j) nextIds.insert(*j); } else nextIds.insert(*(id++)); ConstrIconBB newBB(bb->adjusted(0, oldHeight, 0, oldHeight), nextIds); boundingBoxes.push_back(newBB); } } edit->combinedConstrBoxes[idString] = boundingBoxes; thisInfo->string.setValue(idString.toLatin1().data()); sendConstraintIconToCoin(compositeIcon, thisDest); } /// Note: labels, labelColors, and boundignBoxes are all /// assumed to be the same length. QImage ViewProviderSketch::renderConstrIcon(const QString &type, const QColor &iconColor, const QStringList &labels, const QList<QColor> &labelColors, double iconRotation, std::vector<QRect> *boundingBoxes, int *vPad) { // Constants to help create constraint icons QString joinStr = QString::fromLatin1(", "); QImage icon = Gui::BitmapFactory().pixmap(type.toLatin1()).toImage(); QFont font = QApplication::font(); font.setPixelSize(11); font.setBold(true); QFontMetrics qfm = QFontMetrics(font); int labelWidth = qfm.boundingRect(labels.join(joinStr)).width(); // See Qt docs on qRect::bottom() for explanation of the +1 int pxBelowBase = qfm.boundingRect(labels.join(joinStr)).bottom() + 1; if(vPad) *vPad = pxBelowBase; QTransform rotation; rotation.rotate(iconRotation); QImage roticon = icon.transformed(rotation); QImage image = roticon.copy(0, 0, roticon.width() + labelWidth, roticon.height() + pxBelowBase); // Make a bounding box for the icon if(boundingBoxes) boundingBoxes->push_back(QRect(0, 0, roticon.width(), roticon.height())); // Render the Icons QPainter qp(&image); qp.setCompositionMode(QPainter::CompositionMode_SourceIn); qp.fillRect(roticon.rect(), iconColor); // Render constraint label if necessary if (!labels.join(QString()).isEmpty()) { qp.setCompositionMode(QPainter::CompositionMode_SourceOver); qp.setFont(font); int cursorOffset = 0; //In Python: "for label, color in zip(labels, labelColors):" QStringList::const_iterator labelItr; QString labelStr; QList<QColor>::const_iterator colorItr; QRect labelBB; for(labelItr = labels.begin(), colorItr = labelColors.begin(); labelItr != labels.end() && colorItr != labelColors.end(); ++labelItr, ++colorItr) { qp.setPen(*colorItr); if(labelItr + 1 == labels.end()) // if this is the last label labelStr = *labelItr; else labelStr = *labelItr + joinStr; // Note: text can sometimes draw to the left of the starting // position, eg italic fonts. Check QFontMetrics // documentation for more info, but be mindful if the // icon.width() is ever very small (or removed). qp.drawText(icon.width() + cursorOffset, icon.height(), labelStr); if(boundingBoxes) { labelBB = qfm.boundingRect(labelStr); labelBB.moveTo(icon.width() + cursorOffset, icon.height() - qfm.height() + pxBelowBase); boundingBoxes->push_back(labelBB); } cursorOffset += qfm.width(labelStr); } } return image; } void ViewProviderSketch::drawTypicalConstraintIcon(const constrIconQueueItem &i) { QColor color = constrColor(i.constraintId); QImage image = renderConstrIcon(i.type, color, QStringList(i.label), QList<QColor>() << color, i.iconRotation); i.infoPtr->string.setValue(QString::number(i.constraintId).toLatin1().data()); sendConstraintIconToCoin(image, i.destination); } float ViewProviderSketch::getScaleFactor() { Gui::MDIView *mdi = this->getEditingView(); if (mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) { Gui::View3DInventorViewer *viewer = static_cast<Gui::View3DInventor *>(mdi)->getViewer(); return viewer->getSoRenderManager()->getCamera()->getViewVolume(viewer->getSoRenderManager()->getCamera()->aspectRatio.getValue()).getWorldToScreenScale(SbVec3f(0.f, 0.f, 0.f), 0.1f) / 3; } else { return 1.f; } } void ViewProviderSketch::draw(bool temp) { assert(edit); // Render Geometry =================================================== std::vector<Base::Vector3d> Coords; std::vector<Base::Vector3d> Points; std::vector<unsigned int> Index; int intGeoCount = getSketchObject()->getHighestCurveIndex() + 1; int extGeoCount = getSketchObject()->getExternalGeometryCount(); const std::vector<Part::Geometry *> *geomlist; std::vector<Part::Geometry *> tempGeo; if (temp) tempGeo = getSketchObject()->getSolvedSketch().extractGeometry(true, true); // with memory allocation else tempGeo = getSketchObject()->getCompleteGeometry(); // without memory allocation geomlist = &tempGeo; assert(int(geomlist->size()) == extGeoCount + intGeoCount); assert(int(geomlist->size()) >= 2); edit->CurvIdToGeoId.clear(); int GeoId = 0; // RootPoint Points.push_back(Base::Vector3d(0.,0.,0.)); for (std::vector<Part::Geometry *>::const_iterator it = geomlist->begin(); it != geomlist->end()-2; ++it, GeoId++) { if (GeoId >= intGeoCount) GeoId = -extGeoCount; if ((*it)->getTypeId() == Part::GeomPoint::getClassTypeId()) { // add a point const Part::GeomPoint *point = dynamic_cast<const Part::GeomPoint *>(*it); Points.push_back(point->getPoint()); } else if ((*it)->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { // add a line const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(*it); // create the definition struct for that geom Coords.push_back(lineSeg->getStartPoint()); Coords.push_back(lineSeg->getEndPoint()); Points.push_back(lineSeg->getStartPoint()); Points.push_back(lineSeg->getEndPoint()); Index.push_back(2); edit->CurvIdToGeoId.push_back(GeoId); } else if ((*it)->getTypeId() == Part::GeomCircle::getClassTypeId()) { // add a circle const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(*it); Handle_Geom_Circle curve = Handle_Geom_Circle::DownCast(circle->handle()); int countSegments = 50; Base::Vector3d center = circle->getCenter(); double segment = (2 * M_PI) / countSegments; for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(i*segment); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } gp_Pnt pnt = curve->Value(0); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); Points.push_back(center); } else if ((*it)->getTypeId() == Part::GeomEllipse::getClassTypeId()) { // add an ellipse const Part::GeomEllipse *ellipse = dynamic_cast<const Part::GeomEllipse *>(*it); Handle_Geom_Ellipse curve = Handle_Geom_Ellipse::DownCast(ellipse->handle()); int countSegments = 50; Base::Vector3d center = ellipse->getCenter(); double segment = (2 * M_PI) / countSegments; for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(i*segment); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } gp_Pnt pnt = curve->Value(0); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); Points.push_back(center); } else if ((*it)->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { // add an arc const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(*it); Handle_Geom_TrimmedCurve curve = Handle_Geom_TrimmedCurve::DownCast(arc->handle()); double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/false); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(6, int(50.0 * range / (2 * M_PI))); double segment = range / countSegments; Base::Vector3d center = arc->getCenter(); Base::Vector3d start = arc->getStartPoint(/*emulateCCW=*/true); Base::Vector3d end = arc->getEndPoint(/*emulateCCW=*/true); for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(startangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); startangle += segment; } // end point gp_Pnt pnt = curve->Value(endangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); Points.push_back(start); Points.push_back(end); Points.push_back(center); } else if ((*it)->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { // add an arc const Part::GeomArcOfEllipse *arc = dynamic_cast<const Part::GeomArcOfEllipse *>(*it); Handle_Geom_TrimmedCurve curve = Handle_Geom_TrimmedCurve::DownCast(arc->handle()); double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/false); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(6, int(50.0 * range / (2 * M_PI))); double segment = range / countSegments; Base::Vector3d center = arc->getCenter(); Base::Vector3d start = arc->getStartPoint(/*emulateCCW=*/true); Base::Vector3d end = arc->getEndPoint(/*emulateCCW=*/true); for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(startangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); startangle += segment; } // end point gp_Pnt pnt = curve->Value(endangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); Points.push_back(start); Points.push_back(end); Points.push_back(center); } else if ((*it)->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { // add a bspline const Part::GeomBSplineCurve *spline = dynamic_cast<const Part::GeomBSplineCurve *>(*it); Handle_Geom_BSplineCurve curve = Handle_Geom_BSplineCurve::DownCast(spline->handle()); double first = curve->FirstParameter(); double last = curve->LastParameter(); if (first > last) // if arc is reversed std::swap(first, last); double range = last-first; int countSegments = 50; double segment = range / countSegments; for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(first); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); first += segment; } // end point gp_Pnt end = curve->Value(last); Coords.push_back(Base::Vector3d(end.X(), end.Y(), end.Z())); std::vector<Base::Vector3d> poles = spline->getPoles(); for (std::vector<Base::Vector3d>::iterator it = poles.begin(); it != poles.end(); ++it) { Points.push_back(*it); } Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); } else { } } edit->CurvesCoordinate->point.setNum(Coords.size()); edit->CurveSet->numVertices.setNum(Index.size()); edit->CurvesMaterials->diffuseColor.setNum(Index.size()); edit->PointsCoordinate->point.setNum(Points.size()); edit->PointsMaterials->diffuseColor.setNum(Points.size()); SbVec3f *verts = edit->CurvesCoordinate->point.startEditing(); int32_t *index = edit->CurveSet->numVertices.startEditing(); SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); int i=0; // setting up the line set for (std::vector<Base::Vector3d>::const_iterator it = Coords.begin(); it != Coords.end(); ++it,i++) verts[i].setValue(it->x,it->y,zLines); i=0; // setting up the indexes of the line set for (std::vector<unsigned int>::const_iterator it = Index.begin(); it != Index.end(); ++it,i++) index[i] = *it; i=0; // setting up the point set for (std::vector<Base::Vector3d>::const_iterator it = Points.begin(); it != Points.end(); ++it,i++) pverts[i].setValue(it->x,it->y,zPoints); edit->CurvesCoordinate->point.finishEditing(); edit->CurveSet->numVertices.finishEditing(); edit->PointsCoordinate->point.finishEditing(); // set cross coordinates edit->RootCrossSet->numVertices.set1Value(0,2); edit->RootCrossSet->numVertices.set1Value(1,2); float MiX = -exp(ceil(log(std::abs(MinX)))); MiX = std::min(MiX,(float)-exp(ceil(log(std::abs(0.1f*MaxX))))); float MaX = exp(ceil(log(std::abs(MaxX)))); MaX = std::max(MaX,(float)exp(ceil(log(std::abs(0.1f*MinX))))); float MiY = -exp(ceil(log(std::abs(MinY)))); MiY = std::min(MiY,(float)-exp(ceil(log(std::abs(0.1f*MaxY))))); float MaY = exp(ceil(log(std::abs(MaxY)))); MaY = std::max(MaY,(float)exp(ceil(log(std::abs(0.1f*MinY))))); edit->RootCrossCoordinate->point.set1Value(0,SbVec3f(MiX, 0.0f, zCross)); edit->RootCrossCoordinate->point.set1Value(1,SbVec3f(MaX, 0.0f, zCross)); edit->RootCrossCoordinate->point.set1Value(2,SbVec3f(0.0f, MiY, zCross)); edit->RootCrossCoordinate->point.set1Value(3,SbVec3f(0.0f, MaY, zCross)); // Render Constraints =================================================== const std::vector<Sketcher::Constraint *> &constrlist = getSketchObject()->Constraints.getValues(); // After an undo/redo it can happen that we have an empty geometry list but a non-empty constraint list // In this case just ignore the constraints. (See bug #0000421) if (geomlist->size() <= 2 && !constrlist.empty()) { rebuildConstraintsVisual(); return; } // reset point if the constraint type has changed Restart: // check if a new constraint arrived if (constrlist.size() != edit->vConstrType.size()) rebuildConstraintsVisual(); assert(int(constrlist.size()) == edit->constrGroup->getNumChildren()); assert(int(edit->vConstrType.size()) == edit->constrGroup->getNumChildren()); // go through the constraints and update the position i = 0; for (std::vector<Sketcher::Constraint *>::const_iterator it=constrlist.begin(); it != constrlist.end(); ++it, i++) { // check if the type has changed if ((*it)->Type != edit->vConstrType[i]) { // clearing the type vector will force a rebuild of the visual nodes edit->vConstrType.clear(); //TODO: The 'goto' here is unsafe as it can happen that we cause an endless loop (see bug #0001956). goto Restart; } try{//because calculateNormalAtPoint, used in there, can throw // root separator for this constraint SoSeparator *sep = dynamic_cast<SoSeparator *>(edit->constrGroup->getChild(i)); const Constraint *Constr = *it; // distinquish different constraint types to build up switch (Constr->Type) { case Horizontal: // write the new position of the Horizontal constraint Same as vertical position. case Vertical: // write the new position of the Vertical constraint { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); // get the geometry const Part::Geometry *geo = GeoById(*geomlist, Constr->First); // Vertical can only be a GeomLineSegment assert(geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()); const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo); // calculate the half distance between the start and endpoint Base::Vector3d midpos = ((lineSeg->getEndPoint()+lineSeg->getStartPoint())/2); //Get a set of vectors perpendicular and tangential to these Base::Vector3d dir = (lineSeg->getEndPoint()-lineSeg->getStartPoint()).Normalize(); Base::Vector3d norm(-dir.y,dir.x,0); Base::Vector3d relpos = seekConstraintPosition(midpos, norm, dir, 2.5, edit->constrGroup->getChild(i)); dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(midpos.x, midpos.y, zConstr); //Absolute Reference //Reference Position that is scaled according to zoom dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relpos.x, relpos.y, 0); } break; case Perpendicular: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); // get the geometry const Part::Geometry *geo1 = GeoById(*geomlist, Constr->First); const Part::Geometry *geo2 = GeoById(*geomlist, Constr->Second); Base::Vector3d midpos1, dir1, norm1; Base::Vector3d midpos2, dir2, norm2; bool twoIcons = false;//a very local flag. It's set to true to indicate that the second dir+norm are valid and should be used if (Constr->Third != Constraint::GeoUndef || //perpty via point Constr->FirstPos != Sketcher::none) { //endpoint-to-curve or endpoint-to-endpoint perpty int ptGeoId; Sketcher::PointPos ptPosId; do {//dummy loop to use break =) Maybe goto? ptGeoId = Constr->First; ptPosId = Constr->FirstPos; if (ptPosId != Sketcher::none) break; ptGeoId = Constr->Second; ptPosId = Constr->SecondPos; if (ptPosId != Sketcher::none) break; ptGeoId = Constr->Third; ptPosId = Constr->ThirdPos; if (ptPosId != Sketcher::none) break; assert(0);//no point found! } while (false); if (temp) midpos1 = getSketchObject()->getSolvedSketch().getPoint(ptGeoId, ptPosId); else midpos1 = getSketchObject()->getPoint(ptGeoId, ptPosId); norm1 = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->Second, midpos1.x, midpos1.y); norm1.Normalize(); dir1 = norm1; dir1.RotateZ(-M_PI/2.0); } else if (Constr->FirstPos == Sketcher::none) { if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg1 = dynamic_cast<const Part::GeomLineSegment *>(geo1); midpos1 = ((lineSeg1->getEndPoint()+lineSeg1->getStartPoint())/2); dir1 = (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()).Normalize(); norm1 = Base::Vector3d(-dir1.y,dir1.x,0.); } else if (geo1->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo1); double startangle, endangle, midangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); midangle = (startangle + endangle)/2; norm1 = Base::Vector3d(cos(midangle),sin(midangle),0); dir1 = Base::Vector3d(-norm1.y,norm1.x,0); midpos1 = arc->getCenter() + arc->getRadius() * norm1; } else if (geo1->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo1); norm1 = Base::Vector3d(cos(M_PI/4),sin(M_PI/4),0); dir1 = Base::Vector3d(-norm1.y,norm1.x,0); midpos1 = circle->getCenter() + circle->getRadius() * norm1; } else break; if (geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg2 = dynamic_cast<const Part::GeomLineSegment *>(geo2); midpos2 = ((lineSeg2->getEndPoint()+lineSeg2->getStartPoint())/2); dir2 = (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()).Normalize(); norm2 = Base::Vector3d(-dir2.y,dir2.x,0.); } else if (geo2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo2); double startangle, endangle, midangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); midangle = (startangle + endangle)/2; norm2 = Base::Vector3d(cos(midangle),sin(midangle),0); dir2 = Base::Vector3d(-norm2.y,norm2.x,0); midpos2 = arc->getCenter() + arc->getRadius() * norm2; } else if (geo2->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo2); norm2 = Base::Vector3d(cos(M_PI/4),sin(M_PI/4),0); dir2 = Base::Vector3d(-norm2.y,norm2.x,0); midpos2 = circle->getCenter() + circle->getRadius() * norm2; } else break; twoIcons = true; } Base::Vector3d relpos1 = seekConstraintPosition(midpos1, norm1, dir1, 2.5, edit->constrGroup->getChild(i)); dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(midpos1.x, midpos1.y, zConstr); dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relpos1.x, relpos1.y, 0); if (twoIcons) { Base::Vector3d relpos2 = seekConstraintPosition(midpos2, norm2, dir2, 2.5, edit->constrGroup->getChild(i)); Base::Vector3d secondPos = midpos2 - midpos1; dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->abPos = SbVec3f(secondPos.x, secondPos.y, zConstr); dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->translation = SbVec3f(relpos2.x -relpos1.x, relpos2.y -relpos1.y, 0); } } break; case Parallel: case Equal: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); // get the geometry const Part::Geometry *geo1 = GeoById(*geomlist, Constr->First); const Part::Geometry *geo2 = GeoById(*geomlist, Constr->Second); Base::Vector3d midpos1, dir1, norm1; Base::Vector3d midpos2, dir2, norm2; if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() || geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { if (Constr->Type == Equal) { double r1a=0,r1b=0,r2a=0,r2b=0; double angle1,angle1plus=0., angle2, angle2plus=0.;//angle1 = rotation of object as a whole; angle1plus = arc angle (t parameter for ellipses). if (geo1->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo1); r1a = circle->getRadius(); angle1 = M_PI/4; midpos1 = circle->getCenter(); } else if (geo1->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo1); r1a = arc->getRadius(); double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); angle1 = (startangle + endangle)/2; midpos1 = arc->getCenter(); } else if (geo1->getTypeId() == Part::GeomEllipse::getClassTypeId()) { const Part::GeomEllipse *ellipse = dynamic_cast<const Part::GeomEllipse *>(geo1); r1a = ellipse->getMajorRadius(); r1b = ellipse->getMinorRadius(); Base::Vector3d majdir = ellipse->getMajorAxisDir(); angle1 = atan2(majdir.y, majdir.x); angle1plus = M_PI/4; midpos1 = ellipse->getCenter(); } else if (geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { const Part::GeomArcOfEllipse *aoe = dynamic_cast<const Part::GeomArcOfEllipse *>(geo1); r1a = aoe->getMajorRadius(); r1b = aoe->getMinorRadius(); double startangle, endangle; aoe->getRange(startangle, endangle, /*emulateCCW=*/true); Base::Vector3d majdir = aoe->getMajorAxisDir(); angle1 = atan2(majdir.y, majdir.x); angle1plus = (startangle + endangle)/2; midpos1 = aoe->getCenter(); } else break; if (geo2->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo2); r2a = circle->getRadius(); angle2 = M_PI/4; midpos2 = circle->getCenter(); } else if (geo2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo2); r2a = arc->getRadius(); double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); angle2 = (startangle + endangle)/2; midpos2 = arc->getCenter(); } else if (geo2->getTypeId() == Part::GeomEllipse::getClassTypeId()) { const Part::GeomEllipse *ellipse = dynamic_cast<const Part::GeomEllipse *>(geo2); r2a = ellipse->getMajorRadius(); r2b = ellipse->getMinorRadius(); Base::Vector3d majdir = ellipse->getMajorAxisDir(); angle2 = atan2(majdir.y, majdir.x); angle2plus = M_PI/4; midpos2 = ellipse->getCenter(); } else if (geo2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { const Part::GeomArcOfEllipse *aoe = dynamic_cast<const Part::GeomArcOfEllipse *>(geo2); r2a = aoe->getMajorRadius(); r2b = aoe->getMinorRadius(); double startangle, endangle; aoe->getRange(startangle, endangle, /*emulateCCW=*/true); Base::Vector3d majdir = aoe->getMajorAxisDir(); angle2 = atan2(majdir.y, majdir.x); angle2plus = (startangle + endangle)/2; midpos2 = aoe->getCenter(); } else break; if( geo1->getTypeId() == Part::GeomEllipse::getClassTypeId() || geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() ){ Base::Vector3d majDir, minDir, rvec; majDir = Base::Vector3d(cos(angle1),sin(angle1),0);//direction of major axis of ellipse minDir = Base::Vector3d(-majDir.y,majDir.x,0);//direction of minor axis of ellipse rvec = (r1a*cos(angle1plus)) * majDir + (r1b*sin(angle1plus)) * minDir; midpos1 += rvec; rvec.Normalize(); norm1 = rvec; dir1 = Base::Vector3d(-rvec.y,rvec.x,0);//DeepSOIC: I'm not sure what dir is supposed to mean. } else { norm1 = Base::Vector3d(cos(angle1),sin(angle1),0); dir1 = Base::Vector3d(-norm1.y,norm1.x,0); midpos1 += r1a*norm1; } if( geo2->getTypeId() == Part::GeomEllipse::getClassTypeId() || geo2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() ) { Base::Vector3d majDir, minDir, rvec; majDir = Base::Vector3d(cos(angle2),sin(angle2),0);//direction of major axis of ellipse minDir = Base::Vector3d(-majDir.y,majDir.x,0);//direction of minor axis of ellipse rvec = (r2a*cos(angle2plus)) * majDir + (r2b*sin(angle2plus)) * minDir; midpos2 += rvec; rvec.Normalize(); norm2 = rvec; dir2 = Base::Vector3d(-rvec.y,rvec.x,0); } else { norm2 = Base::Vector3d(cos(angle2),sin(angle2),0); dir2 = Base::Vector3d(-norm2.y,norm2.x,0); midpos2 += r2a*norm2; } } else // Parallel can only apply to a GeomLineSegment break; } else { const Part::GeomLineSegment *lineSeg1 = dynamic_cast<const Part::GeomLineSegment *>(geo1); const Part::GeomLineSegment *lineSeg2 = dynamic_cast<const Part::GeomLineSegment *>(geo2); // calculate the half distance between the start and endpoint midpos1 = ((lineSeg1->getEndPoint()+lineSeg1->getStartPoint())/2); midpos2 = ((lineSeg2->getEndPoint()+lineSeg2->getStartPoint())/2); //Get a set of vectors perpendicular and tangential to these dir1 = (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()).Normalize(); dir2 = (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()).Normalize(); norm1 = Base::Vector3d(-dir1.y,dir1.x,0.); norm2 = Base::Vector3d(-dir2.y,dir2.x,0.); } Base::Vector3d relpos1 = seekConstraintPosition(midpos1, norm1, dir1, 2.5, edit->constrGroup->getChild(i)); Base::Vector3d relpos2 = seekConstraintPosition(midpos2, norm2, dir2, 2.5, edit->constrGroup->getChild(i)); dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(midpos1.x, midpos1.y, zConstr); //Absolute Reference //Reference Position that is scaled according to zoom dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relpos1.x, relpos1.y, 0); Base::Vector3d secondPos = midpos2 - midpos1; dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->abPos = SbVec3f(secondPos.x, secondPos.y, zConstr); //Absolute Reference //Reference Position that is scaled according to zoom dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->translation = SbVec3f(relpos2.x - relpos1.x, relpos2.y -relpos1.y, 0); } break; case Distance: case DistanceX: case DistanceY: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); Base::Vector3d pnt1(0.,0.,0.), pnt2(0.,0.,0.); if (Constr->SecondPos != Sketcher::none) { // point to point distance if (temp) { pnt1 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); pnt2 = getSketchObject()->getSolvedSketch().getPoint(Constr->Second, Constr->SecondPos); } else { pnt1 = getSketchObject()->getPoint(Constr->First, Constr->FirstPos); pnt2 = getSketchObject()->getPoint(Constr->Second, Constr->SecondPos); } } else if (Constr->Second != Constraint::GeoUndef) { // point to line distance if (temp) { pnt1 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); } else { pnt1 = getSketchObject()->getPoint(Constr->First, Constr->FirstPos); } const Part::Geometry *geo = GeoById(*geomlist, Constr->Second); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo); Base::Vector3d l2p1 = lineSeg->getStartPoint(); Base::Vector3d l2p2 = lineSeg->getEndPoint(); // calculate the projection of p1 onto line2 pnt2.ProjToLine(pnt1-l2p1, l2p2-l2p1); pnt2 += pnt1; } else break; } else if (Constr->FirstPos != Sketcher::none) { if (temp) { pnt2 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); } else { pnt2 = getSketchObject()->getPoint(Constr->First, Constr->FirstPos); } } else if (Constr->First != Constraint::GeoUndef) { const Part::Geometry *geo = GeoById(*geomlist, Constr->First); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo); pnt1 = lineSeg->getStartPoint(); pnt2 = lineSeg->getEndPoint(); } else break; } else break; SoDatumLabel *asciiText = dynamic_cast<SoDatumLabel *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); asciiText->string = SbString(Base::Quantity(Constr->getPresentationValue(),Base::Unit::Length).getUserString().toUtf8().constData()); if (Constr->Type == Distance) asciiText->datumtype = SoDatumLabel::DISTANCE; else if (Constr->Type == DistanceX) asciiText->datumtype = SoDatumLabel::DISTANCEX; else if (Constr->Type == DistanceY) asciiText->datumtype = SoDatumLabel::DISTANCEY; // Assign the Datum Points asciiText->pnts.setNum(2); SbVec3f *verts = asciiText->pnts.startEditing(); verts[0] = SbVec3f (pnt1.x,pnt1.y,zConstr); verts[1] = SbVec3f (pnt2.x,pnt2.y,zConstr); asciiText->pnts.finishEditing(); //Assign the Label Distance asciiText->param1 = Constr->LabelDistance; asciiText->param2 = Constr->LabelPosition; } break; case PointOnObject: case Tangent: case SnellsLaw: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); Base::Vector3d pos, relPos; if ( Constr->Type == PointOnObject || Constr->Type == SnellsLaw || (Constr->Type == Tangent && Constr->Third != Constraint::GeoUndef) || //Tangency via point (Constr->Type == Tangent && Constr->FirstPos != Sketcher::none) //endpoint-to-curve or endpoint-to-endpoint tangency ) { //find the point of tangency/point that is on object //just any point among first/second/third should be OK int ptGeoId; Sketcher::PointPos ptPosId; do {//dummy loop to use break =) Maybe goto? ptGeoId = Constr->First; ptPosId = Constr->FirstPos; if (ptPosId != Sketcher::none) break; ptGeoId = Constr->Second; ptPosId = Constr->SecondPos; if (ptPosId != Sketcher::none) break; ptGeoId = Constr->Third; ptPosId = Constr->ThirdPos; if (ptPosId != Sketcher::none) break; assert(0);//no point found! } while (false); pos = getSketchObject()->getSolvedSketch().getPoint(ptGeoId, ptPosId); Base::Vector3d norm = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->Second, pos.x, pos.y); norm.Normalize(); Base::Vector3d dir = norm; dir.RotateZ(-M_PI/2.0); relPos = seekConstraintPosition(pos, norm, dir, 2.5, edit->constrGroup->getChild(i)); dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(pos.x, pos.y, zConstr); //Absolute Reference dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relPos.x, relPos.y, 0); } else if (Constr->Type == Tangent) { // get the geometry const Part::Geometry *geo1 = GeoById(*geomlist, Constr->First); const Part::Geometry *geo2 = GeoById(*geomlist, Constr->Second); if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg1 = dynamic_cast<const Part::GeomLineSegment *>(geo1); const Part::GeomLineSegment *lineSeg2 = dynamic_cast<const Part::GeomLineSegment *>(geo2); // tangency between two lines Base::Vector3d midpos1 = ((lineSeg1->getEndPoint()+lineSeg1->getStartPoint())/2); Base::Vector3d midpos2 = ((lineSeg2->getEndPoint()+lineSeg2->getStartPoint())/2); Base::Vector3d dir1 = (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()).Normalize(); Base::Vector3d dir2 = (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()).Normalize(); Base::Vector3d norm1 = Base::Vector3d(-dir1.y,dir1.x,0.f); Base::Vector3d norm2 = Base::Vector3d(-dir2.y,dir2.x,0.f); Base::Vector3d relpos1 = seekConstraintPosition(midpos1, norm1, dir1, 2.5, edit->constrGroup->getChild(i)); Base::Vector3d relpos2 = seekConstraintPosition(midpos2, norm2, dir2, 2.5, edit->constrGroup->getChild(i)); dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(midpos1.x, midpos1.y, zConstr); //Absolute Reference //Reference Position that is scaled according to zoom dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relpos1.x, relpos1.y, 0); Base::Vector3d secondPos = midpos2 - midpos1; dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->abPos = SbVec3f(secondPos.x, secondPos.y, zConstr); //Absolute Reference //Reference Position that is scaled according to zoom dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->translation = SbVec3f(relpos2.x -relpos1.x, relpos2.y -relpos1.y, 0); break; } else if (geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { std::swap(geo1,geo2); } if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo1); Base::Vector3d dir = (lineSeg->getEndPoint() - lineSeg->getStartPoint()).Normalize(); Base::Vector3d norm(-dir.y, dir.x, 0); if (geo2->getTypeId()== Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo2); // tangency between a line and a circle float length = (circle->getCenter() - lineSeg->getStartPoint())*dir; pos = lineSeg->getStartPoint() + dir * length; relPos = norm * 1; //TODO Huh? } else if (geo2->getTypeId()== Part::GeomEllipse::getClassTypeId() || geo2->getTypeId()== Part::GeomArcOfEllipse::getClassTypeId()) { Base::Vector3d center; if(geo2->getTypeId()== Part::GeomEllipse::getClassTypeId()){ const Part::GeomEllipse *ellipse = dynamic_cast<const Part::GeomEllipse *>(geo2); center=ellipse->getCenter(); } else { const Part::GeomArcOfEllipse *aoc = dynamic_cast<const Part::GeomArcOfEllipse *>(geo2); center=aoc->getCenter(); } // tangency between a line and an ellipse float length = (center - lineSeg->getStartPoint())*dir; pos = lineSeg->getStartPoint() + dir * length; relPos = norm * 1; } else if (geo2->getTypeId()== Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo2); // tangency between a line and an arc float length = (arc->getCenter() - lineSeg->getStartPoint())*dir; pos = lineSeg->getStartPoint() + dir * length; relPos = norm * 1; //TODO Huh? } } if (geo1->getTypeId()== Part::GeomCircle::getClassTypeId() && geo2->getTypeId()== Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle1 = dynamic_cast<const Part::GeomCircle *>(geo1); const Part::GeomCircle *circle2 = dynamic_cast<const Part::GeomCircle *>(geo2); // tangency between two cicles Base::Vector3d dir = (circle2->getCenter() - circle1->getCenter()).Normalize(); pos = circle1->getCenter() + dir * circle1->getRadius(); relPos = dir * 1; } else if (geo2->getTypeId()== Part::GeomCircle::getClassTypeId()) { std::swap(geo1,geo2); } if (geo1->getTypeId()== Part::GeomCircle::getClassTypeId() && geo2->getTypeId()== Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo1); const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo2); // tangency between a circle and an arc Base::Vector3d dir = (arc->getCenter() - circle->getCenter()).Normalize(); pos = circle->getCenter() + dir * circle->getRadius(); relPos = dir * 1; } else if (geo1->getTypeId()== Part::GeomArcOfCircle::getClassTypeId() && geo2->getTypeId()== Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc1 = dynamic_cast<const Part::GeomArcOfCircle *>(geo1); const Part::GeomArcOfCircle *arc2 = dynamic_cast<const Part::GeomArcOfCircle *>(geo2); // tangency between two arcs Base::Vector3d dir = (arc2->getCenter() - arc1->getCenter()).Normalize(); pos = arc1->getCenter() + dir * arc1->getRadius(); relPos = dir * 1; } dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(pos.x, pos.y, zConstr); //Absolute Reference dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relPos.x, relPos.y, 0); } } break; case Symmetric: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); Base::Vector3d pnt1 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); Base::Vector3d pnt2 = getSketchObject()->getSolvedSketch().getPoint(Constr->Second, Constr->SecondPos); SbVec3f p1(pnt1.x,pnt1.y,zConstr); SbVec3f p2(pnt2.x,pnt2.y,zConstr); SbVec3f dir = (p2-p1); dir.normalize(); SbVec3f norm (-dir[1],dir[0],0); SoDatumLabel *asciiText = dynamic_cast<SoDatumLabel *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); asciiText->datumtype = SoDatumLabel::SYMMETRIC; asciiText->pnts.setNum(2); SbVec3f *verts = asciiText->pnts.startEditing(); verts[0] = p1; verts[1] = p2; asciiText->pnts.finishEditing(); dynamic_cast<SoTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = (p1 + p2)/2; } break; case Angle: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); assert((Constr->Second >= -extGeoCount && Constr->Second < intGeoCount) || Constr->Second == Constraint::GeoUndef); SbVec3f p0; double startangle,range,endangle; if (Constr->Second != Constraint::GeoUndef) { Base::Vector3d dir1, dir2; if(Constr->Third == Constraint::GeoUndef) { //angle between two lines const Part::Geometry *geo1 = GeoById(*geomlist, Constr->First); const Part::Geometry *geo2 = GeoById(*geomlist, Constr->Second); if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() || geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) break; const Part::GeomLineSegment *lineSeg1 = dynamic_cast<const Part::GeomLineSegment *>(geo1); const Part::GeomLineSegment *lineSeg2 = dynamic_cast<const Part::GeomLineSegment *>(geo2); bool flip1 = (Constr->FirstPos == end); bool flip2 = (Constr->SecondPos == end); dir1 = (flip1 ? -1. : 1.) * (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()); dir2 = (flip2 ? -1. : 1.) * (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()); Base::Vector3d pnt1 = flip1 ? lineSeg1->getEndPoint() : lineSeg1->getStartPoint(); Base::Vector3d pnt2 = flip2 ? lineSeg2->getEndPoint() : lineSeg2->getStartPoint(); // line-line intersection { double det = dir1.x*dir2.y - dir1.y*dir2.x; if ((det > 0 ? det : -det) < 1e-10) { // lines are coincident (or parallel) and in this case the center // of the point pairs with the shortest distance is used Base::Vector3d p1[2], p2[2]; p1[0] = lineSeg1->getStartPoint(); p1[1] = lineSeg1->getEndPoint(); p2[0] = lineSeg2->getStartPoint(); p2[1] = lineSeg2->getEndPoint(); double length = DBL_MAX; for (int i=0; i <= 1; i++) { for (int j=0; j <= 1; j++) { double tmp = (p2[j]-p1[i]).Length(); if (tmp < length) { length = tmp; p0.setValue((p2[j].x+p1[i].x)/2,(p2[j].y+p1[i].y)/2,0); } } } } else { double c1 = dir1.y*pnt1.x - dir1.x*pnt1.y; double c2 = dir2.y*pnt2.x - dir2.x*pnt2.y; double x = (dir1.x*c2 - dir2.x*c1)/det; double y = (dir1.y*c2 - dir2.y*c1)/det; p0 = SbVec3f(x,y,0); } } } else {//angle-via-point Base::Vector3d p = getSketchObject()->getSolvedSketch().getPoint(Constr->Third, Constr->ThirdPos); p0 = SbVec3f(p.x, p.y, 0); dir1 = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->First, p.x, p.y); dir1.RotateZ(-M_PI/2);//convert to vector of tangency by rotating dir2 = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->Second, p.x, p.y); dir2.RotateZ(-M_PI/2); } startangle = atan2(dir1.y,dir1.x); range = atan2(-dir1.y*dir2.x+dir1.x*dir2.y, dir1.x*dir2.x+dir1.y*dir2.y); endangle = startangle + range; } else if (Constr->First != Constraint::GeoUndef) { const Part::Geometry *geo = GeoById(*geomlist, Constr->First); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo); p0 = Base::convertTo<SbVec3f>((lineSeg->getEndPoint()+lineSeg->getStartPoint())/2); Base::Vector3d dir = lineSeg->getEndPoint()-lineSeg->getStartPoint(); startangle = 0.; range = atan2(dir.y,dir.x); endangle = startangle + range; } else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo); p0 = Base::convertTo<SbVec3f>(arc->getCenter()); arc->getRange(startangle, endangle,/*emulateCCWXY=*/true); range = endangle - startangle; } else { break; } } else break; SoDatumLabel *asciiText = dynamic_cast<SoDatumLabel *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); asciiText->string = SbString(Base::Quantity(Base::toDegrees<double>(Constr->getPresentationValue()),Base::Unit::Angle).getUserString().toUtf8().constData()); asciiText->datumtype = SoDatumLabel::ANGLE; asciiText->param1 = Constr->LabelDistance; asciiText->param2 = startangle; asciiText->param3 = range; asciiText->pnts.setNum(2); SbVec3f *verts = asciiText->pnts.startEditing(); verts[0] = p0; asciiText->pnts.finishEditing(); } break; case Radius: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); Base::Vector3d pnt1(0.,0.,0.), pnt2(0.,0.,0.); if (Constr->First != Constraint::GeoUndef) { const Part::Geometry *geo = GeoById(*geomlist, Constr->First); if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo); double radius = arc->getRadius(); double angle = (double) Constr->LabelPosition; if (angle == 10) { double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); angle = (startangle + endangle)/2; } pnt1 = arc->getCenter(); pnt2 = pnt1 + radius * Base::Vector3d(cos(angle),sin(angle),0.); } else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo); double radius = circle->getRadius(); double angle = (double) Constr->LabelPosition; if (angle == 10) { angle = 0; } pnt1 = circle->getCenter(); pnt2 = pnt1 + radius * Base::Vector3d(cos(angle),sin(angle),0.); } else break; } else break; SbVec3f p1(pnt1.x,pnt1.y,zConstr); SbVec3f p2(pnt2.x,pnt2.y,zConstr); SoDatumLabel *asciiText = dynamic_cast<SoDatumLabel *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); asciiText->string = SbString(Base::Quantity(Constr->getPresentationValue(),Base::Unit::Length).getUserString().toUtf8().constData()); asciiText->datumtype = SoDatumLabel::RADIUS; asciiText->param1 = Constr->LabelDistance; asciiText->param2 = Constr->LabelPosition; asciiText->pnts.setNum(2); SbVec3f *verts = asciiText->pnts.startEditing(); verts[0] = p1; verts[1] = p2; asciiText->pnts.finishEditing(); } break; case Coincident: // nothing to do for coincident case None: case InternalAlignment: case NumConstraintTypes: break; } } catch (Base::Exception e) { Base::Console().Error("Exception during draw: %s\n", e.what()); } catch (...){ Base::Console().Error("Exception during draw: unknown\n"); } } this->drawConstraintIcons(); this->updateColor(); // delete the cloned objects if (temp) { for (std::vector<Part::Geometry *>::iterator it=tempGeo.begin(); it != tempGeo.end(); ++it) { if (*it) delete *it; } } Gui::MDIView *mdi = this->getActiveView(); if (mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) { static_cast<Gui::View3DInventor *>(mdi)->getViewer()->redraw(); } } void ViewProviderSketch::rebuildConstraintsVisual(void) { const std::vector<Sketcher::Constraint *> &constrlist = getSketchObject()->Constraints.getValues(); // clean up edit->constrGroup->removeAllChildren(); edit->vConstrType.clear(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); int fontSize = hGrp->GetInt("EditSketcherFontSize", 17); for (std::vector<Sketcher::Constraint *>::const_iterator it=constrlist.begin(); it != constrlist.end(); ++it) { // root separator for one constraint SoSeparator *sep = new SoSeparator(); sep->ref(); // no caching for fluctuand data structures sep->renderCaching = SoSeparator::OFF; // every constrained visual node gets its own material for preselection and selection SoMaterial *mat = new SoMaterial; mat->ref(); mat->diffuseColor = (*it)->isDriving?ConstrDimColor:NonDrivingConstrDimColor; // Get sketch normal Base::Vector3d RN(0,0,1); // move to position of Sketch Base::Placement Plz = getSketchObject()->Placement.getValue(); Base::Rotation tmp(Plz.getRotation()); tmp.multVec(RN,RN); Plz.setRotation(tmp); SbVec3f norm(RN.x, RN.y, RN.z); // distinguish different constraint types to build up switch ((*it)->Type) { case Distance: case DistanceX: case DistanceY: case Radius: case Angle: { SoDatumLabel *text = new SoDatumLabel(); text->norm.setValue(norm); text->string = ""; text->textColor = (*it)->isDriving?ConstrDimColor:NonDrivingConstrDimColor;; text->size.setValue(fontSize); text->useAntialiasing = false; SoAnnotation *anno = new SoAnnotation(); anno->renderCaching = SoSeparator::OFF; anno->addChild(text); // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(text); edit->constrGroup->addChild(anno); edit->vConstrType.push_back((*it)->Type); // nodes not needed sep->unref(); mat->unref(); continue; // jump to next constraint } break; case Horizontal: case Vertical: { // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(mat); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3 sep->addChild(new SoInfo()); // remember the type of this constraint node edit->vConstrType.push_back((*it)->Type); } break; case Coincident: // no visual for coincident so far edit->vConstrType.push_back(Coincident); break; case Parallel: case Perpendicular: case Equal: { // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(mat); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3 sep->addChild(new SoInfo()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION 4 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_ICON 5 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID 6 sep->addChild(new SoInfo()); // remember the type of this constraint node edit->vConstrType.push_back((*it)->Type); } break; case PointOnObject: case Tangent: case SnellsLaw: { // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(mat); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3 sep->addChild(new SoInfo()); if ((*it)->Type == Tangent) { const Part::Geometry *geo1 = getSketchObject()->getGeometry((*it)->First); const Part::Geometry *geo2 = getSketchObject()->getGeometry((*it)->Second); if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION 4 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_ICON 5 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID 6 sep->addChild(new SoInfo()); } } edit->vConstrType.push_back((*it)->Type); } break; case Symmetric: { SoDatumLabel *arrows = new SoDatumLabel(); arrows->norm.setValue(norm); arrows->string = ""; arrows->textColor = ConstrDimColor; // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(arrows); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 sep->addChild(new SoTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3 sep->addChild(new SoInfo()); edit->vConstrType.push_back((*it)->Type); } break; case InternalAlignment: { edit->vConstrType.push_back((*it)->Type); } break; default: edit->vConstrType.push_back((*it)->Type); } edit->constrGroup->addChild(sep); // decrement ref counter again sep->unref(); mat->unref(); } } void ViewProviderSketch::drawEdit(const std::vector<Base::Vector2D> &EditCurve) { assert(edit); edit->EditCurveSet->numVertices.setNum(1); edit->EditCurvesCoordinate->point.setNum(EditCurve.size()); SbVec3f *verts = edit->EditCurvesCoordinate->point.startEditing(); int32_t *index = edit->EditCurveSet->numVertices.startEditing(); int i=0; // setting up the line set for (std::vector<Base::Vector2D>::const_iterator it = EditCurve.begin(); it != EditCurve.end(); ++it,i++) verts[i].setValue(it->fX,it->fY,zEdit); index[0] = EditCurve.size(); edit->EditCurvesCoordinate->point.finishEditing(); edit->EditCurveSet->numVertices.finishEditing(); } void ViewProviderSketch::updateData(const App::Property *prop) { ViewProvider2DObject::updateData(prop); if (edit && (prop == &(getSketchObject()->Geometry) || prop == &(getSketchObject()->Constraints))) { edit->FullyConstrained = false; // At this point, we do not need to solve the Sketch // If we are adding geometry an update can be triggered before the sketch is actually solved. // Because a solve is mandatory to any addition (at least to update the DoF of the solver), // only when the solver geometry is the same in number than the sketch geometry an update // should trigger a redraw. This reduces even more the number of redraws per insertion of geometry // solver information is also updated when no matching geometry, so that if a solving fails // this failed solving info is presented to the user UpdateSolverInformation(); // just update the solver window with the last SketchObject solving information if(getSketchObject()->getExternalGeometryCount()+getSketchObject()->getHighestCurveIndex() + 1 == getSketchObject()->getSolvedSketch().getGeometrySize()) { Gui::MDIView *mdi = Gui::Application::Instance->activeDocument()->getActiveView(); if (mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) draw(false); signalConstraintsChanged(); signalElementsChanged(); } } } void ViewProviderSketch::onChanged(const App::Property *prop) { // call father PartGui::ViewProvider2DObject::onChanged(prop); } void ViewProviderSketch::attach(App::DocumentObject *pcFeat) { ViewProviderPart::attach(pcFeat); } void ViewProviderSketch::setupContextMenu(QMenu *menu, QObject *receiver, const char *member) { menu->addAction(tr("Edit sketch"), receiver, member); } bool ViewProviderSketch::setEdit(int ModNum) { // When double-clicking on the item for this sketch the // object unsets and sets its edit mode without closing // the task panel Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); TaskDlgEditSketch *sketchDlg = qobject_cast<TaskDlgEditSketch *>(dlg); if (sketchDlg && sketchDlg->getSketchView() != this) sketchDlg = 0; // another sketch left open its task panel if (dlg && !sketchDlg) { QMessageBox msgBox; msgBox.setText(tr("A dialog is already open in the task panel")); msgBox.setInformativeText(tr("Do you want to close this dialog?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); if (ret == QMessageBox::Yes) Gui::Control().reject(); else return false; } Sketcher::SketchObject* sketch = getSketchObject(); if (!sketch->evaluateConstraints()) { QMessageBox box(Gui::getMainWindow()); box.setIcon(QMessageBox::Critical); box.setWindowTitle(tr("Invalid sketch")); box.setText(tr("Do you want to open the sketch validation tool?")); box.setInformativeText(tr("The sketch is invalid and cannot be edited.")); box.setStandardButtons(QMessageBox::Yes | QMessageBox::No); box.setDefaultButton(QMessageBox::Yes); switch (box.exec()) { case QMessageBox::Yes: Gui::Control().showDialog(new TaskSketcherValidation(getSketchObject())); break; default: break; } return false; } // clear the selection (convenience) Gui::Selection().clearSelection(); // create the container for the additional edit data assert(!edit); edit = new EditData(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); edit->MarkerSize = hGrp->GetInt("EditSketcherMarkerSize", 7); createEditInventorNodes(); edit->visibleBeforeEdit = this->isVisible(); this->hide(); // avoid that the wires interfere with the edit lines ShowGrid.setValue(true); TightGrid.setValue(false); float transparency; // set the point color unsigned long color = (unsigned long)(VertexColor.getPackedValue()); color = hGrp->GetUnsigned("EditedVertexColor", color); VertexColor.setPackedValue((uint32_t)color, transparency); // set the curve color color = (unsigned long)(CurveColor.getPackedValue()); color = hGrp->GetUnsigned("EditedEdgeColor", color); CurveColor.setPackedValue((uint32_t)color, transparency); // set the construction curve color color = (unsigned long)(CurveDraftColor.getPackedValue()); color = hGrp->GetUnsigned("ConstructionColor", color); CurveDraftColor.setPackedValue((uint32_t)color, transparency); // set the cross lines color //CrossColorV.setPackedValue((uint32_t)color, transparency); //CrossColorH.setPackedValue((uint32_t)color, transparency); // set the fully constrained color color = (unsigned long)(FullyConstrainedColor.getPackedValue()); color = hGrp->GetUnsigned("FullyConstrainedColor", color); FullyConstrainedColor.setPackedValue((uint32_t)color, transparency); // set the constraint dimension color color = (unsigned long)(ConstrDimColor.getPackedValue()); color = hGrp->GetUnsigned("ConstrainedDimColor", color); ConstrDimColor.setPackedValue((uint32_t)color, transparency); // set the constraint color color = (unsigned long)(ConstrIcoColor.getPackedValue()); color = hGrp->GetUnsigned("ConstrainedIcoColor", color); ConstrIcoColor.setPackedValue((uint32_t)color, transparency); // set non-driving constraint color color = (unsigned long)(NonDrivingConstrDimColor.getPackedValue()); color = hGrp->GetUnsigned("NonDrivingConstrDimColor", color); NonDrivingConstrDimColor.setPackedValue((uint32_t)color, transparency); // set the external geometry color color = (unsigned long)(CurveExternalColor.getPackedValue()); color = hGrp->GetUnsigned("ExternalColor", color); CurveExternalColor.setPackedValue((uint32_t)color, transparency); // set the highlight color unsigned long highlight = (unsigned long)(PreselectColor.getPackedValue()); highlight = hGrp->GetUnsigned("HighlightColor", highlight); PreselectColor.setPackedValue((uint32_t)highlight, transparency); // set the selection color highlight = (unsigned long)(SelectColor.getPackedValue()); highlight = hGrp->GetUnsigned("SelectionColor", highlight); SelectColor.setPackedValue((uint32_t)highlight, transparency); // start the edit dialog if (sketchDlg) Gui::Control().showDialog(sketchDlg); else Gui::Control().showDialog(new TaskDlgEditSketch(this)); // This call to the solver is needed to initialize the DoF and solve time controls // The false parameter indicates that the geometry of the SketchObject shall not be updateData // so as not to trigger an onChanged that would set the document as modified and trigger a recompute // if we just close the sketch without touching anything. if (getSketchObject()->Support.getValue()) { if (!getSketchObject()->evaluateSupport()) getSketchObject()->validateExternalLinks(); } getSketchObject()->solve(false); UpdateSolverInformation(); draw(false); connectUndoDocument = Gui::Application::Instance->activeDocument() ->signalUndoDocument.connect(boost::bind(&ViewProviderSketch::slotUndoDocument, this, _1)); connectRedoDocument = Gui::Application::Instance->activeDocument() ->signalRedoDocument.connect(boost::bind(&ViewProviderSketch::slotRedoDocument, this, _1)); return true; } QString ViewProviderSketch::appendConflictMsg(const std::vector<int> &conflicting) { QString msg; QTextStream ss(&msg); if (conflicting.size() > 0) { if (conflicting.size() == 1) ss << tr("Please remove the following constraint:"); else ss << tr("Please remove at least one of the following constraints:"); ss << "\n"; ss << conflicting[0]; for (unsigned int i=1; i < conflicting.size(); i++) ss << ", " << conflicting[i]; ss << "\n"; } return msg; } QString ViewProviderSketch::appendRedundantMsg(const std::vector<int> &redundant) { QString msg; QTextStream ss(&msg); if (redundant.size() > 0) { if (redundant.size() == 1) ss << tr("Please remove the following redundant constraint:"); else ss << tr("Please remove the following redundant constraints:"); ss << "\n"; ss << redundant[0]; for (unsigned int i=1; i < redundant.size(); i++) ss << ", " << redundant[i]; ss << "\n"; } return msg; } void ViewProviderSketch::UpdateSolverInformation() { // Updates Solver Information with the Last solver execution at SketchObject level int dofs = getSketchObject()->getLastDoF(); bool hasConflicts = getSketchObject()->getLastHasConflicts(); bool hasRedundancies = getSketchObject()->getLastHasRedundancies(); if (getSketchObject()->Geometry.getSize() == 0) { signalSetUp(tr("Empty sketch")); signalSolved(QString()); } else if (dofs < 0) { // over-constrained sketch std::string msg; SketchObject::appendConflictMsg(getSketchObject()->getLastConflicting(), msg); signalSetUp(QString::fromLatin1("<font color='red'>%1<a href=\"#conflicting\"><span style=\" text-decoration: underline; color:#0000ff;\">%2</span></a><br/>%3</font><br/>") .arg(tr("Over-constrained sketch ")) .arg(tr("(click to select)")) .arg(QString::fromStdString(msg))); signalSolved(QString()); } else if (hasConflicts) { // conflicting constraints signalSetUp(QString::fromLatin1("<font color='red'>%1<a href=\"#conflicting\"><span style=\" text-decoration: underline; color:#0000ff;\">%2</span></a><br/>%3</font><br/>") .arg(tr("Sketch contains conflicting constraints ")) .arg(tr("(click to select)")) .arg(appendConflictMsg(getSketchObject()->getLastConflicting()))); signalSolved(QString()); } else { if (hasRedundancies) { // redundant constraints signalSetUp(QString::fromLatin1("<font color='orangered'>%1<a href=\"#redundant\"><span style=\" text-decoration: underline; color:#0000ff;\">%2</span></a><br/>%3</font><br/>") .arg(tr("Sketch contains redundant constraints ")) .arg(tr("(click to select)")) .arg(appendRedundantMsg(getSketchObject()->getLastRedundant()))); } if (getSketchObject()->getLastSolverStatus() == 0) { if (dofs == 0) { // color the sketch as fully constrained if it has geometry (other than the axes) if(getSketchObject()->getSolvedSketch().getGeometrySize()>2) edit->FullyConstrained = true; if (!hasRedundancies) { signalSetUp(QString::fromLatin1("<font color='green'>%1</font>").arg(tr("Fully constrained sketch"))); } } else if (!hasRedundancies) { if (dofs == 1) signalSetUp(tr("Under-constrained sketch with 1 degree of freedom")); else signalSetUp(tr("Under-constrained sketch with %1 degrees of freedom").arg(dofs)); } signalSolved(QString::fromLatin1("<font color='green'>%1</font>").arg(tr("Solved in %1 sec").arg(getSketchObject()->getLastSolveTime()))); } else { signalSolved(QString::fromLatin1("<font color='red'>%1</font>").arg(tr("Unsolved (%1 sec)").arg(getSketchObject()->getLastSolveTime()))); } } } void ViewProviderSketch::createEditInventorNodes(void) { assert(edit); edit->EditRoot = new SoSeparator; edit->EditRoot->setName("Sketch_EditRoot"); pcRoot->addChild(edit->EditRoot); edit->EditRoot->renderCaching = SoSeparator::OFF ; // stuff for the points ++++++++++++++++++++++++++++++++++++++ SoSeparator* pointsRoot = new SoSeparator; edit->EditRoot->addChild(pointsRoot); edit->PointsMaterials = new SoMaterial; edit->PointsMaterials->setName("PointsMaterials"); pointsRoot->addChild(edit->PointsMaterials); SoMaterialBinding *MtlBind = new SoMaterialBinding; MtlBind->setName("PointsMaterialBinding"); MtlBind->value = SoMaterialBinding::PER_VERTEX; pointsRoot->addChild(MtlBind); edit->PointsCoordinate = new SoCoordinate3; edit->PointsCoordinate->setName("PointsCoordinate"); pointsRoot->addChild(edit->PointsCoordinate); SoDrawStyle *DrawStyle = new SoDrawStyle; DrawStyle->setName("PointsDrawStyle"); DrawStyle->pointSize = 8; pointsRoot->addChild(DrawStyle); edit->PointSet = new SoMarkerSet; edit->PointSet->setName("PointSet"); edit->PointSet->markerIndex = Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_FILLED", edit->MarkerSize); pointsRoot->addChild(edit->PointSet); // stuff for the Curves +++++++++++++++++++++++++++++++++++++++ SoSeparator* curvesRoot = new SoSeparator; edit->EditRoot->addChild(curvesRoot); edit->CurvesMaterials = new SoMaterial; edit->CurvesMaterials->setName("CurvesMaterials"); curvesRoot->addChild(edit->CurvesMaterials); MtlBind = new SoMaterialBinding; MtlBind->setName("CurvesMaterialsBinding"); MtlBind->value = SoMaterialBinding::PER_FACE; curvesRoot->addChild(MtlBind); edit->CurvesCoordinate = new SoCoordinate3; edit->CurvesCoordinate->setName("CurvesCoordinate"); curvesRoot->addChild(edit->CurvesCoordinate); DrawStyle = new SoDrawStyle; DrawStyle->setName("CurvesDrawStyle"); DrawStyle->lineWidth = 3; curvesRoot->addChild(DrawStyle); edit->CurveSet = new SoLineSet; edit->CurveSet->setName("CurvesLineSet"); curvesRoot->addChild(edit->CurveSet); // stuff for the RootCross lines +++++++++++++++++++++++++++++++++++++++ SoGroup* crossRoot = new Gui::SoSkipBoundingGroup; edit->pickStyleAxes = new SoPickStyle(); edit->pickStyleAxes->style = SoPickStyle::SHAPE; crossRoot->addChild(edit->pickStyleAxes); edit->EditRoot->addChild(crossRoot); MtlBind = new SoMaterialBinding; MtlBind->setName("RootCrossMaterialBinding"); MtlBind->value = SoMaterialBinding::PER_FACE; crossRoot->addChild(MtlBind); DrawStyle = new SoDrawStyle; DrawStyle->setName("RootCrossDrawStyle"); DrawStyle->lineWidth = 2; crossRoot->addChild(DrawStyle); edit->RootCrossMaterials = new SoMaterial; edit->RootCrossMaterials->setName("RootCrossMaterials"); edit->RootCrossMaterials->diffuseColor.set1Value(0,CrossColorH); edit->RootCrossMaterials->diffuseColor.set1Value(1,CrossColorV); crossRoot->addChild(edit->RootCrossMaterials); edit->RootCrossCoordinate = new SoCoordinate3; edit->RootCrossCoordinate->setName("RootCrossCoordinate"); crossRoot->addChild(edit->RootCrossCoordinate); edit->RootCrossSet = new SoLineSet; edit->RootCrossSet->setName("RootCrossLineSet"); crossRoot->addChild(edit->RootCrossSet); // stuff for the EditCurves +++++++++++++++++++++++++++++++++++++++ SoSeparator* editCurvesRoot = new SoSeparator; edit->EditRoot->addChild(editCurvesRoot); edit->EditCurvesMaterials = new SoMaterial; edit->EditCurvesMaterials->setName("EditCurvesMaterials"); editCurvesRoot->addChild(edit->EditCurvesMaterials); edit->EditCurvesCoordinate = new SoCoordinate3; edit->EditCurvesCoordinate->setName("EditCurvesCoordinate"); editCurvesRoot->addChild(edit->EditCurvesCoordinate); DrawStyle = new SoDrawStyle; DrawStyle->setName("EditCurvesDrawStyle"); DrawStyle->lineWidth = 3; editCurvesRoot->addChild(DrawStyle); edit->EditCurveSet = new SoLineSet; edit->EditCurveSet->setName("EditCurveLineSet"); editCurvesRoot->addChild(edit->EditCurveSet); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); float transparency; SbColor cursorTextColor(0,0,1); cursorTextColor.setPackedValue((uint32_t)hGrp->GetUnsigned("CursorTextColor", cursorTextColor.getPackedValue()), transparency); // stuff for the edit coordinates ++++++++++++++++++++++++++++++++++++++ SoSeparator *Coordsep = new SoSeparator(); Coordsep->setName("CoordSeparator"); // no caching for fluctuand data structures Coordsep->renderCaching = SoSeparator::OFF; SoMaterial *CoordTextMaterials = new SoMaterial; CoordTextMaterials->setName("CoordTextMaterials"); CoordTextMaterials->diffuseColor = cursorTextColor; Coordsep->addChild(CoordTextMaterials); SoFont *font = new SoFont(); font->size = 10.0; Coordsep->addChild(font); edit->textPos = new SoTranslation(); Coordsep->addChild(edit->textPos); edit->textX = new SoText2(); edit->textX->justification = SoText2::LEFT; edit->textX->string = ""; Coordsep->addChild(edit->textX); edit->EditRoot->addChild(Coordsep); // group node for the Constraint visual +++++++++++++++++++++++++++++++++++ MtlBind = new SoMaterialBinding; MtlBind->setName("ConstraintMaterialBinding"); MtlBind->value = SoMaterialBinding::OVERALL ; edit->EditRoot->addChild(MtlBind); // use small line width for the Constraints DrawStyle = new SoDrawStyle; DrawStyle->setName("ConstraintDrawStyle"); DrawStyle->lineWidth = 1; edit->EditRoot->addChild(DrawStyle); // add the group where all the constraints has its SoSeparator edit->constrGroup = new SoGroup(); edit->constrGroup->setName("ConstraintGroup"); edit->EditRoot->addChild(edit->constrGroup); } void ViewProviderSketch::unsetEdit(int ModNum) { ShowGrid.setValue(false); TightGrid.setValue(true); if (edit) { if (edit->sketchHandler) deactivateHandler(); edit->EditRoot->removeAllChildren(); pcRoot->removeChild(edit->EditRoot); if (edit->visibleBeforeEdit) this->show(); else this->hide(); delete edit; edit = 0; } try { // and update the sketch getSketchObject()->getDocument()->recompute(); } catch (...) { } // clear the selection and set the new/edited sketch(convenience) Gui::Selection().clearSelection(); std::string ObjName = getSketchObject()->getNameInDocument(); std::string DocName = getSketchObject()->getDocument()->getName(); Gui::Selection().addSelection(DocName.c_str(),ObjName.c_str()); connectUndoDocument.disconnect(); connectRedoDocument.disconnect(); // when pressing ESC make sure to close the dialog Gui::Control().closeDialog(); } void ViewProviderSketch::setEditViewer(Gui::View3DInventorViewer* viewer, int ModNum) { Base::Placement plm = getSketchObject()->Placement.getValue(); Base::Rotation tmp(plm.getRotation()); SbRotation rot((float)tmp[0],(float)tmp[1],(float)tmp[2],(float)tmp[3]); // Will the sketch be visible from the new position (#0000957)? // SoCamera* camera = viewer->getSoRenderManager()->getCamera(); SbVec3f curdir; // current view direction camera->orientation.getValue().multVec(SbVec3f(0, 0, -1), curdir); SbVec3f focal = camera->position.getValue() + camera->focalDistance.getValue() * curdir; SbVec3f newdir; // future view direction rot.multVec(SbVec3f(0, 0, -1), newdir); SbVec3f newpos = focal - camera->focalDistance.getValue() * newdir; SbVec3f plnpos = Base::convertTo<SbVec3f>(plm.getPosition()); double dist = (plnpos - newpos).dot(newdir); if (dist < 0) { float focalLength = camera->focalDistance.getValue() - dist + 5; camera->position = focal - focalLength * curdir; camera->focalDistance.setValue(focalLength); } viewer->setCameraOrientation(rot); viewer->setEditing(true); SoNode* root = viewer->getSceneGraph(); static_cast<Gui::SoFCUnifiedSelection*>(root)->selectionRole.setValue(false); viewer->addGraphicsItem(rubberband); rubberband->setViewer(viewer); } void ViewProviderSketch::unsetEditViewer(Gui::View3DInventorViewer* viewer) { viewer->removeGraphicsItem(rubberband); viewer->setEditing(false); SoNode* root = viewer->getSceneGraph(); static_cast<Gui::SoFCUnifiedSelection*>(root)->selectionRole.setValue(true); } void ViewProviderSketch::setPositionText(const Base::Vector2D &Pos, const SbString &text) { edit->textX->string = text; edit->textPos->translation = SbVec3f(Pos.fX,Pos.fY,zText); } void ViewProviderSketch::setPositionText(const Base::Vector2D &Pos) { SbString text; text.sprintf(" (%.1f,%.1f)", Pos.fX, Pos.fY); edit->textX->string = text; edit->textPos->translation = SbVec3f(Pos.fX,Pos.fY,zText); } void ViewProviderSketch::resetPositionText(void) { edit->textX->string = ""; } void ViewProviderSketch::setPreselectPoint(int PreselectPoint) { if (edit) { int oldPtId = -1; if (edit->PreselectPoint != -1) oldPtId = edit->PreselectPoint + 1; else if (edit->PreselectCross == 0) oldPtId = 0; int newPtId = PreselectPoint + 1; SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); float x,y,z; if (oldPtId != -1 && edit->SelPointSet.find(oldPtId) == edit->SelPointSet.end()) { // send to background pverts[oldPtId].getValue(x,y,z); pverts[oldPtId].setValue(x,y,zPoints); } // bring to foreground pverts[newPtId].getValue(x,y,z); pverts[newPtId].setValue(x,y,zHighlight); edit->PreselectPoint = PreselectPoint; edit->PointsCoordinate->point.finishEditing(); } } void ViewProviderSketch::resetPreselectPoint(void) { if (edit) { int oldPtId = -1; if (edit->PreselectPoint != -1) oldPtId = edit->PreselectPoint + 1; else if (edit->PreselectCross == 0) oldPtId = 0; if (oldPtId != -1 && edit->SelPointSet.find(oldPtId) == edit->SelPointSet.end()) { // send to background SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); float x,y,z; pverts[oldPtId].getValue(x,y,z); pverts[oldPtId].setValue(x,y,zPoints); edit->PointsCoordinate->point.finishEditing(); } edit->PreselectPoint = -1; } } void ViewProviderSketch::addSelectPoint(int SelectPoint) { if (edit) { int PtId = SelectPoint + 1; SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); // bring to foreground float x,y,z; pverts[PtId].getValue(x,y,z); pverts[PtId].setValue(x,y,zHighlight); edit->SelPointSet.insert(PtId); edit->PointsCoordinate->point.finishEditing(); } } void ViewProviderSketch::removeSelectPoint(int SelectPoint) { if (edit) { int PtId = SelectPoint + 1; SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); // send to background float x,y,z; pverts[PtId].getValue(x,y,z); pverts[PtId].setValue(x,y,zPoints); edit->SelPointSet.erase(PtId); edit->PointsCoordinate->point.finishEditing(); } } void ViewProviderSketch::clearSelectPoints(void) { if (edit) { SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); // send to background float x,y,z; for (std::set<int>::const_iterator it=edit->SelPointSet.begin(); it != edit->SelPointSet.end(); ++it) { pverts[*it].getValue(x,y,z); pverts[*it].setValue(x,y,zPoints); } edit->PointsCoordinate->point.finishEditing(); edit->SelPointSet.clear(); } } int ViewProviderSketch::getPreselectPoint(void) const { if (edit) return edit->PreselectPoint; return -1; } int ViewProviderSketch::getPreselectCurve(void) const { if (edit) return edit->PreselectCurve; return -1; } int ViewProviderSketch::getPreselectCross(void) const { if (edit) return edit->PreselectCross; return -1; } Sketcher::SketchObject *ViewProviderSketch::getSketchObject(void) const { return dynamic_cast<Sketcher::SketchObject *>(pcObject); } bool ViewProviderSketch::onDelete(const std::vector<std::string> &subList) { if (edit) { std::vector<std::string> SubNames = subList; Gui::Selection().clearSelection(); resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); std::set<int> delInternalGeometries, delExternalGeometries, delCoincidents, delConstraints; // go through the selected subelements for (std::vector<std::string>::const_iterator it=SubNames.begin(); it != SubNames.end(); ++it) { if (it->size() > 4 && it->substr(0,4) == "Edge") { int GeoId = std::atoi(it->substr(4,4000).c_str()) - 1; if( GeoId >= 0 ) delInternalGeometries.insert(GeoId); else delExternalGeometries.insert(-3-GeoId); } else if (it->size() > 12 && it->substr(0,12) == "ExternalEdge") { int GeoId = std::atoi(it->substr(12,4000).c_str()) - 1; delExternalGeometries.insert(GeoId); } else if (it->size() > 6 && it->substr(0,6) == "Vertex") { int VtId = std::atoi(it->substr(6,4000).c_str()) - 1; int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(VtId, GeoId, PosId); if (getSketchObject()->getGeometry(GeoId)->getTypeId() == Part::GeomPoint::getClassTypeId()) { if(GeoId>=0) delInternalGeometries.insert(GeoId); else delExternalGeometries.insert(-3-GeoId); } else delCoincidents.insert(VtId); } else if (*it == "RootPoint") { delCoincidents.insert(-1); } else if (it->size() > 10 && it->substr(0,10) == "Constraint") { int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(*it); delConstraints.insert(ConstrId); } } std::set<int>::const_reverse_iterator rit; for (rit = delConstraints.rbegin(); rit != delConstraints.rend(); ++rit) { try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.delConstraint(%i)" ,getObject()->getNameInDocument(), *rit); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); } } for (rit = delCoincidents.rbegin(); rit != delCoincidents.rend(); ++rit) { try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.delConstraintOnPoint(%i)" ,getObject()->getNameInDocument(), *rit); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); } } for (rit = delInternalGeometries.rbegin(); rit != delInternalGeometries.rend(); ++rit) { try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.delGeometry(%i)" ,getObject()->getNameInDocument(), *rit); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); } } for (rit = delExternalGeometries.rbegin(); rit != delExternalGeometries.rend(); ++rit) { try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.delExternal(%i)" ,getObject()->getNameInDocument(), *rit); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); } } int ret=getSketchObject()->solve(); if(ret!=0){ // if the sketched could not be solved, we first redraw to update the UI geometry as // onChanged did not update it. UpdateSolverInformation(); draw(); signalConstraintsChanged(); signalElementsChanged(); } /*this->drawConstraintIcons(); this->updateColor();*/ // if in edit not delete the object return false; } // if not in edit delete the whole object return true; }
kkoksvik/FreeCAD
src/Mod/Sketcher/Gui/ViewProviderSketch.cpp
C++
lgpl-2.1
230,010
/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "btperceptionviewcone.h" btPerceptionViewcone::btPerceptionViewcone() { this->extentAngleHorizontal = 0; this->extentAngleVertical = 0; this->offsetAngleHorizontal = 0; this->offsetAngleVertical = 0; this->radius = 0; this->knowledgePrecision = 1.0; }
pranavrc/gluon
smarts/lib/btperceptionviewcone.cpp
C++
lgpl-2.1
996
/* * DomUI Java User Interface library * Copyright (c) 2010 by Frits Jalvingh, Itris B.V. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * See the "sponsors" file for a list of supporters. * * The latest version of DomUI and related code, support and documentation * can be found at http://www.domui.org/ * The contact for the project is Frits Jalvingh <jal@etc.to>. */ package to.etc.domui.component.binding; import org.eclipse.jdt.annotation.NonNull; import to.etc.domui.dom.html.NodeBase; /** * EXPERIMENTAL - DO NOT USE. * This defines a control binding event interface which gets called when the control's * movement calls are used. * * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on Oct 13, 2009 */ public interface IBindingListener<T extends NodeBase> { void moveControlToModel(@NonNull T control) throws Exception; void moveModelToControl(@NonNull T control) throws Exception; }
fjalvingh/domui
to.etc.domui/src/main/java/to/etc/domui/component/binding/IBindingListener.java
Java
lgpl-2.1
1,628
/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2001 - 2013 Object Refinery Ltd, Hitachi Vantara and Contributors.. All rights reserved. */ package org.pentaho.reporting.engine.classic.core.layout.process.util; import org.pentaho.reporting.engine.classic.core.layout.model.ParagraphRenderBox; import org.pentaho.reporting.engine.classic.core.layout.model.RenderNode; import org.pentaho.reporting.engine.classic.core.layout.process.layoutrules.DefaultSequenceList; import org.pentaho.reporting.engine.classic.core.layout.process.layoutrules.InlineNodeSequenceElement; import org.pentaho.reporting.engine.classic.core.layout.process.layoutrules.InlineSequenceElement; import org.pentaho.reporting.engine.classic.core.layout.process.layoutrules.ReplacedContentSequenceElement; import org.pentaho.reporting.engine.classic.core.layout.process.layoutrules.SequenceList; import org.pentaho.reporting.engine.classic.core.layout.process.layoutrules.TextSequenceElement; import org.pentaho.reporting.engine.classic.core.util.InstanceID; public final class MinorAxisParagraphBreakState { private InstanceID suspendItem; private SequenceList elementSequence; private ParagraphRenderBox paragraph; private boolean containsContent; public MinorAxisParagraphBreakState() { this.elementSequence = new DefaultSequenceList(); } public void init( final ParagraphRenderBox paragraph ) { if ( paragraph == null ) { throw new NullPointerException(); } this.paragraph = paragraph; this.elementSequence.clear(); this.suspendItem = null; this.containsContent = false; } public void deinit() { this.paragraph = null; this.elementSequence.clear(); this.suspendItem = null; this.containsContent = false; } public boolean isInsideParagraph() { return paragraph != null; } public ParagraphRenderBox getParagraph() { return paragraph; } /* * public InstanceID getSuspendItem() { return suspendItem; } * * public void setSuspendItem(final InstanceID suspendItem) { this.suspendItem = suspendItem; } */ public void add( final InlineSequenceElement element, final RenderNode node ) { elementSequence.add( element, node ); if ( element instanceof TextSequenceElement || element instanceof InlineNodeSequenceElement || element instanceof ReplacedContentSequenceElement ) { containsContent = true; } } public boolean isContainsContent() { return containsContent; } public boolean isSuspended() { return suspendItem != null; } public SequenceList getSequence() { return elementSequence; } public void clear() { elementSequence.clear(); suspendItem = null; containsContent = false; } }
mbatchelor/pentaho-reporting
engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/layout/process/util/MinorAxisParagraphBreakState.java
Java
lgpl-2.1
3,462
/* SPI.cpp - SPI library for esp8266 Copyright (c) 2015 Hristo Gochkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "SPI.h" SPIClass SPI; SPIClass::SPIClass(){} void SPIClass::begin(){ pinMode(SCK, SPECIAL); pinMode(MISO, SPECIAL); pinMode(MOSI, SPECIAL); GPMUX = 0x105; SPI1C = 0; SPI1CLK = SPI_CLOCK_DIV16;//1MHz SPI1U = SPIUMOSI | SPIUDUPLEX | SPIUSSE; SPI1U1 = (7 << SPILMOSI) | (7 << SPILMISO); SPI1C1 = 0; } void SPIClass::end() { pinMode(SCK, INPUT); pinMode(MISO, INPUT); pinMode(MOSI, INPUT); } void SPIClass::beginTransaction(SPISettings settings) { setClockDivider(settings._clock); setBitOrder(settings._bitOrder); setDataMode(settings._dataMode); } void SPIClass::endTransaction() {} void SPIClass::setDataMode(uint8_t dataMode) { } void SPIClass::setBitOrder(uint8_t bitOrder) { if (bitOrder == MSBFIRST){ SPI1C &= ~(SPICWBO | SPICRBO); } else { SPI1C |= (SPICWBO | SPICRBO); } } void SPIClass::setClockDivider(uint32_t clockDiv) { SPI1CLK = clockDiv; } uint8_t SPIClass::transfer(uint8_t data) { while(SPI1CMD & SPIBUSY); SPI1W0 = data; SPI1CMD |= SPIBUSY; while(SPI1CMD & SPIBUSY); return (uint8_t)(SPI1W0 & 0xff); }
toddtreece/esp8266-Arduino
package/libraries/SPI/SPI.cpp
C++
lgpl-2.1
1,984
package org.uengine.kernel.designer.ui; import org.metaworks.EventContext; import org.metaworks.annotation.ServiceMethod; import org.uengine.essencia.modeling.ConnectorSymbol; import org.uengine.kernel.graph.MessageTransition; import org.uengine.kernel.graph.Transition; import org.uengine.modeling.IRelation; import org.uengine.modeling.RelationPropertiesView; import org.uengine.modeling.Symbol; public class MessageTransitionView extends TransitionView{ public final static String SHAPE_ID = "OG.shape.bpmn.C_Message"; public MessageTransitionView(){ } public MessageTransitionView(IRelation relation){ super(relation); } @ServiceMethod(callByContent=true, eventBinding=EventContext.EVENT_DBLCLICK) public Object properties() throws Exception { Transition transition; if(this.getRelation() == null) transition = new Transition(); else transition = (Transition)this.getRelation(); return new RelationPropertiesView(transition); } public static Symbol createSymbol() { Symbol symbol = new Symbol(); symbol.setName("메시지 플로우"); return fillSymbol(symbol); } public static Symbol createSymbol(Class<? extends Symbol> symbolType) { Symbol symbol = new ConnectorSymbol(); try { symbol = (Symbol)Thread.currentThread().getContextClassLoader().loadClass(symbolType.getName()).newInstance(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } symbol.setName("커낵터"); return fillSymbol(symbol); } private static Symbol fillSymbol (Symbol symbol){ symbol.setShapeId(SHAPE_ID); symbol.setHeight(150); symbol.setWidth(200); symbol.setElementClassName(MessageTransition.class.getName()); symbol.setShapeType("EDGE"); return symbol; } }
iklim/essencia
src/main/java/org/uengine/kernel/designer/ui/MessageTransitionView.java
Java
lgpl-2.1
1,872
/* = StarPU-Top for StarPU = Copyright (C) 2011 William Braik Yann Courtois Jean-Marie Couteyen Anthony Roy This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QtGui/QApplication> #include "mainwindow.h" #include <string.h> #include <config.h> #define PROGNAME "starpu_top" static void parse_args(int argc, char **argv) { if (argc == 1) return; if (argc > 2 || /* Argc should be either 1 or 2 */ strncmp(argv[1], "--help", 6) == 0 || strncmp(argv[1], "-h", 2) == 0) { (void) fprintf(stderr, "\ starpu-top is an interface which remotely displays the \n\ on-line state of a StarPU application and permits the user \n\ to change parameters on the fly. \n\ \n\ Usage: %s [OPTION] \n\ \n\ Options: \n\ -h, --help display this help and exit \n\ -v, --version output version information and exit \n\ \n\ Report bugs to <" PACKAGE_BUGREPORT ">.", PROGNAME); } else if (strncmp(argv[1], "--version", 9) == 0 || strncmp(argv[1], "-v", 2) == 0) { fprintf(stderr, "%s (%s) %s\n", PROGNAME, PACKAGE_NAME, PACKAGE_VERSION); } else { fprintf(stderr, "Unknown arg %s\n", argv[1]); } exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { parse_args(argc, argv); QApplication a(argc, argv); // Application description QCoreApplication::setOrganizationName("INRIA Bordeaux Sud-Ouest"); QCoreApplication::setOrganizationDomain("runtime.bordeaux.inria.fr"); QCoreApplication::setApplicationName("StarPU-Top"); QCoreApplication::setApplicationVersion("0.1"); MainWindow w; w.show(); return a.exec(); }
joao-lima/starpu-1.2.0rc2
starpu-top/main.cpp
C++
lgpl-2.1
2,638
/*************************************************************************** * Copyright (C) 2003 by Hans Karlsson * * karlsson.h@home.se * * * * 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. * ***************************************************************************/ #include "program.h" #include "karamba.h" ProgramSensor::ProgramSensor(Karamba* k, const QString &progName, int interval, const QString &encoding) : Sensor(interval), m_karamba(k) { if (!encoding.isEmpty()) { codec = QTextCodec::codecForName(encoding.toAscii().constData()); if (codec == 0) codec = QTextCodec::codecForLocale(); } else codec = QTextCodec::codecForLocale(); programName = progName; //update(); connect(&ksp, SIGNAL(receivedStdout(K3Process*,char*,int)), this, SLOT(receivedStdout(K3Process*,char*,int))); connect(&ksp, SIGNAL(processExited(K3Process*)), this, SLOT(processExited(K3Process*))); } ProgramSensor::~ProgramSensor() {} void ProgramSensor::receivedStdout(K3Process *, char *buffer, int len) { buffer[len] = 0; sensorResult += codec->toUnicode(buffer); } void ProgramSensor::replaceLine(QString &format, const QString &line) { const QStringList tokens = line.split(QRegExp("\\s+"), QString::SkipEmptyParts); QRegExp dblDigit("%(\\d\\d)"); replaceArgs(dblDigit, format, tokens); QRegExp digit("%(\\d)"); replaceArgs(digit, format, tokens); } void ProgramSensor::replaceArgs(QRegExp& regEx, QString& format, const QStringList& tokens) { int pos = 0; while (pos >= 0) { pos = regEx.indexIn(format, pos); if (pos > -1) { QString matched = regEx.cap(1); int tokenIndex = matched.toInt() - 1; QString replacement = ""; if (tokenIndex < tokens.size()) { replacement = tokens.at(tokenIndex); } format.replace(QRegExp('%' + matched), replacement); pos += regEx.matchedLength(); } } } void ProgramSensor::processExited(K3Process *) { int lineNbr; SensorParams *sp; Meter *meter; QString value; QVector<QString> lines; QStringList stringList = sensorResult.split('\n'); QStringList::ConstIterator end(stringList.constEnd()); for (QStringList::ConstIterator it = stringList.constBegin(); it != end; ++it) { lines.push_back(*it); } int count = (int) lines.size(); QObject *object; foreach(object, *objList) { sp = (SensorParams*)(object); meter = sp->getMeter(); if (meter != 0) { lineNbr = (sp->getParam("LINE")).toInt(); if (lineNbr >= 1 && lineNbr <= (int) count) { value = lines[lineNbr-1]; } else if (-lineNbr >= 1 && -lineNbr <= (int) count) { value = lines[count+lineNbr]; } else if (lineNbr != 0) { value.clear(); } else { value = sensorResult; } QString format = sp->getParam("FORMAT"); if (!format.isEmpty()) { QString returnValue; QStringList lineList = value.split('\n'); QStringList::ConstIterator lineListEnd(lineList.constEnd()); for (QStringList::ConstIterator line = lineList.constBegin(); line != lineListEnd; ++line) { QString formatCopy = format; replaceLine(formatCopy, *line); returnValue += formatCopy; if ( lineList.size() > 1) { returnValue += '\n'; } } value = returnValue; } meter->setValue(value); } } sensorResult = ""; } void ProgramSensor::update() { QString prog = programName; m_karamba->replaceNamedValues(&prog); if ( prog.isEmpty() || prog.startsWith("%echo ")) { sensorResult += prog.mid(6); processExited(NULL); } else { ksp.clearArguments(); ksp << prog; ksp.start(K3ProcIO::NotifyOnExit, K3ProcIO::Stdout); } } #include "program.moc"
KDE/superkaramba
src/sensors/program.cpp
C++
lgpl-2.1
4,624
package magustechnica.common.lib; public class LibGuiIDs { public static final int MANUAL = 0; }
Azaler/MagusTechnica
src/main/java/magustechnica/common/lib/LibGuiIDs.java
Java
lgpl-2.1
100
package nofs.restfs; import java.util.List; import nofs.Library.Annotations.DomainObject; import nofs.Library.Annotations.FolderObject; import nofs.Library.Annotations.NeedsContainerManager; import nofs.Library.Annotations.RootFolderObject; import nofs.Library.Containers.IDomainObjectContainer; import nofs.Library.Containers.IDomainObjectContainerManager; import nofs.restfs.rules.RulesFolder; @RootFolderObject @FolderObject(ChildTypeFilterMethod="Filter") @DomainObject public class RestfulRoot extends RestfulFolderWithSettings { public boolean Filter(Class<?> possibleChildType) { return possibleChildType == RestfulFolderWithSettings.class || possibleChildType == RestfulFile.class; } private IDomainObjectContainerManager _containerManager; @NeedsContainerManager public void setContainerManager(IDomainObjectContainerManager containerManager) { _containerManager = containerManager; super.setContainerManager(containerManager); } @Override protected void CreatingList(List<BaseFileObject> list) { try { list.add(CreateAuthFolder()); list.add(CreateRulesFolder()); } catch (Exception e) { e.printStackTrace(); } } private RulesFolder CreateRulesFolder() throws Exception { IDomainObjectContainer<RulesFolder> container = _containerManager.GetContainer(RulesFolder.class); RulesFolder folder; if(container.GetAllInstances().size() > 0) { folder = container.GetAllInstances().iterator().next(); } else { folder = container.NewPersistentInstance(); folder.setName("rules"); container.ObjectChanged(folder); } return folder; } @SuppressWarnings("unchecked") private OAuthFolder CreateAuthFolder() throws Exception { IDomainObjectContainer<OAuthFolder> container = _containerManager.GetContainer(OAuthFolder.class); OAuthFolder folder; if(container.GetAllInstances().size() > 0) { folder = container.GetAllInstances().iterator().next(); } else { folder = container.NewPersistentInstance(); folder.setName("auth"); container.ObjectChanged(folder); } return folder; } }
megacoder/restfs
src/main/java/nofs/restfs/RestfulRoot.java
Java
lgpl-2.1
2,225
#include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <vector> #include <map> #include <cstdlib> #include <cmath> #include <algorithm> #include <cstdio> #include "moses/TrellisPathList.h" #include "moses/TrellisPath.h" #include "moses/StaticData.h" #include "moses/Util.h" #include "mbr.h" using namespace std ; using namespace Moses; /* Input : 1. a sorted n-best list, with duplicates filtered out in the following format 0 ||| amr moussa is currently on a visit to libya , tomorrow , sunday , to hold talks with regard to the in sudan . ||| 0 -4.94418 0 0 -2.16036 0 0 -81.4462 -106.593 -114.43 -105.55 -12.7873 -26.9057 -25.3715 -52.9336 7.99917 -24 ||| -4.58432 2. a weight vector 3. bleu order ( default = 4) 4. scaling factor to weigh the weight vector (default = 1.0) Output : translations that minimise the Bayes Risk of the n-best list */ int BLEU_ORDER = 4; int SMOOTH = 1; float min_interval = 1e-4; void extract_ngrams(const vector<const Factor* >& sentence, map < vector < const Factor* >, int > & allngrams) { vector< const Factor* > ngram; for (int k = 0; k < BLEU_ORDER; k++) { for(int i =0; i < max((int)sentence.size()-k,0); i++) { for ( int j = i; j<= i+k; j++) { ngram.push_back(sentence[j]); } ++allngrams[ngram]; ngram.clear(); } } } float calculate_score(const vector< vector<const Factor*> > & sents, int ref, int hyp, vector < map < vector < const Factor *>, int > > & ngram_stats ) { int comps_n = 2*BLEU_ORDER+1; vector<int> comps(comps_n); float logbleu = 0.0, brevity; int hyp_length = sents[hyp].size(); for (int i =0; i<BLEU_ORDER; i++) { comps[2*i] = 0; comps[2*i+1] = max(hyp_length-i,0); } map< vector < const Factor * > ,int > & hyp_ngrams = ngram_stats[hyp] ; map< vector < const Factor * >, int > & ref_ngrams = ngram_stats[ref] ; for (map< vector< const Factor * >, int >::iterator it = hyp_ngrams.begin(); it != hyp_ngrams.end(); it++) { map< vector< const Factor * >, int >::iterator ref_it = ref_ngrams.find(it->first); if(ref_it != ref_ngrams.end()) { comps[2* (it->first.size()-1)] += min(ref_it->second,it->second); } } comps[comps_n-1] = sents[ref].size(); for (int i=0; i<BLEU_ORDER; i++) { if (comps[0] == 0) return 0.0; if ( i > 0 ) logbleu += log((float)comps[2*i]+SMOOTH)-log((float)comps[2*i+1]+SMOOTH); else logbleu += log((float)comps[2*i])-log((float)comps[2*i+1]); } logbleu /= BLEU_ORDER; brevity = 1.0-(float)comps[comps_n-1]/comps[1]; // comps[comps_n-1] is the ref length, comps[1] is the test length if (brevity < 0.0) logbleu += brevity; return exp(logbleu); } const TrellisPath doMBR(const TrellisPathList& nBestList) { float marginal = 0; float mbr_scale = StaticData::Instance().options().mbr.scale; vector<float> joint_prob_vec; vector< vector<const Factor*> > translations; float joint_prob; vector< map < vector <const Factor *>, int > > ngram_stats; TrellisPathList::const_iterator iter; // get max score to prevent underflow float maxScore = -1e20; for (iter = nBestList.begin() ; iter != nBestList.end() ; ++iter) { const TrellisPath &path = **iter; float score = mbr_scale * path.GetScoreBreakdown()->GetWeightedScore(); if (maxScore < score) maxScore = score; } for (iter = nBestList.begin() ; iter != nBestList.end() ; ++iter) { const TrellisPath &path = **iter; joint_prob = UntransformScore(mbr_scale * path.GetScoreBreakdown()->GetWeightedScore() - maxScore); marginal += joint_prob; joint_prob_vec.push_back(joint_prob); // get words in translation vector<const Factor*> translation; GetOutputFactors(path, translation); // collect n-gram counts map < vector < const Factor *>, int > counts; extract_ngrams(translation,counts); ngram_stats.push_back(counts); translations.push_back(translation); } vector<float> mbr_loss; float bleu, weightedLoss; float weightedLossCumul = 0; float minMBRLoss = 1000000; int minMBRLossIdx = -1; /* Main MBR computation done here */ iter = nBestList.begin(); for (unsigned int i = 0; i < nBestList.GetSize(); i++) { weightedLossCumul = 0; for (unsigned int j = 0; j < nBestList.GetSize(); j++) { if ( i != j) { bleu = calculate_score(translations, j, i,ngram_stats ); weightedLoss = ( 1 - bleu) * ( joint_prob_vec[j]/marginal); weightedLossCumul += weightedLoss; if (weightedLossCumul > minMBRLoss) break; } } if (weightedLossCumul < minMBRLoss) { minMBRLoss = weightedLossCumul; minMBRLossIdx = i; } iter++; } /* Find sentence that minimises Bayes Risk under 1- BLEU loss */ return nBestList.at(minMBRLossIdx); //return translations[minMBRLossIdx]; } void GetOutputFactors(const TrellisPath &path, vector <const Factor*> &translation) { const std::vector<const Hypothesis *> &edges = path.GetEdges(); const std::vector<FactorType>& outputFactorOrder = StaticData::Instance().GetOutputFactorOrder(); assert (outputFactorOrder.size() == 1); // print the surface factor of the translation for (int currEdge = (int)edges.size() - 1 ; currEdge >= 0 ; currEdge--) { const Hypothesis &edge = *edges[currEdge]; const Phrase &phrase = edge.GetCurrTargetPhrase(); size_t size = phrase.GetSize(); for (size_t pos = 0 ; pos < size ; pos++) { const Factor *factor = phrase.GetFactor(pos, outputFactorOrder[0]); translation.push_back(factor); } } }
hychyc07/mosesdecoder
moses/mbr.cpp
C++
lgpl-2.1
5,622
#! /usr/bin/python # Copyright 2004 Roman Yakovenko. # Distributed under the Boost Software License, Version 1.0. (See # accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) import sys, os class settings: module_name='TnFOX' boost_path = '' boost_libs_path = '' gccxml_path = '' pygccxml_path = '' pyplusplus_path = '' tnfox_path = '' tnfox_include_path = '' tnfox_python_include_path = '' tnfox_libs_path = '' python_libs_path = '' python_include_path = '' working_dir = '' generated_files_dir = '' unittests_dir = '' xml_files = '' defined_symbols = [ "FXDISABLE_GLOBALALLOCATORREPLACEMENTS" , "FX_INCLUDE_ABSOLUTELY_EVERYTHING" , "FOXPYTHONDLL_EXPORTS" , "FX_NO_GLOBAL_NAMESPACE" ] # For debugging purposes to get far smaller bindings, you can define FX_DISABLEGUI #defined_symbols.append("FX_DISABLEGUI=1") if 'big'==sys.byteorder: defined_symbols.append("FOX_BIGENDIAN=1") else: defined_symbols.append("FOX_BIGENDIAN=0") if 'win32'==sys.platform or 'win64'==sys.platform: defined_symbols.append("WIN32") defined_symbols_gccxml = defined_symbols + ["__GCCXML__" , "_NATIVE_WCHAR_T_DEFINED=1" ] def setup_environment(): sys.path.append( settings.pygccxml_path ) sys.path.append( settings.pyplusplus_path ) setup_environment = staticmethod(setup_environment) rootdir=os.path.normpath(os.getcwd()+'/../..') settings.boost_path = rootdir+'/boost' settings.boost_libs_path = rootdir+'/boost/libs' #settings.gccxml_path = '' #settings.pygccxml_path = '' #settings.pyplusplus_path = '' settings.python_include_path = os.getenv('PYTHON_INCLUDE') settings.python_libs_path = os.getenv('PYTHON_ROOT')+'/libs' settings.tnfox_path = rootdir+'/TnFOX' settings.tnfox_include_path = rootdir+'/TnFOX/include' settings.tnfox_libs_path = rootdir+'/TnFOX/lib' settings.working_dir = os.getcwd() settings.generated_files_dir = rootdir+'/TnFOX/Python/generated' settings.unittests_dir = rootdir+'/TnFOX/Python/unittests' settings.setup_environment()
ned14/tnfox
Python/environment.py
Python
lgpl-2.1
2,231
//$Id: JDBCTransactionFactory.java 8820 2005-12-10 17:25:56Z steveebersole $ package org.hibernate.transaction; import java.util.Properties; import org.hibernate.ConnectionReleaseMode; import org.hibernate.Transaction; import org.hibernate.HibernateException; import org.hibernate.jdbc.JDBCContext; /** * Factory for <tt>JDBCTransaction</tt>. * @see JDBCTransaction * @author Anton van Straaten */ public final class JDBCTransactionFactory implements TransactionFactory { public ConnectionReleaseMode getDefaultReleaseMode() { return ConnectionReleaseMode.AFTER_TRANSACTION; } public Transaction createTransaction(JDBCContext jdbcContext, Context transactionContext) throws HibernateException { return new JDBCTransaction( jdbcContext, transactionContext ); } public void configure(Properties props) throws HibernateException {} public boolean isTransactionManagerRequired() { return false; } public boolean areCallbacksLocalToHibernateTransactions() { return true; } }
raedle/univis
lib/hibernate-3.1.3/src/org/hibernate/transaction/JDBCTransactionFactory.java
Java
lgpl-2.1
1,002
/* * This file is part of Cockpit. * * Copyright (C) 2015 Red Hat, Inc. * * Cockpit is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * Cockpit 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Cockpit; If not, see <http://www.gnu.org/licenses/>. */ import cockpit from "cockpit"; import { mustache } from "mustache"; import day_header_template from 'raw-loader!journal_day_header.mustache'; import line_template from 'raw-loader!journal_line.mustache'; import reboot_template from 'raw-loader!journal_reboot.mustache'; import moment from "moment"; moment.locale(cockpit.language); const _ = cockpit.gettext; export var journal = { }; /** * journalctl([match, ...], [options]) * @match: any number of journal match strings * @options: an object containing further options * * Load and (by default) stream journal entries as * json objects. This function returns a jQuery deferred * object which delivers the various journal entries. * * The various @match strings are journalctl matches. * Zero, one or more can be specified. They must be in * string format, or arrays of strings. * * The optional @options object can contain the following: * * "host": the host to load journal from * * "count": number of entries to load and/or pre-stream. * Default is 10 * * "follow": if set to false just load entries and don't * stream further journal data. Default is true. * * "directory": optional directory to load journal files * * "boot": when set only list entries from this specific * boot id, or if null then the current boot. * * "since": if specified list entries since the date/time * * "until": if specified list entries until the date/time * * "cursor": a cursor to start listing entries from * * "after": a cursor to start listing entries after * * Returns a jQuery deferred promise. You can call these * functions on the deferred to handle the responses. Note that * there are additional non-jQuery methods. * * .done(function(entries) { }): Called when done, @entries is * an array of all journal entries loaded. If .stream() * has been invoked then @entries will be empty. * .fail(funciton(ex) { }): called if the operation fails * .stream(function(entries) { }): called when we receive entries * entries. Called once per batch of journal @entries, * whether following or not. * .stop(): stop following or retrieving entries. */ journal.build_cmd = function build_cmd(/* ... */) { var matches = []; var i, arg; var options = { follow: true }; for (i = 0; i < arguments.length; i++) { arg = arguments[i]; if (typeof arg == "string") { matches.push(arg); } else if (typeof arg == "object") { if (arg instanceof Array) { matches.push.apply(matches, arg); } else { cockpit.extend(options, arg); break; } } else { console.warn("journal.journalctl called with invalid argument:", arg); } } if (options.count === undefined) { if (options.follow) options.count = 10; else options.count = null; } var cmd = ["journalctl", "-q"]; if (!options.count) cmd.push("--no-tail"); else cmd.push("--lines=" + options.count); cmd.push("--output=" + (options.output || "json")); if (options.directory) cmd.push("--directory=" + options.directory); if (options.boot) cmd.push("--boot=" + options.boot); else if (options.boot !== undefined) cmd.push("--boot"); if (options.since) cmd.push("--since=" + options.since); if (options.until) cmd.push("--until=" + options.until); if (options.cursor) cmd.push("--cursor=" + options.cursor); if (options.after) cmd.push("--after=" + options.after); /* journalctl doesn't allow reverse and follow together */ if (options.reverse) cmd.push("--reverse"); else if (options.follow) cmd.push("--follow"); cmd.push("--"); cmd.push.apply(cmd, matches); return [cmd, options]; }; journal.journalctl = function journalctl(/* ... */) { var [cmd, options] = journal.build_cmd.apply(null, arguments); var dfd = cockpit.defer(); var promise; var buffer = ""; var entries = []; var streamers = []; var interval = null; function fire_streamers() { var ents, i; if (streamers.length && entries.length > 0) { ents = entries; entries = []; for (i = 0; i < streamers.length; i++) streamers[i].apply(promise, [ents]); } else { window.clearInterval(interval); interval = null; } } var proc = cockpit.spawn(cmd, { host: options.host, batch: 8192, latency: 300, superuser: "try" }) .stream(function(data) { if (buffer) data = buffer + data; buffer = ""; var lines = data.split("\n"); var last = lines.length - 1; lines.forEach(function(line, i) { if (i == last) { buffer = line; } else if (line && line.indexOf("-- ") !== 0) { try { entries.push(JSON.parse(line)); } catch (e) { console.warn(e, line); } } }); if (streamers.length && interval === null) interval = window.setInterval(fire_streamers, 300); }) .done(function() { fire_streamers(); dfd.resolve(entries); }) .fail(function(ex) { /* The journalctl command fails when no entries are matched * so we just ignore this status code */ if (ex.problem == "cancelled" || ex.exit_status === 1) { fire_streamers(); dfd.resolve(entries); } else { dfd.reject(ex); } }) .always(function() { window.clearInterval(interval); }); promise = dfd.promise(); promise.stream = function stream(callback) { streamers.push(callback); return this; }; promise.stop = function stop() { proc.close("cancelled"); }; return promise; }; journal.printable = function printable(value) { if (value === undefined || value === null) return _("[no data]"); else if (typeof (value) == "string") return value; else if (value.length !== undefined) return cockpit.format(_("[$0 bytes of binary data]"), value.length); else return _("[binary data]"); }; function output_funcs_for_box(box) { /* Dereference any jQuery object here */ if (box.jquery) box = box[0]; mustache.parse(day_header_template); mustache.parse(line_template); mustache.parse(reboot_template); function render_line(ident, prio, message, count, time, entry) { var parts = { cursor: entry.__CURSOR, time: time, message: message, service: ident }; if (count > 1) parts.count = count; if (ident === 'abrt-notification') { parts.problem = true; parts.service = entry.PROBLEM_BINARY; } else if (prio < 4) parts.warning = true; return mustache.render(line_template, parts); } var reboot = _("Reboot"); var reboot_line = mustache.render(reboot_template, { message: reboot }); function render_reboot_separator() { return reboot_line; } function render_day_header(day) { return mustache.render(day_header_template, { day: day }); } function parse_html(string) { var div = document.createElement("div"); div.innerHTML = string.trim(); return div.children[0]; } return { render_line: render_line, render_day_header: render_day_header, render_reboot_separator: render_reboot_separator, append: function(elt) { if (typeof (elt) == "string") elt = parse_html(elt); box.appendChild(elt); }, prepend: function(elt) { if (typeof (elt) == "string") elt = parse_html(elt); if (box.firstChild) box.insertBefore(elt, box.firstChild); else box.appendChild(elt); }, remove_last: function() { if (box.lastChild) box.removeChild(box.lastChild); }, remove_first: function() { if (box.firstChild) box.removeChild(box.firstChild); }, }; } /* Render the journal entries by passing suitable HTML strings back to the caller via the 'output_funcs'. Rendering is context aware. It will insert 'reboot' markers, for example, and collapse repeated lines. You can extend the output at the bottom and also at the top. A new renderer is created by calling 'journal.renderer' like so: var renderer = journal.renderer(funcs); You can feed new entries into the renderer by calling various methods on the returned object: - renderer.append(journal_entry) - renderer.append_flush() - renderer.prepend(journal_entry) - renderer.prepend_flush() A 'journal_entry' is one element of the result array returned by a call to 'Query' with the 'cockpit.journal_fields' as the fields to return. Calling 'append' will append the given entry to the end of the output, naturally, and 'prepend' will prepend it to the start. The output might lag behind what has been input via 'append' and 'prepend', and you need to call 'append_flush' and 'prepend_flush' respectively to ensure that the output is up-to-date. Flushing a renderer does not introduce discontinuities into the output. You can continue to feed entries into the renderer after flushing and repeated lines will be correctly collapsed across the flush, for example. The renderer will call methods of the 'output_funcs' object to produce the desired output: - output_funcs.append(rendered) - output_funcs.remove_last() - output_funcs.prepend(rendered) - output_funcs.remove_first() The 'rendered' argument is the return value of one of the rendering functions described below. The 'append' and 'prepend' methods should add this element to the output, naturally, and 'remove_last' and 'remove_first' should remove the indicated element. If you never call 'prepend' on the renderer, 'output_func.prepend' isn't called either. If you never call 'renderer.prepend' after 'renderer.prepend_flush', then 'output_func.remove_first' will never be called. The same guarantees exist for the 'append' family of functions. The actual rendering is also done by calling methods on 'output_funcs': - output_funcs.render_line(ident, prio, message, count, time, cursor) - output_funcs.render_day_header(day) - output_funcs.render_reboot_separator() */ journal.renderer = function renderer(funcs_or_box) { var output_funcs; if (funcs_or_box.render_line) output_funcs = funcs_or_box; else output_funcs = output_funcs_for_box(funcs_or_box); function copy_object(o) { var c = { }; for (var p in o) c[p] = o[p]; return c; } // A 'entry' object describes a journal entry in formatted form. // It has fields 'bootid', 'ident', 'prio', 'message', 'time', // 'day', all of which are strings. function format_entry(journal_entry) { var d = moment(journal_entry.__REALTIME_TIMESTAMP / 1000); // timestamps are in µs return { cursor: journal_entry.__CURSOR, full: journal_entry, day: d.format('LL'), time: d.format('LT'), bootid: journal_entry._BOOT_ID, ident: journal_entry.SYSLOG_IDENTIFIER || journal_entry._COMM, prio: journal_entry.PRIORITY, message: journal.printable(journal_entry.MESSAGE) }; } function entry_is_equal(a, b) { return (a && b && a.day == b.day && a.bootid == b.bootid && a.ident == b.ident && a.prio == b.prio && a.message == b.message); } // A state object describes a line that should be eventually // output. It has an 'entry' field as per description above, and // also 'count', 'last_time', and 'first_time', which record // repeated entries. Additionally: // // line_present: When true, the line has been output already with // some preliminary data. It needs to be removed before // outputting more recent data. // // header_present: The day header has been output preliminarily // before the actual log lines. It needs to be removed before // prepending more lines. If both line_present and // header_present are true, then the header comes first in the // output, followed by the line. function render_state_line(state) { return output_funcs.render_line(state.entry.ident, state.entry.prio, state.entry.message, state.count, state.last_time, state.entry.full); } // We keep the state of the first and last journal lines, // respectively, in order to collapse repeated lines, and to // insert reboot markers and day headers. // // Normally, there are two state objects, but if only a single // line has been output so far, top_state and bottom_state point // to the same object. var top_state, bottom_state; top_state = bottom_state = { }; function start_new_line() { // If we now have two lines, split the state if (top_state === bottom_state && top_state.entry) { top_state = copy_object(bottom_state); } } function top_output() { if (top_state.header_present) { output_funcs.remove_first(); top_state.header_present = false; } if (top_state.line_present) { output_funcs.remove_first(); top_state.line_present = false; } if (top_state.entry) { output_funcs.prepend(render_state_line(top_state)); top_state.line_present = true; } } function prepend(journal_entry) { var entry = format_entry(journal_entry); if (entry_is_equal(top_state.entry, entry)) { top_state.count += 1; top_state.first_time = entry.time; } else { top_output(); if (top_state.entry) { if (entry.bootid != top_state.entry.bootid) output_funcs.prepend(output_funcs.render_reboot_separator()); if (entry.day != top_state.entry.day) output_funcs.prepend(output_funcs.render_day_header(top_state.entry.day)); } start_new_line(); top_state.entry = entry; top_state.count = 1; top_state.first_time = top_state.last_time = entry.time; top_state.line_present = false; } } function prepend_flush() { top_output(); if (top_state.entry) { output_funcs.prepend(output_funcs.render_day_header(top_state.entry.day)); top_state.header_present = true; } } function bottom_output() { if (bottom_state.line_present) { output_funcs.remove_last(); bottom_state.line_present = false; } if (bottom_state.entry) { output_funcs.append(render_state_line(bottom_state)); bottom_state.line_present = true; } } function append(journal_entry) { var entry = format_entry(journal_entry); if (entry_is_equal(bottom_state.entry, entry)) { bottom_state.count += 1; bottom_state.last_time = entry.time; } else { bottom_output(); if (!bottom_state.entry || entry.day != bottom_state.entry.day) { output_funcs.append(output_funcs.render_day_header(entry.day)); bottom_state.header_present = true; } if (bottom_state.entry && entry.bootid != bottom_state.entry.bootid) output_funcs.append(output_funcs.render_reboot_separator()); start_new_line(); bottom_state.entry = entry; bottom_state.count = 1; bottom_state.first_time = bottom_state.last_time = entry.time; bottom_state.line_present = false; } } function append_flush() { bottom_output(); } return { prepend: prepend, prepend_flush: prepend_flush, append: append, append_flush: append_flush }; }; journal.logbox = function logbox(match, max_entries) { var entries = []; var box = document.createElement("div"); function render() { var renderer = journal.renderer(box); while (box.firstChild) box.removeChild(box.firstChild); for (var i = 0; i < entries.length; i++) { renderer.prepend(entries[i]); } renderer.prepend_flush(); if (entries.length === 0) { const empty_message = document.createElement("span"); empty_message.textContent = _("No log entries"); empty_message.setAttribute("class", "empty-message"); box.appendChild(empty_message); } } render(); var promise = journal.journalctl(match, { count: max_entries }) .stream(function(tail) { entries = entries.concat(tail); if (entries.length > max_entries) entries = entries.slice(-max_entries); render(); }) .fail(function(error) { box.appendChild(document.createTextNode(error.message)); box.removeAttribute("hidden"); }); /* Both a DOM element and a promise */ return promise.promise(box); };
cockpituous/cockpit
pkg/lib/journal.js
JavaScript
lgpl-2.1
19,214
package sdljavax.gfx; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import sdljava.SDLException; import sdljava.SDLMain; import sdljava.SDLTimer; import sdljava.event.SDLEvent; import sdljava.video.SDLSurface; import sdljava.video.SDLVideo; import sdljavax.gfx.SDLGfx; /** * Framerate manager from SDL_gfx library test Class * <P> * * @author Bart LEBOEUF * @version $Id: SDLGfxFramerateTest.java,v 1.1 2005/02/18 03:16:46 doc_alton Exp $ */ public class SDLGfxFramerateTest { private int i, rate, x, y, dx, dy, r, g, b; private SDLSurface screen = null; private FPSmanager fpsm = null; private static SecureRandom sr = null; private final static String TITLE = "SDLGFX framerate test - "; static { try { sr = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { } } public SDLGfxFramerateTest() { fpsm = new FPSmanager(); sdl_init(800, 600, 32, (long) SDLVideo.SDL_HWSURFACE | SDLVideo.SDL_DOUBLEBUF); } public void sdl_init(int X, int Y, int bbp, long flags) { // Initialize SDL's subsystems - in this case, only video. try { SDLMain.init(SDLMain.SDL_INIT_VIDEO); } catch (SDLException e) { System.err.println("Unable initialize SDL: " + SDLMain.getError()); System.exit(1); } try { // Attempt to create a window with 32bit pixels. screen = SDLVideo.setVideoMode(X, Y, bbp, flags); } catch (SDLException se) { System.err.println("Unable to set video: " + SDLMain.getError()); System.exit(1); } try { init(); } catch (SDLException e2) { System.err.println("Unable to initialize : " + SDLMain.getError()); System.exit(1); } } public void destroy() { SDLMain.quit(); System.exit(0); } protected void work() { // Main loop: loop forever. while (true) { try { // Render stuff render(); } catch (SDLException e1) { System.err.println("Error while rendering : " + SDLMain.getError()); System.exit(1); } try { // Poll for events, and handle the ones we care about. SDLEvent event = SDLEvent.pollEvent(); if (event != null) eventOccurred(event); else try { SDLTimer.delay(50); } catch (InterruptedException e) { } } catch (SDLException se) { System.err.println("Error while polling event : " + SDLMain.getError()); System.exit(1); } } } public static void main(String[] args) { SDLGfxFramerateTest j = null; try { j = new SDLGfxFramerateTest(); j.work(); } finally { j.destroy(); } } void init() throws SDLException { i = 0; x = screen.getWidth() / 2; y = screen.getHeight() / 2; dx = 7; dy = 5; r = g = b = 255; fpsm.initFramerate(); } void render() throws SDLException { while (true) { /* Set/switch framerate */ i -= 1; if (i < 0) { /* Set new rate */ rate = 5 + 5 * (rand() % 10); fpsm.setFramerate(rate); System.out.println("\nFramerate set to " + rate + "Hz ..."); SDLVideo.wmSetCaption(TITLE + "Framerate set to " + rate + "Hz ...", null); /* New timeout */ i = 2 * rate; /* New Color */ r = rand() & 255; g = rand() & 255; b = rand() & 255; } /* Black screen */ screen.fillRect(SDLVideo.mapRGB(screen.getFormat(), 0, 0, 0)); /* Move */ x += dx; y += dy; /* Reflect */ if ((x < 0) || (x > screen.getWidth())) { dx = -dx; } if ((y < 0) || (y > screen.getHeight())) { dy = -dy; } /* Draw */ SDLGfx.filledCircleRGBA(screen, x, y, 30, r, g, b, 255); SDLGfx.circleRGBA(screen, x, y, 30, 255, 255, 255, 255); /* Display by flipping screens */ screen.updateRect(); /* Delay to fix rate */ fpsm.framerateDelay(); } } public void eventOccurred(SDLEvent event) { if (event == null) return; switch (event.getType()) { case SDLEvent.SDL_QUIT: destroy(); } } protected int rand() { int i; for (i = sr.nextInt(Integer.MAX_VALUE); i <= 0;) ; return i; } }
MyOwnClone/sdljava-osx-port
testsrc/sdljavax/gfx/SDLGfxFramerateTest.java
Java
lgpl-2.1
3,991
package fr.toss.FF7itemsj; public class itemj175 extends FF7itemsjbase { public itemj175(int id) { super(id); setUnlocalizedName("itemj175"); } }
GhostMonk3408/MidgarCrusade
src/main/java/fr/toss/FF7itemsj/itemj175.java
Java
lgpl-2.1
159
<?php /* * OGetIt, a open source PHP library for handling the new OGame API as of version 6. * Copyright (C) 2015 Klaas Van Parys * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ namespace OGetIt\Technology\Entity\Building; use OGetIt\Technology\TechnologyEconomy; class MissileSilo extends TechnologyEconomy { const TYPE = 44; const METAL = 20000, CRYSTAL = 20000, DEUTERIUM = 1000; public function __construct() { parent::__construct(self::TYPE, self::METAL, self::CRYSTAL, self::DEUTERIUM); } }
Warsaalk/OGetIt
src/OGetIt/Technology/Entity/Building/MissileSilo.php
PHP
lgpl-2.1
1,260
package soot.jimple.toolkits.annotation.methods; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import soot.G; import soot.Scene; import soot.SceneTransformer; import soot.Singletons; import soot.SootClass; import soot.SootMethod; import soot.tagkit.ColorTag; import soot.tagkit.StringTag; /** A scene transformer that adds tags to unused methods. */ public class UnreachableMethodsTagger extends SceneTransformer { public UnreachableMethodsTagger(Singletons.Global g) { } public static UnreachableMethodsTagger v() { return G.v().soot_jimple_toolkits_annotation_methods_UnreachableMethodsTagger(); } protected void internalTransform(String phaseName, Map options) { // make list of all unreachable methods ArrayList<SootMethod> methodList = new ArrayList<SootMethod>(); Iterator getClassesIt = Scene.v().getApplicationClasses().iterator(); while (getClassesIt.hasNext()) { SootClass appClass = (SootClass) getClassesIt.next(); Iterator getMethodsIt = appClass.getMethods().iterator(); while (getMethodsIt.hasNext()) { SootMethod method = (SootMethod) getMethodsIt.next(); // System.out.println("adding method: "+method); if (!Scene.v().getReachableMethods().contains(method)) { methodList.add(method); } } } // tag unused methods Iterator<SootMethod> unusedIt = methodList.iterator(); while (unusedIt.hasNext()) { SootMethod unusedMethod = unusedIt.next(); unusedMethod.addTag(new StringTag("Method " + unusedMethod.getName() + " is not reachable!", "Unreachable Methods")); unusedMethod.addTag(new ColorTag(255, 0, 0, true, "Unreachable Methods")); // System.out.println("tagged method: "+unusedMethod); } } }
plast-lab/soot
src/main/java/soot/jimple/toolkits/annotation/methods/UnreachableMethodsTagger.java
Java
lgpl-2.1
2,595
############################################################################ # # Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). # Contact: http://www.qt-project.org/legal # # This file is part of Qt Creator. # # Commercial License Usage # Licensees holding valid commercial Qt licenses may use this file in # accordance with the commercial license agreement provided with the # Software or, alternatively, in accordance with the terms contained in # a written agreement between you and Digia. For licensing terms and # conditions see http://qt.digia.com/licensing. For further information # use the contact form at http://qt.digia.com/contact-us. # # GNU Lesser General Public License Usage # Alternatively, this file may be used under the terms of the GNU Lesser # General Public License version 2.1 as published by the Free Software # Foundation and appearing in the file LICENSE.LGPL included in the # packaging of this file. Please review the following information to # ensure the GNU Lesser General Public License version 2.1 requirements # will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. # # In addition, as a special exception, Digia gives you certain additional # rights. These rights are described in the Digia Qt LGPL Exception # version 1.1, included in the file LGPL_EXCEPTION.txt in this package. # ############################################################################ import os import sys import base64 if sys.version_info[0] >= 3: xrange = range toInteger = int else: toInteger = long verbosity = 0 verbosity = 1 def hasPlot(): fileName = "/usr/bin/gnuplot" return os.path.isfile(fileName) and os.access(fileName, os.X_OK) try: import subprocess def arrayForms(): if hasPlot(): return "Normal,Plot" return "Normal" except: def arrayForms(): return "Normal" def bytesToString(b): if sys.version_info[0] == 2: return b return b.decode("utf8") def stringToBytes(s): if sys.version_info[0] == 2: return s return s.encode("utf8") # Base 16 decoding operating on string->string def b16decode(s): return bytesToString(base64.b16decode(stringToBytes(s), True)) # Base 16 decoding operating on string->string def b16encode(s): return bytesToString(base64.b16encode(stringToBytes(s))) # Base 64 decoding operating on string->string def b64decode(s): return bytesToString(base64.b64decode(stringToBytes(s))) # Base 64 decoding operating on string->string def b64encode(s): return bytesToString(base64.b64encode(stringToBytes(s))) # # Gnuplot based display for array-like structures. # gnuplotPipe = {} gnuplotPid = {} def warn(message): print("XXX: %s\n" % message.encode("latin1")) def showException(msg, exType, exValue, exTraceback): warn("**** CAUGHT EXCEPTION: %s ****" % msg) try: import traceback for line in traceback.format_exception(exType, exValue, exTraceback): warn("%s" % line) except: pass def stripClassTag(typeName): if typeName.startswith("class "): return typeName[6:] if typeName.startswith("struct "): return typeName[7:] if typeName.startswith("const "): return typeName[6:] if typeName.startswith("volatile "): return typeName[9:] return typeName class Children: def __init__(self, d, numChild = 1, childType = None, childNumChild = None, maxNumChild = None, addrBase = None, addrStep = None): self.d = d self.numChild = numChild self.childNumChild = childNumChild self.maxNumChild = maxNumChild self.addrBase = addrBase self.addrStep = addrStep self.printsAddress = True if childType is None: self.childType = None else: self.childType = stripClassTag(str(childType)) self.d.put('childtype="%s",' % self.childType) if childNumChild is None: pass #if self.d.isSimpleType(childType): # self.d.put('childnumchild="0",') # self.childNumChild = 0 #elif childType.code == PointerCode: # self.d.put('childnumchild="1",') # self.childNumChild = 1 else: self.d.put('childnumchild="%s",' % childNumChild) self.childNumChild = childNumChild try: if not addrBase is None and not addrStep is None: self.d.put('addrbase="0x%x",' % toInteger(addrBase)) self.d.put('addrstep="0x%x",' % toInteger(addrStep)) self.printsAddress = False except: warn("ADDRBASE: %s" % addrBase) warn("ADDRSTEP: %s" % addrStep) #warn("CHILDREN: %s %s %s" % (numChild, childType, childNumChild)) def __enter__(self): self.savedChildType = self.d.currentChildType self.savedChildNumChild = self.d.currentChildNumChild self.savedNumChild = self.d.currentNumChild self.savedMaxNumChild = self.d.currentMaxNumChild self.savedPrintsAddress = self.d.currentPrintsAddress self.d.currentChildType = self.childType self.d.currentChildNumChild = self.childNumChild self.d.currentNumChild = self.numChild self.d.currentMaxNumChild = self.maxNumChild self.d.currentPrintsAddress = self.printsAddress self.d.put("children=[") def __exit__(self, exType, exValue, exTraceBack): if not exType is None: if self.d.passExceptions: showException("CHILDREN", exType, exValue, exTraceBack) self.d.putNumChild(0) self.d.putValue("<not accessible>") if not self.d.currentMaxNumChild is None: if self.d.currentMaxNumChild < self.d.currentNumChild: self.d.put('{name="<incomplete>",value="",type="",numchild="0"},') self.d.currentChildType = self.savedChildType self.d.currentChildNumChild = self.savedChildNumChild self.d.currentNumChild = self.savedNumChild self.d.currentMaxNumChild = self.savedMaxNumChild self.d.currentPrintsAddress = self.savedPrintsAddress self.d.put('],') return True class SubItem: def __init__(self, d, component): self.d = d self.name = component self.iname = None def __enter__(self): self.d.enterSubItem(self) def __exit__(self, exType, exValue, exTraceBack): return self.d.exitSubItem(self, exType, exValue, exTraceBack) class NoAddress: def __init__(self, d): self.d = d def __enter__(self): self.savedPrintsAddress = self.d.currentPrintsAddress self.d.currentPrintsAddress = False def __exit__(self, exType, exValue, exTraceBack): self.d.currentPrintsAddress = self.savedPrintsAddress class TopLevelItem(SubItem): def __init__(self, d, iname): self.d = d self.iname = iname self.name = None class UnnamedSubItem(SubItem): def __init__(self, d, component): self.d = d self.iname = "%s.%s" % (self.d.currentIName, component) self.name = None class DumperBase: def __init__(self): self.isCdb = False self.isGdb = False self.isLldb = False # Later set, or not set: # cachedQtVersion self.stringCutOff = 10000 # This is a cache mapping from 'type name' to 'display alternatives'. self.qqFormats = {} # This is a cache of all known dumpers. self.qqDumpers = {} # This is a cache of all dumpers that support writing. self.qqEditable = {} # This keeps canonical forms of the typenames, without array indices etc. self.cachedFormats = {} def stripForFormat(self, typeName): if typeName in self.cachedFormats: return self.cachedFormats[typeName] stripped = "" inArray = 0 for c in stripClassTag(typeName): if c == '<': break if c == ' ': continue if c == '[': inArray += 1 elif c == ']': inArray -= 1 if inArray and ord(c) >= 48 and ord(c) <= 57: continue stripped += c self.cachedFormats[typeName] = stripped return stripped def is32bit(self): return self.ptrSize() == 4 def computeLimit(self, size, limit): if limit is None: return size if limit == 0: return min(size, self.stringCutOff) return min(size, limit) def byteArrayDataHelper(self, addr): if self.qtVersion() >= 0x050000: # QTypedArray: # - QtPrivate::RefCount ref # - int size # - uint alloc : 31, capacityReserved : 1 # - qptrdiff offset size = self.extractInt(addr + 4) alloc = self.extractInt(addr + 8) & 0x7ffffff data = addr + self.dereference(addr + 8 + self.ptrSize()) if self.ptrSize() == 4: data = data & 0xffffffff else: data = data & 0xffffffffffffffff else: # Data: # - QBasicAtomicInt ref; # - int alloc, size; # - [padding] # - char *data; alloc = self.extractInt(addr + 4) size = self.extractInt(addr + 8) data = self.dereference(addr + 8 + self.ptrSize()) return data, size, alloc # addr is the begin of a QByteArrayData structure def encodeStringHelper(self, addr, limit = 0): # Should not happen, but we get it with LLDB as result # of inferior calls if addr == 0: return "" data, size, alloc = self.byteArrayDataHelper(addr) if alloc != 0: self.check(0 <= size and size <= alloc and alloc <= 100*1000*1000) limit = self.computeLimit(size, limit) s = self.readMemory(data, 2 * limit) if limit < size: s += "2e002e002e00" return s def encodeByteArrayHelper(self, addr, limit = None): data, size, alloc = self.byteArrayDataHelper(addr) if alloc != 0: self.check(0 <= size and size <= alloc and alloc <= 100*1000*1000) limit = self.computeLimit(size, limit) s = self.readMemory(data, limit) if limit < size: s += "2e2e2e" return s def encodeByteArray(self, value): return self.encodeByteArrayHelper(self.dereferenceValue(value)) def byteArrayData(self, value): return self.byteArrayDataHelper(self.dereferenceValue(value)) def putByteArrayValue(self, value): return self.putValue(self.encodeByteArray(value), Hex2EncodedLatin1) def putStringValueByAddress(self, addr): self.putValue(self.encodeStringHelper(self.dereference(addr)), Hex4EncodedLittleEndian) def encodeString(self, value): return self.encodeStringHelper(self.dereferenceValue(value)) def stringData(self, value): return self.byteArrayDataHelper(self.dereferenceValue(value)) def extractTemplateArgument(self, typename, position): level = 0 skipSpace = False inner = '' for c in typename[typename.find('<') + 1 : -1]: if c == '<': inner += c level += 1 elif c == '>': level -= 1 inner += c elif c == ',': if level == 0: if position == 0: return inner.strip() position -= 1 inner = '' else: inner += c skipSpace = True else: if skipSpace and c == ' ': pass else: inner += c skipSpace = False return inner.strip() def putStringValue(self, value): return self.putValue(self.encodeString(value), Hex4EncodedLittleEndian) def putAddressItem(self, name, value, type = ""): with SubItem(self, name): self.putValue("0x%x" % value) self.putType(type) self.putNumChild(0) def putIntItem(self, name, value): with SubItem(self, name): self.putValue(value) self.putType("int") self.putNumChild(0) def putBoolItem(self, name, value): with SubItem(self, name): self.putValue(value) self.putType("bool") self.putNumChild(0) def putGenericItem(self, name, type, value, encoding = None): with SubItem(self, name): self.putValue(value, encoding) self.putType(type) self.putNumChild(0) def putMapName(self, value): ns = self.qtNamespace() if str(value.type) == ns + "QString": self.put('key="%s",' % self.encodeString(value)) self.put('keyencoded="%s",' % Hex4EncodedLittleEndian) elif str(value.type) == ns + "QByteArray": self.put('key="%s",' % self.encodeByteArray(value)) self.put('keyencoded="%s",' % Hex2EncodedLatin1) else: if self.isLldb: self.put('name="%s",' % value.GetValue()) else: self.put('name="%s",' % value) def isMapCompact(self, keyType, valueType): format = self.currentItemFormat() if format == 2: return True # Compact. return self.isSimpleType(keyType) and self.isSimpleType(valueType) def check(self, exp): if not exp: raise RuntimeError("Check failed") def checkRef(self, ref): try: count = int(ref["atomic"]["_q_value"]) # Qt 5. minimum = -1 except: count = int(ref["_q_value"]) # Qt 4. minimum = 0 # Assume there aren't a million references to any object. self.check(count >= minimum) self.check(count < 1000000) def findFirstZero(self, p, maximum): for i in xrange(maximum): if int(p.dereference()) == 0: return i p = p + 1 return maximum + 1 def encodeCArray(self, p, innerType, suffix): t = self.lookupType(innerType) p = p.cast(t.pointer()) limit = self.findFirstZero(p, self.stringCutOff) s = self.readMemory(p, limit * t.sizeof) if limit > self.stringCutOff: s += suffix return s def encodeCharArray(self, p): return self.encodeCArray(p, "unsigned char", "2e2e2e") def encodeChar2Array(self, p): return self.encodeCArray(p, "unsigned short", "2e002e002e00") def encodeChar4Array(self, p): return self.encodeCArray(p, "unsigned int", "2e0000002e0000002e000000") def putItemCount(self, count, maximum = 1000000000): # This needs to override the default value, so don't use 'put' directly. if count > maximum: self.putValue('<>%s items>' % maximum) else: self.putValue('<%s items>' % count) def putNoType(self): # FIXME: replace with something that does not need special handling # in SubItem.__exit__(). self.putBetterType(" ") def putInaccessible(self): #self.putBetterType(" ") self.putNumChild(0) self.currentValue = None def putQObjectNameValue(self, value): try: intSize = self.intSize() ptrSize = self.ptrSize() # dd = value["d_ptr"]["d"] is just behind the vtable. dd = self.dereference(self.addressOf(value) + ptrSize) if self.qtVersion() < 0x050000: # Size of QObjectData: 5 pointer + 2 int # - vtable # - QObject *q_ptr; # - QObject *parent; # - QObjectList children; # - uint isWidget : 1; etc.. # - int postedEvents; # - QMetaObject *metaObject; # Offset of objectName in QObjectPrivate: 5 pointer + 2 int # - [QObjectData base] # - QString objectName objectName = self.dereference(dd + 5 * ptrSize + 2 * intSize) else: # Size of QObjectData: 5 pointer + 2 int # - vtable # - QObject *q_ptr; # - QObject *parent; # - QObjectList children; # - uint isWidget : 1; etc... # - int postedEvents; # - QDynamicMetaObjectData *metaObject; extra = self.dereference(dd + 5 * ptrSize + 2 * intSize) if extra == 0: return False # Offset of objectName in ExtraData: 6 pointer # - QVector<QObjectUserData *> userData; only #ifndef QT_NO_USERDATA # - QList<QByteArray> propertyNames; # - QList<QVariant> propertyValues; # - QVector<int> runningTimers; # - QList<QPointer<QObject> > eventFilters; # - QString objectName objectName = self.dereference(extra + 5 * ptrSize) data, size, alloc = self.byteArrayDataHelper(objectName) if size == 0: return False str = self.readMemory(data, 2 * size) self.putValue(str, Hex4EncodedLittleEndian, 1) return True except: pass def isKnownMovableType(self, type): if type in ( "QBrush", "QBitArray", "QByteArray", "QCustomTypeInfo", "QChar", "QDate", "QDateTime", "QFileInfo", "QFixed", "QFixedPoint", "QFixedSize", "QHashDummyValue", "QIcon", "QImage", "QLine", "QLineF", "QLatin1Char", "QLocale", "QMatrix", "QModelIndex", "QPoint", "QPointF", "QPen", "QPersistentModelIndex", "QResourceRoot", "QRect", "QRectF", "QRegExp", "QSize", "QSizeF", "QString", "QTime", "QTextBlock", "QUrl", "QVariant", "QXmlStreamAttribute", "QXmlStreamNamespaceDeclaration", "QXmlStreamNotationDeclaration", "QXmlStreamEntityDeclaration" ): return True return type == "QStringList" and self.qtVersion() >= 0x050000 def currentItemFormat(self, type = None): format = self.formats.get(self.currentIName) if format is None: if type is None: type = self.currentType needle = self.stripForFormat(str(type)) format = self.typeformats.get(needle) return format def cleanAddress(addr): if addr is None: return "<no address>" # We cannot use str(addr) as it yields rubbish for char pointers # that might trigger Unicode encoding errors. #return addr.cast(lookupType("void").pointer()) # We do not use "hex(...)" as it (sometimes?) adds a "L" suffix. return "0x%x" % toInteger(addr) # Some "Enums" # Encodings. Keep that synchronized with DebuggerEncoding in debuggerprotocol.h Unencoded8Bit, \ Base64Encoded8BitWithQuotes, \ Base64Encoded16BitWithQuotes, \ Base64Encoded32BitWithQuotes, \ Base64Encoded16Bit, \ Base64Encoded8Bit, \ Hex2EncodedLatin1, \ Hex4EncodedLittleEndian, \ Hex8EncodedLittleEndian, \ Hex2EncodedUtf8, \ Hex8EncodedBigEndian, \ Hex4EncodedBigEndian, \ Hex4EncodedLittleEndianWithoutQuotes, \ Hex2EncodedLocal8Bit, \ JulianDate, \ MillisecondsSinceMidnight, \ JulianDateAndMillisecondsSinceMidnight, \ Hex2EncodedInt1, \ Hex2EncodedInt2, \ Hex2EncodedInt4, \ Hex2EncodedInt8, \ Hex2EncodedUInt1, \ Hex2EncodedUInt2, \ Hex2EncodedUInt4, \ Hex2EncodedUInt8, \ Hex2EncodedFloat4, \ Hex2EncodedFloat8, \ IPv6AddressAndHexScopeId, \ Hex2EncodedUtf8WithoutQuotes, \ MillisecondsSinceEpoch \ = range(30) # Display modes. Keep that synchronized with DebuggerDisplay in watchutils.h StopDisplay, \ DisplayImageData, \ DisplayUtf16String, \ DisplayImageFile, \ DisplayProcess, \ DisplayLatin1String, \ DisplayUtf8String \ = range(7) def mapForms(): return "Normal,Compact" def arrayForms(): if hasPlot(): return "Normal,Plot" return "Normal"
richardmg/qtcreator
share/qtcreator/debugger/dumper.py
Python
lgpl-2.1
20,529
/* * Created on 17-dic-2005 * */ package org.herac.tuxguitar.gui.actions.composition; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.TypedEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.herac.tuxguitar.gui.TuxGuitar; import org.herac.tuxguitar.gui.actions.Action; import org.herac.tuxguitar.gui.actions.ActionLock; import org.herac.tuxguitar.gui.editors.tab.TGMeasureImpl; import org.herac.tuxguitar.gui.undo.undoables.custom.UndoableChangeKeySignature; import org.herac.tuxguitar.gui.util.DialogUtils; import org.herac.tuxguitar.gui.util.MessageDialog; import org.herac.tuxguitar.song.models.TGMeasure; import org.herac.tuxguitar.song.models.TGTrack; import org.herac.tuxguitar.util.TGSynchronizer; /** * @author julian * */ public class ChangeKeySignatureAction extends Action{ public static final String NAME = "action.composition.change-key-signature"; public ChangeKeySignatureAction() { super(NAME, AUTO_LOCK | AUTO_UNLOCK | AUTO_UPDATE | DISABLE_ON_PLAYING | KEY_BINDING_AVAILABLE); } protected int execute(TypedEvent e){ showDialog(getEditor().getTablature().getShell()); return 0; } public void showDialog(Shell shell) { TGMeasureImpl measure = getEditor().getTablature().getCaret().getMeasure(); if (measure != null) { final Shell dialog = DialogUtils.newDialog(shell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); dialog.setLayout(new GridLayout()); dialog.setText(TuxGuitar.getProperty("composition.keysignature")); //-------key Signature------------------------------------- Group keySignature = new Group(dialog,SWT.SHADOW_ETCHED_IN); keySignature.setLayout(new GridLayout(2,false)); keySignature.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,true)); keySignature.setText(TuxGuitar.getProperty("composition.keysignature")); Label numeratorLabel = new Label(keySignature, SWT.NULL); numeratorLabel.setText(TuxGuitar.getProperty("composition.keysignature") + ":"); final Combo keySignatures = new Combo(keySignature, SWT.DROP_DOWN | SWT.READ_ONLY); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.natural")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.sharp-1")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.sharp-2")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.sharp-3")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.sharp-4")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.sharp-5")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.sharp-6")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.sharp-7")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.flat-1")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.flat-2")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.flat-3")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.flat-4")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.flat-5")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.flat-6")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.flat-7")); keySignatures.select(measure.getKeySignature()); keySignatures.setLayoutData(getComboData()); //--------------------To End Checkbox------------------------------- Group check = new Group(dialog,SWT.SHADOW_ETCHED_IN); check.setLayout(new GridLayout()); check.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,true)); check.setText(TuxGuitar.getProperty("options")); final Button toEnd = new Button(check, SWT.CHECK); toEnd.setText(TuxGuitar.getProperty("composition.keysignature.to-the-end")); toEnd.setSelection(true); //------------------BUTTONS-------------------------- Composite buttons = new Composite(dialog, SWT.NONE); buttons.setLayout(new GridLayout(2,false)); buttons.setLayoutData(new GridData(SWT.END,SWT.FILL,true,true)); final Button buttonOK = new Button(buttons, SWT.PUSH); buttonOK.setText(TuxGuitar.getProperty("ok")); buttonOK.setLayoutData(getButtonData()); buttonOK.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { final boolean toEndValue = toEnd.getSelection(); final int keySignature = keySignatures.getSelectionIndex(); dialog.dispose(); try { TGSynchronizer.instance().runLater(new TGSynchronizer.TGRunnable() { public void run() throws Throwable { ActionLock.lock(); TuxGuitar.instance().loadCursor(SWT.CURSOR_WAIT); setKeySignature(keySignature,toEndValue); TuxGuitar.instance().updateCache( true ); TuxGuitar.instance().loadCursor(SWT.CURSOR_ARROW); ActionLock.unlock(); } }); } catch (Throwable throwable) { MessageDialog.errorMessage(throwable); } } }); Button buttonCancel = new Button(buttons, SWT.PUSH); buttonCancel.setText(TuxGuitar.getProperty("cancel")); buttonCancel.setLayoutData(getButtonData()); buttonCancel.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { dialog.dispose(); } }); dialog.setDefaultButton( buttonOK ); DialogUtils.openDialog(dialog,DialogUtils.OPEN_STYLE_CENTER | DialogUtils.OPEN_STYLE_PACK | DialogUtils.OPEN_STYLE_WAIT); } } private GridData getButtonData(){ GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); data.minimumWidth = 80; data.minimumHeight = 25; return data; } private GridData getComboData(){ GridData data = new GridData(SWT.FILL,SWT.FILL,true,true); data.minimumWidth = 150; return data; } protected void setKeySignature(int keySignature,boolean toEnd){ //comienza el undoable UndoableChangeKeySignature undoable = UndoableChangeKeySignature.startUndo(); TGMeasure measure = getEditor().getTablature().getCaret().getMeasure(); TGTrack track = getEditor().getTablature().getCaret().getTrack(); getSongManager().getTrackManager().changeKeySignature(track,measure.getStart(),keySignature,toEnd); TuxGuitar.instance().getFileHistory().setUnsavedFile(); //actualizo la tablatura updateTablature(); //termia el undoable addUndoableEdit(undoable.endUndo(keySignature,toEnd)); } }
elkafoury/tux
src/org/herac/tuxguitar/gui/actions/composition/ChangeKeySignatureAction.java
Java
lgpl-2.1
6,797
/* * This file is part of libbluray * Copyright (C) 2012 libbluray * Copyright (C) 2012-2014 Petri Hintukainen <phintuka@users.sourceforge.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see * <http://www.gnu.org/licenses/>. */ package java.awt; import java.awt.image.ColorModel; import java.awt.image.ImageObserver; import java.awt.image.ImageProducer; import java.io.File; import java.net.URL; import java.util.Collections; import java.util.Hashtable; import java.util.WeakHashMap; import java.util.Map; import java.util.Iterator; import sun.awt.image.ByteArrayImageSource; import sun.awt.image.FileImageSource; import sun.awt.image.URLImageSource; import org.videolan.BDJXletContext; import org.videolan.Logger; abstract class BDToolkitBase extends Toolkit { private EventQueue eventQueue = new EventQueue(); private BDGraphicsEnvironment localEnv = new BDGraphicsEnvironment(); private BDGraphicsConfiguration defaultGC = (BDGraphicsConfiguration)localEnv.getDefaultScreenDevice().getDefaultConfiguration(); private static Hashtable cachedImages = new Hashtable(); private static final Logger logger = Logger.getLogger(BDToolkit.class.getName()); // mapping of Components to AppContexts, WeakHashMap<Component,AppContext> private static final Map contextMap = Collections.synchronizedMap(new WeakHashMap()); public BDToolkitBase () { } public static void setFocusedWindow(Window window) { } public static void shutdownDisc() { try { Toolkit toolkit = getDefaultToolkit(); if (toolkit instanceof BDToolkit) { ((BDToolkit)toolkit).shutdown(); } } catch (Throwable t) { logger.error("shutdownDisc() failed: " + t + "\n" + Logger.dumpStack(t)); } } protected void shutdown() { /* if (eventQueue != null) { BDJHelper.stopEventQueue(eventQueue); eventQueue = null; } */ cachedImages.clear(); contextMap.clear(); } public Dimension getScreenSize() { Rectangle dims = defaultGC.getBounds(); return new Dimension(dims.width, dims.height); } Graphics getGraphics(Window window) { if (!(window instanceof BDRootWindow)) { logger.error("getGraphics(): not BDRootWindow"); throw new Error("Not implemented"); } return new BDWindowGraphics((BDRootWindow)window); } GraphicsEnvironment getLocalGraphicsEnvironment() { return localEnv; } public int getScreenResolution() { return 72; } public ColorModel getColorModel() { return defaultGC.getColorModel(); } public String[] getFontList() { return BDFontMetrics.getFontList(); } public FontMetrics getFontMetrics(Font font) { return BDFontMetrics.getFontMetrics(font); } static void clearCache(BDImage image) { synchronized (cachedImages) { Iterator i = cachedImages.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); if (entry.getValue() == image) { i.remove(); return; } } } } public Image getImage(String filename) { if (BDJXletContext.getCurrentContext() == null) { logger.error("getImage(): no context " + Logger.dumpStack()); } if (cachedImages.containsKey(filename)) return (Image)cachedImages.get(filename); Image newImage = createImage(filename); if (newImage != null) cachedImages.put(filename, newImage); return newImage; } public Image getImage(URL url) { if (BDJXletContext.getCurrentContext() == null) { logger.error("getImage(): no context " + Logger.dumpStack()); } if (cachedImages.containsKey(url)) return (Image)cachedImages.get(url); Image newImage = createImage(url); if (newImage != null) cachedImages.put(url, newImage); return newImage; } public Image createImage(String filename) { if (BDJXletContext.getCurrentContext() == null) { logger.error("createImage(): no context " + Logger.dumpStack()); } if (!new File(filename).isAbsolute()) { String home = BDJXletContext.getCurrentXletHome(); if (home != null) { String homeFile = home + filename; if (new File(homeFile).exists()) { logger.warning("resource translated to " + homeFile); filename = homeFile; } else { logger.error("resource " + homeFile + " does not exist"); } } } ImageProducer ip = new FileImageSource(filename); Image newImage = createImage(ip); return newImage; } public Image createImage(URL url) { if (BDJXletContext.getCurrentContext() == null) { logger.error("createImage(): no context " + Logger.dumpStack()); } ImageProducer ip = new URLImageSource(url); Image newImage = createImage(ip); return newImage; } public Image createImage(byte[] imagedata, int imageoffset, int imagelength) { if (BDJXletContext.getCurrentContext() == null) { logger.error("createImage(): no context " + Logger.dumpStack()); } ImageProducer ip = new ByteArrayImageSource(imagedata, imageoffset, imagelength); Image newImage = createImage(ip); return newImage; } public Image createImage(ImageProducer producer) { if (BDJXletContext.getCurrentContext() == null) { logger.error("createImage(): no context " + Logger.dumpStack()); } return new BDImageConsumer(producer); } public Image createImage(Component component, int width, int height) { return new BDImage(component, width, height, defaultGC); } public boolean prepareImage(Image image, int width, int height, ImageObserver observer) { if (!(image instanceof BDImageConsumer)) return true; BDImageConsumer img = (BDImageConsumer)image; return img.prepareImage(observer); } public int checkImage(Image image, int width, int height, ImageObserver observer) { if (!(image instanceof BDImageConsumer)) { return ImageObserver.ALLBITS; } BDImageConsumer img = (BDImageConsumer)image; return img.checkImage(observer); } public void beep() { } public static void addComponent(Component component) { BDJXletContext context = BDJXletContext.getCurrentContext(); if (context == null) { logger.warning("addComponent() outside of app context"); return; } contextMap.put(component, context); } public static EventQueue getEventQueue(Component component) { if (component != null) { do { BDJXletContext ctx = (BDJXletContext)contextMap.get(component); if (ctx != null) { EventQueue eq = ctx.getEventQueue(); if (eq == null) { logger.warning("getEventQueue() failed: no context event queue"); } return eq; } component = component.getParent(); } while (component != null); logger.warning("getEventQueue() failed: no context"); return null; } logger.warning("getEventQueue() failed: no component"); return null; } protected EventQueue getSystemEventQueueImpl() { BDJXletContext ctx = BDJXletContext.getCurrentContext(); if (ctx != null) { EventQueue eq = ctx.getEventQueue(); if (eq != null) { return eq; } } logger.warning("getSystemEventQueue(): no context from:" + logger.dumpStack()); return eventQueue; } }
mwgoldsmith/bluray
src/libbluray/bdj/java/java/awt/BDToolkitBase.java
Java
lgpl-2.1
8,816
package com.Sackboy.TOM.init; import com.Sackboy.TOM.TOM; import com.Sackboy.TOM.mob.EntityCardboardBox; import com.Sackboy.TOM.mob.EntityCrawler; import com.Sackboy.TOM.mob.EntityJoiter; import net.minecraft.entity.EnumCreatureType; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.fml.common.registry.EntityRegistry; public class TOMMobs { // TODO: Finish up on mob AI and sizes public static void register() { createEntity(EntityCrawler.class, "Crawler", 0x175D5A, 0x9E1C1C); createEntity(EntityJoiter.class, "Joiter", 0x406533, 0xF38727); createEntity(EntityCardboardBox.class, "Cardboard Box", 0x406533, 0xF38727); } public static void createEntity(Class entity, String name, int solid, int spot) { int rand = EntityRegistry.findGlobalUniqueEntityId(); EntityRegistry.registerGlobalEntityID(entity, name, rand); EntityRegistry.registerModEntity(entity, name, rand, TOM.INSTANCE, 64, 1, false, solid, spot); EntityRegistry.addSpawn(entity, 10, 1, 2, EnumCreatureType.MONSTER, BiomeGenBase.getBiome(4)); } }
Sackboy132/TheOrdinaryMod
src/main/java/com/Sackboy/TOM/init/TOMMobs.java
Java
lgpl-2.1
1,060
// OO jDREW - An Object Oriented extension of the Java Deductive Reasoning Engine for the Web // Copyright (C) 2005 Marcel Ball // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA package org.ruleml.oojdrew.Builtins; import java.util.Vector; import org.ruleml.oojdrew.util.DefiniteClause; import org.ruleml.oojdrew.util.SymbolTable; import org.ruleml.oojdrew.util.Term; import org.ruleml.oojdrew.util.Types; /** * Implements a String Equal Ignore Case built-in relation. * * Calling format stringEqualIgnoreCase(?input1, ?input2). * * Satisfied iff the first argument is the same as the second * argument (upper/lower case ignored) * * <p>Title: OO jDREW</p> * * <p>Description: Reasoning Engine for the Semantic Web - Supporting OO RuleML * 0.88</p> * * <p>Copyright: Copyright (c) 2005</p> * * @author Marcel A. Ball * @version 0.89 */ public class StringEqualIgnoreCaseBuiltin implements Builtin { private int symbol = SymbolTable.internSymbol("stringEqualIgnoreCase"); public DefiniteClause buildResult(Term t) { if (t.getSymbol() != symbol) { return null; } if (t.subTerms.length != 3) { return null; } Term p1 = t.subTerms[1].deepCopy(); Term p2 = t.subTerms[2].deepCopy(); if (p1.getSymbol() < 0 || p2.getSymbol() < 0) { return null; } if (p1.getType() != Types.ISTRING || p2.getType() != Types.ISTRING) { return null; } String p1s = p1.getSymbolString(); String p2s = p2.getSymbolString(); if (!p1s.equalsIgnoreCase(p2s)) { return null; } Term roid = new Term(SymbolTable.internSymbol("$jdrew-strequalIC-" + p1s + "=" + p2s), SymbolTable.IOID, Types.ITHING); Vector v = new Vector(); v.add(roid); v.add(p1); v.add(p2); Term atm = new Term(symbol, SymbolTable.INOROLE, Types.IOBJECT, v); atm.setAtom(true); Vector v2 = new Vector(); v2.add(atm); return new DefiniteClause(v2, new Vector()); } public int getSymbol() { return symbol; } }
OOjDREW/OOjDREW
src/main/java/org/ruleml/oojdrew/Builtins/StringEqualIgnoreCaseBuiltin.java
Java
lgpl-2.1
3,031
#!/usr/bin/env python # -*- coding: utf-8 -*- # Authors: Chinmaya Pancholi <chinmayapancholi13@gmail.com>, Shiva Manne <s.manne@rare-technologies.com> # Copyright (C) 2017 RaRe Technologies s.r.o. """Learn word representations via fasttext's "skip-gram and CBOW models", using either hierarchical softmax or negative sampling [1]_. Notes ----- There are more ways to get word vectors in Gensim than just FastText. See wrappers for VarEmbed and WordRank or Word2Vec This module allows training a word embedding from a training corpus with the additional ability to obtain word vectors for out-of-vocabulary words. For a tutorial on gensim's native fasttext, refer to the noteboook -- [2]_ **Make sure you have a C compiler before installing gensim, to use optimized (compiled) fasttext training** .. [1] P. Bojanowski, E. Grave, A. Joulin, T. Mikolov Enriching Word Vectors with Subword Information. In arXiv preprint arXiv:1607.04606. https://arxiv.org/abs/1607.04606 .. [2] https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/FastText_Tutorial.ipynb """ import logging import numpy as np from numpy import zeros, ones, vstack, sum as np_sum, empty, float32 as REAL from gensim.models.word2vec import Word2Vec, train_sg_pair, train_cbow_pair from gensim.models.wrappers.fasttext import FastTextKeyedVectors from gensim.models.wrappers.fasttext import FastText as Ft_Wrapper, compute_ngrams, ft_hash logger = logging.getLogger(__name__) try: from gensim.models.fasttext_inner import train_batch_sg, train_batch_cbow from gensim.models.fasttext_inner import FAST_VERSION, MAX_WORDS_IN_BATCH logger.debug('Fast version of Fasttext is being used') except ImportError: # failed... fall back to plain numpy (20-80x slower training than the above) logger.warning('Slow version of Fasttext is being used') FAST_VERSION = -1 MAX_WORDS_IN_BATCH = 10000 def train_batch_cbow(model, sentences, alpha, work=None, neu1=None): """Update CBOW model by training on a sequence of sentences. Each sentence is a list of string tokens, which are looked up in the model's vocab dictionary. Called internally from :meth:`gensim.models.fasttext.FastText.train()`. This is the non-optimized, Python version. If you have cython installed, gensim will use the optimized version from fasttext_inner instead. Parameters ---------- model : :class:`~gensim.models.fasttext.FastText` `FastText` instance. sentences : iterable of iterables Iterable of the sentences directly from disk/network. alpha : float Learning rate. work : :class:`numpy.ndarray` Private working memory for each worker. neu1 : :class:`numpy.ndarray` Private working memory for each worker. Returns ------- int Effective number of words trained. """ result = 0 for sentence in sentences: word_vocabs = [model.wv.vocab[w] for w in sentence if w in model.wv.vocab and model.wv.vocab[w].sample_int > model.random.rand() * 2**32] for pos, word in enumerate(word_vocabs): reduced_window = model.random.randint(model.window) start = max(0, pos - model.window + reduced_window) window_pos = enumerate(word_vocabs[start:(pos + model.window + 1 - reduced_window)], start) word2_indices = [word2.index for pos2, word2 in window_pos if (word2 is not None and pos2 != pos)] word2_subwords = [] vocab_subwords_indices = [] ngrams_subwords_indices = [] for index in word2_indices: vocab_subwords_indices += [index] word2_subwords += model.wv.ngrams_word[model.wv.index2word[index]] for subword in word2_subwords: ngrams_subwords_indices.append(model.wv.ngrams[subword]) l1_vocab = np_sum(model.wv.syn0_vocab[vocab_subwords_indices], axis=0) # 1 x vector_size l1_ngrams = np_sum(model.wv.syn0_ngrams[ngrams_subwords_indices], axis=0) # 1 x vector_size l1 = np_sum([l1_vocab, l1_ngrams], axis=0) subwords_indices = [vocab_subwords_indices] + [ngrams_subwords_indices] if (subwords_indices[0] or subwords_indices[1]) and model.cbow_mean: l1 /= (len(subwords_indices[0]) + len(subwords_indices[1])) # train on the sliding window for target word train_cbow_pair(model, word, subwords_indices, l1, alpha, is_ft=True) result += len(word_vocabs) return result def train_batch_sg(model, sentences, alpha, work=None, neu1=None): """Update skip-gram model by training on a sequence of sentences. Each sentence is a list of string tokens, which are looked up in the model's vocab dictionary. Called internally from :meth:`gensim.models.fasttext.FastText.train()`. This is the non-optimized, Python version. If you have cython installed, gensim will use the optimized version from fasttext_inner instead. Parameters ---------- model : :class:`~gensim.models.fasttext.FastText` `FastText` instance. sentences : iterable of iterables Iterable of the sentences directly from disk/network. alpha : float Learning rate. work : :class:`numpy.ndarray` Private working memory for each worker. neu1 : :class:`numpy.ndarray` Private working memory for each worker. Returns ------- int Effective number of words trained. """ result = 0 for sentence in sentences: word_vocabs = [model.wv.vocab[w] for w in sentence if w in model.wv.vocab and model.wv.vocab[w].sample_int > model.random.rand() * 2**32] for pos, word in enumerate(word_vocabs): reduced_window = model.random.randint(model.window) # `b` in the original word2vec code # now go over all words from the (reduced) window, predicting each one in turn start = max(0, pos - model.window + reduced_window) subwords_indices = [word.index] word2_subwords = model.wv.ngrams_word[model.wv.index2word[word.index]] for subword in word2_subwords: subwords_indices.append(model.wv.ngrams[subword]) for pos2, word2 in enumerate(word_vocabs[start:(pos + model.window + 1 - reduced_window)], start): if pos2 != pos: # don't train on the `word` itself train_sg_pair(model, model.wv.index2word[word2.index], subwords_indices, alpha, is_ft=True) result += len(word_vocabs) return result class FastText(Word2Vec): """Class for training, using and evaluating word representations learned using method described in [1]_ aka Fasttext. The model can be stored/loaded via its :meth:`~gensim.models.fasttext.FastText.save()` and :meth:`~gensim.models.fasttext.FastText.load()` methods, or loaded in a format compatible with the original fasttext implementation via :meth:`~gensim.models.fasttext.FastText.load_fasttext_format()`. """ def __init__( self, sentences=None, sg=0, hs=0, size=100, alpha=0.025, window=5, min_count=5, max_vocab_size=None, word_ngrams=1, sample=1e-3, seed=1, workers=3, min_alpha=0.0001, negative=5, cbow_mean=1, hashfxn=hash, iter=5, null_word=0, min_n=3, max_n=6, sorted_vocab=1, bucket=2000000, trim_rule=None, batch_words=MAX_WORDS_IN_BATCH): """Initialize the model from an iterable of `sentences`. Each sentence is a list of words (unicode strings) that will be used for training. Parameters ---------- sentences : iterable of iterables The `sentences` iterable can be simply a list of lists of tokens, but for larger corpora, consider an iterable that streams the sentences directly from disk/network. See :class:`~gensim.models.word2vec.BrownCorpus`, :class:`~gensim.models.word2vec.Text8Corpus` or :class:`~gensim.models.word2vec.LineSentence` in :mod:`~gensim.models.word2vec` module for such examples. If you don't supply `sentences`, the model is left uninitialized -- use if you plan to initialize it in some other way. sg : int {1, 0} Defines the training algorithm. If 1, CBOW is used, otherwise, skip-gram is employed. size : int Dimensionality of the feature vectors. window : int The maximum distance between the current and predicted word within a sentence. alpha : float The initial learning rate. min_alpha : float Learning rate will linearly drop to `min_alpha` as training progresses. seed : int Seed for the random number generator. Initial vectors for each word are seeded with a hash of the concatenation of word + `str(seed)`. Note that for a fully deterministically-reproducible run, you must also limit the model to a single worker thread (`workers=1`), to eliminate ordering jitter from OS thread scheduling. (In Python 3, reproducibility between interpreter launches also requires use of the `PYTHONHASHSEED` environment variable to control hash randomization). min_count : int Ignores all words with total frequency lower than this. max_vocab_size : int Limits the RAM during vocabulary building; if there are more unique words than this, then prune the infrequent ones. Every 10 million word types need about 1GB of RAM. Set to `None` for no limit. sample : float The threshold for configuring which higher-frequency words are randomly downsampled, useful range is (0, 1e-5). workers : int Use these many worker threads to train the model (=faster training with multicore machines). hs : int {1,0} If 1, hierarchical softmax will be used for model training. If set to 0, and `negative` is non-zero, negative sampling will be used. negative : int If > 0, negative sampling will be used, the int for negative specifies how many "noise words" should be drawn (usually between 5-20). If set to 0, no negative sampling is used. cbow_mean : int {1,0} If 0, use the sum of the context word vectors. If 1, use the mean, only applies when cbow is used. hashfxn : function Hash function to use to randomly initialize weights, for increased training reproducibility. iter : int Number of iterations (epochs) over the corpus. trim_rule : function Vocabulary trimming rule, specifies whether certain words should remain in the vocabulary, be trimmed away, or handled using the default (discard if word count < min_count). Can be None (min_count will be used, look to :func:`~gensim.utils.keep_vocab_item`), or a callable that accepts parameters (word, count, min_count) and returns either :attr:`gensim.utils.RULE_DISCARD`, :attr:`gensim.utils.RULE_KEEP` or :attr:`gensim.utils.RULE_DEFAULT`. Note: The rule, if given, is only used to prune vocabulary during build_vocab() and is not stored as part of the model. sorted_vocab : int {1,0} If 1, sort the vocabulary by descending frequency before assigning word indexes. batch_words : int Target size (in words) for batches of examples passed to worker threads (and thus cython routines).(Larger batches will be passed if individual texts are longer than 10000 words, but the standard cython code truncates to that maximum.) min_n : int Min length of char ngrams to be used for training word representations. max_n : int Max length of char ngrams to be used for training word representations. Set `max_n` to be lesser than `min_n` to avoid char ngrams being used. word_ngrams : int {1,0} If 1, uses enriches word vectors with subword(ngrams) information. If 0, this is equivalent to word2vec. bucket : int Character ngrams are hashed into a fixed number of buckets, in order to limit the memory usage of the model. This option specifies the number of buckets used by the model. Examples -------- Initialize and train a `FastText` model >>> from gensim.models import FastText >>> sentences = [["cat", "say", "meow"], ["dog", "say", "woof"]] >>> >>> model = FastText(sentences, min_count=1) >>> say_vector = model['say'] # get vector for word >>> of_vector = model['of'] # get vector for out-of-vocab word """ # fastText specific params self.bucket = bucket self.word_ngrams = word_ngrams self.min_n = min_n self.max_n = max_n if self.word_ngrams <= 1 and self.max_n == 0: self.bucket = 0 super(FastText, self).__init__( sentences=sentences, size=size, alpha=alpha, window=window, min_count=min_count, max_vocab_size=max_vocab_size, sample=sample, seed=seed, workers=workers, min_alpha=min_alpha, sg=sg, hs=hs, negative=negative, cbow_mean=cbow_mean, hashfxn=hashfxn, iter=iter, null_word=null_word, trim_rule=trim_rule, sorted_vocab=sorted_vocab, batch_words=batch_words) def initialize_word_vectors(self): """Initializes FastTextKeyedVectors instance to store all vocab/ngram vectors for the model.""" self.wv = FastTextKeyedVectors() self.wv.min_n = self.min_n self.wv.max_n = self.max_n def build_vocab(self, sentences, keep_raw_vocab=False, trim_rule=None, progress_per=10000, update=False): """Build vocabulary from a sequence of sentences (can be a once-only generator stream). Each sentence must be a list of unicode strings. Parameters ---------- sentences : iterable of iterables The `sentences` iterable can be simply a list of lists of tokens, but for larger corpora, consider an iterable that streams the sentences directly from disk/network. See :class:`~gensim.models.word2vec.BrownCorpus`, :class:`~gensim.models.word2vec.Text8Corpus` or :class:`~gensim.models.word2vec.LineSentence` in :mod:`~gensim.models.word2vec` module for such examples. keep_raw_vocab : bool If not true, delete the raw vocabulary after the scaling is done and free up RAM. trim_rule : function Vocabulary trimming rule, specifies whether certain words should remain in the vocabulary, be trimmed away, or handled using the default (discard if word count < min_count). Can be None (min_count will be used, look to :func:`~gensim.utils.keep_vocab_item`), or a callable that accepts parameters (word, count, min_count) and returns either :attr:`gensim.utils.RULE_DISCARD`, :attr:`gensim.utils.RULE_KEEP` or :attr:`gensim.utils.RULE_DEFAULT`. Note: The rule, if given, is only used to prune vocabulary during build_vocab() and is not stored as part of the model. progress_per : int Indicates how many words to process before showing/updating the progress. update: bool If true, the new words in `sentences` will be added to model's vocab. Example ------- Train a model and update vocab for online training >>> from gensim.models import FastText >>> sentences_1 = [["cat", "say", "meow"], ["dog", "say", "woof"]] >>> sentences_2 = [["dude", "say", "wazzup!"]] >>> >>> model = FastText(min_count=1) >>> model.build_vocab(sentences_1) >>> model.train(sentences_1, total_examples=model.corpus_count, epochs=model.iter) >>> model.build_vocab(sentences_2, update=True) >>> model.train(sentences_2, total_examples=model.corpus_count, epochs=model.iter) """ if update: if not len(self.wv.vocab): raise RuntimeError( "You cannot do an online vocabulary-update of a model which has no prior vocabulary. " "First build the vocabulary of your model with a corpus " "before doing an online update.") self.old_vocab_len = len(self.wv.vocab) self.old_hash2index_len = len(self.wv.hash2index) super(FastText, self).build_vocab( sentences, keep_raw_vocab=keep_raw_vocab, trim_rule=trim_rule, progress_per=progress_per, update=update) self.init_ngrams(update=update) def init_ngrams(self, update=False): """Compute ngrams of all words present in vocabulary and stores vectors for only those ngrams. Vectors for other ngrams are initialized with a random uniform distribution in FastText. Parameters ---------- update : bool If True, the new vocab words and their new ngrams word vectors are initialized with random uniform distribution and updated/added to the existing vocab word and ngram vectors. """ if not update: self.wv.ngrams = {} self.wv.syn0_vocab = empty((len(self.wv.vocab), self.vector_size), dtype=REAL) self.syn0_vocab_lockf = ones((len(self.wv.vocab), self.vector_size), dtype=REAL) self.wv.syn0_ngrams = empty((self.bucket, self.vector_size), dtype=REAL) self.syn0_ngrams_lockf = ones((self.bucket, self.vector_size), dtype=REAL) all_ngrams = [] for w, v in self.wv.vocab.items(): self.wv.ngrams_word[w] = compute_ngrams(w, self.min_n, self.max_n) all_ngrams += self.wv.ngrams_word[w] all_ngrams = list(set(all_ngrams)) self.num_ngram_vectors = len(all_ngrams) logger.info("Total number of ngrams is %d", len(all_ngrams)) self.wv.hash2index = {} ngram_indices = [] new_hash_count = 0 for i, ngram in enumerate(all_ngrams): ngram_hash = ft_hash(ngram) % self.bucket if ngram_hash in self.wv.hash2index: self.wv.ngrams[ngram] = self.wv.hash2index[ngram_hash] else: ngram_indices.append(ngram_hash % self.bucket) self.wv.hash2index[ngram_hash] = new_hash_count self.wv.ngrams[ngram] = self.wv.hash2index[ngram_hash] new_hash_count = new_hash_count + 1 self.wv.syn0_ngrams = self.wv.syn0_ngrams.take(ngram_indices, axis=0) self.syn0_ngrams_lockf = self.syn0_ngrams_lockf.take(ngram_indices, axis=0) self.reset_ngram_weights() else: new_ngrams = [] for w, v in self.wv.vocab.items(): self.wv.ngrams_word[w] = compute_ngrams(w, self.min_n, self.max_n) new_ngrams += [ng for ng in self.wv.ngrams_word[w] if ng not in self.wv.ngrams] new_ngrams = list(set(new_ngrams)) logger.info("Number of new ngrams is %d", len(new_ngrams)) new_hash_count = 0 for i, ngram in enumerate(new_ngrams): ngram_hash = ft_hash(ngram) % self.bucket if ngram_hash not in self.wv.hash2index: self.wv.hash2index[ngram_hash] = new_hash_count + self.old_hash2index_len self.wv.ngrams[ngram] = self.wv.hash2index[ngram_hash] new_hash_count = new_hash_count + 1 else: self.wv.ngrams[ngram] = self.wv.hash2index[ngram_hash] rand_obj = np.random rand_obj.seed(self.seed) new_vocab_rows = rand_obj.uniform( -1.0 / self.vector_size, 1.0 / self.vector_size, (len(self.wv.vocab) - self.old_vocab_len, self.vector_size) ).astype(REAL) new_vocab_lockf_rows = ones((len(self.wv.vocab) - self.old_vocab_len, self.vector_size), dtype=REAL) new_ngram_rows = rand_obj.uniform( -1.0 / self.vector_size, 1.0 / self.vector_size, (len(self.wv.hash2index) - self.old_hash2index_len, self.vector_size) ).astype(REAL) new_ngram_lockf_rows = ones( (len(self.wv.hash2index) - self.old_hash2index_len, self.vector_size), dtype=REAL) self.wv.syn0_vocab = vstack([self.wv.syn0_vocab, new_vocab_rows]) self.syn0_vocab_lockf = vstack([self.syn0_vocab_lockf, new_vocab_lockf_rows]) self.wv.syn0_ngrams = vstack([self.wv.syn0_ngrams, new_ngram_rows]) self.syn0_ngrams_lockf = vstack([self.syn0_ngrams_lockf, new_ngram_lockf_rows]) def reset_ngram_weights(self): """Reset all projection weights to an initial (untrained) state, but keep the existing vocabulary and their ngrams. """ rand_obj = np.random rand_obj.seed(self.seed) for index in range(len(self.wv.vocab)): self.wv.syn0_vocab[index] = rand_obj.uniform( -1.0 / self.vector_size, 1.0 / self.vector_size, self.vector_size ).astype(REAL) for index in range(len(self.wv.hash2index)): self.wv.syn0_ngrams[index] = rand_obj.uniform( -1.0 / self.vector_size, 1.0 / self.vector_size, self.vector_size ).astype(REAL) def _do_train_job(self, sentences, alpha, inits): """Train a single batch of sentences. Return 2-tuple `(effective word count after ignoring unknown words and sentence length trimming, total word count)`. Parameters ---------- sentences : iterable of iterables The `sentences` iterable can be simply a list of lists of tokens, but for larger corpora, consider an iterable that streams the sentences directly from disk/network. See :class:`~gensim.models.word2vec.BrownCorpus`, :class:`~gensim.models.word2vec.Text8Corpus` or :class:`~gensim.models.word2vec.LineSentence` in :mod:`~gensim.models.word2vec` module for such examples. alpha : float The current learning rate. inits : (:class:`numpy.ndarray`, :class:`numpy.ndarray`) Each worker's private work memory. Returns ------- (int, int) Tuple of (effective word count after ignoring unknown words and sentence length trimming, total word count) """ work, neu1 = inits tally = 0 if self.sg: tally += train_batch_sg(self, sentences, alpha, work, neu1) else: tally += train_batch_cbow(self, sentences, alpha, work, neu1) return tally, self._raw_word_count(sentences) def train(self, sentences, total_examples=None, total_words=None, epochs=None, start_alpha=None, end_alpha=None, word_count=0, queue_factor=2, report_delay=1.0): """Update the model's neural weights from a sequence of sentences (can be a once-only generator stream). For FastText, each sentence must be a list of unicode strings. (Subclasses may accept other examples.) To support linear learning-rate decay from (initial) alpha to min_alpha, and accurate progress-percentage logging, either total_examples (count of sentences) or total_words (count of raw words in sentences) **MUST** be provided (if the corpus is the same as was provided to :meth:`~gensim.models.fasttext.FastText.build_vocab()`, the count of examples in that corpus will be available in the model's :attr:`corpus_count` property). To avoid common mistakes around the model's ability to do multiple training passes itself, an explicit `epochs` argument **MUST** be provided. In the common and recommended case, where :meth:`~gensim.models.fasttext.FastText.train()` is only called once, the model's cached `iter` value should be supplied as `epochs` value. Parameters ---------- sentences : iterable of iterables The `sentences` iterable can be simply a list of lists of tokens, but for larger corpora, consider an iterable that streams the sentences directly from disk/network. See :class:`~gensim.models.word2vec.BrownCorpus`, :class:`~gensim.models.word2vec.Text8Corpus` or :class:`~gensim.models.word2vec.LineSentence` in :mod:`~gensim.models.word2vec` module for such examples. total_examples : int Count of sentences. total_words : int Count of raw words in sentences. epochs : int Number of iterations (epochs) over the corpus. start_alpha : float Initial learning rate. end_alpha : float Final learning rate. Drops linearly from `start_alpha`. word_count : int Count of words already trained. Set this to 0 for the usual case of training on all words in sentences. queue_factor : int Multiplier for size of queue (number of workers * queue_factor). report_delay : float Seconds to wait before reporting progress. Examples -------- >>> from gensim.models import FastText >>> sentences = [["cat", "say", "meow"], ["dog", "say", "woof"]] >>> >>> model = FastText(min_count=1) >>> model.build_vocab(sentences) >>> model.train(sentences, total_examples=model.corpus_count, epochs=model.iter) """ self.neg_labels = [] if self.negative > 0: # precompute negative labels optimization for pure-python training self.neg_labels = zeros(self.negative + 1) self.neg_labels[0] = 1. Word2Vec.train( self, sentences, total_examples=self.corpus_count, epochs=self.iter, start_alpha=self.alpha, end_alpha=self.min_alpha) self.get_vocab_word_vecs() def __getitem__(self, word): """Get `word` representations in vector space, as a 1D numpy array. Parameters ---------- word : str A single word whose vector needs to be returned. Returns ------- :class:`numpy.ndarray` The word's representations in vector space, as a 1D numpy array. Raises ------ KeyError For words with all ngrams absent, a KeyError is raised. Example ------- >>> from gensim.models import FastText >>> from gensim.test.utils import datapath >>> >>> trained_model = FastText.load_fasttext_format(datapath('lee_fasttext')) >>> meow_vector = trained_model['hello'] # get vector for word """ return self.word_vec(word) def get_vocab_word_vecs(self): """Calculate vectors for words in vocabulary and stores them in `wv.syn0`.""" for w, v in self.wv.vocab.items(): word_vec = np.copy(self.wv.syn0_vocab[v.index]) ngrams = self.wv.ngrams_word[w] ngram_weights = self.wv.syn0_ngrams for ngram in ngrams: word_vec += ngram_weights[self.wv.ngrams[ngram]] word_vec /= (len(ngrams) + 1) self.wv.syn0[v.index] = word_vec def word_vec(self, word, use_norm=False): """Get the word's representations in vector space, as a 1D numpy array. Parameters ---------- word : str A single word whose vector needs to be returned. use_norm : bool If True, returns normalized vector. Returns ------- :class:`numpy.ndarray` The word's representations in vector space, as a 1D numpy array. Raises ------ KeyError For words with all ngrams absent, a KeyError is raised. Example ------- >>> from gensim.models import FastText >>> sentences = [["cat", "say", "meow"], ["dog", "say", "woof"]] >>> >>> model = FastText(sentences, min_count=1) >>> meow_vector = model.word_vec('meow') # get vector for word """ return FastTextKeyedVectors.word_vec(self.wv, word, use_norm=use_norm) @classmethod def load_fasttext_format(cls, *args, **kwargs): """Load a :class:`~gensim.models.fasttext.FastText` model from a format compatible with the original fasttext implementation. Parameters ---------- fname : str Path to the file. """ return Ft_Wrapper.load_fasttext_format(*args, **kwargs) def save(self, *args, **kwargs): """Save the model. This saved model can be loaded again using :func:`~gensim.models.fasttext.FastText.load`, which supports online training and getting vectors for out-of-vocabulary words. Parameters ---------- fname : str Path to the file. """ kwargs['ignore'] = kwargs.get('ignore', ['syn0norm', 'syn0_vocab_norm', 'syn0_ngrams_norm']) super(FastText, self).save(*args, **kwargs)
markroxor/gensim
gensim/models/fasttext.py
Python
lgpl-2.1
29,942
package org.wingx; import org.wings.*; import org.wings.border.SLineBorder; import org.wingx.plaf.css.XPageScrollerCG; import java.awt.*; import java.awt.event.AdjustmentListener; public class XPageScroller extends SContainer implements Adjustable { SPageScroller pageScroller = new SPageScroller(Adjustable.VERTICAL); private GridBagConstraints c = new GridBagConstraints(); public XPageScroller() { super(new SGridBagLayout()); SLineBorder border = new SLineBorder(new Color(200, 200, 200), 0); border.setThickness(1, SConstants.TOP); setBorder(border); setPreferredSize(SDimension.FULLWIDTH); c.anchor = GridBagConstraints.EAST; add(pageScroller); pageScroller.setCG(new XPageScrollerCG()); pageScroller.setLayoutMode(Adjustable.HORIZONTAL); pageScroller.setDirectPages(5); pageScroller.setShowAsFormComponent(false); } public SComponent add(SComponent component) { c.weightx = 0d; component.setVerticalAlignment(SConstants.CENTER_ALIGN); return super.addComponent(component, c); } public SComponent add(SComponent component, double weight) { c.weightx = weight; return super.addComponent(component, c); } public void reset(int total) { while (getComponentCount() > 1) { remove(1); } normalize(total); } public void normalize(int total) { int value = pageScroller.getValue(); int visible = pageScroller.getVisibleAmount(); if (value + visible > total) { value = Math.max(0, total - visible); pageScroller.setValue(value); } } public void setUnitIncrement(int i) { pageScroller.setUnitIncrement(i); } public void setBlockIncrement(int i) { pageScroller.setBlockIncrement(i); } public int getUnitIncrement() { return pageScroller.getUnitIncrement(); } public int getBlockIncrement() { return pageScroller.getBlockIncrement(); } public int getValue() { return pageScroller.getValue(); } public void setExtent(int value) { pageScroller.setExtent(value); } public int getVisibleAmount() { return pageScroller.getVisibleAmount(); } public void setVisibleAmount(int i) { pageScroller.setVisibleAmount(i); } public int getMinimum() { return pageScroller.getMinimum(); } public void setMinimum(int i) { pageScroller.setMinimum(i); } public int getMaximum() { return pageScroller.getMaximum(); } public void setMaximum(int i) { pageScroller.setMaximum(i); } public int getOrientation() { return pageScroller.getOrientation(); } public void setValue(int i) { pageScroller.setValue(i); } public void addAdjustmentListener(AdjustmentListener adjustmentListener) { pageScroller.addAdjustmentListener(adjustmentListener); } public void removeAdjustmentListener(AdjustmentListener adjustmentListener) { pageScroller.removeAdjustmentListener(adjustmentListener); } public SPageScroller getPageScroller() { return pageScroller; } public SBoundedRangeModel getModel() { return pageScroller.getModel(); } public void setModel(SBoundedRangeModel newModel) { pageScroller.setModel(newModel); } }
exxcellent/wings3
wingx/src/java/org/wingx/XPageScroller.java
Java
lgpl-2.1
3,484
/* Copyright (c) 2007, 2008, 2009, 2010 Red Hat, Inc. This file is part of the Qpid async store library msgstore.so. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA The GNU Lesser General Public License is available in the file COPYING. */ #include "JournalImpl.h" #include "jrnl/jerrno.hpp" #include "jrnl/jexception.hpp" #include "qpid/log/Statement.h" #include "qpid/management/ManagementAgent.h" #include "qmf/com/redhat/rhm/store/ArgsJournalExpand.h" #include "qmf/com/redhat/rhm/store/EventCreated.h" #include "qmf/com/redhat/rhm/store/EventEnqThresholdExceeded.h" #include "qmf/com/redhat/rhm/store/EventFull.h" #include "qmf/com/redhat/rhm/store/EventRecovered.h" #include "qpid/sys/Monitor.h" #include "qpid/sys/Timer.h" #include "StoreException.h" using namespace mrg::msgstore; using namespace mrg::journal; using qpid::management::ManagementAgent; namespace _qmf = qmf::com::redhat::rhm::store; InactivityFireEvent::InactivityFireEvent(JournalImpl* p, const qpid::sys::Duration timeout): qpid::sys::TimerTask(timeout, "JournalInactive:"+p->id()), _parent(p) {} void InactivityFireEvent::fire() { qpid::sys::Mutex::ScopedLock sl(_ife_lock); if (_parent) _parent->flushFire(); } GetEventsFireEvent::GetEventsFireEvent(JournalImpl* p, const qpid::sys::Duration timeout): qpid::sys::TimerTask(timeout, "JournalGetEvents:"+p->id()), _parent(p) {} void GetEventsFireEvent::fire() { qpid::sys::Mutex::ScopedLock sl(_gefe_lock); if (_parent) _parent->getEventsFire(); } JournalImpl::JournalImpl(qpid::sys::Timer& timer_, const std::string& journalId, const std::string& journalDirectory, const std::string& journalBaseFilename, const qpid::sys::Duration getEventsTimeout, const qpid::sys::Duration flushTimeout, qpid::management::ManagementAgent* a, DeleteCallback onDelete): jcntl(journalId, journalDirectory, journalBaseFilename), timer(timer_), getEventsTimerSetFlag(false), lastReadRid(0), writeActivityFlag(false), flushTriggeredFlag(true), _xidp(0), _datap(0), _dlen(0), _dtok(), _external(false), _mgmtObject(0), deleteCallback(onDelete) { getEventsFireEventsPtr = new GetEventsFireEvent(this, getEventsTimeout); inactivityFireEventPtr = new InactivityFireEvent(this, flushTimeout); { timer.start(); timer.add(inactivityFireEventPtr); } initManagement(a); log(LOG_NOTICE, "Created"); std::ostringstream oss; oss << "Journal directory = \"" << journalDirectory << "\"; Base file name = \"" << journalBaseFilename << "\""; log(LOG_DEBUG, oss.str()); } JournalImpl::~JournalImpl() { if (deleteCallback) deleteCallback(*this); if (_init_flag && !_stop_flag){ try { stop(true); } // NOTE: This will *block* until all outstanding disk aio calls are complete! catch (const jexception& e) { log(LOG_ERROR, e.what()); } } getEventsFireEventsPtr->cancel(); inactivityFireEventPtr->cancel(); free_read_buffers(); if (_mgmtObject != 0) { _mgmtObject->resourceDestroy(); _mgmtObject = 0; } log(LOG_NOTICE, "Destroyed"); } void JournalImpl::initManagement(qpid::management::ManagementAgent* a) { _agent = a; if (_agent != 0) { _mgmtObject = new _qmf::Journal (_agent, (qpid::management::Manageable*) this); _mgmtObject->set_name(_jid); _mgmtObject->set_directory(_jdir.dirname()); _mgmtObject->set_baseFileName(_base_filename); _mgmtObject->set_readPageSize(JRNL_RMGR_PAGE_SIZE * JRNL_SBLK_SIZE * JRNL_DBLK_SIZE); _mgmtObject->set_readPages(JRNL_RMGR_PAGES); // The following will be set on initialize(), but being properties, these must be set to 0 in the meantime _mgmtObject->set_initialFileCount(0); _mgmtObject->set_dataFileSize(0); _mgmtObject->set_currentFileCount(0); _mgmtObject->set_writePageSize(0); _mgmtObject->set_writePages(0); _agent->addObject(_mgmtObject, 0, true); } } void JournalImpl::initialize(const u_int16_t num_jfiles, const bool auto_expand, const u_int16_t ae_max_jfiles, const u_int32_t jfsize_sblks, const u_int16_t wcache_num_pages, const u_int32_t wcache_pgsize_sblks, mrg::journal::aio_callback* const cbp) { std::ostringstream oss; oss << "Initialize; num_jfiles=" << num_jfiles << " jfsize_sblks=" << jfsize_sblks; oss << " wcache_pgsize_sblks=" << wcache_pgsize_sblks; oss << " wcache_num_pages=" << wcache_num_pages; log(LOG_DEBUG, oss.str()); jcntl::initialize(num_jfiles, auto_expand, ae_max_jfiles, jfsize_sblks, wcache_num_pages, wcache_pgsize_sblks, cbp); log(LOG_DEBUG, "Initialization complete"); if (_mgmtObject != 0) { _mgmtObject->set_initialFileCount(_lpmgr.num_jfiles()); _mgmtObject->set_autoExpand(_lpmgr.is_ae()); _mgmtObject->set_currentFileCount(_lpmgr.num_jfiles()); _mgmtObject->set_maxFileCount(_lpmgr.ae_max_jfiles()); _mgmtObject->set_dataFileSize(_jfsize_sblks * JRNL_SBLK_SIZE * JRNL_DBLK_SIZE); _mgmtObject->set_writePageSize(wcache_pgsize_sblks * JRNL_SBLK_SIZE * JRNL_DBLK_SIZE); _mgmtObject->set_writePages(wcache_num_pages); } if (_agent != 0) _agent->raiseEvent(qmf::com::redhat::rhm::store::EventCreated(_jid, _jfsize_sblks * JRNL_SBLK_SIZE * JRNL_DBLK_SIZE, _lpmgr.num_jfiles()), qpid::management::ManagementAgent::SEV_NOTE); } void JournalImpl::recover(const u_int16_t num_jfiles, const bool auto_expand, const u_int16_t ae_max_jfiles, const u_int32_t jfsize_sblks, const u_int16_t wcache_num_pages, const u_int32_t wcache_pgsize_sblks, mrg::journal::aio_callback* const cbp, boost::ptr_list<msgstore::PreparedTransaction>* prep_tx_list_ptr, u_int64_t& highest_rid, u_int64_t queue_id) { std::ostringstream oss1; oss1 << "Recover; num_jfiles=" << num_jfiles << " jfsize_sblks=" << jfsize_sblks; oss1 << " queue_id = 0x" << std::hex << queue_id << std::dec; oss1 << " wcache_pgsize_sblks=" << wcache_pgsize_sblks; oss1 << " wcache_num_pages=" << wcache_num_pages; log(LOG_DEBUG, oss1.str()); if (_mgmtObject != 0) { _mgmtObject->set_initialFileCount(_lpmgr.num_jfiles()); _mgmtObject->set_autoExpand(_lpmgr.is_ae()); _mgmtObject->set_currentFileCount(_lpmgr.num_jfiles()); _mgmtObject->set_maxFileCount(_lpmgr.ae_max_jfiles()); _mgmtObject->set_dataFileSize(_jfsize_sblks * JRNL_SBLK_SIZE * JRNL_DBLK_SIZE); _mgmtObject->set_writePageSize(wcache_pgsize_sblks * JRNL_SBLK_SIZE * JRNL_DBLK_SIZE); _mgmtObject->set_writePages(wcache_num_pages); } if (prep_tx_list_ptr) { // Create list of prepared xids std::vector<std::string> prep_xid_list; for (msgstore::PreparedTransaction::list::iterator i = prep_tx_list_ptr->begin(); i != prep_tx_list_ptr->end(); i++) { prep_xid_list.push_back(i->xid); } jcntl::recover(num_jfiles, auto_expand, ae_max_jfiles, jfsize_sblks, wcache_num_pages, wcache_pgsize_sblks, cbp, &prep_xid_list, highest_rid); } else { jcntl::recover(num_jfiles, auto_expand, ae_max_jfiles, jfsize_sblks, wcache_num_pages, wcache_pgsize_sblks, cbp, 0, highest_rid); } // Populate PreparedTransaction lists from _tmap if (prep_tx_list_ptr) { for (msgstore::PreparedTransaction::list::iterator i = prep_tx_list_ptr->begin(); i != prep_tx_list_ptr->end(); i++) { txn_data_list tdl = _tmap.get_tdata_list(i->xid); // tdl will be empty if xid not found for (tdl_itr tdl_itr = tdl.begin(); tdl_itr < tdl.end(); tdl_itr++) { if (tdl_itr->_enq_flag) { // enqueue op i->enqueues->add(queue_id, tdl_itr->_rid); } else { // dequeue op i->dequeues->add(queue_id, tdl_itr->_drid); } } } } std::ostringstream oss2; oss2 << "Recover phase 1 complete; highest rid found = 0x" << std::hex << highest_rid; oss2 << std::dec << "; emap.size=" << _emap.size() << "; tmap.size=" << _tmap.size(); oss2 << "; journal now read-only."; log(LOG_DEBUG, oss2.str()); if (_mgmtObject != 0) { _mgmtObject->inc_recordDepth(_emap.size()); _mgmtObject->inc_enqueues(_emap.size()); _mgmtObject->inc_txn(_tmap.size()); _mgmtObject->inc_txnEnqueues(_tmap.enq_cnt()); _mgmtObject->inc_txnDequeues(_tmap.deq_cnt()); } } void JournalImpl::recover_complete() { jcntl::recover_complete(); log(LOG_DEBUG, "Recover phase 2 complete; journal now writable."); if (_agent != 0) _agent->raiseEvent(qmf::com::redhat::rhm::store::EventRecovered(_jid, _jfsize_sblks * JRNL_SBLK_SIZE * JRNL_DBLK_SIZE, _lpmgr.num_jfiles(), _emap.size(), _tmap.size(), _tmap.enq_cnt(), _tmap.deq_cnt()), qpid::management::ManagementAgent::SEV_NOTE); } //#define MAX_AIO_SLEEPS 1000000 // tot: ~10 sec //#define AIO_SLEEP_TIME_US 10 // 0.01 ms // Return true if content is recovered from store; false if content is external and must be recovered from an external store. // Throw exception for all errors. bool JournalImpl::loadMsgContent(u_int64_t rid, std::string& data, size_t length, size_t offset) { qpid::sys::Mutex::ScopedLock sl(_read_lock); if (_dtok.rid() != rid) { // Free any previous msg free_read_buffers(); // Last read encountered out-of-order rids, check if this rid is in that list bool oooFlag = false; for (std::vector<u_int64_t>::const_iterator i=oooRidList.begin(); i!=oooRidList.end() && !oooFlag; i++) { if (*i == rid) { oooFlag = true; } } // TODO: This is a brutal approach - very inefficient and slow. Rather introduce a system of remembering // jumpover points and allow the read to jump back to the first known jumpover point - but this needs // a mechanism in rrfc to accomplish it. Also helpful is a struct containing a journal address - a // combination of lid/offset. // NOTE: The second part of the if stmt (rid < lastReadRid) is required to handle browsing. if (oooFlag || rid < lastReadRid) { _rmgr.invalidate(); oooRidList.clear(); } _dlen = 0; _dtok.reset(); _dtok.set_wstate(DataTokenImpl::ENQ); _dtok.set_rid(0); _external = false; size_t xlen = 0; bool transient = false; bool done = false; bool rid_found = false; while (!done) { iores res = read_data_record(&_datap, _dlen, &_xidp, xlen, transient, _external, &_dtok); switch (res) { case mrg::journal::RHM_IORES_SUCCESS: if (_dtok.rid() != rid) { // Check if this is an out-of-order rid that may impact next read if (_dtok.rid() > rid) oooRidList.push_back(_dtok.rid()); free_read_buffers(); // Reset data token for next read _dlen = 0; _dtok.reset(); _dtok.set_wstate(DataTokenImpl::ENQ); _dtok.set_rid(0); } else { rid_found = _dtok.rid() == rid; lastReadRid = rid; done = true; } break; case mrg::journal::RHM_IORES_PAGE_AIOWAIT: if (get_wr_events(&_aio_cmpl_timeout) == journal::jerrno::AIO_TIMEOUT) { std::stringstream ss; ss << "read_data_record() returned " << mrg::journal::iores_str(res); ss << "; timed out waiting for page to be processed."; throw jexception(mrg::journal::jerrno::JERR__TIMEOUT, ss.str().c_str(), "JournalImpl", "loadMsgContent"); } break; default: std::stringstream ss; ss << "read_data_record() returned " << mrg::journal::iores_str(res); throw jexception(mrg::journal::jerrno::JERR__UNEXPRESPONSE, ss.str().c_str(), "JournalImpl", "loadMsgContent"); } } if (!rid_found) { std::stringstream ss; ss << "read_data_record() was unable to find rid 0x" << std::hex << rid << std::dec; ss << " (" << rid << "); last rid found was 0x" << std::hex << _dtok.rid() << std::dec; ss << " (" << _dtok.rid() << ")"; throw jexception(mrg::journal::jerrno::JERR__RECNFOUND, ss.str().c_str(), "JournalImpl", "loadMsgContent"); } } if (_external) return false; u_int32_t hdr_offs = qpid::framing::Buffer(static_cast<char*>(_datap), sizeof(u_int32_t)).getLong() + sizeof(u_int32_t); if (hdr_offs + offset + length > _dlen) { data.append((const char*)_datap + hdr_offs + offset, _dlen - hdr_offs - offset); } else { data.append((const char*)_datap + hdr_offs + offset, length); } return true; } void JournalImpl::enqueue_data_record(const void* const data_buff, const size_t tot_data_len, const size_t this_data_len, data_tok* dtokp, const bool transient) { handleIoResult(jcntl::enqueue_data_record(data_buff, tot_data_len, this_data_len, dtokp, transient)); if (_mgmtObject != 0) { _mgmtObject->inc_enqueues(); _mgmtObject->inc_recordDepth(); } } void JournalImpl::enqueue_extern_data_record(const size_t tot_data_len, data_tok* dtokp, const bool transient) { handleIoResult(jcntl::enqueue_extern_data_record(tot_data_len, dtokp, transient)); if (_mgmtObject != 0) { _mgmtObject->inc_enqueues(); _mgmtObject->inc_recordDepth(); } } void JournalImpl::enqueue_txn_data_record(const void* const data_buff, const size_t tot_data_len, const size_t this_data_len, data_tok* dtokp, const std::string& xid, const bool transient) { bool txn_incr = _mgmtObject != 0 ? _tmap.in_map(xid) : false; handleIoResult(jcntl::enqueue_txn_data_record(data_buff, tot_data_len, this_data_len, dtokp, xid, transient)); if (_mgmtObject != 0) { if (!txn_incr) // If this xid was not in _tmap, it will be now... _mgmtObject->inc_txn(); _mgmtObject->inc_enqueues(); _mgmtObject->inc_txnEnqueues(); _mgmtObject->inc_recordDepth(); } } void JournalImpl::enqueue_extern_txn_data_record(const size_t tot_data_len, data_tok* dtokp, const std::string& xid, const bool transient) { bool txn_incr = _mgmtObject != 0 ? _tmap.in_map(xid) : false; handleIoResult(jcntl::enqueue_extern_txn_data_record(tot_data_len, dtokp, xid, transient)); if (_mgmtObject != 0) { if (!txn_incr) // If this xid was not in _tmap, it will be now... _mgmtObject->inc_txn(); _mgmtObject->inc_enqueues(); _mgmtObject->inc_txnEnqueues(); _mgmtObject->inc_recordDepth(); } } void JournalImpl::dequeue_data_record(data_tok* const dtokp, const bool txn_coml_commit) { handleIoResult(jcntl::dequeue_data_record(dtokp, txn_coml_commit)); if (_mgmtObject != 0) { _mgmtObject->inc_dequeues(); _mgmtObject->inc_txnDequeues(); _mgmtObject->dec_recordDepth(); } } void JournalImpl::dequeue_txn_data_record(data_tok* const dtokp, const std::string& xid, const bool txn_coml_commit) { bool txn_incr = _mgmtObject != 0 ? _tmap.in_map(xid) : false; handleIoResult(jcntl::dequeue_txn_data_record(dtokp, xid, txn_coml_commit)); if (_mgmtObject != 0) { if (!txn_incr) // If this xid was not in _tmap, it will be now... _mgmtObject->inc_txn(); _mgmtObject->inc_dequeues(); _mgmtObject->inc_txnDequeues(); _mgmtObject->dec_recordDepth(); } } void JournalImpl::txn_abort(data_tok* const dtokp, const std::string& xid) { handleIoResult(jcntl::txn_abort(dtokp, xid)); if (_mgmtObject != 0) { _mgmtObject->dec_txn(); _mgmtObject->inc_txnAborts(); } } void JournalImpl::txn_commit(data_tok* const dtokp, const std::string& xid) { handleIoResult(jcntl::txn_commit(dtokp, xid)); if (_mgmtObject != 0) { _mgmtObject->dec_txn(); _mgmtObject->inc_txnCommits(); } } void JournalImpl::stop(bool block_till_aio_cmpl) { InactivityFireEvent* ifep = dynamic_cast<InactivityFireEvent*>(inactivityFireEventPtr.get()); assert(ifep); // dynamic_cast can return null if the cast fails ifep->cancel(); jcntl::stop(block_till_aio_cmpl); if (_mgmtObject != 0) { _mgmtObject->resourceDestroy(); _mgmtObject = 0; } } iores JournalImpl::flush(const bool block_till_aio_cmpl) { const iores res = jcntl::flush(block_till_aio_cmpl); { qpid::sys::Mutex::ScopedLock sl(_getf_lock); if (_wmgr.get_aio_evt_rem() && !getEventsTimerSetFlag) { setGetEventTimer(); } } return res; } void JournalImpl::log(mrg::journal::log_level ll, const std::string& log_stmt) const { log(ll, log_stmt.c_str()); } void JournalImpl::log(mrg::journal::log_level ll, const char* const log_stmt) const { switch (ll) { case LOG_TRACE: QPID_LOG(trace, "Journal \"" << _jid << "\": " << log_stmt); break; case LOG_DEBUG: QPID_LOG(debug, "Journal \"" << _jid << "\": " << log_stmt); break; case LOG_INFO: QPID_LOG(info, "Journal \"" << _jid << "\": " << log_stmt); break; case LOG_NOTICE: QPID_LOG(notice, "Journal \"" << _jid << "\": " << log_stmt); break; case LOG_WARN: QPID_LOG(warning, "Journal \"" << _jid << "\": " << log_stmt); break; case LOG_ERROR: QPID_LOG(error, "Journal \"" << _jid << "\": " << log_stmt); break; case LOG_CRITICAL: QPID_LOG(critical, "Journal \"" << _jid << "\": " << log_stmt); break; } } void JournalImpl::getEventsFire() { qpid::sys::Mutex::ScopedLock sl(_getf_lock); getEventsTimerSetFlag = false; if (_wmgr.get_aio_evt_rem()) { jcntl::get_wr_events(0); } if (_wmgr.get_aio_evt_rem()) { setGetEventTimer(); } } void JournalImpl::flushFire() { if (writeActivityFlag) { writeActivityFlag = false; flushTriggeredFlag = false; } else { if (!flushTriggeredFlag) { flush(); flushTriggeredFlag = true; } } inactivityFireEventPtr->setupNextFire(); { timer.add(inactivityFireEventPtr); } } void JournalImpl::wr_aio_cb(std::vector<data_tok*>& dtokl) { for (std::vector<data_tok*>::const_iterator i=dtokl.begin(); i!=dtokl.end(); i++) { DataTokenImpl* dtokp = static_cast<DataTokenImpl*>(*i); if (/*!is_stopped() &&*/ dtokp->getSourceMessage()) { switch (dtokp->wstate()) { case data_tok::ENQ: dtokp->getSourceMessage()->enqueueComplete(); break; case data_tok::DEQ: /* Don't need to signal until we have a way to ack completion of dequeue in AMQP dtokp->getSourceMessage()->dequeueComplete(); if ( dtokp->getSourceMessage()->isDequeueComplete() ) // clear id after last dequeue dtokp->getSourceMessage()->setPersistenceId(0); */ break; default: ; } } dtokp->release(); } } void JournalImpl::rd_aio_cb(std::vector<u_int16_t>& /*pil*/) {} void JournalImpl::free_read_buffers() { if (_xidp) { ::free(_xidp); _xidp = 0; _datap = 0; } else if (_datap) { ::free(_datap); _datap = 0; } } void JournalImpl::handleIoResult(const iores r) { writeActivityFlag = true; switch (r) { case mrg::journal::RHM_IORES_SUCCESS: return; case mrg::journal::RHM_IORES_ENQCAPTHRESH: { std::ostringstream oss; oss << "Enqueue capacity threshold exceeded on queue \"" << _jid << "\"."; log(LOG_WARN, oss.str()); if (_agent != 0) _agent->raiseEvent(qmf::com::redhat::rhm::store::EventEnqThresholdExceeded(_jid, "Journal enqueue capacity threshold exceeded"), qpid::management::ManagementAgent::SEV_WARN); THROW_STORE_FULL_EXCEPTION(oss.str()); } case mrg::journal::RHM_IORES_FULL: { std::ostringstream oss; oss << "Journal full on queue \"" << _jid << "\"."; log(LOG_CRITICAL, oss.str()); if (_agent != 0) _agent->raiseEvent(qmf::com::redhat::rhm::store::EventFull(_jid, "Journal full"), qpid::management::ManagementAgent::SEV_ERROR); THROW_STORE_FULL_EXCEPTION(oss.str()); } default: { std::ostringstream oss; oss << "Unexpected I/O response (" << mrg::journal::iores_str(r) << ") on queue " << _jid << "\"."; log(LOG_ERROR, oss.str()); THROW_STORE_FULL_EXCEPTION(oss.str()); } } } qpid::management::Manageable::status_t JournalImpl::ManagementMethod (uint32_t methodId, qpid::management::Args& /*args*/, std::string& /*text*/) { Manageable::status_t status = Manageable::STATUS_UNKNOWN_METHOD; switch (methodId) { case _qmf::Journal::METHOD_EXPAND : //_qmf::ArgsJournalExpand& eArgs = (_qmf::ArgsJournalExpand&) args; // Implement "expand" using eArgs.i_by (expand-by argument) status = Manageable::STATUS_NOT_IMPLEMENTED; break; } return status; }
cajus/qpid-cpp-store-debian
lib/JournalImpl.cpp
C++
lgpl-2.1
23,571
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgallerytrackertyperesultset_p.h" #include "qgallerytrackerschema_p.h" #include <QtCore/qdatetime.h> #include <QtDBus/qdbuspendingreply.h> #include "qdocumentgallery.h" #include "qgalleryresultset_p.h" Q_DECLARE_METATYPE(QVector<QStringList>) QTM_BEGIN_NAMESPACE class QGalleryTrackerTypeResultSetPrivate : public QGalleryResultSetPrivate { Q_DECLARE_PUBLIC(QGalleryTrackerTypeResultSet) public: QGalleryTrackerTypeResultSetPrivate(const QGalleryTrackerTypeResultSetArguments &arguments) : accumulative(arguments.accumulative) , canceled(false) , refresh(false) , updateMask(arguments.updateMask) , currentIndex(-1) , count(0) , workingCount(0) , currentOffset(0) , queryWatcher(0) , queryInterface(arguments.queryInterface) , queryMethod(arguments.queryMethod) , queryArguments(arguments.queryArguments) { } void _q_queryFinished(QDBusPendingCallWatcher *watcher); void queryFinished(const QDBusPendingCall &call); void queryCount(); const bool accumulative; bool canceled; bool refresh; const int updateMask; int currentIndex; int count; int workingCount; int currentOffset; QDBusPendingCallWatcher *queryWatcher; const QGalleryDBusInterfacePointer queryInterface; const QString queryMethod; const QVariantList queryArguments; }; void QGalleryTrackerTypeResultSetPrivate::_q_queryFinished(QDBusPendingCallWatcher *watcher) { if (queryWatcher == watcher) { queryWatcher->deleteLater(); queryWatcher = 0; watcher->deleteLater(); queryFinished(*watcher); } } void QGalleryTrackerTypeResultSetPrivate::queryFinished(const QDBusPendingCall &call) { const int oldCount = count; if (call.isError()) { q_func()->finish(QDocumentGallery::ConnectionError); return; } else if (!accumulative) { QDBusPendingReply<int> reply(call); count = reply.value(); if (refresh) { refresh = false; queryCount(); } } else { QDBusPendingReply<QVector<QStringList> > reply(call); const QVector<QStringList> counts = reply.value(); typedef QVector<QStringList>::const_iterator iterator; for (iterator it = counts.begin(), end = counts.end(); it != end; ++it) workingCount += it->value(1).toInt(); if (refresh) { refresh = false; currentOffset = 0; workingCount = 0; queryCount(); } else { currentOffset += counts.count(); if (counts.count() != 0) { if (count > workingCount) count = workingCount; if (canceled) q_func()->QGalleryAbstractResponse::cancel(); else queryCount(); } else { count = workingCount; } } } if (count != oldCount) emit q_func()->metaDataChanged(0, 1, QList<int>() << 0); if (!queryWatcher) q_func()->finish(); } void QGalleryTrackerTypeResultSetPrivate::queryCount() { QVariantList arguments = queryArguments; if (accumulative) arguments << currentOffset << int(0); QDBusPendingCall call = queryInterface->asyncCallWithArgumentList(queryMethod, arguments); if (call.isFinished()) { queryFinished(call); } else { queryWatcher = new QDBusPendingCallWatcher(call, q_func()); QObject::connect(queryWatcher, SIGNAL(finished(QDBusPendingCallWatcher*)), q_func(), SLOT(_q_queryFinished(QDBusPendingCallWatcher*))); } } QGalleryTrackerTypeResultSet::QGalleryTrackerTypeResultSet( const QGalleryTrackerTypeResultSetArguments &arguments, QObject *parent) : QGalleryResultSet(*new QGalleryTrackerTypeResultSetPrivate(arguments), parent) { Q_D(QGalleryTrackerTypeResultSet); d->queryCount(); } QGalleryTrackerTypeResultSet::~QGalleryTrackerTypeResultSet() { } int QGalleryTrackerTypeResultSet::propertyKey(const QString &property) const { return property == QLatin1String("count") ? 0 : -1; } QGalleryProperty::Attributes QGalleryTrackerTypeResultSet::propertyAttributes(int key) const { return key == 0 ? QGalleryProperty::CanRead : QGalleryProperty::Attributes(); } QVariant::Type QGalleryTrackerTypeResultSet::propertyType(int key) const { return key == 0 ? QVariant::Int : QVariant::Invalid; } int QGalleryTrackerTypeResultSet::itemCount() const { return 1; } QVariant QGalleryTrackerTypeResultSet::itemId() const { return QVariant(); } QUrl QGalleryTrackerTypeResultSet::itemUrl() const { return QUrl(); } QString QGalleryTrackerTypeResultSet::itemType() const { return QString(); } QVariant QGalleryTrackerTypeResultSet::metaData(int key) const { return d_func()->currentIndex == 0 && key == 0 ? d_func()->count : 0; } bool QGalleryTrackerTypeResultSet::setMetaData(int, const QVariant &) { return false; } int QGalleryTrackerTypeResultSet::currentIndex() const { return d_func()->currentIndex; } bool QGalleryTrackerTypeResultSet::fetch(int index) { if (index != d_func()->currentIndex) { bool itemChanged = index == 0 || d_func()->currentIndex == 0; d_func()->currentIndex = index; emit currentIndexChanged(index); if (itemChanged) emit currentItemChanged(); } return d_func()->currentIndex == 0; } void QGalleryTrackerTypeResultSet::cancel() { d_func()->canceled = true; d_func()->refresh = false; if (!d_func()->queryWatcher) QGalleryAbstractResponse::cancel(); } bool QGalleryTrackerTypeResultSet::waitForFinished(int msecs) { Q_D(QGalleryTrackerTypeResultSet); QTime timer; timer.start(); do { if (QDBusPendingCallWatcher *watcher = d->queryWatcher) { d->queryWatcher = 0; watcher->waitForFinished(); d->queryFinished(*watcher); delete watcher; if (d->state != QGalleryAbstractRequest::Active) return true; } else { return true; } } while ((msecs -= timer.restart()) > 0); return false; } void QGalleryTrackerTypeResultSet::refresh(int serviceId) { Q_D(QGalleryTrackerTypeResultSet); if (!d->canceled && (d->updateMask & serviceId)) { d->refresh = true; if (!d->queryWatcher) d->queryCount(); } } #include "moc_qgallerytrackertyperesultset_p.cpp" QTM_END_NAMESPACE
KDE/android-qt-mobility
src/gallery/maemo5/qgallerytrackertyperesultset.cpp
C++
lgpl-2.1
8,155
<?php /* vim: set expandtab tabstop=4 shiftwidth=4: */ /** * Image Transformation interface using old ImageMagick extension * * PHP versions 4 and 5 * * LICENSE: This source file is subject to version 3.0 of the PHP license * that is available through the world-wide-web at the following URI: * http://www.php.net/license/3_0.txt. If you did not receive a copy of * the PHP License and are unable to obtain it through the web, please * send a note to license@php.net so we can mail you a copy immediately. * * @category Image * @package Image_Transform * @author Peter Bowyer <peter@mapledesign.co.uk> * @copyright 2002-2005 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: Imagick.php,v 1.6 2005/07/15 05:18:42 jausions Exp $ * @deprecated * @link http://pear.php.net/package/Image_Transform */ /** * Include of base class */ require_once "Image/Transform.php"; /** * Image Transformation interface using old ImageMagick extension * * DEPRECATED: current CVS/release imagick extension should use * the Imagick2 driver * * @deprecated */ class Image_Transform_Driver_Imagick extends Image_Transform { /** * Handler of the imagick image ressource * @var array */ var $imageHandle; /** * Handler of the image ressource before * the last transformation * @var array */ var $oldImage; /** * * */ function Image_Transform_Driver_Imagick() { if (!PEAR::loadExtension('imagick')) { return PEAR::raiseError('The imagick extension can not be found.', true); } include('Image/Transform/Driver/Imagick/ImageTypes.php'); return true; } // End Image_IM /** * Load image * * @param string filename * * @return mixed none or a PEAR error object on error * @see PEAR::isError() */ function load($image) { $this->imageHandle = imagick_create(); if ( !is_resource( $this->imageHandle ) ) { return PEAR::raiseError('Cannot initialize imagick image.', true); } if ( !imagick_read($this->imageHandle, $image) ){ return PEAR::raiseError('The image file ' . $image . ' does\'t exist', true); } $this->image = $image; $result = $this->_get_image_details($image); if (PEAR::isError($result)) { return $result; } } // End load /** * Resize Action * * @param int new_x new width * @param int new_y new width * * @return none * @see PEAR::isError() */ function _resize($new_x, $new_y) { if ($img2 = imagick_copy_resize($this->imageHandle, $new_x, $new_y, IMAGICK_FILTER_CUBIC, 1)){ $this->oldImage = $this->imageHandle; $this->imageHandle =$img2; $this->new_x = $new_x; $this->new_y = $new_y; } else { return PEAR::raiseError("Cannot create a new imagick imagick image for the resize.", true); } } // End resize /** * rotate * Note: color mask are currently not supported * * @param int Rotation angle in degree * @param array No option are actually allowed * * @return none * @see PEAR::isError() */ function rotate($angle,$options=null) { if ($img2 = imagick_copy_rotate ($this->imageHandle, $angle)){ $this->oldImage = $this->imageHandle; $this->imageHandle = $img2; $this->new_x = imagick_get_attribute($img2,'width'); $this->new_y = imagick_get_attribute($img2,'height'); } else { return PEAR::raiseError("Cannot create a new imagick imagick image for the resize.", true); } } // End rotate /** * addText * * @param array options Array contains options * array( * 'text' The string to draw * 'x' Horizontal position * 'y' Vertical Position * 'Color' Font color * 'font' Font to be used * 'size' Size of the fonts in pixel * 'resize_first' Tell if the image has to be resized * before drawing the text * ) * * @return none * @see PEAR::isError() */ function addText($params) { $default_params = array( 'text' => 'This is a Text', 'x' => 10, 'y' => 20, 'size' => 12, 'color' => 'red', 'font' => 'Arial.ttf', 'resize_first' => false // Carry out the scaling of the image before annotation? ); $params = array_merge($default_params, $params); extract($params); $color = is_array($color)?$this->colorarray2colorhex($color):strtolower($color); imagick_annotate($this->imageHandle,array( "primitive" => "text $x,$y ".$text, "pointsize" => $size, "antialias" => 0, "fill" => $color, "font" => $font, )); } // End addText /** * Save the image file * * @param $filename string the name of the file to write to * * @return none */ function save($filename, $type='', $quality = 75) { if ($type == '') { $type = strtoupper($type); imagick_write($this->imageHandle, $filename, $type); } else { imagick_write($this->imageHandle, $filename); } imagick_free($handle); } // End save /** * Display image without saving and lose changes * * @param string type (JPG,PNG...); * @param int quality 75 * * @return none */ function display($type = '', $quality = 75) { if ($type == '') { header('Content-type: image/' . $this->type); if (!imagick_dump($this->imageHandle)); } else { header('Content-type: image/' . $type); if (!imagick_dump($this->imageHandle, $this->type)); } $this->free(); } /** * Destroy image handle * * @return none */ function free() { if(is_resource($this->imageHandle)){ imagick_free($this->imageHandle); } if(is_resource($this->oldImage)){ imagick_free($this->oldImage); } return true; } } // End class ImageIM ?>
omda12/akelosframework
vendor/pear/Image/Transform/Driver/Imagick.php
PHP
lgpl-2.1
7,352
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "GenTemplateInstance.h" #include "Overview.h" #include <CppControl.h> #include <Scope.h> #include <Names.h> #include <Symbols.h> #include <CoreTypes.h> #include <Literals.h> #include <QtCore/QVarLengthArray> #include <QtCore/QDebug> using namespace CPlusPlus; namespace { class ApplySubstitution { public: ApplySubstitution(const LookupContext &context, Symbol *symbol, const GenTemplateInstance::Substitution &substitution); ~ApplySubstitution(); Control *control() const { return context.control(); } FullySpecifiedType apply(const Name *name); FullySpecifiedType apply(const FullySpecifiedType &type); int findSubstitution(const Identifier *id) const; FullySpecifiedType applySubstitution(int index) const; private: class ApplyToType: protected TypeVisitor { public: ApplyToType(ApplySubstitution *q) : q(q) {} FullySpecifiedType operator()(const FullySpecifiedType &ty) { FullySpecifiedType previousType = switchType(ty); accept(ty.type()); return switchType(previousType); } protected: using TypeVisitor::visit; Control *control() const { return q->control(); } FullySpecifiedType switchType(const FullySpecifiedType &type) { FullySpecifiedType previousType = _type; _type = type; return previousType; } virtual void visit(VoidType *) { // nothing to do } virtual void visit(IntegerType *) { // nothing to do } virtual void visit(FloatType *) { // nothing to do } virtual void visit(PointerToMemberType *) { qDebug() << Q_FUNC_INFO; // ### TODO } virtual void visit(PointerType *ptrTy) { _type.setType(control()->pointerType(q->apply(ptrTy->elementType()))); } virtual void visit(ReferenceType *refTy) { _type.setType(control()->referenceType(q->apply(refTy->elementType()))); } virtual void visit(ArrayType *arrayTy) { _type.setType(control()->arrayType(q->apply(arrayTy->elementType()), arrayTy->size())); } virtual void visit(NamedType *ty) { FullySpecifiedType n = q->apply(ty->name()); _type.setType(n.type()); } virtual void visit(Function *funTy) { Function *fun = control()->newFunction(/*sourceLocation=*/ 0, funTy->name()); fun->setScope(funTy->scope()); fun->setConst(funTy->isConst()); fun->setVolatile(funTy->isVolatile()); fun->setVirtual(funTy->isVirtual()); fun->setAmbiguous(funTy->isAmbiguous()); fun->setVariadic(funTy->isVariadic()); fun->setReturnType(q->apply(funTy->returnType())); for (unsigned i = 0; i < funTy->argumentCount(); ++i) { Argument *originalArgument = funTy->argumentAt(i)->asArgument(); Argument *arg = control()->newArgument(/*sourceLocation*/ 0, originalArgument->name()); arg->setType(q->apply(originalArgument->type())); arg->setInitializer(originalArgument->initializer()); fun->arguments()->enterSymbol(arg); } _type.setType(fun); } virtual void visit(Namespace *) { qDebug() << Q_FUNC_INFO; } virtual void visit(Class *) { qDebug() << Q_FUNC_INFO; } virtual void visit(Enum *) { qDebug() << Q_FUNC_INFO; } virtual void visit(ForwardClassDeclaration *) { qDebug() << Q_FUNC_INFO; } virtual void visit(ObjCClass *) { qDebug() << Q_FUNC_INFO; } virtual void visit(ObjCProtocol *) { qDebug() << Q_FUNC_INFO; } virtual void visit(ObjCMethod *) { qDebug() << Q_FUNC_INFO; } virtual void visit(ObjCForwardClassDeclaration *) { qDebug() << Q_FUNC_INFO; } virtual void visit(ObjCForwardProtocolDeclaration *) { qDebug() << Q_FUNC_INFO; } private: ApplySubstitution *q; FullySpecifiedType _type; QHash<Symbol *, FullySpecifiedType> _processed; }; class ApplyToName: protected NameVisitor { public: ApplyToName(ApplySubstitution *q): q(q) {} FullySpecifiedType operator()(const Name *name) { FullySpecifiedType previousType = switchType(FullySpecifiedType()); accept(name); return switchType(previousType); } protected: Control *control() const { return q->control(); } int findSubstitution(const Identifier *id) const { return q->findSubstitution(id); } FullySpecifiedType applySubstitution(int index) const { return q->applySubstitution(index); } FullySpecifiedType switchType(const FullySpecifiedType &type) { FullySpecifiedType previousType = _type; _type = type; return previousType; } virtual void visit(const NameId *name) { int index = findSubstitution(name->identifier()); if (index != -1) _type = applySubstitution(index); else _type = control()->namedType(name); } virtual void visit(const TemplateNameId *name) { QVarLengthArray<FullySpecifiedType, 8> arguments(name->templateArgumentCount()); for (unsigned i = 0; i < name->templateArgumentCount(); ++i) { FullySpecifiedType argTy = name->templateArgumentAt(i); arguments[i] = q->apply(argTy); } const TemplateNameId *templId = control()->templateNameId(name->identifier(), arguments.data(), arguments.size()); _type = control()->namedType(templId); } virtual void visit(const QualifiedNameId *name) { QVarLengthArray<const Name *, 8> names(name->nameCount()); for (unsigned i = 0; i < name->nameCount(); ++i) { const Name *n = name->nameAt(i); if (const TemplateNameId *templId = n->asTemplateNameId()) { QVarLengthArray<FullySpecifiedType, 8> arguments(templId->templateArgumentCount()); for (unsigned templateArgIndex = 0; templateArgIndex < templId->templateArgumentCount(); ++templateArgIndex) { FullySpecifiedType argTy = templId->templateArgumentAt(templateArgIndex); arguments[templateArgIndex] = q->apply(argTy); } n = control()->templateNameId(templId->identifier(), arguments.data(), arguments.size()); } names[i] = n; } const QualifiedNameId *q = control()->qualifiedNameId(names.data(), names.size(), name->isGlobal()); _type = control()->namedType(q); } virtual void visit(const DestructorNameId *name) { Overview oo; qWarning() << "ignored name:" << oo(name); } virtual void visit(const OperatorNameId *name) { Overview oo; qWarning() << "ignored name:" << oo(name); } virtual void visit(const ConversionNameId *name) { Overview oo; qWarning() << "ignored name:" << oo(name); } virtual void visit(const SelectorNameId *name) { Overview oo; qWarning() << "ignored name:" << oo(name); } private: ApplySubstitution *q; FullySpecifiedType _type; }; public: // attributes LookupContext context; Symbol *symbol; GenTemplateInstance::Substitution substitution; ApplyToType applyToType; ApplyToName applyToName; }; ApplySubstitution::ApplySubstitution(const LookupContext &context, Symbol *symbol, const GenTemplateInstance::Substitution &substitution) : context(context), symbol(symbol), substitution(substitution), applyToType(this), applyToName(this) { } ApplySubstitution::~ApplySubstitution() { } FullySpecifiedType ApplySubstitution::apply(const Name *name) { FullySpecifiedType ty = applyToName(name); return ty; } FullySpecifiedType ApplySubstitution::apply(const FullySpecifiedType &type) { FullySpecifiedType ty = applyToType(type); return ty; } int ApplySubstitution::findSubstitution(const Identifier *id) const { Q_ASSERT(id != 0); for (int index = 0; index < substitution.size(); ++index) { QPair<const Identifier *, FullySpecifiedType> s = substitution.at(index); if (id->isEqualTo(s.first)) return index; } return -1; } FullySpecifiedType ApplySubstitution::applySubstitution(int index) const { Q_ASSERT(index != -1); Q_ASSERT(index < substitution.size()); return substitution.at(index).second; } } // end of anonymous namespace GenTemplateInstance::GenTemplateInstance(const LookupContext &context, const Substitution &substitution) : _symbol(0), _context(context), _substitution(substitution) { } FullySpecifiedType GenTemplateInstance::operator()(Symbol *symbol) { ApplySubstitution o(_context, symbol, _substitution); return o.apply(symbol->type()); } Control *GenTemplateInstance::control() const { return _context.control(); }
KDE/android-qt-mobility
tools/icheck/parser/src/libs/cplusplus/GenTemplateInstance.cpp
C++
lgpl-2.1
11,481
"""Wrapper functions for Tcl/Tk. Tkinter provides classes which allow the display, positioning and control of widgets. Toplevel widgets are Tk and Toplevel. Other widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton, Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox LabelFrame and PanedWindow. Properties of the widgets are specified with keyword arguments. Keyword arguments have the same name as the corresponding resource under Tk. Widgets are positioned with one of the geometry managers Place, Pack or Grid. These managers can be called with methods place, pack, grid available in every Widget. Actions are bound to events by resources (e.g. keyword argument command) or with the method bind. Example (Hello, World): import tkinter from tkinter.constants import * tk = tkinter.Tk() frame = tkinter.Frame(tk, relief=RIDGE, borderwidth=2) frame.pack(fill=BOTH,expand=1) label = tkinter.Label(frame, text="Hello, World") label.pack(fill=X, expand=1) button = tkinter.Button(frame,text="Exit",command=tk.destroy) button.pack(side=BOTTOM) tk.mainloop() """ import enum import sys import _tkinter # If this fails your Python may not be configured for Tk TclError = _tkinter.TclError from tkinter.constants import * import re wantobjects = 1 TkVersion = float(_tkinter.TK_VERSION) TclVersion = float(_tkinter.TCL_VERSION) READABLE = _tkinter.READABLE WRITABLE = _tkinter.WRITABLE EXCEPTION = _tkinter.EXCEPTION _magic_re = re.compile(r'([\\{}])') _space_re = re.compile(r'([\s])', re.ASCII) def _join(value): """Internal function.""" return ' '.join(map(_stringify, value)) def _stringify(value): """Internal function.""" if isinstance(value, (list, tuple)): if len(value) == 1: value = _stringify(value[0]) if _magic_re.search(value): value = '{%s}' % value else: value = '{%s}' % _join(value) else: value = str(value) if not value: value = '{}' elif _magic_re.search(value): # add '\' before special characters and spaces value = _magic_re.sub(r'\\\1', value) value = value.replace('\n', r'\n') value = _space_re.sub(r'\\\1', value) if value[0] == '"': value = '\\' + value elif value[0] == '"' or _space_re.search(value): value = '{%s}' % value return value def _flatten(seq): """Internal function.""" res = () for item in seq: if isinstance(item, (tuple, list)): res = res + _flatten(item) elif item is not None: res = res + (item,) return res try: _flatten = _tkinter._flatten except AttributeError: pass def _cnfmerge(cnfs): """Internal function.""" if isinstance(cnfs, dict): return cnfs elif isinstance(cnfs, (type(None), str)): return cnfs else: cnf = {} for c in _flatten(cnfs): try: cnf.update(c) except (AttributeError, TypeError) as msg: print("_cnfmerge: fallback due to:", msg) for k, v in c.items(): cnf[k] = v return cnf try: _cnfmerge = _tkinter._cnfmerge except AttributeError: pass def _splitdict(tk, v, cut_minus=True, conv=None): """Return a properly formatted dict built from Tcl list pairs. If cut_minus is True, the supposed '-' prefix will be removed from keys. If conv is specified, it is used to convert values. Tcl list is expected to contain an even number of elements. """ t = tk.splitlist(v) if len(t) % 2: raise RuntimeError('Tcl list representing a dict is expected ' 'to contain an even number of elements') it = iter(t) dict = {} for key, value in zip(it, it): key = str(key) if cut_minus and key[0] == '-': key = key[1:] if conv: value = conv(value) dict[key] = value return dict class EventType(str, enum.Enum): KeyPress = '2' Key = KeyPress, KeyRelease = '3' ButtonPress = '4' Button = ButtonPress, ButtonRelease = '5' Motion = '6' Enter = '7' Leave = '8' FocusIn = '9' FocusOut = '10' Keymap = '11' # undocumented Expose = '12' GraphicsExpose = '13' # undocumented NoExpose = '14' # undocumented Visibility = '15' Create = '16' Destroy = '17' Unmap = '18' Map = '19' MapRequest = '20' Reparent = '21' Configure = '22' ConfigureRequest = '23' Gravity = '24' ResizeRequest = '25' Circulate = '26' CirculateRequest = '27' Property = '28' SelectionClear = '29' # undocumented SelectionRequest = '30' # undocumented Selection = '31' # undocumented Colormap = '32' ClientMessage = '33' # undocumented Mapping = '34' # undocumented VirtualEvent = '35', # undocumented Activate = '36', Deactivate = '37', MouseWheel = '38', def __str__(self): return self.name class Event: """Container for the properties of an event. Instances of this type are generated if one of the following events occurs: KeyPress, KeyRelease - for keyboard events ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate, Colormap, Gravity, Reparent, Property, Destroy, Activate, Deactivate - for window events. If a callback function for one of these events is registered using bind, bind_all, bind_class, or tag_bind, the callback is called with an Event as first argument. It will have the following attributes (in braces are the event types for which the attribute is valid): serial - serial number of event num - mouse button pressed (ButtonPress, ButtonRelease) focus - whether the window has the focus (Enter, Leave) height - height of the exposed window (Configure, Expose) width - width of the exposed window (Configure, Expose) keycode - keycode of the pressed key (KeyPress, KeyRelease) state - state of the event as a number (ButtonPress, ButtonRelease, Enter, KeyPress, KeyRelease, Leave, Motion) state - state as a string (Visibility) time - when the event occurred x - x-position of the mouse y - y-position of the mouse x_root - x-position of the mouse on the screen (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion) y_root - y-position of the mouse on the screen (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion) char - pressed character (KeyPress, KeyRelease) send_event - see X/Windows documentation keysym - keysym of the event as a string (KeyPress, KeyRelease) keysym_num - keysym of the event as a number (KeyPress, KeyRelease) type - type of the event as a number widget - widget in which the event occurred delta - delta of wheel movement (MouseWheel) """ def __repr__(self): attrs = {k: v for k, v in self.__dict__.items() if v != '??'} if not self.char: del attrs['char'] elif self.char != '??': attrs['char'] = repr(self.char) if not getattr(self, 'send_event', True): del attrs['send_event'] if self.state == 0: del attrs['state'] elif isinstance(self.state, int): state = self.state mods = ('Shift', 'Lock', 'Control', 'Mod1', 'Mod2', 'Mod3', 'Mod4', 'Mod5', 'Button1', 'Button2', 'Button3', 'Button4', 'Button5') s = [] for i, n in enumerate(mods): if state & (1 << i): s.append(n) state = state & ~((1<< len(mods)) - 1) if state or not s: s.append(hex(state)) attrs['state'] = '|'.join(s) if self.delta == 0: del attrs['delta'] # widget usually is known # serial and time are not very interesting # keysym_num duplicates keysym # x_root and y_root mostly duplicate x and y keys = ('send_event', 'state', 'keysym', 'keycode', 'char', 'num', 'delta', 'focus', 'x', 'y', 'width', 'height') return '<%s event%s>' % ( self.type, ''.join(' %s=%s' % (k, attrs[k]) for k in keys if k in attrs) ) _support_default_root = 1 _default_root = None def NoDefaultRoot(): """Inhibit setting of default root window. Call this function to inhibit that the first instance of Tk is used for windows without an explicit parent window. """ global _support_default_root _support_default_root = 0 global _default_root _default_root = None del _default_root def _tkerror(err): """Internal function.""" pass def _exit(code=0): """Internal function. Calling it will raise the exception SystemExit.""" try: code = int(code) except ValueError: pass raise SystemExit(code) _varnum = 0 class Variable: """Class to define value holders for e.g. buttons. Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations that constrain the type of the value returned from get().""" _default = "" _tk = None _tclCommands = None def __init__(self, master=None, value=None, name=None): """Construct a variable MASTER can be given as master widget. VALUE is an optional value (defaults to "") NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ # check for type of NAME parameter to override weird error message # raised from Modules/_tkinter.c:SetVar like: # TypeError: setvar() takes exactly 3 arguments (2 given) if name is not None and not isinstance(name, str): raise TypeError("name must be a string") global _varnum if not master: master = _default_root self._root = master._root() self._tk = master.tk if name: self._name = name else: self._name = 'PY_VAR' + repr(_varnum) _varnum += 1 if value is not None: self.initialize(value) elif not self._tk.getboolean(self._tk.call("info", "exists", self._name)): self.initialize(self._default) def __del__(self): """Unset the variable in Tcl.""" if self._tk is None: return if self._tk.getboolean(self._tk.call("info", "exists", self._name)): self._tk.globalunsetvar(self._name) if self._tclCommands is not None: for name in self._tclCommands: #print '- Tkinter: deleted command', name self._tk.deletecommand(name) self._tclCommands = None def __str__(self): """Return the name of the variable in Tcl.""" return self._name def set(self, value): """Set the variable to VALUE.""" return self._tk.globalsetvar(self._name, value) initialize = set def get(self): """Return value of variable.""" return self._tk.globalgetvar(self._name) def _register(self, callback): f = CallWrapper(callback, None, self._root).__call__ cbname = repr(id(f)) try: callback = callback.__func__ except AttributeError: pass try: cbname = cbname + callback.__name__ except AttributeError: pass self._tk.createcommand(cbname, f) if self._tclCommands is None: self._tclCommands = [] self._tclCommands.append(cbname) return cbname def trace_add(self, mode, callback): """Define a trace callback for the variable. Mode is one of "read", "write", "unset", or a list or tuple of such strings. Callback must be a function which is called when the variable is read, written or unset. Return the name of the callback. """ cbname = self._register(callback) self._tk.call('trace', 'add', 'variable', self._name, mode, (cbname,)) return cbname def trace_remove(self, mode, cbname): """Delete the trace callback for a variable. Mode is one of "read", "write", "unset" or a list or tuple of such strings. Must be same as were specified in trace_add(). cbname is the name of the callback returned from trace_add(). """ self._tk.call('trace', 'remove', 'variable', self._name, mode, cbname) for m, ca in self.trace_info(): if self._tk.splitlist(ca)[0] == cbname: break else: self._tk.deletecommand(cbname) try: self._tclCommands.remove(cbname) except ValueError: pass def trace_info(self): """Return all trace callback information.""" splitlist = self._tk.splitlist return [(splitlist(k), v) for k, v in map(splitlist, splitlist(self._tk.call('trace', 'info', 'variable', self._name)))] def trace_variable(self, mode, callback): """Define a trace callback for the variable. MODE is one of "r", "w", "u" for read, write, undefine. CALLBACK must be a function which is called when the variable is read, written or undefined. Return the name of the callback. This deprecated method wraps a deprecated Tcl method that will likely be removed in the future. Use trace_add() instead. """ # TODO: Add deprecation warning cbname = self._register(callback) self._tk.call("trace", "variable", self._name, mode, cbname) return cbname trace = trace_variable def trace_vdelete(self, mode, cbname): """Delete the trace callback for a variable. MODE is one of "r", "w", "u" for read, write, undefine. CBNAME is the name of the callback returned from trace_variable or trace. This deprecated method wraps a deprecated Tcl method that will likely be removed in the future. Use trace_remove() instead. """ # TODO: Add deprecation warning self._tk.call("trace", "vdelete", self._name, mode, cbname) cbname = self._tk.splitlist(cbname)[0] for m, ca in self.trace_info(): if self._tk.splitlist(ca)[0] == cbname: break else: self._tk.deletecommand(cbname) try: self._tclCommands.remove(cbname) except ValueError: pass def trace_vinfo(self): """Return all trace callback information. This deprecated method wraps a deprecated Tcl method that will likely be removed in the future. Use trace_info() instead. """ # TODO: Add deprecation warning return [self._tk.splitlist(x) for x in self._tk.splitlist( self._tk.call("trace", "vinfo", self._name))] def __eq__(self, other): """Comparison for equality (==). Note: if the Variable's master matters to behavior also compare self._master == other._master """ return self.__class__.__name__ == other.__class__.__name__ \ and self._name == other._name class StringVar(Variable): """Value holder for strings variables.""" _default = "" def __init__(self, master=None, value=None, name=None): """Construct a string variable. MASTER can be given as master widget. VALUE is an optional value (defaults to "") NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name) def get(self): """Return value of variable as string.""" value = self._tk.globalgetvar(self._name) if isinstance(value, str): return value return str(value) class IntVar(Variable): """Value holder for integer variables.""" _default = 0 def __init__(self, master=None, value=None, name=None): """Construct an integer variable. MASTER can be given as master widget. VALUE is an optional value (defaults to 0) NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name) def get(self): """Return the value of the variable as an integer.""" value = self._tk.globalgetvar(self._name) try: return self._tk.getint(value) except (TypeError, TclError): return int(self._tk.getdouble(value)) class DoubleVar(Variable): """Value holder for float variables.""" _default = 0.0 def __init__(self, master=None, value=None, name=None): """Construct a float variable. MASTER can be given as master widget. VALUE is an optional value (defaults to 0.0) NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name) def get(self): """Return the value of the variable as a float.""" return self._tk.getdouble(self._tk.globalgetvar(self._name)) class BooleanVar(Variable): """Value holder for boolean variables.""" _default = False def __init__(self, master=None, value=None, name=None): """Construct a boolean variable. MASTER can be given as master widget. VALUE is an optional value (defaults to False) NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name) def set(self, value): """Set the variable to VALUE.""" return self._tk.globalsetvar(self._name, self._tk.getboolean(value)) initialize = set def get(self): """Return the value of the variable as a bool.""" try: return self._tk.getboolean(self._tk.globalgetvar(self._name)) except TclError: raise ValueError("invalid literal for getboolean()") def mainloop(n=0): """Run the main loop of Tcl.""" _default_root.tk.mainloop(n) getint = int getdouble = float def getboolean(s): """Convert true and false to integer values 1 and 0.""" try: return _default_root.tk.getboolean(s) except TclError: raise ValueError("invalid literal for getboolean()") # Methods defined on both toplevel and interior widgets class Misc: """Internal class. Base class which defines methods common for interior widgets.""" # used for generating child widget names _last_child_ids = None # XXX font command? _tclCommands = None def destroy(self): """Internal function. Delete all Tcl commands created for this widget in the Tcl interpreter.""" if self._tclCommands is not None: for name in self._tclCommands: #print '- Tkinter: deleted command', name self.tk.deletecommand(name) self._tclCommands = None def deletecommand(self, name): """Internal function. Delete the Tcl command provided in NAME.""" #print '- Tkinter: deleted command', name self.tk.deletecommand(name) try: self._tclCommands.remove(name) except ValueError: pass def tk_strictMotif(self, boolean=None): """Set Tcl internal variable, whether the look and feel should adhere to Motif. A parameter of 1 means adhere to Motif (e.g. no color change if mouse passes over slider). Returns the set value.""" return self.tk.getboolean(self.tk.call( 'set', 'tk_strictMotif', boolean)) def tk_bisque(self): """Change the color scheme to light brown as used in Tk 3.6 and before.""" self.tk.call('tk_bisque') def tk_setPalette(self, *args, **kw): """Set a new color scheme for all widget elements. A single color as argument will cause that all colors of Tk widget elements are derived from this. Alternatively several keyword parameters and its associated colors can be given. The following keywords are valid: activeBackground, foreground, selectColor, activeForeground, highlightBackground, selectBackground, background, highlightColor, selectForeground, disabledForeground, insertBackground, troughColor.""" self.tk.call(('tk_setPalette',) + _flatten(args) + _flatten(list(kw.items()))) def wait_variable(self, name='PY_VAR'): """Wait until the variable is modified. A parameter of type IntVar, StringVar, DoubleVar or BooleanVar must be given.""" self.tk.call('tkwait', 'variable', name) waitvar = wait_variable # XXX b/w compat def wait_window(self, window=None): """Wait until a WIDGET is destroyed. If no parameter is given self is used.""" if window is None: window = self self.tk.call('tkwait', 'window', window._w) def wait_visibility(self, window=None): """Wait until the visibility of a WIDGET changes (e.g. it appears). If no parameter is given self is used.""" if window is None: window = self self.tk.call('tkwait', 'visibility', window._w) def setvar(self, name='PY_VAR', value='1'): """Set Tcl variable NAME to VALUE.""" self.tk.setvar(name, value) def getvar(self, name='PY_VAR'): """Return value of Tcl variable NAME.""" return self.tk.getvar(name) def getint(self, s): try: return self.tk.getint(s) except TclError as exc: raise ValueError(str(exc)) def getdouble(self, s): try: return self.tk.getdouble(s) except TclError as exc: raise ValueError(str(exc)) def getboolean(self, s): """Return a boolean value for Tcl boolean values true and false given as parameter.""" try: return self.tk.getboolean(s) except TclError: raise ValueError("invalid literal for getboolean()") def focus_set(self): """Direct input focus to this widget. If the application currently does not have the focus this widget will get the focus if the application gets the focus through the window manager.""" self.tk.call('focus', self._w) focus = focus_set # XXX b/w compat? def focus_force(self): """Direct input focus to this widget even if the application does not have the focus. Use with caution!""" self.tk.call('focus', '-force', self._w) def focus_get(self): """Return the widget which has currently the focus in the application. Use focus_displayof to allow working with several displays. Return None if application does not have the focus.""" name = self.tk.call('focus') if name == 'none' or not name: return None return self._nametowidget(name) def focus_displayof(self): """Return the widget which has currently the focus on the display where this widget is located. Return None if the application does not have the focus.""" name = self.tk.call('focus', '-displayof', self._w) if name == 'none' or not name: return None return self._nametowidget(name) def focus_lastfor(self): """Return the widget which would have the focus if top level for this widget gets the focus from the window manager.""" name = self.tk.call('focus', '-lastfor', self._w) if name == 'none' or not name: return None return self._nametowidget(name) def tk_focusFollowsMouse(self): """The widget under mouse will get automatically focus. Can not be disabled easily.""" self.tk.call('tk_focusFollowsMouse') def tk_focusNext(self): """Return the next widget in the focus order which follows widget which has currently the focus. The focus order first goes to the next child, then to the children of the child recursively and then to the next sibling which is higher in the stacking order. A widget is omitted if it has the takefocus resource set to 0.""" name = self.tk.call('tk_focusNext', self._w) if not name: return None return self._nametowidget(name) def tk_focusPrev(self): """Return previous widget in the focus order. See tk_focusNext for details.""" name = self.tk.call('tk_focusPrev', self._w) if not name: return None return self._nametowidget(name) def after(self, ms, func=None, *args): """Call function once after given time. MS specifies the time in milliseconds. FUNC gives the function which shall be called. Additional parameters are given as parameters to the function call. Return identifier to cancel scheduling with after_cancel.""" if not func: # I'd rather use time.sleep(ms*0.001) self.tk.call('after', ms) return None else: def callit(): try: func(*args) finally: try: self.deletecommand(name) except TclError: pass callit.__name__ = func.__name__ name = self._register(callit) return self.tk.call('after', ms, name) def after_idle(self, func, *args): """Call FUNC once if the Tcl main loop has no event to process. Return an identifier to cancel the scheduling with after_cancel.""" return self.after('idle', func, *args) def after_cancel(self, id): """Cancel scheduling of function identified with ID. Identifier returned by after or after_idle must be given as first parameter. """ if not id: raise ValueError('id must be a valid identifier returned from ' 'after or after_idle') try: data = self.tk.call('after', 'info', id) script = self.tk.splitlist(data)[0] self.deletecommand(script) except TclError: pass self.tk.call('after', 'cancel', id) def bell(self, displayof=0): """Ring a display's bell.""" self.tk.call(('bell',) + self._displayof(displayof)) # Clipboard handling: def clipboard_get(self, **kw): """Retrieve data from the clipboard on window's display. The window keyword defaults to the root window of the Tkinter application. The type keyword specifies the form in which the data is to be returned and should be an atom name such as STRING or FILE_NAME. Type defaults to STRING, except on X11, where the default is to try UTF8_STRING and fall back to STRING. This command is equivalent to: selection_get(CLIPBOARD) """ if 'type' not in kw and self._windowingsystem == 'x11': try: kw['type'] = 'UTF8_STRING' return self.tk.call(('clipboard', 'get') + self._options(kw)) except TclError: del kw['type'] return self.tk.call(('clipboard', 'get') + self._options(kw)) def clipboard_clear(self, **kw): """Clear the data in the Tk clipboard. A widget specified for the optional displayof keyword argument specifies the target display.""" if 'displayof' not in kw: kw['displayof'] = self._w self.tk.call(('clipboard', 'clear') + self._options(kw)) def clipboard_append(self, string, **kw): """Append STRING to the Tk clipboard. A widget specified at the optional displayof keyword argument specifies the target display. The clipboard can be retrieved with selection_get.""" if 'displayof' not in kw: kw['displayof'] = self._w self.tk.call(('clipboard', 'append') + self._options(kw) + ('--', string)) # XXX grab current w/o window argument def grab_current(self): """Return widget which has currently the grab in this application or None.""" name = self.tk.call('grab', 'current', self._w) if not name: return None return self._nametowidget(name) def grab_release(self): """Release grab for this widget if currently set.""" self.tk.call('grab', 'release', self._w) def grab_set(self): """Set grab for this widget. A grab directs all events to this and descendant widgets in the application.""" self.tk.call('grab', 'set', self._w) def grab_set_global(self): """Set global grab for this widget. A global grab directs all events to this and descendant widgets on the display. Use with caution - other applications do not get events anymore.""" self.tk.call('grab', 'set', '-global', self._w) def grab_status(self): """Return None, "local" or "global" if this widget has no, a local or a global grab.""" status = self.tk.call('grab', 'status', self._w) if status == 'none': status = None return status def option_add(self, pattern, value, priority = None): """Set a VALUE (second parameter) for an option PATTERN (first parameter). An optional third parameter gives the numeric priority (defaults to 80).""" self.tk.call('option', 'add', pattern, value, priority) def option_clear(self): """Clear the option database. It will be reloaded if option_add is called.""" self.tk.call('option', 'clear') def option_get(self, name, className): """Return the value for an option NAME for this widget with CLASSNAME. Values with higher priority override lower values.""" return self.tk.call('option', 'get', self._w, name, className) def option_readfile(self, fileName, priority = None): """Read file FILENAME into the option database. An optional second parameter gives the numeric priority.""" self.tk.call('option', 'readfile', fileName, priority) def selection_clear(self, **kw): """Clear the current X selection.""" if 'displayof' not in kw: kw['displayof'] = self._w self.tk.call(('selection', 'clear') + self._options(kw)) def selection_get(self, **kw): """Return the contents of the current X selection. A keyword parameter selection specifies the name of the selection and defaults to PRIMARY. A keyword parameter displayof specifies a widget on the display to use. A keyword parameter type specifies the form of data to be fetched, defaulting to STRING except on X11, where UTF8_STRING is tried before STRING.""" if 'displayof' not in kw: kw['displayof'] = self._w if 'type' not in kw and self._windowingsystem == 'x11': try: kw['type'] = 'UTF8_STRING' return self.tk.call(('selection', 'get') + self._options(kw)) except TclError: del kw['type'] return self.tk.call(('selection', 'get') + self._options(kw)) def selection_handle(self, command, **kw): """Specify a function COMMAND to call if the X selection owned by this widget is queried by another application. This function must return the contents of the selection. The function will be called with the arguments OFFSET and LENGTH which allows the chunking of very long selections. The following keyword parameters can be provided: selection - name of the selection (default PRIMARY), type - type of the selection (e.g. STRING, FILE_NAME).""" name = self._register(command) self.tk.call(('selection', 'handle') + self._options(kw) + (self._w, name)) def selection_own(self, **kw): """Become owner of X selection. A keyword parameter selection specifies the name of the selection (default PRIMARY).""" self.tk.call(('selection', 'own') + self._options(kw) + (self._w,)) def selection_own_get(self, **kw): """Return owner of X selection. The following keyword parameter can be provided: selection - name of the selection (default PRIMARY), type - type of the selection (e.g. STRING, FILE_NAME).""" if 'displayof' not in kw: kw['displayof'] = self._w name = self.tk.call(('selection', 'own') + self._options(kw)) if not name: return None return self._nametowidget(name) def send(self, interp, cmd, *args): """Send Tcl command CMD to different interpreter INTERP to be executed.""" return self.tk.call(('send', interp, cmd) + args) def lower(self, belowThis=None): """Lower this widget in the stacking order.""" self.tk.call('lower', self._w, belowThis) def tkraise(self, aboveThis=None): """Raise this widget in the stacking order.""" self.tk.call('raise', self._w, aboveThis) lift = tkraise def winfo_atom(self, name, displayof=0): """Return integer which represents atom NAME.""" args = ('winfo', 'atom') + self._displayof(displayof) + (name,) return self.tk.getint(self.tk.call(args)) def winfo_atomname(self, id, displayof=0): """Return name of atom with identifier ID.""" args = ('winfo', 'atomname') \ + self._displayof(displayof) + (id,) return self.tk.call(args) def winfo_cells(self): """Return number of cells in the colormap for this widget.""" return self.tk.getint( self.tk.call('winfo', 'cells', self._w)) def winfo_children(self): """Return a list of all widgets which are children of this widget.""" result = [] for child in self.tk.splitlist( self.tk.call('winfo', 'children', self._w)): try: # Tcl sometimes returns extra windows, e.g. for # menus; those need to be skipped result.append(self._nametowidget(child)) except KeyError: pass return result def winfo_class(self): """Return window class name of this widget.""" return self.tk.call('winfo', 'class', self._w) def winfo_colormapfull(self): """Return True if at the last color request the colormap was full.""" return self.tk.getboolean( self.tk.call('winfo', 'colormapfull', self._w)) def winfo_containing(self, rootX, rootY, displayof=0): """Return the widget which is at the root coordinates ROOTX, ROOTY.""" args = ('winfo', 'containing') \ + self._displayof(displayof) + (rootX, rootY) name = self.tk.call(args) if not name: return None return self._nametowidget(name) def winfo_depth(self): """Return the number of bits per pixel.""" return self.tk.getint(self.tk.call('winfo', 'depth', self._w)) def winfo_exists(self): """Return true if this widget exists.""" return self.tk.getint( self.tk.call('winfo', 'exists', self._w)) def winfo_fpixels(self, number): """Return the number of pixels for the given distance NUMBER (e.g. "3c") as float.""" return self.tk.getdouble(self.tk.call( 'winfo', 'fpixels', self._w, number)) def winfo_geometry(self): """Return geometry string for this widget in the form "widthxheight+X+Y".""" return self.tk.call('winfo', 'geometry', self._w) def winfo_height(self): """Return height of this widget.""" return self.tk.getint( self.tk.call('winfo', 'height', self._w)) def winfo_id(self): """Return identifier ID for this widget.""" return int(self.tk.call('winfo', 'id', self._w), 0) def winfo_interps(self, displayof=0): """Return the name of all Tcl interpreters for this display.""" args = ('winfo', 'interps') + self._displayof(displayof) return self.tk.splitlist(self.tk.call(args)) def winfo_ismapped(self): """Return true if this widget is mapped.""" return self.tk.getint( self.tk.call('winfo', 'ismapped', self._w)) def winfo_manager(self): """Return the window manager name for this widget.""" return self.tk.call('winfo', 'manager', self._w) def winfo_name(self): """Return the name of this widget.""" return self.tk.call('winfo', 'name', self._w) def winfo_parent(self): """Return the name of the parent of this widget.""" return self.tk.call('winfo', 'parent', self._w) def winfo_pathname(self, id, displayof=0): """Return the pathname of the widget given by ID.""" args = ('winfo', 'pathname') \ + self._displayof(displayof) + (id,) return self.tk.call(args) def winfo_pixels(self, number): """Rounded integer value of winfo_fpixels.""" return self.tk.getint( self.tk.call('winfo', 'pixels', self._w, number)) def winfo_pointerx(self): """Return the x coordinate of the pointer on the root window.""" return self.tk.getint( self.tk.call('winfo', 'pointerx', self._w)) def winfo_pointerxy(self): """Return a tuple of x and y coordinates of the pointer on the root window.""" return self._getints( self.tk.call('winfo', 'pointerxy', self._w)) def winfo_pointery(self): """Return the y coordinate of the pointer on the root window.""" return self.tk.getint( self.tk.call('winfo', 'pointery', self._w)) def winfo_reqheight(self): """Return requested height of this widget.""" return self.tk.getint( self.tk.call('winfo', 'reqheight', self._w)) def winfo_reqwidth(self): """Return requested width of this widget.""" return self.tk.getint( self.tk.call('winfo', 'reqwidth', self._w)) def winfo_rgb(self, color): """Return tuple of decimal values for red, green, blue for COLOR in this widget.""" return self._getints( self.tk.call('winfo', 'rgb', self._w, color)) def winfo_rootx(self): """Return x coordinate of upper left corner of this widget on the root window.""" return self.tk.getint( self.tk.call('winfo', 'rootx', self._w)) def winfo_rooty(self): """Return y coordinate of upper left corner of this widget on the root window.""" return self.tk.getint( self.tk.call('winfo', 'rooty', self._w)) def winfo_screen(self): """Return the screen name of this widget.""" return self.tk.call('winfo', 'screen', self._w) def winfo_screencells(self): """Return the number of the cells in the colormap of the screen of this widget.""" return self.tk.getint( self.tk.call('winfo', 'screencells', self._w)) def winfo_screendepth(self): """Return the number of bits per pixel of the root window of the screen of this widget.""" return self.tk.getint( self.tk.call('winfo', 'screendepth', self._w)) def winfo_screenheight(self): """Return the number of pixels of the height of the screen of this widget in pixel.""" return self.tk.getint( self.tk.call('winfo', 'screenheight', self._w)) def winfo_screenmmheight(self): """Return the number of pixels of the height of the screen of this widget in mm.""" return self.tk.getint( self.tk.call('winfo', 'screenmmheight', self._w)) def winfo_screenmmwidth(self): """Return the number of pixels of the width of the screen of this widget in mm.""" return self.tk.getint( self.tk.call('winfo', 'screenmmwidth', self._w)) def winfo_screenvisual(self): """Return one of the strings directcolor, grayscale, pseudocolor, staticcolor, staticgray, or truecolor for the default colormodel of this screen.""" return self.tk.call('winfo', 'screenvisual', self._w) def winfo_screenwidth(self): """Return the number of pixels of the width of the screen of this widget in pixel.""" return self.tk.getint( self.tk.call('winfo', 'screenwidth', self._w)) def winfo_server(self): """Return information of the X-Server of the screen of this widget in the form "XmajorRminor vendor vendorVersion".""" return self.tk.call('winfo', 'server', self._w) def winfo_toplevel(self): """Return the toplevel widget of this widget.""" return self._nametowidget(self.tk.call( 'winfo', 'toplevel', self._w)) def winfo_viewable(self): """Return true if the widget and all its higher ancestors are mapped.""" return self.tk.getint( self.tk.call('winfo', 'viewable', self._w)) def winfo_visual(self): """Return one of the strings directcolor, grayscale, pseudocolor, staticcolor, staticgray, or truecolor for the colormodel of this widget.""" return self.tk.call('winfo', 'visual', self._w) def winfo_visualid(self): """Return the X identifier for the visual for this widget.""" return self.tk.call('winfo', 'visualid', self._w) def winfo_visualsavailable(self, includeids=False): """Return a list of all visuals available for the screen of this widget. Each item in the list consists of a visual name (see winfo_visual), a depth and if includeids is true is given also the X identifier.""" data = self.tk.call('winfo', 'visualsavailable', self._w, 'includeids' if includeids else None) data = [self.tk.splitlist(x) for x in self.tk.splitlist(data)] return [self.__winfo_parseitem(x) for x in data] def __winfo_parseitem(self, t): """Internal function.""" return t[:1] + tuple(map(self.__winfo_getint, t[1:])) def __winfo_getint(self, x): """Internal function.""" return int(x, 0) def winfo_vrootheight(self): """Return the height of the virtual root window associated with this widget in pixels. If there is no virtual root window return the height of the screen.""" return self.tk.getint( self.tk.call('winfo', 'vrootheight', self._w)) def winfo_vrootwidth(self): """Return the width of the virtual root window associated with this widget in pixel. If there is no virtual root window return the width of the screen.""" return self.tk.getint( self.tk.call('winfo', 'vrootwidth', self._w)) def winfo_vrootx(self): """Return the x offset of the virtual root relative to the root window of the screen of this widget.""" return self.tk.getint( self.tk.call('winfo', 'vrootx', self._w)) def winfo_vrooty(self): """Return the y offset of the virtual root relative to the root window of the screen of this widget.""" return self.tk.getint( self.tk.call('winfo', 'vrooty', self._w)) def winfo_width(self): """Return the width of this widget.""" return self.tk.getint( self.tk.call('winfo', 'width', self._w)) def winfo_x(self): """Return the x coordinate of the upper left corner of this widget in the parent.""" return self.tk.getint( self.tk.call('winfo', 'x', self._w)) def winfo_y(self): """Return the y coordinate of the upper left corner of this widget in the parent.""" return self.tk.getint( self.tk.call('winfo', 'y', self._w)) def update(self): """Enter event loop until all pending events have been processed by Tcl.""" self.tk.call('update') def update_idletasks(self): """Enter event loop until all idle callbacks have been called. This will update the display of windows but not process events caused by the user.""" self.tk.call('update', 'idletasks') def bindtags(self, tagList=None): """Set or get the list of bindtags for this widget. With no argument return the list of all bindtags associated with this widget. With a list of strings as argument the bindtags are set to this list. The bindtags determine in which order events are processed (see bind).""" if tagList is None: return self.tk.splitlist( self.tk.call('bindtags', self._w)) else: self.tk.call('bindtags', self._w, tagList) def _bind(self, what, sequence, func, add, needcleanup=1): """Internal function.""" if isinstance(func, str): self.tk.call(what + (sequence, func)) elif func: funcid = self._register(func, self._substitute, needcleanup) cmd = ('%sif {"[%s %s]" == "break"} break\n' % (add and '+' or '', funcid, self._subst_format_str)) self.tk.call(what + (sequence, cmd)) return funcid elif sequence: return self.tk.call(what + (sequence,)) else: return self.tk.splitlist(self.tk.call(what)) def bind(self, sequence=None, func=None, add=None): """Bind to this widget at event SEQUENCE a call to function FUNC. SEQUENCE is a string of concatenated event patterns. An event pattern is of the form <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4, Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3, B3, Alt, Button4, B4, Double, Button5, B5 Triple, Mod1, M1. TYPE is one of Activate, Enter, Map, ButtonPress, Button, Expose, Motion, ButtonRelease FocusIn, MouseWheel, Circulate, FocusOut, Property, Colormap, Gravity Reparent, Configure, KeyPress, Key, Unmap, Deactivate, KeyRelease Visibility, Destroy, Leave and DETAIL is the button number for ButtonPress, ButtonRelease and DETAIL is the Keysym for KeyPress and KeyRelease. Examples are <Control-Button-1> for pressing Control and mouse button 1 or <Alt-A> for pressing A and the Alt key (KeyPress can be omitted). An event pattern can also be a virtual event of the form <<AString>> where AString can be arbitrary. This event can be generated by event_generate. If events are concatenated they must appear shortly after each other. FUNC will be called if the event sequence occurs with an instance of Event as argument. If the return value of FUNC is "break" no further bound function is invoked. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. Bind will return an identifier to allow deletion of the bound function with unbind without memory leak. If FUNC or SEQUENCE is omitted the bound function or list of bound events are returned.""" return self._bind(('bind', self._w), sequence, func, add) def unbind(self, sequence, funcid=None): """Unbind for this widget for event SEQUENCE the function identified with FUNCID.""" self.tk.call('bind', self._w, sequence, '') if funcid: self.deletecommand(funcid) def bind_all(self, sequence=None, func=None, add=None): """Bind to all widgets at an event SEQUENCE a call to function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.""" return self._bind(('bind', 'all'), sequence, func, add, 0) def unbind_all(self, sequence): """Unbind for all widgets for event SEQUENCE all functions.""" self.tk.call('bind', 'all' , sequence, '') def bind_class(self, className, sequence=None, func=None, add=None): """Bind to widgets with bindtag CLASSNAME at event SEQUENCE a call of function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.""" return self._bind(('bind', className), sequence, func, add, 0) def unbind_class(self, className, sequence): """Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE all functions.""" self.tk.call('bind', className , sequence, '') def mainloop(self, n=0): """Call the mainloop of Tk.""" self.tk.mainloop(n) def quit(self): """Quit the Tcl interpreter. All widgets will be destroyed.""" self.tk.quit() def _getints(self, string): """Internal function.""" if string: return tuple(map(self.tk.getint, self.tk.splitlist(string))) def _getdoubles(self, string): """Internal function.""" if string: return tuple(map(self.tk.getdouble, self.tk.splitlist(string))) def _getboolean(self, string): """Internal function.""" if string: return self.tk.getboolean(string) def _displayof(self, displayof): """Internal function.""" if displayof: return ('-displayof', displayof) if displayof is None: return ('-displayof', self._w) return () @property def _windowingsystem(self): """Internal function.""" try: return self._root()._windowingsystem_cached except AttributeError: ws = self._root()._windowingsystem_cached = \ self.tk.call('tk', 'windowingsystem') return ws def _options(self, cnf, kw = None): """Internal function.""" if kw: cnf = _cnfmerge((cnf, kw)) else: cnf = _cnfmerge(cnf) res = () for k, v in cnf.items(): if v is not None: if k[-1] == '_': k = k[:-1] if callable(v): v = self._register(v) elif isinstance(v, (tuple, list)): nv = [] for item in v: if isinstance(item, int): nv.append(str(item)) elif isinstance(item, str): nv.append(_stringify(item)) else: break else: v = ' '.join(nv) res = res + ('-'+k, v) return res def nametowidget(self, name): """Return the Tkinter instance of a widget identified by its Tcl name NAME.""" name = str(name).split('.') w = self if not name[0]: w = w._root() name = name[1:] for n in name: if not n: break w = w.children[n] return w _nametowidget = nametowidget def _register(self, func, subst=None, needcleanup=1): """Return a newly created Tcl function. If this function is called, the Python function FUNC will be executed. An optional function SUBST can be given which will be executed before FUNC.""" f = CallWrapper(func, subst, self).__call__ name = repr(id(f)) try: func = func.__func__ except AttributeError: pass try: name = name + func.__name__ except AttributeError: pass self.tk.createcommand(name, f) if needcleanup: if self._tclCommands is None: self._tclCommands = [] self._tclCommands.append(name) return name register = _register def _root(self): """Internal function.""" w = self while w.master: w = w.master return w _subst_format = ('%#', '%b', '%f', '%h', '%k', '%s', '%t', '%w', '%x', '%y', '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D') _subst_format_str = " ".join(_subst_format) def _substitute(self, *args): """Internal function.""" if len(args) != len(self._subst_format): return args getboolean = self.tk.getboolean getint = self.tk.getint def getint_event(s): """Tk changed behavior in 8.4.2, returning "??" rather more often.""" try: return getint(s) except (ValueError, TclError): return s nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args # Missing: (a, c, d, m, o, v, B, R) e = Event() # serial field: valid for all events # number of button: ButtonPress and ButtonRelease events only # height field: Configure, ConfigureRequest, Create, # ResizeRequest, and Expose events only # keycode field: KeyPress and KeyRelease events only # time field: "valid for events that contain a time field" # width field: Configure, ConfigureRequest, Create, ResizeRequest, # and Expose events only # x field: "valid for events that contain an x field" # y field: "valid for events that contain a y field" # keysym as decimal: KeyPress and KeyRelease events only # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress, # KeyRelease, and Motion events e.serial = getint(nsign) e.num = getint_event(b) try: e.focus = getboolean(f) except TclError: pass e.height = getint_event(h) e.keycode = getint_event(k) e.state = getint_event(s) e.time = getint_event(t) e.width = getint_event(w) e.x = getint_event(x) e.y = getint_event(y) e.char = A try: e.send_event = getboolean(E) except TclError: pass e.keysym = K e.keysym_num = getint_event(N) try: e.type = EventType(T) except ValueError: e.type = T try: e.widget = self._nametowidget(W) except KeyError: e.widget = W e.x_root = getint_event(X) e.y_root = getint_event(Y) try: e.delta = getint(D) except (ValueError, TclError): e.delta = 0 return (e,) def _report_exception(self): """Internal function.""" exc, val, tb = sys.exc_info() root = self._root() root.report_callback_exception(exc, val, tb) def _getconfigure(self, *args): """Call Tcl configure command and return the result as a dict.""" cnf = {} for x in self.tk.splitlist(self.tk.call(*args)): x = self.tk.splitlist(x) cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf def _getconfigure1(self, *args): x = self.tk.splitlist(self.tk.call(*args)) return (x[0][1:],) + x[1:] def _configure(self, cmd, cnf, kw): """Internal function.""" if kw: cnf = _cnfmerge((cnf, kw)) elif cnf: cnf = _cnfmerge(cnf) if cnf is None: return self._getconfigure(_flatten((self._w, cmd))) if isinstance(cnf, str): return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf))) self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) # These used to be defined in Widget: def configure(self, cnf=None, **kw): """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method keys. """ return self._configure('configure', cnf, kw) config = configure def cget(self, key): """Return the resource value for a KEY given as string.""" return self.tk.call(self._w, 'cget', '-' + key) __getitem__ = cget def __setitem__(self, key, value): self.configure({key: value}) def keys(self): """Return a list of all resource names of this widget.""" splitlist = self.tk.splitlist return [splitlist(x)[0][1:] for x in splitlist(self.tk.call(self._w, 'configure'))] def __str__(self): """Return the window path name of this widget.""" return self._w def __repr__(self): return '<%s.%s object %s>' % ( self.__class__.__module__, self.__class__.__qualname__, self._w) # Pack methods that apply to the master _noarg_ = ['_noarg_'] def pack_propagate(self, flag=_noarg_): """Set or get the status for propagation of geometry information. A boolean argument specifies whether the geometry information of the slaves will determine the size of this widget. If no argument is given the current setting will be returned. """ if flag is Misc._noarg_: return self._getboolean(self.tk.call( 'pack', 'propagate', self._w)) else: self.tk.call('pack', 'propagate', self._w, flag) propagate = pack_propagate def pack_slaves(self): """Return a list of all slaves of this widget in its packing order.""" return [self._nametowidget(x) for x in self.tk.splitlist( self.tk.call('pack', 'slaves', self._w))] slaves = pack_slaves # Place method that applies to the master def place_slaves(self): """Return a list of all slaves of this widget in its packing order.""" return [self._nametowidget(x) for x in self.tk.splitlist( self.tk.call( 'place', 'slaves', self._w))] # Grid methods that apply to the master def grid_anchor(self, anchor=None): # new in Tk 8.5 """The anchor value controls how to place the grid within the master when no row/column has any weight. The default anchor is nw.""" self.tk.call('grid', 'anchor', self._w, anchor) anchor = grid_anchor def grid_bbox(self, column=None, row=None, col2=None, row2=None): """Return a tuple of integer coordinates for the bounding box of this widget controlled by the geometry manager grid. If COLUMN, ROW is given the bounding box applies from the cell with row and column 0 to the specified cell. If COL2 and ROW2 are given the bounding box starts at that cell. The returned integers specify the offset of the upper left corner in the master widget and the width and height. """ args = ('grid', 'bbox', self._w) if column is not None and row is not None: args = args + (column, row) if col2 is not None and row2 is not None: args = args + (col2, row2) return self._getints(self.tk.call(*args)) or None bbox = grid_bbox def _gridconvvalue(self, value): if isinstance(value, (str, _tkinter.Tcl_Obj)): try: svalue = str(value) if not svalue: return None elif '.' in svalue: return self.tk.getdouble(svalue) else: return self.tk.getint(svalue) except (ValueError, TclError): pass return value def _grid_configure(self, command, index, cnf, kw): """Internal function.""" if isinstance(cnf, str) and not kw: if cnf[-1:] == '_': cnf = cnf[:-1] if cnf[:1] != '-': cnf = '-'+cnf options = (cnf,) else: options = self._options(cnf, kw) if not options: return _splitdict( self.tk, self.tk.call('grid', command, self._w, index), conv=self._gridconvvalue) res = self.tk.call( ('grid', command, self._w, index) + options) if len(options) == 1: return self._gridconvvalue(res) def grid_columnconfigure(self, index, cnf={}, **kw): """Configure column INDEX of a grid. Valid resources are minsize (minimum size of the column), weight (how much does additional space propagate to this column) and pad (how much space to let additionally).""" return self._grid_configure('columnconfigure', index, cnf, kw) columnconfigure = grid_columnconfigure def grid_location(self, x, y): """Return a tuple of column and row which identify the cell at which the pixel at position X and Y inside the master widget is located.""" return self._getints( self.tk.call( 'grid', 'location', self._w, x, y)) or None def grid_propagate(self, flag=_noarg_): """Set or get the status for propagation of geometry information. A boolean argument specifies whether the geometry information of the slaves will determine the size of this widget. If no argument is given, the current setting will be returned. """ if flag is Misc._noarg_: return self._getboolean(self.tk.call( 'grid', 'propagate', self._w)) else: self.tk.call('grid', 'propagate', self._w, flag) def grid_rowconfigure(self, index, cnf={}, **kw): """Configure row INDEX of a grid. Valid resources are minsize (minimum size of the row), weight (how much does additional space propagate to this row) and pad (how much space to let additionally).""" return self._grid_configure('rowconfigure', index, cnf, kw) rowconfigure = grid_rowconfigure def grid_size(self): """Return a tuple of the number of column and rows in the grid.""" return self._getints( self.tk.call('grid', 'size', self._w)) or None size = grid_size def grid_slaves(self, row=None, column=None): """Return a list of all slaves of this widget in its packing order.""" args = () if row is not None: args = args + ('-row', row) if column is not None: args = args + ('-column', column) return [self._nametowidget(x) for x in self.tk.splitlist(self.tk.call( ('grid', 'slaves', self._w) + args))] # Support for the "event" command, new in Tk 4.2. # By Case Roole. def event_add(self, virtual, *sequences): """Bind a virtual event VIRTUAL (of the form <<Name>>) to an event SEQUENCE such that the virtual event is triggered whenever SEQUENCE occurs.""" args = ('event', 'add', virtual) + sequences self.tk.call(args) def event_delete(self, virtual, *sequences): """Unbind a virtual event VIRTUAL from SEQUENCE.""" args = ('event', 'delete', virtual) + sequences self.tk.call(args) def event_generate(self, sequence, **kw): """Generate an event SEQUENCE. Additional keyword arguments specify parameter of the event (e.g. x, y, rootx, rooty).""" args = ('event', 'generate', self._w, sequence) for k, v in kw.items(): args = args + ('-%s' % k, str(v)) self.tk.call(args) def event_info(self, virtual=None): """Return a list of all virtual events or the information about the SEQUENCE bound to the virtual event VIRTUAL.""" return self.tk.splitlist( self.tk.call('event', 'info', virtual)) # Image related commands def image_names(self): """Return a list of all existing image names.""" return self.tk.splitlist(self.tk.call('image', 'names')) def image_types(self): """Return a list of all available image types (e.g. photo bitmap).""" return self.tk.splitlist(self.tk.call('image', 'types')) class CallWrapper: """Internal class. Stores function to call when some user defined Tcl function is called e.g. after an event occurred.""" def __init__(self, func, subst, widget): """Store FUNC, SUBST and WIDGET as members.""" self.func = func self.subst = subst self.widget = widget def __call__(self, *args): """Apply first function SUBST to arguments, than FUNC.""" try: if self.subst: args = self.subst(*args) return self.func(*args) except SystemExit: raise except: self.widget._report_exception() class XView: """Mix-in class for querying and changing the horizontal position of a widget's window.""" def xview(self, *args): """Query and change the horizontal position of the view.""" res = self.tk.call(self._w, 'xview', *args) if not args: return self._getdoubles(res) def xview_moveto(self, fraction): """Adjusts the view in the window so that FRACTION of the total width of the canvas is off-screen to the left.""" self.tk.call(self._w, 'xview', 'moveto', fraction) def xview_scroll(self, number, what): """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT).""" self.tk.call(self._w, 'xview', 'scroll', number, what) class YView: """Mix-in class for querying and changing the vertical position of a widget's window.""" def yview(self, *args): """Query and change the vertical position of the view.""" res = self.tk.call(self._w, 'yview', *args) if not args: return self._getdoubles(res) def yview_moveto(self, fraction): """Adjusts the view in the window so that FRACTION of the total height of the canvas is off-screen to the top.""" self.tk.call(self._w, 'yview', 'moveto', fraction) def yview_scroll(self, number, what): """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT).""" self.tk.call(self._w, 'yview', 'scroll', number, what) class Wm: """Provides functions for the communication with the window manager.""" def wm_aspect(self, minNumer=None, minDenom=None, maxNumer=None, maxDenom=None): """Instruct the window manager to set the aspect ratio (width/height) of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple of the actual values if no argument is given.""" return self._getints( self.tk.call('wm', 'aspect', self._w, minNumer, minDenom, maxNumer, maxDenom)) aspect = wm_aspect def wm_attributes(self, *args): """This subcommand returns or sets platform specific attributes The first form returns a list of the platform specific flags and their values. The second form returns the value for the specific option. The third form sets one or more of the values. The values are as follows: On Windows, -disabled gets or sets whether the window is in a disabled state. -toolwindow gets or sets the style of the window to toolwindow (as defined in the MSDN). -topmost gets or sets whether this is a topmost window (displays above all other windows). On Macintosh, XXXXX On Unix, there are currently no special attribute values. """ args = ('wm', 'attributes', self._w) + args return self.tk.call(args) attributes=wm_attributes def wm_client(self, name=None): """Store NAME in WM_CLIENT_MACHINE property of this widget. Return current value.""" return self.tk.call('wm', 'client', self._w, name) client = wm_client def wm_colormapwindows(self, *wlist): """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property of this widget. This list contains windows whose colormaps differ from their parents. Return current list of widgets if WLIST is empty.""" if len(wlist) > 1: wlist = (wlist,) # Tk needs a list of windows here args = ('wm', 'colormapwindows', self._w) + wlist if wlist: self.tk.call(args) else: return [self._nametowidget(x) for x in self.tk.splitlist(self.tk.call(args))] colormapwindows = wm_colormapwindows def wm_command(self, value=None): """Store VALUE in WM_COMMAND property. It is the command which shall be used to invoke the application. Return current command if VALUE is None.""" return self.tk.call('wm', 'command', self._w, value) command = wm_command def wm_deiconify(self): """Deiconify this widget. If it was never mapped it will not be mapped. On Windows it will raise this widget and give it the focus.""" return self.tk.call('wm', 'deiconify', self._w) deiconify = wm_deiconify def wm_focusmodel(self, model=None): """Set focus model to MODEL. "active" means that this widget will claim the focus itself, "passive" means that the window manager shall give the focus. Return current focus model if MODEL is None.""" return self.tk.call('wm', 'focusmodel', self._w, model) focusmodel = wm_focusmodel def wm_forget(self, window): # new in Tk 8.5 """The window will be unmapped from the screen and will no longer be managed by wm. toplevel windows will be treated like frame windows once they are no longer managed by wm, however, the menu option configuration will be remembered and the menus will return once the widget is managed again.""" self.tk.call('wm', 'forget', window) forget = wm_forget def wm_frame(self): """Return identifier for decorative frame of this widget if present.""" return self.tk.call('wm', 'frame', self._w) frame = wm_frame def wm_geometry(self, newGeometry=None): """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return current value if None is given.""" return self.tk.call('wm', 'geometry', self._w, newGeometry) geometry = wm_geometry def wm_grid(self, baseWidth=None, baseHeight=None, widthInc=None, heightInc=None): """Instruct the window manager that this widget shall only be resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the number of grid units requested in Tk_GeometryRequest.""" return self._getints(self.tk.call( 'wm', 'grid', self._w, baseWidth, baseHeight, widthInc, heightInc)) grid = wm_grid def wm_group(self, pathName=None): """Set the group leader widgets for related widgets to PATHNAME. Return the group leader of this widget if None is given.""" return self.tk.call('wm', 'group', self._w, pathName) group = wm_group def wm_iconbitmap(self, bitmap=None, default=None): """Set bitmap for the iconified widget to BITMAP. Return the bitmap if None is given. Under Windows, the DEFAULT parameter can be used to set the icon for the widget and any descendents that don't have an icon set explicitly. DEFAULT can be the relative path to a .ico file (example: root.iconbitmap(default='myicon.ico') ). See Tk documentation for more information.""" if default: return self.tk.call('wm', 'iconbitmap', self._w, '-default', default) else: return self.tk.call('wm', 'iconbitmap', self._w, bitmap) iconbitmap = wm_iconbitmap def wm_iconify(self): """Display widget as icon.""" return self.tk.call('wm', 'iconify', self._w) iconify = wm_iconify def wm_iconmask(self, bitmap=None): """Set mask for the icon bitmap of this widget. Return the mask if None is given.""" return self.tk.call('wm', 'iconmask', self._w, bitmap) iconmask = wm_iconmask def wm_iconname(self, newName=None): """Set the name of the icon for this widget. Return the name if None is given.""" return self.tk.call('wm', 'iconname', self._w, newName) iconname = wm_iconname def wm_iconphoto(self, default=False, *args): # new in Tk 8.5 """Sets the titlebar icon for this window based on the named photo images passed through args. If default is True, this is applied to all future created toplevels as well. The data in the images is taken as a snapshot at the time of invocation. If the images are later changed, this is not reflected to the titlebar icons. Multiple images are accepted to allow different images sizes to be provided. The window manager may scale provided icons to an appropriate size. On Windows, the images are packed into a Windows icon structure. This will override an icon specified to wm_iconbitmap, and vice versa. On X, the images are arranged into the _NET_WM_ICON X property, which most modern window managers support. An icon specified by wm_iconbitmap may exist simultaneously. On Macintosh, this currently does nothing.""" if default: self.tk.call('wm', 'iconphoto', self._w, "-default", *args) else: self.tk.call('wm', 'iconphoto', self._w, *args) iconphoto = wm_iconphoto def wm_iconposition(self, x=None, y=None): """Set the position of the icon of this widget to X and Y. Return a tuple of the current values of X and X if None is given.""" return self._getints(self.tk.call( 'wm', 'iconposition', self._w, x, y)) iconposition = wm_iconposition def wm_iconwindow(self, pathName=None): """Set widget PATHNAME to be displayed instead of icon. Return the current value if None is given.""" return self.tk.call('wm', 'iconwindow', self._w, pathName) iconwindow = wm_iconwindow def wm_manage(self, widget): # new in Tk 8.5 """The widget specified will become a stand alone top-level window. The window will be decorated with the window managers title bar, etc.""" self.tk.call('wm', 'manage', widget) manage = wm_manage def wm_maxsize(self, width=None, height=None): """Set max WIDTH and HEIGHT for this widget. If the window is gridded the values are given in grid units. Return the current values if None is given.""" return self._getints(self.tk.call( 'wm', 'maxsize', self._w, width, height)) maxsize = wm_maxsize def wm_minsize(self, width=None, height=None): """Set min WIDTH and HEIGHT for this widget. If the window is gridded the values are given in grid units. Return the current values if None is given.""" return self._getints(self.tk.call( 'wm', 'minsize', self._w, width, height)) minsize = wm_minsize def wm_overrideredirect(self, boolean=None): """Instruct the window manager to ignore this widget if BOOLEAN is given with 1. Return the current value if None is given.""" return self._getboolean(self.tk.call( 'wm', 'overrideredirect', self._w, boolean)) overrideredirect = wm_overrideredirect def wm_positionfrom(self, who=None): """Instruct the window manager that the position of this widget shall be defined by the user if WHO is "user", and by its own policy if WHO is "program".""" return self.tk.call('wm', 'positionfrom', self._w, who) positionfrom = wm_positionfrom def wm_protocol(self, name=None, func=None): """Bind function FUNC to command NAME for this widget. Return the function bound to NAME if None is given. NAME could be e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW".""" if callable(func): command = self._register(func) else: command = func return self.tk.call( 'wm', 'protocol', self._w, name, command) protocol = wm_protocol def wm_resizable(self, width=None, height=None): """Instruct the window manager whether this width can be resized in WIDTH or HEIGHT. Both values are boolean values.""" return self.tk.call('wm', 'resizable', self._w, width, height) resizable = wm_resizable def wm_sizefrom(self, who=None): """Instruct the window manager that the size of this widget shall be defined by the user if WHO is "user", and by its own policy if WHO is "program".""" return self.tk.call('wm', 'sizefrom', self._w, who) sizefrom = wm_sizefrom def wm_state(self, newstate=None): """Query or set the state of this widget as one of normal, icon, iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only).""" return self.tk.call('wm', 'state', self._w, newstate) state = wm_state def wm_title(self, string=None): """Set the title of this widget.""" return self.tk.call('wm', 'title', self._w, string) title = wm_title def wm_transient(self, master=None): """Instruct the window manager that this widget is transient with regard to widget MASTER.""" return self.tk.call('wm', 'transient', self._w, master) transient = wm_transient def wm_withdraw(self): """Withdraw this widget from the screen such that it is unmapped and forgotten by the window manager. Re-draw it with wm_deiconify.""" return self.tk.call('wm', 'withdraw', self._w) withdraw = wm_withdraw class Tk(Misc, Wm): """Toplevel widget of Tk which represents mostly the main window of an application. It has an associated Tcl interpreter.""" _w = '.' def __init__(self, screenName=None, baseName=None, className='Tk', useTk=1, sync=0, use=None): """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will be created. BASENAME will be used for the identification of the profile file (see readprofile). It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME is the name of the widget class.""" self.master = None self.children = {} self._tkloaded = 0 # to avoid recursions in the getattr code in case of failure, we # ensure that self.tk is always _something_. self.tk = None if baseName is None: import os baseName = os.path.basename(sys.argv[0]) baseName, ext = os.path.splitext(baseName) if ext not in ('.py', '.pyc'): baseName = baseName + ext interactive = 0 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) if useTk: self._loadtk() if not sys.flags.ignore_environment: # Issue #16248: Honor the -E flag to avoid code injection. self.readprofile(baseName, className) def loadtk(self): if not self._tkloaded: self.tk.loadtk() self._loadtk() def _loadtk(self): self._tkloaded = 1 global _default_root # Version sanity checks tk_version = self.tk.getvar('tk_version') if tk_version != _tkinter.TK_VERSION: raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)" % (_tkinter.TK_VERSION, tk_version)) # Under unknown circumstances, tcl_version gets coerced to float tcl_version = str(self.tk.getvar('tcl_version')) if tcl_version != _tkinter.TCL_VERSION: raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \ % (_tkinter.TCL_VERSION, tcl_version)) # Create and register the tkerror and exit commands # We need to inline parts of _register here, _ register # would register differently-named commands. if self._tclCommands is None: self._tclCommands = [] self.tk.createcommand('tkerror', _tkerror) self.tk.createcommand('exit', _exit) self._tclCommands.append('tkerror') self._tclCommands.append('exit') if _support_default_root and not _default_root: _default_root = self self.protocol("WM_DELETE_WINDOW", self.destroy) def destroy(self): """Destroy this and all descendants widgets. This will end the application of this Tcl interpreter.""" for c in list(self.children.values()): c.destroy() self.tk.call('destroy', self._w) Misc.destroy(self) global _default_root if _support_default_root and _default_root is self: _default_root = None def readprofile(self, baseName, className): """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into the Tcl Interpreter and calls exec on the contents of BASENAME.py and CLASSNAME.py if such a file exists in the home directory.""" import os if 'HOME' in os.environ: home = os.environ['HOME'] else: home = os.curdir class_tcl = os.path.join(home, '.%s.tcl' % className) class_py = os.path.join(home, '.%s.py' % className) base_tcl = os.path.join(home, '.%s.tcl' % baseName) base_py = os.path.join(home, '.%s.py' % baseName) dir = {'self': self} exec('from tkinter import *', dir) if os.path.isfile(class_tcl): self.tk.call('source', class_tcl) if os.path.isfile(class_py): exec(open(class_py).read(), dir) if os.path.isfile(base_tcl): self.tk.call('source', base_tcl) if os.path.isfile(base_py): exec(open(base_py).read(), dir) def report_callback_exception(self, exc, val, tb): """Report callback exception on sys.stderr. Applications may want to override this internal function, and should when sys.stderr is None.""" import traceback print("Exception in Tkinter callback", file=sys.stderr) sys.last_type = exc sys.last_value = val sys.last_traceback = tb traceback.print_exception(exc, val, tb) def __getattr__(self, attr): "Delegate attribute access to the interpreter object" return getattr(self.tk, attr) # Ideally, the classes Pack, Place and Grid disappear, the # pack/place/grid methods are defined on the Widget class, and # everybody uses w.pack_whatever(...) instead of Pack.whatever(w, # ...), with pack(), place() and grid() being short for # pack_configure(), place_configure() and grid_columnconfigure(), and # forget() being short for pack_forget(). As a practical matter, I'm # afraid that there is too much code out there that may be using the # Pack, Place or Grid class, so I leave them intact -- but only as # backwards compatibility features. Also note that those methods that # take a master as argument (e.g. pack_propagate) have been moved to # the Misc class (which now incorporates all methods common between # toplevel and interior widgets). Again, for compatibility, these are # copied into the Pack, Place or Grid class. def Tcl(screenName=None, baseName=None, className='Tk', useTk=0): return Tk(screenName, baseName, className, useTk) class Pack: """Geometry manager Pack. Base class to use the methods pack_* in every widget.""" def pack_configure(self, cnf={}, **kw): """Pack a widget in the parent widget. Use as options: after=widget - pack it after you have packed widget anchor=NSEW (or subset) - position widget according to given direction before=widget - pack it before you will pack widget expand=bool - expand widget if parent size grows fill=NONE or X or Y or BOTH - fill widget if widget grows in=master - use master to contain this widget in_=master - see 'in' option description ipadx=amount - add internal padding in x direction ipady=amount - add internal padding in y direction padx=amount - add padding in x direction pady=amount - add padding in y direction side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget. """ self.tk.call( ('pack', 'configure', self._w) + self._options(cnf, kw)) pack = configure = config = pack_configure def pack_forget(self): """Unmap this widget and do not use it for the packing order.""" self.tk.call('pack', 'forget', self._w) forget = pack_forget def pack_info(self): """Return information about the packing options for this widget.""" d = _splitdict(self.tk, self.tk.call('pack', 'info', self._w)) if 'in' in d: d['in'] = self.nametowidget(d['in']) return d info = pack_info propagate = pack_propagate = Misc.pack_propagate slaves = pack_slaves = Misc.pack_slaves class Place: """Geometry manager Place. Base class to use the methods place_* in every widget.""" def place_configure(self, cnf={}, **kw): """Place a widget in the parent widget. Use as options: in=master - master relative to which the widget is placed in_=master - see 'in' option description x=amount - locate anchor of this widget at position x of master y=amount - locate anchor of this widget at position y of master relx=amount - locate anchor of this widget between 0.0 and 1.0 relative to width of master (1.0 is right edge) rely=amount - locate anchor of this widget between 0.0 and 1.0 relative to height of master (1.0 is bottom edge) anchor=NSEW (or subset) - position anchor according to given direction width=amount - width of this widget in pixel height=amount - height of this widget in pixel relwidth=amount - width of this widget between 0.0 and 1.0 relative to width of master (1.0 is the same width as the master) relheight=amount - height of this widget between 0.0 and 1.0 relative to height of master (1.0 is the same height as the master) bordermode="inside" or "outside" - whether to take border width of master widget into account """ self.tk.call( ('place', 'configure', self._w) + self._options(cnf, kw)) place = configure = config = place_configure def place_forget(self): """Unmap this widget.""" self.tk.call('place', 'forget', self._w) forget = place_forget def place_info(self): """Return information about the placing options for this widget.""" d = _splitdict(self.tk, self.tk.call('place', 'info', self._w)) if 'in' in d: d['in'] = self.nametowidget(d['in']) return d info = place_info slaves = place_slaves = Misc.place_slaves class Grid: """Geometry manager Grid. Base class to use the methods grid_* in every widget.""" # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu) def grid_configure(self, cnf={}, **kw): """Position a widget in the parent widget in a grid. Use as options: column=number - use cell identified with given column (starting with 0) columnspan=number - this widget will span several columns in=master - use master to contain this widget in_=master - see 'in' option description ipadx=amount - add internal padding in x direction ipady=amount - add internal padding in y direction padx=amount - add padding in x direction pady=amount - add padding in y direction row=number - use cell identified with given row (starting with 0) rowspan=number - this widget will span several rows sticky=NSEW - if cell is larger on which sides will this widget stick to the cell boundary """ self.tk.call( ('grid', 'configure', self._w) + self._options(cnf, kw)) grid = configure = config = grid_configure bbox = grid_bbox = Misc.grid_bbox columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure def grid_forget(self): """Unmap this widget.""" self.tk.call('grid', 'forget', self._w) forget = grid_forget def grid_remove(self): """Unmap this widget but remember the grid options.""" self.tk.call('grid', 'remove', self._w) def grid_info(self): """Return information about the options for positioning this widget in a grid.""" d = _splitdict(self.tk, self.tk.call('grid', 'info', self._w)) if 'in' in d: d['in'] = self.nametowidget(d['in']) return d info = grid_info location = grid_location = Misc.grid_location propagate = grid_propagate = Misc.grid_propagate rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure size = grid_size = Misc.grid_size slaves = grid_slaves = Misc.grid_slaves class BaseWidget(Misc): """Internal class.""" def _setup(self, master, cnf): """Internal function. Sets up information about children.""" if _support_default_root: global _default_root if not master: if not _default_root: _default_root = Tk() master = _default_root self.master = master self.tk = master.tk name = None if 'name' in cnf: name = cnf['name'] del cnf['name'] if not name: name = self.__class__.__name__.lower() if master._last_child_ids is None: master._last_child_ids = {} count = master._last_child_ids.get(name, 0) + 1 master._last_child_ids[name] = count if count == 1: name = '!%s' % (name,) else: name = '!%s%d' % (name, count) self._name = name if master._w=='.': self._w = '.' + name else: self._w = master._w + '.' + name self.children = {} if self._name in self.master.children: self.master.children[self._name].destroy() self.master.children[self._name] = self def __init__(self, master, widgetName, cnf={}, kw={}, extra=()): """Construct a widget with the parent widget MASTER, a name WIDGETNAME and appropriate options.""" if kw: cnf = _cnfmerge((cnf, kw)) self.widgetName = widgetName BaseWidget._setup(self, master, cnf) if self._tclCommands is None: self._tclCommands = [] classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)] for k, v in classes: del cnf[k] self.tk.call( (widgetName, self._w) + extra + self._options(cnf)) for k, v in classes: k.configure(self, v) def destroy(self): """Destroy this and all descendants widgets.""" for c in list(self.children.values()): c.destroy() self.tk.call('destroy', self._w) if self._name in self.master.children: del self.master.children[self._name] Misc.destroy(self) def _do(self, name, args=()): # XXX Obsolete -- better use self.tk.call directly! return self.tk.call((self._w, name) + args) class Widget(BaseWidget, Pack, Place, Grid): """Internal class. Base class for a widget which can be positioned with the geometry managers Pack, Place or Grid.""" pass class Toplevel(BaseWidget, Wm): """Toplevel widget, e.g. for dialogs.""" def __init__(self, master=None, cnf={}, **kw): """Construct a toplevel widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, class, colormap, container, cursor, height, highlightbackground, highlightcolor, highlightthickness, menu, relief, screen, takefocus, use, visual, width.""" if kw: cnf = _cnfmerge((cnf, kw)) extra = () for wmkey in ['screen', 'class_', 'class', 'visual', 'colormap']: if wmkey in cnf: val = cnf[wmkey] # TBD: a hack needed because some keys # are not valid as keyword arguments if wmkey[-1] == '_': opt = '-'+wmkey[:-1] else: opt = '-'+wmkey extra = extra + (opt, val) del cnf[wmkey] BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra) root = self._root() self.iconname(root.iconname()) self.title(root.title()) self.protocol("WM_DELETE_WINDOW", self.destroy) class Button(Widget): """Button widget.""" def __init__(self, master=None, cnf={}, **kw): """Construct a button widget with the parent MASTER. STANDARD OPTIONS activebackground, activeforeground, anchor, background, bitmap, borderwidth, cursor, disabledforeground, font, foreground highlightbackground, highlightcolor, highlightthickness, image, justify, padx, pady, relief, repeatdelay, repeatinterval, takefocus, text, textvariable, underline, wraplength WIDGET-SPECIFIC OPTIONS command, compound, default, height, overrelief, state, width """ Widget.__init__(self, master, 'button', cnf, kw) def flash(self): """Flash the button. This is accomplished by redisplaying the button several times, alternating between active and normal colors. At the end of the flash the button is left in the same normal/active state as when the command was invoked. This command is ignored if the button's state is disabled. """ self.tk.call(self._w, 'flash') def invoke(self): """Invoke the command associated with the button. The return value is the return value from the command, or an empty string if there is no command associated with the button. This command is ignored if the button's state is disabled. """ return self.tk.call(self._w, 'invoke') class Canvas(Widget, XView, YView): """Canvas widget to display graphical elements like lines or text.""" def __init__(self, master=None, cnf={}, **kw): """Construct a canvas widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, closeenough, confine, cursor, height, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, offset, relief, scrollregion, selectbackground, selectborderwidth, selectforeground, state, takefocus, width, xscrollcommand, xscrollincrement, yscrollcommand, yscrollincrement.""" Widget.__init__(self, master, 'canvas', cnf, kw) def addtag(self, *args): """Internal function.""" self.tk.call((self._w, 'addtag') + args) def addtag_above(self, newtag, tagOrId): """Add tag NEWTAG to all items above TAGORID.""" self.addtag(newtag, 'above', tagOrId) def addtag_all(self, newtag): """Add tag NEWTAG to all items.""" self.addtag(newtag, 'all') def addtag_below(self, newtag, tagOrId): """Add tag NEWTAG to all items below TAGORID.""" self.addtag(newtag, 'below', tagOrId) def addtag_closest(self, newtag, x, y, halo=None, start=None): """Add tag NEWTAG to item which is closest to pixel at X, Y. If several match take the top-most. All items closer than HALO are considered overlapping (all are closests). If START is specified the next below this tag is taken.""" self.addtag(newtag, 'closest', x, y, halo, start) def addtag_enclosed(self, newtag, x1, y1, x2, y2): """Add tag NEWTAG to all items in the rectangle defined by X1,Y1,X2,Y2.""" self.addtag(newtag, 'enclosed', x1, y1, x2, y2) def addtag_overlapping(self, newtag, x1, y1, x2, y2): """Add tag NEWTAG to all items which overlap the rectangle defined by X1,Y1,X2,Y2.""" self.addtag(newtag, 'overlapping', x1, y1, x2, y2) def addtag_withtag(self, newtag, tagOrId): """Add tag NEWTAG to all items with TAGORID.""" self.addtag(newtag, 'withtag', tagOrId) def bbox(self, *args): """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses all items with tags specified as arguments.""" return self._getints( self.tk.call((self._w, 'bbox') + args)) or None def tag_unbind(self, tagOrId, sequence, funcid=None): """Unbind for all items with TAGORID for event SEQUENCE the function identified with FUNCID.""" self.tk.call(self._w, 'bind', tagOrId, sequence, '') if funcid: self.deletecommand(funcid) def tag_bind(self, tagOrId, sequence=None, func=None, add=None): """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.""" return self._bind((self._w, 'bind', tagOrId), sequence, func, add) def canvasx(self, screenx, gridspacing=None): """Return the canvas x coordinate of pixel position SCREENX rounded to nearest multiple of GRIDSPACING units.""" return self.tk.getdouble(self.tk.call( self._w, 'canvasx', screenx, gridspacing)) def canvasy(self, screeny, gridspacing=None): """Return the canvas y coordinate of pixel position SCREENY rounded to nearest multiple of GRIDSPACING units.""" return self.tk.getdouble(self.tk.call( self._w, 'canvasy', screeny, gridspacing)) def coords(self, *args): """Return a list of coordinates for the item given in ARGS.""" # XXX Should use _flatten on args return [self.tk.getdouble(x) for x in self.tk.splitlist( self.tk.call((self._w, 'coords') + args))] def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={}) """Internal function.""" args = _flatten(args) cnf = args[-1] if isinstance(cnf, (dict, tuple)): args = args[:-1] else: cnf = {} return self.tk.getint(self.tk.call( self._w, 'create', itemType, *(args + self._options(cnf, kw)))) def create_arc(self, *args, **kw): """Create arc shaped region with coordinates x1,y1,x2,y2.""" return self._create('arc', args, kw) def create_bitmap(self, *args, **kw): """Create bitmap with coordinates x1,y1.""" return self._create('bitmap', args, kw) def create_image(self, *args, **kw): """Create image item with coordinates x1,y1.""" return self._create('image', args, kw) def create_line(self, *args, **kw): """Create line with coordinates x1,y1,...,xn,yn.""" return self._create('line', args, kw) def create_oval(self, *args, **kw): """Create oval with coordinates x1,y1,x2,y2.""" return self._create('oval', args, kw) def create_polygon(self, *args, **kw): """Create polygon with coordinates x1,y1,...,xn,yn.""" return self._create('polygon', args, kw) def create_rectangle(self, *args, **kw): """Create rectangle with coordinates x1,y1,x2,y2.""" return self._create('rectangle', args, kw) def create_text(self, *args, **kw): """Create text with coordinates x1,y1.""" return self._create('text', args, kw) def create_window(self, *args, **kw): """Create window with coordinates x1,y1,x2,y2.""" return self._create('window', args, kw) def dchars(self, *args): """Delete characters of text items identified by tag or id in ARGS (possibly several times) from FIRST to LAST character (including).""" self.tk.call((self._w, 'dchars') + args) def delete(self, *args): """Delete items identified by all tag or ids contained in ARGS.""" self.tk.call((self._w, 'delete') + args) def dtag(self, *args): """Delete tag or id given as last arguments in ARGS from items identified by first argument in ARGS.""" self.tk.call((self._w, 'dtag') + args) def find(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'find') + args)) or () def find_above(self, tagOrId): """Return items above TAGORID.""" return self.find('above', tagOrId) def find_all(self): """Return all items.""" return self.find('all') def find_below(self, tagOrId): """Return all items below TAGORID.""" return self.find('below', tagOrId) def find_closest(self, x, y, halo=None, start=None): """Return item which is closest to pixel at X, Y. If several match take the top-most. All items closer than HALO are considered overlapping (all are closest). If START is specified the next below this tag is taken.""" return self.find('closest', x, y, halo, start) def find_enclosed(self, x1, y1, x2, y2): """Return all items in rectangle defined by X1,Y1,X2,Y2.""" return self.find('enclosed', x1, y1, x2, y2) def find_overlapping(self, x1, y1, x2, y2): """Return all items which overlap the rectangle defined by X1,Y1,X2,Y2.""" return self.find('overlapping', x1, y1, x2, y2) def find_withtag(self, tagOrId): """Return all items with TAGORID.""" return self.find('withtag', tagOrId) def focus(self, *args): """Set focus to the first item specified in ARGS.""" return self.tk.call((self._w, 'focus') + args) def gettags(self, *args): """Return tags associated with the first item specified in ARGS.""" return self.tk.splitlist( self.tk.call((self._w, 'gettags') + args)) def icursor(self, *args): """Set cursor at position POS in the item identified by TAGORID. In ARGS TAGORID must be first.""" self.tk.call((self._w, 'icursor') + args) def index(self, *args): """Return position of cursor as integer in item specified in ARGS.""" return self.tk.getint(self.tk.call((self._w, 'index') + args)) def insert(self, *args): """Insert TEXT in item TAGORID at position POS. ARGS must be TAGORID POS TEXT.""" self.tk.call((self._w, 'insert') + args) def itemcget(self, tagOrId, option): """Return the resource value for an OPTION for item TAGORID.""" return self.tk.call( (self._w, 'itemcget') + (tagOrId, '-'+option)) def itemconfigure(self, tagOrId, cnf=None, **kw): """Configure resources of an item TAGORID. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method without arguments. """ return self._configure(('itemconfigure', tagOrId), cnf, kw) itemconfig = itemconfigure # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift, # so the preferred name for them is tag_lower, tag_raise # (similar to tag_bind, and similar to the Text widget); # unfortunately can't delete the old ones yet (maybe in 1.6) def tag_lower(self, *args): """Lower an item TAGORID given in ARGS (optional below another item).""" self.tk.call((self._w, 'lower') + args) lower = tag_lower def move(self, *args): """Move an item TAGORID given in ARGS.""" self.tk.call((self._w, 'move') + args) def postscript(self, cnf={}, **kw): """Print the contents of the canvas to a postscript file. Valid options: colormap, colormode, file, fontmap, height, pageanchor, pageheight, pagewidth, pagex, pagey, rotate, width, x, y.""" return self.tk.call((self._w, 'postscript') + self._options(cnf, kw)) def tag_raise(self, *args): """Raise an item TAGORID given in ARGS (optional above another item).""" self.tk.call((self._w, 'raise') + args) lift = tkraise = tag_raise def scale(self, *args): """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE.""" self.tk.call((self._w, 'scale') + args) def scan_mark(self, x, y): """Remember the current X, Y coordinates.""" self.tk.call(self._w, 'scan', 'mark', x, y) def scan_dragto(self, x, y, gain=10): """Adjust the view of the canvas to GAIN times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x, y, gain) def select_adjust(self, tagOrId, index): """Adjust the end of the selection near the cursor of an item TAGORID to index.""" self.tk.call(self._w, 'select', 'adjust', tagOrId, index) def select_clear(self): """Clear the selection if it is in this widget.""" self.tk.call(self._w, 'select', 'clear') def select_from(self, tagOrId, index): """Set the fixed end of a selection in item TAGORID to INDEX.""" self.tk.call(self._w, 'select', 'from', tagOrId, index) def select_item(self): """Return the item which has the selection.""" return self.tk.call(self._w, 'select', 'item') or None def select_to(self, tagOrId, index): """Set the variable end of a selection in item TAGORID to INDEX.""" self.tk.call(self._w, 'select', 'to', tagOrId, index) def type(self, tagOrId): """Return the type of the item TAGORID.""" return self.tk.call(self._w, 'type', tagOrId) or None class Checkbutton(Widget): """Checkbutton widget which is either in on- or off-state.""" def __init__(self, master=None, cnf={}, **kw): """Construct a checkbutton widget with the parent MASTER. Valid resource names: activebackground, activeforeground, anchor, background, bd, bg, bitmap, borderwidth, command, cursor, disabledforeground, fg, font, foreground, height, highlightbackground, highlightcolor, highlightthickness, image, indicatoron, justify, offvalue, onvalue, padx, pady, relief, selectcolor, selectimage, state, takefocus, text, textvariable, underline, variable, width, wraplength.""" Widget.__init__(self, master, 'checkbutton', cnf, kw) def deselect(self): """Put the button in off-state.""" self.tk.call(self._w, 'deselect') def flash(self): """Flash the button.""" self.tk.call(self._w, 'flash') def invoke(self): """Toggle the button and invoke a command if given as resource.""" return self.tk.call(self._w, 'invoke') def select(self): """Put the button in on-state.""" self.tk.call(self._w, 'select') def toggle(self): """Toggle the button.""" self.tk.call(self._w, 'toggle') class Entry(Widget, XView): """Entry widget which allows displaying simple text.""" def __init__(self, master=None, cnf={}, **kw): """Construct an entry widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, cursor, exportselection, fg, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, invalidcommand, invcmd, justify, relief, selectbackground, selectborderwidth, selectforeground, show, state, takefocus, textvariable, validate, validatecommand, vcmd, width, xscrollcommand.""" Widget.__init__(self, master, 'entry', cnf, kw) def delete(self, first, last=None): """Delete text from FIRST to LAST (not included).""" self.tk.call(self._w, 'delete', first, last) def get(self): """Return the text.""" return self.tk.call(self._w, 'get') def icursor(self, index): """Insert cursor at INDEX.""" self.tk.call(self._w, 'icursor', index) def index(self, index): """Return position of cursor.""" return self.tk.getint(self.tk.call( self._w, 'index', index)) def insert(self, index, string): """Insert STRING at INDEX.""" self.tk.call(self._w, 'insert', index, string) def scan_mark(self, x): """Remember the current X, Y coordinates.""" self.tk.call(self._w, 'scan', 'mark', x) def scan_dragto(self, x): """Adjust the view of the canvas to 10 times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x) def selection_adjust(self, index): """Adjust the end of the selection near the cursor to INDEX.""" self.tk.call(self._w, 'selection', 'adjust', index) select_adjust = selection_adjust def selection_clear(self): """Clear the selection if it is in this widget.""" self.tk.call(self._w, 'selection', 'clear') select_clear = selection_clear def selection_from(self, index): """Set the fixed end of a selection to INDEX.""" self.tk.call(self._w, 'selection', 'from', index) select_from = selection_from def selection_present(self): """Return True if there are characters selected in the entry, False otherwise.""" return self.tk.getboolean( self.tk.call(self._w, 'selection', 'present')) select_present = selection_present def selection_range(self, start, end): """Set the selection from START to END (not included).""" self.tk.call(self._w, 'selection', 'range', start, end) select_range = selection_range def selection_to(self, index): """Set the variable end of a selection to INDEX.""" self.tk.call(self._w, 'selection', 'to', index) select_to = selection_to class Frame(Widget): """Frame widget which may contain other widgets and can have a 3D border.""" def __init__(self, master=None, cnf={}, **kw): """Construct a frame widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, class, colormap, container, cursor, height, highlightbackground, highlightcolor, highlightthickness, relief, takefocus, visual, width.""" cnf = _cnfmerge((cnf, kw)) extra = () if 'class_' in cnf: extra = ('-class', cnf['class_']) del cnf['class_'] elif 'class' in cnf: extra = ('-class', cnf['class']) del cnf['class'] Widget.__init__(self, master, 'frame', cnf, {}, extra) class Label(Widget): """Label widget which can display text and bitmaps.""" def __init__(self, master=None, cnf={}, **kw): """Construct a label widget with the parent MASTER. STANDARD OPTIONS activebackground, activeforeground, anchor, background, bitmap, borderwidth, cursor, disabledforeground, font, foreground, highlightbackground, highlightcolor, highlightthickness, image, justify, padx, pady, relief, takefocus, text, textvariable, underline, wraplength WIDGET-SPECIFIC OPTIONS height, state, width """ Widget.__init__(self, master, 'label', cnf, kw) class Listbox(Widget, XView, YView): """Listbox widget which can display a list of strings.""" def __init__(self, master=None, cnf={}, **kw): """Construct a listbox widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, cursor, exportselection, fg, font, foreground, height, highlightbackground, highlightcolor, highlightthickness, relief, selectbackground, selectborderwidth, selectforeground, selectmode, setgrid, takefocus, width, xscrollcommand, yscrollcommand, listvariable.""" Widget.__init__(self, master, 'listbox', cnf, kw) def activate(self, index): """Activate item identified by INDEX.""" self.tk.call(self._w, 'activate', index) def bbox(self, index): """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses the item identified by the given index.""" return self._getints(self.tk.call(self._w, 'bbox', index)) or None def curselection(self): """Return the indices of currently selected item.""" return self._getints(self.tk.call(self._w, 'curselection')) or () def delete(self, first, last=None): """Delete items from FIRST to LAST (included).""" self.tk.call(self._w, 'delete', first, last) def get(self, first, last=None): """Get list of items from FIRST to LAST (included).""" if last is not None: return self.tk.splitlist(self.tk.call( self._w, 'get', first, last)) else: return self.tk.call(self._w, 'get', first) def index(self, index): """Return index of item identified with INDEX.""" i = self.tk.call(self._w, 'index', index) if i == 'none': return None return self.tk.getint(i) def insert(self, index, *elements): """Insert ELEMENTS at INDEX.""" self.tk.call((self._w, 'insert', index) + elements) def nearest(self, y): """Get index of item which is nearest to y coordinate Y.""" return self.tk.getint(self.tk.call( self._w, 'nearest', y)) def scan_mark(self, x, y): """Remember the current X, Y coordinates.""" self.tk.call(self._w, 'scan', 'mark', x, y) def scan_dragto(self, x, y): """Adjust the view of the listbox to 10 times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x, y) def see(self, index): """Scroll such that INDEX is visible.""" self.tk.call(self._w, 'see', index) def selection_anchor(self, index): """Set the fixed end oft the selection to INDEX.""" self.tk.call(self._w, 'selection', 'anchor', index) select_anchor = selection_anchor def selection_clear(self, first, last=None): """Clear the selection from FIRST to LAST (included).""" self.tk.call(self._w, 'selection', 'clear', first, last) select_clear = selection_clear def selection_includes(self, index): """Return True if INDEX is part of the selection.""" return self.tk.getboolean(self.tk.call( self._w, 'selection', 'includes', index)) select_includes = selection_includes def selection_set(self, first, last=None): """Set the selection from FIRST to LAST (included) without changing the currently selected elements.""" self.tk.call(self._w, 'selection', 'set', first, last) select_set = selection_set def size(self): """Return the number of elements in the listbox.""" return self.tk.getint(self.tk.call(self._w, 'size')) def itemcget(self, index, option): """Return the resource value for an ITEM and an OPTION.""" return self.tk.call( (self._w, 'itemcget') + (index, '-'+option)) def itemconfigure(self, index, cnf=None, **kw): """Configure resources of an ITEM. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method without arguments. Valid resource names: background, bg, foreground, fg, selectbackground, selectforeground.""" return self._configure(('itemconfigure', index), cnf, kw) itemconfig = itemconfigure class Menu(Widget): """Menu widget which allows displaying menu bars, pull-down menus and pop-up menus.""" def __init__(self, master=None, cnf={}, **kw): """Construct menu widget with the parent MASTER. Valid resource names: activebackground, activeborderwidth, activeforeground, background, bd, bg, borderwidth, cursor, disabledforeground, fg, font, foreground, postcommand, relief, selectcolor, takefocus, tearoff, tearoffcommand, title, type.""" Widget.__init__(self, master, 'menu', cnf, kw) def tk_popup(self, x, y, entry=""): """Post the menu at position X,Y with entry ENTRY.""" self.tk.call('tk_popup', self._w, x, y, entry) def activate(self, index): """Activate entry at INDEX.""" self.tk.call(self._w, 'activate', index) def add(self, itemType, cnf={}, **kw): """Internal function.""" self.tk.call((self._w, 'add', itemType) + self._options(cnf, kw)) def add_cascade(self, cnf={}, **kw): """Add hierarchical menu item.""" self.add('cascade', cnf or kw) def add_checkbutton(self, cnf={}, **kw): """Add checkbutton menu item.""" self.add('checkbutton', cnf or kw) def add_command(self, cnf={}, **kw): """Add command menu item.""" self.add('command', cnf or kw) def add_radiobutton(self, cnf={}, **kw): """Addd radio menu item.""" self.add('radiobutton', cnf or kw) def add_separator(self, cnf={}, **kw): """Add separator.""" self.add('separator', cnf or kw) def insert(self, index, itemType, cnf={}, **kw): """Internal function.""" self.tk.call((self._w, 'insert', index, itemType) + self._options(cnf, kw)) def insert_cascade(self, index, cnf={}, **kw): """Add hierarchical menu item at INDEX.""" self.insert(index, 'cascade', cnf or kw) def insert_checkbutton(self, index, cnf={}, **kw): """Add checkbutton menu item at INDEX.""" self.insert(index, 'checkbutton', cnf or kw) def insert_command(self, index, cnf={}, **kw): """Add command menu item at INDEX.""" self.insert(index, 'command', cnf or kw) def insert_radiobutton(self, index, cnf={}, **kw): """Addd radio menu item at INDEX.""" self.insert(index, 'radiobutton', cnf or kw) def insert_separator(self, index, cnf={}, **kw): """Add separator at INDEX.""" self.insert(index, 'separator', cnf or kw) def delete(self, index1, index2=None): """Delete menu items between INDEX1 and INDEX2 (included).""" if index2 is None: index2 = index1 num_index1, num_index2 = self.index(index1), self.index(index2) if (num_index1 is None) or (num_index2 is None): num_index1, num_index2 = 0, -1 for i in range(num_index1, num_index2 + 1): if 'command' in self.entryconfig(i): c = str(self.entrycget(i, 'command')) if c: self.deletecommand(c) self.tk.call(self._w, 'delete', index1, index2) def entrycget(self, index, option): """Return the resource value of a menu item for OPTION at INDEX.""" return self.tk.call(self._w, 'entrycget', index, '-' + option) def entryconfigure(self, index, cnf=None, **kw): """Configure a menu item at INDEX.""" return self._configure(('entryconfigure', index), cnf, kw) entryconfig = entryconfigure def index(self, index): """Return the index of a menu item identified by INDEX.""" i = self.tk.call(self._w, 'index', index) if i == 'none': return None return self.tk.getint(i) def invoke(self, index): """Invoke a menu item identified by INDEX and execute the associated command.""" return self.tk.call(self._w, 'invoke', index) def post(self, x, y): """Display a menu at position X,Y.""" self.tk.call(self._w, 'post', x, y) def type(self, index): """Return the type of the menu item at INDEX.""" return self.tk.call(self._w, 'type', index) def unpost(self): """Unmap a menu.""" self.tk.call(self._w, 'unpost') def xposition(self, index): # new in Tk 8.5 """Return the x-position of the leftmost pixel of the menu item at INDEX.""" return self.tk.getint(self.tk.call(self._w, 'xposition', index)) def yposition(self, index): """Return the y-position of the topmost pixel of the menu item at INDEX.""" return self.tk.getint(self.tk.call( self._w, 'yposition', index)) class Menubutton(Widget): """Menubutton widget, obsolete since Tk8.0.""" def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, 'menubutton', cnf, kw) class Message(Widget): """Message widget to display multiline text. Obsolete since Label does it too.""" def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, 'message', cnf, kw) class Radiobutton(Widget): """Radiobutton widget which shows only one of several buttons in on-state.""" def __init__(self, master=None, cnf={}, **kw): """Construct a radiobutton widget with the parent MASTER. Valid resource names: activebackground, activeforeground, anchor, background, bd, bg, bitmap, borderwidth, command, cursor, disabledforeground, fg, font, foreground, height, highlightbackground, highlightcolor, highlightthickness, image, indicatoron, justify, padx, pady, relief, selectcolor, selectimage, state, takefocus, text, textvariable, underline, value, variable, width, wraplength.""" Widget.__init__(self, master, 'radiobutton', cnf, kw) def deselect(self): """Put the button in off-state.""" self.tk.call(self._w, 'deselect') def flash(self): """Flash the button.""" self.tk.call(self._w, 'flash') def invoke(self): """Toggle the button and invoke a command if given as resource.""" return self.tk.call(self._w, 'invoke') def select(self): """Put the button in on-state.""" self.tk.call(self._w, 'select') class Scale(Widget): """Scale widget which can display a numerical scale.""" def __init__(self, master=None, cnf={}, **kw): """Construct a scale widget with the parent MASTER. Valid resource names: activebackground, background, bigincrement, bd, bg, borderwidth, command, cursor, digits, fg, font, foreground, from, highlightbackground, highlightcolor, highlightthickness, label, length, orient, relief, repeatdelay, repeatinterval, resolution, showvalue, sliderlength, sliderrelief, state, takefocus, tickinterval, to, troughcolor, variable, width.""" Widget.__init__(self, master, 'scale', cnf, kw) def get(self): """Get the current value as integer or float.""" value = self.tk.call(self._w, 'get') try: return self.tk.getint(value) except (ValueError, TypeError, TclError): return self.tk.getdouble(value) def set(self, value): """Set the value to VALUE.""" self.tk.call(self._w, 'set', value) def coords(self, value=None): """Return a tuple (X,Y) of the point along the centerline of the trough that corresponds to VALUE or the current value if None is given.""" return self._getints(self.tk.call(self._w, 'coords', value)) def identify(self, x, y): """Return where the point X,Y lies. Valid return values are "slider", "though1" and "though2".""" return self.tk.call(self._w, 'identify', x, y) class Scrollbar(Widget): """Scrollbar widget which displays a slider at a certain position.""" def __init__(self, master=None, cnf={}, **kw): """Construct a scrollbar widget with the parent MASTER. Valid resource names: activebackground, activerelief, background, bd, bg, borderwidth, command, cursor, elementborderwidth, highlightbackground, highlightcolor, highlightthickness, jump, orient, relief, repeatdelay, repeatinterval, takefocus, troughcolor, width.""" Widget.__init__(self, master, 'scrollbar', cnf, kw) def activate(self, index=None): """Marks the element indicated by index as active. The only index values understood by this method are "arrow1", "slider", or "arrow2". If any other value is specified then no element of the scrollbar will be active. If index is not specified, the method returns the name of the element that is currently active, or None if no element is active.""" return self.tk.call(self._w, 'activate', index) or None def delta(self, deltax, deltay): """Return the fractional change of the scrollbar setting if it would be moved by DELTAX or DELTAY pixels.""" return self.tk.getdouble( self.tk.call(self._w, 'delta', deltax, deltay)) def fraction(self, x, y): """Return the fractional value which corresponds to a slider position of X,Y.""" return self.tk.getdouble(self.tk.call(self._w, 'fraction', x, y)) def identify(self, x, y): """Return the element under position X,Y as one of "arrow1","slider","arrow2" or "".""" return self.tk.call(self._w, 'identify', x, y) def get(self): """Return the current fractional values (upper and lower end) of the slider position.""" return self._getdoubles(self.tk.call(self._w, 'get')) def set(self, first, last): """Set the fractional values of the slider position (upper and lower ends as value between 0 and 1).""" self.tk.call(self._w, 'set', first, last) class Text(Widget, XView, YView): """Text widget which can display text in various forms.""" def __init__(self, master=None, cnf={}, **kw): """Construct a text widget with the parent MASTER. STANDARD OPTIONS background, borderwidth, cursor, exportselection, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, padx, pady, relief, selectbackground, selectborderwidth, selectforeground, setgrid, takefocus, xscrollcommand, yscrollcommand, WIDGET-SPECIFIC OPTIONS autoseparators, height, maxundo, spacing1, spacing2, spacing3, state, tabs, undo, width, wrap, """ Widget.__init__(self, master, 'text', cnf, kw) def bbox(self, index): """Return a tuple of (x,y,width,height) which gives the bounding box of the visible part of the character at the given index.""" return self._getints( self.tk.call(self._w, 'bbox', index)) or None def compare(self, index1, op, index2): """Return whether between index INDEX1 and index INDEX2 the relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=.""" return self.tk.getboolean(self.tk.call( self._w, 'compare', index1, op, index2)) def count(self, index1, index2, *args): # new in Tk 8.5 """Counts the number of relevant things between the two indices. If index1 is after index2, the result will be a negative number (and this holds for each of the possible options). The actual items which are counted depends on the options given by args. The result is a list of integers, one for the result of each counting option given. Valid counting options are "chars", "displaychars", "displayindices", "displaylines", "indices", "lines", "xpixels" and "ypixels". There is an additional possible option "update", which if given then all subsequent options ensure that any possible out of date information is recalculated.""" args = ['-%s' % arg for arg in args if not arg.startswith('-')] args += [index1, index2] res = self.tk.call(self._w, 'count', *args) or None if res is not None and len(args) <= 3: return (res, ) else: return res def debug(self, boolean=None): """Turn on the internal consistency checks of the B-Tree inside the text widget according to BOOLEAN.""" if boolean is None: return self.tk.getboolean(self.tk.call(self._w, 'debug')) self.tk.call(self._w, 'debug', boolean) def delete(self, index1, index2=None): """Delete the characters between INDEX1 and INDEX2 (not included).""" self.tk.call(self._w, 'delete', index1, index2) def dlineinfo(self, index): """Return tuple (x,y,width,height,baseline) giving the bounding box and baseline position of the visible part of the line containing the character at INDEX.""" return self._getints(self.tk.call(self._w, 'dlineinfo', index)) def dump(self, index1, index2=None, command=None, **kw): """Return the contents of the widget between index1 and index2. The type of contents returned in filtered based on the keyword parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are given and true, then the corresponding items are returned. The result is a list of triples of the form (key, value, index). If none of the keywords are true then 'all' is used by default. If the 'command' argument is given, it is called once for each element of the list of triples, with the values of each triple serving as the arguments to the function. In this case the list is not returned.""" args = [] func_name = None result = None if not command: # Never call the dump command without the -command flag, since the # output could involve Tcl quoting and would be a pain to parse # right. Instead just set the command to build a list of triples # as if we had done the parsing. result = [] def append_triple(key, value, index, result=result): result.append((key, value, index)) command = append_triple try: if not isinstance(command, str): func_name = command = self._register(command) args += ["-command", command] for key in kw: if kw[key]: args.append("-" + key) args.append(index1) if index2: args.append(index2) self.tk.call(self._w, "dump", *args) return result finally: if func_name: self.deletecommand(func_name) ## new in tk8.4 def edit(self, *args): """Internal method This method controls the undo mechanism and the modified flag. The exact behavior of the command depends on the option argument that follows the edit argument. The following forms of the command are currently supported: edit_modified, edit_redo, edit_reset, edit_separator and edit_undo """ return self.tk.call(self._w, 'edit', *args) def edit_modified(self, arg=None): """Get or Set the modified flag If arg is not specified, returns the modified flag of the widget. The insert, delete, edit undo and edit redo commands or the user can set or clear the modified flag. If boolean is specified, sets the modified flag of the widget to arg. """ return self.edit("modified", arg) def edit_redo(self): """Redo the last undone edit When the undo option is true, reapplies the last undone edits provided no other edits were done since then. Generates an error when the redo stack is empty. Does nothing when the undo option is false. """ return self.edit("redo") def edit_reset(self): """Clears the undo and redo stacks """ return self.edit("reset") def edit_separator(self): """Inserts a separator (boundary) on the undo stack. Does nothing when the undo option is false """ return self.edit("separator") def edit_undo(self): """Undoes the last edit action If the undo option is true. An edit action is defined as all the insert and delete commands that are recorded on the undo stack in between two separators. Generates an error when the undo stack is empty. Does nothing when the undo option is false """ return self.edit("undo") def get(self, index1, index2=None): """Return the text from INDEX1 to INDEX2 (not included).""" return self.tk.call(self._w, 'get', index1, index2) # (Image commands are new in 8.0) def image_cget(self, index, option): """Return the value of OPTION of an embedded image at INDEX.""" if option[:1] != "-": option = "-" + option if option[-1:] == "_": option = option[:-1] return self.tk.call(self._w, "image", "cget", index, option) def image_configure(self, index, cnf=None, **kw): """Configure an embedded image at INDEX.""" return self._configure(('image', 'configure', index), cnf, kw) def image_create(self, index, cnf={}, **kw): """Create an embedded image at INDEX.""" return self.tk.call( self._w, "image", "create", index, *self._options(cnf, kw)) def image_names(self): """Return all names of embedded images in this widget.""" return self.tk.call(self._w, "image", "names") def index(self, index): """Return the index in the form line.char for INDEX.""" return str(self.tk.call(self._w, 'index', index)) def insert(self, index, chars, *args): """Insert CHARS before the characters at INDEX. An additional tag can be given in ARGS. Additional CHARS and tags can follow in ARGS.""" self.tk.call((self._w, 'insert', index, chars) + args) def mark_gravity(self, markName, direction=None): """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT). Return the current value if None is given for DIRECTION.""" return self.tk.call( (self._w, 'mark', 'gravity', markName, direction)) def mark_names(self): """Return all mark names.""" return self.tk.splitlist(self.tk.call( self._w, 'mark', 'names')) def mark_set(self, markName, index): """Set mark MARKNAME before the character at INDEX.""" self.tk.call(self._w, 'mark', 'set', markName, index) def mark_unset(self, *markNames): """Delete all marks in MARKNAMES.""" self.tk.call((self._w, 'mark', 'unset') + markNames) def mark_next(self, index): """Return the name of the next mark after INDEX.""" return self.tk.call(self._w, 'mark', 'next', index) or None def mark_previous(self, index): """Return the name of the previous mark before INDEX.""" return self.tk.call(self._w, 'mark', 'previous', index) or None def peer_create(self, newPathName, cnf={}, **kw): # new in Tk 8.5 """Creates a peer text widget with the given newPathName, and any optional standard configuration options. By default the peer will have the same start and end line as the parent widget, but these can be overridden with the standard configuration options.""" self.tk.call(self._w, 'peer', 'create', newPathName, *self._options(cnf, kw)) def peer_names(self): # new in Tk 8.5 """Returns a list of peers of this widget (this does not include the widget itself).""" return self.tk.splitlist(self.tk.call(self._w, 'peer', 'names')) def replace(self, index1, index2, chars, *args): # new in Tk 8.5 """Replaces the range of characters between index1 and index2 with the given characters and tags specified by args. See the method insert for some more information about args, and the method delete for information about the indices.""" self.tk.call(self._w, 'replace', index1, index2, chars, *args) def scan_mark(self, x, y): """Remember the current X, Y coordinates.""" self.tk.call(self._w, 'scan', 'mark', x, y) def scan_dragto(self, x, y): """Adjust the view of the text to 10 times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x, y) def search(self, pattern, index, stopindex=None, forwards=None, backwards=None, exact=None, regexp=None, nocase=None, count=None, elide=None): """Search PATTERN beginning from INDEX until STOPINDEX. Return the index of the first character of a match or an empty string.""" args = [self._w, 'search'] if forwards: args.append('-forwards') if backwards: args.append('-backwards') if exact: args.append('-exact') if regexp: args.append('-regexp') if nocase: args.append('-nocase') if elide: args.append('-elide') if count: args.append('-count'); args.append(count) if pattern and pattern[0] == '-': args.append('--') args.append(pattern) args.append(index) if stopindex: args.append(stopindex) return str(self.tk.call(tuple(args))) def see(self, index): """Scroll such that the character at INDEX is visible.""" self.tk.call(self._w, 'see', index) def tag_add(self, tagName, index1, *args): """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS. Additional pairs of indices may follow in ARGS.""" self.tk.call( (self._w, 'tag', 'add', tagName, index1) + args) def tag_unbind(self, tagName, sequence, funcid=None): """Unbind for all characters with TAGNAME for event SEQUENCE the function identified with FUNCID.""" self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid) def tag_bind(self, tagName, sequence, func, add=None): """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.""" return self._bind((self._w, 'tag', 'bind', tagName), sequence, func, add) def tag_cget(self, tagName, option): """Return the value of OPTION for tag TAGNAME.""" if option[:1] != '-': option = '-' + option if option[-1:] == '_': option = option[:-1] return self.tk.call(self._w, 'tag', 'cget', tagName, option) def tag_configure(self, tagName, cnf=None, **kw): """Configure a tag TAGNAME.""" return self._configure(('tag', 'configure', tagName), cnf, kw) tag_config = tag_configure def tag_delete(self, *tagNames): """Delete all tags in TAGNAMES.""" self.tk.call((self._w, 'tag', 'delete') + tagNames) def tag_lower(self, tagName, belowThis=None): """Change the priority of tag TAGNAME such that it is lower than the priority of BELOWTHIS.""" self.tk.call(self._w, 'tag', 'lower', tagName, belowThis) def tag_names(self, index=None): """Return a list of all tag names.""" return self.tk.splitlist( self.tk.call(self._w, 'tag', 'names', index)) def tag_nextrange(self, tagName, index1, index2=None): """Return a list of start and end index for the first sequence of characters between INDEX1 and INDEX2 which all have tag TAGNAME. The text is searched forward from INDEX1.""" return self.tk.splitlist(self.tk.call( self._w, 'tag', 'nextrange', tagName, index1, index2)) def tag_prevrange(self, tagName, index1, index2=None): """Return a list of start and end index for the first sequence of characters between INDEX1 and INDEX2 which all have tag TAGNAME. The text is searched backwards from INDEX1.""" return self.tk.splitlist(self.tk.call( self._w, 'tag', 'prevrange', tagName, index1, index2)) def tag_raise(self, tagName, aboveThis=None): """Change the priority of tag TAGNAME such that it is higher than the priority of ABOVETHIS.""" self.tk.call( self._w, 'tag', 'raise', tagName, aboveThis) def tag_ranges(self, tagName): """Return a list of ranges of text which have tag TAGNAME.""" return self.tk.splitlist(self.tk.call( self._w, 'tag', 'ranges', tagName)) def tag_remove(self, tagName, index1, index2=None): """Remove tag TAGNAME from all characters between INDEX1 and INDEX2.""" self.tk.call( self._w, 'tag', 'remove', tagName, index1, index2) def window_cget(self, index, option): """Return the value of OPTION of an embedded window at INDEX.""" if option[:1] != '-': option = '-' + option if option[-1:] == '_': option = option[:-1] return self.tk.call(self._w, 'window', 'cget', index, option) def window_configure(self, index, cnf=None, **kw): """Configure an embedded window at INDEX.""" return self._configure(('window', 'configure', index), cnf, kw) window_config = window_configure def window_create(self, index, cnf={}, **kw): """Create a window at INDEX.""" self.tk.call( (self._w, 'window', 'create', index) + self._options(cnf, kw)) def window_names(self): """Return all names of embedded windows in this widget.""" return self.tk.splitlist( self.tk.call(self._w, 'window', 'names')) def yview_pickplace(self, *what): """Obsolete function, use see.""" self.tk.call((self._w, 'yview', '-pickplace') + what) class _setit: """Internal class. It wraps the command in the widget OptionMenu.""" def __init__(self, var, value, callback=None): self.__value = value self.__var = var self.__callback = callback def __call__(self, *args): self.__var.set(self.__value) if self.__callback: self.__callback(self.__value, *args) class OptionMenu(Menubutton): """OptionMenu which allows the user to select a value from a menu.""" def __init__(self, master, variable, value, *values, **kwargs): """Construct an optionmenu widget with the parent MASTER, with the resource textvariable set to VARIABLE, the initially selected value VALUE, the other menu values VALUES and an additional keyword argument command.""" kw = {"borderwidth": 2, "textvariable": variable, "indicatoron": 1, "relief": RAISED, "anchor": "c", "highlightthickness": 2} Widget.__init__(self, master, "menubutton", kw) self.widgetName = 'tk_optionMenu' menu = self.__menu = Menu(self, name="menu", tearoff=0) self.menuname = menu._w # 'command' is the only supported keyword callback = kwargs.get('command') if 'command' in kwargs: del kwargs['command'] if kwargs: raise TclError('unknown option -'+kwargs.keys()[0]) menu.add_command(label=value, command=_setit(variable, value, callback)) for v in values: menu.add_command(label=v, command=_setit(variable, v, callback)) self["menu"] = menu def __getitem__(self, name): if name == 'menu': return self.__menu return Widget.__getitem__(self, name) def destroy(self): """Destroy this widget and the associated menu.""" Menubutton.destroy(self) self.__menu = None class Image: """Base class for images.""" _last_id = 0 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw): self.name = None if not master: master = _default_root if not master: raise RuntimeError('Too early to create image') self.tk = getattr(master, 'tk', master) if not name: Image._last_id += 1 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x> if kw and cnf: cnf = _cnfmerge((cnf, kw)) elif kw: cnf = kw options = () for k, v in cnf.items(): if callable(v): v = self._register(v) options = options + ('-'+k, v) self.tk.call(('image', 'create', imgtype, name,) + options) self.name = name def __str__(self): return self.name def __del__(self): if self.name: try: self.tk.call('image', 'delete', self.name) except TclError: # May happen if the root was destroyed pass def __setitem__(self, key, value): self.tk.call(self.name, 'configure', '-'+key, value) def __getitem__(self, key): return self.tk.call(self.name, 'configure', '-'+key) def configure(self, **kw): """Configure the image.""" res = () for k, v in _cnfmerge(kw).items(): if v is not None: if k[-1] == '_': k = k[:-1] if callable(v): v = self._register(v) res = res + ('-'+k, v) self.tk.call((self.name, 'config') + res) config = configure def height(self): """Return the height of the image.""" return self.tk.getint( self.tk.call('image', 'height', self.name)) def type(self): """Return the type of the image, e.g. "photo" or "bitmap".""" return self.tk.call('image', 'type', self.name) def width(self): """Return the width of the image.""" return self.tk.getint( self.tk.call('image', 'width', self.name)) class PhotoImage(Image): """Widget which can display images in PGM, PPM, GIF, PNG format.""" def __init__(self, name=None, cnf={}, master=None, **kw): """Create an image with NAME. Valid resource names: data, format, file, gamma, height, palette, width.""" Image.__init__(self, 'photo', name, cnf, master, **kw) def blank(self): """Display a transparent image.""" self.tk.call(self.name, 'blank') def cget(self, option): """Return the value of OPTION.""" return self.tk.call(self.name, 'cget', '-' + option) # XXX config def __getitem__(self, key): return self.tk.call(self.name, 'cget', '-' + key) # XXX copy -from, -to, ...? def copy(self): """Return a new PhotoImage with the same image as this widget.""" destImage = PhotoImage(master=self.tk) self.tk.call(destImage, 'copy', self.name) return destImage def zoom(self, x, y=''): """Return a new PhotoImage with the same image as this widget but zoom it with a factor of x in the X direction and y in the Y direction. If y is not given, the default value is the same as x. """ destImage = PhotoImage(master=self.tk) if y=='': y=x self.tk.call(destImage, 'copy', self.name, '-zoom',x,y) return destImage def subsample(self, x, y=''): """Return a new PhotoImage based on the same image as this widget but use only every Xth or Yth pixel. If y is not given, the default value is the same as x. """ destImage = PhotoImage(master=self.tk) if y=='': y=x self.tk.call(destImage, 'copy', self.name, '-subsample',x,y) return destImage def get(self, x, y): """Return the color (red, green, blue) of the pixel at X,Y.""" return self.tk.call(self.name, 'get', x, y) def put(self, data, to=None): """Put row formatted colors to image starting from position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))""" args = (self.name, 'put', data) if to: if to[0] == '-to': to = to[1:] args = args + ('-to',) + tuple(to) self.tk.call(args) # XXX read def write(self, filename, format=None, from_coords=None): """Write image to file FILENAME in FORMAT starting from position FROM_COORDS.""" args = (self.name, 'write', filename) if format: args = args + ('-format', format) if from_coords: args = args + ('-from',) + tuple(from_coords) self.tk.call(args) class BitmapImage(Image): """Widget which can display images in XBM format.""" def __init__(self, name=None, cnf={}, master=None, **kw): """Create a bitmap with NAME. Valid resource names: background, data, file, foreground, maskdata, maskfile.""" Image.__init__(self, 'bitmap', name, cnf, master, **kw) def image_names(): return _default_root.tk.splitlist(_default_root.tk.call('image', 'names')) def image_types(): return _default_root.tk.splitlist(_default_root.tk.call('image', 'types')) class Spinbox(Widget, XView): """spinbox widget.""" def __init__(self, master=None, cnf={}, **kw): """Construct a spinbox widget with the parent MASTER. STANDARD OPTIONS activebackground, background, borderwidth, cursor, exportselection, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, justify, relief, repeatdelay, repeatinterval, selectbackground, selectborderwidth selectforeground, takefocus, textvariable xscrollcommand. WIDGET-SPECIFIC OPTIONS buttonbackground, buttoncursor, buttondownrelief, buttonuprelief, command, disabledbackground, disabledforeground, format, from, invalidcommand, increment, readonlybackground, state, to, validate, validatecommand values, width, wrap, """ Widget.__init__(self, master, 'spinbox', cnf, kw) def bbox(self, index): """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses the character given by index. The first two elements of the list give the x and y coordinates of the upper-left corner of the screen area covered by the character (in pixels relative to the widget) and the last two elements give the width and height of the character, in pixels. The bounding box may refer to a region outside the visible area of the window. """ return self._getints(self.tk.call(self._w, 'bbox', index)) or None def delete(self, first, last=None): """Delete one or more elements of the spinbox. First is the index of the first character to delete, and last is the index of the character just after the last one to delete. If last isn't specified it defaults to first+1, i.e. a single character is deleted. This command returns an empty string. """ return self.tk.call(self._w, 'delete', first, last) def get(self): """Returns the spinbox's string""" return self.tk.call(self._w, 'get') def icursor(self, index): """Alter the position of the insertion cursor. The insertion cursor will be displayed just before the character given by index. Returns an empty string """ return self.tk.call(self._w, 'icursor', index) def identify(self, x, y): """Returns the name of the widget at position x, y Return value is one of: none, buttondown, buttonup, entry """ return self.tk.call(self._w, 'identify', x, y) def index(self, index): """Returns the numerical index corresponding to index """ return self.tk.call(self._w, 'index', index) def insert(self, index, s): """Insert string s at index Returns an empty string. """ return self.tk.call(self._w, 'insert', index, s) def invoke(self, element): """Causes the specified element to be invoked The element could be buttondown or buttonup triggering the action associated with it. """ return self.tk.call(self._w, 'invoke', element) def scan(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'scan') + args)) or () def scan_mark(self, x): """Records x and the current view in the spinbox window; used in conjunction with later scan dragto commands. Typically this command is associated with a mouse button press in the widget. It returns an empty string. """ return self.scan("mark", x) def scan_dragto(self, x): """Compute the difference between the given x argument and the x argument to the last scan mark command It then adjusts the view left or right by 10 times the difference in x-coordinates. This command is typically associated with mouse motion events in the widget, to produce the effect of dragging the spinbox at high speed through the window. The return value is an empty string. """ return self.scan("dragto", x) def selection(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'selection') + args)) or () def selection_adjust(self, index): """Locate the end of the selection nearest to the character given by index, Then adjust that end of the selection to be at index (i.e including but not going beyond index). The other end of the selection is made the anchor point for future select to commands. If the selection isn't currently in the spinbox, then a new selection is created to include the characters between index and the most recent selection anchor point, inclusive. """ return self.selection("adjust", index) def selection_clear(self): """Clear the selection If the selection isn't in this widget then the command has no effect. """ return self.selection("clear") def selection_element(self, element=None): """Sets or gets the currently selected element. If a spinbutton element is specified, it will be displayed depressed. """ return self.tk.call(self._w, 'selection', 'element', element) ########################################################################### class LabelFrame(Widget): """labelframe widget.""" def __init__(self, master=None, cnf={}, **kw): """Construct a labelframe widget with the parent MASTER. STANDARD OPTIONS borderwidth, cursor, font, foreground, highlightbackground, highlightcolor, highlightthickness, padx, pady, relief, takefocus, text WIDGET-SPECIFIC OPTIONS background, class, colormap, container, height, labelanchor, labelwidget, visual, width """ Widget.__init__(self, master, 'labelframe', cnf, kw) ######################################################################## class PanedWindow(Widget): """panedwindow widget.""" def __init__(self, master=None, cnf={}, **kw): """Construct a panedwindow widget with the parent MASTER. STANDARD OPTIONS background, borderwidth, cursor, height, orient, relief, width WIDGET-SPECIFIC OPTIONS handlepad, handlesize, opaqueresize, sashcursor, sashpad, sashrelief, sashwidth, showhandle, """ Widget.__init__(self, master, 'panedwindow', cnf, kw) def add(self, child, **kw): """Add a child widget to the panedwindow in a new pane. The child argument is the name of the child widget followed by pairs of arguments that specify how to manage the windows. The possible options and values are the ones accepted by the paneconfigure method. """ self.tk.call((self._w, 'add', child) + self._options(kw)) def remove(self, child): """Remove the pane containing child from the panedwindow All geometry management options for child will be forgotten. """ self.tk.call(self._w, 'forget', child) forget=remove def identify(self, x, y): """Identify the panedwindow component at point x, y If the point is over a sash or a sash handle, the result is a two element list containing the index of the sash or handle, and a word indicating whether it is over a sash or a handle, such as {0 sash} or {2 handle}. If the point is over any other part of the panedwindow, the result is an empty list. """ return self.tk.call(self._w, 'identify', x, y) def proxy(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'proxy') + args)) or () def proxy_coord(self): """Return the x and y pair of the most recent proxy location """ return self.proxy("coord") def proxy_forget(self): """Remove the proxy from the display. """ return self.proxy("forget") def proxy_place(self, x, y): """Place the proxy at the given x and y coordinates. """ return self.proxy("place", x, y) def sash(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'sash') + args)) or () def sash_coord(self, index): """Return the current x and y pair for the sash given by index. Index must be an integer between 0 and 1 less than the number of panes in the panedwindow. The coordinates given are those of the top left corner of the region containing the sash. pathName sash dragto index x y This command computes the difference between the given coordinates and the coordinates given to the last sash coord command for the given sash. It then moves that sash the computed difference. The return value is the empty string. """ return self.sash("coord", index) def sash_mark(self, index): """Records x and y for the sash given by index; Used in conjunction with later dragto commands to move the sash. """ return self.sash("mark", index) def sash_place(self, index, x, y): """Place the sash given by index at the given coordinates """ return self.sash("place", index, x, y) def panecget(self, child, option): """Query a management option for window. Option may be any value allowed by the paneconfigure subcommand """ return self.tk.call( (self._w, 'panecget') + (child, '-'+option)) def paneconfigure(self, tagOrId, cnf=None, **kw): """Query or modify the management options for window. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. The following options are supported: after window Insert the window after the window specified. window should be the name of a window already managed by pathName. before window Insert the window before the window specified. window should be the name of a window already managed by pathName. height size Specify a height for the window. The height will be the outer dimension of the window including its border, if any. If size is an empty string, or if -height is not specified, then the height requested internally by the window will be used initially; the height may later be adjusted by the movement of sashes in the panedwindow. Size may be any value accepted by Tk_GetPixels. minsize n Specifies that the size of the window cannot be made less than n. This constraint only affects the size of the widget in the paned dimension -- the x dimension for horizontal panedwindows, the y dimension for vertical panedwindows. May be any value accepted by Tk_GetPixels. padx n Specifies a non-negative value indicating how much extra space to leave on each side of the window in the X-direction. The value may have any of the forms accepted by Tk_GetPixels. pady n Specifies a non-negative value indicating how much extra space to leave on each side of the window in the Y-direction. The value may have any of the forms accepted by Tk_GetPixels. sticky style If a window's pane is larger than the requested dimensions of the window, this option may be used to position (or stretch) the window within its pane. Style is a string that contains zero or more of the characters n, s, e or w. The string can optionally contains spaces or commas, but they are ignored. Each letter refers to a side (north, south, east, or west) that the window will "stick" to. If both n and s (or e and w) are specified, the window will be stretched to fill the entire height (or width) of its cavity. width size Specify a width for the window. The width will be the outer dimension of the window including its border, if any. If size is an empty string, or if -width is not specified, then the width requested internally by the window will be used initially; the width may later be adjusted by the movement of sashes in the panedwindow. Size may be any value accepted by Tk_GetPixels. """ if cnf is None and not kw: return self._getconfigure(self._w, 'paneconfigure', tagOrId) if isinstance(cnf, str) and not kw: return self._getconfigure1( self._w, 'paneconfigure', tagOrId, '-'+cnf) self.tk.call((self._w, 'paneconfigure', tagOrId) + self._options(cnf, kw)) paneconfig = paneconfigure def panes(self): """Returns an ordered list of the child panes.""" return self.tk.splitlist(self.tk.call(self._w, 'panes')) # Test: def _test(): root = Tk() text = "This is Tcl/Tk version %s" % TclVersion text += "\nThis should be a cedilla: \xe7" label = Label(root, text=text) label.pack() test = Button(root, text="Click me!", command=lambda root=root: root.test.configure( text="[%s]" % root.test['text'])) test.pack() root.test = test quit = Button(root, text="QUIT", command=root.destroy) quit.pack() # The following three commands are needed so the window pops # up on top on Windows... root.iconify() root.update() root.deiconify() root.mainloop() if __name__ == '__main__': _test()
prefetchnta/questlab
bin/x64bin/python/37/Lib/tkinter/__init__.py
Python
lgpl-2.1
170,982
// Accord Statistics Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2016 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.MachineLearning { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; /// <summary> /// Common interface for parallel algorithms. /// </summary> /// public interface IParallel : ISupportsCancellation { /// <summary> /// Gets or sets the parallelization options for this algorithm. /// </summary> /// ParallelOptions ParallelOptions { get; set; } } /// <summary> /// Common interface for algorithms that can be canceled /// in the middle of execution. /// </summary> /// public interface ISupportsCancellation { /// <summary> /// Gets or sets a cancellation token that can be used /// to cancel the algorithm while it is running. /// </summary> /// CancellationToken Token { get; set; } } }
cureos/accord
Sources/Accord.Statistics/Accord.MachineLearning/Learning/IParallel.cs
C#
lgpl-2.1
1,980
///////////////////////////////////////////////////////////////////////////// // Name: controls.cpp // Purpose: Controls wxWidgets sample // Author: Robert Roebling // Modified by: // RCS-ID: $Id$ // Copyright: (c) Robert Roebling, Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wx/spinbutt.h" #include "wx/tglbtn.h" #include "wx/bookctrl.h" #include "wx/imaglist.h" #include "wx/artprov.h" #include "wx/cshelp.h" #include "wx/gbsizer.h" #if wxUSE_TOOLTIPS #include "wx/tooltip.h" #ifdef __WXMSW__ #include "wx/numdlg.h" #endif // __WXMSW__ #endif // wxUSE_TOOLTIPS #ifndef __WXMSW__ #include "icons/choice.xpm" #include "icons/combo.xpm" #include "icons/list.xpm" #include "icons/radio.xpm" #include "icons/text.xpm" #include "icons/gauge.xpm" #endif #ifndef wxUSE_SPINBTN #define wxUSE_SPINBTN 1 #endif #include "wx/progdlg.h" #if wxUSE_SPINCTRL #include "wx/spinctrl.h" #endif // wxUSE_SPINCTRL #if !wxUSE_TOGGLEBTN #define wxToggleButton wxCheckBox #define EVT_TOGGLEBUTTON EVT_CHECKBOX #endif #ifndef wxHAS_IMAGES_IN_RESOURCES #include "../sample.xpm" #endif //---------------------------------------------------------------------- // class definitions //---------------------------------------------------------------------- class MyApp: public wxApp { public: bool OnInit(); }; class MyPanel: public wxPanel { public: MyPanel(wxFrame *frame, int x, int y, int w, int h); virtual ~MyPanel(); #if wxUSE_TOOLTIPS void SetAllToolTips(); #endif // wxUSE_TOOLTIPS void OnIdle( wxIdleEvent &event ); void OnListBox( wxCommandEvent &event ); void OnListBoxDoubleClick( wxCommandEvent &event ); void OnListBoxButtons( wxCommandEvent &event ); #if wxUSE_CHOICE void OnChoice( wxCommandEvent &event ); void OnChoiceButtons( wxCommandEvent &event ); #endif void OnCombo( wxCommandEvent &event ); void OnComboTextChanged( wxCommandEvent &event ); void OnComboTextEnter( wxCommandEvent &event ); void OnComboButtons( wxCommandEvent &event ); void OnRadio( wxCommandEvent &event ); void OnRadioButtons( wxCommandEvent &event ); void OnRadioButton1( wxCommandEvent &event ); void OnRadioButton2( wxCommandEvent &event ); void OnSetFont( wxCommandEvent &event ); void OnPageChanged( wxBookCtrlEvent &event ); void OnPageChanging( wxBookCtrlEvent &event ); void OnSliderUpdate( wxCommandEvent &event ); void OnUpdateLabel( wxCommandEvent &event ); #if wxUSE_SPINBTN void OnSpinUp( wxSpinEvent &event ); void OnSpinDown( wxSpinEvent &event ); void OnSpinUpdate( wxSpinEvent &event ); #if wxUSE_PROGRESSDLG void OnUpdateShowProgress( wxUpdateUIEvent& event ); void OnShowProgress( wxCommandEvent &event ); #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN void OnNewText( wxCommandEvent &event ); #if wxUSE_SPINCTRL void OnSpinCtrl(wxSpinEvent& event); void OnSpinCtrlUp(wxSpinEvent& event); void OnSpinCtrlDown(wxSpinEvent& event); void OnSpinCtrlText(wxCommandEvent& event); #endif // wxUSE_SPINCTRL void OnEnableAll(wxCommandEvent& event); void OnChangeColour(wxCommandEvent& event); void OnTestButton(wxCommandEvent& event); void OnBmpButton(wxCommandEvent& event); void OnBmpButtonToggle(wxCommandEvent& event); void OnSizerCheck (wxCommandEvent &event); wxListBox *m_listbox, *m_listboxSorted; #if wxUSE_CHOICE wxChoice *m_choice, *m_choiceSorted; #endif // wxUSE_CHOICE wxComboBox *m_combo; wxRadioBox *m_radio; #if wxUSE_GAUGE wxGauge *m_gauge, *m_gaugeVert; #endif // wxUSE_GAUGE #if wxUSE_SLIDER wxSlider *m_slider; #endif // wxUSE_SLIDER wxButton *m_fontButton; wxButton *m_lbSelectNum; wxButton *m_lbSelectThis; #if wxUSE_SPINBTN wxSpinButton *m_spinbutton; #if wxUSE_PROGRESSDLG wxButton *m_btnProgress; #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN wxStaticText *m_wrappingText; wxStaticText *m_nonWrappingText; #if wxUSE_SPINCTRL wxSpinCtrl *m_spinctrl; #endif // wxUSE_SPINCTRL wxTextCtrl *m_spintext; wxCheckBox *m_checkbox; wxTextCtrl *m_text; wxBookCtrl *m_book; wxStaticText *m_label; wxBoxSizer *m_buttonSizer; wxButton *m_sizerBtn1; wxButton *m_sizerBtn2; wxButton *m_sizerBtn3; wxButton *m_sizerBtn4; wxBoxSizer *m_hsizer; wxButton *m_bigBtn; private: wxLog *m_logTargetOld; DECLARE_EVENT_TABLE() }; class MyFrame: public wxFrame { public: MyFrame(const wxChar *title, int x, int y); void OnQuit(wxCommandEvent& event); void OnAbout(wxCommandEvent& event); void OnClearLog(wxCommandEvent& event); #if wxUSE_TOOLTIPS void OnSetTooltipDelay(wxCommandEvent& event); void OnToggleTooltips(wxCommandEvent& event); #ifdef __WXMSW__ void OnSetMaxTooltipWidth(wxCommandEvent& event); #endif // __WXMSW__ #endif // wxUSE_TOOLTIPS void OnEnableAll(wxCommandEvent& event); void OnHideAll(wxCommandEvent& event); void OnHideList(wxCommandEvent& event); void OnContextHelp(wxCommandEvent& event); void OnIdle( wxIdleEvent& event ); void OnIconized( wxIconizeEvent& event ); void OnMaximized( wxMaximizeEvent& event ); void OnSize( wxSizeEvent& event ); void OnMove( wxMoveEvent& event ); MyPanel *GetPanel() const { return m_panel; } private: #if wxUSE_STATUSBAR void UpdateStatusBar(const wxPoint& pos, const wxSize& size) { if ( m_frameStatusBar ) { wxString msg; wxSize sizeAll = GetSize(), sizeCl = GetClientSize(); msg.Printf(_("pos=(%d, %d), size=%dx%d or %dx%d (client=%dx%d)"), pos.x, pos.y, size.x, size.y, sizeAll.x, sizeAll.y, sizeCl.x, sizeCl.y); SetStatusText(msg, 1); } } #endif // wxUSE_STATUSBAR MyPanel *m_panel; DECLARE_EVENT_TABLE() }; // a button which intercepts double clicks (for testing...) class MyButton : public wxButton { public: MyButton(wxWindow *parent, wxWindowID id, const wxString& label = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize) : wxButton(parent, id, label, pos, size) { } void OnDClick(wxMouseEvent& event) { wxLogMessage(wxT("MyButton::OnDClick")); event.Skip(); } private: DECLARE_EVENT_TABLE() }; // a combo which intercepts chars (to test Windows behaviour) class MyComboBox : public wxComboBox { public: MyComboBox(wxWindow *parent, wxWindowID id, const wxString& value = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, int n = 0, const wxString choices[] = NULL, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxComboBoxNameStr) : wxComboBox(parent, id, value, pos, size, n, choices, style, validator, name) { } protected: void OnChar(wxKeyEvent& event); void OnKeyDown(wxKeyEvent& event); void OnKeyUp(wxKeyEvent& event); void OnFocusGot(wxFocusEvent& event) { wxLogMessage(wxT("MyComboBox::OnFocusGot")); event.Skip(); } private: DECLARE_EVENT_TABLE() }; // a radiobox which handles focus set/kill (for testing) class MyRadioBox : public wxRadioBox { public: MyRadioBox(wxWindow *parent, wxWindowID id, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, int n = 0, const wxString choices[] = NULL, int majorDim = 1, long style = wxRA_SPECIFY_COLS, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxRadioBoxNameStr) : wxRadioBox(parent, id, title, pos, size, n, choices, majorDim, style, validator, name) { } protected: void OnFocusGot(wxFocusEvent& event) { wxLogMessage(wxT("MyRadioBox::OnFocusGot")); event.Skip(); } void OnFocusLost(wxFocusEvent& event) { wxLogMessage(wxT("MyRadioBox::OnFocusLost")); event.Skip(); } private: DECLARE_EVENT_TABLE() }; // a choice which handles focus set/kill (for testing) class MyChoice : public wxChoice { public: MyChoice(wxWindow *parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, int n = 0, const wxString choices[] = NULL, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxChoiceNameStr ) : wxChoice(parent, id, pos, size, n, choices, style, validator, name) { } protected: void OnFocusGot(wxFocusEvent& event) { wxLogMessage(wxT("MyChoice::OnFocusGot")); event.Skip(); } void OnFocusLost(wxFocusEvent& event) { wxLogMessage(wxT("MyChoice::OnFocusLost")); event.Skip(); } private: DECLARE_EVENT_TABLE() }; //---------------------------------------------------------------------- // other //---------------------------------------------------------------------- static void SetListboxClientData(const wxChar *name, wxListBox *control); #if wxUSE_CHOICE static void SetChoiceClientData(const wxChar *name, wxChoice *control); #endif // wxUSE_CHOICE IMPLEMENT_APP(MyApp) //---------------------------------------------------------------------- // MyApp //---------------------------------------------------------------------- enum { CONTROLS_QUIT = wxID_EXIT, CONTROLS_ABOUT = wxID_ABOUT, CONTROLS_TEXT = 100, CONTROLS_CLEAR_LOG, // tooltip menu CONTROLS_SET_TOOLTIP_DELAY = 200, CONTROLS_ENABLE_TOOLTIPS, CONTROLS_SET_TOOLTIPS_MAX_WIDTH, // panel menu CONTROLS_ENABLE_ALL, CONTROLS_HIDE_ALL, CONTROLS_HIDE_LIST, CONTROLS_CONTEXT_HELP }; bool MyApp::OnInit() { // use standard command line handling: if ( !wxApp::OnInit() ) return false; // parse the cmd line int x = 50, y = 50; if ( argc == 3 ) { wxSscanf(wxString(argv[1]), wxT("%d"), &x); wxSscanf(wxString(argv[2]), wxT("%d"), &y); } #if wxUSE_HELP wxHelpProvider::Set( new wxSimpleHelpProvider ); #endif // wxUSE_HELP // Create the main frame window MyFrame *frame = new MyFrame(wxT("Controls wxWidgets App"), x, y); frame->Show(true); return true; } //---------------------------------------------------------------------- // MyPanel //---------------------------------------------------------------------- const int ID_BOOK = 1000; const int ID_LISTBOX = 130; const int ID_LISTBOX_SEL_NUM = 131; const int ID_LISTBOX_SEL_STR = 132; const int ID_LISTBOX_CLEAR = 133; const int ID_LISTBOX_APPEND = 134; const int ID_LISTBOX_DELETE = 135; const int ID_LISTBOX_FONT = 136; const int ID_LISTBOX_ENABLE = 137; const int ID_LISTBOX_SORTED = 138; const int ID_CHOICE = 120; const int ID_CHOICE_SEL_NUM = 121; const int ID_CHOICE_SEL_STR = 122; const int ID_CHOICE_CLEAR = 123; const int ID_CHOICE_APPEND = 124; const int ID_CHOICE_DELETE = 125; const int ID_CHOICE_FONT = 126; const int ID_CHOICE_ENABLE = 127; const int ID_CHOICE_SORTED = 128; const int ID_COMBO = 140; const int ID_COMBO_SEL_NUM = 141; const int ID_COMBO_SEL_STR = 142; const int ID_COMBO_CLEAR = 143; const int ID_COMBO_APPEND = 144; const int ID_COMBO_DELETE = 145; const int ID_COMBO_FONT = 146; const int ID_COMBO_ENABLE = 147; const int ID_COMBO_SET_TEXT = 148; const int ID_RADIOBOX = 160; const int ID_RADIOBOX_SEL_NUM = 161; const int ID_RADIOBOX_SEL_STR = 162; const int ID_RADIOBOX_FONT = 163; const int ID_RADIOBOX_ENABLE = 164; const int ID_RADIOBOX2 = 165; const int ID_RADIOBUTTON_1 = 166; const int ID_RADIOBUTTON_2 = 167; const int ID_SET_FONT = 170; #if wxUSE_GAUGE const int ID_GAUGE = 180; #endif // wxUSE_GAUGE #if wxUSE_SLIDER const int ID_SLIDER = 181; #endif // wxUSE_SLIDER const int ID_SPIN = 182; #if wxUSE_PROGRESSDLG const int ID_BTNPROGRESS = 183; #endif // wxUSE_PROGRESSDLG const int ID_BUTTON_LABEL = 184; const int ID_SPINCTRL = 185; const int ID_BTNNEWTEXT = 186; const int ID_BUTTON_TEST1 = 190; const int ID_BUTTON_TEST2 = 191; const int ID_BITMAP_BTN = 192; const int ID_BITMAP_BTN_ENABLE = 193; const int ID_CHANGE_COLOUR = 200; const int ID_SIZER_CHECK1 = 201; const int ID_SIZER_CHECK2 = 202; const int ID_SIZER_CHECK3 = 203; const int ID_SIZER_CHECK4 = 204; const int ID_SIZER_CHECK14 = 205; const int ID_SIZER_CHECKBIG = 206; const int ID_HYPERLINK = 300; BEGIN_EVENT_TABLE(MyPanel, wxPanel) EVT_IDLE ( MyPanel::OnIdle) EVT_BOOKCTRL_PAGE_CHANGING(ID_BOOK, MyPanel::OnPageChanging) EVT_BOOKCTRL_PAGE_CHANGED(ID_BOOK, MyPanel::OnPageChanged) EVT_LISTBOX (ID_LISTBOX, MyPanel::OnListBox) EVT_LISTBOX (ID_LISTBOX_SORTED, MyPanel::OnListBox) EVT_LISTBOX_DCLICK(ID_LISTBOX, MyPanel::OnListBoxDoubleClick) EVT_BUTTON (ID_LISTBOX_SEL_NUM, MyPanel::OnListBoxButtons) EVT_BUTTON (ID_LISTBOX_SEL_STR, MyPanel::OnListBoxButtons) EVT_BUTTON (ID_LISTBOX_CLEAR, MyPanel::OnListBoxButtons) EVT_BUTTON (ID_LISTBOX_APPEND, MyPanel::OnListBoxButtons) EVT_BUTTON (ID_LISTBOX_DELETE, MyPanel::OnListBoxButtons) EVT_BUTTON (ID_LISTBOX_FONT, MyPanel::OnListBoxButtons) EVT_CHECKBOX (ID_LISTBOX_ENABLE, MyPanel::OnListBoxButtons) #if wxUSE_CHOICE EVT_CHOICE (ID_CHOICE, MyPanel::OnChoice) EVT_CHOICE (ID_CHOICE_SORTED, MyPanel::OnChoice) EVT_BUTTON (ID_CHOICE_SEL_NUM, MyPanel::OnChoiceButtons) EVT_BUTTON (ID_CHOICE_SEL_STR, MyPanel::OnChoiceButtons) EVT_BUTTON (ID_CHOICE_CLEAR, MyPanel::OnChoiceButtons) EVT_BUTTON (ID_CHOICE_APPEND, MyPanel::OnChoiceButtons) EVT_BUTTON (ID_CHOICE_DELETE, MyPanel::OnChoiceButtons) EVT_BUTTON (ID_CHOICE_FONT, MyPanel::OnChoiceButtons) EVT_CHECKBOX (ID_CHOICE_ENABLE, MyPanel::OnChoiceButtons) #endif EVT_COMBOBOX (ID_COMBO, MyPanel::OnCombo) EVT_TEXT (ID_COMBO, MyPanel::OnComboTextChanged) EVT_TEXT_ENTER(ID_COMBO, MyPanel::OnComboTextEnter) EVT_BUTTON (ID_COMBO_SEL_NUM, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_SEL_STR, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_CLEAR, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_APPEND, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_DELETE, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_FONT, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_SET_TEXT, MyPanel::OnComboButtons) EVT_CHECKBOX (ID_COMBO_ENABLE, MyPanel::OnComboButtons) EVT_RADIOBOX (ID_RADIOBOX, MyPanel::OnRadio) EVT_RADIOBOX (ID_RADIOBOX2, MyPanel::OnRadio) EVT_BUTTON (ID_RADIOBOX_SEL_NUM, MyPanel::OnRadioButtons) EVT_BUTTON (ID_RADIOBOX_SEL_STR, MyPanel::OnRadioButtons) EVT_BUTTON (ID_RADIOBOX_FONT, MyPanel::OnRadioButtons) EVT_CHECKBOX (ID_RADIOBOX_ENABLE, MyPanel::OnRadioButtons) EVT_RADIOBUTTON(ID_RADIOBUTTON_1, MyPanel::OnRadioButton1) EVT_RADIOBUTTON(ID_RADIOBUTTON_2, MyPanel::OnRadioButton2) EVT_BUTTON (ID_SET_FONT, MyPanel::OnSetFont) #if wxUSE_SLIDER EVT_SLIDER (ID_SLIDER, MyPanel::OnSliderUpdate) #endif // wxUSE_SLIDER #if wxUSE_SPINBTN EVT_SPIN (ID_SPIN, MyPanel::OnSpinUpdate) EVT_SPIN_UP (ID_SPIN, MyPanel::OnSpinUp) EVT_SPIN_DOWN (ID_SPIN, MyPanel::OnSpinDown) #if wxUSE_PROGRESSDLG EVT_UPDATE_UI (ID_BTNPROGRESS, MyPanel::OnUpdateShowProgress) EVT_BUTTON (ID_BTNPROGRESS, MyPanel::OnShowProgress) #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN #if wxUSE_SPINCTRL EVT_SPINCTRL (ID_SPINCTRL, MyPanel::OnSpinCtrl) EVT_SPIN_UP (ID_SPINCTRL, MyPanel::OnSpinCtrlUp) EVT_SPIN_DOWN (ID_SPINCTRL, MyPanel::OnSpinCtrlDown) EVT_TEXT (ID_SPINCTRL, MyPanel::OnSpinCtrlText) #endif // wxUSE_SPINCTRL EVT_BUTTON (ID_BTNNEWTEXT, MyPanel::OnNewText) EVT_TOGGLEBUTTON(ID_BUTTON_LABEL, MyPanel::OnUpdateLabel) EVT_CHECKBOX (ID_CHANGE_COLOUR, MyPanel::OnChangeColour) EVT_BUTTON (ID_BUTTON_TEST1, MyPanel::OnTestButton) EVT_BUTTON (ID_BUTTON_TEST2, MyPanel::OnTestButton) EVT_BUTTON (ID_BITMAP_BTN, MyPanel::OnBmpButton) EVT_TOGGLEBUTTON(ID_BITMAP_BTN_ENABLE, MyPanel::OnBmpButtonToggle) EVT_CHECKBOX (ID_SIZER_CHECK1, MyPanel::OnSizerCheck) EVT_CHECKBOX (ID_SIZER_CHECK2, MyPanel::OnSizerCheck) EVT_CHECKBOX (ID_SIZER_CHECK3, MyPanel::OnSizerCheck) EVT_CHECKBOX (ID_SIZER_CHECK4, MyPanel::OnSizerCheck) EVT_CHECKBOX (ID_SIZER_CHECK14, MyPanel::OnSizerCheck) EVT_CHECKBOX (ID_SIZER_CHECKBIG, MyPanel::OnSizerCheck) END_EVENT_TABLE() BEGIN_EVENT_TABLE(MyButton, wxButton) EVT_LEFT_DCLICK(MyButton::OnDClick) END_EVENT_TABLE() BEGIN_EVENT_TABLE(MyComboBox, wxComboBox) EVT_CHAR(MyComboBox::OnChar) EVT_KEY_DOWN(MyComboBox::OnKeyDown) EVT_KEY_UP(MyComboBox::OnKeyUp) EVT_SET_FOCUS(MyComboBox::OnFocusGot) END_EVENT_TABLE() BEGIN_EVENT_TABLE(MyRadioBox, wxRadioBox) EVT_SET_FOCUS(MyRadioBox::OnFocusGot) EVT_KILL_FOCUS(MyRadioBox::OnFocusLost) END_EVENT_TABLE() BEGIN_EVENT_TABLE(MyChoice, wxChoice) EVT_SET_FOCUS(MyChoice::OnFocusGot) EVT_KILL_FOCUS(MyChoice::OnFocusLost) END_EVENT_TABLE() // ============================================================================ // implementation // ============================================================================ MyPanel::MyPanel( wxFrame *frame, int x, int y, int w, int h ) : wxPanel( frame, wxID_ANY, wxPoint(x, y), wxSize(w, h) ) { m_listbox = NULL; m_listboxSorted = NULL; #if wxUSE_CHOICE m_choice = NULL; m_choiceSorted = NULL; #endif // wxUSE_CHOICE m_combo = NULL; m_radio = NULL; #if wxUSE_GAUGE m_gauge = NULL; m_gaugeVert = NULL; #endif // wxUSE_GAUGE #if wxUSE_SLIDER m_slider = NULL; #endif // wxUSE_SLIDER m_fontButton = NULL; m_lbSelectNum = NULL; m_lbSelectThis = NULL; #if wxUSE_SPINBTN m_spinbutton = NULL; #if wxUSE_PROGRESSDLG m_btnProgress = NULL; #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN #if wxUSE_SPINCTRL m_spinctrl = NULL; #endif // wxUSE_SPINCTRL m_spintext = NULL; m_checkbox = NULL; m_text = NULL; m_book = NULL; m_label = NULL; m_text = new wxTextCtrl(this, wxID_ANY, wxT("This is the log window.\n"), wxPoint(0, 250), wxSize(100, 50), wxTE_MULTILINE); m_logTargetOld = wxLog::SetActiveTarget(new wxLogTextCtrl(m_text)); m_book = new wxBookCtrl(this, ID_BOOK); wxString choices[] = { wxT("This"), wxT("is"), wxT("one of my long and"), wxT("wonderful"), wxT("examples.") }; #ifndef __WXMSW__ // image ids enum { Image_List, Image_Choice, Image_Combo, Image_Text, Image_Radio, #if wxUSE_GAUGE Image_Gauge, #endif // wxUSE_GAUGE Image_Max }; // fill the image list wxBitmap bmp(list_xpm); wxImageList *imagelist = new wxImageList(bmp.GetWidth(), bmp.GetHeight()); imagelist-> Add( bmp ); imagelist-> Add( wxBitmap( choice_xpm )); imagelist-> Add( wxBitmap( combo_xpm )); imagelist-> Add( wxBitmap( text_xpm )); imagelist-> Add( wxBitmap( radio_xpm )); #if wxUSE_GAUGE imagelist-> Add( wxBitmap( gauge_xpm )); #endif // wxUSE_GAUGE m_book->SetImageList(imagelist); #else // load images from resources enum { Image_List, Image_Choice, Image_Combo, Image_Text, Image_Radio, #if wxUSE_GAUGE Image_Gauge, #endif // wxUSE_GAUGE Image_Max }; wxImageList *imagelist = new wxImageList(16, 16, false, Image_Max); static const wxChar *s_iconNames[Image_Max] = { wxT("list") , wxT("choice") , wxT("combo") , wxT("text") , wxT("radio") #if wxUSE_GAUGE , wxT("gauge") #endif // wxUSE_GAUGE }; for ( size_t n = 0; n < Image_Max; n++ ) { wxBitmap bmp(s_iconNames[n]); if ( !bmp.IsOk() || (imagelist->Add(bmp) == -1) ) { wxLogWarning(wxT("Couldn't load the image '%s' for the book control page %d."), s_iconNames[n], n); } } m_book->SetImageList(imagelist); #endif // ------------------------------------------------------------------------ // listbox page // ------------------------------------------------------------------------ wxPanel *panel = new wxPanel(m_book); m_listbox = new wxListBox( panel, ID_LISTBOX, wxPoint(10,10), wxSize(120,70), 5, choices, wxLB_MULTIPLE | wxLB_ALWAYS_SB | wxHSCROLL ); m_listboxSorted = new wxListBox( panel, ID_LISTBOX_SORTED, wxPoint(10,90), wxSize(120,70), 3, choices, wxLB_SORT ); SetListboxClientData(wxT("listbox"), m_listbox); SetListboxClientData(wxT("listbox"), m_listboxSorted); m_listbox->SetCursor(*wxCROSS_CURSOR); m_lbSelectNum = new wxButton( panel, ID_LISTBOX_SEL_NUM, wxT("Select #&2"), wxPoint(180,30), wxSize(140,30) ); m_lbSelectThis = new wxButton( panel, ID_LISTBOX_SEL_STR, wxT("&Select 'This'"), wxPoint(340,30), wxSize(140,30) ); (void)new wxButton( panel, ID_LISTBOX_CLEAR, wxT("&Clear"), wxPoint(180,80), wxSize(140,30) ); (void)new MyButton( panel, ID_LISTBOX_APPEND, wxT("&Append 'Hi!'"), wxPoint(340,80), wxSize(140,30) ); (void)new wxButton( panel, ID_LISTBOX_DELETE, wxT("D&elete selected item"), wxPoint(180,130), wxSize(140,30) ); wxButton *button = new MyButton( panel, ID_LISTBOX_FONT, wxT("Set &Italic font"), wxPoint(340,130), wxSize(140,30) ); button->SetDefault(); m_checkbox = new wxCheckBox( panel, ID_LISTBOX_ENABLE, wxT("&Disable"), wxPoint(20,170) ); m_checkbox->SetValue(false); button->MoveAfterInTabOrder(m_checkbox); (void)new wxCheckBox( panel, ID_CHANGE_COLOUR, wxT("&Toggle colour"), wxPoint(110,170) ); panel->SetCursor(wxCursor(wxCURSOR_HAND)); m_book->AddPage(panel, wxT("wxListBox"), true, Image_List); // ------------------------------------------------------------------------ // choice page // ------------------------------------------------------------------------ #if wxUSE_CHOICE panel = new wxPanel(m_book); m_choice = new MyChoice( panel, ID_CHOICE, wxPoint(10,10), wxSize(120,wxDefaultCoord), 5, choices ); m_choiceSorted = new MyChoice( panel, ID_CHOICE_SORTED, wxPoint(10,70), wxSize(120,wxDefaultCoord), 5, choices, wxCB_SORT ); SetChoiceClientData(wxT("choice"), m_choice); SetChoiceClientData(wxT("choice"), m_choiceSorted); m_choice->SetSelection(2); (void)new wxButton( panel, ID_CHOICE_SEL_NUM, wxT("Select #&2"), wxPoint(180,30), wxSize(140,30) ); (void)new wxButton( panel, ID_CHOICE_SEL_STR, wxT("&Select 'This'"), wxPoint(340,30), wxSize(140,30) ); (void)new wxButton( panel, ID_CHOICE_CLEAR, wxT("&Clear"), wxPoint(180,80), wxSize(140,30) ); (void)new wxButton( panel, ID_CHOICE_APPEND, wxT("&Append 'Hi!'"), wxPoint(340,80), wxSize(140,30) ); (void)new wxButton( panel, ID_CHOICE_DELETE, wxT("D&elete selected item"), wxPoint(180,130), wxSize(140,30) ); (void)new wxButton( panel, ID_CHOICE_FONT, wxT("Set &Italic font"), wxPoint(340,130), wxSize(140,30) ); (void)new wxCheckBox( panel, ID_CHOICE_ENABLE, wxT("&Disable"), wxPoint(20,130), wxSize(140,30) ); m_book->AddPage(panel, wxT("wxChoice"), false, Image_Choice); #endif // wxUSE_CHOICE // ------------------------------------------------------------------------ // combo page // ------------------------------------------------------------------------ panel = new wxPanel(m_book); (void)new wxStaticBox( panel, wxID_ANY, wxT("&Box around combobox"), wxPoint(5, 5), wxSize(150, 100)); m_combo = new MyComboBox( panel, ID_COMBO, wxT("This"), wxPoint(20,25), wxSize(120, wxDefaultCoord), 5, choices, wxTE_PROCESS_ENTER); (void)new wxButton( panel, ID_COMBO_SEL_NUM, wxT("Select #&2"), wxPoint(180,30), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_SEL_STR, wxT("&Select 'This'"), wxPoint(340,30), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_CLEAR, wxT("&Clear"), wxPoint(180,80), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_APPEND, wxT("&Append 'Hi!'"), wxPoint(340,80), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_DELETE, wxT("D&elete selected item"), wxPoint(180,130), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_FONT, wxT("Set &Italic font"), wxPoint(340,130), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_SET_TEXT, wxT("Set 'Hi!' at #2"), wxPoint(340,180), wxSize(140,30) ); (void)new wxCheckBox( panel, ID_COMBO_ENABLE, wxT("&Disable"), wxPoint(20,130), wxSize(140,30) ); m_book->AddPage(panel, wxT("wxComboBox"), false, Image_Combo); // ------------------------------------------------------------------------ // radio box // ------------------------------------------------------------------------ wxString choices2[] = { wxT("First"), wxT("Second"), /* "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Nineth", "Tenth" */ }; panel = new wxPanel(m_book); wxGridBagSizer* radio_page_sizer = new wxGridBagSizer(5, 5); m_radio = new wxRadioBox(panel, ID_RADIOBOX, wxT("T&his"), wxPoint(10,10), wxDefaultSize, WXSIZEOF(choices), choices, 1, wxRA_SPECIFY_COLS ); MyRadioBox* mybox = new MyRadioBox(panel, ID_RADIOBOX2, wxT("&That"), wxPoint(10,160), wxDefaultSize, WXSIZEOF(choices2), choices2, 1, wxRA_SPECIFY_ROWS ); radio_page_sizer->Add( m_radio, wxGBPosition(0,0), wxGBSpan(2,1) ); radio_page_sizer->Add( mybox, wxGBPosition(2,0), wxGBSpan(2,1) ); #if wxUSE_HELP for (unsigned int item = 0; item < WXSIZEOF(choices); ++item) m_radio->SetItemHelpText( item, wxString::Format( wxT("Help text for \"%s\""), choices[item].c_str() ) ); // erase help text for the second item m_radio->SetItemHelpText( 1, wxT("") ); // set default help text for control m_radio->SetHelpText( wxT("Default helptext for wxRadioBox") ); #endif // wxUSE_HELP wxButton* select_two = new wxButton ( panel, ID_RADIOBOX_SEL_NUM, wxT("Select #&2") ); wxButton* select_this = new wxButton ( panel, ID_RADIOBOX_SEL_STR, wxT("&Select 'This'") ); m_fontButton = new wxButton ( panel, ID_SET_FONT, wxT("Set &more Italic font") ); wxButton* set_italic = new wxButton ( panel, ID_RADIOBOX_FONT, wxT("Set &Italic font") ); wxCheckBox* disable_cb = new wxCheckBox( panel, ID_RADIOBOX_ENABLE, wxT("&Disable") ); wxRadioButton *rb = new wxRadioButton( panel, ID_RADIOBUTTON_1, wxT("Radiobutton1"), wxDefaultPosition, wxDefaultSize, wxRB_GROUP ); wxRadioButton *rb2 = new wxRadioButton( panel, ID_RADIOBUTTON_2, wxT("&Radiobutton2"), wxDefaultPosition, wxDefaultSize ); rb->SetValue( false ); radio_page_sizer->Add( select_two, wxGBPosition(0, 1), wxDefaultSpan, wxALL , 10 ); radio_page_sizer->Add( select_this, wxGBPosition(1, 1), wxDefaultSpan, wxALL , 10 ); radio_page_sizer->Add( m_fontButton, wxGBPosition(0, 2), wxDefaultSpan, wxALL , 10 ); radio_page_sizer->Add( set_italic, wxGBPosition(1, 2), wxDefaultSpan, wxALL , 10 ); radio_page_sizer->Add( disable_cb, wxGBPosition(2, 2), wxDefaultSpan, wxLEFT | wxRIGHT, 10 ); radio_page_sizer->Add( rb, wxGBPosition(3, 1), wxDefaultSpan, wxLEFT | wxRIGHT, 10 ); radio_page_sizer->Add( rb2, wxGBPosition(3, 2), wxDefaultSpan, wxLEFT | wxRIGHT, 10 ); panel->SetSizer( radio_page_sizer ); m_book->AddPage(panel, wxT("wxRadioBox"), false, Image_Radio); // ------------------------------------------------------------------------ // gauge and slider // ------------------------------------------------------------------------ #if wxUSE_SLIDER && wxUSE_GAUGE panel = new wxPanel(m_book); wxBoxSizer *gauge_page_vsizer = new wxBoxSizer( wxVERTICAL ); wxBoxSizer *gauge_page_first_row_sizer = new wxBoxSizer( wxHORIZONTAL ); wxStaticBoxSizer *gauge_sizer = new wxStaticBoxSizer( wxHORIZONTAL, panel, wxT("&wxGauge and wxSlider") ); gauge_page_first_row_sizer->Add( gauge_sizer, 0, wxALL, 5 ); wxBoxSizer *sz = new wxBoxSizer( wxVERTICAL ); gauge_sizer->Add( sz ); m_gauge = new wxGauge( panel, wxID_ANY, 200, wxDefaultPosition, wxSize(155, 30), wxGA_HORIZONTAL|wxNO_BORDER ); sz->Add( m_gauge, 0, wxALL, 10 ); m_slider = new wxSlider( panel, ID_SLIDER, 0, 0, 200, wxDefaultPosition, wxSize(155,wxDefaultCoord), wxSL_AUTOTICKS | wxSL_LABELS); m_slider->SetTickFreq(40); sz->Add( m_slider, 0, wxALL, 10 ); m_gaugeVert = new wxGauge( panel, wxID_ANY, 100, wxDefaultPosition, wxSize(wxDefaultCoord, 90), wxGA_VERTICAL | wxGA_SMOOTH | wxNO_BORDER ); gauge_sizer->Add( m_gaugeVert, 0, wxALL, 10 ); wxStaticBox *sb = new wxStaticBox( panel, wxID_ANY, wxT("&Explanation"), wxDefaultPosition, wxDefaultSize ); //, wxALIGN_CENTER ); wxStaticBoxSizer *wrapping_sizer = new wxStaticBoxSizer( sb, wxVERTICAL ); gauge_page_first_row_sizer->Add( wrapping_sizer, 0, wxALL, 5 ); #ifdef __WXMOTIF__ // No wrapping text in wxStaticText yet :-( m_wrappingText = new wxStaticText( panel, wxID_ANY, wxT("Drag the slider!"), wxPoint(250,30), wxSize(240, wxDefaultCoord) ); #else m_wrappingText = new wxStaticText( panel, wxID_ANY, wxT("In order see the gauge (aka progress bar) ") wxT("control do something you have to drag the ") wxT("handle of the slider to the right.") wxT("\n\n") wxT("This is also supposed to demonstrate how ") wxT("to use static controls with line wrapping."), wxDefaultPosition, wxSize(240, wxDefaultCoord) ); #endif wrapping_sizer->Add( m_wrappingText ); wxStaticBoxSizer *non_wrapping_sizer = new wxStaticBoxSizer( wxVERTICAL, panel, wxT("Non-wrapping") ); gauge_page_first_row_sizer->Add( non_wrapping_sizer, 0, wxALL, 5 ); m_nonWrappingText = new wxStaticText( panel, wxID_ANY, wxT("This static text has two lines.\nThey do not wrap."), wxDefaultPosition, wxDefaultSize ); non_wrapping_sizer->Add( m_nonWrappingText ); gauge_page_vsizer->Add( gauge_page_first_row_sizer, 1 ); wxBoxSizer *gauge_page_second_row_sizer = new wxBoxSizer( wxHORIZONTAL ); int initialSpinValue = -5; wxString s; s << initialSpinValue; m_spintext = new wxTextCtrl( panel, wxID_ANY, s ); gauge_page_second_row_sizer->Add( m_spintext, 0, wxALL, 5 ); #if wxUSE_SPINBTN m_spinbutton = new wxSpinButton( panel, ID_SPIN ); m_spinbutton->SetRange(-40,30); m_spinbutton->SetValue(initialSpinValue); gauge_page_second_row_sizer->Add( m_spinbutton, 0, wxALL, 5 ); #endif // wxUSE_SPINBTN #if wxUSE_SPINCTRL m_spinctrl = new wxSpinCtrl( panel, ID_SPINCTRL, wxEmptyString ); m_spinctrl->SetRange(-10,30); m_spinctrl->SetValue(15); gauge_page_second_row_sizer->Add( m_spinctrl, 0, wxALL, 5 ); #endif // wxUSE_SPINCTRL #if wxUSE_SPINBTN #if wxUSE_PROGRESSDLG m_btnProgress = new wxButton( panel, ID_BTNPROGRESS, wxT("&Show progress dialog") ); gauge_page_second_row_sizer->Add( m_btnProgress, 0, wxALL, 5 ); #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN wxButton* newTextButton = new wxButton( panel, ID_BTNNEWTEXT, wxT("New text")); gauge_page_second_row_sizer->Add( newTextButton, 0, wxALL, 5 ); gauge_page_vsizer->Add(gauge_page_second_row_sizer, 1); panel->SetSizer( gauge_page_vsizer ); m_book->AddPage(panel, wxT("wxGauge"), false, Image_Gauge); #endif // wxUSE_SLIDER && wxUSE_GAUGE // ------------------------------------------------------------------------ // wxBitmapXXX // ------------------------------------------------------------------------ panel = new wxPanel(m_book); #if !defined(__WXMOTIF__) // wxStaticBitmap not working under Motif yet. wxIcon icon = wxArtProvider::GetIcon(wxART_INFORMATION); (void) new wxStaticBitmap( panel, wxID_ANY, icon, wxPoint(10, 10) ); // VZ: don't leak memory // bmpStatic = new wxStaticBitmap(panel, wxID_ANY, wxNullIcon, wxPoint(50, 10)); // bmpStatic->SetIcon(wxArtProvider::GetIcon(wxART_QUESTION)); #endif // !Motif wxBitmap bitmap( 100, 100 ); wxMemoryDC dc; dc.SelectObject( bitmap ); dc.SetBackground(*wxGREEN); dc.SetPen(*wxRED_PEN); dc.Clear(); dc.DrawEllipse(5, 5, 90, 90); dc.DrawText(wxT("Bitmap"), 30, 40); dc.SelectObject( wxNullBitmap ); wxPanel *panel2 = new wxPanel(panel, -1, wxPoint(100, 0), wxSize(100, 200)); (void)new wxBitmapButton(panel2, ID_BITMAP_BTN, bitmap, wxPoint(0, 20)); (void)new wxToggleButton(panel2, ID_BITMAP_BTN_ENABLE, wxT("Enable/disable &bitmap"), wxPoint(0, 140)); #if defined(__WXMSW__) || defined(__WXMOTIF__) // test for masked bitmap display bitmap = wxBitmap(wxT("test2.bmp"), wxBITMAP_TYPE_BMP); if (bitmap.IsOk()) { bitmap.SetMask(new wxMask(bitmap, *wxBLUE)); (void)new wxStaticBitmap(panel, wxID_ANY, bitmap, wxPoint(300, 120)); } #endif wxBitmap bmp1(wxArtProvider::GetBitmap(wxART_INFORMATION)), bmp2(wxArtProvider::GetBitmap(wxART_WARNING)), bmp3(wxArtProvider::GetBitmap(wxART_QUESTION)); wxBitmapButton *bmpBtn = new wxBitmapButton ( panel, wxID_ANY, bmp1, wxPoint(30, 70) ); bmpBtn->SetBitmapSelected(bmp2); bmpBtn->SetBitmapFocus(bmp3); (void)new wxToggleButton(panel, ID_BUTTON_LABEL, wxT("&Toggle label"), wxPoint(250, 20)); m_label = new wxStaticText(panel, wxID_ANY, wxT("Label with some long text"), wxPoint(250, 60), wxDefaultSize, wxALIGN_RIGHT /*| wxST_NO_AUTORESIZE*/); m_label->SetForegroundColour( *wxBLUE ); m_book->AddPage(panel, wxT("wxBitmapXXX")); // ------------------------------------------------------------------------ // sizer page // ------------------------------------------------------------------------ panel = new wxPanel(m_book); wxBoxSizer *sizer = new wxBoxSizer( wxVERTICAL ); wxStaticBoxSizer *csizer = new wxStaticBoxSizer (new wxStaticBox (panel, wxID_ANY, wxT("Show Buttons")), wxHORIZONTAL ); wxCheckBox *check1, *check2, *check3, *check4, *check14, *checkBig; check1 = new wxCheckBox (panel, ID_SIZER_CHECK1, wxT("1")); check1->SetValue (true); csizer->Add (check1); check2 = new wxCheckBox (panel, ID_SIZER_CHECK2, wxT("2")); check2->SetValue (true); csizer->Add (check2); check3 = new wxCheckBox (panel, ID_SIZER_CHECK3, wxT("3")); check3->SetValue (true); csizer->Add (check3); check4 = new wxCheckBox (panel, ID_SIZER_CHECK4, wxT("4")); check4->SetValue (true); csizer->Add (check4); check14 = new wxCheckBox (panel, ID_SIZER_CHECK14, wxT("1-4")); check14->SetValue (true); csizer->Add (check14); checkBig = new wxCheckBox (panel, ID_SIZER_CHECKBIG, wxT("Big")); checkBig->SetValue (true); csizer->Add (checkBig); sizer->Add (csizer); m_hsizer = new wxBoxSizer( wxHORIZONTAL ); m_buttonSizer = new wxBoxSizer (wxVERTICAL); m_sizerBtn1 = new wxButton(panel, wxID_ANY, wxT("Test Button &1 (tab order 1)") ); m_buttonSizer->Add( m_sizerBtn1, 0, wxALL, 10 ); m_sizerBtn2 = new wxButton(panel, wxID_ANY, wxT("Test Button &2 (tab order 3)") ); m_buttonSizer->Add( m_sizerBtn2, 0, wxALL, 10 ); m_sizerBtn3 = new wxButton(panel, wxID_ANY, wxT("Test Button &3 (tab order 2)") ); m_buttonSizer->Add( m_sizerBtn3, 0, wxALL, 10 ); m_sizerBtn4 = new wxButton(panel, wxID_ANY, wxT("Test Button &4 (tab order 4)") ); m_buttonSizer->Add( m_sizerBtn4, 0, wxALL, 10 ); m_sizerBtn3->MoveBeforeInTabOrder(m_sizerBtn2); m_hsizer->Add (m_buttonSizer); m_hsizer->Add( 20,20, 1 ); m_bigBtn = new wxButton(panel, wxID_ANY, wxT("Multiline\nbutton") ); m_hsizer->Add( m_bigBtn , 3, wxGROW|wxALL, 10 ); sizer->Add (m_hsizer, 1, wxGROW); panel->SetSizer( sizer ); m_book->AddPage(panel, wxT("wxSizer")); // set the sizer for the panel itself sizer = new wxBoxSizer(wxVERTICAL); sizer->Add(m_book, wxSizerFlags().Border().Expand()); sizer->Add(m_text, wxSizerFlags(1).Border().Expand()); SetSizer(sizer); #if wxUSE_TOOLTIPS SetAllToolTips(); #endif // wxUSE_TOOLTIPS } #if wxUSE_TOOLTIPS namespace { void ResetToolTip(wxWindow *win, const char *tip) { wxCHECK_RET( win, "NULL window?" ); win->UnsetToolTip(); win->SetToolTip(tip); } } void MyPanel::SetAllToolTips() { ResetToolTip(FindWindow(ID_LISTBOX_FONT), "Press here to set italic font"); ResetToolTip(m_checkbox, "Click here to disable the listbox"); ResetToolTip(m_listbox, "This is a list box"); ResetToolTip(m_combo, "This is a natural\ncombobox - can you believe me?"); ResetToolTip(m_slider, "This is a sliding slider"); ResetToolTip(FindWindow(ID_RADIOBOX2), "Ever seen a radiobox?"); //ResetToolTip(m_radio, "Tooltip for the entire radiobox"); for ( unsigned int nb = 0; nb < m_radio->GetCount(); nb++ ) { m_radio->SetItemToolTip(nb, ""); m_radio->SetItemToolTip(nb, "tooltip for\n" + m_radio->GetString(nb)); } // remove the tooltip for one of the items m_radio->SetItemToolTip(2, ""); } #endif // wxUSE_TOOLTIPS void MyPanel::OnIdle(wxIdleEvent& event) { static const int INVALID_SELECTION = -2; static int s_selCombo = INVALID_SELECTION; if (!m_combo || !m_choice) { event.Skip(); return; } int sel = m_combo->GetSelection(); if ( sel != s_selCombo ) { if ( s_selCombo != INVALID_SELECTION ) { wxLogMessage(wxT("EVT_IDLE: combobox selection changed from %d to %d"), s_selCombo, sel); } s_selCombo = sel; } static int s_selChoice = INVALID_SELECTION; sel = m_choice->GetSelection(); if ( sel != s_selChoice ) { if ( s_selChoice != INVALID_SELECTION ) { wxLogMessage(wxT("EVT_IDLE: choice selection changed from %d to %d"), s_selChoice, sel); } s_selChoice = sel; } event.Skip(); } void MyPanel::OnPageChanging( wxBookCtrlEvent &event ) { int selOld = event.GetOldSelection(); if ( selOld == 2 ) { if ( wxMessageBox(wxT("This demonstrates how a program may prevent the\n") wxT("page change from taking place - if you select\n") wxT("[No] the current page will stay the third one\n"), wxT("Control sample"), wxICON_QUESTION | wxYES_NO, this) != wxYES ) { event.Veto(); return; } } *m_text << wxT("Book selection is being changed from ") << selOld << wxT(" to ") << event.GetSelection() << wxT(" (current page from book is ") << m_book->GetSelection() << wxT(")\n"); } void MyPanel::OnPageChanged( wxBookCtrlEvent &event ) { *m_text << wxT("Book selection is now ") << event.GetSelection() << wxT(" (from book: ") << m_book->GetSelection() << wxT(")\n"); } void MyPanel::OnTestButton(wxCommandEvent& event) { wxLogMessage(wxT("Button %c clicked."), event.GetId() == ID_BUTTON_TEST1 ? wxT('1') : wxT('2')); } void MyPanel::OnBmpButton(wxCommandEvent& WXUNUSED(event)) { wxLogMessage(wxT("Bitmap button clicked.")); } void MyPanel::OnBmpButtonToggle(wxCommandEvent& event) { FindWindow(ID_BITMAP_BTN)->Enable(!event.IsChecked()); } void MyPanel::OnChangeColour(wxCommandEvent& WXUNUSED(event)) { static wxColour s_colOld; SetThemeEnabled(false); // test panel colour changing and propagation to the subcontrols if ( s_colOld.IsOk() ) { SetBackgroundColour(s_colOld); s_colOld = wxNullColour; m_lbSelectThis->SetForegroundColour(wxNullColour); m_lbSelectThis->SetBackgroundColour(wxNullColour); } else { s_colOld = wxColour(wxT("red")); SetBackgroundColour(wxT("white")); m_lbSelectThis->SetForegroundColour(wxT("white")); m_lbSelectThis->SetBackgroundColour(wxT("red")); } m_lbSelectThis->Refresh(); Refresh(); } void MyPanel::OnListBox( wxCommandEvent &event ) { wxListBox *listbox = event.GetId() == ID_LISTBOX ? m_listbox : m_listboxSorted; bool deselect = false; if (listbox->HasFlag(wxLB_MULTIPLE) || listbox->HasFlag(wxLB_EXTENDED)) { deselect = !event.IsSelection(); if (deselect) m_text->AppendText( wxT("ListBox deselection event\n") ); } m_text->AppendText( wxT("ListBox event selection string is: '") ); m_text->AppendText( event.GetString() ); m_text->AppendText( wxT("'\n") ); // can't use GetStringSelection() with multiple selections, there could be // more than one of them if ( !listbox->HasFlag(wxLB_MULTIPLE) && !listbox->HasFlag(wxLB_EXTENDED) ) { m_text->AppendText( wxT("ListBox control selection string is: '") ); m_text->AppendText( listbox->GetStringSelection() ); m_text->AppendText( wxT("'\n") ); } wxStringClientData *obj = ((wxStringClientData *)event.GetClientObject()); m_text->AppendText( wxT("ListBox event client data string is: '") ); if (obj) // BC++ doesn't like use of '? .. : .. ' in this context m_text->AppendText( obj->GetData() ); else m_text->AppendText( wxString(wxT("none")) ); m_text->AppendText( wxT("'\n") ); m_text->AppendText( wxT("ListBox control client data string is: '") ); obj = (wxStringClientData *)listbox->GetClientObject(event.GetInt()); if (obj) m_text->AppendText( obj->GetData() ); else m_text->AppendText( wxString(wxT("none")) ); m_text->AppendText( wxT("'\n") ); } void MyPanel::OnListBoxDoubleClick( wxCommandEvent &event ) { m_text->AppendText( wxT("ListBox double click string is: ") ); m_text->AppendText( event.GetString() ); m_text->AppendText( wxT("\n") ); } void MyPanel::OnListBoxButtons( wxCommandEvent &event ) { switch (event.GetId()) { case ID_LISTBOX_ENABLE: { m_text->AppendText(wxT("Checkbox clicked.\n")); #if wxUSE_TOOLTIPS wxCheckBox *cb = (wxCheckBox*)event.GetEventObject(); if (event.GetInt()) cb->SetToolTip( wxT("Click to enable listbox") ); else cb->SetToolTip( wxT("Click to disable listbox") ); #endif // wxUSE_TOOLTIPS m_listbox->Enable( event.GetInt() == 0 ); m_lbSelectThis->Enable( event.GetInt() == 0 ); m_lbSelectNum->Enable( event.GetInt() == 0 ); m_listboxSorted->Enable( event.GetInt() == 0 ); FindWindow(ID_CHANGE_COLOUR)->Enable( event.GetInt() == 0 ); break; } case ID_LISTBOX_SEL_NUM: { if (m_listbox->GetCount() > 2) m_listbox->SetSelection( 2 ); if (m_listboxSorted->GetCount() > 2) m_listboxSorted->SetSelection( 2 ); m_lbSelectThis->WarpPointer( 40, 14 ); break; } case ID_LISTBOX_SEL_STR: { if (m_listbox->FindString(wxT("This")) != wxNOT_FOUND) m_listbox->SetStringSelection( wxT("This") ); if (m_listboxSorted->FindString(wxT("This")) != wxNOT_FOUND) m_listboxSorted->SetStringSelection( wxT("This") ); m_lbSelectNum->WarpPointer( 40, 14 ); break; } case ID_LISTBOX_CLEAR: { m_listbox->Clear(); m_listboxSorted->Clear(); break; } case ID_LISTBOX_APPEND: { m_listbox->Append( wxT("Hi kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk!") ); m_listboxSorted->Append( wxT("Hi hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh!") ); break; } case ID_LISTBOX_DELETE: { int idx; idx = m_listbox->GetSelection(); if ( idx != wxNOT_FOUND ) m_listbox->Delete( idx ); idx = m_listboxSorted->GetSelection(); if ( idx != wxNOT_FOUND ) m_listboxSorted->Delete( idx ); break; } case ID_LISTBOX_FONT: { m_listbox->SetFont( *wxITALIC_FONT ); m_listboxSorted->SetFont( *wxITALIC_FONT ); m_checkbox->SetFont( *wxITALIC_FONT ); break; } } } #if wxUSE_CHOICE static wxString GetDataString(wxClientData *data) { return data ? static_cast<wxStringClientData *>(data)->GetData() : wxString("none"); } void MyPanel::OnChoice( wxCommandEvent &event ) { wxChoice *choice = event.GetId() == ID_CHOICE ? m_choice : m_choiceSorted; const int sel = choice->GetSelection(); wxClientData *dataEvt = event.GetClientObject(), *dataCtrl = choice->GetClientObject(sel); wxLogMessage(wxT("EVT_CHOICE: item %d/%d (event/control), ") wxT("string \"%s\"/\"%s\", ") wxT("data \"%s\"/\"%s\""), (int)event.GetInt(), sel, event.GetString(), choice->GetStringSelection(), GetDataString(dataEvt), GetDataString(dataCtrl)); } void MyPanel::OnChoiceButtons( wxCommandEvent &event ) { switch (event.GetId()) { case ID_CHOICE_ENABLE: { m_choice->Enable( event.GetInt() == 0 ); m_choiceSorted->Enable( event.GetInt() == 0 ); break; } case ID_CHOICE_SEL_NUM: { m_choice->SetSelection( 2 ); m_choiceSorted->SetSelection( 2 ); break; } case ID_CHOICE_SEL_STR: { m_choice->SetStringSelection( wxT("This") ); m_choiceSorted->SetStringSelection( wxT("This") ); break; } case ID_CHOICE_CLEAR: { m_choice->Clear(); m_choiceSorted->Clear(); break; } case ID_CHOICE_APPEND: { m_choice->Append( wxT("Hi!") ); m_choiceSorted->Append( wxT("Hi!") ); break; } case ID_CHOICE_DELETE: { int idx = m_choice->GetSelection(); if ( idx != wxNOT_FOUND ) m_choice->Delete( idx ); idx = m_choiceSorted->GetSelection(); if ( idx != wxNOT_FOUND ) m_choiceSorted->Delete( idx ); break; } case ID_CHOICE_FONT: { m_choice->SetFont( *wxITALIC_FONT ); m_choiceSorted->SetFont( *wxITALIC_FONT ); break; } } } #endif // wxUSE_CHOICE void MyPanel::OnCombo( wxCommandEvent &event ) { if (!m_combo) return; wxLogMessage(wxT("EVT_COMBOBOX: item %d/%d (event/control), string \"%s\"/\"%s\""), (int)event.GetInt(), m_combo->GetSelection(), event.GetString().c_str(), m_combo->GetStringSelection().c_str()); } void MyPanel::OnComboTextChanged(wxCommandEvent& event) { if (m_combo) { wxLogMessage(wxT("EVT_TEXT for the combobox: \"%s\" (event) or \"%s\" (control)."), event.GetString().c_str(), m_combo->GetValue().c_str()); } } void MyPanel::OnComboTextEnter(wxCommandEvent& WXUNUSED(event)) { if (m_combo) { wxLogMessage(wxT("Enter pressed in the combobox: value is '%s'."), m_combo->GetValue().c_str()); } } void MyPanel::OnComboButtons( wxCommandEvent &event ) { switch (event.GetId()) { case ID_COMBO_ENABLE: { m_combo->Enable( event.GetInt() == 0 ); break; } case ID_COMBO_SEL_NUM: { m_combo->SetSelection( 2 ); break; } case ID_COMBO_SEL_STR: { m_combo->SetStringSelection( wxT("This") ); break; } case ID_COMBO_CLEAR: { m_combo->Clear(); break; } case ID_COMBO_APPEND: { m_combo->Append( wxT("Hi!") ); break; } case ID_COMBO_DELETE: { int idx = m_combo->GetSelection(); m_combo->Delete( idx ); break; } case ID_COMBO_FONT: { m_combo->SetFont( *wxITALIC_FONT ); break; } case ID_COMBO_SET_TEXT: { m_combo->SetString( 2, wxT("Hi!") ); break; } } } void MyPanel::OnRadio( wxCommandEvent &event ) { m_text->AppendText( wxT("RadioBox selection string is: ") ); m_text->AppendText( event.GetString() ); m_text->AppendText( wxT("\n") ); } void MyPanel::OnRadioButton1( wxCommandEvent & WXUNUSED(event) ) { wxMessageBox(wxT("First wxRadioButton selected."), wxT("wxControl sample")); } void MyPanel::OnRadioButton2( wxCommandEvent & WXUNUSED(event) ) { m_text->AppendText(wxT("Second wxRadioButton selected.\n")); } void MyPanel::OnRadioButtons( wxCommandEvent &event ) { switch (event.GetId()) { case ID_RADIOBOX_ENABLE: m_radio->Enable( event.GetInt() == 0 ); break; case ID_RADIOBOX_SEL_NUM: m_radio->SetSelection( 2 ); break; case ID_RADIOBOX_SEL_STR: m_radio->SetStringSelection( wxT("This") ); break; case ID_RADIOBOX_FONT: m_radio->SetFont( *wxITALIC_FONT ); break; } } void MyPanel::OnSetFont( wxCommandEvent &WXUNUSED(event) ) { m_fontButton->SetFont( *wxITALIC_FONT ); m_text->SetFont( *wxITALIC_FONT ); } void MyPanel::OnUpdateLabel( wxCommandEvent &event ) { m_label->SetLabel(event.GetInt() ? wxT("Very very very very very long text.") : wxT("Shorter text.")); } #if wxUSE_SLIDER void MyPanel::OnSliderUpdate( wxCommandEvent &WXUNUSED(event) ) { #if wxUSE_GAUGE m_gauge->SetValue( m_slider->GetValue() ); m_gaugeVert->SetValue( m_slider->GetValue() / 2 ); #endif // wxUSE_GAUGE } #endif // wxUSE_SLIDER #if wxUSE_SPINCTRL void MyPanel::OnSpinCtrlText(wxCommandEvent& event) { if ( m_spinctrl ) { wxString s; s.Printf( wxT("Spin ctrl text changed: now %d (from event: %s)\n"), m_spinctrl->GetValue(), event.GetString().c_str() ); m_text->AppendText(s); } } void MyPanel::OnSpinCtrl(wxSpinEvent& event) { if ( m_spinctrl ) { wxString s; s.Printf( wxT("Spin ctrl changed: now %d (from event: %d)\n"), m_spinctrl->GetValue(), event.GetInt() ); m_text->AppendText(s); } } void MyPanel::OnSpinCtrlUp(wxSpinEvent& event) { if ( m_spinctrl ) { m_text->AppendText( wxString::Format( wxT("Spin up: %d (from event: %d)\n"), m_spinctrl->GetValue(), event.GetInt() ) ); } } void MyPanel::OnSpinCtrlDown(wxSpinEvent& event) { if ( m_spinctrl ) { m_text->AppendText( wxString::Format( wxT("Spin down: %d (from event: %d)\n"), m_spinctrl->GetValue(), event.GetInt() ) ); } } #endif // wxUSE_SPINCTRL #if wxUSE_SPINBTN void MyPanel::OnSpinUp( wxSpinEvent &event ) { wxString value; value.Printf( wxT("Spin control up: current = %d\n"), m_spinbutton->GetValue()); if ( event.GetPosition() > 17 ) { value += wxT("Preventing the spin button from going above 17.\n"); event.Veto(); } m_text->AppendText(value); } void MyPanel::OnSpinDown( wxSpinEvent &event ) { wxString value; value.Printf( wxT("Spin control down: current = %d\n"), m_spinbutton->GetValue()); if ( event.GetPosition() < -17 ) { value += wxT("Preventing the spin button from going below -17.\n"); event.Veto(); } m_text->AppendText(value); } void MyPanel::OnSpinUpdate( wxSpinEvent &event ) { wxString value; value.Printf( wxT("%d"), event.GetPosition() ); m_spintext->SetValue( value ); value.Printf( wxT("Spin control range: (%d, %d), current = %d\n"), m_spinbutton->GetMin(), m_spinbutton->GetMax(), m_spinbutton->GetValue()); m_text->AppendText(value); } void MyPanel::OnNewText( wxCommandEvent& /* event */) { m_nonWrappingText->SetLabel( wxT("This text is short\nbut still spans\nover three lines.") ); m_wrappingText->SetLabel( wxT("This text is short but will still be wrapped if it is too long.") ); m_wrappingText->GetParent()->Layout(); } #if wxUSE_PROGRESSDLG void MyPanel::OnUpdateShowProgress( wxUpdateUIEvent& event ) { event.Enable( m_spinbutton->GetValue() > 0 ); } void MyPanel::OnShowProgress( wxCommandEvent& WXUNUSED(event) ) { int max = m_spinbutton->GetValue(); if ( max <= 0 ) { wxLogError(wxT("You must set positive range!")); return; } wxProgressDialog dialog(wxT("Progress dialog example"), wxT("An informative message"), max, // range this, // parent wxPD_CAN_ABORT | wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME); bool cont = true; for ( int i = 0; i <= max && cont; i++ ) { wxSleep(1); if ( i == max ) { cont = dialog.Update(i, wxT("That's all, folks!")); } else if ( i == max / 2 ) { cont = dialog.Update(i, wxT("Only a half left (very long message)!")); } else { cont = dialog.Update(i); } } if ( !cont ) { *m_text << wxT("Progress dialog aborted!\n"); } else { *m_text << wxT("Countdown from ") << max << wxT(" finished.\n"); } } #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN void MyPanel::OnSizerCheck( wxCommandEvent &event) { switch (event.GetId ()) { case ID_SIZER_CHECK1: m_buttonSizer->Show (m_sizerBtn1, event.IsChecked ()); m_buttonSizer->Layout (); break; case ID_SIZER_CHECK2: m_buttonSizer->Show (m_sizerBtn2, event.IsChecked ()); m_buttonSizer->Layout (); break; case ID_SIZER_CHECK3: m_buttonSizer->Show (m_sizerBtn3, event.IsChecked ()); m_buttonSizer->Layout (); break; case ID_SIZER_CHECK4: m_buttonSizer->Show (m_sizerBtn4, event.IsChecked ()); m_buttonSizer->Layout (); break; case ID_SIZER_CHECK14: m_hsizer->Show (m_buttonSizer, event.IsChecked ()); m_hsizer->Layout (); break; case ID_SIZER_CHECKBIG: m_hsizer->Show (m_bigBtn, event.IsChecked ()); m_hsizer->Layout (); break; } } MyPanel::~MyPanel() { //wxLog::RemoveTraceMask(wxT("focus")); delete wxLog::SetActiveTarget(m_logTargetOld); delete m_book->GetImageList(); } //---------------------------------------------------------------------- // MyFrame //---------------------------------------------------------------------- BEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU(CONTROLS_QUIT, MyFrame::OnQuit) EVT_MENU(CONTROLS_ABOUT, MyFrame::OnAbout) EVT_MENU(CONTROLS_CLEAR_LOG, MyFrame::OnClearLog) #if wxUSE_TOOLTIPS EVT_MENU(CONTROLS_SET_TOOLTIP_DELAY, MyFrame::OnSetTooltipDelay) EVT_MENU(CONTROLS_ENABLE_TOOLTIPS, MyFrame::OnToggleTooltips) #ifdef __WXMSW__ EVT_MENU(CONTROLS_SET_TOOLTIPS_MAX_WIDTH, MyFrame::OnSetMaxTooltipWidth) #endif // __WXMSW__ #endif // wxUSE_TOOLTIPS EVT_MENU(CONTROLS_ENABLE_ALL, MyFrame::OnEnableAll) EVT_MENU(CONTROLS_HIDE_ALL, MyFrame::OnHideAll) EVT_MENU(CONTROLS_HIDE_LIST, MyFrame::OnHideList) EVT_MENU(CONTROLS_CONTEXT_HELP, MyFrame::OnContextHelp) EVT_ICONIZE(MyFrame::OnIconized) EVT_MAXIMIZE(MyFrame::OnMaximized) EVT_SIZE(MyFrame::OnSize) EVT_MOVE(MyFrame::OnMove) EVT_IDLE(MyFrame::OnIdle) END_EVENT_TABLE() MyFrame::MyFrame(const wxChar *title, int x, int y) : wxFrame(NULL, wxID_ANY, title, wxPoint(x, y), wxSize(700, 450)) { SetHelpText( wxT("Controls sample demonstrating various widgets") ); // Give it an icon // The wxICON() macros loads an icon from a resource under Windows // and uses an #included XPM image under GTK+ and Motif SetIcon( wxICON(sample) ); wxMenu *file_menu = new wxMenu; file_menu->Append(CONTROLS_CLEAR_LOG, wxT("&Clear log\tCtrl-L")); file_menu->AppendSeparator(); file_menu->Append(CONTROLS_ABOUT, wxT("&About\tF1")); file_menu->AppendSeparator(); file_menu->Append(CONTROLS_QUIT, wxT("E&xit\tAlt-X"), wxT("Quit controls sample")); wxMenuBar *menu_bar = new wxMenuBar; menu_bar->Append(file_menu, wxT("&File")); #if wxUSE_TOOLTIPS wxMenu *tooltip_menu = new wxMenu; tooltip_menu->Append(CONTROLS_SET_TOOLTIP_DELAY, wxT("Set &delay\tCtrl-D")); tooltip_menu->AppendSeparator(); tooltip_menu->Append(CONTROLS_ENABLE_TOOLTIPS, wxT("&Toggle tooltips\tCtrl-T"), wxT("enable/disable tooltips"), true); tooltip_menu->Check(CONTROLS_ENABLE_TOOLTIPS, true); #ifdef __WXMSW__ tooltip_menu->Append(CONTROLS_SET_TOOLTIPS_MAX_WIDTH, "Set maximal &width"); #endif // __WXMSW__ menu_bar->Append(tooltip_menu, wxT("&Tooltips")); #endif // wxUSE_TOOLTIPS wxMenu *panel_menu = new wxMenu; panel_menu->Append(CONTROLS_ENABLE_ALL, wxT("&Disable all\tCtrl-E"), wxT("Enable/disable all panel controls"), true); panel_menu->Append(CONTROLS_HIDE_ALL, wxT("&Hide all\tCtrl-I"), wxT("Show/hide thoe whole panel controls"), true); panel_menu->Append(CONTROLS_HIDE_LIST, wxT("Hide &list ctrl\tCtrl-S"), wxT("Enable/disable all panel controls"), true); panel_menu->Append(CONTROLS_CONTEXT_HELP, wxT("&Context help...\tCtrl-H"), wxT("Get context help for a control")); menu_bar->Append(panel_menu, wxT("&Panel")); SetMenuBar(menu_bar); #if wxUSE_STATUSBAR CreateStatusBar(2); #endif // wxUSE_STATUSBAR m_panel = new MyPanel( this, 10, 10, 300, 100 ); } void MyFrame::OnQuit (wxCommandEvent& WXUNUSED(event) ) { Close(true); } void MyFrame::OnAbout( wxCommandEvent& WXUNUSED(event) ) { wxBusyCursor bc; wxMessageDialog dialog(this, wxT("This is a control sample"), wxT("About Controls"), wxOK ); dialog.ShowModal(); } void MyFrame::OnClearLog(wxCommandEvent& WXUNUSED(event)) { m_panel->m_text->Clear(); } #if wxUSE_TOOLTIPS void MyFrame::OnSetTooltipDelay(wxCommandEvent& WXUNUSED(event)) { static long s_delay = 5000; wxString delay; delay.Printf( wxT("%ld"), s_delay); delay = wxGetTextFromUser(wxT("Enter delay (in milliseconds)"), wxT("Set tooltip delay"), delay, this); if ( !delay ) return; // cancelled wxSscanf(delay, wxT("%ld"), &s_delay); wxToolTip::SetDelay(s_delay); wxLogStatus(this, wxT("Tooltip delay set to %ld milliseconds"), s_delay); } void MyFrame::OnToggleTooltips(wxCommandEvent& WXUNUSED(event)) { static bool s_enabled = true; s_enabled = !s_enabled; wxToolTip::Enable(s_enabled); wxLogStatus(this, wxT("Tooltips %sabled"), s_enabled ? wxT("en") : wxT("dis") ); } #ifdef __WXMSW__ void MyFrame::OnSetMaxTooltipWidth(wxCommandEvent& WXUNUSED(event)) { static int s_maxWidth = 0; wxNumberEntryDialog dlg ( this, "Change maximal tooltip width", "&Width in pixels:", GetTitle(), s_maxWidth, -1, 600 ); if ( dlg.ShowModal() == wxID_CANCEL ) return; s_maxWidth = dlg.GetValue(); wxToolTip::SetMaxWidth(s_maxWidth); // we need to set the tooltip again to test the new width m_panel->SetAllToolTips(); } #endif // __WXMSW__ #endif // wxUSE_TOOLTIPS void MyFrame::OnEnableAll(wxCommandEvent& WXUNUSED(event)) { static bool s_enable = true; s_enable = !s_enable; m_panel->Enable(s_enable); static bool s_enableCheckbox = true; if ( !s_enable ) { // this is a test for correct behaviour of either enabling or disabling // a child when its parent is disabled: the checkbox should have the // correct state when the parent is enabled back m_panel->m_checkbox->Enable(s_enableCheckbox); s_enableCheckbox = !s_enableCheckbox; } } void MyFrame::OnHideAll(wxCommandEvent& WXUNUSED(event)) { static bool s_show = true; s_show = !s_show; m_panel->Show(s_show); } void MyFrame::OnHideList(wxCommandEvent& WXUNUSED(event)) { static bool s_show = true; s_show = !s_show; m_panel->m_listbox->Show(s_show); } void MyFrame::OnContextHelp(wxCommandEvent& WXUNUSED(event)) { // starts a local event loop wxContextHelp chelp(this); } void MyFrame::OnMove( wxMoveEvent& event ) { #if wxUSE_STATUSBAR UpdateStatusBar(event.GetPosition(), GetSize()); #endif // wxUSE_STATUSBAR event.Skip(); } void MyFrame::OnIconized( wxIconizeEvent& event ) { wxLogMessage(wxT("Frame %s"), event.IsIconized() ? wxT("iconized") : wxT("restored")); event.Skip(); } void MyFrame::OnMaximized( wxMaximizeEvent& WXUNUSED(event) ) { wxLogMessage(wxT("Frame maximized")); } void MyFrame::OnSize( wxSizeEvent& event ) { #if wxUSE_STATUSBAR UpdateStatusBar(GetPosition(), event.GetSize()); #endif // wxUSE_STATUSBAR event.Skip(); } void MyFrame::OnIdle( wxIdleEvent& WXUNUSED(event) ) { // track the window which has the focus in the status bar static wxWindow *s_windowFocus = NULL; wxWindow *focus = wxWindow::FindFocus(); if ( focus != s_windowFocus ) { s_windowFocus = focus; wxString msg; if ( focus ) { msg.Printf( "Focus: %s" #ifdef __WXMSW__ ", HWND = %08x" #endif , s_windowFocus->GetName().c_str() #ifdef __WXMSW__ , (unsigned int) s_windowFocus->GetHWND() #endif ); } else { msg = wxT("No focus"); } #if wxUSE_STATUSBAR SetStatusText(msg); #endif // wxUSE_STATUSBAR } } void MyComboBox::OnChar(wxKeyEvent& event) { wxLogMessage(wxT("MyComboBox::OnChar")); if ( event.GetKeyCode() == 'w' ) { wxLogMessage(wxT("MyComboBox: 'w' will be ignored.")); } else { event.Skip(); } } void MyComboBox::OnKeyDown(wxKeyEvent& event) { wxLogMessage(wxT("MyComboBox::OnKeyDown")); if ( event.GetKeyCode() == 'w' ) { wxLogMessage(wxT("MyComboBox: 'w' will be ignored.")); } else { event.Skip(); } } void MyComboBox::OnKeyUp(wxKeyEvent& event) { wxLogMessage(wxT("MyComboBox::OnKeyUp")); event.Skip(); } static void SetListboxClientData(const wxChar *name, wxListBox *control) { size_t count = control->GetCount(); for ( size_t n = 0; n < count; n++ ) { wxString s; s.Printf(wxT("%s client data for '%s'"), name, control->GetString(n).c_str()); control->SetClientObject(n, new wxStringClientData(s)); } } #if wxUSE_CHOICE static void SetChoiceClientData(const wxChar *name, wxChoice *control) { size_t count = control->GetCount(); for ( size_t n = 0; n < count; n++ ) { wxString s; s.Printf(wxT("%s client data for '%s'"), name, control->GetString(n).c_str()); control->SetClientObject(n, new wxStringClientData(s)); } } #endif // wxUSE_CHOICE
enachb/freetel-code
src/wxWidgets-2.9.4/samples/controls/controls.cpp
C++
lgpl-2.1
68,101
// // CodeAnalysisRunner.cs // // Author: // Mike Krüger <mkrueger@xamarin.com> // // Copyright (c) 2012 Xamarin Inc. (http://xamarin.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. //#define PROFILE using System; using System.Linq; using MonoDevelop.AnalysisCore; using System.Collections.Generic; using MonoDevelop.AnalysisCore.Fixes; using ICSharpCode.NRefactory.CSharp; using MonoDevelop.Core; using MonoDevelop.Ide.Gui; using MonoDevelop.Refactoring; using System.Threading; using System.Threading.Tasks; using System.Collections.Concurrent; using MonoDevelop.SourceEditor.QuickTasks; using ICSharpCode.NRefactory.TypeSystem; using MonoDevelop.CodeIssues; using Mono.TextEditor; using ICSharpCode.NRefactory.Refactoring; using MonoDevelop.CodeActions; using System.Diagnostics; using MonoDevelop.Ide.TypeSystem; namespace MonoDevelop.CodeIssues { public static class CodeAnalysisRunner { static IEnumerable<BaseCodeIssueProvider> EnumerateProvider (CodeIssueProvider p) { if (p.HasSubIssues) return p.SubIssues; return new BaseCodeIssueProvider[] { p }; } public static IEnumerable<Result> Check (Document input, ParsedDocument parsedDocument, CancellationToken cancellationToken) { if (!QuickTaskStrip.EnableFancyFeatures || input.Project == null || !input.IsCompileableInProject) return Enumerable.Empty<Result> (); #if PROFILE var runList = new List<Tuple<long, string>> (); #endif var editor = input.Editor; if (editor == null) return Enumerable.Empty<Result> (); var loc = editor.Caret.Location; var result = new BlockingCollection<Result> (); var codeIssueProvider = RefactoringService.GetInspectors (editor.Document.MimeType).ToArray (); var context = parsedDocument.CreateRefactoringContext != null ? parsedDocument.CreateRefactoringContext (input, cancellationToken) : null; Parallel.ForEach (codeIssueProvider, (parentProvider) => { try { #if PROFILE var clock = new Stopwatch(); clock.Start (); #endif foreach (var provider in EnumerateProvider (parentProvider)) { cancellationToken.ThrowIfCancellationRequested (); var severity = provider.GetSeverity (); if (severity == Severity.None || !provider.GetIsEnabled ()) continue; foreach (var r in provider.GetIssues (context, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested (); var fixes = r.Actions == null ? new List<GenericFix> () : new List<GenericFix> (r.Actions.Where (a => a != null).Select (a => { Action batchAction = null; if (a.SupportsBatchRunning) batchAction = () => a.BatchRun (input, loc); return new GenericFix ( a.Title, () => { using (var script = context.CreateScript ()) { a.Run (context, script); } }, batchAction) { DocumentRegion = new DocumentRegion (r.Region.Begin, r.Region.End), IdString = a.IdString }; })); result.Add (new InspectorResults ( provider, r.Region, r.Description, severity, r.IssueMarker, fixes.ToArray () )); } } #if PROFILE clock.Stop (); lock (runList) { runList.Add (Tuple.Create (clock.ElapsedMilliseconds, parentProvider.Title)); } #endif } catch (OperationCanceledException) { //ignore } catch (Exception e) { LoggingService.LogError ("CodeAnalysis: Got exception in inspector '" + parentProvider + "'", e); } }); #if PROFILE runList.Sort (); foreach (var item in runList) { Console.WriteLine (item.Item1 +"ms\t: " + item.Item2); } #endif return result; } } }
mono/linux-packaging-monodevelop
src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/CodeAnalysisRunner.cs
C#
lgpl-2.1
4,774
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qtoptionspage.h" #include "qtconfigwidget.h" #include "ui_showbuildlog.h" #include "ui_qtversionmanager.h" #include "ui_qtversioninfo.h" #include "ui_debugginghelper.h" #include "qtsupportconstants.h" #include "qtversionmanager.h" #include "qtversionfactory.h" #include "qmldumptool.h" #include <coreplugin/progressmanager/progressmanager.h> #include <coreplugin/coreconstants.h> #include <coreplugin/variablechooser.h> #include <projectexplorer/toolchain.h> #include <projectexplorer/toolchainmanager.h> #include <projectexplorer/projectexplorerconstants.h> #include <utils/hostosinfo.h> #include <utils/pathchooser.h> #include <utils/qtcassert.h> #include <utils/runextensions.h> #include <utils/algorithm.h> #include <QDir> #include <QMessageBox> #include <QFileDialog> #include <QTextBrowser> #include <QDesktopServices> using namespace ProjectExplorer; using namespace Utils; namespace QtSupport { namespace Internal { enum ModelRoles { VersionIdRole = Qt::UserRole, ToolChainIdRole, BuildLogRole, BuildRunningRole}; /// // QtOptionsPage /// QtOptionsPage::QtOptionsPage() : m_widget(0) { setId(Constants::QTVERSION_SETTINGS_PAGE_ID); setDisplayName(QCoreApplication::translate("Qt4ProjectManager", Constants::QTVERSION_SETTINGS_PAGE_NAME)); setCategory(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY); setDisplayCategory(QCoreApplication::translate("ProjectExplorer", ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_TR_CATEGORY)); setCategoryIcon(QLatin1String(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY_ICON)); } QWidget *QtOptionsPage::widget() { if (!m_widget) m_widget = new QtOptionsPageWidget; return m_widget; } void QtOptionsPage::apply() { if (!m_widget) // page was never shown return; m_widget->apply(); } void QtOptionsPage::finish() { delete m_widget; } //----------------------------------------------------- QtOptionsPageWidget::QtOptionsPageWidget(QWidget *parent) : QWidget(parent) , m_specifyNameString(tr("<specify a name>")) , m_ui(new Internal::Ui::QtVersionManager()) , m_versionUi(new Internal::Ui::QtVersionInfo()) , m_debuggingHelperUi(new Internal::Ui::DebuggingHelper()) , m_infoBrowser(new QTextBrowser) , m_invalidVersionIcon(QLatin1String(Core::Constants::ICON_ERROR)) , m_warningVersionIcon(QLatin1String(Core::Constants::ICON_WARNING)) , m_configurationWidget(0) , m_autoItem(0) , m_manualItem(0) { QWidget *versionInfoWidget = new QWidget(); m_versionUi->setupUi(versionInfoWidget); m_versionUi->editPathPushButton->setText(PathChooser::browseButtonLabel()); QWidget *debuggingHelperDetailsWidget = new QWidget(); m_debuggingHelperUi->setupUi(debuggingHelperDetailsWidget); m_ui->setupUi(this); m_infoBrowser->setOpenLinks(false); m_infoBrowser->setTextInteractionFlags(Qt::TextBrowserInteraction); connect(m_infoBrowser, &QTextBrowser::anchorClicked, this, &QtOptionsPageWidget::infoAnchorClicked); m_ui->infoWidget->setWidget(m_infoBrowser); connect(m_ui->infoWidget, &DetailsWidget::expanded, this, &QtOptionsPageWidget::setInfoWidgetVisibility); m_ui->versionInfoWidget->setWidget(versionInfoWidget); m_ui->versionInfoWidget->setState(DetailsWidget::NoSummary); m_ui->debuggingHelperWidget->setWidget(debuggingHelperDetailsWidget); connect(m_ui->debuggingHelperWidget, &DetailsWidget::expanded, this, &QtOptionsPageWidget::setInfoWidgetVisibility); // setup parent items for auto-detected and manual versions m_ui->qtdirList->header()->setStretchLastSection(false); m_ui->qtdirList->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); m_ui->qtdirList->header()->setSectionResizeMode(1, QHeaderView::Stretch); m_ui->qtdirList->setTextElideMode(Qt::ElideNone); m_autoItem = new QTreeWidgetItem(m_ui->qtdirList); m_autoItem->setText(0, tr("Auto-detected")); m_autoItem->setFirstColumnSpanned(true); m_autoItem->setFlags(Qt::ItemIsEnabled); m_manualItem = new QTreeWidgetItem(m_ui->qtdirList); m_manualItem->setText(0, tr("Manual")); m_manualItem->setFirstColumnSpanned(true); m_manualItem->setFlags(Qt::ItemIsEnabled); QList<int> additions = transform(QtVersionManager::versions(), &BaseQtVersion::uniqueId); updateQtVersions(additions, QList<int>(), QList<int>()); m_ui->qtdirList->expandAll(); connect(m_versionUi->nameEdit, &QLineEdit::textEdited, this, &QtOptionsPageWidget::updateCurrentQtName); connect(m_versionUi->editPathPushButton, &QAbstractButton::clicked, this, &QtOptionsPageWidget::editPath); connect(m_ui->addButton, &QAbstractButton::clicked, this, &QtOptionsPageWidget::addQtDir); connect(m_ui->delButton, &QAbstractButton::clicked, this, &QtOptionsPageWidget::removeQtDir); connect(m_ui->qtdirList, &QTreeWidget::currentItemChanged, this, &QtOptionsPageWidget::versionChanged); connect(m_debuggingHelperUi->rebuildButton, &QAbstractButton::clicked, this, [this]() { buildDebuggingHelper(); }); connect(m_debuggingHelperUi->qmlDumpBuildButton, &QAbstractButton::clicked, this, &QtOptionsPageWidget::buildQmlDump); connect(m_debuggingHelperUi->showLogButton, &QAbstractButton::clicked, this, &QtOptionsPageWidget::slotShowDebuggingBuildLog); connect(m_debuggingHelperUi->toolChainComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), this, &QtOptionsPageWidget::selectedToolChainChanged); connect(m_ui->cleanUpButton, &QAbstractButton::clicked, this, &QtOptionsPageWidget::cleanUpQtVersions); userChangedCurrentVersion(); updateCleanUpButton(); connect(QtVersionManager::instance(), &QtVersionManager::dumpUpdatedFor, this, &QtOptionsPageWidget::qtVersionsDumpUpdated); connect(QtVersionManager::instance(), &QtVersionManager::qtVersionsChanged, this, &QtOptionsPageWidget::updateQtVersions); connect(ProjectExplorer::ToolChainManager::instance(), &ToolChainManager::toolChainsChanged, this, &QtOptionsPageWidget::toolChainsUpdated); auto chooser = new Core::VariableChooser(this); chooser->addSupportedWidget(m_versionUi->nameEdit, "Qt:Name"); chooser->addMacroExpanderProvider( [this]() -> Utils::MacroExpander * { BaseQtVersion *version = currentVersion(); return version ? version->macroExpander() : 0; }); } int QtOptionsPageWidget::currentIndex() const { if (QTreeWidgetItem *currentItem = m_ui->qtdirList->currentItem()) return indexForTreeItem(currentItem); return -1; } BaseQtVersion *QtOptionsPageWidget::currentVersion() const { const int currentItemIndex = currentIndex(); if (currentItemIndex >= 0 && currentItemIndex < m_versions.size()) return m_versions.at(currentItemIndex); return 0; } static inline int findVersionById(const QList<BaseQtVersion *> &l, int id) { const int size = l.size(); for (int i = 0; i < size; i++) if (l.at(i)->uniqueId() == id) return i; return -1; } // Update with results of terminated helper build void QtOptionsPageWidget::debuggingHelperBuildFinished(int qtVersionId, const QString &output, DebuggingHelperBuildTask::Tools tools) { const int index = findVersionById(m_versions, qtVersionId); if (index == -1) return; // Oops, somebody managed to delete the version BaseQtVersion *version = m_versions.at(index); // Update item view QTreeWidgetItem *item = treeItemForIndex(index); QTC_ASSERT(item, return); DebuggingHelperBuildTask::Tools buildFlags = item->data(0, BuildRunningRole).value<DebuggingHelperBuildTask::Tools>(); buildFlags &= ~tools; item->setData(0, BuildRunningRole, QVariant::fromValue(buildFlags)); item->setData(0, BuildLogRole, output); bool success = true; if (tools & DebuggingHelperBuildTask::QmlDump) success &= version->hasQmlDump(); if (!success) showDebuggingBuildLog(item); updateDebuggingHelperUi(); } void QtOptionsPageWidget::cleanUpQtVersions() { QStringList toRemove; foreach (const BaseQtVersion *v, m_versions) { if (!v->isValid()) toRemove.append(v->displayName()); } if (toRemove.isEmpty()) return; if (QMessageBox::warning(0, tr("Remove Invalid Qt Versions"), tr("Do you want to remove all invalid Qt Versions?<br>" "<ul><li>%1</li></ul><br>" "will be removed.").arg(toRemove.join(QLatin1String("</li><li>"))), QMessageBox::Yes, QMessageBox::No) == QMessageBox::No) return; for (int i = m_versions.count() - 1; i >= 0; --i) { if (!m_versions.at(i)->isValid()) { QTreeWidgetItem *item = treeItemForIndex(i); delete item; delete m_versions.at(i); m_versions.removeAt(i); } } updateCleanUpButton(); } void QtOptionsPageWidget::toolChainsUpdated() { for (int i = 0; i < m_versions.count(); ++i) { QTreeWidgetItem *item = treeItemForIndex(i); if (item == m_ui->qtdirList->currentItem()) { updateDescriptionLabel(); updateDebuggingHelperUi(); } else { updateVersionItem(m_versions.at(i)); } } } void QtOptionsPageWidget::selectedToolChainChanged(int comboIndex) { const int index = currentIndex(); if (index < 0) return; QTreeWidgetItem *item = treeItemForIndex(index); QTC_ASSERT(item, return); QString toolChainId = m_debuggingHelperUi->toolChainComboBox->itemData(comboIndex).toString(); item->setData(0, ToolChainIdRole, toolChainId); } void QtOptionsPageWidget::qtVersionsDumpUpdated(const FileName &qmakeCommand) { foreach (BaseQtVersion *version, m_versions) { if (version->qmakeCommand() == qmakeCommand) version->recheckDumper(); } if (currentVersion() && currentVersion()->qmakeCommand() == qmakeCommand) { updateWidgets(); updateDescriptionLabel(); updateDebuggingHelperUi(); } } void QtOptionsPageWidget::setInfoWidgetVisibility() { m_ui->versionInfoWidget->setVisible((m_ui->infoWidget->state() == DetailsWidget::Collapsed) && (m_ui->debuggingHelperWidget->state() == DetailsWidget::Collapsed)); m_ui->infoWidget->setVisible(m_ui->debuggingHelperWidget->state() == DetailsWidget::Collapsed); m_ui->debuggingHelperWidget->setVisible(m_ui->infoWidget->state() == DetailsWidget::Collapsed); } void QtOptionsPageWidget::infoAnchorClicked(const QUrl &url) { QDesktopServices::openUrl(url); } QtOptionsPageWidget::ValidityInfo QtOptionsPageWidget::validInformation(const BaseQtVersion *version) { ValidityInfo info; info.icon = m_validVersionIcon; if (!version) return info; info.description = tr("Qt version %1 for %2").arg(version->qtVersionString(), version->description()); if (!version->isValid()) { info.icon = m_invalidVersionIcon; info.message = version->invalidReason(); return info; } // Do we have tool chain issues? QStringList missingToolChains; int abiCount = 0; foreach (const Abi &abi, version->qtAbis()) { if (ToolChainManager::findToolChains(abi).isEmpty()) missingToolChains.append(abi.toString()); ++abiCount; } bool useable = true; QStringList warnings; if (!isNameUnique(version)) warnings << tr("Display Name is not unique."); if (!missingToolChains.isEmpty()) { if (missingToolChains.count() == abiCount) { // Yes, this Qt version can't be used at all! info.message = tr("No compiler can produce code for this Qt version. Please define one or more compilers."); info.icon = m_invalidVersionIcon; useable = false; } else { // Yes, some ABIs are unsupported warnings << tr("Not all possible target environments can be supported due to missing compilers."); info.toolTip = tr("The following ABIs are currently not supported:<ul><li>%1</li></ul>") .arg(missingToolChains.join(QLatin1String("</li><li>"))); info.icon = m_warningVersionIcon; } } if (useable) { warnings += version->warningReason(); if (!warnings.isEmpty()) { info.message = warnings.join(QLatin1Char('\n')); info.icon = m_warningVersionIcon; } } return info; } QList<ToolChain*> QtOptionsPageWidget::toolChains(const BaseQtVersion *version) { QList<ToolChain*> toolChains; if (!version) return toolChains; QSet<QString> ids; foreach (const Abi &a, version->qtAbis()) { foreach (ToolChain *tc, ToolChainManager::findToolChains(a)) { if (ids.contains(tc->id())) continue; ids.insert(tc->id()); toolChains.append(tc); } } return toolChains; } QString QtOptionsPageWidget::defaultToolChainId(const BaseQtVersion *version) { QList<ToolChain*> possibleToolChains = toolChains(version); if (!possibleToolChains.isEmpty()) return possibleToolChains.first()->id(); return QString(); } bool QtOptionsPageWidget::isNameUnique(const BaseQtVersion *version) { const QString name = version->displayName().trimmed(); foreach (const BaseQtVersion *i, m_versions) { if (i == version) continue; if (i->displayName().trimmed() == name) return false; } return true; } void QtOptionsPageWidget::updateVersionItem(BaseQtVersion *version) { const ValidityInfo info = validInformation(version); QTreeWidgetItem *item = treeItemForIndex(m_versions.indexOf(version)); item->setText(0, version->displayName()); item->setText(1, version->qmakeCommand().toUserOutput()); item->setIcon(0, info.icon); } void QtOptionsPageWidget::buildDebuggingHelper(DebuggingHelperBuildTask::Tools tools) { const int index = currentIndex(); if (index < 0) return; // remove tools that cannot be build tools &= DebuggingHelperBuildTask::availableTools(currentVersion()); QTreeWidgetItem *item = treeItemForIndex(index); QTC_ASSERT(item, return); DebuggingHelperBuildTask::Tools buildFlags = item->data(0, BuildRunningRole).value<DebuggingHelperBuildTask::Tools>(); buildFlags |= tools; item->setData(0, BuildRunningRole, QVariant::fromValue(buildFlags)); BaseQtVersion *version = m_versions.at(index); if (!version) return; updateDebuggingHelperUi(); // Run a debugging helper build task in the background. QString toolChainId = m_debuggingHelperUi->toolChainComboBox->itemData( m_debuggingHelperUi->toolChainComboBox->currentIndex()).toString(); ToolChain *toolChain = ToolChainManager::findToolChain(toolChainId); if (!toolChain) return; DebuggingHelperBuildTask *buildTask = new DebuggingHelperBuildTask(version, toolChain, tools); // Don't open General Messages pane with errors buildTask->showOutputOnError(false); connect(buildTask, SIGNAL(finished(int,QString,DebuggingHelperBuildTask::Tools)), this, SLOT(debuggingHelperBuildFinished(int,QString,DebuggingHelperBuildTask::Tools)), Qt::QueuedConnection); QFuture<void> task = QtConcurrent::run(&DebuggingHelperBuildTask::run, buildTask); const QString taskName = tr("Building Helpers"); Core::ProgressManager::addTask(task, taskName, "QmakeProjectManager::BuildHelpers"); } void QtOptionsPageWidget::buildQmlDump() { buildDebuggingHelper(DebuggingHelperBuildTask::QmlDump); } // Non-modal dialog class BuildLogDialog : public QDialog { public: explicit BuildLogDialog(QWidget *parent = 0); void setText(const QString &text); private: Ui_ShowBuildLog m_ui; }; BuildLogDialog::BuildLogDialog(QWidget *parent) : QDialog(parent) { m_ui.setupUi(this); setAttribute(Qt::WA_DeleteOnClose, true); } void BuildLogDialog::setText(const QString &text) { m_ui.log->setPlainText(text); // Show and scroll to bottom m_ui.log->moveCursor(QTextCursor::End); m_ui.log->ensureCursorVisible(); } void QtOptionsPageWidget::slotShowDebuggingBuildLog() { if (const QTreeWidgetItem *currentItem = m_ui->qtdirList->currentItem()) showDebuggingBuildLog(currentItem); } void QtOptionsPageWidget::showDebuggingBuildLog(const QTreeWidgetItem *currentItem) { const int currentItemIndex = indexForTreeItem(currentItem); if (currentItemIndex < 0) return; BuildLogDialog *dialog = new BuildLogDialog(this->window()); dialog->setWindowTitle(tr("Debugging Helper Build Log for \"%1\"").arg(currentItem->text(0))); dialog->setText(currentItem->data(0, BuildLogRole).toString()); dialog->show(); } void QtOptionsPageWidget::updateQtVersions(const QList<int> &additions, const QList<int> &removals, const QList<int> &changes) { QList<QTreeWidgetItem *> toRemove; QList<int> toAdd = additions; // Generate list of all existing items: QList<QTreeWidgetItem *> itemList; for (int i = 0; i < m_autoItem->childCount(); ++i) itemList.append(m_autoItem->child(i)); for (int i = 0; i < m_manualItem->childCount(); ++i) itemList.append(m_manualItem->child(i)); // Find existing items to remove/change: foreach (QTreeWidgetItem *item, itemList) { int id = item->data(0, VersionIdRole).toInt(); if (removals.contains(id)) { toRemove.append(item); continue; } if (changes.contains(id)) { toAdd.append(id); toRemove.append(item); continue; } } // Remove changed/removed items: foreach (QTreeWidgetItem *item, toRemove) { int index = indexForTreeItem(item); delete m_versions.at(index); m_versions.removeAt(index); delete item; } // Add changed/added items: foreach (int a, toAdd) { BaseQtVersion *version = QtVersionManager::version(a)->clone(); m_versions.append(version); QTreeWidgetItem *item = new QTreeWidgetItem; item->setData(0, VersionIdRole, version->uniqueId()); item->setData(0, ToolChainIdRole, defaultToolChainId(version)); // Insert in the right place: QTreeWidgetItem *parent = version->isAutodetected()? m_autoItem : m_manualItem; for (int i = 0; i < parent->childCount(); ++i) { BaseQtVersion *currentVersion = m_versions.at(indexForTreeItem(parent->child(i))); if (currentVersion->qtVersion() > version->qtVersion()) continue; parent->insertChild(i, item); parent = 0; break; } if (parent) parent->addChild(item); } // Only set the icon after all versions are there to make sure all names are known: foreach (BaseQtVersion *i, m_versions) updateVersionItem(i); } QtOptionsPageWidget::~QtOptionsPageWidget() { delete m_ui; delete m_versionUi; delete m_debuggingHelperUi; delete m_configurationWidget; qDeleteAll(m_versions); } void QtOptionsPageWidget::addQtDir() { FileName qtVersion = FileName::fromString( QFileDialog::getOpenFileName(this, tr("Select a qmake Executable"), QString(), BuildableHelperLibrary::filterForQmakeFileDialog(), 0, QFileDialog::DontResolveSymlinks)); if (qtVersion.isNull()) return; QFileInfo fi(qtVersion.toString()); // should add all qt versions here ? if (BuildableHelperLibrary::isQtChooser(fi)) qtVersion = FileName::fromString(BuildableHelperLibrary::qtChooserToQmakePath(fi.symLinkTarget())); BaseQtVersion *version = Utils::findOrDefault(m_versions, Utils::equal(&BaseQtVersion::qmakeCommand, qtVersion)); if (version) { // Already exist QMessageBox::warning(this, tr("Qt Version Already Known"), tr("This Qt version was already registered as \"%1\".") .arg(version->displayName())); return; } QString error; version = QtVersionFactory::createQtVersionFromQMakePath(qtVersion, false, QString(), &error); if (version) { m_versions.append(version); QTreeWidgetItem *item = new QTreeWidgetItem(m_ui->qtdirList->topLevelItem(1)); item->setText(0, version->displayName()); item->setText(1, version->qmakeCommand().toUserOutput()); item->setData(0, VersionIdRole, version->uniqueId()); item->setData(0, ToolChainIdRole, defaultToolChainId(version)); item->setIcon(0, version->isValid()? m_validVersionIcon : m_invalidVersionIcon); m_ui->qtdirList->setCurrentItem(item); // should update the rest of the ui m_versionUi->nameEdit->setFocus(); m_versionUi->nameEdit->selectAll(); } else { QMessageBox::warning(this, tr("Qmake Not Executable"), tr("The qmake executable %1 could not be added: %2").arg(qtVersion.toUserOutput()).arg(error)); return; } updateCleanUpButton(); } void QtOptionsPageWidget::removeQtDir() { QTreeWidgetItem *item = m_ui->qtdirList->currentItem(); int index = indexForTreeItem(item); if (index < 0) return; delete item; BaseQtVersion *version = m_versions.at(index); m_versions.removeAt(index); delete version; updateCleanUpButton(); } void QtOptionsPageWidget::editPath() { BaseQtVersion *current = currentVersion(); QString dir = currentVersion()->qmakeCommand().toFileInfo().absolutePath(); FileName qtVersion = FileName::fromString( QFileDialog::getOpenFileName(this, tr("Select a qmake Executable"), dir, BuildableHelperLibrary::filterForQmakeFileDialog(), 0, QFileDialog::DontResolveSymlinks)); if (qtVersion.isNull()) return; BaseQtVersion *version = QtVersionFactory::createQtVersionFromQMakePath(qtVersion); if (!version) return; // Same type? then replace! if (current->type() != version->type()) { // not the same type, error out QMessageBox::critical(this, tr("Incompatible Qt Versions"), tr("The Qt version selected must match the device type."), QMessageBox::Ok); delete version; return; } // same type, replace version->setId(current->uniqueId()); if (current->unexpandedDisplayName() != current->defaultUnexpandedDisplayName(current->qmakeCommand())) version->setUnexpandedDisplayName(current->displayName()); m_versions.replace(m_versions.indexOf(current), version); delete current; // Update ui userChangedCurrentVersion(); QTreeWidgetItem *item = m_ui->qtdirList->currentItem(); item->setText(0, version->displayName()); item->setText(1, version->qmakeCommand().toUserOutput()); item->setData(0, VersionIdRole, version->uniqueId()); item->setData(0, ToolChainIdRole, defaultToolChainId(version)); item->setIcon(0, version->isValid()? m_validVersionIcon : m_invalidVersionIcon); } void QtOptionsPageWidget::updateDebuggingHelperUi() { BaseQtVersion *version = currentVersion(); const QTreeWidgetItem *currentItem = m_ui->qtdirList->currentItem(); QList<ToolChain*> toolchains = toolChains(currentVersion()); if (!version || !version->isValid() || toolchains.isEmpty()) { m_ui->debuggingHelperWidget->setVisible(false); } else { const DebuggingHelperBuildTask::Tools availableTools = DebuggingHelperBuildTask::availableTools(version); const bool canBuildQmlDumper = availableTools & DebuggingHelperBuildTask::QmlDump; const bool hasQmlDumper = version->hasQmlDump(); const bool needsQmlDumper = version->needsQmlDump(); bool isBuildingQmlDumper = false; if (currentItem) { DebuggingHelperBuildTask::Tools buildingTools = currentItem->data(0, BuildRunningRole).value<DebuggingHelperBuildTask::Tools>(); isBuildingQmlDumper = buildingTools & DebuggingHelperBuildTask::QmlDump; } // get names of tools from labels QStringList helperNames; const QChar colon = QLatin1Char(':'); if (hasQmlDumper) helperNames << m_debuggingHelperUi->qmlDumpLabel->text().remove(colon); QString status; if (helperNames.isEmpty()) { status = tr("Helpers: None available"); } else { //: %1 is list of tool names. status = tr("Helpers: %1.").arg(helperNames.join(QLatin1String(", "))); } m_ui->debuggingHelperWidget->setSummaryText(status); QString qmlDumpStatusText, qmlDumpStatusToolTip; Qt::TextInteractionFlags qmlDumpStatusTextFlags = Qt::NoTextInteraction; if (hasQmlDumper) { qmlDumpStatusText = QDir::toNativeSeparators(version->qmlDumpTool(false)); const QString debugQmlDumpPath = QDir::toNativeSeparators(version->qmlDumpTool(true)); if (qmlDumpStatusText != debugQmlDumpPath) { if (!qmlDumpStatusText.isEmpty() && !debugQmlDumpPath.isEmpty()) qmlDumpStatusText += QLatin1String("\n"); qmlDumpStatusText += debugQmlDumpPath; } qmlDumpStatusTextFlags = Qt::TextSelectableByMouse; } else { if (!needsQmlDumper) { qmlDumpStatusText = tr("<i>Not needed.</i>"); } else if (canBuildQmlDumper) { qmlDumpStatusText = tr("<i>Not yet built.</i>"); } else { qmlDumpStatusText = tr("<i>Cannot be compiled.</i>"); QmlDumpTool::canBuild(version, &qmlDumpStatusToolTip); } } m_debuggingHelperUi->qmlDumpStatus->setText(qmlDumpStatusText); m_debuggingHelperUi->qmlDumpStatus->setTextInteractionFlags(qmlDumpStatusTextFlags); m_debuggingHelperUi->qmlDumpStatus->setToolTip(qmlDumpStatusToolTip); m_debuggingHelperUi->qmlDumpBuildButton->setEnabled(canBuildQmlDumper & !isBuildingQmlDumper); QList<ToolChain*> toolchains = toolChains(currentVersion()); QString selectedToolChainId = currentItem->data(0, ToolChainIdRole).toString(); m_debuggingHelperUi->toolChainComboBox->clear(); for (int i = 0; i < toolchains.size(); ++i) { if (!toolchains.at(i)->isValid()) continue; if (i >= m_debuggingHelperUi->toolChainComboBox->count()) { m_debuggingHelperUi->toolChainComboBox->insertItem(i, toolchains.at(i)->displayName(), toolchains.at(i)->id()); } if (toolchains.at(i)->id() == selectedToolChainId) m_debuggingHelperUi->toolChainComboBox->setCurrentIndex(i); } const bool hasLog = currentItem && !currentItem->data(0, BuildLogRole).toString().isEmpty(); m_debuggingHelperUi->showLogButton->setEnabled(hasLog); const bool canBuild = canBuildQmlDumper; const bool isBuilding = isBuildingQmlDumper; m_debuggingHelperUi->rebuildButton->setEnabled(canBuild && !isBuilding); m_debuggingHelperUi->toolChainComboBox->setEnabled(canBuild && !isBuilding); setInfoWidgetVisibility(); } } // To be called if a Qt version was removed or added void QtOptionsPageWidget::updateCleanUpButton() { bool hasInvalidVersion = false; for (int i = 0; i < m_versions.count(); ++i) { if (!m_versions.at(i)->isValid()) { hasInvalidVersion = true; break; } } m_ui->cleanUpButton->setEnabled(hasInvalidVersion); } void QtOptionsPageWidget::userChangedCurrentVersion() { updateWidgets(); updateDescriptionLabel(); updateDebuggingHelperUi(); } void QtOptionsPageWidget::qtVersionChanged() { updateDescriptionLabel(); updateDebuggingHelperUi(); } void QtOptionsPageWidget::updateDescriptionLabel() { QTreeWidgetItem *item = m_ui->qtdirList->currentItem(); const BaseQtVersion *version = currentVersion(); const ValidityInfo info = validInformation(version); if (info.message.isEmpty()) { m_versionUi->errorLabel->setVisible(false); } else { m_versionUi->errorLabel->setVisible(true); m_versionUi->errorLabel->setText(info.message); m_versionUi->errorLabel->setToolTip(info.toolTip); } m_ui->infoWidget->setSummaryText(info.description); if (item) item->setIcon(0, info.icon); if (version) { m_infoBrowser->setHtml(version->toHtml(true)); setInfoWidgetVisibility(); } else { m_infoBrowser->clear(); m_ui->versionInfoWidget->setVisible(false); m_ui->infoWidget->setVisible(false); m_ui->debuggingHelperWidget->setVisible(false); } } int QtOptionsPageWidget::indexForTreeItem(const QTreeWidgetItem *item) const { if (!item || !item->parent()) return -1; const int uniqueId = item->data(0, VersionIdRole).toInt(); for (int index = 0; index < m_versions.size(); ++index) { if (m_versions.at(index)->uniqueId() == uniqueId) return index; } return -1; } QTreeWidgetItem *QtOptionsPageWidget::treeItemForIndex(int index) const { const int uniqueId = m_versions.at(index)->uniqueId(); for (int i = 0; i < m_ui->qtdirList->topLevelItemCount(); ++i) { QTreeWidgetItem *toplevelItem = m_ui->qtdirList->topLevelItem(i); for (int j = 0; j < toplevelItem->childCount(); ++j) { QTreeWidgetItem *item = toplevelItem->child(j); if (item->data(0, VersionIdRole).toInt() == uniqueId) return item; } } return 0; } void QtOptionsPageWidget::versionChanged(QTreeWidgetItem *newItem, QTreeWidgetItem *old) { Q_UNUSED(newItem); Q_UNUSED(old); userChangedCurrentVersion(); } void QtOptionsPageWidget::updateWidgets() { delete m_configurationWidget; m_configurationWidget = 0; BaseQtVersion *version = currentVersion(); if (version) { m_versionUi->nameEdit->setText(version->unexpandedDisplayName()); m_versionUi->qmakePath->setText(version->qmakeCommand().toUserOutput()); m_configurationWidget = version->createConfigurationWidget(); if (m_configurationWidget) { m_versionUi->formLayout->addRow(m_configurationWidget); m_configurationWidget->setEnabled(!version->isAutodetected()); connect(m_configurationWidget, SIGNAL(changed()), this, SLOT(qtVersionChanged())); } } else { m_versionUi->nameEdit->clear(); m_versionUi->qmakePath->clear(); } const bool enabled = version != 0; const bool isAutodetected = enabled && version->isAutodetected(); m_ui->delButton->setEnabled(enabled && !isAutodetected); m_versionUi->nameEdit->setEnabled(enabled); m_versionUi->editPathPushButton->setEnabled(enabled && !isAutodetected); } void QtOptionsPageWidget::updateCurrentQtName() { QTreeWidgetItem *currentItem = m_ui->qtdirList->currentItem(); Q_ASSERT(currentItem); int currentItemIndex = indexForTreeItem(currentItem); if (currentItemIndex < 0) return; BaseQtVersion *version = m_versions[currentItemIndex]; version->setUnexpandedDisplayName(m_versionUi->nameEdit->text()); updateDescriptionLabel(); foreach (BaseQtVersion *i, m_versions) updateVersionItem(i); } void QtOptionsPageWidget::apply() { disconnect(QtVersionManager::instance(), &QtVersionManager::qtVersionsChanged, this, &QtOptionsPageWidget::updateQtVersions); QtVersionManager::setNewQtVersions(versions()); connect(QtVersionManager::instance(), &QtVersionManager::qtVersionsChanged, this, &QtOptionsPageWidget::updateQtVersions); } QList<BaseQtVersion *> QtOptionsPageWidget::versions() const { QList<BaseQtVersion *> result; for (int i = 0; i < m_versions.count(); ++i) result.append(m_versions.at(i)->clone()); return result; } } // namespace Internal } // namespace QtSupport
martyone/sailfish-qtcreator
src/plugins/qtsupport/qtoptionspage.cpp
C++
lgpl-2.1
34,775
<?php /* * 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. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\DBAL\Schema; /** * Configuration for a Schema * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.0 * @author Benjamin Eberlei <kontakt@beberlei.de> */ class SchemaConfig { /** * @var bool */ protected $hasExplicitForeignKeyIndexes = false; /** * @var int */ protected $maxIdentifierLength = 63; /** * @var string */ protected $name; /** * @var array */ protected $defaultTableOptions = array(); /** * @return bool */ public function hasExplicitForeignKeyIndexes() { return $this->hasExplicitForeignKeyIndexes; } /** * @param bool $flag */ public function setExplicitForeignKeyIndexes($flag) { $this->hasExplicitForeignKeyIndexes = (bool)$flag; } /** * @param int $length */ public function setMaxIdentifierLength($length) { $this->maxIdentifierLength = (int)$length; } /** * @return int */ public function getMaxIdentifierLength() { return $this->maxIdentifierLength; } /** * Get default namespace of schema objects. * * @return string */ public function getName() { return $this->name; } /** * set default namespace name of schema objects. * * @param string $name the value to set. */ public function setName($name) { $this->name = $name; } /** * Get the default options that are passed to Table instances created with * Schema#createTable(). * * @return array */ public function getDefaultTableOptions() { return $this->defaultTableOptions; } public function setDefaultTableOptions(array $defaultTableOptions) { $this->defaultTableOptions = $defaultTableOptions; } }
PureBilling/dbal
lib/Doctrine/DBAL/Schema/SchemaConfig.php
PHP
lgpl-2.1
2,923
/* * Copyright (C) 2004, 2005, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org> * Copyright (C) 2004, 2005, 2006, 2007, 2008 Rob Buis <buis@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #if ENABLE(SVG) #include "SVGTextContentElement.h" #include "CSSPropertyNames.h" #include "CSSValueKeywords.h" #include "Frame.h" #include "FrameSelection.h" #include "RenderObject.h" #include "RenderSVGResource.h" #include "RenderSVGText.h" #include "SVGDocumentExtensions.h" #include "SVGElementInstance.h" #include "SVGNames.h" #include "SVGTextQuery.h" #include "XMLNames.h" namespace WebCore { // Define custom animated property 'textLength'. const SVGPropertyInfo* SVGTextContentElement::textLengthPropertyInfo() { static const SVGPropertyInfo* s_propertyInfo = 0; if (!s_propertyInfo) { s_propertyInfo = new SVGPropertyInfo(AnimatedLength, PropertyIsReadWrite, SVGNames::textLengthAttr, SVGNames::textLengthAttr.localName(), &SVGTextContentElement::synchronizeTextLength, &SVGTextContentElement::lookupOrCreateTextLengthWrapper); } return s_propertyInfo; } // Animated property definitions DEFINE_ANIMATED_ENUMERATION(SVGTextContentElement, SVGNames::lengthAdjustAttr, LengthAdjust, lengthAdjust, SVGLengthAdjustType) DEFINE_ANIMATED_BOOLEAN(SVGTextContentElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired) BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGTextContentElement) REGISTER_LOCAL_ANIMATED_PROPERTY(textLength) REGISTER_LOCAL_ANIMATED_PROPERTY(lengthAdjust) REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired) REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement) END_REGISTER_ANIMATED_PROPERTIES SVGTextContentElement::SVGTextContentElement(const QualifiedName& tagName, Document* document) : SVGGraphicsElement(tagName, document) , m_textLength(LengthModeOther) , m_specifiedTextLength(LengthModeOther) , m_lengthAdjust(SVGLengthAdjustSpacing) { registerAnimatedPropertiesForSVGTextContentElement(); } void SVGTextContentElement::synchronizeTextLength(SVGElement* contextElement) { ASSERT(contextElement); SVGTextContentElement* ownerType = toSVGTextContentElement(contextElement); if (!ownerType->m_textLength.shouldSynchronize) return; AtomicString value(SVGPropertyTraits<SVGLength>::toString(ownerType->m_specifiedTextLength)); ownerType->m_textLength.synchronize(ownerType, textLengthPropertyInfo()->attributeName, value); } PassRefPtr<SVGAnimatedProperty> SVGTextContentElement::lookupOrCreateTextLengthWrapper(SVGElement* contextElement) { ASSERT(contextElement); SVGTextContentElement* ownerType = toSVGTextContentElement(contextElement); return SVGAnimatedProperty::lookupOrCreateWrapper<SVGTextContentElement, SVGAnimatedLength, SVGLength> (ownerType, textLengthPropertyInfo(), ownerType->m_textLength.value); } PassRefPtr<SVGAnimatedLength> SVGTextContentElement::textLengthAnimated() { DEFINE_STATIC_LOCAL(SVGLength, defaultTextLength, (LengthModeOther)); if (m_specifiedTextLength == defaultTextLength) m_textLength.value.newValueSpecifiedUnits(LengthTypeNumber, getComputedTextLength(), ASSERT_NO_EXCEPTION); m_textLength.shouldSynchronize = true; return static_pointer_cast<SVGAnimatedLength>(lookupOrCreateTextLengthWrapper(this)); } unsigned SVGTextContentElement::getNumberOfChars() { document()->updateLayoutIgnorePendingStylesheets(); return SVGTextQuery(renderer()).numberOfCharacters(); } float SVGTextContentElement::getComputedTextLength() { document()->updateLayoutIgnorePendingStylesheets(); return SVGTextQuery(renderer()).textLength(); } float SVGTextContentElement::getSubStringLength(unsigned charnum, unsigned nchars, ExceptionCode& ec) { document()->updateLayoutIgnorePendingStylesheets(); unsigned numberOfChars = getNumberOfChars(); if (charnum >= numberOfChars) { ec = INDEX_SIZE_ERR; return 0.0f; } return SVGTextQuery(renderer()).subStringLength(charnum, nchars); } SVGPoint SVGTextContentElement::getStartPositionOfChar(unsigned charnum, ExceptionCode& ec) { document()->updateLayoutIgnorePendingStylesheets(); if (charnum > getNumberOfChars()) { ec = INDEX_SIZE_ERR; return SVGPoint(); } return SVGTextQuery(renderer()).startPositionOfCharacter(charnum); } SVGPoint SVGTextContentElement::getEndPositionOfChar(unsigned charnum, ExceptionCode& ec) { document()->updateLayoutIgnorePendingStylesheets(); if (charnum > getNumberOfChars()) { ec = INDEX_SIZE_ERR; return SVGPoint(); } return SVGTextQuery(renderer()).endPositionOfCharacter(charnum); } FloatRect SVGTextContentElement::getExtentOfChar(unsigned charnum, ExceptionCode& ec) { document()->updateLayoutIgnorePendingStylesheets(); if (charnum > getNumberOfChars()) { ec = INDEX_SIZE_ERR; return FloatRect(); } return SVGTextQuery(renderer()).extentOfCharacter(charnum); } float SVGTextContentElement::getRotationOfChar(unsigned charnum, ExceptionCode& ec) { document()->updateLayoutIgnorePendingStylesheets(); if (charnum > getNumberOfChars()) { ec = INDEX_SIZE_ERR; return 0.0f; } return SVGTextQuery(renderer()).rotationOfCharacter(charnum); } int SVGTextContentElement::getCharNumAtPosition(const SVGPoint& point) { document()->updateLayoutIgnorePendingStylesheets(); return SVGTextQuery(renderer()).characterNumberAtPosition(point); } void SVGTextContentElement::selectSubString(unsigned charnum, unsigned nchars, ExceptionCode& ec) { unsigned numberOfChars = getNumberOfChars(); if (charnum >= numberOfChars) { ec = INDEX_SIZE_ERR; return; } if (nchars > numberOfChars - charnum) nchars = numberOfChars - charnum; ASSERT(document()); ASSERT(document()->frame()); FrameSelection& selection = document()->frame()->selection(); // Find selection start VisiblePosition start(firstPositionInNode(const_cast<SVGTextContentElement*>(this))); for (unsigned i = 0; i < charnum; ++i) start = start.next(); // Find selection end VisiblePosition end(start); for (unsigned i = 0; i < nchars; ++i) end = end.next(); selection.setSelection(VisibleSelection(start, end)); } bool SVGTextContentElement::isSupportedAttribute(const QualifiedName& attrName) { DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ()); if (supportedAttributes.isEmpty()) { SVGLangSpace::addSupportedAttributes(supportedAttributes); SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes); supportedAttributes.add(SVGNames::lengthAdjustAttr); supportedAttributes.add(SVGNames::textLengthAttr); } return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName); } bool SVGTextContentElement::isPresentationAttribute(const QualifiedName& name) const { if (name.matches(XMLNames::spaceAttr)) return true; return SVGGraphicsElement::isPresentationAttribute(name); } void SVGTextContentElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style) { if (!isSupportedAttribute(name)) SVGGraphicsElement::collectStyleForPresentationAttribute(name, value, style); else if (name.matches(XMLNames::spaceAttr)) { DEFINE_STATIC_LOCAL(const AtomicString, preserveString, ("preserve", AtomicString::ConstructFromLiteral)); if (value == preserveString) addPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePre); else addPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValueNowrap); } } void SVGTextContentElement::parseAttribute(const QualifiedName& name, const AtomicString& value) { SVGParsingError parseError = NoError; if (!isSupportedAttribute(name)) SVGGraphicsElement::parseAttribute(name, value); else if (name == SVGNames::lengthAdjustAttr) { SVGLengthAdjustType propertyValue = SVGPropertyTraits<SVGLengthAdjustType>::fromString(value); if (propertyValue > 0) setLengthAdjustBaseValue(propertyValue); } else if (name == SVGNames::textLengthAttr) { m_textLength.value = SVGLength::construct(LengthModeOther, value, parseError, ForbidNegativeLengths); } else if (SVGExternalResourcesRequired::parseAttribute(name, value)) { } else if (SVGLangSpace::parseAttribute(name, value)) { } else ASSERT_NOT_REACHED(); reportAttributeParsingError(parseError, name, value); } void SVGTextContentElement::svgAttributeChanged(const QualifiedName& attrName) { if (!isSupportedAttribute(attrName)) { SVGGraphicsElement::svgAttributeChanged(attrName); return; } SVGElementInstance::InvalidationGuard invalidationGuard(this); if (attrName == SVGNames::textLengthAttr) m_specifiedTextLength = m_textLength.value; if (RenderObject* renderer = this->renderer()) RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer); } bool SVGTextContentElement::selfHasRelativeLengths() const { // Any element of the <text> subtree is advertized as using relative lengths. // On any window size change, we have to relayout the text subtree, as the // effective 'on-screen' font size may change. return true; } SVGTextContentElement* SVGTextContentElement::elementFromRenderer(RenderObject* renderer) { if (!renderer) return 0; if (!renderer->isSVGText() && !renderer->isSVGInline()) return 0; SVGElement* element = toSVGElement(renderer->node()); ASSERT(element); if (!element->isTextContent()) return 0; return toSVGTextContentElement(element); } } #endif // ENABLE(SVG)
KnightSwarm/WebKitTi
Source/WebCore/svg/SVGTextContentElement.cpp
C++
lgpl-2.1
10,922
package pl.grmdev.narutocraft.items.weapons; import net.minecraft.item.Item; import pl.grmdev.narutocraft.NarutoCraft; public class SmokeBomb extends Item { public SmokeBomb(){ this.setUnlocalizedName("SmokeBomb"); this.setCreativeTab(NarutoCraft.mTabNarutoCraft); this.maxStackSize = 64; } }
GRM-dev/Narutocraft-PL_Mod
src/main/java/pl/grmdev/narutocraft/items/weapons/SmokeBomb.java
Java
lgpl-2.1
318
package com.prowritingaid.client; public class TagAnalysisResponse { public String url; public int wordCount; public DocTag[] tags; public int numReports; public long requestId ; public String onreportsidebar; }
prowritingaid/openoffice-extension
src/main/java/com/prowritingaid/client/TagAnalysisResponse.java
Java
lgpl-2.1
261
package betteragriculture.client.render.mobs; import betteragriculture.entity.entitymob.EntityMobPig8; import net.minecraft.client.model.ModelPig; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.renderer.entity.layers.LayerHeldItem; import net.minecraft.util.ResourceLocation; public class RenderEntityMobPig8 extends RenderLiving<EntityMobPig8> { private final ResourceLocation textures = new ResourceLocation("betteragriculture:textures/models/pig8.png"); public RenderEntityMobPig8(RenderManager renderManager) { super(renderManager, new ModelPig(), 0); this.addLayer(new LayerHeldItem(this)); } @Override protected ResourceLocation getEntityTexture(EntityMobPig8 entity) { return textures; } }
nfinit-gaming/BetterAgriculture
src/main/java/betteragriculture/client/render/mobs/RenderEntityMobPig8.java
Java
lgpl-2.1
815
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2012, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.jca.sjc.maven; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.Serializable; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; /** * A deploy mojo * @author <a href="mailto:jesper.pedersen@ironjacamar.org">Jesper Pedersen</a> */ public class Deploy extends AbstractHostPortMojo { /** The file */ private File file; /** * Constructor */ public Deploy() { this.file = null; } /** * Set the file * @param v The value */ public void setFile(File v) { file = v; } /** * {@inheritDoc} */ public void execute() throws MojoExecutionException, MojoFailureException { if (file == null) throw new MojoFailureException("File not defined"); if (!file.exists()) throw new MojoFailureException("File doesn't exists: " + file); FileInputStream fis = null; try { Boolean result = null; if (isLocal()) { Object value = executeCommand("local-deploy", new Serializable[] {file.toURI().toURL()}); if (value instanceof Boolean) { result = (Boolean)value; } else { throw (Throwable)value; } } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); fis = new FileInputStream(file); int i = fis.read(); while (i != -1) { baos.write(i); i = fis.read(); } byte[] bytes = baos.toByteArray(); Object value = executeCommand("remote-deploy", new Serializable[] {file.getName(), bytes}); if (value instanceof Boolean) { result = (Boolean)value; } else { throw (Throwable)value; } } if (result.booleanValue()) { getLog().info("Deployed: " + file.getName()); } else { getLog().info(file.getName() + " wasn't deployed"); } } catch (Throwable t) { throw new MojoFailureException("Unable to deploy to " + getHost() + ":" + getPort() + " (" + t.getMessage() + ")", t); } finally { if (fis != null) { try { fis.close(); } catch (IOException ioe) { // Ignore } } } } }
ironjacamar/ironjacamar
sjc/src/main/java/org/jboss/jca/sjc/maven/Deploy.java
Java
lgpl-2.1
3,793
<?php namespace wcf\system\option\user\group; use wcf\system\option\TextOptionType; use wcf\util\StringUtil; /** * User group option type implementation for textual input fields. * * The merge of option values returns merge of all text values. * * @author Marcel Werk * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Option\User\Group */ class TextUserGroupOptionType extends TextOptionType implements IUserGroupOptionType { /** * @inheritDoc */ public function merge($defaultValue, $groupValue) { $defaultValue = empty($defaultValue) ? [] : explode("\n", StringUtil::unifyNewlines($defaultValue)); $groupValue = empty($groupValue) ? [] : explode("\n", StringUtil::unifyNewlines($groupValue)); return implode("\n", array_unique(array_merge($defaultValue, $groupValue))); } }
MenesesEvandro/WCF
wcfsetup/install/files/lib/system/option/user/group/TextUserGroupOptionType.class.php
PHP
lgpl-2.1
921
/* * Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * 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 Poly2Tri 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. */ #include "shapes.h" #include <iostream> #include <stdexcept> namespace p2t { Triangle::Triangle(Point& a, Point& b, Point& c) { points_[0] = &a; points_[1] = &b; points_[2] = &c; neighbors_[0] = NULL; neighbors_[1] = NULL; neighbors_[2] = NULL; constrained_edge[0] = constrained_edge[1] = constrained_edge[2] = false; delaunay_edge[0] = delaunay_edge[1] = delaunay_edge[2] = false; interior_ = false; } // Update neighbor pointers void Triangle::MarkNeighbor(Point* p1, Point* p2, Triangle* t) { if ((p1 == points_[2] && p2 == points_[1]) || (p1 == points_[1] && p2 == points_[2])) neighbors_[0] = t; else if ((p1 == points_[0] && p2 == points_[2]) || (p1 == points_[2] && p2 == points_[0])) neighbors_[1] = t; else if ((p1 == points_[0] && p2 == points_[1]) || (p1 == points_[1] && p2 == points_[0])) neighbors_[2] = t; else throw std::runtime_error("failed to MarkNeighbor"); } // Exhaustive search to update neighbor pointers void Triangle::MarkNeighbor(Triangle& t) { if (t.Contains(points_[1], points_[2])) { neighbors_[0] = &t; t.MarkNeighbor(points_[1], points_[2], this); } else if (t.Contains(points_[0], points_[2])) { neighbors_[1] = &t; t.MarkNeighbor(points_[0], points_[2], this); } else if (t.Contains(points_[0], points_[1])) { neighbors_[2] = &t; t.MarkNeighbor(points_[0], points_[1], this); } } /** * Clears all references to all other triangles and points */ void Triangle::Clear() { Triangle *t; for( int i=0; i<3; i++ ) { t = neighbors_[i]; if( t != NULL ) { t->ClearNeighbor( this ); } } ClearNeighbors(); points_[0]=points_[1]=points_[2] = NULL; } void Triangle::ClearNeighbor(Triangle *triangle ) { if( neighbors_[0] == triangle ) { neighbors_[0] = NULL; } else if( neighbors_[1] == triangle ) { neighbors_[1] = NULL; } else { neighbors_[2] = NULL; } } void Triangle::ClearNeighbors() { neighbors_[0] = NULL; neighbors_[1] = NULL; neighbors_[2] = NULL; } void Triangle::ClearDelunayEdges() { delaunay_edge[0] = delaunay_edge[1] = delaunay_edge[2] = false; } Point* Triangle::OppositePoint(Triangle& t, Point& p) { Point *cw = t.PointCW(p); //double x = cw->x; //double y = cw->y; //x = p.x; //y = p.y; assert(cw); return PointCW(*cw); } // Legalized triangle by rotating clockwise around point(0) void Triangle::Legalize(Point& point) { points_[1] = points_[0]; points_[0] = points_[2]; points_[2] = &point; } // Legalize triagnle by rotating clockwise around oPoint void Triangle::Legalize(Point& opoint, Point& npoint) { if (&opoint == points_[0]) { points_[1] = points_[0]; points_[0] = points_[2]; points_[2] = &npoint; } else if (&opoint == points_[1]) { points_[2] = points_[1]; points_[1] = points_[0]; points_[0] = &npoint; } else if (&opoint == points_[2]) { points_[0] = points_[2]; points_[2] = points_[1]; points_[1] = &npoint; } else { throw std::runtime_error("failed to Legalize"); } } int Triangle::Index(const Point* p) { if (p == points_[0]) { return 0; } else if (p == points_[1]) { return 1; } else if (p == points_[2]) { return 2; } throw std::runtime_error("failed to Index"); } int Triangle::EdgeIndex(const Point* p1, const Point* p2) { if (points_[0] == p1) { if (points_[1] == p2) { return 2; } else if (points_[2] == p2) { return 1; } } else if (points_[1] == p1) { if (points_[2] == p2) { return 0; } else if (points_[0] == p2) { return 2; } } else if (points_[2] == p1) { if (points_[0] == p2) { return 1; } else if (points_[1] == p2) { return 0; } } return -1; } void Triangle::MarkConstrainedEdge(const int index) { constrained_edge[index] = true; } void Triangle::MarkConstrainedEdge(Edge& edge) { MarkConstrainedEdge(edge.p, edge.q); } // Mark edge as constrained void Triangle::MarkConstrainedEdge(Point* p, Point* q) { if ((q == points_[0] && p == points_[1]) || (q == points_[1] && p == points_[0])) { constrained_edge[2] = true; } else if ((q == points_[0] && p == points_[2]) || (q == points_[2] && p == points_[0])) { constrained_edge[1] = true; } else if ((q == points_[1] && p == points_[2]) || (q == points_[2] && p == points_[1])) { constrained_edge[0] = true; } } // The point counter-clockwise to given point Point* Triangle::PointCW(Point& point) { if (&point == points_[0]) { return points_[2]; } else if (&point == points_[1]) { return points_[0]; } else if (&point == points_[2]) { return points_[1]; } throw std::runtime_error("failed in PointCW"); } // The point counter-clockwise to given point Point* Triangle::PointCCW(Point& point) { if (&point == points_[0]) { return points_[1]; } else if (&point == points_[1]) { return points_[2]; } else if (&point == points_[2]) { return points_[0]; } throw std::runtime_error("failed in PointCCW"); } // The neighbor clockwise to given point Triangle* Triangle::NeighborCW(Point& point) { if (&point == points_[0]) { return neighbors_[1]; } else if (&point == points_[1]) { return neighbors_[2]; } return neighbors_[0]; } // The neighbor counter-clockwise to given point Triangle* Triangle::NeighborCCW(Point& point) { if (&point == points_[0]) { return neighbors_[2]; } else if (&point == points_[1]) { return neighbors_[0]; } return neighbors_[1]; } bool Triangle::GetConstrainedEdgeCCW(Point& p) { if (&p == points_[0]) { return constrained_edge[2]; } else if (&p == points_[1]) { return constrained_edge[0]; } return constrained_edge[1]; } bool Triangle::GetConstrainedEdgeCW(Point& p) { if (&p == points_[0]) { return constrained_edge[1]; } else if (&p == points_[1]) { return constrained_edge[2]; } return constrained_edge[0]; } void Triangle::SetConstrainedEdgeCCW(Point& p, bool ce) { if (&p == points_[0]) { constrained_edge[2] = ce; } else if (&p == points_[1]) { constrained_edge[0] = ce; } else { constrained_edge[1] = ce; } } void Triangle::SetConstrainedEdgeCW(Point& p, bool ce) { if (&p == points_[0]) { constrained_edge[1] = ce; } else if (&p == points_[1]) { constrained_edge[2] = ce; } else { constrained_edge[0] = ce; } } bool Triangle::GetDelunayEdgeCCW(Point& p) { if (&p == points_[0]) { return delaunay_edge[2]; } else if (&p == points_[1]) { return delaunay_edge[0]; } return delaunay_edge[1]; } bool Triangle::GetDelunayEdgeCW(Point& p) { if (&p == points_[0]) { return delaunay_edge[1]; } else if (&p == points_[1]) { return delaunay_edge[2]; } return delaunay_edge[0]; } void Triangle::SetDelunayEdgeCCW(Point& p, bool e) { if (&p == points_[0]) { delaunay_edge[2] = e; } else if (&p == points_[1]) { delaunay_edge[0] = e; } else { delaunay_edge[1] = e; } } void Triangle::SetDelunayEdgeCW(Point& p, bool e) { if (&p == points_[0]) { delaunay_edge[1] = e; } else if (&p == points_[1]) { delaunay_edge[2] = e; } else { delaunay_edge[0] = e; } } // The neighbor across to given point Triangle& Triangle::NeighborAcross(Point& opoint) { if (&opoint == points_[0]) { return *neighbors_[0]; } else if (&opoint == points_[1]) { return *neighbors_[1]; } return *neighbors_[2]; } void Triangle::DebugPrint() { using namespace std; cout << points_[0]->x << "," << points_[0]->y << " "; cout << points_[1]->x << "," << points_[1]->y << " "; cout << points_[2]->x << "," << points_[2]->y << endl; } }
Oslandia/horao
src/poly2tri/common/shapes.cc
C++
lgpl-2.1
9,354
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Common")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Common")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("15fcb70e-9a51-4d36-a2bc-51541204eebe")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
spaghettidba/ExtendedTSQLCollector
ExtendedTSQLCollector/Common/Properties/AssemblyInfo.cs
C#
lgpl-2.1
1,388
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #define QT_NO_CAST_FROM_ASCII #include "lldbenginehost.h" #include "debuggerstartparameters.h" #include "debuggeractions.h" #include "debuggerconstants.h" #include "debuggerdialogs.h" #include "debuggerplugin.h" #include "debuggerstringutils.h" #include "breakhandler.h" #include "breakpoint.h" #include "moduleshandler.h" #include "registerhandler.h" #include "stackhandler.h" #include "watchhandler.h" #include "watchutils.h" #include "threadshandler.h" #include "disassembleragent.h" #include "memoryagent.h" #include <coreplugin/icore.h> #include <utils/qtcassert.h> #include <QDebug> #include <QProcess> #include <QFileInfo> #include <QThread> #include <QCoreApplication> namespace Debugger { namespace Internal { SshIODevice::SshIODevice(QSsh::SshRemoteProcessRunner *r) : runner(r) , buckethead(0) { setOpenMode(QIODevice::ReadWrite | QIODevice::Unbuffered); connect (runner, SIGNAL(processStarted()), this, SLOT(processStarted())); connect(runner, SIGNAL(readyReadStandardOutput()), this, SLOT(outputAvailable())); connect(runner, SIGNAL(readyReadStandardError()), this, SLOT(errorOutputAvailable())); } SshIODevice::~SshIODevice() { delete runner; } qint64 SshIODevice::bytesAvailable () const { qint64 r = QIODevice::bytesAvailable(); foreach (const QByteArray &bucket, buckets) r += bucket.size(); r-= buckethead; return r; } qint64 SshIODevice::writeData (const char * data, qint64 maxSize) { if (proc == 0) { startupbuffer += QByteArray::fromRawData(data, maxSize); return maxSize; } proc->write(data, maxSize); return maxSize; } qint64 SshIODevice::readData (char * data, qint64 maxSize) { if (proc == 0) return 0; qint64 size = maxSize; while (size > 0) { if (!buckets.size()) { return maxSize - size; } QByteArray &bucket = buckets.head(); if ((size + buckethead) >= bucket.size()) { int d = bucket.size() - buckethead; memcpy(data, bucket.data() + buckethead, d); data += d; size -= d; buckets.dequeue(); buckethead = 0; } else { memcpy(data, bucket.data() + buckethead, size); data += size; buckethead += size; size = 0; } } return maxSize - size; } void SshIODevice::processStarted() { runner->writeDataToProcess(startupbuffer); } void SshIODevice::outputAvailable() { buckets.enqueue(runner->readAllStandardOutput()); emit readyRead(); } void SshIODevice::errorOutputAvailable() { fprintf(stderr, "%s", runner->readAllStandardError().data()); } LldbEngineHost::LldbEngineHost(const DebuggerStartParameters &startParameters) :IPCEngineHost(startParameters), m_ssh(0) { showMessage(QLatin1String("setting up coms")); if (startParameters.startMode == StartRemoteEngine) { m_guestProcess = 0; QSsh::SshRemoteProcessRunner * const runner = new QSsh::SshRemoteProcessRunner; connect (runner, SIGNAL(connectionError(QSsh::SshError)), this, SLOT(sshConnectionError(QSsh::SshError))); runner->run(startParameters.serverStartScript.toUtf8(), startParameters.connParams); setGuestDevice(new SshIODevice(runner)); } else { m_guestProcess = new QProcess(this); connect(m_guestProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(finished(int,QProcess::ExitStatus))); connect(m_guestProcess, SIGNAL(readyReadStandardError()), this, SLOT(stderrReady())); QString a = Core::ICore::resourcePath() + QLatin1String("/qtcreator-lldb"); if(getenv("QTC_LLDB_GUEST") != 0) a = QString::fromLocal8Bit(getenv("QTC_LLDB_GUEST")); showStatusMessage(QString(QLatin1String("starting %1")).arg(a)); m_guestProcess->start(a, QStringList(), QIODevice::ReadWrite | QIODevice::Unbuffered); m_guestProcess->setReadChannel(QProcess::StandardOutput); if (!m_guestProcess->waitForStarted()) { showStatusMessage(tr("qtcreator-lldb failed to start: %1").arg(m_guestProcess->errorString())); notifyEngineSpontaneousShutdown(); return; } setGuestDevice(m_guestProcess); } } LldbEngineHost::~LldbEngineHost() { showMessage(QLatin1String("tear down qtcreator-lldb")); if (m_guestProcess) { disconnect(m_guestProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(finished(int,QProcess::ExitStatus))); m_guestProcess->terminate(); m_guestProcess->kill(); } if (m_ssh && m_ssh->isProcessRunning()) { // TODO: openssh doesn't do that m_ssh->sendSignalToProcess(QSsh::SshRemoteProcess::KillSignal); } } void LldbEngineHost::nuke() { stderrReady(); showMessage(QLatin1String("Nuke engaged. Bug in Engine/IPC or incompatible IPC versions. "), LogError); showStatusMessage(tr("Fatal engine shutdown. Consult debugger log for details.")); m_guestProcess->terminate(); m_guestProcess->kill(); notifyEngineSpontaneousShutdown(); } void LldbEngineHost::sshConnectionError(QSsh::SshError e) { showStatusMessage(tr("SSH connection error: %1").arg(e)); } void LldbEngineHost::finished(int, QProcess::ExitStatus status) { showMessage(QString(QLatin1String("guest went bye bye. exit status: %1 and code: %2")) .arg(status).arg(m_guestProcess->exitCode()), LogError); nuke(); } void LldbEngineHost::stderrReady() { fprintf(stderr,"%s", m_guestProcess->readAllStandardError().data()); } DebuggerEngine *createLldbEngine(const DebuggerStartParameters &startParameters) { return new LldbEngineHost(startParameters); } } // namespace Internal } // namespace Debugger
KDE/android-qt-creator
src/plugins/debugger/lldb/lldbenginehost.cpp
C++
lgpl-2.1
7,149
/* * Copyright 2014 The Solmix Project * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.gnu.org/licenses/ * or see the FSF site: http://www.fsf.org. */ package org.solmix.datax.support; import org.solmix.datax.RequestContext; import org.solmix.runtime.resource.support.ResourceResolverAdaptor; /** * * @author solmix.f@gmail.com * @version $Id$ 2015年7月26日 */ public class RequestContextResourceResolver extends ResourceResolverAdaptor { private final RequestContext context; public RequestContextResourceResolver(RequestContext context){ this.context=context; } @SuppressWarnings("unchecked") @Override public <T> T resolve(String resourceName, Class<T> resourceType) { if (resourceType == RequestContext.class) { return (T) context; } else if (context != null) { return context.get(resourceType); } return null; } }
solmix/datax
core/src/main/java/org/solmix/datax/support/RequestContextResourceResolver.java
Java
lgpl-2.1
1,570
<?php namespace phplug\plugins\phplug_core\annotations; class ReflectionAnnotatedClass extends \ReflectionClass { private $annotations; public function __construct($class) { parent::__construct($class); $this->annotations = $this->createAnnotationBuilder()->build($this); } public function hasAnnotation($class) { $class = AnnotationMap::getInstance()->getClass($class); return $this->annotations->hasAnnotation($class); } public function getAnnotation($annotation) { $class = AnnotationMap::getInstance()->getClass($annotation); return $this->annotations->getAnnotation($class); } public function getAnnotations() { return $this->annotations->getAnnotations(); } public function getAllAnnotations($restriction = false) { return $this->annotations->getAllAnnotations($restriction); } public function getConstructor() { return $this->createReflectionAnnotatedMethod(parent::getConstructor()); } public function getMethod($name) { return $this->createReflectionAnnotatedMethod(parent::getMethod($name)); } public function getMethods($filter = -1) { $result = array(); foreach(parent::getMethods($filter) as $method) { $result[] = $this->createReflectionAnnotatedMethod($method); } return $result; } public function getProperty($name) { return $this->createReflectionAnnotatedProperty(parent::getProperty($name)); } public function getProperties($filter = -1) { $result = array(); foreach(parent::getProperties($filter) as $property) { $result[] = $this->createReflectionAnnotatedProperty($property); } return $result; } public function getInterfaces() { $result = array(); foreach(parent::getInterfaces() as $interface) { $result[] = $this->createReflectionAnnotatedClass($interface); } return $result; } public function getParentClass() { $class = parent::getParentClass(); return $this->createReflectionAnnotatedClass($class); } protected function createAnnotationBuilder() { return new AnnotationsBuilder(); } private function createReflectionAnnotatedClass($class) { return ($class !== false) ? new ReflectionAnnotatedClass($class->getName()) : false; } private function createReflectionAnnotatedMethod($method) { return ($method !== null) ? new ReflectionAnnotatedMethod($this->getName(), $method->getName()) : null; } private function createReflectionAnnotatedProperty($property) { return ($property !== null) ? new ReflectionAnnotatedProperty($this->getName(), $property->getName()) : null; } }
thobens/PHPlug
plugins/phplug_core/annotations/ReflectionAnnotatedClass.php
PHP
lgpl-2.1
2,601
# Copyright (c) 2002 Zooko, blanu # This file is licensed under the # GNU Lesser General Public License v2.1. # See the file COPYING or visit http://www.gnu.org/ for details. __revision__ = "$Id: tristero.py,v 1.2 2002/12/02 19:58:54 myers_carpenter Exp $" nodeSchema='http://tristero.sourceforge.net/mnet/MetaTracker#' commSchema='http://tristero.sourceforge.net/mnet/CommStrategies#' lowerSchema='http://tristero.sourceforge.net/mnet/LowerStrategy#' pubkeySchema='http://tristero.sourceforge.net/mnet/Pubkey#' keyHeaderSchema='http://tristero.sourceforge.net/mnet/PubkeyHeader#' keyValueSchema='http://tristero.sourceforge.net/mnet/PubkeyValue#' LITERAL=0 RESOURCE=1 NODE=2
zooko/egtp_new
egtp/tristero.py
Python
lgpl-2.1
687
<?php class Article_Model extends CI_Model { function getArticleById($id) { $data=array(); $this->db->where('article_id',$id); $query=$this->db->get('article'); $row=$query->row(); if(isset($row)) { $data['article_id']=$row->article_id; $data['article_author_id']=$row->article_author_id; $data['article_type_id']=$row->article_type_id; $data['article_title']=$row->article_title; $data['article_introduction']=$row->article_introduction; $data['article_content']=$row->article_content; $data['article_posttime']=$row->article_posttime; $data['article_comment_nums']=$row->article_comment_nums; $data['article_view_nums']=$row->article_view_nums; $data['article_tags']=$row->article_tags; } return $data; } }
zhangbailong945/LoachBlog
application/models/loachblog/Article_Model.php
PHP
lgpl-2.1
882
/** * Copyright (C) 2010 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 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 Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.processor.impl; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.processor.Processor; import org.orbeon.oxf.processor.ProcessorImpl; import org.orbeon.oxf.processor.ProcessorInput; import org.orbeon.oxf.processor.ProcessorOutput; import org.orbeon.datatypes.LocationData; public class DelegatingProcessorInput implements ProcessorInput { private final String originalName; private ProcessorInput delegateInput; private ProcessorOutput delegateOutput; private ProcessorImpl processor; public DelegatingProcessorInput(ProcessorImpl processor, String originalName, ProcessorInput delegateInput, ProcessorOutput delegateOutput) { this.processor = processor; this.originalName = originalName; this.delegateInput = delegateInput; this.delegateOutput = delegateOutput; } DelegatingProcessorInput(ProcessorImpl processor, String originalName) { this.processor = processor; this.originalName = originalName; } public Processor getProcessor(PipelineContext pipelineContext) { return processor; } public void setDelegateInput(ProcessorInput delegateInput) { this.delegateInput = delegateInput; } public void setDelegateOutput(ProcessorOutput delegateOutput) { this.delegateOutput = delegateOutput; } public void setOutput(ProcessorOutput output) { delegateInput.setOutput(output); } public ProcessorOutput getOutput() { // Not sure why the input validation stuff expects another output here. For now, allow caller to specify // which output is returned. Once we are confident, switch to delegateInput.getOutput(). return delegateOutput; // return delegateInput.getOutput(); } public String getSchema() { return delegateInput.getSchema(); } public void setSchema(String schema) { delegateInput.setSchema(schema); } public Class getProcessorClass() { return processor.getClass(); } public String getName() { return originalName; } public void setDebug(String debugMessage) { delegateInput.setDebug(debugMessage); } public void setLocationData(LocationData locationData) { delegateInput.setLocationData(locationData); } public String getDebugMessage() { return delegateInput.getDebugMessage(); } public LocationData getLocationData() { return delegateInput.getLocationData(); } }
orbeon/orbeon-forms
src/main/java/org/orbeon/oxf/processor/impl/DelegatingProcessorInput.java
Java
lgpl-2.1
3,194
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "openeditorswindow.h" #include "openeditorsmodel.h" #include "editormanager.h" #include "editorview.h" #include "idocument.h" #include <utils/qtcassert.h> #include <QFocusEvent> #include <QHeaderView> #include <QTreeWidget> #include <QVBoxLayout> Q_DECLARE_METATYPE(Core::Internal::EditorView*) Q_DECLARE_METATYPE(Core::IDocument*) using namespace Core; using namespace Core::Internal; const int WIDTH = 300; const int HEIGHT = 200; OpenEditorsWindow::OpenEditorsWindow(QWidget *parent) : QFrame(parent, Qt::Popup), m_emptyIcon(QLatin1String(":/core/images/empty14.png")), m_editorList(new QTreeWidget(this)) { resize(QSize(WIDTH, HEIGHT)); m_editorList->setColumnCount(1); m_editorList->header()->hide(); m_editorList->setIndentation(0); m_editorList->setSelectionMode(QAbstractItemView::SingleSelection); m_editorList->setTextElideMode(Qt::ElideMiddle); #ifdef Q_OS_MAC m_editorList->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); #endif m_editorList->installEventFilter(this); // We disable the frame on this list view and use a QFrame around it instead. // This improves the look with QGTKStyle. #ifndef Q_OS_MAC setFrameStyle(m_editorList->frameStyle()); #endif m_editorList->setFrameStyle(QFrame::NoFrame); QVBoxLayout *layout = new QVBoxLayout(this); layout->setMargin(0); layout->addWidget(m_editorList); connect(m_editorList, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(editorClicked(QTreeWidgetItem*))); } void OpenEditorsWindow::selectAndHide() { setVisible(false); selectEditor(m_editorList->currentItem()); } void OpenEditorsWindow::setVisible(bool visible) { QWidget::setVisible(visible); if (visible) { setFocus(); } } bool OpenEditorsWindow::isCentering() { int internalMargin = m_editorList->viewport()->mapTo(m_editorList, QPoint(0,0)).y(); QRect rect0 = m_editorList->visualItemRect(m_editorList->topLevelItem(0)); QRect rect1 = m_editorList->visualItemRect(m_editorList->topLevelItem(m_editorList->topLevelItemCount()-1)); int height = rect1.y() + rect1.height() - rect0.y(); height += 2 * internalMargin; if (height > HEIGHT) return true; return false; } bool OpenEditorsWindow::eventFilter(QObject *obj, QEvent *e) { if (obj == m_editorList) { if (e->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent*>(e); if (ke->key() == Qt::Key_Escape) { setVisible(false); return true; } if (ke->key() == Qt::Key_Return) { selectEditor(m_editorList->currentItem()); return true; } } else if (e->type() == QEvent::KeyRelease) { QKeyEvent *ke = static_cast<QKeyEvent*>(e); if (ke->modifiers() == 0 /*HACK this is to overcome some event inconsistencies between platforms*/ || (ke->modifiers() == Qt::AltModifier && (ke->key() == Qt::Key_Alt || ke->key() == -1))) { selectAndHide(); } } } return QWidget::eventFilter(obj, e); } void OpenEditorsWindow::focusInEvent(QFocusEvent *) { m_editorList->setFocus(); } void OpenEditorsWindow::selectUpDown(bool up) { int itemCount = m_editorList->topLevelItemCount(); if (itemCount < 2) return; int index = m_editorList->indexOfTopLevelItem(m_editorList->currentItem()); if (index < 0) return; QTreeWidgetItem *editor = 0; int count = 0; while (!editor && count < itemCount) { if (up) { index--; if (index < 0) index = itemCount-1; } else { index++; if (index >= itemCount) index = 0; } editor = m_editorList->topLevelItem(index); count++; } if (editor) { m_editorList->setCurrentItem(editor); ensureCurrentVisible(); } } void OpenEditorsWindow::selectPreviousEditor() { selectUpDown(false); } void OpenEditorsWindow::selectNextEditor() { selectUpDown(true); } void OpenEditorsWindow::centerOnItem(int selectedIndex) { if (selectedIndex >= 0) { QTreeWidgetItem *item; int num = m_editorList->topLevelItemCount(); int rotate = selectedIndex-(num-1)/2; for (int i = 0; i < rotate; ++i) { item = m_editorList->takeTopLevelItem(0); m_editorList->addTopLevelItem(item); } rotate = -rotate; for (int i = 0; i < rotate; ++i) { item = m_editorList->takeTopLevelItem(num-1); m_editorList->insertTopLevelItem(0, item); } } } void OpenEditorsWindow::setEditors(EditorView *mainView, EditorView *view, OpenEditorsModel *model) { m_editorList->clear(); bool first = true; QSet<IDocument*> documentsDone; foreach (const EditLocation &hi, view->editorHistory()) { if (hi.document.isNull() || documentsDone.contains(hi.document)) continue; QString title = model->displayNameForDocument(hi.document); QTC_ASSERT(!title.isEmpty(), continue); documentsDone.insert(hi.document.data()); QTreeWidgetItem *item = new QTreeWidgetItem(); if (hi.document->isModified()) title += tr("*"); item->setIcon(0, !hi.document->fileName().isEmpty() && hi.document->isFileReadOnly() ? model->lockedIcon() : m_emptyIcon); item->setText(0, title); item->setToolTip(0, hi.document->fileName()); item->setData(0, Qt::UserRole, QVariant::fromValue(hi.document.data())); item->setData(0, Qt::UserRole+1, QVariant::fromValue(view)); item->setTextAlignment(0, Qt::AlignLeft); m_editorList->addTopLevelItem(item); if (first){ m_editorList->setCurrentItem(item); first = false; } } // add missing editors from the main view if (mainView != view) { foreach (const EditLocation &hi, mainView->editorHistory()) { if (hi.document.isNull() || documentsDone.contains(hi.document)) continue; documentsDone.insert(hi.document.data()); QTreeWidgetItem *item = new QTreeWidgetItem(); QString title = model->displayNameForDocument(hi.document); if (hi.document->isModified()) title += tr("*"); item->setIcon(0, !hi.document->fileName().isEmpty() && hi.document->isFileReadOnly() ? model->lockedIcon() : m_emptyIcon); item->setText(0, title); item->setToolTip(0, hi.document->fileName()); item->setData(0, Qt::UserRole, QVariant::fromValue(hi.document.data())); item->setData(0, Qt::UserRole+1, QVariant::fromValue(view)); item->setData(0, Qt::UserRole+2, QVariant::fromValue(hi.id)); item->setTextAlignment(0, Qt::AlignLeft); m_editorList->addTopLevelItem(item); if (first){ m_editorList->setCurrentItem(item); first = false; } } } // add purely restored editors which are not initialised yet foreach (const OpenEditorsModel::Entry &entry, model->entries()) { if (entry.editor) continue; QTreeWidgetItem *item = new QTreeWidgetItem(); QString title = entry.displayName(); item->setIcon(0, m_emptyIcon); item->setText(0, title); item->setToolTip(0, entry.fileName()); item->setData(0, Qt::UserRole+2, QVariant::fromValue(entry.id())); item->setTextAlignment(0, Qt::AlignLeft); m_editorList->addTopLevelItem(item); } } void OpenEditorsWindow::selectEditor(QTreeWidgetItem *item) { if (!item) return; if (IDocument *document = item->data(0, Qt::UserRole).value<IDocument*>()) { EditorView *view = item->data(0, Qt::UserRole+1).value<EditorView*>(); EditorManager::instance()->activateEditorForDocument(view, document, EditorManager::ModeSwitch); } else { if (!EditorManager::openEditor( item->toolTip(0), item->data(0, Qt::UserRole+2).value<Core::Id>(), Core::EditorManager::ModeSwitch)) { EditorManager::instance()->openedEditorsModel()->removeEditor(item->toolTip(0)); delete item; } } } void OpenEditorsWindow::editorClicked(QTreeWidgetItem *item) { selectEditor(item); setFocus(); } void OpenEditorsWindow::ensureCurrentVisible() { m_editorList->scrollTo(m_editorList->currentIndex(), QAbstractItemView::PositionAtCenter); }
KDE/android-qt-creator
src/plugins/coreplugin/editormanager/openeditorswindow.cpp
C++
lgpl-2.1
10,060
/* * Copyright © 2012 Intel Corporation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * * Author: Benjamin Segovia <benjamin.segovia@intel.com> */ #include "utest_helper.hpp" static void compiler_local_memory_two_ptr(void) { const size_t n = 1024; // Setup kernel and buffers OCL_CREATE_KERNEL("compiler_local_memory_two_ptr"); OCL_CREATE_BUFFER(buf[0], 0, n * sizeof(uint32_t), NULL); OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]); OCL_SET_ARG(1, 64, NULL); // 16 x int OCL_SET_ARG(2, 64, NULL); // 16 x int // Run the kernel globals[0] = n; locals[0] = 16; OCL_NDRANGE(1); OCL_MAP_BUFFER(0); // Check results int32_t *dst = (int32_t*)buf_data[0]; for (int32_t i = 0; i < (int) n; i+=16) for (int32_t j = 0; j < 16; ++j) { const int gid = i + j; const int tid = j; OCL_ASSERT(dst[i+j] == (gid&~0xf) + 15-tid + 15-tid); } } MAKE_UTEST_FROM_FUNCTION(compiler_local_memory_two_ptr);
ignatenkobrain/beignet
utests/compiler_local_memory_two_ptr.cpp
C++
lgpl-2.1
1,557
#ifndef __femus_enums_MarkerTypeEnum_hpp__ #define __femus_enums_MarkerTypeEnum_hpp__ enum MarkerType { VOLUME = 0, INTERSECTION, FIXED, BOUNDARY, INTERIOR }; #endif
eaulisa/MyFEMuS
src/enums/MarkerTypeEnum.hpp
C++
lgpl-2.1
180
/* * Part of the ROBOID project * Copyright (C) 2016 Kwang-Hyun Park (akaii@kw.ac.kr) and Kyoung Jin Kim * https://github.com/roboidstudio/embedded * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package org.roboid.studio.timeline.impl; import java.util.Arrays; import java.util.List; import javax.sound.sampled.AudioFormat; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.ui.views.properties.IPropertyDescriptor; import org.eclipse.ui.views.properties.PropertyDescriptor; import org.roboid.audio.AudioUtil; import org.roboid.robot.AudioMode; import org.roboid.robot.DataType; import org.roboid.robot.Device; import org.roboid.studio.timeline.AudioPoint; import org.roboid.studio.timeline.AudioTrack; import org.roboid.studio.timeline.ChannelTrack; import org.roboid.studio.timeline.ControlPoint; import org.roboid.studio.timeline.TimelineFactory; import org.roboid.studio.timeline.TimelinePackage; import org.roboid.studio.timeline.VoicePoint; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Audio Track</b></em>'. * @author Kyoung Jin Kim * @author Kwang-Hyun Park * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.roboid.studio.timeline.impl.AudioTrackImpl#getMode <em>Mode</em>}</li> * </ul> * </p> * * @generated */ public class AudioTrackImpl extends ChannelTrackImpl implements AudioTrack { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected AudioTrackImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return TimelinePackage.Literals.AUDIO_TRACK; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMode(AudioMode newMode) { AudioMode oldMode = mode; mode = newMode == null ? MODE_EDEFAULT : newMode; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TimelinePackage.AUDIO_TRACK__MODE, oldMode, mode)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case TimelinePackage.AUDIO_TRACK__MODE: return getMode(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case TimelinePackage.AUDIO_TRACK__MODE: setMode((AudioMode)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case TimelinePackage.AUDIO_TRACK__MODE: setMode(MODE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case TimelinePackage.AUDIO_TRACK__MODE: return mode != MODE_EDEFAULT; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (mode: "); result.append(mode); result.append(')'); return result.toString(); } /*===================================================================================== *===================================================================================== * MODIFIED *===================================================================================== *===================================================================================== */ /** * The default value of the '{@link #getMode() <em>Mode</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMode() * @generated NOT * @ordered */ protected static final AudioMode MODE_EDEFAULT = null; /** * The cached value of the '{@link #getMode() <em>Mode</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMode() * @generated * @ordered */ protected AudioMode mode = MODE_EDEFAULT; private static final String P_MODE = "_mode"; int[] wave; // temporary wave data for one frame private AudioFormat audioFormat; @Override protected void getPropertyDescriptors(List<IPropertyDescriptor> propertyDescriptors) { super.getPropertyDescriptors(propertyDescriptors); propertyDescriptors.add(new PropertyDescriptor(P_MODE, "Mode")); } @Override public Object getPropertyValue(Object id) { if(id.equals(P_CHANNEL)) return "Audio Channel"; if(id.equals(P_MODE)) return getMode().getLiteral(); if(id.equals(P_TARGET_DEVICE)) { Device left = getTargetDevice(0); if(left == null) return ""; Device right = getTargetDevice(1); if(right == null) return left.getName(); else return left.getName() + ", " + right.getName(); } return super.getPropertyValue(id); } @Override public ChannelTrack deepCopy() { AudioTrack newTrack = TimelineFactory.eINSTANCE.createAudioTrack(); copyTo(newTrack); return newTrack; } @Override public boolean canCopy(ControlPoint cp) { if(cp instanceof AudioPoint) return true; return false; } @Override public AudioPoint deepCopy(ControlPoint cp) { if(cp instanceof VoicePoint) { AudioPoint newPoint = TimelineFactory.eINSTANCE.createAudioPoint(); ((AudioPointImpl)cp).copyTo(newPoint); return newPoint; } else if(cp instanceof AudioPoint) return (AudioPoint)cp.deepCopy(); return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public AudioMode getMode() { if(mode == null) { if(getTargetDevices().size() == 1) mode = AudioMode.MONO; else mode = AudioMode.STEREO; } return mode; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public void setMode(int newMode) { AudioMode mode = AudioMode.get(newMode); if(mode != null) setMode(mode); } @Override public int getTotalFrames() { int maxFrame = 0; for(ControlPoint cp : getPoints()) { int frame = cp.getFrame() + ((AudioPoint)cp).getLength(); // start frame + length of frames if(maxFrame < frame) maxFrame = frame; } return maxFrame; } private AudioFormat getAudioFormatOfChannel(Device device) { // exception // support only BYTE, SHORT, INTEGER types if(!(device.getDataType().equals(DataType.BYTE) || device.getDataType().equals(DataType.SHORT) || device.getDataType().equals(DataType.INTEGER))) throw new IllegalArgumentException("The datatype of target device should be BYTE, SHORT or INTEGER only."); // format int sampleSizeInBits = device.getDataType().getValue(); int channels = (getMode() == AudioMode.STEREO) ? 2 : 1; int frameSize = ((sampleSizeInBits + 7) / 8) * channels; float sampleRate = 50 * device.getDataSize(); AudioFormat targetFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sampleRate, sampleSizeInBits, channels, frameSize, sampleRate, false); return targetFormat; } public void preLoad() { Device leftDevice = getTargetDevice(0); audioFormat = getAudioFormatOfChannel(leftDevice); for(ControlPoint cp : getPoints()) { ((AudioPoint)cp).getPcm(audioFormat); } } @Override public void dump(int frame) { if(getPoints().size() == 0) return; // no control points Device leftDevice = getTargetDevice(0); Device rightDevice = getTargetDevice(1); dump(frame, leftDevice, rightDevice); } /** * writes audio data at current frame to the corresponding device * * @param frame * @param leftDevice * @param rightDevice */ protected void dump(int frame, Device leftDevice, Device rightDevice) { if(leftDevice == null) return; // device format if(audioFormat == null) audioFormat = getAudioFormatOfChannel(leftDevice); // obtain audio data at current frame wave = getAudioData(frame, leftDevice, audioFormat); if(getMode() == AudioMode.MONO) { leftDevice.write(wave); } else { if(rightDevice == null) return; // stereo case AudioFormat rightDeviceFormat = getAudioFormatOfChannel(rightDevice); // exception // audio formats of two target devices should be same if(!AudioUtil.isEqual(audioFormat, rightDeviceFormat)) { throw new IllegalArgumentException("The type of two target audio devices should be the same: " + audioFormat + " and " + rightDeviceFormat); } // divide two channels into seperate arrays int stereo[][] = AudioUtil.splitChannel(wave, audioFormat.getChannels()); // write to each device leftDevice.write(stereo[1]); // IMPORTANT: exchange left and right rightDevice.write(stereo[0]); } } /** * returns audio data at current frame in target format * * @param frame * @param targetFormat * @return */ private int[] getAudioData(int frame, Device device, AudioFormat targetFormat) { int dataSize = device.getDataSize() * targetFormat.getChannels(); int maxValue = device.getMax();; int minValue = device.getMin(); if(wave == null) wave = new int[dataSize]; Arrays.fill(wave, 0); for(ControlPoint cp : getPoints()) { AudioPoint ap = (AudioPoint)cp; if(frame < ap.getFrame()) break; else if(frame >= ap.getFrame() + ap.getLength()) continue; int[] pcm = ap.getPcm(targetFormat); if(pcm == null) continue; // calculate offset of current frame in whole audio data int offset = (frame - ap.getFrame()) * dataSize; int len = pcm.length > offset + dataSize ? dataSize : pcm.length - offset; // apply volume to audio data AudioUtil.multiplyAndSum(pcm, offset, ap.getVolume()/100.0f, wave, 0, len, minValue, maxValue); } return wave; } } //AudioTrackImpl
roboidstudio/embedded
org.roboid.studio.timeline.model/src/org/roboid/studio/timeline/impl/AudioTrackImpl.java
Java
lgpl-2.1
10,917
// nextweb - modern web framework for Python and C++ // Copyright (C) 2011 Oleg Obolenskiy <highpower@yandex-team.ru> // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #ifndef NEXTWEB_UTILS_ITERATOR_HPP_INCLUDED #define NEXTWEB_UTILS_ITERATOR_HPP_INCLUDED #include <iterator> #include "nextweb/Config.hpp" namespace nextweb { namespace utils { template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference, typename Tag> struct IteratorBase; template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> struct IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag> { Pointer operator -> (); Reference operator * (); Derived& operator ++ (); Derived operator ++ (int); bool operator == (Derived const &other) const; bool operator != (Derived const &other) const; }; template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> struct IteratorBase<Derived, Type, Dist, Pointer, Reference, std::bidirectional_iterator_tag> : public IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag> { Derived& operator -- (); Derived operator -- (int); }; template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> struct IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag> : public IteratorBase<Derived, Type, Dist, Pointer, Reference, std::bidirectional_iterator_tag> { Derived operator + (Dist dist) const; Derived& operator += (Dist dist); Derived operator - (Dist dist) const; Derived& operator -= (Dist dist); Type operator [] (Dist dist) const; Dist operator - (Derived const &other) const; bool operator < (Derived const &other) const; bool operator > (Derived const &other) const; bool operator <= (Derived const &other) const; bool operator >= (Derived const &other) const; }; template <typename Derived, typename Tag, typename Type, typename Dist = std::ptrdiff_t, typename Pointer = Type*, typename Reference = Type&> struct Iterator : public IteratorBase<Derived, Type, Dist, Pointer, Reference, Tag>, public std::iterator<Tag, Type, Dist, Pointer, Reference> { }; template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived& IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator ++ () { Derived &object = static_cast<Derived&>(*this); object.increment(); return object; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator ++ (int) { Derived copy(static_cast<Derived const&>(*this)); ++(*this); return copy; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Pointer IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator -> () { Reference ref = static_cast<Derived*>(this)->dereference(); return &ref; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Reference IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator * () { return static_cast<Derived*>(this)->dereference(); } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator == (Derived const &other) const { return static_cast<Derived const*>(this)->equal(other); } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator != (Derived const &other) const { return !static_cast<Derived const*>(this)->equal(other); } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived& IteratorBase<Derived, Type, Dist, Pointer, Reference, std::bidirectional_iterator_tag>::operator -- () { Derived &object = static_cast<Derived&>(*this); object.decrement(); return object; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived IteratorBase<Derived, Type, Dist, Pointer, Reference, std::bidirectional_iterator_tag>::operator -- (int) { Derived copy(static_cast<Derived const&>(*this)); --(*this); return copy; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator + (Dist dist) const { Derived copy(static_cast<Derived const&>(*this)); copy += dist; return copy; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived& IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator += (Dist dist) { Derived &object = static_cast<Derived&>(*this); object.advance(dist); return object; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator - (Dist dist) const { Derived copy(static_cast<Derived const&>(*this)); copy -= dist; return copy; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived& IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator -= (Dist dist) { Derived &object = static_cast<Derived&>(*this); object.advance(-dist); return object; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Type IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator [] (Dist dist) const { Derived copy(static_cast<Derived const&>(*this)); copy += dist; return copy.dereference(); } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Dist IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator - (Derived const &other) const { return other.distance(static_cast<Derived const&>(*this)); } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator < (Derived const &other) const { return (static_cast<Derived const&>(*this) - other) < 0; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator > (Derived const &other) const { return (static_cast<Derived const&>(*this) - other) > 0; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator <= (Derived const &other) const { return (static_cast<Derived const&>(*this) - other) <= 0; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator >= (Derived const &other) const { return (static_cast<Derived const&>(*this) - other) >= 0; } }} // namespaces #endif // NEXTWEB_UTILS_ITERATOR_HPP_INCLUDED
tinybit/nextweb
include/nextweb/utils/Iterator.hpp
C++
lgpl-2.1
8,530
#include "libavoid/libavoid.h" using namespace Avoid; int main(void) { Router *router = new Router(OrthogonalRouting); router->setRoutingParameter((RoutingParameter)0, 10); router->setRoutingParameter((RoutingParameter)1, 0); router->setRoutingParameter((RoutingParameter)2, 1000); router->setRoutingParameter((RoutingParameter)3, 4000); router->setRoutingParameter((RoutingParameter)4, 0); router->setRoutingParameter((RoutingParameter)5, 100); router->setRoutingParameter((RoutingParameter)6, 1); router->setRoutingParameter((RoutingParameter)7, 10); router->setRoutingParameter(reverseDirectionPenalty, 500); router->setRoutingOption((RoutingOption)0, false); router->setRoutingOption((RoutingOption)1, true); router->setRoutingOption((RoutingOption)2, false); router->setRoutingOption((RoutingOption)3, false); router->setRoutingOption((RoutingOption)4, true); router->setRoutingOption((RoutingOption)5, true); Polygon polygon; ConnRef *connRef = NULL; ConnEnd srcPt; ConnEnd dstPt; PolyLine newRoute; // shapeRef1 polygon = Polygon(4); polygon.ps[0] = Point(0, 0); polygon.ps[1] = Point(0, 0); polygon.ps[2] = Point(0, 0); polygon.ps[3] = Point(0, 0); new ShapeRef(router, polygon, 1); // shapeRef2 polygon = Polygon(4); polygon.ps[0] = Point(0, 0); polygon.ps[1] = Point(0, 0); polygon.ps[2] = Point(0, 0); polygon.ps[3] = Point(0, 0); new ShapeRef(router, polygon, 2); // shapeRef3 polygon = Polygon(4); polygon.ps[0] = Point(0, 0); polygon.ps[1] = Point(0, 0); polygon.ps[2] = Point(0, 0); polygon.ps[3] = Point(0, 0); new ShapeRef(router, polygon, 3); // shapeRef4 polygon = Polygon(4); polygon.ps[0] = Point(0, 0); polygon.ps[1] = Point(0, 0); polygon.ps[2] = Point(0, 0); polygon.ps[3] = Point(0, 0); new ShapeRef(router, polygon, 4); // shapeRef5 polygon = Polygon(4); polygon.ps[0] = Point(501, 345); polygon.ps[1] = Point(501, 404); polygon.ps[2] = Point(421, 404); polygon.ps[3] = Point(421, 345); ShapeRef *shapeRef5 = new ShapeRef(router, polygon, 5); new ShapeConnectionPin(shapeRef5, 5, 1, 0.652542, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef5, 6, 0, 0.79096, true, 0, (ConnDirFlags) 4); new ShapeConnectionPin(shapeRef5, 7, 0, 0.514124, true, 0, (ConnDirFlags) 4); // shapeRef6 polygon = Polygon(4); polygon.ps[0] = Point(94, 251.5); polygon.ps[1] = Point(94, 315.5); polygon.ps[2] = Point(12, 315.5); polygon.ps[3] = Point(12, 251.5); ShapeRef *shapeRef6 = new ShapeRef(router, polygon, 6); new ShapeConnectionPin(shapeRef6, 8, 1, 0.640625, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef6, 9, 0, 0.640625, true, 0, (ConnDirFlags) 4); // shapeRef7 polygon = Polygon(4); polygon.ps[0] = Point(634.366, 262); polygon.ps[1] = Point(634.366, 305); polygon.ps[2] = Point(416.366, 305); polygon.ps[3] = Point(416.366, 262); ShapeRef *shapeRef7 = new ShapeRef(router, polygon, 7); new ShapeConnectionPin(shapeRef7, 10, 1, 0.709302, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef7, 11, 0, 0.709302, true, 0, (ConnDirFlags) 4); // shapeRef8 polygon = Polygon(4); polygon.ps[0] = Point(324, 147.167); polygon.ps[1] = Point(324, 206.167); polygon.ps[2] = Point(236, 206.167); polygon.ps[3] = Point(236, 147.167); ShapeRef *shapeRef8 = new ShapeRef(router, polygon, 8); new ShapeConnectionPin(shapeRef8, 12, 1, 0.652542, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef8, 13, 0, 0.79096, true, 0, (ConnDirFlags) 4); new ShapeConnectionPin(shapeRef8, 14, 0, 0.514124, true, 0, (ConnDirFlags) 4); // shapeRef9 polygon = Polygon(4); polygon.ps[0] = Point(816, 353.167); polygon.ps[1] = Point(816, 412.167); polygon.ps[2] = Point(735, 412.167); polygon.ps[3] = Point(735, 353.167); ShapeRef *shapeRef9 = new ShapeRef(router, polygon, 9); new ShapeConnectionPin(shapeRef9, 15, 1, 0.514124, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef9, 16, 1, 0.79096, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef9, 17, 0, 0.79096, true, 0, (ConnDirFlags) 4); new ShapeConnectionPin(shapeRef9, 18, 0, 0.514124, true, 0, (ConnDirFlags) 4); // shapeRef10 polygon = Polygon(4); polygon.ps[0] = Point(981, 263.833); polygon.ps[1] = Point(981, 321.833); polygon.ps[2] = Point(828, 321.833); polygon.ps[3] = Point(828, 263.833); ShapeRef *shapeRef10 = new ShapeRef(router, polygon, 10); new ShapeConnectionPin(shapeRef10, 19, 0, 0.655172, true, 0, (ConnDirFlags) 4); // shapeRef11 polygon = Polygon(4); polygon.ps[0] = Point(1011.49, 361.833); polygon.ps[1] = Point(1011.49, 419.833); polygon.ps[2] = Point(834.489, 419.833); polygon.ps[3] = Point(834.489, 361.833); ShapeRef *shapeRef11 = new ShapeRef(router, polygon, 11); new ShapeConnectionPin(shapeRef11, 20, 0, 0.655172, true, 0, (ConnDirFlags) 4); // shapeRef12 polygon = Polygon(4); polygon.ps[0] = Point(511, 155.333); polygon.ps[1] = Point(511, 214.333); polygon.ps[2] = Point(422, 214.333); polygon.ps[3] = Point(422, 155.333); ShapeRef *shapeRef12 = new ShapeRef(router, polygon, 12); new ShapeConnectionPin(shapeRef12, 21, 1, 0.514124, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef12, 22, 1, 0.79096, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef12, 23, 0, 0.79096, true, 0, (ConnDirFlags) 4); new ShapeConnectionPin(shapeRef12, 24, 0, 0.514124, true, 0, (ConnDirFlags) 4); // shapeRef13 polygon = Polygon(4); polygon.ps[0] = Point(690, 66); polygon.ps[1] = Point(690, 124); polygon.ps[2] = Point(523, 124); polygon.ps[3] = Point(523, 66); ShapeRef *shapeRef13 = new ShapeRef(router, polygon, 13); new ShapeConnectionPin(shapeRef13, 25, 0, 0.655172, true, 0, (ConnDirFlags) 4); // shapeRef14 polygon = Polygon(4); polygon.ps[0] = Point(720.212, 164); polygon.ps[1] = Point(720.212, 222); polygon.ps[2] = Point(529.212, 222); polygon.ps[3] = Point(529.212, 164); ShapeRef *shapeRef14 = new ShapeRef(router, polygon, 14); new ShapeConnectionPin(shapeRef14, 26, 0, 0.655172, true, 0, (ConnDirFlags) 4); // shapeRef15 polygon = Polygon(4); polygon.ps[0] = Point(217, 336.833); polygon.ps[1] = Point(217, 395.833); polygon.ps[2] = Point(98, 395.833); polygon.ps[3] = Point(98, 336.833); ShapeRef *shapeRef15 = new ShapeRef(router, polygon, 15); new ShapeConnectionPin(shapeRef15, 27, 1, 0.652542, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef15, 28, 0, 0.652542, true, 0, (ConnDirFlags) 4); // shapeRef16 polygon = Polygon(4); polygon.ps[0] = Point(413, 147.167); polygon.ps[1] = Point(413, 206.167); polygon.ps[2] = Point(336, 206.167); polygon.ps[3] = Point(336, 147.167); ShapeRef *shapeRef16 = new ShapeRef(router, polygon, 16); new ShapeConnectionPin(shapeRef16, 29, 1, 0.652542, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef16, 30, 0, 0.652542, true, 0, (ConnDirFlags) 4); // shapeRef17 polygon = Polygon(4); polygon.ps[0] = Point(306, 336.833); polygon.ps[1] = Point(306, 395.833); polygon.ps[2] = Point(229, 395.833); polygon.ps[3] = Point(229, 336.833); ShapeRef *shapeRef17 = new ShapeRef(router, polygon, 17); new ShapeConnectionPin(shapeRef17, 31, 1, 0.652542, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef17, 32, 0, 0.652542, true, 0, (ConnDirFlags) 4); // shapeRef18 polygon = Polygon(4); polygon.ps[0] = Point(175, 139); polygon.ps[1] = Point(175, 198); polygon.ps[2] = Point(98, 198); polygon.ps[3] = Point(98, 139); ShapeRef *shapeRef18 = new ShapeRef(router, polygon, 18); new ShapeConnectionPin(shapeRef18, 33, 1, 0.652542, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef18, 34, 0, 0.652542, true, 0, (ConnDirFlags) 4); // shapeRef19 polygon = Polygon(4); polygon.ps[0] = Point(409, 399.333); polygon.ps[1] = Point(409, 458.333); polygon.ps[2] = Point(298, 458.333); polygon.ps[3] = Point(298, 399.333); ShapeRef *shapeRef19 = new ShapeRef(router, polygon, 19); new ShapeConnectionPin(shapeRef19, 35, 1, 0.652542, true, 0, (ConnDirFlags) 8); // shapeRef20 polygon = Polygon(4); polygon.ps[0] = Point(224, 40); polygon.ps[1] = Point(224, 99); polygon.ps[2] = Point(106, 99); polygon.ps[3] = Point(106, 40); ShapeRef *shapeRef20 = new ShapeRef(router, polygon, 20); new ShapeConnectionPin(shapeRef20, 36, 1, 0.652542, true, 0, (ConnDirFlags) 8); // shapeRef21 polygon = Polygon(4); polygon.ps[0] = Point(604, 345); polygon.ps[1] = Point(604, 404); polygon.ps[2] = Point(513, 404); polygon.ps[3] = Point(513, 345); ShapeRef *shapeRef21 = new ShapeRef(router, polygon, 21); new ShapeConnectionPin(shapeRef21, 37, 1, 0.652542, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef21, 38, 0, 0.652542, true, 0, (ConnDirFlags) 4); // connRef1 connRef = new ConnRef(router, 1); srcPt = ConnEnd(shapeRef5, 5); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef21, 38); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef2 connRef = new ConnRef(router, 2); srcPt = ConnEnd(shapeRef6, 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef18, 34); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef3 connRef = new ConnRef(router, 3); srcPt = ConnEnd(shapeRef6, 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef15, 28); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef4 connRef = new ConnRef(router, 4); srcPt = ConnEnd(shapeRef6, 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef12, 23); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef5 connRef = new ConnRef(router, 5); srcPt = ConnEnd(shapeRef6, 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef7, 11); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef6 connRef = new ConnRef(router, 6); srcPt = ConnEnd(shapeRef7, 10); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef9, 17); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); ConnRef *connector6 = connRef; // connRef7 connRef = new ConnRef(router, 7); srcPt = ConnEnd(shapeRef8, 12); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef16, 30); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef8 connRef = new ConnRef(router, 8); srcPt = ConnEnd(shapeRef9, 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef10, 19); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef9 connRef = new ConnRef(router, 9); srcPt = ConnEnd(shapeRef9, 16); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef11, 20); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef10 connRef = new ConnRef(router, 10); srcPt = ConnEnd(shapeRef12, 21); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef13, 25); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef11 connRef = new ConnRef(router, 11); srcPt = ConnEnd(shapeRef12, 22); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef14, 26); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef12 connRef = new ConnRef(router, 12); srcPt = ConnEnd(shapeRef15, 27); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef17, 32); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef13 connRef = new ConnRef(router, 13); srcPt = ConnEnd(shapeRef16, 29); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef12, 24); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef14 connRef = new ConnRef(router, 14); srcPt = ConnEnd(shapeRef17, 31); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef5, 7); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef15 connRef = new ConnRef(router, 15); srcPt = ConnEnd(shapeRef18, 33); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef8, 14); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef16 connRef = new ConnRef(router, 16); srcPt = ConnEnd(shapeRef19, 35); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef5, 7); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef17 connRef = new ConnRef(router, 17); srcPt = ConnEnd(shapeRef20, 36); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef8, 14); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef18 connRef = new ConnRef(router, 18); srcPt = ConnEnd(shapeRef21, 37); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef9, 18); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); router->processTransaction(); // Test that connector 6 has three segments and doesnt loop right // around the shapes on the right due to the crossing penalty. bool suceeds = (connector6->displayRoute().size() == 4); //router->outputInstanceToSVG("output/forwardFlowingConnectors01"); delete router; return (suceeds ? 0 : 1); };
oliverchang/libavoid
tests/forwardFlowingConnectors01.cpp
C++
lgpl-2.1
14,496
export function convertRawMessage(rawMessage, currentThreadID) { return { ...rawMessage, date: new Date(rawMessage.timestamp), isRead: rawMessage.threadID === currentThreadID }; }; export function getCreatedMessageData(text, currentThreadID) { var timestamp = Date.now(); return { id: 'm_' + timestamp, threadID: currentThreadID, authorName: 'You', date: new Date(timestamp), text: text, isRead: true, type: 'message' }; }; export function getSUSIMessageData(message, currentThreadID) { var timestamp = Date.now(); let receivedMessage = { id: 'm_' + timestamp, threadID: currentThreadID, authorName: 'SUSI', // hard coded for the example text: message.text, response: message.response, actions: message.actions, websearchresults: message.websearchresults, date: new Date(timestamp), isRead: true, responseTime: message.responseTime, type: 'message' }; return receivedMessage; }
DravitLochan/accounts.susi.ai
src/utils/ChatMessageUtils.js
JavaScript
lgpl-2.1
986
package soot.coffi; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 Clark Verbrugge * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * Instruction subclasses are used to represent parsed bytecode; each bytecode operation has a corresponding subclass of * Instruction. * <p> * Each subclass is derived from one of * <ul> * <li>Instruction</li> * <li>Instruction_noargs (an Instruction with no embedded arguments)</li> * <li>Instruction_byte (an Instruction with a single byte data argument)</li> * <li>Instruction_bytevar (a byte argument specifying a local variable)</li> * <li>Instruction_byteindex (a byte argument specifying a constant pool index)</li> * <li>Instruction_int (an Instruction with a single short data argument)</li> * <li>Instruction_intvar (a short argument specifying a local variable)</li> * <li>Instruction_intindex (a short argument specifying a constant pool index)</li> * <li>Instruction_intbranch (a short argument specifying a code offset)</li> * <li>Instruction_longbranch (an int argument specifying a code offset)</li> * </ul> * * @author Clark Verbrugge * @see Instruction * @see Instruction_noargs * @see Instruction_byte * @see Instruction_bytevar * @see Instruction_byteindex * @see Instruction_int * @see Instruction_intvar * @see Instruction_intindex * @see Instruction_intbranch * @see Instruction_longbranch * @see Instruction_Unknown */ class Instruction_If_icmpge extends Instruction_intbranch { public Instruction_If_icmpge() { super((byte) ByteCode.IF_ICMPGE); name = "if_icmpge"; } }
plast-lab/soot
src/main/java/soot/coffi/Instruction_If_icmpge.java
Java
lgpl-2.1
2,261
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ /*! \class QGraphicsSceneIndex \brief The QGraphicsSceneIndex class provides a base class to implement a custom indexing algorithm for discovering items in QGraphicsScene. \since 4.6 \ingroup graphicsview-api \internal The QGraphicsSceneIndex class provides a base class to implement a custom indexing algorithm for discovering items in QGraphicsScene. You need to subclass it and reimplement addItem, removeItem, estimateItems and items in order to have an functional indexing. \sa QGraphicsScene, QGraphicsView */ #include "qdebug.h" #include "qgraphicsscene.h" #include "qgraphicsitem_p.h" #include "qgraphicsscene_p.h" #include "qgraphicswidget.h" #include "qgraphicssceneindex_p.h" #include "qgraphicsscenebsptreeindex_p.h" #ifndef QT_NO_GRAPHICSVIEW QT_BEGIN_NAMESPACE class QGraphicsSceneIndexRectIntersector : public QGraphicsSceneIndexIntersector { public: bool intersect(const QGraphicsItem *item, const QRectF &exposeRect, Qt::ItemSelectionMode mode, const QTransform &deviceTransform) const { QRectF brect = item->boundingRect(); _q_adjustRect(&brect); // ### Add test for this (without making things slower?) Q_UNUSED(exposeRect); bool keep = true; const QGraphicsItemPrivate *itemd = QGraphicsItemPrivate::get(item); if (itemd->itemIsUntransformable()) { // Untransformable items; map the scene rect to item coordinates. const QTransform transform = item->deviceTransform(deviceTransform); QRectF itemRect = (deviceTransform * transform.inverted()).mapRect(sceneRect); if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect) keep = itemRect.contains(brect) && itemRect != brect; else keep = itemRect.intersects(brect); if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) { QPainterPath itemPath; itemPath.addRect(itemRect); keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, itemPath, mode); } } else { Q_ASSERT(!itemd->dirtySceneTransform); const QRectF itemSceneBoundingRect = itemd->sceneTransformTranslateOnly ? brect.translated(itemd->sceneTransform.dx(), itemd->sceneTransform.dy()) : itemd->sceneTransform.mapRect(brect); if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect) keep = sceneRect != brect && sceneRect.contains(itemSceneBoundingRect); else keep = sceneRect.intersects(itemSceneBoundingRect); if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) { QPainterPath rectPath; rectPath.addRect(sceneRect); if (itemd->sceneTransformTranslateOnly) rectPath.translate(-itemd->sceneTransform.dx(), -itemd->sceneTransform.dy()); else rectPath = itemd->sceneTransform.inverted().map(rectPath); keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, rectPath, mode); } } return keep; } QRectF sceneRect; }; class QGraphicsSceneIndexPointIntersector : public QGraphicsSceneIndexIntersector { public: bool intersect(const QGraphicsItem *item, const QRectF &exposeRect, Qt::ItemSelectionMode mode, const QTransform &deviceTransform) const { QRectF brect = item->boundingRect(); _q_adjustRect(&brect); // ### Add test for this (without making things slower?) Q_UNUSED(exposeRect); bool keep = false; const QGraphicsItemPrivate *itemd = QGraphicsItemPrivate::get(item); if (itemd->itemIsUntransformable()) { // Untransformable items; map the scene point to item coordinates. const QTransform transform = item->deviceTransform(deviceTransform); QPointF itemPoint = (deviceTransform * transform.inverted()).map(scenePoint); keep = brect.contains(itemPoint); if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) { QPainterPath pointPath; pointPath.addRect(QRectF(itemPoint, QSizeF(1, 1))); keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, pointPath, mode); } } else { Q_ASSERT(!itemd->dirtySceneTransform); QRectF sceneBoundingRect = itemd->sceneTransformTranslateOnly ? brect.translated(itemd->sceneTransform.dx(), itemd->sceneTransform.dy()) : itemd->sceneTransform.mapRect(brect); keep = sceneBoundingRect.intersects(QRectF(scenePoint, QSizeF(1, 1))); if (keep) { QPointF p = itemd->sceneTransformTranslateOnly ? QPointF(scenePoint.x() - itemd->sceneTransform.dx(), scenePoint.y() - itemd->sceneTransform.dy()) : itemd->sceneTransform.inverted().map(scenePoint); keep = item->contains(p); } } return keep; } QPointF scenePoint; }; class QGraphicsSceneIndexPathIntersector : public QGraphicsSceneIndexIntersector { public: bool intersect(const QGraphicsItem *item, const QRectF &exposeRect, Qt::ItemSelectionMode mode, const QTransform &deviceTransform) const { QRectF brect = item->boundingRect(); _q_adjustRect(&brect); // ### Add test for this (without making things slower?) Q_UNUSED(exposeRect); bool keep = true; const QGraphicsItemPrivate *itemd = QGraphicsItemPrivate::get(item); if (itemd->itemIsUntransformable()) { // Untransformable items; map the scene rect to item coordinates. const QTransform transform = item->deviceTransform(deviceTransform); QPainterPath itemPath = (deviceTransform * transform.inverted()).map(scenePath); if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect) keep = itemPath.contains(brect); else keep = itemPath.intersects(brect); if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, itemPath, mode); } else { Q_ASSERT(!itemd->dirtySceneTransform); const QRectF itemSceneBoundingRect = itemd->sceneTransformTranslateOnly ? brect.translated(itemd->sceneTransform.dx(), itemd->sceneTransform.dy()) : itemd->sceneTransform.mapRect(brect); if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect) keep = scenePath.contains(itemSceneBoundingRect); else keep = scenePath.intersects(itemSceneBoundingRect); if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) { QPainterPath itemPath = itemd->sceneTransformTranslateOnly ? scenePath.translated(-itemd->sceneTransform.dx(), -itemd->sceneTransform.dy()) : itemd->sceneTransform.inverted().map(scenePath); keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, itemPath, mode); } } return keep; } QPainterPath scenePath; }; /*! Constructs a private scene index. */ QGraphicsSceneIndexPrivate::QGraphicsSceneIndexPrivate(QGraphicsScene *scene) : scene(scene) { pointIntersector = new QGraphicsSceneIndexPointIntersector; rectIntersector = new QGraphicsSceneIndexRectIntersector; pathIntersector = new QGraphicsSceneIndexPathIntersector; } /*! Destructor of private scene index. */ QGraphicsSceneIndexPrivate::~QGraphicsSceneIndexPrivate() { delete pointIntersector; delete rectIntersector; delete pathIntersector; } /*! \internal Checks if item collides with the path and mode, but also checks that if it doesn't collide, maybe its frame rect will. */ bool QGraphicsSceneIndexPrivate::itemCollidesWithPath(const QGraphicsItem *item, const QPainterPath &path, Qt::ItemSelectionMode mode) { if (item->collidesWithPath(path, mode)) return true; if (item->isWidget()) { // Check if this is a window, and if its frame rect collides. const QGraphicsWidget *widget = static_cast<const QGraphicsWidget *>(item); if (widget->isWindow()) { QRectF frameRect = widget->windowFrameRect(); QPainterPath framePath; framePath.addRect(frameRect); bool intersects = path.intersects(frameRect); if (mode == Qt::IntersectsItemShape || mode == Qt::IntersectsItemBoundingRect) return intersects || path.contains(frameRect.topLeft()) || framePath.contains(path.elementAt(0)); return !intersects && path.contains(frameRect.topLeft()); } } return false; } /*! \internal This function returns the items in ascending order. */ void QGraphicsSceneIndexPrivate::recursive_items_helper(QGraphicsItem *item, QRectF exposeRect, QGraphicsSceneIndexIntersector *intersector, QList<QGraphicsItem *> *items, const QTransform &viewTransform, Qt::ItemSelectionMode mode, qreal parentOpacity) const { Q_ASSERT(item); if (!item->d_ptr->visible) return; const qreal opacity = item->d_ptr->combineOpacityFromParent(parentOpacity); const bool itemIsFullyTransparent = (opacity < 0.0001); const bool itemHasChildren = !item->d_ptr->children.isEmpty(); if (itemIsFullyTransparent && (!itemHasChildren || item->d_ptr->childrenCombineOpacity())) return; // Update the item's scene transform if dirty. const bool itemIsUntransformable = item->d_ptr->itemIsUntransformable(); const bool wasDirtyParentSceneTransform = item->d_ptr->dirtySceneTransform && !itemIsUntransformable; if (wasDirtyParentSceneTransform) { item->d_ptr->updateSceneTransformFromParent(); Q_ASSERT(!item->d_ptr->dirtySceneTransform); } const bool itemClipsChildrenToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape); bool processItem = !itemIsFullyTransparent; if (processItem) { processItem = intersector->intersect(item, exposeRect, mode, viewTransform); if (!processItem && (!itemHasChildren || itemClipsChildrenToShape)) { if (wasDirtyParentSceneTransform) item->d_ptr->invalidateChildrenSceneTransform(); return; } } // else we know for sure this item has children we must process. int i = 0; if (itemHasChildren) { // Sort children. item->d_ptr->ensureSortedChildren(); // Clip to shape. if (itemClipsChildrenToShape && !itemIsUntransformable) { QPainterPath mappedShape = item->d_ptr->sceneTransformTranslateOnly ? item->shape().translated(item->d_ptr->sceneTransform.dx(), item->d_ptr->sceneTransform.dy()) : item->d_ptr->sceneTransform.map(item->shape()); exposeRect &= mappedShape.controlPointRect(); } // Process children behind for (i = 0; i < item->d_ptr->children.size(); ++i) { QGraphicsItem *child = item->d_ptr->children.at(i); if (wasDirtyParentSceneTransform) child->d_ptr->dirtySceneTransform = 1; if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent)) break; if (itemIsFullyTransparent && !(child->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity)) continue; recursive_items_helper(child, exposeRect, intersector, items, viewTransform, mode, opacity); } } // Process item if (processItem) items->append(item); // Process children in front if (itemHasChildren) { for (; i < item->d_ptr->children.size(); ++i) { QGraphicsItem *child = item->d_ptr->children.at(i); if (wasDirtyParentSceneTransform) child->d_ptr->dirtySceneTransform = 1; if (itemIsFullyTransparent && !(child->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity)) continue; recursive_items_helper(child, exposeRect, intersector, items, viewTransform, mode, opacity); } } } void QGraphicsSceneIndexPrivate::init() { if (!scene) return; QObject::connect(scene, SIGNAL(sceneRectChanged(QRectF)), q_func(), SLOT(updateSceneRect(QRectF))); } /*! Constructs an abstract scene index for a given \a scene. */ QGraphicsSceneIndex::QGraphicsSceneIndex(QGraphicsScene *scene) : QObject(*new QGraphicsSceneIndexPrivate(scene), scene) { d_func()->init(); } /*! \internal */ QGraphicsSceneIndex::QGraphicsSceneIndex(QGraphicsSceneIndexPrivate &dd, QGraphicsScene *scene) : QObject(dd, scene) { d_func()->init(); } /*! Destroys the scene index. */ QGraphicsSceneIndex::~QGraphicsSceneIndex() { } /*! Returns the scene of this index. */ QGraphicsScene* QGraphicsSceneIndex::scene() const { Q_D(const QGraphicsSceneIndex); return d->scene; } /*! \fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPointF &pos, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const Returns all visible items that, depending on \a mode, are at the specified \a pos and return a list sorted using \a order. The default value for \a mode is Qt::IntersectsItemShape; all items whose exact shape intersects with \a pos are returned. \a deviceTransform is the transformation apply to the view. This method use the estimation of the index (estimateItems) and refine the list to get an exact result. If you want to implement your own refinement algorithm you can reimplement this method. \sa estimateItems() */ QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPointF &pos, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const { Q_D(const QGraphicsSceneIndex); QList<QGraphicsItem *> itemList; d->pointIntersector->scenePoint = pos; d->items_helper(QRectF(pos, QSizeF(1, 1)), d->pointIntersector, &itemList, deviceTransform, mode, order); return itemList; } /*! \fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QRectF &rect, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const \overload Returns all visible items that, depending on \a mode, are either inside or intersect with the specified \a rect and return a list sorted using \a order. The default value for \a mode is Qt::IntersectsItemShape; all items whose exact shape intersects with or is contained by \a rect are returned. \a deviceTransform is the transformation apply to the view. This method use the estimation of the index (estimateItems) and refine the list to get an exact result. If you want to implement your own refinement algorithm you can reimplement this method. \sa estimateItems() */ QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QRectF &rect, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const { Q_D(const QGraphicsSceneIndex); QRectF exposeRect = rect; _q_adjustRect(&exposeRect); QList<QGraphicsItem *> itemList; d->rectIntersector->sceneRect = rect; d->items_helper(exposeRect, d->rectIntersector, &itemList, deviceTransform, mode, order); return itemList; } /*! \fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const \overload Returns all visible items that, depending on \a mode, are either inside or intersect with the specified \a polygon and return a list sorted using \a order. The default value for \a mode is Qt::IntersectsItemShape; all items whose exact shape intersects with or is contained by \a polygon are returned. \a deviceTransform is the transformation apply to the view. This method use the estimation of the index (estimateItems) and refine the list to get an exact result. If you want to implement your own refinement algorithm you can reimplement this method. \sa estimateItems() */ QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const { Q_D(const QGraphicsSceneIndex); QList<QGraphicsItem *> itemList; QRectF exposeRect = polygon.boundingRect(); _q_adjustRect(&exposeRect); QPainterPath path; path.addPolygon(polygon); d->pathIntersector->scenePath = path; d->items_helper(exposeRect, d->pathIntersector, &itemList, deviceTransform, mode, order); return itemList; } /*! \fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPainterPath &path, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const \overload Returns all visible items that, depending on \a mode, are either inside or intersect with the specified \a path and return a list sorted using \a order. The default value for \a mode is Qt::IntersectsItemShape; all items whose exact shape intersects with or is contained by \a path are returned. \a deviceTransform is the transformation apply to the view. This method use the estimation of the index (estimateItems) and refine the list to get an exact result. If you want to implement your own refinement algorithm you can reimplement this method. \sa estimateItems() */ QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPainterPath &path, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const { Q_D(const QGraphicsSceneIndex); QList<QGraphicsItem *> itemList; QRectF exposeRect = path.controlPointRect(); _q_adjustRect(&exposeRect); d->pathIntersector->scenePath = path; d->items_helper(exposeRect, d->pathIntersector, &itemList, deviceTransform, mode, order); return itemList; } /*! This virtual function return an estimation of items at position \a point. This method return a list sorted using \a order. */ QList<QGraphicsItem *> QGraphicsSceneIndex::estimateItems(const QPointF &point, Qt::SortOrder order) const { return estimateItems(QRectF(point, QSize(1, 1)), order); } QList<QGraphicsItem *> QGraphicsSceneIndex::estimateTopLevelItems(const QRectF &rect, Qt::SortOrder order) const { Q_D(const QGraphicsSceneIndex); Q_UNUSED(rect); QGraphicsScenePrivate *scened = d->scene->d_func(); scened->ensureSortedTopLevelItems(); if (order == Qt::DescendingOrder) { QList<QGraphicsItem *> sorted; for (int i = scened->topLevelItems.size() - 1; i >= 0; --i) sorted << scened->topLevelItems.at(i); return sorted; } return scened->topLevelItems; } /*! \fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(Qt::SortOrder order = Qt::DescendingOrder) const This pure virtual function all items in the index and sort them using \a order. */ /*! Notifies the index that the scene's scene rect has changed. \a rect is thew new scene rect. \sa QGraphicsScene::sceneRect() */ void QGraphicsSceneIndex::updateSceneRect(const QRectF &rect) { Q_UNUSED(rect); } /*! This virtual function removes all items in the scene index. */ void QGraphicsSceneIndex::clear() { const QList<QGraphicsItem *> allItems = items(); for (int i = 0 ; i < allItems.size(); ++i) removeItem(allItems.at(i)); } /*! \fn virtual void QGraphicsSceneIndex::addItem(QGraphicsItem *item) = 0 This pure virtual function inserts an \a item to the scene index. \sa removeItem(), deleteItem() */ /*! \fn virtual void QGraphicsSceneIndex::removeItem(QGraphicsItem *item) = 0 This pure virtual function removes an \a item to the scene index. \sa addItem(), deleteItem() */ /*! This method is called when an \a item has been deleted. The default implementation call removeItem. Be carefull, if your implementation of removeItem use pure virtual method of QGraphicsItem like boundingRect(), then you should reimplement this method. \sa addItem(), removeItem() */ void QGraphicsSceneIndex::deleteItem(QGraphicsItem *item) { removeItem(item); } /*! This virtual function is called by QGraphicsItem to notify the index that some part of the \a item 's state changes. By reimplementing this function, your can react to a change, and in some cases, (depending on \a change,) adjustments in the index can be made. \a change is the parameter of the item that is changing. \a value is the value that changed; the type of the value depends on \a change. The default implementation does nothing. \sa QGraphicsItem::GraphicsItemChange */ void QGraphicsSceneIndex::itemChange(const QGraphicsItem *item, QGraphicsItem::GraphicsItemChange change, const QVariant &value) { Q_UNUSED(item); Q_UNUSED(change); Q_UNUSED(value); } /*! Notify the index for a geometry change of an \a item. \sa QGraphicsItem::prepareGeometryChange() */ void QGraphicsSceneIndex::prepareBoundingRectChange(const QGraphicsItem *item) { Q_UNUSED(item); } QT_END_NAMESPACE #include "moc_qgraphicssceneindex_p.cpp" #endif // QT_NO_GRAPHICSVIEW
radekp/qt
src/gui/graphicsview/qgraphicssceneindex.cpp
C++
lgpl-2.1
24,608
package train.client.render.models; import net.minecraft.client.model.ModelBase; import net.minecraft.entity.Entity; import train.client.render.CustomModelRenderer; import train.common.core.handlers.ConfigHandler; public class ModelFreightWagenDB extends ModelBase { public ModelFreightWagenDB() { box = new CustomModelRenderer(70, 25, 256, 128); box.addBox(0F, 0F, 0F, 8, 4, 4); box.setPosition(-5F, 2F, 0F); box0 = new CustomModelRenderer(3, 27, 256, 128); box0.addBox(0F, 0F, 0F, 14, 5, 1); box0.setPosition(-23F, 1F, -6F); box1 = new CustomModelRenderer(189, 12, 256, 128); box1.addBox(0F, 0F, 0F, 8, 7, 0); box1.setPosition(-20F, 0F, 5F); box10 = new CustomModelRenderer(213, 80, 256, 128); box10.addBox(0F, 0F, 0F, 1, 5, 16); box10.setPosition(27F, 6F, -8F); box11 = new CustomModelRenderer(158, 77, 256, 128); box11.addBox(0F, 0F, 0F, 2, 3, 4); box11.setPosition(28F, 6F, -2F); box12 = new CustomModelRenderer(159, 87, 256, 128); box12.addBox(0F, 0F, 0F, 14, 17, 24); box12.setPosition(-7F, 8F, -12F); box13 = new CustomModelRenderer(0, 46, 256, 128); box13.addBox(0F, -2F, 0F, 54, 2, 6); box13.setPosition(-27F, 32F, -3F); box14 = new CustomModelRenderer(73, 69, 256, 128); box14.addBox(0F, 0F, 0F, 28, 2, 1); box14.setPosition(-19F, 25F, 11F); box15 = new CustomModelRenderer(0, 0, 256, 128); box15.addBox(0F, 0F, 0F, 1, 8, 1); box15.setPosition(5F, 2F, -8F); box15.rotateAngleX = -6.1086523819801535F; box16 = new CustomModelRenderer(1, 55, 256, 128); box16.addBox(0F, -2F, 0F, 54, 2, 5); box16.setPosition(-27F, 32F, 3F); box16.rotateAngleX = -6.09119908946021F; box17 = new CustomModelRenderer(1, 38, 256, 128); box17.addBox(0F, -2F, 0F, 54, 2, 5); box17.setPosition(-27F, 31F, 8F); box17.rotateAngleX = -5.480333851262195F; box18 = new CustomModelRenderer(1, 55, 256, 128); box18.addBox(0F, -2F, 0F, 54, 2, 5); box18.setPosition(27F, 32F, -3F); box18.rotateAngleX = -6.09119908946021F; box18.rotateAngleY = -3.141592653589793F; box19 = new CustomModelRenderer(1, 38, 256, 128); box19.addBox(0F, -2F, 0F, 54, 2, 5); box19.setPosition(27F, 31F, -8F); box19.rotateAngleX = -5.480333851262195F; box19.rotateAngleY = -3.141592653589793F; box2 = new CustomModelRenderer(96, 1, 256, 128); box2.addBox(0F, 0F, 0F, 2, 2, 14); box2.setPosition(15F, 2F, -7F); box20 = new CustomModelRenderer(187, 66, 256, 128); box20.addBox(0F, 0F, 0F, 1, 5, 16); box20.setPosition(-28F, 6F, -8F); box21 = new CustomModelRenderer(73, 69, 256, 128); box21.addBox(0F, 0F, 0F, 28, 2, 1); box21.setPosition(-9F, 25F, -12F); box22 = new CustomModelRenderer(0, 65, 256, 128); box22.addBox(0F, 0F, 0F, 1, 20, 1); box22.setPosition(-28F, 11F, -4F); box23 = new CustomModelRenderer(0, 65, 256, 128); box23.addBox(0F, 0F, 0F, 1, 20, 1); box23.setPosition(-28F, 11F, 3F); box24 = new CustomModelRenderer(0, 83, 256, 128); box24.addBox(0F, 0F, 0F, 54, 23, 22); box24.setPosition(-27F, 8F, -11F); box25 = new CustomModelRenderer(146, 80, 256, 128); box25.addBox(0F, 0F, 0F, 1, 3, 3); box25.setPosition(28F, 7F, -7F); box26 = new CustomModelRenderer(104, 42, 256, 128); box26.addBox(0F, 0F, 0F, 54, 2, 22); box26.setPosition(-27F, 6F, -11F); box27 = new CustomModelRenderer(134, 92, 256, 128); box27.addBox(0F, 0F, 0F, 14, 1, 3); box27.setPosition(-7F, 2F, -10F); box28 = new CustomModelRenderer(0, 65, 256, 128); box28.addBox(0F, 0F, 0F, 1, 20, 1); box28.setPosition(27F, 11F, -4F); box29 = new CustomModelRenderer(0, 65, 256, 128); box29.addBox(0F, 0F, 0F, 1, 20, 1); box29.setPosition(27F, 11F, 3F); box3 = new CustomModelRenderer(96, 1, 256, 128); box3.addBox(0F, 0F, 0F, 2, 2, 14); box3.setPosition(-17F, 2F, -7F); box30 = new CustomModelRenderer(73, 74, 256, 128); box30.addBox(0F, 0F, 0F, 12, 1, 1); box30.setPosition(7F, 8F, -12F); box31 = new CustomModelRenderer(73, 74, 256, 128); box31.addBox(0F, 0F, 0F, 12, 1, 1); box31.setPosition(-19F, 8F, 11F); box35 = new CustomModelRenderer(189, 12, 256, 128); box35.addBox(0F, 0F, 0F, 8, 7, 0); box35.setPosition(12F, 0F, 5F); box36 = new CustomModelRenderer(134, 92, 256, 128); box36.addBox(0F, 0F, 0F, 14, 1, 3); box36.setPosition(-7F, 2F, 7F); box38 = new CustomModelRenderer(146, 80, 256, 128); box38.addBox(0F, 0F, 0F, 1, 3, 3); box38.setPosition(28F, 7F, 4F); box4 = new CustomModelRenderer(36, 27, 256, 128); box4.addBox(0F, 0F, 0F, 14, 5, 1); box4.setPosition(-23F, 1F, 5F); box40 = new CustomModelRenderer(138, 80, 256, 128); box40.addBox(0F, 0F, 0F, 1, 3, 3); box40.setPosition(-29F, 7F, -7F); box42 = new CustomModelRenderer(138, 80, 256, 128); box42.addBox(0F, 0F, 0F, 1, 3, 3); box42.setPosition(-29F, 7F, 4F); box44 = new CustomModelRenderer(158, 77, 256, 128); box44.addBox(0F, 0F, 0F, 2, 3, 4); box44.setPosition(-30F, 6F, -2F); box46 = new CustomModelRenderer(0, 0, 256, 128); box46.addBox(0F, 0F, 0F, 1, 8, 1); box46.setPosition(-5F, 2F, 8F); box46.rotateAngleX = -6.1086523819801535F; box46.rotateAngleY = -3.141592653589793F; box5 = new CustomModelRenderer(189, 12, 256, 128); box5.addBox(0F, 0F, 0F, 8, 7, 0); box5.setPosition(12F, 0F, -5F); box55 = new CustomModelRenderer(0, 0, 256, 128); box55.addBox(0F, 0F, 0F, 1, 8, 1); box55.setPosition(6F, 2F, 8F); box55.rotateAngleX = -6.1086523819801535F; box55.rotateAngleY = -3.141592653589793F; box6 = new CustomModelRenderer(36, 27, 256, 128); box6.addBox(0F, 0F, 0F, 14, 5, 1); box6.setPosition(9F, 1F, 5F); box63 = new CustomModelRenderer(189, 12, 256, 128); box63.addBox(0F, 0F, 0F, 8, 7, 0); box63.setPosition(-20F, 0F, -5F); box7 = new CustomModelRenderer(0, 0, 256, 128); box7.addBox(0F, 0F, 0F, 1, 8, 1); box7.setPosition(-6F, 2F, -8F); box7.rotateAngleX = -6.1086523819801535F; box8 = new CustomModelRenderer(3, 27, 256, 128); box8.addBox(0F, 0F, 0F, 14, 5, 1); box8.setPosition(9F, 1F, -6F); box9 = new CustomModelRenderer(118, 21, 256, 128); box9.addBox(0F, 0F, 0F, 54, 3, 14); box9.setPosition(-27F, 6F, -7F); } @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { if (ConfigHandler.FLICKERING) { super.render(entity, f, f1, f2, f3, f4, f5); } box.render(f5); box0.render(f5); box1.render(f5); box10.render(f5); box11.render(f5); box12.render(f5); box13.render(f5); box14.render(f5); box15.render(f5); box16.render(f5); box17.render(f5); box18.render(f5); box19.render(f5); box2.render(f5); box20.render(f5); box21.render(f5); box22.render(f5); box23.render(f5); box24.render(f5); box25.render(f5); box26.render(f5); box27.render(f5); box28.render(f5); box29.render(f5); box3.render(f5); box30.render(f5); box31.render(f5); box35.render(f5); box36.render(f5); box38.render(f5); box4.render(f5); box40.render(f5); box42.render(f5); box44.render(f5); box46.render(f5); box5.render(f5); box55.render(f5); box6.render(f5); box63.render(f5); box7.render(f5); box8.render(f5); box9.render(f5); } public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5) {} public CustomModelRenderer box; public CustomModelRenderer box0; public CustomModelRenderer box1; public CustomModelRenderer box10; public CustomModelRenderer box11; public CustomModelRenderer box12; public CustomModelRenderer box13; public CustomModelRenderer box14; public CustomModelRenderer box15; public CustomModelRenderer box16; public CustomModelRenderer box17; public CustomModelRenderer box18; public CustomModelRenderer box19; public CustomModelRenderer box2; public CustomModelRenderer box20; public CustomModelRenderer box21; public CustomModelRenderer box22; public CustomModelRenderer box23; public CustomModelRenderer box24; public CustomModelRenderer box25; public CustomModelRenderer box26; public CustomModelRenderer box27; public CustomModelRenderer box28; public CustomModelRenderer box29; public CustomModelRenderer box3; public CustomModelRenderer box30; public CustomModelRenderer box31; public CustomModelRenderer box35; public CustomModelRenderer box36; public CustomModelRenderer box38; public CustomModelRenderer box4; public CustomModelRenderer box40; public CustomModelRenderer box42; public CustomModelRenderer box44; public CustomModelRenderer box46; public CustomModelRenderer box5; public CustomModelRenderer box55; public CustomModelRenderer box6; public CustomModelRenderer box63; public CustomModelRenderer box7; public CustomModelRenderer box8; public CustomModelRenderer box9; }
BlesseNtumble/Traincraft-5
src/main/java/train/client/render/models/ModelFreightWagenDB.java
Java
lgpl-2.1
8,722
/* TerraLib - a library for developing GIS applications. Copyright 2001, 2002, 2003 INPE and Tecgraf/PUC-Rio. This code is part of the TerraLib library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. You should have received a copy of the GNU Lesser General Public License along with this library. The authors reassure the license terms regarding the warranties. They specifically disclaim any warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The library provided hereunder is on an "as is" basis, and the authors have no obligation to provide maintenance, support, updates, enhancements, or modifications. In no event shall INPE be held liable to any party for direct, indirect, special, incidental, or consequential damages arising out of the use of this library and its documentation. */ #ifndef TEPDIPRINCIPALCOMPONENTSFUSION_HPP #define TEPDIPRINCIPALCOMPONENTSFUSION_HPP #include "TePDIAlgorithm.hpp" /** * @brief This is the class for principal components generation. * @author Felipe Castro da Silva <felipe@dpi.inpe.br> * @ingroup PDIFusionAlgorithms * * @note The required parameters are: * * @param input_rasters (TePDITypes::TePDIRasterVectorType) - Low resolution rasters. * @param bands (std::vector< int >) - The bands from each low resolution raster. * @param output_raster (TePDITypes::TePDIRasterPtrType) - High resolution fused raster. * @param reference_raster (TePDITypes::TePDIRasterPtrType) - High resolution raster. * @param reference_raster_band (int) - Reference raster band number. * @param resampling_type (TePDIInterpolator::InterpMethod) - * Resampling type. * @param fit_histogram (bool) - Fit the reference histogram to the * low resolution rasters histograms (better collor quality). * * @note The optional parameters are: * * @param output_rasters (TePDITypes::TePDIRasterVectorType) - High resolution fused rasters, each one represents one band/channel, if this parameter is set the output_raster parameter will be ignored. * */ class PDI_DLL TePDIPrincipalComponentsFusion : public TePDIAlgorithm { public : /** * @brief Default Constructor. * */ TePDIPrincipalComponentsFusion(); /** * @brief Default Destructor */ ~TePDIPrincipalComponentsFusion(); /** * @brief Checks if the supplied parameters fits the requirements of each * PDI algorithm implementation. * * @note Error log messages must be generated. No exceptions generated. * * @param parameters The parameters to be checked. * @return true if the parameters are OK. false if not. */ bool CheckParameters( const TePDIParameters& parameters ) const; protected : /** * @brief Decide the direction of the analysis based on the analysis_type parameter. * * @return true if OK. false on error. */ bool RunImplementation(); /** * @brief Reset the internal state to the initial state. * * @param params The new parameters referente at initial state. */ void ResetState( const TePDIParameters& params ); }; /** @example TePDIFusion_test.cpp * Fusion algorithms test. */ #endif //TEPDIPRINCIPALCOMPONENTS_HPP
Universefei/Terralib-analysis
src/terralib/image_processing/TePDIPrincipalComponentsFusion.hpp
C++
lgpl-2.1
3,696
#!/usr/bin/env python from __future__ import print_function import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from datetime import datetime, timedelta from obspy.core.utcdatetime import UTCDateTime from matplotlib import gridspec from pdart.view import stream_from_directory from obspy import read_inventory import os from obspy.core import read # start_time = UTCDateTime('1971-02-07T00:45:00') from pdart.diffusion.view_single_seismogram import remove_response # update 25-08-21 def single_seismogram(title): # 1969-11-20T22:17:17.7 # onset is 42.4 s Lognonne 2003 onset = UTCDateTime('1969-11-20TT22:17:17.700000Z') # +42.4 # onset = UTCDateTime('1969-11-20T22:17:700000Z') start_time = onset - timedelta(minutes=2) stations = ['S12'] channels = ['MHZ'] end_time = start_time + timedelta(minutes=15) stream = stream_from_directory( top_level_dir='/Users/cnunn/lunar_data/PDART_CONTINUOUS_MAIN_TAPES', start_time=start_time, stations=stations, channels=channels, end_time=end_time) ######## fig = plt.figure(figsize=(15, 4)) gs = gridspec.GridSpec(5, 1, hspace=0.001) ax0 = plt.subplot(gs[0]) trace_MHZ = stream.select(channel='MHZ')[0] ax0.plot(times_to_seconds(trace_MHZ.times()), trace_MHZ.data, color='k') ax0.set_xlim(-2*60, 15*60) ax0.set_xticks(np.arange(0,15*60,6*50)) ax0.set_xticks(np.arange(-180,15*60,60), minor=True) ax0.set_title(title, fontsize=20) ax0.set_yticks(np.arange(480, 560, 20)) # ax0.set_yticks(np.arange(460,580,20), minor=True) ax0.set_ylim(510-50, 510+50) ax0.set_ylabel('DU', fontsize=14) ax0.annotate(xy=(0.01,0.9), text=onset.strftime("%Y-%m-%d %H:%M:%S"), fontsize=13, horizontalalignment="left", verticalalignment="top", xycoords="axes fraction") xticklabels = (ax0.get_xticklabels()) plt.setp(xticklabels, visible=False) ax0.tick_params(length=6, width=1, which='minor') ax0.yaxis.set_label_coords(-0.04, 0.5) ax0.annotate(xy=(1.01,0.5), text='MHZ', fontsize=16, xycoords="axes fraction", horizontalalignment='left', verticalalignment='center') plt.subplots_adjust(left=0.06, right=0.95, top=0.9, bottom=0.12) plt.savefig('Apollo12_LM_impact_XXXX.png') plt.show() # def single_seismogram_remove_response_short(title): # # # peaked mode # inv_name = "/Users/cnunn/lunar_data/IRIS_dataless_seed/XA.1969-1977.xml" # # onset is 42.4 s Lognonne 2003 # onset = UTCDateTime('1969-11-20TT22:17:17.700000Z') # start_time = onset - timedelta(minutes=2) # # XXXX # station = 'S12' # channel = 'MHZ' # pre_filt = [0.1, 0.3,0.7,1] # # end_time = UTCDateTime('1971:02:07T02:35.25') # # end_time = onset + timedelta(minutes=60) # # # 1969-11-20T22:17:17.7 # # stream = remove_response_from_seismogram(inv_name=inv_name, # start_time=start_time, # station=station, # channel=channel, # pre_filt=pre_filt, # water_level=None, # end_time=end_time, # plot=False) # # ######## # # fig = plt.figure(figsize=(15, 4)) # gs = gridspec.GridSpec(1, 1, hspace=0.001) # # ax0 = plt.subplot(gs[0]) # # trace_MHZ = stream.select(channel='MHZ')[0] # ax0.plot(times_to_seconds(trace_MHZ.times()), trace_MHZ.data, color='k') # ax0.set_xlim(-2*60, 5*60) # # print('short') # ax0.set_xticks(np.arange(0,6*60,6*50),minor=False) # ax0.set_xticks(np.arange(-180,6*60,60), minor=True) # ax0.set_title(title, fontsize=20) # # # ax0.set_yticks(np.arange(480, 560, 20)) # # ax0.set_yticks(np.arange(460,580,20), minor=True) # ax0.set_ylim(-1.1e-8, 1.01e-8) # ax0.set_ylabel('Displacement [m]', fontsize=14) # ax0.annotate(xy=(0.01,0.9), text=onset.strftime("%Y-%m-%d %H:%M:%S"), # fontsize=13, horizontalalignment="left", verticalalignment="top", # xycoords="axes fraction") # # # xticklabels = (ax0.get_xticklabels()) # # plt.setp(xticklabels, visible=False) # # ax0.tick_params(length=3, width=1, which='minor') # ax0.tick_params(length=6, width=1, which='major') # # ax0.yaxis.set_label_coords(-0.04, 0.5) # # ax0.annotate(xy=(1.01,0.5), text='MHZ', fontsize=16, # xycoords="axes fraction", horizontalalignment='left', # verticalalignment='center') # # ax0.set_xlabel('Time after impact [s]', fontsize=14) # ax0.yaxis.set_label_coords(-0.04, 0.5) # # plt.subplots_adjust(left=0.06, right=0.95, top=0.9, bottom=0.12) # plt.savefig('Apollo12_LM_impact_XXXX.png') # plt.show() def single_seismogram_remove_response(title,onset,pick=None): # peaked mode inv_name = "/Users/cnunn/lunar_data/IRIS_dataless_seed/XA.1969-1977.xml" onset = UTCDateTime('1969-11-20TT22:17:17.700000Z') start_time = onset - timedelta(minutes=2) # XXXX station = 'S12' channel = 'MHZ' pre_filt = [0.1, 0.3,0.7,1] # end_time = UTCDateTime('1971:02:07T02:35.25') end_time = onset + timedelta(minutes=60) # 1969-11-20T22:17:17.7 # reset the timing # make a correction # find actual time of onset # print(onset.time) stream = remove_response_from_seismogram(inv_name=inv_name, start_time=start_time, station=station, channel=channel, pre_filt=pre_filt, water_level=None, end_time=end_time, plot=False) ######## fig = plt.figure(figsize=(15, 4)) gs = gridspec.GridSpec(1, 1, hspace=0.001) ax0 = plt.subplot(gs[0]) trace_MHZ = stream.select(channel='MHZ')[0] ax0.plot(times_to_seconds(trace_MHZ.times()), trace_MHZ.data, color='k') ax0.set_xlim(-2*60, 60*60) ax0.set_xticks(np.arange(0,61*60,6*50),minor=False) ax0.set_xticks(np.arange(-180,61*60,60), minor=True) # pick_markP = pick - onset # plt.gca().axvline(x=pick_markP, # color='r', linewidth=2) ax0.set_title(title, fontsize=20) # ax0.set_yticks(np.arange(480, 560, 20)) # ax0.set_yticks(np.arange(460,580,20), minor=True) ax0.set_ylim(-1.1e-8, 1.01e-8) ax0.set_ylabel('Displacement [m]', fontsize=14) ax0.annotate(xy=(0.01,0.9), text=onset.strftime("%Y-%m-%d %H:%M:%S"), fontsize=13, horizontalalignment="left", verticalalignment="top", xycoords="axes fraction") # xticklabels = (ax0.get_xticklabels()) # plt.setp(xticklabels, visible=False) ax0.tick_params(length=3, width=1, which='minor') ax0.tick_params(length=6, width=1, which='major') ax0.yaxis.set_label_coords(-0.04, 0.5) ax0.annotate(xy=(1.01,0.5), text='MHZ', fontsize=16, xycoords="axes fraction", horizontalalignment='left', verticalalignment='center') ax0.set_xlabel('Time after impact [s]', fontsize=14) ax0.yaxis.set_label_coords(-0.04, 0.5) ax0.plot(times_to_seconds(trace_MHZ.times()), times_to_seconds(trace_MHZ.data-trace_MHZ.stats.starttime.timestamp), color='k') plt.subplots_adjust(left=0.06, right=0.95, top=0.9, bottom=0.13) plt.savefig('../extra_plots_output/Apollo12_LM_impact_XXXX.png') plt.show() # def times_to_minutes(times_in_seconds): # return ((times_in_seconds / 60) - 2) # copied from /Users/cnunn/python_packages/pdart/extra_plots/view_response.py def remove_response_from_seismogram( inv_name, start_time, station, channel, pre_filt, end_time=None, outfile=None, output='DISP', water_level=None, plot=True): # read the response file inv = read_inventory(inv_name) if end_time is None: time_interval = timedelta(hours=3) end_time = start_time + time_interval # xa.s12..att.1969.324.0.mseed filename = '%s.%s.*.%s.%s.%03d.0.mseed' % ('xa',station.lower(), channel.lower(), str(start_time.year), start_time.julday) filename = os.path.join('/Users/cnunn/lunar_data/PDART_CONTINUOUS_MAIN_TAPES',station.lower(),str(start_time.year),str(start_time.julday),filename) stream = read(filename) stream = stream.select(channel=channel) stream.trim(starttime=start_time, endtime=end_time) # remove location (ground station) for tr in stream: tr.stats.location = '' # detrend stream.detrend('linear') # taper the edges # if there are gaps in the seismogram - EVERY short trace will be tapered # this is required to remove the response later # stream.taper(max_percentage=0.05, type='cosine') # experiment with tapering? not tapering preserves the overall shape better # but it may required # merge the streams stream.merge() if stream.count() > 1: print('Too many streams - exiting') # find the gaps in the trace if isinstance(stream[0].data,np.ma.MaskedArray): mask = np.ma.getmask(stream[0].data) else: mask = None # split the stream, then refill it with zeros on the gaps stream = stream.split() stream = stream.merge(fill_value=0) # for i, n in enumerate(stream[0].times()): # # print(n) # stream[0].data[i]=np.sin(2*np.pi*(1/25)*n) stream.attach_response(inv) # print('here') # zero_mean=False - because the trace can be asymmetric - remove the mean ourselves # do not taper here - it doesn't work well with the masked arrays - often required # when there are gaps - if necessary taper first # water level - this probably doesn't have much impact - because we are pre filtering # stream.remove_response(pre_filt=pre_filt,output="DISP",water_level=30,zero_mean=False,taper=False,plot=True,fig=outfile) for tr in stream: remove_response(tr, pre_filt=pre_filt,output=output,water_level=water_level,zero_mean=False,taper=False,plot=plot,fig=outfile) for tr in stream: tr.stats.location = 'changed' if mask is not None: stream[0].data = np.ma.array(stream[0].data, mask = mask) print(stream) return stream def times_to_seconds(times_in_seconds): return (times_in_seconds - 120) if __name__ == "__main__": # single_seismogram(title='Impact of Apollo 12 Lunar Ascent Module') onset = UTCDateTime('1969-11-20TT22:17:17.700000Z') # <pick publicID="smi:nunn19/pick/00001/lognonne03/S12/P"> pick = UTCDateTime('1969-11-20T22:17:42.400000Z') arrival_time = pick - onset print(arrival_time) single_seismogram_remove_response(title='Impact of Apollo 12 Lunar Ascent Module',onset=onset,pick=pick) # single_seismogram_remove_response_short(title='Impact of Apollo 12 Lunar Ascent Module')
cerinunn/pdart
extra_plots/plot_seismograms.py
Python
lgpl-3.0
10,680
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.es; import com.google.common.net.HostAndPort; import java.io.IOException; import java.util.Arrays; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.impl.client.BasicCredentialsProvider; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.elasticsearch.core.TimeValue.timeValueSeconds; public class EsConnectorImpl implements EsConnector { private static final String ES_USERNAME = "elastic"; private static final Logger LOG = LoggerFactory.getLogger(EsConnectorImpl.class); private final AtomicReference<RestHighLevelClient> restClient = new AtomicReference<>(null); private final Set<HostAndPort> hostAndPorts; private final String searchPassword; public EsConnectorImpl(Set<HostAndPort> hostAndPorts, @Nullable String searchPassword) { this.hostAndPorts = hostAndPorts; this.searchPassword = searchPassword; } @Override public Optional<ClusterHealthStatus> getClusterHealthStatus() { try { ClusterHealthResponse healthResponse = getRestHighLevelClient().cluster() .health(new ClusterHealthRequest().waitForYellowStatus().timeout(timeValueSeconds(30)), RequestOptions.DEFAULT); return Optional.of(healthResponse.getStatus()); } catch (IOException e) { LOG.trace("Failed to check health status ", e); return Optional.empty(); } } @Override public void stop() { RestHighLevelClient restHighLevelClient = restClient.get(); if (restHighLevelClient != null) { try { restHighLevelClient.close(); } catch (IOException e) { LOG.warn("Error occurred while closing Rest Client", e); } } } private RestHighLevelClient getRestHighLevelClient() { RestHighLevelClient res = this.restClient.get(); if (res != null) { return res; } RestHighLevelClient restHighLevelClient = buildRestHighLevelClient(); this.restClient.set(restHighLevelClient); return restHighLevelClient; } private RestHighLevelClient buildRestHighLevelClient() { HttpHost[] httpHosts = hostAndPorts.stream() .map(hostAndPort -> new HttpHost(hostAndPort.getHost(), hostAndPort.getPortOrDefault(9001))) .toArray(HttpHost[]::new); if (LOG.isDebugEnabled()) { String addresses = Arrays.stream(httpHosts) .map(t -> t.getHostName() + ":" + t.getPort()) .collect(Collectors.joining(", ")); LOG.debug("Connected to Elasticsearch node: [{}]", addresses); } RestClientBuilder builder = RestClient.builder(httpHosts) .setHttpClientConfigCallback(httpClientBuilder -> { if (searchPassword != null) { BasicCredentialsProvider provider = getBasicCredentialsProvider(searchPassword); httpClientBuilder.setDefaultCredentialsProvider(provider); } return httpClientBuilder; }); return new RestHighLevelClient(builder); } private static BasicCredentialsProvider getBasicCredentialsProvider(String searchPassword) { BasicCredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(ES_USERNAME, searchPassword)); return provider; } }
SonarSource/sonarqube
server/sonar-main/src/main/java/org/sonar/application/es/EsConnectorImpl.java
Java
lgpl-3.0
4,727
/*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ package de.cismet.cids.custom.wrrl_db_mv.util.gup; import Sirius.navigator.tools.CacheException; import Sirius.navigator.tools.MetaObjectCache; import Sirius.server.middleware.types.MetaClass; import Sirius.server.middleware.types.MetaObject; import org.jdesktop.swingx.painter.CompoundPainter; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.painter.RectanglePainter; import java.awt.Color; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import javax.swing.JMenuItem; import de.cismet.cids.custom.wrrl_db_mv.commons.WRRLUtil; import de.cismet.cids.custom.wrrl_db_mv.util.CidsBeanSupport; import de.cismet.cids.dynamics.CidsBean; import de.cismet.cids.navigator.utils.ClassCacheMultiple; /** * DOCUMENT ME! * * @author therter * @version $Revision$, $Date$ */ public class VermeidungsgruppeRWBandMember extends LineBandMember { //~ Static fields/initializers --------------------------------------------- private static final MetaClass VERMEIDUNGSGRUPPE = ClassCacheMultiple.getMetaClass( WRRLUtil.DOMAIN_NAME, "VERMEIDUNGSGRUPPE"); //~ Instance fields -------------------------------------------------------- private JMenuItem[] menuItems; //~ Constructors ----------------------------------------------------------- /** * Creates new form MassnahmenBandMember. * * @param parent DOCUMENT ME! */ public VermeidungsgruppeRWBandMember(final VermeidungsgruppeRWBand parent) { super(parent); lineFieldName = "linie"; } /** * Creates new form MassnahmenBandMember. * * @param parent DOCUMENT ME! * @param readOnly DOCUMENT ME! */ public VermeidungsgruppeRWBandMember(final VermeidungsgruppeRWBand parent, final boolean readOnly) { super(parent, readOnly); lineFieldName = "linie"; } //~ Methods ---------------------------------------------------------------- @Override public void setCidsBean(final CidsBean cidsBean) { super.setCidsBean(cidsBean); setToolTipText(bean.getProperty("vermeidungsgruppe.name") + ""); } /** * DOCUMENT ME! */ @Override protected void determineBackgroundColour() { if ((bean.getProperty("vermeidungsgruppe") == null) || (bean.getProperty("vermeidungsgruppe.color") == null)) { setDefaultBackground(); return; } final String color = (String)bean.getProperty("vermeidungsgruppe.color"); if (color != null) { try { setBackgroundPainter(new MattePainter(Color.decode(color))); } catch (NumberFormatException e) { LOG.error("Error while parsing the color.", e); setDefaultBackground(); } } unselectedBackgroundPainter = getBackgroundPainter(); selectedBackgroundPainter = new CompoundPainter( unselectedBackgroundPainter, new RectanglePainter( 3, 3, 3, 3, 3, 3, true, new Color(100, 100, 100, 100), 2f, new Color(50, 50, 50, 100))); setBackgroundPainter(unselectedBackgroundPainter); } /** * DOCUMENT ME! * * @param id DOCUMENT ME! */ private void setVermeidungsgruppe(final String id) { try { final String query = "select " + VERMEIDUNGSGRUPPE.getID() + "," + VERMEIDUNGSGRUPPE.getPrimaryKey() + " from " + VERMEIDUNGSGRUPPE.getTableName(); // NOI18N final MetaObject[] metaObjects = MetaObjectCache.getInstance() .getMetaObjectsByQuery(query, WRRLUtil.DOMAIN_NAME); CidsBean b = null; if (metaObjects != null) { for (final MetaObject tmp : metaObjects) { if (tmp.getBean().getProperty("id").toString().equals(id)) { b = tmp.getBean(); break; } } } bean.setProperty("vermeidungsgruppe", b); } catch (Exception e) { LOG.error("Error while setting property massnahme.", e); } } /** * DOCUMENT ME! */ @Override protected void configurePopupMenu() { try { final String query = "select " + VERMEIDUNGSGRUPPE.getID() + "," + VERMEIDUNGSGRUPPE.getPrimaryKey() + " from " + VERMEIDUNGSGRUPPE.getTableName(); // NOI18N final MetaObject[] metaObjects = MetaObjectCache.getInstance() .getMetaObjectsByQuery(query, WRRLUtil.DOMAIN_NAME); menuItems = new JMenuItem[metaObjects.length]; for (int i = 0; i < metaObjects.length; ++i) { menuItems[i] = new JMenuItem(metaObjects[i].getBean().toString()); menuItems[i].addActionListener(this); menuItems[i].setActionCommand(String.valueOf(metaObjects[i].getID())); popup.add(menuItems[i]); } } catch (CacheException e) { LOG.error("Cache Exception", e); } popup.addSeparator(); super.configurePopupMenu(); } @Override public void actionPerformed(final ActionEvent e) { boolean found = false; for (final JMenuItem tmp : menuItems) { if (e.getSource() == tmp) { found = true; setVermeidungsgruppe(tmp.getActionCommand()); fireBandMemberChanged(false); break; } } if (!found) { super.actionPerformed(e); } newMode = false; } @Override public void propertyChange(final PropertyChangeEvent evt) { if (evt.getPropertyName().equals("vermeidungsgruppe")) { determineBackgroundColour(); setSelected(isSelected); setToolTipText(bean.getProperty("vermeidungsgruppe.name") + ""); } else { super.propertyChange(evt); } } /** * DOCUMENT ME! * * @param bean DOCUMENT ME! * * @return DOCUMENT ME! * * @throws Exception DOCUMENT ME! */ @Override protected CidsBean cloneBean(final CidsBean bean) throws Exception { return CidsBeanSupport.cloneCidsBean(bean, false); } }
cismet/cids-custom-wrrl-db-mv
src/main/java/de/cismet/cids/custom/wrrl_db_mv/util/gup/VermeidungsgruppeRWBandMember.java
Java
lgpl-3.0
6,828
/* * XAdES4j - A Java library for generation and verification of XAdES signatures. * Copyright (C) 2010 Luis Goncalves. * * XAdES4j is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or any later version. * * XAdES4j 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 Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License along * with XAdES4j. If not, see <http://www.gnu.org/licenses/>. */ package xades4j.production; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.xml.security.signature.*; import org.apache.xml.security.transforms.Transforms; import org.apache.xml.security.utils.resolver.ResourceResolverSpi; import org.w3c.dom.Document; import xades4j.UnsupportedAlgorithmException; import xades4j.XAdES4jXMLSigException; import xades4j.algorithms.Algorithm; import xades4j.properties.DataObjectDesc; import xades4j.utils.ResolverAnonymous; import xades4j.utils.TransformUtils; import xades4j.xml.marshalling.algorithms.AlgorithmsParametersMarshallingProvider; import javax.inject.Inject; /** * Helper class that processes a set of data object descriptions. * * @author Luís */ final class SignedDataObjectsProcessor { static final class Result { final Map<DataObjectDesc, Reference> referenceMappings; final Set<Manifest> manifests; public Result(Map<DataObjectDesc, Reference> referenceMappings, Set<Manifest> manifests) { this.referenceMappings = Collections.unmodifiableMap(referenceMappings); this.manifests = Collections.unmodifiableSet(manifests); } } private final SignatureAlgorithms signatureAlgorithms; private final AlgorithmsParametersMarshallingProvider algorithmsParametersMarshaller; @Inject SignedDataObjectsProcessor(SignatureAlgorithms signatureAlgorithms, AlgorithmsParametersMarshallingProvider algorithmsParametersMarshaller) { this.signatureAlgorithms = signatureAlgorithms; this.algorithmsParametersMarshaller = algorithmsParametersMarshaller; } /** * Processes the signed data objects and adds the corresponding {@code Reference}s * and {@code Object}s to the signature. This method must be invoked before * adding any other {@code Reference}s to the signature. * * @return result with reference mappings resulting from the data object descriptions and manifests to be digested * @throws UnsupportedAlgorithmException if the reference digest algorithm is not supported * @throws IllegalStateException if the signature already contains {@code Reference}s * @throws XAdES4jXMLSigException if a Manifest cannot be digested */ SignedDataObjectsProcessor.Result process( SignedDataObjects signedDataObjects, XMLSignature xmlSignature) throws UnsupportedAlgorithmException, XAdES4jXMLSigException { if (xmlSignature.getSignedInfo().getLength() != 0) { throw new IllegalStateException("XMLSignature already contains references"); } return process( signedDataObjects.getDataObjectsDescs(), xmlSignature.getSignedInfo(), xmlSignature.getId(), signedDataObjects.getResourceResolvers(), xmlSignature, false); } private SignedDataObjectsProcessor.Result process( Collection<? extends DataObjectDesc> dataObjects, Manifest container, String idPrefix, List<ResourceResolverSpi> resourceResolvers, XMLSignature xmlSignature, boolean hasNullURIReference) throws UnsupportedAlgorithmException, XAdES4jXMLSigException { Map<DataObjectDesc, Reference> referenceMappings = new IdentityHashMap<DataObjectDesc, Reference>(dataObjects.size()); Set<Manifest> manifests = new HashSet<Manifest>(); for (ResourceResolverSpi resolver : resourceResolvers) { container.addResourceResolver(resolver); } String digestMethodUri = this.signatureAlgorithms.getDigestAlgorithmForDataObjectReferences(); /**/ try { for (DataObjectDesc dataObjDesc : dataObjects) { String refUri, refType; int index = container.getLength(); if (dataObjDesc instanceof DataObjectReference) { // If the data object info is a DataObjectReference, the Reference uri // and type are the ones specified on the object. DataObjectReference dataObjRef = (DataObjectReference) dataObjDesc; refUri = dataObjRef.getUri(); refType = dataObjRef.getType(); } else if (dataObjDesc instanceof EnvelopedXmlObject) { // If the data object info is a EnvelopedXmlObject we need to create a ds:Object to embed it. // The Reference uri will refer the new ds:Object's id. EnvelopedXmlObject envXmlObj = (EnvelopedXmlObject) dataObjDesc; String xmlObjId = String.format("%s-object%d", idPrefix, index); ObjectContainer xmlObj = new ObjectContainer(container.getDocument()); xmlObj.setId(xmlObjId); xmlObj.appendChild(envXmlObj.getContent()); xmlObj.setMimeType(envXmlObj.getMimeType()); xmlObj.setEncoding(envXmlObj.getEncoding()); xmlSignature.appendObject(xmlObj); refUri = '#' + xmlObjId; refType = Reference.OBJECT_URI; } else if (dataObjDesc instanceof AnonymousDataObjectReference) { if (hasNullURIReference) { // This shouldn't happen because SignedDataObjects does the validation. throw new IllegalStateException("Multiple AnonymousDataObjectReference detected"); } hasNullURIReference = true; refUri = refType = null; AnonymousDataObjectReference anonymousRef = (AnonymousDataObjectReference) dataObjDesc; container.addResourceResolver(new ResolverAnonymous(anonymousRef.getDataStream())); } else if (dataObjDesc instanceof EnvelopedManifest) { // If the data object info is a EnvelopedManifest we need to create a ds:Manifest and a ds:Object // to embed it. The Reference uri will refer the manifest's id. EnvelopedManifest envManifest = (EnvelopedManifest) dataObjDesc; String xmlManifestId = String.format("%s-manifest%d", idPrefix, index); Manifest xmlManifest = new Manifest(container.getDocument()); xmlManifest.setId(xmlManifestId); SignedDataObjectsProcessor.Result manifestResult = process( envManifest.getDataObjects(), xmlManifest, xmlManifestId, resourceResolvers, xmlSignature, hasNullURIReference); ObjectContainer xmlObj = new ObjectContainer(container.getDocument()); xmlObj.appendChild(xmlManifest.getElement()); xmlSignature.appendObject(xmlObj); manifests.add(xmlManifest); manifests.addAll(manifestResult.manifests); refUri = '#' + xmlManifestId; refType = Reference.MANIFEST_URI; } else { throw new ClassCastException("Unsupported SignedDataObjectDesc. Must be one of DataObjectReference, EnvelopedXmlObject, EnvelopedManifest and AnonymousDataObjectReference"); } Transforms transforms = processTransforms(dataObjDesc, container.getDocument()); // Add the Reference. References need an ID because data object properties may refer them. container.addDocument( xmlSignature.getBaseURI(), refUri, transforms, digestMethodUri, String.format("%s-ref%d", idPrefix, index), // id refType); // SignedDataObjects and EnvelopedManifest don't allow repeated instances, so there's no // need to check for duplicate entries on the map. Reference ref = container.item(index); referenceMappings.put(dataObjDesc, ref); } } catch (XMLSignatureException ex) { // -> xmlSignature.appendObject(xmlObj): not thrown when signing. // -> xmlSignature.addDocument(...): appears to be thrown when the digest // algorithm is not supported. throw new UnsupportedAlgorithmException( "Digest algorithm not supported in the XML Signature provider", digestMethodUri, ex); } catch (org.apache.xml.security.exceptions.XMLSecurityException ex) { // -> xmlSignature.getSignedInfo().item(...): shouldn't be thrown // when signing. throw new IllegalStateException(ex); } return new Result(referenceMappings, manifests); } private Transforms processTransforms( DataObjectDesc dataObjDesc, Document document) throws UnsupportedAlgorithmException { Collection<Algorithm> transforms = dataObjDesc.getTransforms(); if (transforms.isEmpty()) { return null; } return TransformUtils.createTransforms(document, this.algorithmsParametersMarshaller, transforms); } }
luisgoncalves/xades4j
src/main/java/xades4j/production/SignedDataObjectsProcessor.java
Java
lgpl-3.0
10,850
// Copyright (c) 2014-2016 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package blockchain import ( "fmt" ) // DeploymentError identifies an error that indicates a deployment ID was // specified that does not exist. type DeploymentError uint32 // Error returns the assertion error as a human-readable string and satisfies // the error interface. func (e DeploymentError) Error() string { return fmt.Sprintf("deployment ID %d does not exist", uint32(e)) } // AssertError identifies an error that indicates an internal code consistency // issue and should be treated as a critical and unrecoverable error. type AssertError string // Error returns the assertion error as a human-readable string and satisfies // the error interface. func (e AssertError) Error() string { return "assertion failed: " + string(e) } // ErrorCode identifies a kind of error. type ErrorCode int // These constants are used to identify a specific RuleError. const ( // ErrDuplicateBlock indicates a block with the same hash already // exists. ErrDuplicateBlock ErrorCode = iota // ErrBlockTooBig indicates the serialized block size exceeds the // maximum allowed size. ErrBlockTooBig // ErrBlockWeightTooHigh indicates that the block's computed weight // metric exceeds the maximum allowed value. ErrBlockWeightTooHigh // ErrBlockVersionTooOld indicates the block version is too old and is // no longer accepted since the majority of the network has upgraded // to a newer version. ErrBlockVersionTooOld // ErrInvalidTime indicates the time in the passed block has a precision // that is more than one second. The chain consensus rules require // timestamps to have a maximum precision of one second. ErrInvalidTime // ErrTimeTooOld indicates the time is either before the median time of // the last several blocks per the chain consensus rules or prior to the // most recent checkpoint. ErrTimeTooOld // ErrTimeTooNew indicates the time is too far in the future as compared // the current time. ErrTimeTooNew // ErrDifficultyTooLow indicates the difficulty for the block is lower // than the difficulty required by the most recent checkpoint. ErrDifficultyTooLow // ErrUnexpectedDifficulty indicates specified bits do not align with // the expected value either because it doesn't match the calculated // valued based on difficulty regarted rules or it is out of the valid // range. ErrUnexpectedDifficulty // ErrHighHash indicates the block does not hash to a value which is // lower than the required target difficultly. ErrHighHash // ErrBadMerkleRoot indicates the calculated merkle root does not match // the expected value. ErrBadMerkleRoot // ErrBadCheckpoint indicates a block that is expected to be at a // checkpoint height does not match the expected one. ErrBadCheckpoint // ErrForkTooOld indicates a block is attempting to fork the block chain // before the most recent checkpoint. ErrForkTooOld // ErrCheckpointTimeTooOld indicates a block has a timestamp before the // most recent checkpoint. ErrCheckpointTimeTooOld // ErrNoTransactions indicates the block does not have a least one // transaction. A valid block must have at least the coinbase // transaction. ErrNoTransactions // ErrTooManyTransactions indicates the block has more transactions than // are allowed. ErrTooManyTransactions // ErrNoTxInputs indicates a transaction does not have any inputs. A // valid transaction must have at least one input. ErrNoTxInputs // ErrNoTxOutputs indicates a transaction does not have any outputs. A // valid transaction must have at least one output. ErrNoTxOutputs // ErrTxTooBig indicates a transaction exceeds the maximum allowed size // when serialized. ErrTxTooBig // ErrBadTxOutValue indicates an output value for a transaction is // invalid in some way such as being out of range. ErrBadTxOutValue // ErrDuplicateTxInputs indicates a transaction references the same // input more than once. ErrDuplicateTxInputs // ErrBadTxInput indicates a transaction input is invalid in some way // such as referencing a previous transaction outpoint which is out of // range or not referencing one at all. ErrBadTxInput // ErrMissingTxOut indicates a transaction output referenced by an input // either does not exist or has already been spent. ErrMissingTxOut // ErrUnfinalizedTx indicates a transaction has not been finalized. // A valid block may only contain finalized transactions. ErrUnfinalizedTx // ErrDuplicateTx indicates a block contains an identical transaction // (or at least two transactions which hash to the same value). A // valid block may only contain unique transactions. ErrDuplicateTx // ErrOverwriteTx indicates a block contains a transaction that has // the same hash as a previous transaction which has not been fully // spent. ErrOverwriteTx // ErrImmatureSpend indicates a transaction is attempting to spend a // coinbase that has not yet reached the required maturity. ErrImmatureSpend // ErrSpendTooHigh indicates a transaction is attempting to spend more // value than the sum of all of its inputs. ErrSpendTooHigh // ErrBadFees indicates the total fees for a block are invalid due to // exceeding the maximum possible value. ErrBadFees // ErrTooManySigOps indicates the total number of signature operations // for a transaction or block exceed the maximum allowed limits. ErrTooManySigOps // ErrFirstTxNotCoinbase indicates the first transaction in a block // is not a coinbase transaction. ErrFirstTxNotCoinbase // ErrMultipleCoinbases indicates a block contains more than one // coinbase transaction. ErrMultipleCoinbases // ErrBadCoinbaseScriptLen indicates the length of the signature script // for a coinbase transaction is not within the valid range. ErrBadCoinbaseScriptLen // ErrBadCoinbaseValue indicates the amount of a coinbase value does // not match the expected value of the subsidy plus the sum of all fees. ErrBadCoinbaseValue // ErrMissingCoinbaseHeight indicates the coinbase transaction for a // block does not start with the serialized block block height as // required for version 2 and higher blocks. ErrMissingCoinbaseHeight // ErrBadCoinbaseHeight indicates the serialized block height in the // coinbase transaction for version 2 and higher blocks does not match // the expected value. ErrBadCoinbaseHeight // ErrScriptMalformed indicates a transaction script is malformed in // some way. For example, it might be longer than the maximum allowed // length or fail to parse. ErrScriptMalformed // ErrScriptValidation indicates the result of executing transaction // script failed. The error covers any failure when executing scripts // such signature verification failures and execution past the end of // the stack. ErrScriptValidation // ErrUnexpectedWitness indicates that a block includes transactions // with witness data, but doesn't also have a witness commitment within // the coinbase transaction. ErrUnexpectedWitness // ErrInvalidWitnessCommitment indicates that a block's witness // commitment is not well formed. ErrInvalidWitnessCommitment // ErrWitnessCommitmentMismatch indicates that the witness commitment // included in the block's coinbase transaction doesn't match the // manually computed witness commitment. ErrWitnessCommitmentMismatch // ErrPrevBlockNotBest indicates that the block's previous block is not the // current chain tip. This is not a block validation rule, but is required // for block proposals submitted via getblocktemplate RPC. ErrPrevBlockNotBest ) // Map of ErrorCode values back to their constant names for pretty printing. var errorCodeStrings = map[ErrorCode]string{ ErrDuplicateBlock: "ErrDuplicateBlock", ErrBlockTooBig: "ErrBlockTooBig", ErrBlockVersionTooOld: "ErrBlockVersionTooOld", ErrBlockWeightTooHigh: "ErrBlockWeightTooHigh", ErrInvalidTime: "ErrInvalidTime", ErrTimeTooOld: "ErrTimeTooOld", ErrTimeTooNew: "ErrTimeTooNew", ErrDifficultyTooLow: "ErrDifficultyTooLow", ErrUnexpectedDifficulty: "ErrUnexpectedDifficulty", ErrHighHash: "ErrHighHash", ErrBadMerkleRoot: "ErrBadMerkleRoot", ErrBadCheckpoint: "ErrBadCheckpoint", ErrForkTooOld: "ErrForkTooOld", ErrCheckpointTimeTooOld: "ErrCheckpointTimeTooOld", ErrNoTransactions: "ErrNoTransactions", ErrTooManyTransactions: "ErrTooManyTransactions", ErrNoTxInputs: "ErrNoTxInputs", ErrNoTxOutputs: "ErrNoTxOutputs", ErrTxTooBig: "ErrTxTooBig", ErrBadTxOutValue: "ErrBadTxOutValue", ErrDuplicateTxInputs: "ErrDuplicateTxInputs", ErrBadTxInput: "ErrBadTxInput", ErrMissingTxOut: "ErrMissingTxOut", ErrUnfinalizedTx: "ErrUnfinalizedTx", ErrDuplicateTx: "ErrDuplicateTx", ErrOverwriteTx: "ErrOverwriteTx", ErrImmatureSpend: "ErrImmatureSpend", ErrSpendTooHigh: "ErrSpendTooHigh", ErrBadFees: "ErrBadFees", ErrTooManySigOps: "ErrTooManySigOps", ErrFirstTxNotCoinbase: "ErrFirstTxNotCoinbase", ErrMultipleCoinbases: "ErrMultipleCoinbases", ErrBadCoinbaseScriptLen: "ErrBadCoinbaseScriptLen", ErrBadCoinbaseValue: "ErrBadCoinbaseValue", ErrMissingCoinbaseHeight: "ErrMissingCoinbaseHeight", ErrBadCoinbaseHeight: "ErrBadCoinbaseHeight", ErrScriptMalformed: "ErrScriptMalformed", ErrScriptValidation: "ErrScriptValidation", ErrUnexpectedWitness: "ErrUnexpectedWitness", ErrInvalidWitnessCommitment: "ErrInvalidWitnessCommitment", ErrWitnessCommitmentMismatch: "ErrWitnessCommitmentMismatch", ErrPrevBlockNotBest: "ErrPrevBlockNotBest", } // String returns the ErrorCode as a human-readable name. func (e ErrorCode) String() string { if s := errorCodeStrings[e]; s != "" { return s } return fmt.Sprintf("Unknown ErrorCode (%d)", int(e)) } // RuleError identifies a rule violation. It is used to indicate that // processing of a block or transaction failed due to one of the many validation // rules. The caller can use type assertions to determine if a failure was // specifically due to a rule violation and access the ErrorCode field to // ascertain the specific reason for the rule violation. type RuleError struct { ErrorCode ErrorCode // Describes the kind of error Description string // Human readable description of the issue } // Error satisfies the error interface and prints human-readable errors. func (e RuleError) Error() string { return e.Description } // ruleError creates an RuleError given a set of arguments. func ruleError(c ErrorCode, desc string) RuleError { return RuleError{ErrorCode: c, Description: desc} }
maichain/listener
vendor/github.com/btcsuite/btcd/blockchain/error.go
GO
lgpl-3.0
11,052
package net.minecraft.src; import net.minecraft.server.MinecraftServer; import java.util.List; public class CommandServerBanlist extends CommandBase { public String getCommandName() { return "banlist"; } /** * Return the required permission level for this command. */ public int getRequiredPermissionLevel() { return 3; } /** * Returns true if the given command sender is allowed to use this command. */ public boolean canCommandSenderUseCommand(ICommandSender par1ICommandSender) { return (MinecraftServer.getServer().getConfigurationManager().getBannedIPs().isListActive() || MinecraftServer.getServer().getConfigurationManager().getBannedPlayers().isListActive()) && super.canCommandSenderUseCommand(par1ICommandSender); } public String getCommandUsage(ICommandSender par1ICommandSender) { return "commands.banlist.usage"; } public void processCommand(ICommandSender par1ICommandSender, String[] par2ArrayOfStr) { if (par2ArrayOfStr.length >= 1 && par2ArrayOfStr[0].equalsIgnoreCase("ips")) { par1ICommandSender.func_110122_a(ChatMessageComponent.func_111082_b("commands.banlist.ips", new Object[] {Integer.valueOf(MinecraftServer.getServer().getConfigurationManager().getBannedIPs().getBannedList().size())})); par1ICommandSender.func_110122_a(ChatMessageComponent.func_111066_d(joinNiceString(MinecraftServer.getServer().getConfigurationManager().getBannedIPs().getBannedList().keySet().toArray()))); } else { par1ICommandSender.func_110122_a(ChatMessageComponent.func_111082_b("commands.banlist.players", new Object[] {Integer.valueOf(MinecraftServer.getServer().getConfigurationManager().getBannedPlayers().getBannedList().size())})); par1ICommandSender.func_110122_a(ChatMessageComponent.func_111066_d(joinNiceString(MinecraftServer.getServer().getConfigurationManager().getBannedPlayers().getBannedList().keySet().toArray()))); } } /** * Adds the strings available in this command to the given list of tab completion options. */ public List addTabCompletionOptions(ICommandSender par1ICommandSender, String[] par2ArrayOfStr) { return par2ArrayOfStr.length == 1 ? getListOfStringsMatchingLastWord(par2ArrayOfStr, new String[] {"players", "ips"}): null; } }
Neil5043/Minetweak
src/main/java/net/minecraft/src/CommandServerBanlist.java
Java
lgpl-3.0
2,423
# Redmine - project management software # Copyright (C) 2006-2013 Jean-Philippe Lang # # 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. require File.expand_path('../../../test_helper', __FILE__) class RoutingPreviewsTest < ActionController::IntegrationTest def test_previews ["get", "post", "put"].each do |method| assert_routing( { :method => method, :path => "/issues/preview/new/123" }, { :controller => 'previews', :action => 'issue', :project_id => '123' } ) assert_routing( { :method => method, :path => "/issues/preview/edit/321" }, { :controller => 'previews', :action => 'issue', :id => '321' } ) end assert_routing( { :method => 'get', :path => "/news/preview" }, { :controller => 'previews', :action => 'news' } ) end end
HuaiJiang/pjm
test/integration/routing/previews_test.rb
Ruby
lgpl-3.0
1,499
/******************************************************************************* * logsniffer, open source tool for viewing, monitoring and analysing log data. * Copyright (c) 2015 Scaleborn UG, www.scaleborn.com * * logsniffer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * logsniffer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package com.logsniffer.util; import java.io.File; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; import com.logsniffer.app.ContextProvider; import com.logsniffer.app.DataSourceAppConfig.DBInitIndicator; import com.logsniffer.app.LogSnifferHome; import com.logsniffer.model.LogSourceProvider; import com.logsniffer.model.file.RollingLogsSource; import com.logsniffer.reader.filter.FilteredLogEntryReader; import com.logsniffer.reader.log4j.Log4jTextReader; /** * Registers LogSniffers own logs as source. * * @author mbok * */ @Component public class SniffMePopulator implements ApplicationContextAware { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private LogSnifferHome home; @Autowired private LogSourceProvider sourceProvider; @Autowired private DBInitIndicator dbInitIndicator; @Autowired private ContextProvider dummy; @SuppressWarnings({ "unchecked", "rawtypes" }) public void populate() { final RollingLogsSource myLogSource = new RollingLogsSource(); myLogSource.setPattern(new File(home.getHomeDir(), "logs/logsniffer.log").getPath()); myLogSource.setName("logsniffer's own log"); final Log4jTextReader reader = new Log4jTextReader(); reader.setFormatPattern("%d %-5p [%c] %m%n"); final Map<String, String> specifiersFieldMapping = new HashMap<>(); specifiersFieldMapping.put("d", "date"); specifiersFieldMapping.put("p", "priority"); specifiersFieldMapping.put("c", "category"); specifiersFieldMapping.put("m", "message"); reader.setSpecifiersFieldMapping(specifiersFieldMapping); myLogSource.setReader(new FilteredLogEntryReader(reader, null)); sourceProvider.createSource(myLogSource); logger.info("Created source for LogSniffer's own log: {}", myLogSource); } @Override public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { if (dbInitIndicator.isNewSchema()) { try { populate(); } catch (final Exception e) { logger.error("Failed to create logsniffer's own log", e); } } } }
logsniffer/logsniffer
logsniffer-core/src/main/java/com/logsniffer/util/SniffMePopulator.java
Java
lgpl-3.0
3,418
# -*- coding: utf-8 -*- __author__ = 'sdukaka' #只是为了测试一下装饰器的作用 decorator import functools def log(func): @functools.wraps(func) def wrapper(*args, **kw): print('call %s():' % func.__name__) return func(*args, **kw) return wrapper @log def now(): print('2015-3-25') now() def logger(text): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): print('%s %s():' % (text, func.__name__)) return func(*args, **kw) return wrapper return decorator @logger('DEBUG') def today(): print('2015-3-25') today() print(today.__name__)
sdukaka/sdukakaBlog
test_decorator.py
Python
lgpl-3.0
664
/************************************************************************* * * ADOBE CONFIDENTIAL * __________________ * * Copyright 2002 - 2007 Adobe Systems Incorporated * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Adobe Systems Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Adobe Systems Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Adobe Systems Incorporated. **************************************************************************/ package flex.management; import java.util.ArrayList; import java.util.Iterator; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import flex.messaging.log.Log; import flex.messaging.log.LogCategories; /** * The default implementation of an MBeanServerLocator. This implementation * returns the first MBeanServer from the list returned by MBeanServerFactory.findMBeanServer(null). * If no MBeanServers have been instantiated, this class will request the creation * of an MBeanServer and return a reference to it. * * @author shodgson */ public class DefaultMBeanServerLocator implements MBeanServerLocator { private MBeanServer server; /** {@inheritDoc} */ public synchronized MBeanServer getMBeanServer() { if (server == null) { // Use the first MBeanServer we can find. ArrayList servers = MBeanServerFactory.findMBeanServer(null); if (servers.size() > 0) { Iterator iterator = servers.iterator(); server = (MBeanServer)iterator.next(); } else { // As a last resort, try to create a new MBeanServer. server = MBeanServerFactory.createMBeanServer(); } if (Log.isDebug()) Log.getLogger(LogCategories.MANAGEMENT_MBEANSERVER).debug("Using MBeanServer: " + server); } return server; } }
SOASTA/BlazeDS
modules/core/src/java/flex/management/DefaultMBeanServerLocator.java
Java
lgpl-3.0
2,377
# -*- coding: utf-8 -*- # util.py # Copyright (C) 2012 Red Hat, Inc. # # Authors: # Akira TAGOH <tagoh@redhat.com> # # This library is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gettext import gi import os.path import string from collections import OrderedDict from fontstweak import FontsTweak from gi.repository import Gtk def N_(s): return s class FontsTweakUtil: @classmethod def find_file(self, uifile): path = os.path.dirname(os.path.realpath(__file__)) f = os.path.join(path, 'data', uifile) if not os.path.isfile(f): f = os.path.join(path, '..', 'data', uifile) if not os.path.isfile(f): f = os.path.join(FontsTweak.UIPATH, uifile) return f @classmethod def create_builder(self, uifile): builder = Gtk.Builder() builder.set_translation_domain(FontsTweak.GETTEXT_PACKAGE) builder.add_from_file(self.find_file(uifile)) return builder @classmethod def translate_text(self, text, lang): try: self.translations except AttributeError: self.translations = {} if self.translations.has_key(lang) == False: self.translations[lang] = gettext.translation( domain=FontsTweak.GETTEXT_PACKAGE, localedir=FontsTweak.LOCALEDIR, languages=[lang.replace('-', '_')], fallback=True, codeset="utf8") return unicode(self.translations[lang].gettext(text), "utf8") @classmethod def get_language_list(self, default): dict = OrderedDict() if default == True: dict[''] = N_('Default') try: fd = open(self.find_file('locale-list'), 'r') except: raise RuntimeError, "Unable to open locale-list" while True: line = fd.readline() if not line: break tokens = string.split(line) lang = str(tokens[0]).split('.')[0].replace('_', '-') dict[lang] = string.join(tokens[3:], ' ') return dict
jamesni/fonts-tweak-tool
fontstweak/util.py
Python
lgpl-3.0
2,700