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 |
|---|---|---|---|---|---|
<?php
/**
* @package copix
* @subpackage taglib
* @author Salleyron Julien
* @copyright 2000-2006 CopixTeam
* @link http://www.copix.org
* @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public Licence, see LICENCE file
*/
/**
* Génération de fenetre confirm
* @package copix
* @subpackage taglib
*/
class TemplateTagConfirm extends CopixTemplateTag {
public function process ($pParams, $pContent=null){
$toReturn = ' '.$pContent.'<br /><br />';
$toReturn .= ' <a href="'.CopixUrl::get($pParams['yes']).'">'._i18n('copix:common.buttons.yes').'</a>';
$toReturn .= ' <a href="'.CopixUrl::get($pParams['no']).'">'._i18n('copix:common.buttons.no').'</a>';
_tag('mootools');
CopixHTMLHeader::addJsCode ("
window.addEvent('domready', function () {
var elem = new Element('div');
elem.setStyles({'z-index':99999,'background-color':'white','border':'1px solid black','width':'200px','height':'100px','top': window.getScrollTop().toInt()+window.getHeight ().toInt()/2-100+'px','left':window.getScrollLeft().toInt()+window.getWidth ().toInt()/2-100+'px','position':'absolute','text-align':'center'});
elem.setHTML ('$toReturn');
elem.injectInside(document.body);
});
");
return null;
}
}
?> | Copix/Copix3 | utils/copix/taglib/confirm.templatetag.php | PHP | lgpl-2.1 | 1,308 |
/*
* 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.test.annotations.cascade.circle.identity;
/**
* No Documentation
*/
@javax.persistence.Entity
public class C extends AbstractEntity {
private static final long serialVersionUID = 1226955752L;
/**
* No documentation
*/
@javax.persistence.ManyToOne(cascade = {
javax.persistence.CascadeType.MERGE, javax.persistence.CascadeType.PERSIST, javax.persistence.CascadeType.REFRESH}
, optional = false)
private A a;
/**
* No documentation
*/
@javax.persistence.ManyToOne(cascade = {
javax.persistence.CascadeType.MERGE, javax.persistence.CascadeType.PERSIST, javax.persistence.CascadeType.REFRESH}
)
private G g;
/**
* No documentation
*/
@javax.persistence.ManyToOne(cascade = {
javax.persistence.CascadeType.MERGE, javax.persistence.CascadeType.PERSIST, javax.persistence.CascadeType.REFRESH}
, optional = false)
private B b;
public A getA() {
return a;
}
public void setA(A parameter) {
this.a = parameter;
}
public G getG() {
return g;
}
public void setG(G parameter) {
this.g = parameter;
}
public B getB() {
return b;
}
public void setB(B parameter) {
this.b = parameter;
}
}
| 1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/test/java/org/hibernate/test/annotations/cascade/circle/identity/C.java | Java | lgpl-2.1 | 1,549 |
package osmo.tester.parser;
/**
* A model-object that represents test model elements.
*
* @author Teemu Kanstren
*/
public class ModelObject {
/** Prefix of the model object, added to names of all parsed test steps, guards, etc. */
private final String prefix;
/** The model object, which implements a set of given test steps, guards, etc. to be invoked. */
private final Object object;
public ModelObject(String prefix, Object object) {
this.prefix = prefix;
this.object = object;
}
public ModelObject(Object object) {
this.prefix = "";
this.object = object;
}
public String getPrefix() {
return prefix;
}
public Object getObject() {
return object;
}
}
| mukatee/osmo | osmotester/src/osmo/tester/parser/ModelObject.java | Java | lgpl-2.1 | 742 |
// ---------------------------------------------------------------------------
// DeviceÖANX
// Original : cisc
// Modification : Yumitaro
// ---------------------------------------------------------------------------
#include <string.h>
#include <new>
#include "device.h"
////////////////////////////////////////////////////////////////
// DeviceList
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
// RXgN^
////////////////////////////////////////////////////////////////
DeviceList::DeviceList( void ) : node(NULL) {}
////////////////////////////////////////////////////////////////
// fXgN^
////////////////////////////////////////////////////////////////
DeviceList::~DeviceList( void )
{
Cleanup();
}
////////////////////////////////////////////////////////////////
// m[hõ
////////////////////////////////////////////////////////////////
DeviceList::Node *DeviceList::FindNode( const ID id )
{
for( Node *n = node; n; n = n->next ){
if( n->entry->GetID() == id )
return n;
}
return NULL;
}
////////////////////////////////////////////////////////////////
// foCXXgSÁ
////////////////////////////////////////////////////////////////
void DeviceList::Cleanup( void )
{
Node *n = node;
while( n ){
Node *nx = n->next;
delete n;
n = nx;
}
node = NULL;
}
////////////////////////////////////////////////////////////////
// foCXÇÁ
////////////////////////////////////////////////////////////////
bool DeviceList::Add( IDevice *t )
{
ID id = t->GetID();
if( !id ) return false;
Node *n = FindNode( id );
if( n ){
n->count++;
return true;
}else{
n = new Node;
if( !n ) return false;
n->entry = t;
n->next = node;
n->count = 1;
node = n;
return true;
}
}
////////////////////////////////////////////////////////////////
// foCXí(|C^)
////////////////////////////////////////////////////////////////
bool DeviceList::Del( IDevice *t )
{
return t->GetID() ? Del( t->GetID() ) : false;
}
////////////////////////////////////////////////////////////////
// foCXí(ID)
////////////////////////////////////////////////////////////////
bool DeviceList::Del( const ID id )
{
for( Node **r = &node; *r; r = &((*r)->next) ){
if( ((*r)->entry->GetID() == id) && ((*r)->count) ){
((*r)->count)--;
// if( (*r)->entry->GetID() == id ){
// Node* d = *r;
// if( !--d->count ){
// *r = d->next;
// delete d;
// }
return true;
}
}
return false;
}
////////////////////////////////////////////////////////////////
// foCXõ
////////////////////////////////////////////////////////////////
IDevice *DeviceList::Find( const ID id )
{
Node *n = FindNode( id );
return n ? n->entry : NULL;
}
| meesokim/p6001v | src/device.cpp | C++ | lgpl-2.1 | 2,818 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ch.unizh.ini.jaer.projects.eventbasedfeatures;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import net.sf.jaer.Description;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.graphics.ImageDisplay;
/** This class develops an intensity map representation of the incoming AE events. A ring buffer
* is maintained at each pixel to keep track of the history of the events at that position.
* A score is calculated for each pixel position - +1 for every ON event that enters the ring buffer (hence, -1
* for every ON event that leaves) and -1 for every OFF event that enters the ring buffer (hence, -1
* for every OFF event that leaves)
*
* @author Varad
*/
@Description("Creates an intensity map representation of AE events")
public class PixelBuffer extends EventFilter2D {
public int RingBufferSize = getPrefs().getInt("PixelBuffer.RingBufferSize", 1);
public boolean renderBufferMap = getPrefs().getBoolean("PixelBuffer.renderBufferMap", false);
public boolean hasKernelImplementor = false;
public boolean hasConvolutionFeatureScheme = false;
public boolean hasBinaryFeatureDetector = false;
KernelImplementor kernelimplement;
ConvolutionFeatureScheme featurescheme;
BinaryFeatureDetector bindetect;
public float max ;
public float min ;
public float base;
public int sizex;
public int sizey;
public int maplength;
public float[] colorv;
public int[] map;
public RingBuffer[] rbarr;
ImageDisplay disp;
JFrame frame;
public PixelBuffer (AEChip chip){
super(chip);
this.chip = chip;
final String sz = "Size";
setPropertyTooltip(sz, "RingBufferSize", "sets size of ring buffer");
sizex = chip.getSizeX();
sizey = chip.getSizeY();
disp = ImageDisplay.createOpenGLCanvas(); // makde a new ImageDisplay GLCanvas with default OpenGL capabilities
frame = new JFrame("ImageFrame"); // make a JFrame to hold it
frame.setPreferredSize(new Dimension(sizex, sizey)); // set the window size
frame.getContentPane().add(disp, BorderLayout.CENTER); // add the GLCanvas to the center of the window
frame.pack(); // otherwise it wont fill up the display
initFilter();
resetFilter();
}
synchronized public boolean isRenderBufferMapEnabled(){
return renderBufferMap;
}
synchronized public void setRenderBufferMapEnabled( boolean renderBufferMap ) {
this.renderBufferMap = renderBufferMap;
getPrefs().putBoolean("PixelBuffer.renderBufferMap", renderBufferMap);
getSupport().firePropertyChange("renderBufferMap", this.renderBufferMap, renderBufferMap);
resetFilter();
}
synchronized public int getRingBufferSize (){
return RingBufferSize;
}
synchronized public void setRingBufferSize( int RingBufferSize){
this.RingBufferSize = RingBufferSize;
getPrefs().putInt("PixelBuffer.RingBufferSize", RingBufferSize);
getSupport().firePropertyChange("RingBufferSize", this.RingBufferSize, RingBufferSize);
resetFilter();
}
synchronized public void setKernelImplementor(KernelImplementor kernelimplement){
this.hasKernelImplementor = true;
this.kernelimplement = kernelimplement;
}
synchronized public void setConvolutionFeatureScheme(ConvolutionFeatureScheme featurescheme){
this.hasConvolutionFeatureScheme = true;
this.featurescheme = featurescheme;
}
synchronized public void setBinaryFeatureDetector(BinaryFeatureDetector bindetect){
this.hasBinaryFeatureDetector = true;
this.bindetect = bindetect;
}
synchronized private void checkMaps (){
if ( rbarr == null || rbarr.length != (chip.getSizeX()*chip.getSizeY()) )
resetRingBuffers();
}
synchronized private void resetRingBuffers(){
max = 1;
min = 0;
maplength = sizex*sizey;
base = ((max+min)/2);
int size = 128;
disp.setImageSize(size, size); // set dimensions of image
disp.resetFrame(base);
frame.setVisible(true); // make the frame visible
map = new int[maplength];
rbarr = new RingBuffer[maplength];
colorv = new float[maplength];
for (int a = 0; a < maplength; a++){
rbarr[a] = new RingBuffer( getRingBufferSize() );
}
}
public class RingBuffer{
public final int length; // buffer length
public int[] buffer; // an array of fixed length
public int leadPointer, trailPointer ;
public boolean fullflag;
public RingBuffer(int cap){
length = cap;
resetBuffer();
}
public void resetBuffer(){
buffer = new int[length];
this.leadPointer = 0;
this.fullflag = false;
}
public int incrIndex(int i){
i++;
if(i>=length)i=0;
return i;
}
public void insert( PolarityEvent e){
buffer[leadPointer] = e.getType();
leadPointer = incrIndex(leadPointer);
if(leadPointer == 0) this.fullflag = true;
}
public int getOldest(){
return buffer[leadPointer];
}
}
@Override
synchronized public EventPacket filterPacket(EventPacket in) {
sizex = chip.getSizeX();
sizey = chip.getSizeY();
if ( in == null ){
return null;
}
if ( enclosedFilter != null ){
in = enclosedFilter.filterPacket(in);
}
checkMaps();
if(hasKernelImplementor) kernelimplement.kernel.checkMaps();
if(hasConvolutionFeatureScheme) featurescheme.detector.checkMaps();
if(hasBinaryFeatureDetector){
bindetect.kernel.checkMaps();
bindetect.binaryMethod.checkMaps();
}
for ( Object ein:in ){
PolarityEvent e = (PolarityEvent)ein;
int type = e.getType();
int x = e.getX();
int y = e.getY();
int index = getIndex(x, y);
if( !rbarr[index].fullflag){ //partially or unfilled buffer
if( type == 1){ //ON event
map[index] += 1;
if(hasKernelImplementor && kernelimplement.kernel!= null)
kernelimplement.kernel.updateMap(x, y, 1);
if(hasConvolutionFeatureScheme && featurescheme.kernel!= null)
featurescheme.detector.getFeatures(x, y, 1, featurescheme.RelativeThreshold, e);
if(hasBinaryFeatureDetector && bindetect.kernel!=null){
bindetect.kernel.updateMap(x, y, 1);
bindetect.binaryMethod.getFeatures(x, y);
}
}
else{ //OFF event
map[index] -= 1;
if(hasKernelImplementor && kernelimplement.kernel!= null)
kernelimplement.kernel.updateMap(x, y, -1);
if(hasConvolutionFeatureScheme && featurescheme.kernel!= null)
featurescheme.detector.getFeatures(x, y, -1, featurescheme.RelativeThreshold, e);
if(hasBinaryFeatureDetector && bindetect.kernel!=null){
bindetect.kernel.updateMap(x, y, -1);
bindetect.binaryMethod.getFeatures(x, y);
}
}
checkMax(index);
checkMin(index);
}
else{ //filled to the capacity at least once
if ( type == rbarr[index].getOldest() ){ //if incoming event is same
; //as one being pushed out ;
}
else{
if( type == 1 ){ //ON event
map[index] += 2;
if(hasKernelImplementor && kernelimplement.kernel!= null)
kernelimplement.kernel.updateMap(x, y, 2);
if(hasConvolutionFeatureScheme && featurescheme.kernel!= null){
featurescheme.detector.getFeatures(x, y, 2, featurescheme.RelativeThreshold, e);
}
if(hasBinaryFeatureDetector && bindetect.kernel!=null){
bindetect.kernel.updateMap(x, y, 2);
bindetect.binaryMethod.getFeatures(x, y);
}
}
else{ //OFF event
map[index] -= 2;
if(hasKernelImplementor && kernelimplement.kernel!= null)
kernelimplement.kernel.updateMap(x, y, -2);
if(hasConvolutionFeatureScheme && featurescheme.kernel!= null)
featurescheme.detector.getFeatures(x, y, -2, featurescheme.RelativeThreshold, e);
if(hasBinaryFeatureDetector && bindetect.kernel!=null){
bindetect.kernel.updateMap(x, y, -2);
bindetect.binaryMethod.getFeatures(x, y);
}
}
checkMax(index);
checkMin(index);
}
}
if(isRenderBufferMapEnabled()){
colorv[index] = (float)((map[index] - min)/(max - min));
disp.checkPixmapAllocation(); // make sure we have a pixmaps (not resally necessary since setting size will allocate pixmap
disp.setPixmapRGB(x, y, colorv[index], colorv[index], colorv[index]);
}
rbarr[index].insert(e);
}
if(hasKernelImplementor){
kernelimplement.kernel.display.setPixmapArray(kernelimplement.kernel.grayvalue);
kernelimplement.kernel.display.repaint();
// kernelimplement.kernel.updateFeatures(kernelimplement.kernel.keypoints, kernelimplement.RelativeThreshold);
}
if(hasConvolutionFeatureScheme){
featurescheme.detector.display.setPixmapArray(featurescheme.detector.grayvalue);
featurescheme.detector.display.repaint();
// featurescheme.kernel.updateFeatures(featurescheme.kernel.keypoints, featurescheme.RelativeThreshold);
}
// if(hasBinaryFeatureDetector){
// bindetect.kernel.display.setPixmapArray(bindetect.kernel.grayvalue);
// bindetect.kernel.display.repaint();
//// bindetect.binaryMethod.updateFeatures(bindetect.binaryMethod.keypoints);
//
// }
disp.repaint();
return in;
}
public void checkMax(int index){
if ( map[index] > max ){
max = map[index];
}
}
public void checkMin(int index){
if ( map[index] < min ){
min = map[index];
}
}
public int getIndex(int x, int y){
int index = (x + (y*sizex));
return index;
}
@Override
public void resetFilter() {
if(!isFilterEnabled())
return;
resetRingBuffers();
}
@Override
public void initFilter() {
resetFilter();
}
}
//public class RingBuffer extends AbstractList<PolarityEvent> implements RandomAccess { //or extends Object
//
// private final int n; // buffer length
// private final List<PolarityEvent> buf; // a List implementing RandomAccess
// private int leader = 0;
// private int size = 0;
//
//
//
//
// public RingBuffer(int capacity) { //constructor for the ring buffer with size as argument
// n = capacity + 1;
// buf = new ArrayList<PolarityEvent>(Collections.nCopies(n, (PolarityEvent) null));
// }
//
// private int wrapIndex(int i) { //implementing circularity
// int m = i % n;
// if (m < 0) {
// m += n;
// }
// return m;
// }
//
// @Override
// public int size() {
// return this.size;
// }
//
// @Override
// public PolarityEvent get(int i) { //PolarityEvent is a defined return type
// //this code returns the buffer member at the requested index
// if (i < 0 || i >= n-1) throw new IndexOutOfBoundsException();
//
// if(i > size()) throw new NullPointerException("Index is greater than size.");
//
// return buf.get(wrapIndex(leader + i));
// }
//
// @Override
// public PolarityEvent set(int i, PolarityEvent e) { //this code sets the buffer member at the requested index
// if (i < 0 || i >= n-1) {
// throw new IndexOutOfBoundsException();
// }
// if(i == size()) // assume leader's position as invalid (should use insert(e))
// throw new IndexOutOfBoundsException("The size of the list is " + size() + " while the index was " + i
// +"");
// return buf.set(wrapIndex(leader - size + i), e);
// }
//
// public void insert(PolarityEvent e) //adds a new element
// {
// int s = size();
// buf.set(wrapIndex(leader), e);
// leader = wrapIndex(++leader);
// buf.set(leader, null);
// if(s == n-1){
// fullflag[e.x][e.y] = true;
// return; // we have replaced the eldest element.
// }
//
// this.size++;
//
// }
//
// public PolarityEvent getOldest(){ //returns oldest member i.e. index 99 of the buffer
// int i = wrapIndex(leader+1);
// PolarityEvent a = null;
//
// for(;;i = wrapIndex(++i)) {
// if(buf.get(i) != null) break;
// if(i == leader) //break;
// throw new IllegalStateException("Cannot remove element."
// + " CircularArrayList is empty.");
// }
//// if( i!= leader )
//// a = buf.get(i);
// return buf.get(i);
// }
// }
///*
// * To change this template, choose Tools | Templates
// * and open the template in the editor.
// */
//package ch.unizh.ini.jaer.projects.eventbasedfeatures;
//
//
///**
// *
// * @author Varad
// */
//public class PixelTimeBuffer extends EventFilter2D{
//
// public int RingBufferSize = getPrefs().getInt("PixelTimeBuffer.RingBufferSize", 1);
// public int dt = getPrefs().getInt("PixelTimeBuffer.dt", 500);
//
// public int sizex;
// public int sizey;
//
// public float max ;
// public float min ;
//
// public float[][] map;
// public RingBuffer[][] rbarr;
//
// public float[][] colorv;
//
// ImageDisplay disp;
// JFrame frame;
//
// public PixelTimeBuffer (AEChip chip){
//
// super(chip);
// this.chip = chip;
//
// final String sz = "Size", tim = "Timing";
//
// setPropertyTooltip(sz, "RingBufferSize", "sets size of ring buffer");
// setPropertyTooltip(tim, "dt", "Events with less than this delta time in us to neighbors pass through");
//
// sizex = chip.getSizeX();
// sizey = chip.getSizeY();
//
// disp = ImageDisplay.createOpenGLCanvas(); // makde a new ImageDisplay GLCanvas with default OpenGL capabilities
// frame = new JFrame("ImageFrame"); // make a JFrame to hold it
// frame.setPreferredSize(new Dimension(sizex, sizey)); // set the window size
// frame.getContentPane().add(disp, BorderLayout.CENTER); // add the GLCanvas to the center of the window
// frame.pack(); // otherwise it wont fill up the display
// }
//
// synchronized public int getRingBufferSize (){
// return RingBufferSize;
// }
//
// synchronized public void setRingBufferSize( int RingBufferSize){
// this.RingBufferSize = RingBufferSize;
// getPrefs().putInt("PixelTimeBuffer.RingBufferSize", RingBufferSize);
// getSupport().firePropertyChange("RingBufferSize", this.RingBufferSize, RingBufferSize);
// resetFilter();
// }
//
// public int getDt() {
// return this.dt;
// }
//
// public void setDt(final int dt) {
// this.dt = dt;
// getPrefs().putInt("PixelTimeBuffer.dt", dt);
// getSupport().firePropertyChange("dt", this.dt, dt);
// resetFilter();
// }
//
// synchronized public void checkMaps (){
// if ( rbarr == null || rbarr.length != chip.getSizeX() || rbarr[0].length != chip.getSizeY() )
// resetRingBuffers();
// }
//
// public void resetRingBuffers(){
//
// int size = 128;
// disp.setImageSize(size, size); // set dimensions of image
// frame.setVisible(true); // make the frame visible
//
// max = 1;
// min = 0;
// map = new float[sizex][sizey];
// rbarr = new RingBuffer[sizex][sizey];
// colorv = new float[sizex][sizey];
//
// for (int a = 0; a < sizex; a++){
// for (int b = 0; b < sizey; b++){
// rbarr[a][b] = new RingBuffer( getRingBufferSize() );
// }
// }
// }
//
// public class RingBuffer{
//
// public int length ;
// public PolarityEvent[] buffer; // an array of fixed length
// public int leadPointer, trailPointer ;
// public boolean arrayEmpty;
// public int typeOldest;
//
// public RingBuffer(int cap){
// length = cap;
// resetBuffer();
// }
//
// public void resetBuffer(){
// buffer = new PolarityEvent[length];
// this.leadPointer = 0;
// this.trailPointer = 0;
// this.arrayEmpty = true;
// this.typeOldest = 0;
// }
//
// public int incrIndex(int i){
//
// i++;
// return(wrapIndex(i));
// }
//
// public int wrapIndex(int j){
//
// if(j>=length)j=0;
// return j;
// }
//
// public void insert( PolarityEvent e){
//
// buffer[leadPointer] = e;
// leadPointer = incrIndex(leadPointer);
//
// if(this.arrayEmpty == true)
// this.arrayEmpty = false;
//
//
//
// }
//
// public PolarityEvent getOldest(){
//
// return buffer[this.trailPointer];
// }
//
// public void updateBuffer(PolarityEvent e){
//
// int x = e.getX();
// int y = e.getY();
//
//// if(buffer[this.trailPointer] != null){
// while( ((e.getTimestamp() - rbarr[x][y].getOldest().getTimestamp()) > dt) && (rbarr[x][y].leadPointer != rbarr[x][y].trailPointer)){
//
// if( (rbarr[x][y].buffer[rbarr[x][y].trailPointer]).getType() == 1){
// map[x][y] -= 1;
// }
// else{
// map[x][y] += 1;
// }
// checkMax(e);
// checkMin(e);
//
// removeEvent();
// }
//
// }
//
// public void removeEvent(){
//
// buffer[this.trailPointer] = null;
// this.trailPointer = incrIndex(this.trailPointer);
//
// if(this.leadPointer == this.trailPointer)
// this.arrayEmpty = true;
// }
//
//
// }
// @Override
// public EventPacket<?> filterPacket(EventPacket<?> in) {
//
// sizex = chip.getSizeX();
// sizey = chip.getSizeY();
//
// if ( in == null ){
// return null;
// }
//
// if ( enclosedFilter != null ){
// in = enclosedFilter.filterPacket(in);
// }
//
// checkMaps();
//
// for ( Object ein:in ){
//
// PolarityEvent e = (PolarityEvent)ein;
// int type = e.getType();
// int x = e.getX();
// int y = e.getY();
//
// if(rbarr[x][y].arrayEmpty == true){
//
// if( type == 1 ){ //ON event
// map[x][y] += 1;
// }
// else{
// map[x][y] -= 1;
// }
// checkMax(e);
// checkMin(e);
//
// }
//
// else{
//
//// if(rbarr[x][y].leadPointer == 0){
//
// if((rbarr[x][y].leadPointer == rbarr[x][y].trailPointer) && rbarr[x][y].arrayEmpty == false){
//
//// System.out.print(2+"\n");
//
// rbarr[x][y].typeOldest = rbarr[x][y].getOldest().getType();
// rbarr[x][y].trailPointer = rbarr[x][y].incrIndex(rbarr[x][y].trailPointer);
//// rbarr[x][y].removeEvent();
//
// rbarr[x][y].updateBuffer(e);
//
// if(rbarr[x][y].arrayEmpty == true){
//
// if( type == 1 ){ //ON event
// map[x][y] += 1;
// }
// else{
// map[x][y] -= 1;
// }
// checkMax(e);
// checkMin(e);
// }
//
// else{
//
// if(rbarr[x][y].trailPointer == rbarr[x][y].wrapIndex(rbarr[x][y].leadPointer + 1)){
//
//// System.out.print(2+"\n");
//
// if ( type == rbarr[x][y].typeOldest ) { //if incoming event is same
// ;
//// System.out.print(3+"\n");
// }
// else{
// if( type == 1 ){ //ON event
// map[x][y] += 2;
//
// }
// else{ //OFF event
// map[x][y] -= 2;
// }
// checkMax(e);
// checkMin(e);
// }
//
//// rbarr[x][y].removeEvent();
//
// }
//
// else{
// if( type == 1 ){ //ON event
// map[x][y] += 1;
// }
// else{
// map[x][y] -= 1;
// }
//
// checkMax(e);
// checkMin(e);
// }
// }
//
// }
//
// else{
// if( type == 1 ){ //ON event
// map[x][y] += 1;
// }
// else{
// map[x][y] -= 1;
// }
// checkMax(e);
// checkMin(e);
// }
// }
//
// colorv[x][y] = (float)((map[x][y] - min)/(max - min));
// disp.checkPixmapAllocation(); // make sure we have a pixmaps (not really necessary since setting size will allocate pixmap
// disp.setPixmapRGB(x, y, colorv[x][y], colorv[x][y], colorv[x][y]);
// rbarr[x][y].insert(e);
// }
//
// disp.repaint();
// return in;
// }
//
//
//
// synchronized public void checkMax(PolarityEvent e){
//
// int x = e.getX();
// int y = e.getY();
// if ( map[x][y] > max ){
// max = map[x][y];
//
// }
// }
//
// synchronized public void checkMin(PolarityEvent e){
//
// int x = e.getX();
// int y = e.getY();
// if ( map[x][y] < min ){
// min = map[x][y];
//
// }
// }
//
//
// @Override
// public void resetFilter() {
//
// if(!isFilterEnabled())
// return;
//
// disp.clearImage();
// resetRingBuffers();
// }
//
// @Override
// public void initFilter() {
// resetFilter();
// }
//
//
//}
| viktorbahr/jaer | src/ch/unizh/ini/jaer/projects/eventbasedfeatures/PixelBuffer.java | Java | lgpl-2.1 | 27,642 |
package iax.protocol.user.command;
import iax.protocol.peer.Peer;
/**
* Facade to user commands.
*/
public class UserCommandFacade {
/**
* Method that indicates that user has answered an incoming call.
* @param peer Current peer.
* @param callingNumber the calling number of the call that is going to be accepted
*/
public static void answerCall(Peer peer, String callingNumber) {
(new AnswerCall(peer, callingNumber)).execute();
}
/**
* Method to hang up a call.
* @param peer Current peer.
* @param calledNumber The number of the hung call.
*/
public static void hangupCall(Peer peer, String calledNumber) {
(new HangupCall(peer, calledNumber)).execute();
}
/**
* Method to hold a call.
* @param peer Current peer.
* @param calledNumber The number of the muted call.
*/
public static void holdCall(Peer peer, String calledNumber) {
(new HoldCall(peer, calledNumber)).execute();
}
/**
* Method to start a new call.
* @param peer Current peer.
* @param calledNumber Number to call to.
*/
public static void newCall(Peer peer, String calledNumber) {
(new NewCall(peer, calledNumber)).execute();
}
/**
* Exit from the system
* @param peer Current peer.
*/
public static void exit(Peer peer) {
(new Exit(peer)).execute();
}
/**
* Method to mute a call.
* @param peer Current peer.
* @param calledNumber The number of the muted call.
*/
public static void muteCall(Peer peer, String calledNumber) {
(new MuteCall(peer, calledNumber)).execute();
}
/**
* Method to unhold a call.
* @param peer Current peer.
* @param calledNumber The number of the muted call.
*/
public static void unHoldCall(Peer peer, String calledNumber) {
(new UnHoldCall(peer, calledNumber)).execute();
}
/**
* Method to unmute a call.
* @param peer Current peer.
* @param calledNumber The number of the muted call.
*/
public static void unMuteCall(Peer peer, String calledNumber) {
(new UnMuteCall(peer, calledNumber)).execute();
}
/**
* Method to send a DTMF tone.
* @param peer Current peer.
* @param calledNumber The number of the muted call.
*/
public static void sendDTMF(Peer peer, String calledNumber, char tone) {
(new SendDTMF(peer, calledNumber, tone)).execute();
}
/**
* Method to transfer a call.
* @param peer Current peer.
* @param srcNumber the source number of the transfer
* @param dstNumber the destination number of the transfer
*/
public static void transferCall(Peer peer, String srcNumber, String dstNumber) {
(new TransferCall(peer, srcNumber, dstNumber)).execute();
}
} | jonmersha/njiax | src/iax/protocol/user/command/UserCommandFacade.java | Java | lgpl-2.1 | 2,903 |
/******************************************************************************
jXEventUtil.cpp
Useful functions for dealing with X events.
Copyright © 1996 John Lindal. All rights reserved.
******************************************************************************/
#include <JXStdInc.h>
#include <jXEventUtil.h>
#include <JXDisplay.h>
#include <JString.h>
#include <jAssert.h>
/******************************************************************************
JXIsPrint
Returns kJTrue if the keysym is between 1 and 255 and isprint() returns
kJTrue.
******************************************************************************/
JBoolean
JXIsPrint
(
const int keysym
)
{
return JConvertToBoolean( 0 < keysym && keysym <= 255 && JIsPrint(keysym) );
}
/******************************************************************************
JXGetEventTime
Return the time stamp of the event. Returns kJFalse if the given
event doesn't contain a time stamp.
Selection events contain a time field, but this is a timestamp generated
by clients, not the current server time.
******************************************************************************/
JBoolean
JXGetEventTime
(
const XEvent& xEvent,
Time* time
)
{
*time = 0;
if (xEvent.type == KeyPress || xEvent.type == KeyRelease)
{
*time = xEvent.xkey.time;
return kJTrue;
}
else if (xEvent.type == ButtonPress || xEvent.type == ButtonRelease)
{
*time = xEvent.xbutton.time;
return kJTrue;
}
else if (xEvent.type == MotionNotify)
{
*time = xEvent.xmotion.time;
return kJTrue;
}
else if (xEvent.type == EnterNotify || xEvent.type == LeaveNotify)
{
*time = xEvent.xcrossing.time;
return kJTrue;
}
else if (xEvent.type == PropertyNotify)
{
*time = xEvent.xproperty.time;
return kJTrue;
}
else
{
return kJFalse; // event doesn't contain the information
}
}
/******************************************************************************
JXGetButtonAndModifierStates
Return the button and key modifiers states of the event.
Returns kJFalse if the given event doesn't contain the information.
******************************************************************************/
JBoolean
JXGetButtonAndModifierStates
(
const XEvent& xEvent,
JXDisplay* display,
unsigned int* state
)
{
*state = 0;
if (xEvent.type == KeyPress)
{
*state = xEvent.xkey.state;
JIndex modifierIndex;
if (display->KeycodeToModifier(xEvent.xkey.keycode, &modifierIndex))
{
*state = JXKeyModifiers::SetState(display, *state, modifierIndex, kJTrue);
}
return kJTrue;
}
else if (xEvent.type == KeyRelease)
{
*state = xEvent.xkey.state;
JIndex modifierIndex;
if (display->KeycodeToModifier(xEvent.xkey.keycode, &modifierIndex))
{
*state = JXKeyModifiers::SetState(display, *state, modifierIndex, kJFalse);
}
return kJTrue;
}
else if (xEvent.type == ButtonPress)
{
const JXMouseButton currButton = (JXMouseButton) xEvent.xbutton.button;
*state = JXButtonStates::SetState(xEvent.xbutton.state,
currButton, kJTrue);
return kJTrue;
}
else if (xEvent.type == ButtonRelease)
{
const JXMouseButton currButton = (JXMouseButton) xEvent.xbutton.button;
*state = JXButtonStates::SetState(xEvent.xbutton.state,
currButton, kJFalse);
return kJTrue;
}
else if (xEvent.type == MotionNotify)
{
*state = xEvent.xmotion.state;
return kJTrue;
}
else if (xEvent.type == EnterNotify || xEvent.type == LeaveNotify)
{
*state = xEvent.xcrossing.state;
return kJTrue;
}
else
{
return kJFalse; // event doesn't contain the information
}
}
| mbert/mulberry-lib-jx | libjx/code/jXEventUtil.cpp | C++ | lgpl-2.1 | 3,644 |
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2022, by David Gilbert and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* 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.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ---------------------------
* XYSeriesLabelGenerator.java
* ---------------------------
* (C) Copyright 2004-2022, by David Gilbert.
*
* Original Author: David Gilbert;
* Contributor(s): -;
*
*/
package org.jfree.chart.labels;
import org.jfree.data.xy.XYDataset;
/**
* A generator that creates labels for the series in an {@link XYDataset}.
* <P>
* Classes that implement this interface should be either (a) immutable, or
* (b) cloneable via the {@code PublicCloneable} interface (defined in
* the JCommon class library). This provides a mechanism for the referring
* renderer to clone the generator if necessary.
*/
public interface XYSeriesLabelGenerator {
/**
* Generates a label for the specified series. This label will be
* used for the chart legend.
*
* @param dataset the dataset ({@code null} not permitted).
* @param series the series.
*
* @return A series label.
*/
String generateLabel(XYDataset dataset, int series);
}
| jfree/jfreechart | src/main/java/org/jfree/chart/labels/XYSeriesLabelGenerator.java | Java | lgpl-2.1 | 2,286 |
<?php
namespace wcf\system\template\plugin;
use wcf\system\exception\SystemException;
use wcf\system\request\LinkHandler;
use wcf\system\template\TemplateEngine;
use wcf\system\WCF;
use wcf\util\StringUtil;
/**
* Template function plugin which generates sliding pagers.
*
* Usage:
* {pages pages=10 link='page-%d.html'}
* {pages page=8 pages=10 link='page-%d.html'}
*
* assign to variable 'output'; do not print:
* {pages page=8 pages=10 link='page-%d.html' assign='output'}
*
* assign to variable 'output' and do print also:
* {pages page=8 pages=10 link='page-%d.html' assign='output' print=true}
*
* @author Marcel Werk
* @copyright 2001-2014 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package com.woltlab.wcf
* @subpackage system.template.plugin
* @category Community Framework
*/
class PagesFunctionTemplatePlugin implements IFunctionTemplatePlugin {
const SHOW_LINKS = 11;
/**
* Inserts the page number into the link.
*
* @param string $link
* @param integer $pageNo
* @return string final link
*/
protected static function insertPageNumber($link, $pageNo) {
$startPos = mb_strpos($link, '%d');
if ($startPos !== null) $link = mb_substr($link, 0, $startPos) . $pageNo . mb_substr($link, $startPos + 2);
return $link;
}
/**
* Generates HTML code for a link.
*
* @param string $link
* @param integer $pageNo
* @param integer $activePage
* @param integer $pages
* @return string
*/
protected function makeLink($link, $pageNo, $activePage, $pages) {
// first page
if ($activePage != $pageNo) {
return '<li class="button"><a href="'.$this->insertPageNumber($link, $pageNo).'" title="'.WCF::getLanguage()->getDynamicVariable('wcf.page.pageNo', array('pageNo' => $pageNo)).'">'.StringUtil::formatInteger($pageNo).'</a></li>'."\n";
}
else {
return '<li class="button active"><span>'.StringUtil::formatInteger($pageNo).'</span><span class="invisible">'.WCF::getLanguage()->getDynamicVariable('wcf.page.pagePosition', array('pageNo' => $pageNo, 'pages' => $pages)).'</span></li>'."\n";
}
}
/**
* Generates HTML code for 'previous' link.
*
* @param type $link
* @param type $pageNo
* @return string
*/
protected function makePreviousLink($link, $pageNo) {
if ($pageNo > 1) {
return '<li class="button skip"><a href="'.$this->insertPageNumber($link, $pageNo - 1).'" title="'.WCF::getLanguage()->getDynamicVariable('wcf.global.page.previous').'" class="jsTooltip"><span class="icon icon16 icon-double-angle-left"></span></a></li>'."\n";
}
else {
return '<li class="skip disabled"><span class="icon icon16 icon-double-angle-left disabled"></span></li>'."\n";
}
}
/**
* Generates HTML code for 'next' link.
*
* @param type $link
* @param type $pageNo
* @return string
*/
protected function makeNextLink($link, $pageNo, $pages) {
if ($pageNo && $pageNo < $pages) {
return '<li class="button skip"><a href="'.$this->insertPageNumber($link, $pageNo + 1).'" title="'.WCF::getLanguage()->getDynamicVariable('wcf.global.page.next').'" class="jsTooltip"><span class="icon icon16 icon-double-angle-right"></span></a></li>'."\n";
}
else {
return '<li class="skip disabled"><span class="icon icon16 icon-double-angle-right disabled"></span></li>'."\n";
}
}
/**
* @see \wcf\system\template\IFunctionTemplatePlugin::execute()
*/
public function execute($tagArgs, TemplateEngine $tplObj) {
// needed params: controller, link, page, pages
if (!isset($tagArgs['link'])) throw new SystemException("missing 'link' argument in pages tag");
if (!isset($tagArgs['controller'])) throw new SystemException("missing 'controller' argument in pages tag");
if (!isset($tagArgs['pages'])) {
if (($tagArgs['pages'] = $tplObj->get('pages')) === null) {
throw new SystemException("missing 'pages' argument in pages tag");
}
}
$html = '';
if ($tagArgs['pages'] > 1) {
// create and encode route link
$parameters = array();
if (isset($tagArgs['id'])) $parameters['id'] = $tagArgs['id'];
if (isset($tagArgs['title'])) $parameters['title'] = $tagArgs['title'];
if (isset($tagArgs['object'])) $parameters['object'] = $tagArgs['object'];
if (isset($tagArgs['application'])) $parameters['application'] = $tagArgs['application'];
$link = StringUtil::encodeHTML(LinkHandler::getInstance()->getLink($tagArgs['controller'], $parameters, $tagArgs['link']));
if (!isset($tagArgs['page'])) {
if (($tagArgs['page'] = $tplObj->get('pageNo')) === null) {
$tagArgs['page'] = 0;
}
}
// open div and ul
$html .= "<nav class=\"pageNavigation\" data-link=\"".$link."\" data-pages=\"".$tagArgs['pages']."\">\n<ul>\n";
// previous page
$html .= $this->makePreviousLink($link, $tagArgs['page']);
// first page
$html .= $this->makeLink($link, 1, $tagArgs['page'], $tagArgs['pages']);
// calculate page links
$maxLinks = static::SHOW_LINKS - 4;
$linksBeforePage = $tagArgs['page'] - 2;
if ($linksBeforePage < 0) $linksBeforePage = 0;
$linksAfterPage = $tagArgs['pages'] - ($tagArgs['page'] + 1);
if ($linksAfterPage < 0) $linksAfterPage = 0;
if ($tagArgs['page'] > 1 && $tagArgs['page'] < $tagArgs['pages']) {
$maxLinks--;
}
$half = $maxLinks / 2;
$left = $right = $tagArgs['page'];
if ($left < 1) $left = 1;
if ($right < 1) $right = 1;
if ($right > $tagArgs['pages'] - 1) $right = $tagArgs['pages'] - 1;
if ($linksBeforePage >= $half) {
$left -= $half;
}
else {
$left -= $linksBeforePage;
$right += $half - $linksBeforePage;
}
if ($linksAfterPage >= $half) {
$right += $half;
}
else {
$right += $linksAfterPage;
$left -= $half - $linksAfterPage;
}
$right = intval(ceil($right));
$left = intval(ceil($left));
if ($left < 1) $left = 1;
if ($right > $tagArgs['pages']) $right = $tagArgs['pages'];
// left ... links
if ($left > 1) {
if ($left - 1 < 2) {
$html .= $this->makeLink($link, 2, $tagArgs['page'], $tagArgs['pages']);
}
else {
$html .= '<li class="button jumpTo"><a title="'.WCF::getLanguage()->getDynamicVariable('wcf.global.page.jumpTo').'" class="jsTooltip">'.StringUtil::HELLIP.'</a></li>'."\n";
}
}
// visible links
for ($i = $left + 1; $i < $right; $i++) {
$html .= $this->makeLink($link, $i, $tagArgs['page'], $tagArgs['pages']);
}
// right ... links
if ($right < $tagArgs['pages']) {
if ($tagArgs['pages'] - $right < 2) {
$html .= $this->makeLink($link, $tagArgs['pages'] - 1, $tagArgs['page'], $tagArgs['pages']);
}
else {
$html .= '<li class="button jumpTo"><a title="'.WCF::getLanguage()->getDynamicVariable('wcf.global.page.jumpTo').'" class="jsTooltip">'.StringUtil::HELLIP.'</a></li>'."\n";
}
}
// last page
$html .= $this->makeLink($link, $tagArgs['pages'], $tagArgs['page'], $tagArgs['pages']);
// next page
$html .= $this->makeNextLink($link, $tagArgs['page'], $tagArgs['pages']);
// close div and ul
$html .= "</ul></nav>\n";
}
// assign html output to template var
if (isset($tagArgs['assign'])) {
$tplObj->assign($tagArgs['assign'], $html);
if (!isset($tagArgs['print']) || !$tagArgs['print']) return '';
}
return $html;
}
}
| PhrozenByte/WCF2 | wcfsetup/install/files/lib/system/template/plugin/PagesFunctionTemplatePlugin.class.php | PHP | lgpl-2.1 | 7,411 |
/*
* Copyright (C) 2004 The Concord Consortium, Inc.,
* 10 Concord Crossing, Concord, MA 01742
*
* Web Site: http://www.concord.org
* Email: info@concord.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* END LICENSE */
package org.concord.framework.otrunk;
import java.util.Vector;
public interface OTControllerService {
/**
* This method is typically not used. Typically controller classes are
* registered in a OTPackage implementation.
*
* If a controller class is only registered using this method then it will need to be
* registered each time a new view wants to use it. If it is registered in the OTPackage
* then new views don't need to worry about registering it.
*
* This method takes a controllerClass.
* Controller classes take OTObjects and create
* real objects from them.
*
*/
public void registerControllerClass(Class<? extends OTController> viewClass);
/**
* This is a helper method. The real object class of a controller class should
* be in a public final static Class [] realObjectClasses
* field of the interface. This method just looks up that field and returns
* the value.
*
* @param controllerClass
* @return
*/
public Class<?> [] getRealObjectClasses(Class<? extends OTController> controllerClass);
/**
* This searches an internal table of realObjects to
* see if an OTObject has been created for this object.
* It returns it if it has.
*
* If the OTObject has not been created then the
* registered OTController classes are searched to see if there
* is one that can work with this realObject class.
* The OTController class needs to define a
* public final static Class [] realObjectClasses
* field. If it matches, that controller is used to make the
* OTObject.
*
* The {@link OTController} registerRealObject is called.
* followed by saveRealObject.
*
* In the OTController object the saveRealObject method can and should
* call getOTObject when it needs to save a reference to another
* realObject.
*
* Note: getOTObject will only call saveRealObject if this is the first time the
* realObject is seen by this service.
*
* Note to implementors: a weak map should be used so that if all the
* references to the real object are gone then the real object
* can be garbage collected. If the real object is needed again for
* some reason then it will just be created again.
*
* @param realObject
* @return
*/
public OTObject getOTObject(Object realObject);
/**
* Look to see if this realObject has been created already or added with
* getOTObject. If so return that previous realObject.
*
* Otherwise, use the controller registered for the class of this otObject
* to create the realObject, and load the
* state from the otObject into the realObject.
*
* The implementation should use a weak map so that if all the
* references to the real object are gone then the real object
* can be garbage collected. If the real object is needed again for
* some reason then it will just be created again.
*
* If the controller service is in the middle of disposing then this will
* return null for real objects that haven't already been created.
*
* @param otObject
* @return
*/
public Object getRealObject(OTObject otObject);
/**
* Take a real object which was created else
* where and connect it to an otObject and
* load the state of otObject into the realObject
*
* @param realObject
* @param otObject
*/
public Object getRealObject(OTObject otObject, Object realObject);
/**
* A helper method to get a Vector of real objects from an
* OTObjectList, so that we don't have to first get the OTObjectList
* and then create all the RealObjects ourselves.
*
* @param otObjectList
* @return
*/
public Vector<Object> getRealObjects(OTObjectList otObjectList);
/**
* This saves the state of realObject into this ot object. It needs
* to lookup the controller for this realObject and otObject.
*
* This is very similar to getOTObject, which calls saveRealObject
* at the end. Exposing it here allows others to use this
* functionality without having to directly access the controller
* or otObject directly
*
* TODO it is not clear how much state should be saved here and whether it should
* be recursive. If listeners are being used on all the sub objects then when
* this is called after the object has been registered it doesn't need to be
* recursive. If this is called to store a realObject that wasn't created by
* the controllerservice this will need to recursively save all the sub objects.
*
* It should not mess up anything if the method is recursive. It is just a waste of
* time in some cases. However there is a danger of infinite loops with circular
* references.
*
* @param otObject
* @param realObject
*/
public void saveRealObject(Object realObject, OTObject otObject);
/**
* This loads the state of this ot object into the realObject. It needs
* to lookup the controller for this realObject and otObject.
*
* This is very similar to getRealObject but getRealObject only calls
* loadRealObject on the controller when it's called the first time
*
* TODO it is not clear how much state should be loaded here and whether it should
* be recursive. If listeners are being used on all the sub objects then when
* this is called after the object has been registered it doesn't need to be
* recursive. If this is called to load a realObject that wasn't created by
* the controllerservice this will need to recursively load all the sub objects.
*
* It should not mess up anything if the method is recursive. It is just a waste of
* time in some cases. However there is a danger of infinite loops with circular
* references.
*
* @param otObject
* @param realObject
*/
public void loadRealObject(OTObject otObject, Object realObject);
/**
* This saves the state of realObject into this ot object. It needs
* to lookup the controller for this realObject and otObject.
*
* This method is called both by getOTObject and getRealObject. You should
* only need to call it explicitly if you don't want the other side effects
* of those methods. For example if the realObject needs to be managed by
* some parent object instead of the standard controller for the realObject
*
* A possible alternative solution to this is to make a custom controller.
* but that alternative hasn't been tried yet, so it might need more
* framework support to be possible.
*/
public void registerRealObject(Object realObject, OTObject otObject);
/**
* Return the controller instance that has been or would be be used to create a
* real object. You should not call any of the public methods of OTController
* these methods should only be called by the controller service.
*
* @param otObject
* @return
*/
public OTController getController(OTObject otObject);
/**
* Calling this will call dispose on all of the controllers this controller
* service knows about. That will give them a chance to clean up any
* listeners they've added.
*/
public void dispose();
/**
* provide a service which other controllers can use.
* this allows views which use controllers to provide custom services to those
* controllers.
*
* @param serviceClass
* @param service
*/
public void addService(Class<?> serviceClass, Object service);
/**
* Lookup a service that was provided to this controllerService
*
* @param serviceClass
* @return
*/
public <T> T getService(Class<T> serviceClass);
}
| concord-consortium/framework | src/org/concord/framework/otrunk/OTControllerService.java | Java | lgpl-2.1 | 8,453 |
// The UpdateCheck plug-in
// Copyright (C) 2004-2016 Maurits Rijk
//
// Renderer.cs
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Xml;
namespace Gimp.UpdateCheck
{
public class Renderer : BaseRenderer
{
static ManualResetEvent allDone= new ManualResetEvent(false);
const int BUFFER_SIZE = 1024;
const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout
public Renderer(VariableSet variables) : base(variables)
{
}
public void Render()
{
bool enableProxy = GetValue<bool>("enable_proxy");
string httpProxy = GetValue<string>("http_proxy");
string port = GetValue<string>("port");
if (enableProxy)
{
Gimp.RcSet("update-enable-proxy", (enableProxy) ? "true" : "false");
Gimp.RcSet("update-http-proxy", httpProxy);
Gimp.RcSet("update-port", port);
}
var assembly = Assembly.GetAssembly(typeof(Plugin));
Console.WriteLine(assembly.GetName().Version);
var doc = new XmlDocument();
try
{
var myRequest = (HttpWebRequest)
WebRequest.Create("http://gimp-sharp.sourceforge.net/version.xml");
// Create a proxy object, needed for mono behind a firewall?!
if (enableProxy)
{
var myProxy = new WebProxy()
{Address = new Uri(httpProxy + ":" + port)};
myRequest.Proxy = myProxy;
}
var requestState = new RequestState(myRequest);
// Start the asynchronous request.
IAsyncResult result= (IAsyncResult) myRequest.BeginGetResponse
(new AsyncCallback(RespCallback), requestState);
// this line implements the timeout, if there is a timeout,
// the callback fires and the request becomes aborted
ThreadPool.RegisterWaitForSingleObject
(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback),
myRequest, DefaultTimeout, true);
// The response came in the allowed time. The work processing will
// happen in the callback function.
allDone.WaitOne();
// Release the HttpWebResponse resource.
requestState.Response.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception!");
Console.WriteLine(e.StackTrace);
return;
}
}
static void TimeoutCallback(object state, bool timedOut)
{
if (timedOut)
{
var request = state as HttpWebRequest;
request?.Abort();
}
}
static void RespCallback(IAsyncResult asynchronousResult)
{
try
{
// State of request is asynchronous.
var requestState = (RequestState) asynchronousResult.AsyncState;
var myHttpWebRequest = requestState.Request;
requestState.Response = (HttpWebResponse)
myHttpWebRequest.EndGetResponse(asynchronousResult);
// Read the response into a Stream object.
var responseStream = requestState.Response.GetResponseStream();
requestState.StreamResponse = responseStream;
var asynchronousInputRead =
responseStream.BeginRead(requestState.BufferRead, 0,
BUFFER_SIZE,
new AsyncCallback(ReadCallBack),
requestState);
return;
}
catch(WebException e)
{
Console.WriteLine("\nRespCallback Exception raised!");
Console.WriteLine("\nMessage:{0}",e.Message);
Console.WriteLine("\nStatus:{0}",e.Status);
}
allDone.Set();
}
static void ReadCallBack(IAsyncResult asyncResult)
{
try
{
var requestState = (RequestState) asyncResult.AsyncState;
var responseStream = requestState.StreamResponse;
int read = responseStream.EndRead(asyncResult);
if (read > 0)
{
requestState.RequestData.Append
(Encoding.ASCII.GetString(requestState.BufferRead, 0, read));
IAsyncResult asynchronousResult =
responseStream.BeginRead(requestState.BufferRead, 0,
BUFFER_SIZE,
new AsyncCallback(ReadCallBack),
requestState);
return;
}
else
{
if (requestState.RequestData.Length > 1)
{
string stringContent = requestState.RequestData.ToString();
Console.WriteLine(stringContent);
}
responseStream.Close();
}
}
catch (WebException e)
{
Console.WriteLine("\nReadCallBack Exception raised!");
Console.WriteLine("\nMessage:{0}",e.Message);
Console.WriteLine("\nStatus:{0}",e.Status);
}
allDone.Set();
}
}
}
| mrijk/gimp-sharp | plug-ins/UpdateCheck/Renderer.cs | C# | lgpl-2.1 | 5,050 |
/****************************************************************************
**
** 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 demonstration applications 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$
**
****************************************************************************/
#include <QXmlStreamReader>
#include "fluidlauncher.h"
#define DEFAULT_INPUT_TIMEOUT 10000
#define SIZING_FACTOR_HEIGHT 6/10
#define SIZING_FACTOR_WIDTH 6/10
FluidLauncher::FluidLauncher(QStringList* args)
{
pictureFlowWidget = new PictureFlow();
slideShowWidget = new SlideShow();
inputTimer = new QTimer();
addWidget(pictureFlowWidget);
addWidget(slideShowWidget);
setCurrentWidget(pictureFlowWidget);
pictureFlowWidget->setFocus();
QRect screen_size = QApplication::desktop()->screenGeometry();
QObject::connect(pictureFlowWidget, SIGNAL(itemActivated(int)), this, SLOT(launchApplication(int)));
QObject::connect(pictureFlowWidget, SIGNAL(inputReceived()), this, SLOT(resetInputTimeout()));
QObject::connect(slideShowWidget, SIGNAL(inputReceived()), this, SLOT(switchToLauncher()));
QObject::connect(inputTimer, SIGNAL(timeout()), this, SLOT(inputTimedout()));
inputTimer->setSingleShot(true);
inputTimer->setInterval(DEFAULT_INPUT_TIMEOUT);
const int h = screen_size.height() * SIZING_FACTOR_HEIGHT;
const int w = screen_size.width() * SIZING_FACTOR_WIDTH;
const int hh = qMin(h, w);
const int ww = hh / 3 * 2;
pictureFlowWidget->setSlideSize(QSize(ww, hh));
bool success;
int configIndex = args->indexOf("-config");
if ( (configIndex != -1) && (configIndex != args->count()-1) )
success = loadConfig(args->at(configIndex+1));
else
success = loadConfig("config.xml");
if (success) {
populatePictureFlow();
showFullScreen();
inputTimer->start();
} else {
pictureFlowWidget->setAttribute(Qt::WA_DeleteOnClose, true);
pictureFlowWidget->close();
}
}
FluidLauncher::~FluidLauncher()
{
delete pictureFlowWidget;
delete slideShowWidget;
}
bool FluidLauncher::loadConfig(QString configPath)
{
QFile xmlFile(configPath);
if (!xmlFile.exists() || (xmlFile.error() != QFile::NoError)) {
qDebug() << "ERROR: Unable to open config file " << configPath;
return false;
}
slideShowWidget->clearImages();
xmlFile.open(QIODevice::ReadOnly);
QXmlStreamReader reader(&xmlFile);
while (!reader.atEnd()) {
reader.readNext();
if (reader.isStartElement()) {
if (reader.name() == "demos")
parseDemos(reader);
else if(reader.name() == "slideshow")
parseSlideshow(reader);
}
}
if (reader.hasError()) {
qDebug() << QString("Error parsing %1 on line %2 column %3: \n%4")
.arg(configPath)
.arg(reader.lineNumber())
.arg(reader.columnNumber())
.arg(reader.errorString());
}
// Append an exit Item
DemoApplication* exitItem = new DemoApplication(QString(), QLatin1String("Exit Embedded Demo"), QString(), QStringList());
demoList.append(exitItem);
return true;
}
void FluidLauncher::parseDemos(QXmlStreamReader& reader)
{
while (!reader.atEnd()) {
reader.readNext();
if (reader.isStartElement() && reader.name() == "example") {
QXmlStreamAttributes attrs = reader.attributes();
QStringRef filename = attrs.value("filename");
if (!filename.isEmpty()) {
QStringRef name = attrs.value("name");
QStringRef image = attrs.value("image");
QStringRef args = attrs.value("args");
DemoApplication* newDemo = new DemoApplication(
filename.toString(),
name.isEmpty() ? "Unamed Demo" : name.toString(),
image.toString(),
args.toString().split(" "));
demoList.append(newDemo);
}
} else if(reader.isEndElement() && reader.name() == "demos") {
return;
}
}
}
void FluidLauncher::parseSlideshow(QXmlStreamReader& reader)
{
QXmlStreamAttributes attrs = reader.attributes();
QStringRef timeout = attrs.value("timeout");
bool valid;
if (!timeout.isEmpty()) {
int t = timeout.toString().toInt(&valid);
if (valid)
inputTimer->setInterval(t);
}
QStringRef interval = attrs.value("interval");
if (!interval.isEmpty()) {
int i = interval.toString().toInt(&valid);
if (valid)
slideShowWidget->setSlideInterval(i);
}
while (!reader.atEnd()) {
reader.readNext();
if (reader.isStartElement()) {
QXmlStreamAttributes attrs = reader.attributes();
if (reader.name() == "imagedir") {
QStringRef dir = attrs.value("dir");
slideShowWidget->addImageDir(dir.toString());
} else if(reader.name() == "image") {
QStringRef image = attrs.value("image");
slideShowWidget->addImage(image.toString());
}
} else if(reader.isEndElement() && reader.name() == "slideshow") {
return;
}
}
}
void FluidLauncher::populatePictureFlow()
{
pictureFlowWidget->setSlideCount(demoList.count());
for (int i=demoList.count()-1; i>=0; --i) {
pictureFlowWidget->setSlide(i, *(demoList[i]->getImage()));
pictureFlowWidget->setSlideCaption(i, demoList[i]->getCaption());
}
pictureFlowWidget->setCurrentSlide(demoList.count()/2);
}
void FluidLauncher::launchApplication(int index)
{
// NOTE: Clearing the caches will free up more memory for the demo but will cause
// a delay upon returning, as items are reloaded.
//pictureFlowWidget->clearCaches();
if (index == demoList.size() -1) {
qApp->quit();
return;
}
inputTimer->stop();
QObject::connect(demoList[index], SIGNAL(demoFinished()), this, SLOT(demoFinished()));
demoList[index]->launch();
}
void FluidLauncher::switchToLauncher()
{
slideShowWidget->stopShow();
inputTimer->start();
setCurrentWidget(pictureFlowWidget);
}
void FluidLauncher::resetInputTimeout()
{
if (inputTimer->isActive())
inputTimer->start();
}
void FluidLauncher::inputTimedout()
{
switchToSlideshow();
}
void FluidLauncher::switchToSlideshow()
{
inputTimer->stop();
slideShowWidget->startShow();
setCurrentWidget(slideShowWidget);
}
void FluidLauncher::demoFinished()
{
setCurrentWidget(pictureFlowWidget);
inputTimer->start();
// Bring the Fluidlauncher to the foreground to allow selecting another demo
raise();
activateWindow();
}
void FluidLauncher::changeEvent(QEvent* event)
{
if (event->type() == QEvent::ActivationChange) {
if (isActiveWindow()) {
if(currentWidget() == pictureFlowWidget) {
resetInputTimeout();
} else {
slideShowWidget->startShow();
}
} else {
inputTimer->stop();
slideShowWidget->stopShow();
}
}
QStackedWidget::changeEvent(event);
}
| radekp/qt | demos/embedded/fluidlauncher/fluidlauncher.cpp | C++ | lgpl-2.1 | 8,555 |
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.ComponentModel.Composition;
using System;
using System.Linq;
namespace Rolcore.Web.Protocols
{
[Export(typeof(Sitemap))]
public class Sitemap : List<SitemapUrl>
{
private string _Xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9";
#region Constructors
public Sitemap(){ }
public Sitemap(int capacity) : base(capacity) { }
public Sitemap(IEnumerable<SitemapUrl> collection): base(collection){ }
#endregion Constructors
public string Xmlns
{
get { return _Xmlns; }
set { _Xmlns = value; }
}
public void Write(TextWriter output)
{
using (XmlTextWriter writer = new XmlTextWriter(output))
{
//writer.WriteStartDocument();
writer.WriteStartElement("urlset");
writer.WriteAttributeString("xmlns", this.Xmlns);
writer.WriteAttributeString("xmlns:geo", "http://www.google.com/geo/schemas/sitemap/1.0");
foreach (SitemapUrl url in this.OrderBy(item => item.Loc))
{
writer.WriteStartElement("url");
writer.WriteElementString("loc", url.Loc);
if (!string.IsNullOrEmpty(url.LastMod))
writer.WriteElementString("lastmod", url.LastMod);
if (!string.IsNullOrEmpty(url.ChangeFreq))
writer.WriteElementString("changefreq", url.ChangeFreq);
if (!string.IsNullOrEmpty(url.Priority))
writer.WriteElementString("priority", url.Priority);
if (url.Loc.EndsWith(".kml")) // See http://code.google.com/apis/kml/documentation/kmlSearch.html
{
writer.WriteStartElement("geo:geo");
writer.WriteElementString("geo:format", "kml");
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndElement();
//writer.WriteEndDocument();
writer.Flush();
}
}
public override string ToString()
{
using (StringWriter result = new StringWriter())
{
this.Write(result);
return result.ToString();
}
}
}
}
| Rollins/Rolcore | src/Rolcore.Web/Protocols/Sitemap.cs | C# | lgpl-2.1 | 2,518 |
"""
This file shows how to use pyDatalog using facts stored in python objects.
It has 3 parts :
1. define python class and business rules
2. create python objects for 2 employees
3. Query the objects using the datalog engine
"""
from pyDatalog import pyDatalog
""" 1. define python class and business rules """
class Employee(pyDatalog.Mixin): # --> Employee inherits the pyDatalog capability to use logic clauses
def __init__(self, name, manager, salary): # method to initialize Employee instances
super(Employee, self).__init__() # calls the initialization method of the Mixin class
self.name = name
self.manager = manager # direct manager of the employee, or None
self.salary = salary # monthly salary of the employee
def __repr__(self): # specifies how to display an Employee
return self.name
@pyDatalog.program() # indicates that the following method contains pyDatalog clauses
def Employee(self):
# the salary class N of employee X is computed as a function of his/her salary
# this statement is a logic equality, not an assignment !
Employee.salary_class[X] = Employee.salary[X]//1000
# all the indirect managers Y of employee X are derived from his manager, recursively
Employee.indirect_manager(X,Y) <= (Employee.manager[X]==Y) & (Y != None)
Employee.indirect_manager(X,Y) <= (Employee.manager[X]==Z) & Employee.indirect_manager(Z,Y) & (Y != None)
# count the number of reports of X
(Employee.report_count[X] == len(Y)) <= Employee.indirect_manager(Y,X)
""" 2. create python objects for 3 employees """
# John is the manager of Mary, who is the manager of Sam
John = Employee('John', None, 6800)
Mary = Employee('Mary', John, 6300)
Sam = Employee('Sam', Mary, 5900)
""" 3. Query the objects using the datalog engine """
# the following python statements implicitly use the datalog clauses in the class definition
# What is the salary class of John ?
print(John.salary_class) # prints 6
# who has a salary of 6300 ?
pyDatalog.create_terms('X')
Employee.salary[X] == 6300 # notice the similarity to a pyDatalog query
print(X) # prints [Mary]
print(X.v()) # prints Mary
# who are the indirect managers of Mary ?
Employee.indirect_manager(Mary, X)
print(X) # prints [John]
# Who are the employees of John with a salary below 6000 ?
result = (Employee.salary[X] < 6000) & Employee.indirect_manager(X, John)
print(result) # Sam is in the result
print(X) # prints [Sam]
print((Employee.salary_class[X] == 5) & Employee.indirect_manager(X, John) >= X) # Sam
# verify that the manager of Mary is John
assert Employee.manager[Mary]==John
# who is his own indirect manager ?
Employee.indirect_manager(X, X)
print(X) # prints []
# who has 2 reports ?
Employee.report_count[X] == 2
print(X) # prints [John]
# what is the total salary of the employees of John ?
# note : it is better to place aggregation clauses in the class definition
pyDatalog.load("(Employee.budget[X] == sum(N, for_each=Y)) <= (Employee.indirect_manager(Y, X)) & (Employee.salary[Y]==N)")
Employee.budget[John]==X
print(X) # prints [12200]
# who has the lowest salary ?
pyDatalog.load("(lowest[1] == min(X, order_by=N)) <= (Employee.salary[X]==N)")
# must use ask() because inline queries cannot use unprefixed literals
print(pyDatalog.ask("lowest[1]==X")) # prints set([(1, 'Sam')])
| pcarbonn/pyDatalog | pyDatalog/examples/python.py | Python | lgpl-2.1 | 3,454 |
// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "bseitem.hh"
#include "bsesuper.hh"
#include "bsesnet.hh"
#include "bsestorage.hh"
#include "bseprocedure.hh"
#include "bsemain.hh"
#include "bseproject.hh"
#include "bsesong.hh" // for song->musical_tuning
#include "bseundostack.hh"
#include <gobject/gvaluecollector.h>
#include <string.h>
enum {
PROP_0,
PROP_SEQID,
};
/* --- prototypes --- */
static void bse_item_class_init_base (BseItemClass *klass);
static void bse_item_class_finalize_base (BseItemClass *klass);
static void bse_item_class_init (BseItemClass *klass);
static void bse_item_init (BseItem *item);
static void bse_item_set_property_internal (GObject *object,
uint param_id,
const GValue *value,
GParamSpec *pspec);
static void bse_item_get_property_internal (GObject *object,
uint param_id,
GValue *value,
GParamSpec *pspec);
static void bse_item_update_state (BseItem *self);
static gboolean bse_item_real_needs_storage (BseItem *self,
BseStorage *storage);
static void bse_item_do_dispose (GObject *object);
static void bse_item_do_finalize (GObject *object);
static void bse_item_do_set_uname (BseObject *object,
const char *uname);
static uint bse_item_do_get_seqid (BseItem *item);
static void bse_item_do_set_parent (BseItem *item,
BseItem *parent);
static BseUndoStack* bse_item_default_get_undo (BseItem *self);
/* --- variables --- */
static GTypeClass *parent_class = NULL;
static GSList *item_seqid_changed_queue = NULL;
/* --- functions --- */
BSE_BUILTIN_TYPE (BseItem)
{
static const GTypeInfo item_info = {
sizeof (BseItemClass),
(GBaseInitFunc) bse_item_class_init_base,
(GBaseFinalizeFunc) bse_item_class_finalize_base,
(GClassInitFunc) bse_item_class_init,
(GClassFinalizeFunc) NULL,
NULL /* class_data */,
sizeof (BseItem),
0 /* n_preallocs */,
(GInstanceInitFunc) bse_item_init,
};
assert_return (BSE_ITEM_FLAGS_USHIFT < BSE_OBJECT_FLAGS_MAX_SHIFT, 0);
return bse_type_register_abstract (BSE_TYPE_OBJECT,
"BseItem",
"Base type for objects managed by a container",
__FILE__, __LINE__,
&item_info);
}
static void
bse_item_class_init_base (BseItemClass *klass)
{
klass->get_candidates = NULL;
}
static void
bse_item_class_finalize_base (BseItemClass *klass)
{
}
static void
bse_item_class_init (BseItemClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
BseObjectClass *object_class = BSE_OBJECT_CLASS (klass);
parent_class = (GTypeClass*) g_type_class_peek_parent (klass);
gobject_class->get_property = bse_item_get_property_internal;
gobject_class->set_property = bse_item_set_property_internal;
gobject_class->dispose = bse_item_do_dispose;
gobject_class->finalize = bse_item_do_finalize;
object_class->set_uname = bse_item_do_set_uname;
klass->set_parent = bse_item_do_set_parent;
klass->get_seqid = bse_item_do_get_seqid;
klass->get_undo = bse_item_default_get_undo;
klass->needs_storage = bse_item_real_needs_storage;
bse_object_class_add_param (object_class, NULL,
PROP_SEQID,
sfi_pspec_int ("seqid", "Sequential ID", NULL,
0, 0, SFI_MAXINT, 1, "r"));
}
static void
bse_item_init (BseItem *item)
{
item->parent = NULL;
}
static void
bse_item_set_property_internal (GObject *object,
uint param_id,
const GValue *value,
GParamSpec *pspec)
{
// BseItem *self = BSE_ITEM (object);
switch (param_id)
{
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
break;
}
}
static void
bse_item_get_property_internal (GObject *object,
uint param_id,
GValue *value,
GParamSpec *pspec)
{
BseItem *self = BSE_ITEM (object);
switch (param_id)
{
case PROP_SEQID:
sfi_value_set_int (value, bse_item_get_seqid (self));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
break;
}
}
static void
bse_item_do_dispose (GObject *gobject)
{
BseItem *item = BSE_ITEM (gobject);
/* force removal from parent */
if (item->parent)
bse_container_remove_item (BSE_CONTAINER (item->parent), item);
/* chain parent class' handler */
G_OBJECT_CLASS (parent_class)->dispose (gobject);
}
static void
bse_item_do_finalize (GObject *object)
{
BseItem *item = BSE_ITEM (object);
item_seqid_changed_queue = g_slist_remove (item_seqid_changed_queue, item);
/* chain parent class' handler */
G_OBJECT_CLASS (parent_class)->finalize (object);
assert_return (item->use_count == 0);
}
static void
bse_item_do_set_uname (BseObject *object,
const char *uname)
{
BseItem *item = BSE_ITEM (object);
/* ensure that item names within their container are unique,
* and that we don't end up with a NULL uname
*/
if (!BSE_IS_CONTAINER (item->parent) ||
(uname && !bse_container_lookup_item (BSE_CONTAINER (item->parent), uname)))
{
/* chain parent class' set_uname handler */
BSE_OBJECT_CLASS (parent_class)->set_uname (object, uname);
}
}
static void
bse_item_do_set_parent (BseItem *self,
BseItem *parent)
{
self->parent = parent;
bse_item_update_state (self);
}
static gboolean
recurse_update_state (BseItem *self,
void *data)
{
bse_item_update_state (self);
return TRUE;
}
static void
bse_item_update_state (BseItem *self)
{
/* save original state */
gboolean old_internal = BSE_ITEM_INTERNAL (self);
/* update state */
if ((BSE_OBJECT_FLAGS (self) & BSE_ITEM_FLAG_INTERN) ||
(self->parent && BSE_ITEM_INTERNAL (self->parent)))
BSE_OBJECT_SET_FLAGS (self, BSE_ITEM_FLAG_INTERN_BRANCH);
else
BSE_OBJECT_UNSET_FLAGS (self, BSE_ITEM_FLAG_INTERN_BRANCH);
/* compare state and recurse if necessary */
if (BSE_IS_CONTAINER (self) && (old_internal != BSE_ITEM_INTERNAL (self)))
bse_container_forall_items ((BseContainer*) self, recurse_update_state, NULL);
}
/**
* @param item valid BseItem
* @param internal TRUE or FALSE
*
* Set whether an item should be considered internal to the BSE
* implementation (or implementation of another BSE object).
* Internal items are not stored with their parents and undo
* is not recorded for internal items either. Marking containers
* internal also affects any children they contain, in effect,
* the whole posterity spawned by the container is considered
* internal.
*/
void
bse_item_set_internal (void *item,
gboolean internal)
{
BseItem *self = BSE_ITEM (item);
assert_return (BSE_IS_ITEM (self));
if (internal)
BSE_OBJECT_SET_FLAGS (self, BSE_ITEM_FLAG_INTERN);
else
BSE_OBJECT_UNSET_FLAGS (self, BSE_ITEM_FLAG_INTERN);
bse_item_update_state (self);
}
static gboolean
bse_item_real_needs_storage (BseItem *self,
BseStorage *storage)
{
return TRUE;
}
gboolean
bse_item_needs_storage (BseItem *self,
BseStorage *storage)
{
assert_return (BSE_IS_ITEM (self), FALSE);
assert_return (BSE_IS_STORAGE (storage), FALSE);
return BSE_ITEM_GET_CLASS (self)->needs_storage (self, storage);
}
void
bse_item_compat_setup (BseItem *self,
uint vmajor,
uint vminor,
uint vmicro)
{
assert_return (BSE_IS_ITEM (self));
if (BSE_ITEM_GET_CLASS (self)->compat_setup)
BSE_ITEM_GET_CLASS (self)->compat_setup (self, vmajor, vminor, vmicro);
}
struct GatherData {
BseItem *item;
void *data;
Bse::ItemSeq &iseq;
GType base_type;
BseItemCheckContainer ccheck;
BseItemCheckProxy pcheck;
GatherData (Bse::ItemSeq &is) : iseq (is) {}
};
static gboolean
gather_child (BseItem *child,
void *data)
{
GatherData *gdata = (GatherData*) data;
if (child != gdata->item && !BSE_ITEM_INTERNAL (child) &&
g_type_is_a (G_OBJECT_TYPE (child), gdata->base_type) &&
(!gdata->pcheck || gdata->pcheck (child, gdata->item, gdata->data)))
gdata->iseq.push_back (child->as<Bse::ItemIfaceP>());
return TRUE;
}
/**
* @param item valid BseItem from which to start gathering
* @param items sequence of items to append to
* @param base_type base type of the items to gather
* @param ccheck container filter function
* @param pcheck proxy filter function
* @param data @a data pointer to @a ccheck and @a pcheck
*
* This function gathers items from an object hierachy, walking upwards,
* starting out with @a item. For each container passing @a ccheck(), all
* immediate children are tested for addition with @a pcheck.
*/
static void
bse_item_gather_items (BseItem *item, Bse::ItemSeq &iseq, GType base_type, BseItemCheckContainer ccheck, BseItemCheckProxy pcheck, void *data)
{
GatherData gdata (iseq);
assert_return (BSE_IS_ITEM (item));
assert_return (g_type_is_a (base_type, BSE_TYPE_ITEM));
gdata.item = item;
gdata.data = data;
gdata.base_type = base_type;
gdata.ccheck = ccheck;
gdata.pcheck = pcheck;
item = BSE_IS_CONTAINER (item) ? item : item->parent;
while (item)
{
BseContainer *container = BSE_CONTAINER (item);
if (!gdata.ccheck || gdata.ccheck (container, gdata.item, gdata.data))
bse_container_forall_items (container, gather_child, &gdata);
item = item->parent;
}
}
static gboolean
gather_typed_ccheck (BseContainer *container,
BseItem *item,
void *data)
{
GType type = (GType) data;
return g_type_is_a (G_OBJECT_TYPE (container), type);
}
static gboolean
gather_typed_acheck (BseItem *proxy,
BseItem *item,
void *data)
{
return proxy != item && !bse_item_has_ancestor (item, proxy);
}
/**
* @param item valid BseItem from which to start gathering
* @param items sequence of items to append to
* @param proxy_type base type of the items to gather
* @param container_type base type of the containers to check for items
* @param allow_ancestor if FALSE, ancestors of @a item are omitted
*
* Variant of bse_item_gather_items(), the containers and items
* are simply filtered by checking derivation from @a container_type
* and @a proxy_type respectively. Gathered items may not be ancestors
* of @a item if @a allow_ancestor is @a false.
*/
void
bse_item_gather_items_typed (BseItem *item, Bse::ItemSeq &iseq, GType proxy_type, GType container_type, bool allow_ancestor)
{
if (allow_ancestor)
bse_item_gather_items (item, iseq, proxy_type, gather_typed_ccheck, NULL, (void*) container_type);
else
bse_item_gather_items (item, iseq, proxy_type, gather_typed_ccheck, gather_typed_acheck, (void*) container_type);
}
gboolean
bse_item_get_candidates (BseItem *item, const Bse::String &property, Bse::PropertyCandidates &pc)
{
BseItemClass *klass;
GParamSpec *pspec;
assert_return (BSE_IS_ITEM (item), FALSE);
pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (item), property.c_str());
if (!pspec)
return FALSE;
klass = (BseItemClass*) g_type_class_peek (pspec->owner_type);
if (klass && klass->get_candidates)
klass->get_candidates (item, pspec->param_id, pc, pspec);
return TRUE;
}
BseItem*
bse_item_use (BseItem *item)
{
assert_return (BSE_IS_ITEM (item), NULL);
assert_return (G_OBJECT (item)->ref_count > 0, NULL);
if (!item->use_count)
g_object_ref (item);
item->use_count++;
return item;
}
void
bse_item_unuse (BseItem *item)
{
assert_return (BSE_IS_ITEM (item));
assert_return (item->use_count > 0);
item->use_count--;
if (!item->use_count)
{
if (!item->parent)
g_object_run_dispose (G_OBJECT (item));
g_object_unref (item);
}
}
void
bse_item_set_parent (BseItem *item,
BseItem *parent)
{
assert_return (BSE_IS_ITEM (item));
if (parent)
{
assert_return (item->parent == NULL);
assert_return (BSE_IS_CONTAINER (parent));
}
else
assert_return (item->parent != NULL);
assert_return (BSE_ITEM_GET_CLASS (item)->set_parent != NULL); /* paranoid */
g_object_ref (item);
if (parent)
g_object_ref (parent);
BSE_ITEM_GET_CLASS (item)->set_parent (item, parent);
if (parent)
g_object_unref (parent);
else
g_object_run_dispose (G_OBJECT (item));
g_object_unref (item);
}
static uint
bse_item_do_get_seqid (BseItem *item)
{
if (item->parent)
return bse_container_get_item_seqid (BSE_CONTAINER (item->parent), item);
else
return 0;
}
static gboolean
idle_handler_seqid_changed (void *data)
{
BSE_THREADS_ENTER ();
while (item_seqid_changed_queue)
{
BseItem *item = (BseItem*) g_slist_pop_head (&item_seqid_changed_queue);
g_object_notify (G_OBJECT (item), "seqid");
}
BSE_THREADS_LEAVE ();
return FALSE;
}
void
bse_item_queue_seqid_changed (BseItem *item)
{
assert_return (BSE_IS_ITEM (item));
assert_return (BSE_ITEM (item)->parent != NULL);
if (!item_seqid_changed_queue)
bse_idle_notify (idle_handler_seqid_changed, NULL);
if (!g_slist_find (item_seqid_changed_queue, item))
item_seqid_changed_queue = g_slist_prepend (item_seqid_changed_queue, item);
}
uint
bse_item_get_seqid (BseItem *item)
{
assert_return (BSE_IS_ITEM (item), 0);
assert_return (BSE_ITEM_GET_CLASS (item)->get_seqid != NULL, 0); /* paranoid */
return BSE_ITEM_GET_CLASS (item)->get_seqid (item);
}
BseItem*
bse_item_common_ancestor (BseItem *item1,
BseItem *item2)
{
assert_return (BSE_IS_ITEM (item1), NULL);
assert_return (BSE_IS_ITEM (item2), NULL);
do
{
BseItem *item = item2;
do
{
if (item == item1)
return item;
item = item->parent;
}
while (item);
item1 = item1->parent;
}
while (item1);
return NULL;
}
/**
* @param owner reference owner
* @param link item to be referenced by @a owner
* @param uncross_func notifier to be executed on uncrossing
*
* Install a weak cross reference from @a owner to @a link.
* The two items must have a common ancestor when the cross
* link is installed. Once their ancestry changes so that
* they don't have a common ancestor anymore, @a uncross_func()
* is executed.
*/
void
bse_item_cross_link (BseItem *owner,
BseItem *link,
BseItemUncross uncross_func)
{
BseItem *container;
assert_return (BSE_IS_ITEM (owner));
assert_return (BSE_IS_ITEM (link));
assert_return (uncross_func != NULL);
container = bse_item_common_ancestor (owner, link);
if (container)
_bse_container_cross_link (BSE_CONTAINER (container), owner, link, uncross_func);
else
Bse::warning ("%s: %s and %s have no common anchestor", G_STRLOC,
bse_object_debug_name (owner),
bse_object_debug_name (link));
}
/**
* @param owner reference owner
* @param link item referenced by @a owner
* @param uncross_func notifier queued to be executed on uncrossing
*
* Removes a cross link previously installed via
* bse_item_cross_link() without executing @a uncross_func().
*/
void
bse_item_cross_unlink (BseItem *owner,
BseItem *link,
BseItemUncross uncross_func)
{
BseItem *container;
assert_return (BSE_IS_ITEM (owner));
assert_return (BSE_IS_ITEM (link));
assert_return (uncross_func != NULL);
container = bse_item_common_ancestor (owner, link);
if (container)
_bse_container_cross_unlink (BSE_CONTAINER (container), owner, link, uncross_func);
else
Bse::warning ("%s: `%s' and `%s' have no common anchestor", G_STRLOC,
BSE_OBJECT_TYPE_NAME (owner),
BSE_OBJECT_TYPE_NAME (link));
}
/**
* @param owner reference owner
* @param link item referenced by @a owner
*
* Destroys all existing cross links from @a owner to
* @a link by executing the associated notifiers.
*/
void
bse_item_uncross_links (BseItem *owner,
BseItem *link)
{
BseItem *container;
assert_return (BSE_IS_ITEM (owner));
assert_return (BSE_IS_ITEM (link));
container = bse_item_common_ancestor (owner, link);
if (container)
_bse_container_uncross (BSE_CONTAINER (container), owner, link);
}
BseSuper*
bse_item_get_super (BseItem *item)
{
assert_return (BSE_IS_ITEM (item), NULL);
while (!BSE_IS_SUPER (item) && item)
item = item->parent;
return item ? BSE_SUPER (item) : NULL;
}
BseSNet*
bse_item_get_snet (BseItem *item)
{
assert_return (BSE_IS_ITEM (item), NULL);
while (!BSE_IS_SNET (item) && item)
item = item->parent;
return item ? BSE_SNET (item) : NULL;
}
BseItem*
bse_item_get_toplevel (BseItem *item)
{
assert_return (BSE_IS_ITEM (item), NULL);
while (item->parent)
item = item->parent;
return item;
}
BseProject*
bse_item_get_project (BseItem *item)
{
assert_return (BSE_IS_ITEM (item), NULL);
while (item->parent)
item = item->parent;
return BSE_IS_PROJECT (item) ? (BseProject*) item : NULL;
}
gboolean
bse_item_has_ancestor (BseItem *item,
BseItem *ancestor)
{
assert_return (BSE_IS_ITEM (item), FALSE);
assert_return (BSE_IS_ITEM (ancestor), FALSE);
while (item->parent)
{
item = item->parent;
if (item == ancestor)
return TRUE;
}
return FALSE;
}
/**
* @param self a valid Item
* @return the current BseMusicalTuningType, defaulting to BSE_MUSICAL_TUNING_12_TET
* Find out about the musical tuning that is currently used for this item.
* The musical tuning depends on project wide settings that may change after
* this funciton has been called, so the result should be used with caution.
*/
Bse::MusicalTuning
bse_item_current_musical_tuning (BseItem *self)
{
assert_return (BSE_IS_ITEM (self), Bse::MusicalTuning::OD_12_TET);
/* finding the musical tuning *should* be possible by just visiting
* an items parents. however, .bse objects are not currently (0.7.1)
* structured that way, so we get the tuning from the first song in
* a project, or simply provide a default.
*/
BseProject *project = bse_item_get_project (self);
if (project)
{
GSList *slist;
for (slist = project->supers; slist; slist = slist->next)
if (BSE_IS_SONG (slist->data))
return BSE_SONG (slist->data)->musical_tuning;
}
return Bse::MusicalTuning::OD_12_TET;
}
static inline GType
find_method_procedure (GType object_type,
const char *method_name)
{
uint l2 = strlen (method_name);
GType proc_type, type = object_type; /* assumed to be *derived* from BSE_TYPE_ITEM */
do
{
const char *type_name = g_type_name (type);
uint l1 = strlen (type_name);
char *name = g_new (char, l1 + 1 + l2 + 1);
memcpy (name, type_name, l1);
name[l1] = '+';
memcpy (name + l1 + 1, method_name, l2);
name[l1 + 1 + l2] = 0;
proc_type = bse_procedure_lookup (name);
g_free (name);
if (proc_type)
break;
type = g_type_parent (type);
}
while (type != BSE_TYPE_ITEM); /* type will become BSE_TYPE_ITEM eventually */
return proc_type;
}
static inline Bse::Error
bse_item_execva_i (BseItem *item,
const char *procedure,
va_list var_args,
gboolean skip_oparams)
{
Bse::Error error;
GType proc_type = find_method_procedure (BSE_OBJECT_TYPE (item), procedure);
GValue obj_value;
if (!proc_type)
{
Bse::warning ("no such method \"%s\" of item %s",
procedure, bse_object_debug_name (item));
return Bse::Error::INTERNAL;
}
/* setup first arg (the object) */
obj_value.g_type = 0;
g_value_init (&obj_value, BSE_TYPE_ITEM);
g_value_set_object (&obj_value, item);
/* invoke procedure */
error = bse_procedure_marshal_valist (proc_type, &obj_value, NULL, NULL, skip_oparams, var_args);
g_value_unset (&obj_value);
return error;
}
Bse::Error
bse_item_exec (void *_item,
const char *procedure,
...)
{
BseItem *item = (BseItem*) _item;
va_list var_args;
Bse::Error error;
assert_return (BSE_IS_ITEM (item), Bse::Error::INTERNAL);
assert_return (procedure != NULL, Bse::Error::INTERNAL);
va_start (var_args, procedure);
error = bse_item_execva_i (item, procedure, var_args, FALSE);
va_end (var_args);
return error;
}
Bse::Error
bse_item_exec_void (void *_item,
const char *procedure,
...)
{
BseItem *item = (BseItem*) _item;
va_list var_args;
Bse::Error error;
assert_return (BSE_IS_ITEM (item), Bse::Error::INTERNAL);
assert_return (procedure != NULL, Bse::Error::INTERNAL);
va_start (var_args, procedure);
error = bse_item_execva_i (item, procedure, var_args, TRUE);
va_end (var_args);
return error;
}
static GValue*
pack_value_for_undo (GValue *value,
BseUndoStack *ustack)
{
GType type = G_VALUE_TYPE (value);
if (G_TYPE_IS_OBJECT (type))
{
char *p = bse_undo_pointer_pack (g_value_get_object (value), ustack);
g_value_unset (value);
g_value_init (value, BSE_TYPE_PACKED_POINTER);
sfi_value_take_string (value, p);
}
return value;
}
static GValue*
unpack_value_from_undo (GValue *value,
BseUndoStack *ustack)
{
GType type = G_VALUE_TYPE (value);
if (type == BSE_TYPE_PACKED_POINTER)
{
BseItem *item = (BseItem*) bse_undo_pointer_unpack (g_value_get_string (value), ustack);
g_value_unset (value);
g_value_init (value, G_TYPE_OBJECT);
g_value_set_object (value, item);
}
return value;
}
static void
unde_free_proc (BseUndoStep *ustep)
{
BseProcedureClass *proc = (BseProcedureClass*) ustep->data[0].v_pointer;
GValue *ivalues = (GValue*) ustep->data[1].v_pointer; /* may or may not packed for undo */
if (ivalues && proc)
{
uint i;
for (i = 0; i < proc->n_in_pspecs; i++)
g_value_unset (ivalues + i);
g_free (ivalues);
g_type_class_unref (proc);
}
}
static void
undo_call_proc (BseUndoStep *ustep,
BseUndoStack *ustack)
{
BseProcedureClass *proc = (BseProcedureClass*) ustep->data[0].v_pointer;
GValue *ivalues = (GValue*) ustep->data[1].v_pointer; /* packed for undo */
gboolean commit_as_redo = ustep->data[2].v_long;
if (commit_as_redo)
{
const char *packed_item_pointer = g_value_get_string (ivalues + 0);
BseItem *item = (BseItem*) bse_undo_pointer_unpack (packed_item_pointer, ustack);
BseUndoStack *redo_stack = bse_item_undo_open (item, "%s", BSE_PROCEDURE_NAME (proc));
BseUndoStep *redo_step;
redo_step = bse_undo_step_new (undo_call_proc, unde_free_proc, 3);
redo_step->data[0].v_pointer = proc;
redo_step->data[1].v_pointer = ivalues;
redo_step->data[2].v_long = FALSE; /* not commit_as_redo again */
bse_undo_stack_push (redo_stack, redo_step);
bse_item_undo_close (redo_stack);
/* prevent premature deletion */
ustep->data[0].v_pointer = NULL;
ustep->data[1].v_pointer = NULL;
}
else /* invoke procedure */
{
GValue ovalue = { 0, };
Bse::Error error;
uint i;
/* convert values from undo */
for (i = 0; i < proc->n_in_pspecs; i++)
unpack_value_from_undo (ivalues + i, ustack);
/* setup return value (maximum one) */
if (proc->n_out_pspecs)
g_value_init (&ovalue, G_PARAM_SPEC_VALUE_TYPE (proc->out_pspecs[0]));
/* invoke procedure */
error = bse_procedure_marshal (BSE_PROCEDURE_TYPE (proc), ivalues, &ovalue, NULL, NULL);
/* clenup return value */
if (proc->n_out_pspecs)
{
/* check returned error if any */
if (G_PARAM_SPEC_VALUE_TYPE (proc->out_pspecs[0]) == BSE_TYPE_ERROR_TYPE && error == 0)
error = Bse::Error (g_value_get_enum (&ovalue));
g_value_unset (&ovalue);
}
/* we're not tolerating any errors */
if (error != 0)
Bse::warning ("while executing undo method \"%s\" of item %s: %s", BSE_PROCEDURE_NAME (proc),
bse_object_debug_name (g_value_get_object (ivalues + 0)), bse_error_blurb (error));
}
}
static void
bse_item_push_undo_proc_valist (void *item,
const char *procedure,
gboolean commit_as_redo,
va_list var_args)
{
GType proc_type = find_method_procedure (BSE_OBJECT_TYPE (item), procedure);
BseUndoStack *ustack = bse_item_undo_open (item, "%s: %s", commit_as_redo ? "redo-proc" : "undo-proc", procedure);
BseProcedureClass *proc;
GValue *ivalues;
Bse::Error error;
uint i;
if (BSE_UNDO_STACK_VOID (ustack) ||
BSE_ITEM_INTERNAL (item))
{
bse_item_undo_close (ustack);
return;
}
if (!proc_type)
{
Bse::warning ("no such method \"%s\" of item %s",
procedure, bse_object_debug_name (item));
bse_item_undo_close (ustack);
return;
}
proc = (BseProcedureClass*) g_type_class_ref (proc_type);
/* we allow one return value */
if (proc->n_out_pspecs > 1)
{
Bse::warning ("method \"%s\" of item %s called with more than one return value",
procedure, bse_object_debug_name (item));
g_type_class_unref (proc);
bse_item_undo_close (ustack);
return;
}
ivalues = g_new (GValue, proc->n_in_pspecs);
/* setup first arg (the object) */
ivalues[0].g_type = 0;
g_value_init (ivalues + 0, BSE_TYPE_ITEM);
g_value_set_object (ivalues + 0, item);
/* collect procedure args */
error = bse_procedure_collect_input_args (proc, ivalues + 0, var_args, ivalues);
if (error == 0)
{
BseUndoStep *ustep = bse_undo_step_new (undo_call_proc, unde_free_proc, 3);
/* convert values for undo */
for (i = 0; i < proc->n_in_pspecs; i++)
pack_value_for_undo (ivalues + i, ustack);
ustep->data[0].v_pointer = proc;
ustep->data[1].v_pointer = ivalues;
ustep->data[2].v_long = commit_as_redo;
bse_undo_stack_push (ustack, ustep);
}
else /* urg shouldn't happen */
{
Bse::warning ("while collecting arguments for method \"%s\" of item %s: %s",
procedure, bse_object_debug_name (item), bse_error_blurb (error));
for (i = 0; i < proc->n_in_pspecs; i++)
g_value_unset (ivalues + i);
g_free (ivalues);
g_type_class_unref (proc);
}
bse_item_undo_close (ustack);
}
void
bse_item_push_undo_proc (void *item,
const char *procedure,
...)
{
va_list var_args;
assert_return (BSE_IS_ITEM (item));
assert_return (procedure != NULL);
va_start (var_args, procedure);
bse_item_push_undo_proc_valist (item, procedure, FALSE, var_args);
va_end (var_args);
}
void
bse_item_push_redo_proc (void *item,
const char *procedure,
...)
{
va_list var_args;
assert_return (BSE_IS_ITEM (item));
assert_return (procedure != NULL);
va_start (var_args, procedure);
bse_item_push_undo_proc_valist (item, procedure, TRUE, var_args);
va_end (var_args);
}
void
bse_item_set_undoable (void *object,
const char *first_property_name,
...)
{
va_list var_args;
assert_return (BSE_IS_ITEM (object));
va_start (var_args, first_property_name);
bse_item_set_valist_undoable (object, first_property_name, var_args);
va_end (var_args);
}
void
bse_item_set_valist_undoable (void *object,
const char *first_property_name,
va_list var_args)
{
BseItem *self = BSE_ITEM (object);
const char *name;
assert_return (BSE_IS_ITEM (self));
g_object_ref (object);
g_object_freeze_notify (G_OBJECT (object));
name = first_property_name;
while (name)
{
GValue value = { 0, };
GParamSpec *pspec;
char *error = NULL;
pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (self), name);
if (!pspec)
{
Bse::warning ("item %s has no property named `%s'",
bse_object_debug_name (self), name);
break;
}
g_value_init (&value, G_PARAM_SPEC_VALUE_TYPE (pspec));
G_VALUE_COLLECT (&value, var_args, 0, &error);
if (error)
{
Bse::warning ("while setting property `%s' on %s: %s",
name, bse_object_debug_name (self), error);
g_free (error);
g_value_unset (&value);
break;
}
bse_item_set_property_undoable (self, pspec->name, &value);
g_value_unset (&value);
name = va_arg (var_args, char*);
}
g_object_thaw_notify (G_OBJECT (object));
g_object_unref (object);
}
static BseUndoStack*
bse_item_default_get_undo (BseItem *self)
{
if (self->parent)
return BSE_ITEM_GET_CLASS (self->parent)->get_undo (self->parent);
else
return NULL;
}
static gboolean
values_equal_for_undo (const GValue *v1,
const GValue *v2)
{
SfiSCategory sc1 = sfi_categorize_type (G_VALUE_TYPE (v1));
SfiSCategory sc2 = sfi_categorize_type (G_VALUE_TYPE (v2));
if (sc1 != sc2)
return FALSE;
switch (sc1)
{
case SFI_SCAT_BOOL: return sfi_value_get_bool (v1) == sfi_value_get_bool (v2);
case SFI_SCAT_INT: return sfi_value_get_int (v1) == sfi_value_get_int (v2);
case SFI_SCAT_NUM: return sfi_value_get_num (v1) == sfi_value_get_num (v2);
case SFI_SCAT_REAL: return sfi_value_get_real (v1) == sfi_value_get_real (v2); /* *no* epsilon! */
case SFI_SCAT_CHOICE:
case SFI_SCAT_STRING: return bse_string_equals (sfi_value_get_string (v1), sfi_value_get_string (v2));
default:
if (G_TYPE_IS_OBJECT (G_VALUE_TYPE (v1)) &&
G_TYPE_IS_OBJECT (G_VALUE_TYPE (v2)))
return g_value_get_object (v1) == g_value_get_object (v2);
}
return FALSE;
}
static void
undo_set_property (BseUndoStep *ustep,
BseUndoStack *ustack)
{
bse_item_set_property_undoable ((BseItem*) bse_undo_pointer_unpack ((const char*) ustep->data[0].v_pointer, ustack),
(const char*) ustep->data[1].v_pointer,
unpack_value_from_undo ((GValue*) ustep->data[2].v_pointer, ustack));
}
static void
unde_free_property (BseUndoStep *ustep)
{
g_free (ustep->data[0].v_pointer);
g_free (ustep->data[1].v_pointer);
g_value_unset ((GValue*) ustep->data[2].v_pointer); /* may or may not be unpacked */
g_free (ustep->data[2].v_pointer);
}
static inline gboolean
item_property_check_skip_undo (BseItem *self,
const char *name)
{
GParamSpec *pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (self), name);
return pspec && sfi_pspec_check_option (pspec, "skip-undo");
}
void
bse_item_set_property_undoable (BseItem *self,
const char *name,
const GValue *value)
{
BseUndoStack *ustack = bse_item_undo_open (self, "set-property(%s,\"%s\")", bse_object_debug_name (self), name);
BseUndoStep *ustep;
GValue *tvalue = g_new0 (GValue, 1);
g_value_init (tvalue, G_VALUE_TYPE (value));
g_object_get_property (G_OBJECT (self), name, tvalue);
if (BSE_ITEM_INTERNAL (self) ||
item_property_check_skip_undo (self, name) ||
values_equal_for_undo (value, tvalue))
{
/* we're about to set a value on an internal item or
* to set the same value again => skip undo
*/
g_value_unset (tvalue);
g_free (tvalue);
bse_item_undo_close (ustack);
g_object_set_property (G_OBJECT (self), name, value);
return;
}
g_object_set_property (G_OBJECT (self), name, value);
/* pointer-pack must be called *after* property update (could be "uname") */
ustep = bse_undo_step_new (undo_set_property, unde_free_property, 3);
ustep->data[0].v_pointer = bse_undo_pointer_pack (self, ustack);
ustep->data[1].v_pointer = g_strdup (name);
ustep->data[2].v_pointer = pack_value_for_undo (tvalue, ustack);
bse_undo_stack_push (ustack, ustep);
bse_item_undo_close (ustack);
}
BseUndoStack*
bse_item_undo_open_str (void *item, const std::string &string)
{
BseItem *self = BSE_ITEM (item);
BseUndoStack *ustack = BSE_ITEM_GET_CLASS (self)->get_undo (self);
if (ustack)
bse_undo_group_open (ustack, string.c_str());
else
{
ustack = bse_undo_stack_dummy ();
bse_undo_group_open (ustack, Bse::string_format ("DUMMY-GROUP(%s)", string).c_str());
}
return ustack;
}
void
bse_item_undo_close (BseUndoStack *ustack)
{
if (ustack)
bse_undo_group_close (ustack);
}
static void
undo_restore_item (BseUndoStep *ustep,
BseUndoStack *ustack)
{
BseItem *item = (BseItem*) bse_undo_pointer_unpack ((const char*) ustep->data[0].v_pointer, ustack);
BseStorage *storage = BSE_STORAGE (ustep->data[1].v_pointer);
GTokenType expected_token = G_TOKEN_NONE;
expected_token = bse_storage_restore_item (storage, item);
if (expected_token != G_TOKEN_NONE)
bse_storage_unexp_token (storage, expected_token);
bse_storage_finish_parsing (storage);
}
static void
unde_free_item (BseUndoStep *ustep)
{
BseStorage *storage = BSE_STORAGE (ustep->data[1].v_pointer);
g_free (ustep->data[0].v_pointer);
bse_storage_reset (storage);
g_object_unref (storage);
}
void
bse_item_push_undo_storage (BseItem *self,
BseUndoStack *ustack,
BseStorage *storage)
{
if (!BSE_ITEM_INTERNAL (self) && !BSE_UNDO_STACK_VOID (ustack))
{
BseUndoStep *ustep = bse_undo_step_new (undo_restore_item, unde_free_item, 2);
bse_storage_turn_readable (storage, "<undo-storage>");
ustep->data[0].v_pointer = bse_undo_pointer_pack (self, ustack);
ustep->data[1].v_pointer = g_object_ref (storage);
bse_undo_stack_push (ustack, ustep);
}
else
bse_storage_reset (storage);
}
void
bse_item_backup_to_undo (BseItem *self,
BseUndoStack *ustack)
{
if (!BSE_UNDO_STACK_VOID (ustack))
{
BseStorage *storage = (BseStorage*) bse_object_new (BSE_TYPE_STORAGE, NULL);
bse_storage_prepare_write (storage, BseStorageMode (BSE_STORAGE_DBLOCK_CONTAINED |
BSE_STORAGE_SELF_CONTAINED));
bse_storage_store_item (storage, self);
bse_item_push_undo_storage (self, ustack, storage);
g_object_unref (storage);
}
}
namespace Bse {
ItemImpl::ItemImpl (BseObject *bobj) :
ObjectImpl (bobj)
{}
ItemImpl::~ItemImpl ()
{}
ItemIfaceP
ItemImpl::use ()
{
BseItem *self = as<BseItem*>();
ItemIfaceP iface = self->as<ItemIfaceP>();
assert_return (self->parent || self->use_count, iface);
bse_item_use (self);
return iface;
}
void
ItemImpl::unuse ()
{
BseItem *self = as<BseItem*>();
assert_return (self->use_count >= 1);
bse_item_unuse (self);
}
void
ItemImpl::set_name (const std::string &name)
{
BseItem *self = as<BseItem*>();
if (name != BSE_OBJECT_UNAME (self))
bse_item_set (self, "uname", name.c_str(), NULL);
}
bool
ItemImpl::editable_property (const std::string &property)
{
BseItem *self = as<BseItem*>();
return bse_object_editable_property (self, property.c_str());
}
ContainerImpl*
ItemImpl::parent ()
{
BseItem *self = as<BseItem*>();
return self->parent ? self->parent->as<ContainerImpl*>() : NULL;
}
ItemImpl::UndoDescriptorData
ItemImpl::make_undo_descriptor_data (ItemImpl &item)
{
// sync with bse_undo_pointer_pack
UndoDescriptorData udd;
BseItem *bitem = item.as<BseItem*>();
BseProject *bproject = bse_item_get_project (this->as<BseItem*>());
if (!bproject) // may happen during destruction
return udd; // this UndoDescriptorData is constructed but will never be used
assert_return (bproject == bse_item_get_project (bitem), udd); // undo descriptors work only for items within same project
ProjectImpl *project = bproject->as<ProjectImpl*>();
udd.projectid = ptrdiff_t (project);
if (&item == project)
udd.upath = "\002project\003";
else
{
gchar *upath = bse_container_make_upath (bproject, bitem);
udd.upath = upath;
g_free (upath);
}
return udd;
}
ItemImpl&
ItemImpl::resolve_undo_descriptor_data (const UndoDescriptorData &udd)
{
// sync with bse_undo_pointer_unpack
ItemImpl &nullitem = *(ItemImpl*) NULL;
assert_return (udd.projectid != 0, nullitem);
BseProject *bproject = bse_item_get_project (this->as<BseItem*>());
ProjectImpl *project = bproject ? bproject->as<ProjectImpl*>() : NULL;
assert_return (udd.projectid == ptrdiff_t (project), nullitem); // undo cannot work on orphans
if (udd.upath == "\002project\003")
return *project;
BseItem *bitem = bse_container_resolve_upath (bproject, udd.upath.c_str());
assert_return (bitem != NULL, nullitem); // undo descriptor for NULL objects is not currently supported
return *bitem->as<ItemImpl*>();
}
static void
undo_lambda_free (BseUndoStep *ustep)
{
delete (ItemImpl::UndoDescriptor<ItemImpl>*) ustep->data[0].v_pointer;
delete (ItemImpl::UndoLambda*) ustep->data[1].v_pointer;
delete (String*) ustep->data[2].v_pointer;
}
static void
undo_lambda_call (BseUndoStep *ustep, BseUndoStack *ustack)
{
ProjectImpl &project = *ustack->project->as<ProjectImpl*>();
ItemImpl &self = project.undo_resolve (*(ItemImpl::UndoDescriptor<ItemImpl>*) ustep->data[0].v_pointer);
auto *lambda = (ItemImpl::UndoLambda*) ustep->data[1].v_pointer;
// invoke undo function
const Bse::Error error = (*lambda) (self, ustack);
if (error != 0) // undo errors shouldn't happen
{
String *blurb = (String*) ustep->data[2].v_pointer;
Bse::warning ("error during undo '%s' of item %s: %s", blurb->c_str(),
self.debug_name().c_str(), bse_error_blurb (error));
}
}
void
ItemImpl::push_item_undo (const String &blurb, const UndoLambda &lambda)
{
BseItem *self = as<BseItem*>();
BseUndoStack *ustack = bse_item_undo_open (self, "undo: %s", blurb.c_str());
if (BSE_UNDO_STACK_VOID (ustack) || BSE_ITEM_INTERNAL (self))
{
bse_item_undo_close (ustack);
return;
}
BseUndoStep *ustep = bse_undo_step_new (undo_lambda_call, undo_lambda_free, 3);
ustep->data[0].v_pointer = new UndoDescriptor<ItemImpl> (undo_descriptor (*this));
ustep->data[1].v_pointer = new UndoLambda (lambda);
ustep->data[2].v_pointer = new String (blurb);
bse_undo_stack_push (ustack, ustep);
bse_item_undo_close (ustack);
}
void
ItemImpl::push_property_undo (const String &property_name)
{
assert_return (property_name.empty() == false);
Any saved_value = __aida_get__ (property_name);
if (saved_value.empty())
Bse::warning ("%s: invalid property name: %s", __func__, property_name);
else
{
auto lambda = [property_name, saved_value] (ItemImpl &self, BseUndoStack *ustack) -> Error {
const bool success = self.__aida_set__ (property_name, saved_value);
if (!success)
Bse::warning ("%s: failed to undo property change for '%s': %s", __func__, property_name, saved_value.repr());
return Error::NONE;
};
push_undo (__func__, *this, lambda);
}
}
ProjectIfaceP
ItemImpl::get_project ()
{
BseItem *self = as<BseItem*>();
BseProject *project = bse_item_get_project (self);
return project ? project->as<Bse::ProjectIfaceP>() : NULL;
}
ItemIfaceP
ItemImpl::common_ancestor (ItemIface &other)
{
BseItem *self = as<BseItem*>();
BseItem *bo = other.as<BseItem*>();
BseItem *common = bse_item_common_ancestor (self, bo);
return common->as<ItemIfaceP>();
}
bool
ItemImpl::check_is_a (const String &type_name)
{
BseItem *self = as<BseItem*>();
const GType type = g_type_from_name (type_name.c_str());
const bool is_a = g_type_is_a (G_OBJECT_TYPE (self), type);
return is_a;
}
void
ItemImpl::group_undo (const std::string &name)
{
BseItem *self = as<BseItem*>();
BseUndoStack *ustack = bse_item_undo_open (self, "item-group-undo");
bse_undo_stack_add_merger (ustack, name.c_str());
bse_item_undo_close (ustack);
}
void
ItemImpl::ungroup_undo ()
{
BseItem *self = as<BseItem*>();
BseUndoStack *ustack = bse_item_undo_open (self, "item-ungroup-undo");
bse_undo_stack_remove_merger (ustack);
bse_item_undo_close (ustack);
}
class CustomIconKey : public DataKey<Icon*> {
virtual void destroy (Icon *icon) override { delete icon; }
};
static CustomIconKey custom_icon_key;
Icon
ItemImpl::icon () const
{
BseItem *self = const_cast<ItemImpl*> (this)->as<BseItem*>();
Icon *icon = get_data (&custom_icon_key);
return icon ? *icon : bse_object_get_icon (self);
}
void
ItemImpl::icon (const Icon &icon)
{
Icon *custom_icon = new Icon (icon);
icon_sanitize (custom_icon);
if (custom_icon->width != 0)
set_data (&custom_icon_key, custom_icon);
else
{
delete custom_icon;
delete_data (&custom_icon_key);
}
}
ItemIfaceP
ItemImpl::get_parent ()
{
return parent() ? parent()->as<ContainerIfaceP>() : NULL;
}
int
ItemImpl::get_seqid ()
{
BseItem *self = as<BseItem*>();
return bse_item_get_seqid (self);
}
String
ItemImpl::get_type ()
{
BseItem *self = as<BseItem*>();
return g_type_name (G_OBJECT_TYPE (self));
}
String
ItemImpl::get_type_authors ()
{
BseItem *self = as<BseItem*>();
return bse_type_get_authors (G_OBJECT_TYPE (self));
}
String
ItemImpl::get_type_blurb ()
{
BseItem *self = as<BseItem*>();
return bse_type_get_blurb (G_OBJECT_TYPE (self));
}
String
ItemImpl::get_type_license ()
{
BseItem *self = as<BseItem*>();
return bse_type_get_license (G_OBJECT_TYPE (self));
}
String
ItemImpl::get_type_name ()
{
BseItem *self = as<BseItem*>();
return g_type_name (G_OBJECT_TYPE (self));
}
String
ItemImpl::get_uname_path ()
{
BseItem *self = as<BseItem*>();
BseProject *project = bse_item_get_project (self);
gchar *upath = project ? bse_container_make_upath (BSE_CONTAINER (project), self) : NULL;
const String result = upath ? upath : "";
g_free (upath);
return result;
}
String
ItemImpl::get_name ()
{
BseItem *self = as<BseItem*>();
return BSE_OBJECT_UNAME (self);
}
String
ItemImpl::get_name_or_type ()
{
BseItem *self = as<BseItem*>();
const char *name = BSE_OBJECT_UNAME (self);
const String result = name ? name : BSE_OBJECT_TYPE_NAME (self);
return result;
}
bool
ItemImpl::internal ()
{
BseItem *self = as<BseItem*>();
return BSE_ITEM_INTERNAL (self);
}
PropertyCandidates
ItemImpl::get_property_candidates (const String &property_name)
{
BseItem *self = as<BseItem*>();
PropertyCandidates pc;
if (bse_item_get_candidates (self, property_name, pc))
return pc;
return PropertyCandidates();
}
} // Bse
| GNOME/beast | bse/bseitem.cc | C++ | lgpl-2.1 | 44,851 |
// dummy file needed by the build system because
// main is in main.cpp rather than fil-sdk-example.cpp
| einon/affymetrix-power-tools | sdk/mas5-stat/example/mas5-stat-example.cpp | C++ | lgpl-2.1 | 104 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.06.12 at 12:19:07 PM EDT
//
package org.hl7.fhir;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ConstraintSeverity-list.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ConstraintSeverity-list">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="error"/>
* <enumeration value="warning"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "ConstraintSeverity-list")
@XmlEnum
public enum ConstraintSeverityList {
/**
* If the constraint is violated, the resource is not conformant.
*
*/
@XmlEnumValue("error")
ERROR("error"),
/**
* If the constraint is violated, the resource is conformant, but it is not necessarily following best practice.
*
*/
@XmlEnumValue("warning")
WARNING("warning");
private final java.lang.String value;
ConstraintSeverityList(java.lang.String v) {
value = v;
}
public java.lang.String value() {
return value;
}
public static ConstraintSeverityList fromValue(java.lang.String v) {
for (ConstraintSeverityList c: ConstraintSeverityList.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| attunetc/ehr | src/org/hl7/fhir/ConstraintSeverityList.java | Java | lgpl-2.1 | 1,835 |
/**
* This file is part of TelepathyQt4
*
* @copyright Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
* @copyright Copyright (C) 2008 Nokia Corporation
* @license LGPL 2.1
*
* 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 <TelepathyQt4/Channel>
#include "TelepathyQt4/channel-internal.h"
#include "TelepathyQt4/_gen/cli-channel-body.hpp"
#include "TelepathyQt4/_gen/cli-channel.moc.hpp"
#include "TelepathyQt4/_gen/channel.moc.hpp"
#include "TelepathyQt4/_gen/channel-internal.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include "TelepathyQt4/future-internal.h"
#include <TelepathyQt4/ChannelFactory>
#include <TelepathyQt4/Connection>
#include <TelepathyQt4/ConnectionCapabilities>
#include <TelepathyQt4/ConnectionLowlevel>
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/PendingContacts>
#include <TelepathyQt4/PendingFailure>
#include <TelepathyQt4/PendingOperation>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/PendingSuccess>
#include <TelepathyQt4/StreamTubeChannel>
#include <TelepathyQt4/ReferencedHandles>
#include <TelepathyQt4/Constants>
#include <QHash>
#include <QQueue>
#include <QSharedData>
#include <QTimer>
namespace Tp
{
using TpFuture::Client::ChannelInterfaceMergeableConferenceInterface;
using TpFuture::Client::ChannelInterfaceSplittableInterface;
struct TELEPATHY_QT4_NO_EXPORT Channel::Private
{
Private(Channel *parent, const ConnectionPtr &connection,
const QVariantMap &immutableProperties);
~Private();
static void introspectMain(Private *self);
void introspectMainProperties();
void introspectMainFallbackChannelType();
void introspectMainFallbackHandle();
void introspectMainFallbackInterfaces();
void introspectGroup();
void introspectGroupFallbackFlags();
void introspectGroupFallbackMembers();
void introspectGroupFallbackLocalPendingWithInfo();
void introspectGroupFallbackSelfHandle();
void introspectConference();
static void introspectConferenceInitialInviteeContacts(Private *self);
void continueIntrospection();
void extractMainProps(const QVariantMap &props);
void extract0176GroupProps(const QVariantMap &props);
void nowHaveInterfaces();
void nowHaveInitialMembers();
bool setGroupFlags(uint groupFlags);
void buildContacts();
void doMembersChangedDetailed(const UIntList &, const UIntList &, const UIntList &,
const UIntList &, const QVariantMap &);
void processMembersChanged();
void updateContacts(const QList<ContactPtr> &contacts =
QList<ContactPtr>());
bool fakeGroupInterfaceIfNeeded();
void setReady();
QString groupMemberChangeDetailsTelepathyError(
const GroupMemberChangeDetails &details);
inline ChannelInterfaceMergeableConferenceInterface *mergeableConferenceInterface(
InterfaceSupportedChecking check = CheckInterfaceSupported) const
{
return parent->optionalInterface<ChannelInterfaceMergeableConferenceInterface>(check);
}
inline ChannelInterfaceSplittableInterface *splittableInterface(
InterfaceSupportedChecking check = CheckInterfaceSupported) const
{
return parent->optionalInterface<ChannelInterfaceSplittableInterface>(check);
}
void processConferenceChannelRemoved();
struct GroupMembersChangedInfo;
struct ConferenceChannelRemovedInfo;
// Public object
Channel *parent;
// Instance of generated interface class
Client::ChannelInterface *baseInterface;
// Mandatory properties interface proxy
Client::DBus::PropertiesInterface *properties;
// Owning connection - it can be a SharedPtr as Connection does not cache
// channels
ConnectionPtr connection;
QVariantMap immutableProperties;
// Optional interface proxies
Client::ChannelInterfaceGroupInterface *group;
Client::ChannelInterfaceConferenceInterface *conference;
ReadinessHelper *readinessHelper;
// Introspection
QQueue<void (Private::*)()> introspectQueue;
// Introspected properties
// Main interface
QString channelType;
uint targetHandleType;
uint targetHandle;
QString targetId;
ContactPtr targetContact;
bool requested;
uint initiatorHandle;
ContactPtr initiatorContact;
// Group flags
uint groupFlags;
bool usingMembersChangedDetailed;
// Group member introspection
bool groupHaveMembers;
bool buildingContacts;
// Queue of received MCD signals to process
QQueue<GroupMembersChangedInfo *> groupMembersChangedQueue;
GroupMembersChangedInfo *currentGroupMembersChangedInfo;
// Pending from the MCD signal currently processed, but contacts not yet built
QSet<uint> pendingGroupMembers;
QSet<uint> pendingGroupLocalPendingMembers;
QSet<uint> pendingGroupRemotePendingMembers;
UIntList groupMembersToRemove;
UIntList groupLocalPendingMembersToRemove;
UIntList groupRemotePendingMembersToRemove;
// Initial members
UIntList groupInitialMembers;
LocalPendingInfoList groupInitialLP;
UIntList groupInitialRP;
// Current members
QHash<uint, ContactPtr> groupContacts;
QHash<uint, ContactPtr> groupLocalPendingContacts;
QHash<uint, ContactPtr> groupRemotePendingContacts;
// Stored change info
QHash<uint, GroupMemberChangeDetails> groupLocalPendingContactsChangeInfo;
GroupMemberChangeDetails groupSelfContactRemoveInfo;
// Group handle owners
bool groupAreHandleOwnersAvailable;
HandleOwnerMap groupHandleOwners;
// Group self identity
bool pendingRetrieveGroupSelfContact;
bool groupIsSelfHandleTracked;
uint groupSelfHandle;
ContactPtr groupSelfContact;
// Conference
bool introspectingConference;
QHash<QString, ChannelPtr> conferenceChannels;
QHash<QString, ChannelPtr> conferenceInitialChannels;
QString conferenceInvitationMessage;
QHash<uint, ChannelPtr> conferenceOriginalChannels;
UIntList conferenceInitialInviteeHandles;
Contacts conferenceInitialInviteeContacts;
QQueue<ConferenceChannelRemovedInfo *> conferenceChannelRemovedQueue;
bool buildingConferenceChannelRemovedActorContact;
static const QString keyActor;
};
struct TELEPATHY_QT4_NO_EXPORT Channel::Private::GroupMembersChangedInfo
{
GroupMembersChangedInfo(const UIntList &added, const UIntList &removed,
const UIntList &localPending, const UIntList &remotePending,
const QVariantMap &details)
: added(added),
removed(removed),
localPending(localPending),
remotePending(remotePending),
details(details),
// TODO most of these probably should be removed once the rest of the code using them is sanitized
actor(qdbus_cast<uint>(details.value(keyActor))),
reason(qdbus_cast<uint>(details.value(keyChangeReason))),
message(qdbus_cast<QString>(details.value(keyMessage)))
{
}
UIntList added;
UIntList removed;
UIntList localPending;
UIntList remotePending;
QVariantMap details;
uint actor;
uint reason;
QString message;
static const QString keyChangeReason;
static const QString keyMessage;
static const QString keyContactIds;
};
struct TELEPATHY_QT4_NO_EXPORT Channel::Private::ConferenceChannelRemovedInfo
{
ConferenceChannelRemovedInfo(const QDBusObjectPath &channelPath, const QVariantMap &details)
: channelPath(channelPath),
details(details)
{
}
QDBusObjectPath channelPath;
QVariantMap details;
};
const QString Channel::Private::keyActor(QLatin1String("actor"));
const QString Channel::Private::GroupMembersChangedInfo::keyChangeReason(
QLatin1String("change-reason"));
const QString Channel::Private::GroupMembersChangedInfo::keyMessage(QLatin1String("message"));
const QString Channel::Private::GroupMembersChangedInfo::keyContactIds(QLatin1String("contact-ids"));
Channel::Private::Private(Channel *parent, const ConnectionPtr &connection,
const QVariantMap &immutableProperties)
: parent(parent),
baseInterface(new Client::ChannelInterface(parent)),
properties(parent->interface<Client::DBus::PropertiesInterface>()),
connection(connection),
immutableProperties(immutableProperties),
group(0),
conference(0),
readinessHelper(parent->readinessHelper()),
targetHandleType(0),
targetHandle(0),
requested(false),
initiatorHandle(0),
groupFlags(0),
usingMembersChangedDetailed(false),
groupHaveMembers(false),
buildingContacts(false),
currentGroupMembersChangedInfo(0),
groupAreHandleOwnersAvailable(false),
pendingRetrieveGroupSelfContact(false),
groupIsSelfHandleTracked(false),
groupSelfHandle(0),
introspectingConference(false),
buildingConferenceChannelRemovedActorContact(false)
{
debug() << "Creating new Channel:" << parent->objectPath();
if (connection->isValid()) {
debug() << " Connecting to Channel::Closed() signal";
parent->connect(baseInterface,
SIGNAL(Closed()),
SLOT(onClosed()));
debug() << " Connection to owning connection's lifetime signals";
parent->connect(connection.data(),
SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
SLOT(onConnectionInvalidated()));
}
else {
warning() << "Connection given as the owner for a Channel was "
"invalid! Channel will be stillborn.";
parent->invalidate(QLatin1String(TELEPATHY_ERROR_INVALID_ARGUMENT),
QLatin1String("Connection given as the owner of this channel was invalid"));
}
ReadinessHelper::Introspectables introspectables;
// As Channel does not have predefined statuses let's simulate one (0)
ReadinessHelper::Introspectable introspectableCore(
QSet<uint>() << 0, // makesSenseForStatuses
Features(), // dependsOnFeatures
QStringList(), // dependsOnInterfaces
(ReadinessHelper::IntrospectFunc) &Private::introspectMain,
this);
introspectables[FeatureCore] = introspectableCore;
// As Channel does not have predefined statuses let's simulate one (0)
ReadinessHelper::Introspectable introspectableConferenceInitialInviteeContacts(
QSet<uint>() << 0, // makesSenseForStatuses
Features() << FeatureCore, // dependsOnFeatures
QStringList() << TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE, // dependsOnInterfaces
(ReadinessHelper::IntrospectFunc) &Private::introspectConferenceInitialInviteeContacts,
this);
introspectables[FeatureConferenceInitialInviteeContacts] =
introspectableConferenceInitialInviteeContacts;
readinessHelper->addIntrospectables(introspectables);
}
Channel::Private::~Private()
{
delete currentGroupMembersChangedInfo;
foreach (GroupMembersChangedInfo *info, groupMembersChangedQueue) {
delete info;
}
foreach (ConferenceChannelRemovedInfo *info, conferenceChannelRemovedQueue) {
delete info;
}
}
void Channel::Private::introspectMain(Channel::Private *self)
{
// Make sure connection object is ready, as we need to use some methods that
// are only available after connection object gets ready.
debug() << "Calling Connection::becomeReady()";
self->parent->connect(self->connection->becomeReady(),
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onConnectionReady(Tp::PendingOperation*)));
}
void Channel::Private::introspectMainProperties()
{
QVariantMap props;
QString key;
bool needIntrospectMainProps = false;
const unsigned numNames = 8;
const static QString names[numNames] = {
QLatin1String("ChannelType"),
QLatin1String("Interfaces"),
QLatin1String("TargetHandleType"),
QLatin1String("TargetHandle"),
QLatin1String("TargetID"),
QLatin1String("Requested"),
QLatin1String("InitiatorHandle"),
QLatin1String("InitiatorID")
};
const static QString qualifiedNames[numNames] = {
QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"),
QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".Interfaces"),
QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"),
QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle"),
QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetID"),
QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".Requested"),
QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".InitiatorHandle"),
QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".InitiatorID")
};
for (unsigned i = 0; i < numNames; ++i) {
const QString &qualified = qualifiedNames[i];
if (!immutableProperties.contains(qualified)) {
needIntrospectMainProps = true;
break;
}
props.insert(names[i], immutableProperties.value(qualified));
}
// Save Requested and InitiatorHandle here, so even if the GetAll return doesn't have them but
// the given immutable props do (eg. due to the PendingChannel fallback guesses) we use them
requested = qdbus_cast<bool>(props[QLatin1String("Requested")]);
initiatorHandle = qdbus_cast<uint>(props[QLatin1String("InitiatorHandle")]);
if (props.contains(QLatin1String("InitiatorID"))) {
QString initiatorId = qdbus_cast<QString>(props[QLatin1String("InitiatorID")]);
connection->lowlevel()->injectContactId(initiatorHandle, initiatorId);
}
if (needIntrospectMainProps) {
debug() << "Calling Properties::GetAll(Channel)";
QDBusPendingCallWatcher *watcher =
new QDBusPendingCallWatcher(
properties->GetAll(QLatin1String(TELEPATHY_INTERFACE_CHANNEL)),
parent);
parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(gotMainProperties(QDBusPendingCallWatcher*)));
} else {
extractMainProps(props);
continueIntrospection();
}
}
void Channel::Private::introspectMainFallbackChannelType()
{
debug() << "Calling Channel::GetChannelType()";
QDBusPendingCallWatcher *watcher =
new QDBusPendingCallWatcher(baseInterface->GetChannelType(), parent);
parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(gotChannelType(QDBusPendingCallWatcher*)));
}
void Channel::Private::introspectMainFallbackHandle()
{
debug() << "Calling Channel::GetHandle()";
QDBusPendingCallWatcher *watcher =
new QDBusPendingCallWatcher(baseInterface->GetHandle(), parent);
parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(gotHandle(QDBusPendingCallWatcher*)));
}
void Channel::Private::introspectMainFallbackInterfaces()
{
debug() << "Calling Channel::GetInterfaces()";
QDBusPendingCallWatcher *watcher =
new QDBusPendingCallWatcher(baseInterface->GetInterfaces(), parent);
parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(gotInterfaces(QDBusPendingCallWatcher*)));
}
void Channel::Private::introspectGroup()
{
Q_ASSERT(properties != 0);
if (!group) {
group = parent->interface<Client::ChannelInterfaceGroupInterface>();
Q_ASSERT(group != 0);
}
debug() << "Introspecting Channel.Interface.Group for" << parent->objectPath();
parent->connect(group,
SIGNAL(GroupFlagsChanged(uint,uint)),
SLOT(onGroupFlagsChanged(uint,uint)));
parent->connect(group,
SIGNAL(MembersChanged(QString,Tp::UIntList,
Tp::UIntList,Tp::UIntList,
Tp::UIntList,uint,uint)),
SLOT(onMembersChanged(QString,Tp::UIntList,
Tp::UIntList,Tp::UIntList,
Tp::UIntList,uint,uint)));
parent->connect(group,
SIGNAL(MembersChangedDetailed(Tp::UIntList,
Tp::UIntList,Tp::UIntList,
Tp::UIntList,QVariantMap)),
SLOT(onMembersChangedDetailed(Tp::UIntList,
Tp::UIntList,Tp::UIntList,
Tp::UIntList,QVariantMap)));
parent->connect(group,
SIGNAL(HandleOwnersChanged(Tp::HandleOwnerMap,
Tp::UIntList)),
SLOT(onHandleOwnersChanged(Tp::HandleOwnerMap,
Tp::UIntList)));
parent->connect(group,
SIGNAL(SelfHandleChanged(uint)),
SLOT(onSelfHandleChanged(uint)));
debug() << "Calling Properties::GetAll(Channel.Interface.Group)";
QDBusPendingCallWatcher *watcher =
new QDBusPendingCallWatcher(
properties->GetAll(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP)),
parent);
parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(gotGroupProperties(QDBusPendingCallWatcher*)));
}
void Channel::Private::introspectGroupFallbackFlags()
{
Q_ASSERT(group != 0);
debug() << "Calling Channel.Interface.Group::GetGroupFlags()";
QDBusPendingCallWatcher *watcher =
new QDBusPendingCallWatcher(group->GetGroupFlags(), parent);
parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(gotGroupFlags(QDBusPendingCallWatcher*)));
}
void Channel::Private::introspectGroupFallbackMembers()
{
Q_ASSERT(group != 0);
debug() << "Calling Channel.Interface.Group::GetAllMembers()";
QDBusPendingCallWatcher *watcher =
new QDBusPendingCallWatcher(group->GetAllMembers(), parent);
parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(gotAllMembers(QDBusPendingCallWatcher*)));
}
void Channel::Private::introspectGroupFallbackLocalPendingWithInfo()
{
Q_ASSERT(group != 0);
debug() << "Calling Channel.Interface.Group::GetLocalPendingMembersWithInfo()";
QDBusPendingCallWatcher *watcher =
new QDBusPendingCallWatcher(group->GetLocalPendingMembersWithInfo(),
parent);
parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(gotLocalPendingMembersWithInfo(QDBusPendingCallWatcher*)));
}
void Channel::Private::introspectGroupFallbackSelfHandle()
{
Q_ASSERT(group != 0);
debug() << "Calling Channel.Interface.Group::GetSelfHandle()";
QDBusPendingCallWatcher *watcher =
new QDBusPendingCallWatcher(group->GetSelfHandle(), parent);
parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(gotSelfHandle(QDBusPendingCallWatcher*)));
}
void Channel::Private::introspectConference()
{
Q_ASSERT(properties != 0);
Q_ASSERT(conference == 0);
debug() << "Introspecting Conference interface";
conference = parent->interface<Client::ChannelInterfaceConferenceInterface>();
Q_ASSERT(conference != 0);
introspectingConference = true;
debug() << "Connecting to Channel.Interface.Conference.ChannelMerged/Removed";
parent->connect(conference,
SIGNAL(ChannelMerged(QDBusObjectPath,uint,QVariantMap)),
SLOT(onConferenceChannelMerged(QDBusObjectPath,uint,QVariantMap)));
parent->connect(conference,
SIGNAL(ChannelRemoved(QDBusObjectPath,QVariantMap)),
SLOT(onConferenceChannelRemoved(QDBusObjectPath,QVariantMap)));
debug() << "Calling Properties::GetAll(Channel.Interface.Conference)";
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
properties->GetAll(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_CONFERENCE)),
parent);
parent->connect(watcher,
SIGNAL(finished(QDBusPendingCallWatcher*)),
SLOT(gotConferenceProperties(QDBusPendingCallWatcher*)));
}
void Channel::Private::introspectConferenceInitialInviteeContacts(Private *self)
{
if (!self->conferenceInitialInviteeHandles.isEmpty()) {
ContactManagerPtr manager = self->connection->contactManager();
PendingContacts *pendingContacts = manager->contactsForHandles(
self->conferenceInitialInviteeHandles);
self->parent->connect(pendingContacts,
SIGNAL(finished(Tp::PendingOperation *)),
SLOT(gotConferenceInitialInviteeContacts(Tp::PendingOperation *)));
} else {
self->readinessHelper->setIntrospectCompleted(
FeatureConferenceInitialInviteeContacts, true);
}
}
void Channel::Private::continueIntrospection()
{
if (introspectQueue.isEmpty()) {
// this should always be true, but let's make sure
if (!parent->isReady(Channel::FeatureCore)) {
if (groupMembersChangedQueue.isEmpty() && !buildingContacts &&
!introspectingConference) {
debug() << "Both the IS and the MCD queue empty for the first time. Ready.";
setReady();
} else {
debug() << "Introspection done before contacts done - contacts sets ready";
}
}
} else {
(this->*(introspectQueue.dequeue()))();
}
}
void Channel::Private::extractMainProps(const QVariantMap &props)
{
const static QString keyChannelType(QLatin1String("ChannelType"));
const static QString keyInterfaces(QLatin1String("Interfaces"));
const static QString keyTargetHandle(QLatin1String("TargetHandle"));
const static QString keyTargetHandleType(QLatin1String("TargetHandleType"));
bool haveProps = props.size() >= 4
&& props.contains(keyChannelType)
&& !qdbus_cast<QString>(props[keyChannelType]).isEmpty()
&& props.contains(keyInterfaces)
&& props.contains(keyTargetHandle)
&& props.contains(keyTargetHandleType);
if (!haveProps) {
warning() << "Channel properties specified in 0.17.7 not found";
introspectQueue.enqueue(&Private::introspectMainFallbackChannelType);
introspectQueue.enqueue(&Private::introspectMainFallbackHandle);
introspectQueue.enqueue(&Private::introspectMainFallbackInterfaces);
} else {
parent->setInterfaces(qdbus_cast<QStringList>(props[keyInterfaces]));
readinessHelper->setInterfaces(parent->interfaces());
channelType = qdbus_cast<QString>(props[keyChannelType]);
targetHandle = qdbus_cast<uint>(props[keyTargetHandle]);
targetHandleType = qdbus_cast<uint>(props[keyTargetHandleType]);
const static QString keyTargetId(QLatin1String("TargetID"));
const static QString keyRequested(QLatin1String("Requested"));
const static QString keyInitiatorHandle(QLatin1String("InitiatorHandle"));
const static QString keyInitiatorId(QLatin1String("InitiatorID"));
if (props.contains(keyTargetId)) {
targetId = qdbus_cast<QString>(props[keyTargetId]);
if (targetHandleType == HandleTypeContact) {
connection->lowlevel()->injectContactId(targetHandle, targetId);
}
}
if (props.contains(keyRequested)) {
requested = qdbus_cast<uint>(props[keyRequested]);
}
if (props.contains(keyInitiatorHandle)) {
initiatorHandle = qdbus_cast<uint>(props[keyInitiatorHandle]);
}
if (props.contains(keyInitiatorId)) {
QString initiatorId = qdbus_cast<QString>(props[keyInitiatorId]);
connection->lowlevel()->injectContactId(initiatorHandle, initiatorId);
}
if (!fakeGroupInterfaceIfNeeded() &&
!parent->interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP)) &&
initiatorHandle) {
// No group interface, so nobody will build the poor fellow for us. Will do it ourselves
// out of pity for him.
// TODO: needs testing. I would imagine some of the elaborate updateContacts logic
// tripping over with just this.
buildContacts();
}
nowHaveInterfaces();
}
debug() << "Have initiator handle:" << (initiatorHandle ? "yes" : "no");
}
void Channel::Private::extract0176GroupProps(const QVariantMap &props)
{
const static QString keyGroupFlags(QLatin1String("GroupFlags"));
const static QString keyHandleOwners(QLatin1String("HandleOwners"));
const static QString keyLPMembers(QLatin1String("LocalPendingMembers"));
const static QString keyMembers(QLatin1String("Members"));
const static QString keyRPMembers(QLatin1String("RemotePendingMembers"));
const static QString keySelfHandle(QLatin1String("SelfHandle"));
bool haveProps = props.size() >= 6
&& (props.contains(keyGroupFlags)
&& (qdbus_cast<uint>(props[keyGroupFlags]) &
ChannelGroupFlagProperties))
&& props.contains(keyHandleOwners)
&& props.contains(keyLPMembers)
&& props.contains(keyMembers)
&& props.contains(keyRPMembers)
&& props.contains(keySelfHandle);
if (!haveProps) {
warning() << " Properties specified in 0.17.6 not found";
warning() << " Handle owners and self handle tracking disabled";
introspectQueue.enqueue(&Private::introspectGroupFallbackFlags);
introspectQueue.enqueue(&Private::introspectGroupFallbackMembers);
introspectQueue.enqueue(&Private::introspectGroupFallbackLocalPendingWithInfo);
introspectQueue.enqueue(&Private::introspectGroupFallbackSelfHandle);
} else {
debug() << " Found properties specified in 0.17.6";
groupAreHandleOwnersAvailable = true;
groupIsSelfHandleTracked = true;
setGroupFlags(qdbus_cast<uint>(props[keyGroupFlags]));
groupHandleOwners = qdbus_cast<HandleOwnerMap>(props[keyHandleOwners]);
groupInitialMembers = qdbus_cast<UIntList>(props[keyMembers]);
groupInitialLP = qdbus_cast<LocalPendingInfoList>(props[keyLPMembers]);
groupInitialRP = qdbus_cast<UIntList>(props[keyRPMembers]);
uint propSelfHandle = qdbus_cast<uint>(props[keySelfHandle]);
// Don't overwrite the self handle we got from the Connection with 0
if (propSelfHandle) {
groupSelfHandle = propSelfHandle;
}
nowHaveInitialMembers();
}
}
void Channel::Private::nowHaveInterfaces()
{
debug() << "Channel has" << parent->interfaces().size() <<
"optional interfaces:" << parent->interfaces();
QStringList interfaces = parent->interfaces();
if (interfaces.contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) {
introspectQueue.enqueue(&Private::introspectGroup);
}
if (interfaces.contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_CONFERENCE))) {
introspectQueue.enqueue(&Private::introspectConference);
}
}
void Channel::Private::nowHaveInitialMembers()
{
// Must be called with no contacts anywhere in the first place
Q_ASSERT(!parent->isReady(Channel::FeatureCore));
Q_ASSERT(!buildingContacts);
Q_ASSERT(pendingGroupMembers.isEmpty());
Q_ASSERT(pendingGroupLocalPendingMembers.isEmpty());
Q_ASSERT(pendingGroupRemotePendingMembers.isEmpty());
Q_ASSERT(groupContacts.isEmpty());
Q_ASSERT(groupLocalPendingContacts.isEmpty());
Q_ASSERT(groupRemotePendingContacts.isEmpty());
// Set groupHaveMembers so we start queueing fresh MCD signals
Q_ASSERT(!groupHaveMembers);
groupHaveMembers = true;
// Synthesize MCD for current + RP
groupMembersChangedQueue.enqueue(new GroupMembersChangedInfo(
groupInitialMembers, // Members
UIntList(), // Removed - obviously, none
UIntList(), // LP - will be handled separately, see below
groupInitialRP, // Remote pending
QVariantMap())); // No details for members + RP
// Synthesize one MCD for each initial LP member - they might have different details
foreach (const LocalPendingInfo &info, groupInitialLP) {
QVariantMap details;
if (info.actor != 0) {
details.insert(QLatin1String("actor"), info.actor);
}
if (info.reason != ChannelGroupChangeReasonNone) {
details.insert(QLatin1String("change-reason"), info.reason);
}
if (!info.message.isEmpty()) {
details.insert(QLatin1String("message"), info.message);
}
groupMembersChangedQueue.enqueue(new GroupMembersChangedInfo(UIntList(), UIntList(),
UIntList() << info.toBeAdded, UIntList(), details));
}
// At least our added MCD event to process
processMembersChanged();
}
bool Channel::Private::setGroupFlags(uint newGroupFlags)
{
if (groupFlags == newGroupFlags) {
return false;
}
groupFlags = newGroupFlags;
// this shouldn't happen but let's make sure
if (!parent->interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) {
return false;
}
if ((groupFlags & ChannelGroupFlagMembersChangedDetailed) &&
!usingMembersChangedDetailed) {
usingMembersChangedDetailed = true;
debug() << "Starting to exclusively listen to MembersChangedDetailed for" <<
parent->objectPath();
parent->disconnect(group,
SIGNAL(MembersChanged(QString,Tp::UIntList,
Tp::UIntList,Tp::UIntList,
Tp::UIntList,uint,uint)),
parent,
SLOT(onMembersChanged(QString,Tp::UIntList,
Tp::UIntList,Tp::UIntList,
Tp::UIntList,uint,uint)));
} else if (!(groupFlags & ChannelGroupFlagMembersChangedDetailed) &&
usingMembersChangedDetailed) {
warning() << " Channel service did spec-incompliant removal of MCD from GroupFlags";
usingMembersChangedDetailed = false;
parent->connect(group,
SIGNAL(MembersChanged(QString,Tp::UIntList,
Tp::UIntList,Tp::UIntList,
Tp::UIntList,uint,uint)),
parent,
SLOT(onMembersChanged(QString,Tp::UIntList,
Tp::UIntList,Tp::UIntList,
Tp::UIntList,uint,uint)));
}
return true;
}
void Channel::Private::buildContacts()
{
buildingContacts = true;
ContactManagerPtr manager = connection->contactManager();
UIntList toBuild = QSet<uint>(pendingGroupMembers +
pendingGroupLocalPendingMembers +
pendingGroupRemotePendingMembers).toList();
if (currentGroupMembersChangedInfo &&
currentGroupMembersChangedInfo->actor != 0) {
toBuild.append(currentGroupMembersChangedInfo->actor);
}
if (!initiatorContact && initiatorHandle) {
// No initiator contact, but Yes initiator handle - might do something about it with just
// that information
toBuild.append(initiatorHandle);
}
if (!targetContact && targetHandleType == HandleTypeContact && targetHandle != 0) {
toBuild.append(targetHandle);
}
// always try to retrieve selfContact and check if it changed on
// updateContacts or on gotContacts, in case we were not able to retrieve it
if (groupSelfHandle) {
toBuild.append(groupSelfHandle);
}
// group self handle changed to 0 <- strange but it may happen, and contacts
// were being built at the time, so check now
if (toBuild.isEmpty()) {
if (!groupSelfHandle && groupSelfContact) {
groupSelfContact.reset();
if (parent->isReady(Channel::FeatureCore)) {
emit parent->groupSelfContactChanged();
}
}
buildingContacts = false;
return;
}
PendingContacts *pendingContacts = manager->contactsForHandles(
toBuild);
parent->connect(pendingContacts,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(gotContacts(Tp::PendingOperation*)));
}
void Channel::Private::processMembersChanged()
{
Q_ASSERT(!buildingContacts);
if (groupMembersChangedQueue.isEmpty()) {
if (pendingRetrieveGroupSelfContact) {
pendingRetrieveGroupSelfContact = false;
// nothing queued but selfContact changed
buildContacts();
return;
}
if (!parent->isReady(Channel::FeatureCore)) {
if (introspectQueue.isEmpty()) {
debug() << "Both the MCD and the introspect queue empty for the first time. Ready!";
if (initiatorHandle && !initiatorContact) {
warning() << " Unable to create contact object for initiator with handle" <<
initiatorHandle;
}
if (targetHandleType == HandleTypeContact && targetHandle != 0 && !targetContact) {
warning() << " Unable to create contact object for target with handle" <<
targetHandle;
}
if (groupSelfHandle && !groupSelfContact) {
warning() << " Unable to create contact object for self handle" <<
groupSelfHandle;
}
continueIntrospection();
} else {
debug() << "Contact queue empty but introspect queue isn't. IS will set ready.";
}
}
return;
}
Q_ASSERT(pendingGroupMembers.isEmpty());
Q_ASSERT(pendingGroupLocalPendingMembers.isEmpty());
Q_ASSERT(pendingGroupRemotePendingMembers.isEmpty());
// always set this to false here, as buildContacts will always try to
// retrieve the selfContact and updateContacts will check if the built
// contact is the same as the current contact.
pendingRetrieveGroupSelfContact = false;
currentGroupMembersChangedInfo = groupMembersChangedQueue.dequeue();
foreach (uint handle, currentGroupMembersChangedInfo->added) {
if (!groupContacts.contains(handle)) {
pendingGroupMembers.insert(handle);
}
// the member was added to current members, check if it was in the
// local/pending lists and if true, schedule for removal from that list
if (groupLocalPendingContacts.contains(handle)) {
groupLocalPendingMembersToRemove.append(handle);
} else if(groupRemotePendingContacts.contains(handle)) {
groupRemotePendingMembersToRemove.append(handle);
}
}
foreach (uint handle, currentGroupMembersChangedInfo->localPending) {
if (!groupLocalPendingContacts.contains(handle)) {
pendingGroupLocalPendingMembers.insert(handle);
}
}
foreach (uint handle, currentGroupMembersChangedInfo->remotePending) {
if (!groupRemotePendingContacts.contains(handle)) {
pendingGroupRemotePendingMembers.insert(handle);
}
}
foreach (uint handle, currentGroupMembersChangedInfo->removed) {
groupMembersToRemove.append(handle);
}
// Always go through buildContacts - we might have a self/initiator/whatever handle to build
buildContacts();
}
void Channel::Private::updateContacts(const QList<ContactPtr> &contacts)
{
Contacts groupContactsAdded;
Contacts groupLocalPendingContactsAdded;
Contacts groupRemotePendingContactsAdded;
ContactPtr actorContact;
bool selfContactUpdated = false;
debug() << "Entering Chan::Priv::updateContacts() with" << contacts.size() << "contacts";
// FIXME: simplify. Some duplication of logic present.
foreach (ContactPtr contact, contacts) {
uint handle = contact->handle()[0];
if (pendingGroupMembers.contains(handle)) {
groupContactsAdded.insert(contact);
groupContacts[handle] = contact;
} else if (pendingGroupLocalPendingMembers.contains(handle)) {
groupLocalPendingContactsAdded.insert(contact);
groupLocalPendingContacts[handle] = contact;
// FIXME: should set the details and actor here too
groupLocalPendingContactsChangeInfo[handle] = GroupMemberChangeDetails();
} else if (pendingGroupRemotePendingMembers.contains(handle)) {
groupRemotePendingContactsAdded.insert(contact);
groupRemotePendingContacts[handle] = contact;
}
if (groupSelfHandle == handle && groupSelfContact != contact) {
groupSelfContact = contact;
selfContactUpdated = true;
}
if (!initiatorContact && initiatorHandle == handle) {
// No initiator contact stored, but there's a contact for the initiator handle
// We can use that!
initiatorContact = contact;
}
if (!targetContact && targetHandleType == HandleTypeContact && targetHandle == handle) {
targetContact = contact;
if (targetId.isEmpty()) {
// For some reason, TargetID was missing from the property map. We can initialize it
// here in that case.
targetId = targetContact->id();
}
}
if (currentGroupMembersChangedInfo &&
currentGroupMembersChangedInfo->actor == contact->handle()[0]) {
actorContact = contact;
}
}
if (!groupSelfHandle && groupSelfContact) {
groupSelfContact.reset();
selfContactUpdated = true;
}
pendingGroupMembers.clear();
pendingGroupLocalPendingMembers.clear();
pendingGroupRemotePendingMembers.clear();
// FIXME: This shouldn't be needed. Clearer would be to first scan for the actor being present
// in the contacts supplied.
foreach (ContactPtr contact, contacts) {
uint handle = contact->handle()[0];
if (groupLocalPendingContactsChangeInfo.contains(handle)) {
groupLocalPendingContactsChangeInfo[handle] =
GroupMemberChangeDetails(actorContact,
currentGroupMembersChangedInfo ? currentGroupMembersChangedInfo->details : QVariantMap());
}
}
Contacts groupContactsRemoved;
ContactPtr contactToRemove;
foreach (uint handle, groupMembersToRemove) {
if (groupContacts.contains(handle)) {
contactToRemove = groupContacts[handle];
groupContacts.remove(handle);
} else if (groupLocalPendingContacts.contains(handle)) {
contactToRemove = groupLocalPendingContacts[handle];
groupLocalPendingContacts.remove(handle);
} else if (groupRemotePendingContacts.contains(handle)) {
contactToRemove = groupRemotePendingContacts[handle];
groupRemotePendingContacts.remove(handle);
}
if (groupLocalPendingContactsChangeInfo.contains(handle)) {
groupLocalPendingContactsChangeInfo.remove(handle);
}
if (contactToRemove) {
groupContactsRemoved.insert(contactToRemove);
}
}
groupMembersToRemove.clear();
// FIXME: drop the LPToRemove and RPToRemove sets - they're redundant
foreach (uint handle, groupLocalPendingMembersToRemove) {
groupLocalPendingContacts.remove(handle);
}
groupLocalPendingMembersToRemove.clear();
foreach (uint handle, groupRemotePendingMembersToRemove) {
groupRemotePendingContacts.remove(handle);
}
groupRemotePendingMembersToRemove.clear();
if (!groupContactsAdded.isEmpty() ||
!groupLocalPendingContactsAdded.isEmpty() ||
!groupRemotePendingContactsAdded.isEmpty() ||
!groupContactsRemoved.isEmpty()) {
GroupMemberChangeDetails details(
actorContact,
currentGroupMembersChangedInfo ? currentGroupMembersChangedInfo->details : QVariantMap());
if (currentGroupMembersChangedInfo
&& currentGroupMembersChangedInfo->removed.contains(groupSelfHandle)) {
// Update groupSelfContactRemoveInfo with the proper actor in case
// the actor was not available by the time onMembersChangedDetailed
// was called.
groupSelfContactRemoveInfo = details;
}
if (parent->isReady(Channel::FeatureCore)) {
// Channel is ready, we can signal membership changes to the outside world without
// confusing anyone's fragile logic.
emit parent->groupMembersChanged(
groupContactsAdded,
groupLocalPendingContactsAdded,
groupRemotePendingContactsAdded,
groupContactsRemoved,
details);
}
}
delete currentGroupMembersChangedInfo;
currentGroupMembersChangedInfo = 0;
if (selfContactUpdated && parent->isReady(Channel::FeatureCore)) {
emit parent->groupSelfContactChanged();
}
processMembersChanged();
}
bool Channel::Private::fakeGroupInterfaceIfNeeded()
{
if (parent->interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) {
return false;
} else if (targetHandleType != HandleTypeContact) {
return false;
}
// fake group interface
if (connection->selfHandle() && targetHandle) {
// Fake groupSelfHandle and initial members, let the MCD handling take care of the rest
// TODO connect to Connection::selfHandleChanged
groupSelfHandle = connection->selfHandle();
groupInitialMembers = UIntList() << groupSelfHandle << targetHandle;
debug().nospace() << "Faking a group on channel with self handle=" <<
groupSelfHandle << " and other handle=" << targetHandle;
nowHaveInitialMembers();
} else {
warning() << "Connection::selfHandle is 0 or targetHandle is 0, "
"not faking a group on channel";
}
return true;
}
void Channel::Private::setReady()
{
Q_ASSERT(!parent->isReady(Channel::FeatureCore));
debug() << "Channel fully ready";
debug() << " Channel type" << channelType;
debug() << " Target handle" << targetHandle;
debug() << " Target handle type" << targetHandleType;
if (parent->interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) {
debug() << " Group: flags" << groupFlags;
if (groupAreHandleOwnersAvailable) {
debug() << " Group: Number of handle owner mappings" <<
groupHandleOwners.size();
}
else {
debug() << " Group: No handle owners property present";
}
debug() << " Group: Number of current members" <<
groupContacts.size();
debug() << " Group: Number of local pending members" <<
groupLocalPendingContacts.size();
debug() << " Group: Number of remote pending members" <<
groupRemotePendingContacts.size();
debug() << " Group: Self handle" << groupSelfHandle <<
"tracked:" << (groupIsSelfHandleTracked ? "yes" : "no");
}
readinessHelper->setIntrospectCompleted(FeatureCore, true);
}
QString Channel::Private::groupMemberChangeDetailsTelepathyError(
const GroupMemberChangeDetails &details)
{
QString error;
uint reason = details.reason();
switch (reason) {
case ChannelGroupChangeReasonOffline:
error = QLatin1String(TELEPATHY_ERROR_OFFLINE);
break;
case ChannelGroupChangeReasonKicked:
error = QLatin1String(TELEPATHY_ERROR_CHANNEL_KICKED);
break;
case ChannelGroupChangeReasonBanned:
error = QLatin1String(TELEPATHY_ERROR_CHANNEL_BANNED);
break;
case ChannelGroupChangeReasonBusy:
error = QLatin1String(TELEPATHY_ERROR_BUSY);
break;
case ChannelGroupChangeReasonNoAnswer:
error = QLatin1String(TELEPATHY_ERROR_NO_ANSWER);
break;
case ChannelGroupChangeReasonPermissionDenied:
error = QLatin1String(TELEPATHY_ERROR_PERMISSION_DENIED);
break;
case ChannelGroupChangeReasonInvalidContact:
error = QLatin1String(TELEPATHY_ERROR_DOES_NOT_EXIST);
break;
// The following change reason are being mapped to default
// case ChannelGroupChangeReasonNone:
// case ChannelGroupChangeReasonInvited: // shouldn't happen
// case ChannelGroupChangeReasonError:
// case ChannelGroupChangeReasonRenamed:
// case ChannelGroupChangeReasonSeparated: // shouldn't happen
default:
// let's use the actor handle and selfHandle here instead of the
// contacts, as the contacts may not be ready.
error = ((qdbus_cast<uint>(details.allDetails().value(QLatin1String("actor"))) == groupSelfHandle) ?
QLatin1String(TELEPATHY_ERROR_CANCELLED) :
QLatin1String(TELEPATHY_ERROR_TERMINATED));
break;
}
return error;
}
void Channel::Private::processConferenceChannelRemoved()
{
if (buildingConferenceChannelRemovedActorContact ||
conferenceChannelRemovedQueue.isEmpty()) {
return;
}
ConferenceChannelRemovedInfo *info = conferenceChannelRemovedQueue.first();
if (!conferenceChannels.contains(info->channelPath.path())) {
info = conferenceChannelRemovedQueue.dequeue();
delete info;
processConferenceChannelRemoved();
return;
}
buildingConferenceChannelRemovedActorContact = true;
if (info->details.contains(keyActor)) {
ContactManagerPtr manager = connection->contactManager();
PendingContacts *pendingContacts = manager->contactsForHandles(
UIntList() << qdbus_cast<uint>(info->details.value(keyActor)));
parent->connect(pendingContacts,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(gotConferenceChannelRemovedActorContact(Tp::PendingOperation*)));
} else {
parent->gotConferenceChannelRemovedActorContact(0);
}
}
struct TELEPATHY_QT4_NO_EXPORT Channel::GroupMemberChangeDetails::Private : public QSharedData
{
Private(const ContactPtr &actor, const QVariantMap &details)
: actor(actor), details(details) {}
ContactPtr actor;
QVariantMap details;
};
/**
* \class Channel::GroupMemberChangeDetails
* \ingroup clientchannel
* \headerfile TelepathyQt4/channel.h <TelepathyQt4/Channel>
*
* \brief The Channel::GroupMemberChangeDetails class represents the details of a group membership
* change.
*
* Extended information is not always available; this will be reflected by
* the return value of isValid().
*/
/**
* Constructs a new invalid GroupMemberChangeDetails instance.
*/
Channel::GroupMemberChangeDetails::GroupMemberChangeDetails()
{
}
/**
* Copy constructor.
*/
Channel::GroupMemberChangeDetails::GroupMemberChangeDetails(const GroupMemberChangeDetails &other)
: mPriv(other.mPriv)
{
}
/**
* Class destructor.
*/
Channel::GroupMemberChangeDetails::~GroupMemberChangeDetails()
{
}
/**
* Assigns all information (validity, details) from other to this.
*/
Channel::GroupMemberChangeDetails &Channel::GroupMemberChangeDetails::operator=(
const GroupMemberChangeDetails &other)
{
this->mPriv = other.mPriv;
return *this;
}
/**
* \fn bool Channel::GroupMemberChangeDetails::isValid() const
*
* Return whether the details are valid (have actually been received from the service).
*
* \return \c true if valid, \c false otherwise.
*/
/**
* Return whether the details specify an actor.
*
* If present, actor() will return the contact object representing the person who made the change.
*
* \return \c true if the actor is known, \c false otherwise.
* \sa actor()
*/
bool Channel::GroupMemberChangeDetails::hasActor() const
{
return isValid() && !mPriv->actor.isNull();
}
/**
* Return the contact object representing the person who made the change (actor), if known.
*
* \return A pointer to the Contact object, or a null ContactPtr if the actor is unknown.
* \sa hasActor()
*/
ContactPtr Channel::GroupMemberChangeDetails::actor() const
{
return isValid() ? mPriv->actor : ContactPtr();
}
/**
* \fn bool Channel::GroupMemberChangeDetails::hasReason() const
*
* Return whether the details specify the reason for the change.
*
* \return \c true if the reason is known, \c false otherwise.
* \sa reason()
*/
/**
* \fn ChannelGroupChangeReason Channel::GroupMemberChangeDetails::reason() const
*
* Return the reason for the change, if known.
*
* \return The change reason as #ChannelGroupChangeReason, or #ChannelGroupChangeReasonNone
* if the reason is unknown.
* \sa hasReason()
*/
/**
* \fn bool Channel::GroupMemberChangeDetails::hasMessage() const
*
* Return whether the details specify a human-readable message from the contact represented by
* actor() pertaining to the change.
*
* \return \c true if the message is known, \c false otherwise.
* \sa message()
*/
/**
* \fn QString Channel::GroupMemberChangeDetails::message() const
*
* Return a human-readable message from the contact represented by actor() pertaining to the change,
* if known.
*
* \return The message, or an empty string if the message is unknown.
* \sa hasMessage()
*/
/**
* \fn bool Channel::GroupMemberChangeDetails::hasError() const
*
* Return whether the details specify a D-Bus error describing the change.
*
* \return \c true if the error is known, \c false otherwise.
* \sa error()
*/
/**
* \fn QString Channel::GroupMemberChangeDetails::error() const
*
* Return the D-Bus error describing the change, if known.
*
* The D-Bus error provides more specific information than the reason() and should be used if
* applicable.
*
* \return A D-Bus error describing the change, or an empty string if the error is unknown.
* \sa hasError()
*/
/**
* \fn bool Channel::GroupMemberChangeDetails::hasDebugMessage() const
*
* Return whether the details specify a debug message.
*
* \return \c true if debug message is present, \c false otherwise.
* \sa debugMessage()
*/
/**
* \fn QString Channel::GroupMemberChangeDetails::debugMessage() const
*
* Return the debug message specified by the details, if any.
*
* The debug message is purely informational, offered for display for bug reporting purposes, and
* should not be attempted to be parsed.
*
* \return The debug message, or an empty string if there is none.
* \sa hasDebugMessage()
*/
/**
* Return a map containing all details of the group members change.
*
* This is useful for accessing domain-specific additional details.
*
* \return The details of the group members change as QVariantMap.
*/
QVariantMap Channel::GroupMemberChangeDetails::allDetails() const
{
return isValid() ? mPriv->details : QVariantMap();
}
Channel::GroupMemberChangeDetails::GroupMemberChangeDetails(const ContactPtr &actor,
const QVariantMap &details)
: mPriv(new Private(actor, details))
{
}
/**
* \class Channel
* \ingroup clientchannel
* \headerfile TelepathyQt4/channel.h <TelepathyQt4/Channel>
*
* \brief The Channel class represents a Telepathy channel.
*
* All communication in the Telepathy framework is carried out via channel
* objects. Specialized classes for some specific channel types such as
* StreamedMediaChannel, TextChannel, FileTransferChannel are provided.
*
* The remote object accessor functions on this object (channelType(), targetHandleType(),
* and so on) don't make any D-Bus calls; instead, they return/use
* values cached from a previous introspection run. The introspection process
* populates their values in the most efficient way possible based on what the
* service implements.
*
* To avoid unnecessary D-Bus traffic, some accessors only return valid
* information after specific features have been enabled.
* For instance, to retrieve the initial invitee contacts in a conference channel,
* it is necessary to enable the feature Channel::FeatureConferenceInitialInviteeContacts.
* See the individual methods descriptions for more details.
*
* Channel features can be enabled by constructing a ChannelFactory and enabling
* the desired features, and passing it to AccountManager, Account or ClientRegistrar
* when creating them as appropriate. However, if a particular
* feature is only ever used in a specific circumstance, such as an user opening
* some settings dialog separate from the general view of the application,
* features can be later enabled as needed by calling becomeReady() with the additional
* features, and waiting for the resulting PendingOperation to finish.
*
* Each channel is owned by a connection. If the Connection object becomes invalidated
* the Channel object will also get invalidated.
*
* \section chan_usage_sec Usage
*
* \subsection chan_create_sec Creating a channel object
*
* Channel objects can be created in various ways, but the preferred way is
* trough Account channel creation methods such as Account::ensureTextChat(),
* Account::createFileTransfer(), which uses the channel dispatcher.
*
* If you already know the object path, you can just call create().
* For example:
*
* \code
*
* ChannelPtr chan = Channel::create(connection, objectPath,
* immutableProperties);
*
* \endcode
*
* \subsection chan_ready_sec Making channel ready to use
*
* A Channel object needs to become ready before usage, meaning that the
* introspection process finished and the object accessors can be used.
*
* To make the object ready, use becomeReady() and wait for the
* PendingOperation::finished() signal to be emitted.
*
* \code
*
* class MyClass : public QObject
* {
* QOBJECT
*
* public:
* MyClass(QObject *parent = 0);
* ~MyClass() { }
*
* private Q_SLOTS:
* void onChannelReady(Tp::PendingOperation*);
*
* private:
* ChannelPtr chan;
* };
*
* MyClass::MyClass(const ConnectionPtr &connection,
* const QString &objectPath, const QVariantMap &immutableProperties)
* : QObject(parent)
* chan(Channel::create(connection, objectPath, immutableProperties))
* {
* connect(chan->becomeReady(),
* SIGNAL(finished(Tp::PendingOperation*)),
* SLOT(onChannelReady(Tp::PendingOperation*)));
* }
*
* void MyClass::onChannelReady(Tp::PendingOperation *op)
* {
* if (op->isError()) {
* qWarning() << "Channel cannot become ready:" <<
* op->errorName() << "-" << op->errorMessage();
* return;
* }
*
* // Channel is now ready
* }
*
* \endcode
*
* See \ref async_model, \ref shared_ptr
*/
/**
* Feature representing the core that needs to become ready to make the Channel
* object usable.
*
* Note that this feature must be enabled in order to use most Channel methods.
* See specific methods documentation for more details.
*
* When calling isReady(), becomeReady(), this feature is implicitly added
* to the requested features.
*/
const Feature Channel::FeatureCore = Feature(QLatin1String(Channel::staticMetaObject.className()), 0, true);
/**
* Feature used in order to access the conference initial invitee contacts info.
*
* \sa conferenceInitialInviteeContacts()
*/
const Feature Channel::FeatureConferenceInitialInviteeContacts = Feature(QLatin1String(Channel::staticMetaObject.className()), 1, true);
/**
* Create a new Channel object.
*
* \param connection Connection owning this channel, and specifying the
* service.
* \param objectPath The channel object path.
* \param immutableProperties The channel immutable properties.
* \return A ChannelPtr object pointing to the newly created Channel object.
*
* \todo \a immutableProperties should be used to populate the corresponding accessors (such as
* channelType()) already on construction, not only when making FeatureCore ready (fd.o #41654)
*/
ChannelPtr Channel::create(const ConnectionPtr &connection,
const QString &objectPath, const QVariantMap &immutableProperties)
{
return ChannelPtr(new Channel(connection, objectPath, immutableProperties,
Channel::FeatureCore));
}
/**
* Construct a new Channel object.
*
* \param connection Connection owning this channel, and specifying the
* service.
* \param objectPath The channel object path.
* \param immutableProperties The channel immutable properties.
* \param coreFeature The core feature of the channel type. The corresponding introspectable should
* depend on Channel::FeatureCore.
*/
Channel::Channel(const ConnectionPtr &connection,
const QString &objectPath,
const QVariantMap &immutableProperties,
const Feature &coreFeature)
: StatefulDBusProxy(connection->dbusConnection(), connection->busName(),
objectPath, coreFeature),
OptionalInterfaceFactory<Channel>(this),
mPriv(new Private(this, connection, immutableProperties))
{
}
/**
* Class destructor.
*/
Channel::~Channel()
{
delete mPriv;
}
/**
* Return the connection owning this channel.
*
* \return A pointer to the Connection object.
*/
ConnectionPtr Channel::connection() const
{
return mPriv->connection;
}
/**
* Return the immutable properties of the channel.
*
* If the channel is ready (isReady(Channel::FeatureCore) returns true), the following keys are
* guaranteed to be present:
* org.freedesktop.Telepathy.Channel.ChannelType,
* org.freedesktop.Telepathy.Channel.TargetHandleType,
* org.freedesktop.Telepathy.Channel.TargetHandle and
* org.freedesktop.Telepathy.Channel.Requested.
*
* The keys and values in this map are defined by the \telepathy_spec,
* or by third-party extensions to that specification.
* These are the properties that cannot change over the lifetime of the
* channel; they're announced in the result of the request, for efficiency.
*
* \return The immutable properties as QVariantMap.
*/
QVariantMap Channel::immutableProperties() const
{
if (isReady(Channel::FeatureCore)) {
QString key;
key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType");
if (!mPriv->immutableProperties.contains(key)) {
mPriv->immutableProperties.insert(key, mPriv->channelType);
}
key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".Interfaces");
if (!mPriv->immutableProperties.contains(key)) {
mPriv->immutableProperties.insert(key, interfaces());
}
key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType");
if (!mPriv->immutableProperties.contains(key)) {
mPriv->immutableProperties.insert(key, mPriv->targetHandleType);
}
key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle");
if (!mPriv->immutableProperties.contains(key)) {
mPriv->immutableProperties.insert(key, mPriv->targetHandle);
}
key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetID");
if (!mPriv->immutableProperties.contains(key)) {
mPriv->immutableProperties.insert(key, mPriv->targetId);
}
key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".Requested");
if (!mPriv->immutableProperties.contains(key)) {
mPriv->immutableProperties.insert(key, mPriv->requested);
}
key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".InitiatorHandle");
if (!mPriv->immutableProperties.contains(key)) {
mPriv->immutableProperties.insert(key, mPriv->initiatorHandle);
}
key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".InitiatorID");
if (!mPriv->immutableProperties.contains(key) && !mPriv->initiatorContact.isNull()) {
mPriv->immutableProperties.insert(key, mPriv->initiatorContact->id());
}
}
return mPriv->immutableProperties;
}
/**
* Return the D-Bus interface name for the type of this channel.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return The D-Bus interface name for the type of the channel.
*/
QString Channel::channelType() const
{
// Similarly, we don't want warnings triggered when using the type interface
// proxies internally.
if (!isReady(Channel::FeatureCore) && mPriv->channelType.isEmpty()) {
warning() << "Channel::channelType() before the channel type has "
"been received";
}
else if (!isValid()) {
warning() << "Channel::channelType() used with channel closed";
}
return mPriv->channelType;
}
/**
* Return the type of the handle returned by targetHandle() as specified in
* #HandleType.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return The target handle type as #HandleType.
* \sa targetHandle(), targetId()
*/
HandleType Channel::targetHandleType() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::targetHandleType() used channel not ready";
}
return (HandleType) mPriv->targetHandleType;
}
/**
* Return the handle of the remote party with which this channel
* communicates.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return An integer representing the target handle, which is of the type
* targetHandleType() indicates.
* \sa targetHandleType(), targetId()
*/
uint Channel::targetHandle() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::targetHandle() used channel not ready";
}
return mPriv->targetHandle;
}
/**
* Return the persistent unique ID of the remote party with which this channel communicates.
*
* If targetHandleType() is #HandleTypeContact, this will be the ID of the remote contact, and
* similarly the unique ID of the room when targetHandleType() is #HandleTypeRoom.
*
* This is not necessarily the best identifier to display to the user, though. In particular, for
* contacts, their alias should be displayed instead. It can be used for matching channels and UI
* elements for them across reconnects, though, at which point the old channels and contacts are
* invalidated.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return The target identifier.
* \sa targetHandle(), targetContact()
*/
QString Channel::targetId() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::targetId() used, but the channel is not ready";
}
return mPriv->targetId;
}
/**
* Return the contact with which this channel communicates for its lifetime, if applicable.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return A pointer to the Contact object, or a null ContactPtr if targetHandleType() is not
* #HandleTypeContact.
* \sa targetHandle(), targetId()
*/
ContactPtr Channel::targetContact() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::targetContact() used, but the channel is not ready";
} else if (targetHandleType() != HandleTypeContact) {
warning() << "Channel::targetContact() used with targetHandleType() != Contact";
}
return mPriv->targetContact;
}
/**
* Return whether this channel was created in response to a
* local request.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return \c true if the channel was created in response to a local request,
* \c false otherwise.
*/
bool Channel::isRequested() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::isRequested() used channel not ready";
}
return mPriv->requested;
}
/**
* Return the contact who initiated this channel.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return A pointer to the Contact object representing the contact who initiated the channel,
* or a null ContactPtr if it can't be retrieved.
*/
ContactPtr Channel::initiatorContact() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::initiatorContact() used channel not ready";
}
return mPriv->initiatorContact;
}
/**
* Start an asynchronous request that this channel be closed.
*
* The returned PendingOperation object will signal the success or failure
* of this request; under normal circumstances, it can be expected to
* succeed.
*
* \return A PendingOperation which will emit PendingOperation::finished
* when the call has finished.
* \sa requestLeave()
*/
PendingOperation *Channel::requestClose()
{
// Closing a channel does not make sense if it is already closed,
// just silently Return.
if (!isValid()) {
return new PendingSuccess(ChannelPtr(this));
}
return new PendingVoid(mPriv->baseInterface->Close(), ChannelPtr(this));
}
Channel::PendingLeave::PendingLeave(const ChannelPtr &chan, const QString &message,
ChannelGroupChangeReason reason)
: PendingOperation(chan)
{
Q_ASSERT(chan->mPriv->group != NULL);
QDBusPendingCall call =
chan->mPriv->group->RemoveMembersWithReason(
UIntList() << chan->mPriv->groupSelfHandle,
message,
reason);
connect(chan.data(),
SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
this,
SLOT(onChanInvalidated(Tp::DBusProxy*)));
connect(new PendingVoid(call, chan),
SIGNAL(finished(Tp::PendingOperation*)),
this,
SLOT(onRemoveFinished(Tp::PendingOperation*)));
}
void Channel::PendingLeave::onChanInvalidated(Tp::DBusProxy *proxy)
{
if (isFinished()) {
return;
}
debug() << "Finishing PendingLeave successfully as the channel was invalidated";
setFinished();
}
void Channel::PendingLeave::onRemoveFinished(Tp::PendingOperation *op)
{
if (isFinished()) {
return;
}
ChannelPtr chan = ChannelPtr::staticCast(_object());
if (op->isValid()) {
debug() << "We left the channel" << chan->objectPath();
ContactPtr c = chan->groupSelfContact();
if (chan->groupContacts().contains(c)
|| chan->groupLocalPendingContacts().contains(c)
|| chan->groupRemotePendingContacts().contains(c)) {
debug() << "Waiting for self remove to be picked up";
connect(chan.data(),
SIGNAL(groupMembersChanged(Tp::Contacts,Tp::Contacts,Tp::Contacts,Tp::Contacts,
Tp::Channel::GroupMemberChangeDetails)),
this,
SLOT(onMembersChanged(Tp::Contacts,Tp::Contacts,Tp::Contacts,Tp::Contacts)));
} else {
setFinished();
}
return;
}
debug() << "Leave RemoveMembersWithReason failed with " << op->errorName() << op->errorMessage()
<< "- falling back to Close";
// If the channel has been closed or otherwise invalidated already in this mainloop iteration,
// the requestClose() operation will early-succeed
connect(chan->requestClose(),
SIGNAL(finished(Tp::PendingOperation*)),
this,
SLOT(onCloseFinished(Tp::PendingOperation*)));
}
void Channel::PendingLeave::onMembersChanged(const Tp::Contacts &, const Tp::Contacts &,
const Tp::Contacts &, const Tp::Contacts &removed)
{
if (isFinished()) {
return;
}
ChannelPtr chan = ChannelPtr::staticCast(_object());
ContactPtr c = chan->groupSelfContact();
if (removed.contains(c)) {
debug() << "Leave event picked up for" << chan->objectPath();
setFinished();
}
}
void Channel::PendingLeave::onCloseFinished(Tp::PendingOperation *op)
{
if (isFinished()) {
return;
}
ChannelPtr chan = ChannelPtr::staticCast(_object());
if (op->isError()) {
warning() << "Closing the channel" << chan->objectPath()
<< "as a fallback for leaving it failed with"
<< op->errorName() << op->errorMessage() << "- so didn't leave";
setFinishedWithError(op->errorName(), op->errorMessage());
} else {
debug() << "We left (by closing) the channel" << chan->objectPath();
setFinished();
}
}
/**
* Start an asynchronous request to leave this channel as gracefully as possible.
*
* If leaving any more gracefully is not possible, this will revert to the same as requestClose().
* In particular, this will be the case for channels with no group interface
* (#TP_QT4_IFACE_CHANNEL_INTERFACE_GROUP not in the list returned by interfaces()).
*
* The returned PendingOperation object will signal the success or failure
* of this request; under normal circumstances, it can be expected to
* succeed.
*
* A message and a reason may be provided along with the request, which will be sent to the server
* if supported, which is indicated by #ChannelGroupFlagMessageDepart and/or
* #ChannelGroupFlagMessageReject.
*
* Attempting to leave again when we have already left, either by our request or forcibly, will be a
* no-op, with the returned PendingOperation immediately finishing successfully.
*
* \param message The message, which can be blank if desired.
* \param reason A reason for leaving.
* \return A PendingOperation which will emit PendingOperation::finished
* when the call has finished.
*/
PendingOperation *Channel::requestLeave(const QString &message, ChannelGroupChangeReason reason)
{
// Leaving a channel does not make sense if it is already closed,
// just silently Return.
if (!isValid()) {
return new PendingSuccess(ChannelPtr(this));
}
if (!isReady(Channel::FeatureCore)) {
return new PendingFailure(TP_QT4_ERROR_NOT_AVAILABLE,
QLatin1String("Channel::FeatureCore must be ready to leave a channel"),
ChannelPtr(this));
}
if (!interfaces().contains(TP_QT4_IFACE_CHANNEL_INTERFACE_GROUP)) {
return requestClose();
}
ContactPtr self = groupSelfContact();
if (!groupContacts().contains(self) && !groupLocalPendingContacts().contains(self)
&& !groupRemotePendingContacts().contains(self)) {
debug() << "Channel::requestLeave() called for " << objectPath() <<
"which we aren't a member of";
return new PendingSuccess(ChannelPtr(this));
}
return new PendingLeave(ChannelPtr(this), message, reason);
}
/**
* \name Group interface
*
* Cached access to state of the group interface on the associated remote
* object, if the interface is present.
*
* Some methods can be used when targetHandleType() == #HandleTypeContact, such
* as groupFlags(), groupCanAddContacts(), groupCanRemoveContacts(),
* groupSelfContact() and groupContacts().
*
* As the group interface state can change freely during the lifetime of the
* channel due to events like new contacts joining the group, the cached state
* is automatically kept in sync with the remote object's state by hooking
* to the change notification signals present in the D-Bus interface.
*
* As the cached value changes, change notification signals are emitted.
*
* Signals such as groupMembersChanged(), groupSelfContactChanged(), etc., are emitted to
* indicate that properties have changed.
*
* Check the individual signals' descriptions for details.
*/
//@{
/**
* Return a set of flags indicating the capabilities and behaviour of the
* group on this channel.
*
* Change notification is via the groupFlagsChanged() signal.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return The bitfield combination of flags as #ChannelGroupFlags.
* \sa groupFlagsChanged()
*/
ChannelGroupFlags Channel::groupFlags() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupFlags() used channel not ready";
}
return (ChannelGroupFlags) mPriv->groupFlags;
}
/**
* Return whether contacts can be added or invited to this channel.
*
* Change notification is via the groupCanAddContactsChanged() signal.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return \c true if contacts can be added or invited to the channel,
* \c false otherwise.
* \sa groupFlags(), groupAddContacts()
*/
bool Channel::groupCanAddContacts() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupCanAddContacts() used channel not ready";
}
return mPriv->groupFlags & ChannelGroupFlagCanAdd;
}
/**
* Return whether a message is expected when adding/inviting contacts, who
* are not already members, to this channel.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return \c true if a message is expected, \c false otherwise.
* \sa groupFlags(), groupAddContacts()
*/
bool Channel::groupCanAddContactsWithMessage() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupCanAddContactsWithMessage() used when channel not ready";
}
return mPriv->groupFlags & ChannelGroupFlagMessageAdd;
}
/**
* Return whether a message is expected when accepting contacts' requests to
* join this channel.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return \c true if a message is expected, \c false otherwise.
* \sa groupFlags(), groupAddContacts()
*/
bool Channel::groupCanAcceptContactsWithMessage() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupCanAcceptContactsWithMessage() used when channel not ready";
}
return mPriv->groupFlags & ChannelGroupFlagMessageAccept;
}
/**
* Add contacts to this channel.
*
* Contacts on the local pending list (those waiting for permission to join
* the channel) can always be added. If groupCanAcceptContactsWithMessage()
* returns \c true, an optional message is expected when doing this; if not,
* the message parameter is likely to be ignored (so the user should not be
* asked for a message, and the message parameter should be left empty).
*
* Other contacts can only be added if groupCanAddContacts() returns \c true.
* If groupCanAddContactsWithMessage() returns \c true, an optional message is
* expected when doing this, and if not, the message parameter is likely to be
* ignored.
*
* This method requires Channel::FeatureCore to be ready.
*
* \param contacts Contacts to be added.
* \param message A string message, which can be blank if desired.
* \return A PendingOperation which will emit PendingOperation::finished
* when the call has finished.
* \sa groupCanAddContacts(), groupCanAddContactsWithMessage(), groupCanAcceptContactsWithMessage()
*/
PendingOperation *Channel::groupAddContacts(const QList<ContactPtr> &contacts,
const QString &message)
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupAddContacts() used channel not ready";
return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
QLatin1String("Channel not ready"),
ChannelPtr(this));
} else if (contacts.isEmpty()) {
warning() << "Channel::groupAddContacts() used with empty contacts param";
return new PendingFailure(QLatin1String(TELEPATHY_ERROR_INVALID_ARGUMENT),
QLatin1String("contacts cannot be an empty list"),
ChannelPtr(this));
}
foreach (const ContactPtr &contact, contacts) {
if (!contact) {
warning() << "Channel::groupAddContacts() used but contacts param contains "
"invalid contact";
return new PendingFailure(QLatin1String(TELEPATHY_ERROR_INVALID_ARGUMENT),
QLatin1String("Unable to add invalid contacts"),
ChannelPtr(this));
}
}
if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) {
warning() << "Channel::groupAddContacts() used with no group interface";
return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED),
QLatin1String("Channel does not support group interface"),
ChannelPtr(this));
}
UIntList handles;
foreach (const ContactPtr &contact, contacts) {
handles << contact->handle()[0];
}
return new PendingVoid(mPriv->group->AddMembers(handles, message), ChannelPtr(this));
}
/**
* Return whether contacts in groupRemotePendingContacts() can be removed from
* this channel (i.e. whether an invitation can be rescinded).
*
* Change notification is via the groupCanRescindContactsChanged() signal.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return \c true if contacts can be removed, \c false otherwise.
* \sa groupFlags(), groupRemoveContacts()
*/
bool Channel::groupCanRescindContacts() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupCanRescindContacts() used channel not ready";
}
return mPriv->groupFlags & ChannelGroupFlagCanRescind;
}
/**
* Return whether a message is expected when removing contacts who are in
* groupRemotePendingContacts() from this channel (i.e. rescinding an
* invitation).
*
* This method requires Channel::FeatureCore to be ready.
*
* \return \c true if a message is expected, \c false otherwise.
* \sa groupFlags(), groupRemoveContacts()
*/
bool Channel::groupCanRescindContactsWithMessage() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupCanRescindContactsWithMessage() used when channel not ready";
}
return mPriv->groupFlags & ChannelGroupFlagMessageRescind;
}
/**
* Return if contacts in groupContacts() can be removed from this channel.
*
* Note that contacts in local pending lists, and the groupSelfContact(), can
* always be removed from the channel.
*
* Change notification is via the groupCanRemoveContactsChanged() signal.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return \c true if contacts can be removed, \c false otherwise.
* \sa groupFlags(), groupRemoveContacts()
*/
bool Channel::groupCanRemoveContacts() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupCanRemoveContacts() used channel not ready";
}
return mPriv->groupFlags & ChannelGroupFlagCanRemove;
}
/**
* Return whether a message is expected when removing contacts who are in
* groupContacts() from this channel.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return \c true if a message is expected, \c false otherwise.
* \sa groupFlags(), groupRemoveContacts()
*/
bool Channel::groupCanRemoveContactsWithMessage() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupCanRemoveContactsWithMessage() used when channel not ready";
}
return mPriv->groupFlags & ChannelGroupFlagMessageRemove;
}
/**
* Return whether a message is expected when removing contacts who are in
* groupLocalPendingContacts() from this channel (i.e. rejecting a request to
* join).
*
* This method requires Channel::FeatureCore to be ready.
*
* \return \c true if a message is expected, \c false otherwise.
* \sa groupFlags(), groupRemoveContacts()
*/
bool Channel::groupCanRejectContactsWithMessage() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupCanRejectContactsWithMessage() used when channel not ready";
}
return mPriv->groupFlags & ChannelGroupFlagMessageReject;
}
/**
* Return whether a message is expected when removing the groupSelfContact()
* from this channel (i.e. departing from the channel).
*
* \return \c true if a message is expected, \c false otherwise.
* \sa groupFlags(), groupRemoveContacts()
*/
bool Channel::groupCanDepartWithMessage() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupCanDepartWithMessage() used when channel not ready";
}
return mPriv->groupFlags & ChannelGroupFlagMessageDepart;
}
/**
* Remove contacts from this channel.
*
* Contacts on the local pending list (those waiting for permission to join
* the channel) can always be removed. If groupCanRejectContactsWithMessage()
* returns \c true, an optional message is expected when doing this; if not,
* the message parameter is likely to be ignored (so the user should not be
* asked for a message, and the message parameter should be left empty).
*
* The groupSelfContact() can also always be removed, as a way to leave the
* group with an optional departure message and/or departure reason indication.
* If groupCanDepartWithMessage() returns \c true, an optional message is
* expected when doing this, and if not, the message parameter is likely to
* be ignored.
*
* Contacts in the group can only be removed (e.g. kicked) if
* groupCanRemoveContacts() returns \c true. If
* groupCanRemoveContactsWithMessage() returns \c true, an optional message is
* expected when doing this, and if not, the message parameter is likely to be
* ignored.
*
* Contacts in the remote pending list (those who have been invited to the
* channel) can only be removed (have their invitations rescinded) if
* groupCanRescindContacts() returns \c true. If
* groupCanRescindContactsWithMessage() returns \c true, an optional message is
* expected when doing this, and if not, the message parameter is likely to be
* ignored.
*
* This method requires Channel::FeatureCore to be ready.
*
* \param contacts Contacts to be removed.
* \param message A string message, which can be blank if desired.
* \param reason Reason of the change, as specified in
* #ChannelGroupChangeReason
* \return A PendingOperation which will emit PendingOperation::finished
* when the call has finished.
* \sa groupCanRemoveContacts(), groupCanRemoveContactsWithMessage(),
* groupCanRejectContactsWithMessage(), groupCanRescindContacts(),
* groupCanRescindContacts(), groupCanRescindContactsWithMessage(),
* groupCanDepartWithMessage()
*/
PendingOperation *Channel::groupRemoveContacts(const QList<ContactPtr> &contacts,
const QString &message, ChannelGroupChangeReason reason)
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupRemoveContacts() used channel not ready";
return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE),
QLatin1String("Channel not ready"),
ChannelPtr(this));
}
if (contacts.isEmpty()) {
warning() << "Channel::groupRemoveContacts() used with empty contacts param";
return new PendingFailure(QLatin1String(TELEPATHY_ERROR_INVALID_ARGUMENT),
QLatin1String("contacts param cannot be an empty list"),
ChannelPtr(this));
}
foreach (const ContactPtr &contact, contacts) {
if (!contact) {
warning() << "Channel::groupRemoveContacts() used but contacts param contains "
"invalid contact:";
return new PendingFailure(QLatin1String(TELEPATHY_ERROR_INVALID_ARGUMENT),
QLatin1String("Unable to remove invalid contacts"),
ChannelPtr(this));
}
}
if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) {
warning() << "Channel::groupRemoveContacts() used with no group interface";
return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED),
QLatin1String("Channel does not support group interface"),
ChannelPtr(this));
}
UIntList handles;
foreach (const ContactPtr &contact, contacts) {
handles << contact->handle()[0];
}
return new PendingVoid(
mPriv->group->RemoveMembersWithReason(handles, message, reason),
ChannelPtr(this));
}
/**
* Return the current contacts of the group.
*
* Change notification is via the groupMembersChanged() signal.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return A set of pointers to the Contact objects.
* \sa groupLocalPendingContacts(), groupRemotePendingContacts()
*/
Contacts Channel::groupContacts() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupMembers() used channel not ready";
}
return mPriv->groupContacts.values().toSet();
}
/**
* Return the contacts currently waiting for local approval to join the
* group.
*
* Change notification is via the groupMembersChanged() signal.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return A set of pointers to the Contact objects.
* \sa groupContacts(), groupRemotePendingContacts()
*/
Contacts Channel::groupLocalPendingContacts() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupLocalPendingContacts() used channel not ready";
} else if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) {
warning() << "Channel::groupLocalPendingContacts() used with no group interface";
}
return mPriv->groupLocalPendingContacts.values().toSet();
}
/**
* Return the contacts currently waiting for remote approval to join the
* group.
*
* Change notification is via the groupMembersChanged() signal.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return A set of pointers to the Contact objects.
* \sa groupContacts(), groupLocalPendingContacts()
*/
Contacts Channel::groupRemotePendingContacts() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupRemotePendingContacts() used channel not ready";
} else if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) {
warning() << "Channel::groupRemotePendingContacts() used with no "
"group interface";
}
return mPriv->groupRemotePendingContacts.values().toSet();
}
/**
* Return information of a local pending contact change. If
* no information is available, an object for which
* GroupMemberChangeDetails::isValid() returns <code>false</code> is returned.
*
* This method requires Channel::FeatureCore to be ready.
*
* \param contact A Contact object that is on the local pending contacts list.
* \return The change info as a GroupMemberChangeDetails object.
*/
Channel::GroupMemberChangeDetails Channel::groupLocalPendingContactChangeInfo(
const ContactPtr &contact) const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupLocalPendingContactChangeInfo() used channel not ready";
} else if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) {
warning() << "Channel::groupLocalPendingContactChangeInfo() used with no group interface";
} else if (!contact) {
warning() << "Channel::groupLocalPendingContactChangeInfo() used with null contact param";
return GroupMemberChangeDetails();
}
uint handle = contact->handle()[0];
return mPriv->groupLocalPendingContactsChangeInfo.value(handle);
}
/**
* Return information on the removal of the local user from the group. If
* the user hasn't been removed from the group, an object for which
* GroupMemberChangeDetails::isValid() returns <code>false</code> is returned.
*
* This method should be called only after you've left the channel.
* This is useful for getting the remove information after missing the
* corresponding groupMembersChanged() signal, as the local user being
* removed usually causes the channel to be closed.
*
* The returned information is not guaranteed to be correct if
* groupIsSelfHandleTracked() returns false and a self handle change has
* occurred on the remote object.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return The remove info as a GroupMemberChangeDetails object.
*/
Channel::GroupMemberChangeDetails Channel::groupSelfContactRemoveInfo() const
{
// Oftentimes, the channel will be closed as a result from being left - so checking a channel's
// self remove info when it has been closed and hence invalidated is valid
if (isValid() && !isReady(Channel::FeatureCore)) {
warning() << "Channel::groupSelfContactRemoveInfo() used before Channel::FeatureCore is ready";
} else if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) {
warning() << "Channel::groupSelfContactRemoveInfo() used with "
"no group interface";
}
return mPriv->groupSelfContactRemoveInfo;
}
/**
* Return whether globally valid handles can be looked up using the
* channel-specific handle on this channel using this object.
*
* Handle owner lookup is only available if:
* <ul>
* <li>The object is ready
* <li>The list returned by interfaces() contains #TP_QT4_IFACE_CHANNEL_INTERFACE_GROUP</li>
* <li>The set of flags returned by groupFlags() contains
* #GroupFlagProperties and #GroupFlagChannelSpecificHandles</li>
* </ul>
*
* If this function returns \c false, the return value of
* groupHandleOwners() is undefined and groupHandleOwnersChanged() will
* never be emitted.
*
* The value returned by this function will stay fixed for the entire time
* the object is ready, so no change notification is provided.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return \c true if handle owner lookup functionality is available, \c false otherwise.
*/
bool Channel::groupAreHandleOwnersAvailable() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupAreHandleOwnersAvailable() used channel not ready";
} else if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) {
warning() << "Channel::groupAreHandleOwnersAvailable() used with "
"no group interface";
}
return mPriv->groupAreHandleOwnersAvailable;
}
/**
* Return a mapping of handles specific to this channel to globally valid
* handles.
*
* The mapping includes at least all of the channel-specific handles in this
* channel's members, local-pending and remote-pending sets as keys. Any
* handle not in the keys of this mapping is not channel-specific in this
* channel. Handles which are channel-specific, but for which the owner is
* unknown, appear in this mapping with 0 as owner.
*
* Change notification is via the groupHandleOwnersChanged() signal.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return A mapping from group-specific handles to globally valid handles.
*/
HandleOwnerMap Channel::groupHandleOwners() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupHandleOwners() used channel not ready";
} else if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) {
warning() << "Channel::groupAreHandleOwnersAvailable() used with no "
"group interface";
}
else if (!groupAreHandleOwnersAvailable()) {
warning() << "Channel::groupAreHandleOwnersAvailable() used, but handle "
"owners not available";
}
return mPriv->groupHandleOwners;
}
/**
* Return whether the value returned by groupSelfContact() is guaranteed to
* accurately represent the local user even after nickname changes, etc.
*
* This should always be \c true for new services implementing the group interface.
*
* Older services not providing group properties don't necessarily
* emit the SelfHandleChanged signal either, so self contact changes can't be
* reliably tracked.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return \c true if changes to the self contact are tracked, \c false otherwise.
*/
bool Channel::groupIsSelfContactTracked() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupIsSelfHandleTracked() used channel not ready";
} else if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) {
warning() << "Channel::groupIsSelfHandleTracked() used with "
"no group interface";
}
return mPriv->groupIsSelfHandleTracked;
}
/**
* Return a Contact object representing the user in the group if at all possible, otherwise a
* Contact object representing the user globally.
*
* Change notification is via the groupSelfContactChanged() signal.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return A pointer to the Contact object.
*/
ContactPtr Channel::groupSelfContact() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupSelfContact() used channel not ready";
}
return mPriv->groupSelfContact;
}
/**
* Return whether the local user is in the "local pending" state. This
* indicates that the local user needs to take action to accept an invitation,
* an incoming call, etc.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return \c true if local user is in the channel's local-pending set, \c false otherwise.
*/
bool Channel::groupSelfHandleIsLocalPending() const
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupSelfHandleIsLocalPending() used when "
"channel not ready";
return false;
}
return mPriv->groupLocalPendingContacts.contains(mPriv->groupSelfHandle);
}
/**
* Attempt to add the local user to this channel. In some channel types,
* such as Text and StreamedMedia, this is used to accept an invitation or an
* incoming call.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return A PendingOperation which will emit PendingOperation::finished
* when the call has finished.
*/
PendingOperation *Channel::groupAddSelfHandle()
{
if (!isReady(Channel::FeatureCore)) {
warning() << "Channel::groupAddSelfHandle() used when channel not "
"ready";
return new PendingFailure(QLatin1String(TELEPATHY_ERROR_INVALID_ARGUMENT),
QLatin1String("Channel object not ready"),
ChannelPtr(this));
}
UIntList handles;
if (mPriv->groupSelfHandle == 0) {
handles << mPriv->connection->selfHandle();
} else {
handles << mPriv->groupSelfHandle;
}
return new PendingVoid(
mPriv->group->AddMembers(handles, QLatin1String("")),
ChannelPtr(this));
}
//@}
/**
* Return whether this channel implements the conference interface
* (#TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE is in the list returned by interfaces()).
*
* This method requires Channel::FeatureCore to be ready.
*
* \return \c true if the conference interface is supported, \c false otherwise.
*/
bool Channel::isConference() const
{
return hasInterface(TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE);
}
/**
* Return a list of contacts invited to this conference when it was created.
*
* This method requires Channel::FeatureConferenceInitialInviteeContacts to be ready.
*
* \return A set of pointers to the Contact objects.
*/
Contacts Channel::conferenceInitialInviteeContacts() const
{
return mPriv->conferenceInitialInviteeContacts;
}
/**
* Return the individual channels that are part of this conference.
*
* Change notification is via the conferenceChannelMerged() and
* conferenceChannelRemoved() signals.
*
* Note that the returned channels are not guaranteed to be ready. Calling
* Channel::becomeReady() may be needed.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return A list of pointers to Channel objects containing all channels in the conference.
* \sa conferenceInitialChannels(), conferenceOriginalChannels()
*/
QList<ChannelPtr> Channel::conferenceChannels() const
{
return mPriv->conferenceChannels.values();
}
/**
* Return the initial value of conferenceChannels().
*
* Note that the returned channels are not guaranteed to be ready. Calling
* Channel::becomeReady() may be needed.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return A list of pointers to Channel objects containing all channels that were initially
* part of the conference.
* \sa conferenceChannels(), conferenceOriginalChannels()
*/
QList<ChannelPtr> Channel::conferenceInitialChannels() const
{
return mPriv->conferenceInitialChannels.values();
}
/**
* Return a map between channel specific handles and the corresponding channels of this conference.
*
* This method is only relevant on GSM conference calls where it is possible to have the same phone
* number in a conference twice; for instance, it could be the number of a corporate switchboard.
* This is represented using channel-specific handles; whether or not a channel uses
* channel-specific handles is reported in groupFlags(). The groupHandleOwners() specifies the
* mapping from opaque channel-specific handles to actual numbers; this property specifies the
* original 1-1 channel corresponding to each channel-specific handle in the conference.
*
* In protocols where this situation cannot arise, such as XMPP, this method will return an empty
* hash.
*
* Example, consider this situation:
* 1. Place a call (with path /call/to/simon) to the contact +441234567890 (which is assigned the
* handle h, say), and ask to be put through to Simon McVittie;
* 2. Put that call on hold;
* 3. Place another call (with path /call/to/jonny) to +441234567890, and ask to be put through to
* Jonny Lamb;
* 4. Request a new conference channel with initial channels: ['/call/to/simon', '/call/to/jonny'].
*
* The new channel will have the following properties, for some handles s and j:
*
* {
* groupFlags(): ChannelGroupFlagChannelSpecificHandles | (other flags),
* groupMembers(): [self handle, s, j],
* groupHandleOwners(): { s: h, j: h },
* conferenceInitialChannels(): ['/call/to/simon', '/call/to/jonny'],
* conferenceChannels(): ['/call/to/simon', '/call/to/jonny'],
* conferenceOriginalChannels(): { s: '/call/to/simon', j: '/call/to/jonny' },
* # ...
* }
*
* Note that the returned channels are not guaranteed to be ready. Calling
* Channel::becomeReady() may be needed.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return A map of channel specific handles to pointers to Channel objects.
* \sa conferenceChannels(), conferenceInitialChannels()
*/
QHash<uint, ChannelPtr> Channel::conferenceOriginalChannels() const
{
return mPriv->conferenceOriginalChannels;
}
/**
* Return whether this channel supports conference merging using conferenceMergeChannel().
*
* This method requires Channel::FeatureCore to be ready.
*
* \return \c true if the interface is supported, \c false otherwise.
* \sa conferenceMergeChannel()
*/
bool Channel::supportsConferenceMerging() const
{
return interfaces().contains(QLatin1String(
TP_FUTURE_INTERFACE_CHANNEL_INTERFACE_MERGEABLE_CONFERENCE));
}
/**
* Request that the given channel be incorporated into this channel.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return A PendingOperation which will emit PendingOperation::finished
* when the call has finished.
* \sa supportsConferenceMerging()
*/
PendingOperation *Channel::conferenceMergeChannel(const ChannelPtr &channel)
{
if (!supportsConferenceMerging()) {
return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED),
QLatin1String("Channel does not support MergeableConference interface"),
ChannelPtr(this));
}
return new PendingVoid(mPriv->mergeableConferenceInterface()->Merge(
QDBusObjectPath(channel->objectPath())),
ChannelPtr(this));
}
/**
* Return whether this channel supports splitting using conferenceSplitChannel().
*
* This method requires Channel::FeatureCore to be ready.
*
* \return \c true if the interface is supported, \c false otherwise.
* \sa conferenceSplitChannel()
*/
bool Channel::supportsConferenceSplitting() const
{
return interfaces().contains(QLatin1String(
TP_FUTURE_INTERFACE_CHANNEL_INTERFACE_SPLITTABLE));
}
/**
* Request that this channel is removed from any conference of which it is
* a part.
*
* This method requires Channel::FeatureCore to be ready.
*
* \return A PendingOperation which will emit PendingOperation::finished
* when the call has finished.
* \sa supportsConferenceSplitting()
*/
PendingOperation *Channel::conferenceSplitChannel()
{
if (!supportsConferenceSplitting()) {
return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED),
QLatin1String("Channel does not support Splittable interface"),
ChannelPtr(this));
}
return new PendingVoid(mPriv->splittableInterface()->Split(), ChannelPtr(this));
}
/**
* Return the Client::ChannelInterface interface proxy object for this channel.
* This method is protected since the convenience methods provided by this
* class should generally be used instead of calling D-Bus methods
* directly.
*
* \return A pointer to the existing Client::ChannelInterface object for this
* Channel object.
*/
Client::ChannelInterface *Channel::baseInterface() const
{
return mPriv->baseInterface;
}
void Channel::gotMainProperties(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QVariantMap> reply = *watcher;
QVariantMap props;
if (!reply.isError()) {
debug() << "Got reply to Properties::GetAll(Channel)";
props = reply.value();
} else {
warning().nospace() << "Properties::GetAll(Channel) failed with " <<
reply.error().name() << ": " << reply.error().message();
}
mPriv->extractMainProps(props);
mPriv->continueIntrospection();
}
void Channel::gotChannelType(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QString> reply = *watcher;
if (reply.isError()) {
warning().nospace() << "Channel::GetChannelType() failed with " <<
reply.error().name() << ": " << reply.error().message() <<
", Channel officially dead";
invalidate(reply.error());
return;
}
debug() << "Got reply to fallback Channel::GetChannelType()";
mPriv->channelType = reply.value();
mPriv->continueIntrospection();
}
void Channel::gotHandle(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<uint, uint> reply = *watcher;
if (reply.isError()) {
warning().nospace() << "Channel::GetHandle() failed with " <<
reply.error().name() << ": " << reply.error().message() <<
", Channel officially dead";
invalidate(reply.error());
return;
}
debug() << "Got reply to fallback Channel::GetHandle()";
mPriv->targetHandleType = reply.argumentAt<0>();
mPriv->targetHandle = reply.argumentAt<1>();
mPriv->continueIntrospection();
}
void Channel::gotInterfaces(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QStringList> reply = *watcher;
if (reply.isError()) {
warning().nospace() << "Channel::GetInterfaces() failed with " <<
reply.error().name() << ": " << reply.error().message() <<
", Channel officially dead";
invalidate(reply.error());
return;
}
debug() << "Got reply to fallback Channel::GetInterfaces()";
setInterfaces(reply.value());
mPriv->readinessHelper->setInterfaces(interfaces());
mPriv->nowHaveInterfaces();
mPriv->fakeGroupInterfaceIfNeeded();
mPriv->continueIntrospection();
}
void Channel::onClosed()
{
debug() << "Got Channel::Closed";
QString error;
QString message;
if (mPriv->groupSelfContactRemoveInfo.isValid() &&
mPriv->groupSelfContactRemoveInfo.hasReason()) {
error = mPriv->groupMemberChangeDetailsTelepathyError(
mPriv->groupSelfContactRemoveInfo);
message = mPriv->groupSelfContactRemoveInfo.message();
} else {
error = TP_QT4_ERROR_CANCELLED;
message = QLatin1String("channel closed");
}
invalidate(error, message);
}
void Channel::onConnectionReady(PendingOperation *op)
{
if (op->isError()) {
invalidate(op->errorName(), op->errorMessage());
return;
}
// FIXME: should connect to selfHandleChanged and act accordingly, but that is a PITA for
// keeping the Contacts built and even if we don't do it, the new code is better than the
// old one anyway because earlier on we just wouldn't have had a self contact.
//
// besides, the only thing which breaks without connecting in the world likely is if you're
// using idle and decide to change your nick, which I don't think we necessarily even have API
// to do from tp-qt4 anyway (or did I make idle change the nick when setting your alias? can't
// remember)
//
// Simply put, I just don't care ATM.
// Will be overwritten by the group self handle, if we can discover any.
Q_ASSERT(!mPriv->groupSelfHandle);
mPriv->groupSelfHandle = mPriv->connection->selfHandle();
mPriv->introspectMainProperties();
}
void Channel::onConnectionInvalidated()
{
debug() << "Owning connection died leaving an orphan Channel, "
"changing to closed";
invalidate(QLatin1String(TP_QT4_ERROR_ORPHANED),
QLatin1String("Connection given as the owner of this channel was invalidated"));
}
void Channel::gotGroupProperties(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QVariantMap> reply = *watcher;
QVariantMap props;
if (!reply.isError()) {
debug() << "Got reply to Properties::GetAll(Channel.Interface.Group)";
props = reply.value();
}
else {
warning().nospace() << "Properties::GetAll(Channel.Interface.Group) "
"failed with " << reply.error().name() << ": " <<
reply.error().message();
}
mPriv->extract0176GroupProps(props);
// Add extraction (and possible fallbacks) in similar functions, called from here
mPriv->continueIntrospection();
}
void Channel::gotGroupFlags(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<uint> reply = *watcher;
if (reply.isError()) {
warning().nospace() << "Channel.Interface.Group::GetGroupFlags() failed with " <<
reply.error().name() << ": " << reply.error().message();
}
else {
debug() << "Got reply to fallback Channel.Interface.Group::GetGroupFlags()";
mPriv->setGroupFlags(reply.value());
if (mPriv->groupFlags & ChannelGroupFlagProperties) {
warning() << " Reply included ChannelGroupFlagProperties, even "
"though properties specified in 0.17.7 didn't work! - unsetting";
mPriv->groupFlags &= ~ChannelGroupFlagProperties;
}
}
mPriv->continueIntrospection();
}
void Channel::gotAllMembers(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<UIntList, UIntList, UIntList> reply = *watcher;
if (reply.isError()) {
warning().nospace() << "Channel.Interface.Group::GetAllMembers() failed with " <<
reply.error().name() << ": " << reply.error().message();
} else {
debug() << "Got reply to fallback Channel.Interface.Group::GetAllMembers()";
mPriv->groupInitialMembers = reply.argumentAt<0>();
mPriv->groupInitialRP = reply.argumentAt<2>();
foreach (uint handle, reply.argumentAt<1>()) {
LocalPendingInfo info = {handle, 0, ChannelGroupChangeReasonNone,
QLatin1String("")};
mPriv->groupInitialLP.push_back(info);
}
}
mPriv->continueIntrospection();
}
void Channel::gotLocalPendingMembersWithInfo(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<LocalPendingInfoList> reply = *watcher;
if (reply.isError()) {
warning().nospace() << "Channel.Interface.Group::GetLocalPendingMembersWithInfo() "
"failed with " << reply.error().name() << ": " << reply.error().message();
warning() << " Falling back to what GetAllMembers returned with no extended info";
}
else {
debug() << "Got reply to fallback "
"Channel.Interface.Group::GetLocalPendingMembersWithInfo()";
// Overrides the previous vague list provided by gotAllMembers
mPriv->groupInitialLP = reply.value();
}
mPriv->continueIntrospection();
}
void Channel::gotSelfHandle(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<uint> reply = *watcher;
if (reply.isError()) {
warning().nospace() << "Channel.Interface.Group::GetSelfHandle() failed with " <<
reply.error().name() << ": " << reply.error().message();
} else {
debug() << "Got reply to fallback Channel.Interface.Group::GetSelfHandle()";
// Don't overwrite the self handle we got from the connection with 0
if (reply.value()) {
mPriv->groupSelfHandle = reply.value();
}
}
mPriv->nowHaveInitialMembers();
mPriv->continueIntrospection();
}
void Channel::gotContacts(PendingOperation *op)
{
PendingContacts *pending = qobject_cast<PendingContacts *>(op);
mPriv->buildingContacts = false;
QList<ContactPtr> contacts;
if (pending->isValid()) {
contacts = pending->contacts();
if (!pending->invalidHandles().isEmpty()) {
warning() << "Unable to construct Contact objects for handles:" <<
pending->invalidHandles();
if (mPriv->groupSelfHandle &&
pending->invalidHandles().contains(mPriv->groupSelfHandle)) {
warning() << "Unable to retrieve self contact";
mPriv->groupSelfContact.reset();
emit groupSelfContactChanged();
}
}
} else {
warning().nospace() << "Getting contacts failed with " <<
pending->errorName() << ":" << pending->errorMessage();
}
mPriv->updateContacts(contacts);
}
void Channel::onGroupFlagsChanged(uint added, uint removed)
{
debug().nospace() << "Got Channel.Interface.Group::GroupFlagsChanged(" <<
hex << added << ", " << removed << ")";
added &= ~(mPriv->groupFlags);
removed &= mPriv->groupFlags;
debug().nospace() << "Arguments after filtering (" << hex << added <<
", " << removed << ")";
uint groupFlags = mPriv->groupFlags;
groupFlags |= added;
groupFlags &= ~removed;
// just emit groupFlagsChanged and related signals if the flags really
// changed and we are ready
if (mPriv->setGroupFlags(groupFlags) && isReady(Channel::FeatureCore)) {
debug() << "Emitting groupFlagsChanged with" << mPriv->groupFlags <<
"value" << added << "added" << removed << "removed";
emit groupFlagsChanged((ChannelGroupFlags) mPriv->groupFlags,
(ChannelGroupFlags) added, (ChannelGroupFlags) removed);
if (added & ChannelGroupFlagCanAdd ||
removed & ChannelGroupFlagCanAdd) {
debug() << "Emitting groupCanAddContactsChanged";
emit groupCanAddContactsChanged(groupCanAddContacts());
}
if (added & ChannelGroupFlagCanRemove ||
removed & ChannelGroupFlagCanRemove) {
debug() << "Emitting groupCanRemoveContactsChanged";
emit groupCanRemoveContactsChanged(groupCanRemoveContacts());
}
if (added & ChannelGroupFlagCanRescind ||
removed & ChannelGroupFlagCanRescind) {
debug() << "Emitting groupCanRescindContactsChanged";
emit groupCanRescindContactsChanged(groupCanRescindContacts());
}
}
}
void Channel::onMembersChanged(const QString &message,
const UIntList &added, const UIntList &removed,
const UIntList &localPending, const UIntList &remotePending,
uint actor, uint reason)
{
// Ignore the signal if we're using the MCD signal to not duplicate events
if (mPriv->usingMembersChangedDetailed) {
return;
}
debug() << "Got Channel.Interface.Group::MembersChanged with" << added.size() <<
"added," << removed.size() << "removed," << localPending.size() <<
"moved to LP," << remotePending.size() << "moved to RP," << actor <<
"being the actor," << reason << "the reason and" << message << "the message";
debug() << " synthesizing a corresponding MembersChangedDetailed signal";
QVariantMap details;
if (!message.isEmpty()) {
details.insert(QLatin1String("message"), message);
}
if (actor != 0) {
details.insert(QLatin1String("actor"), actor);
}
details.insert(QLatin1String("change-reason"), reason);
mPriv->doMembersChangedDetailed(added, removed, localPending, remotePending, details);
}
void Channel::onMembersChangedDetailed(
const UIntList &added, const UIntList &removed,
const UIntList &localPending, const UIntList &remotePending,
const QVariantMap &details)
{
// Ignore the signal if we aren't (yet) using MCD to not duplicate events
if (!mPriv->usingMembersChangedDetailed) {
return;
}
debug() << "Got Channel.Interface.Group::MembersChangedDetailed with" << added.size() <<
"added," << removed.size() << "removed," << localPending.size() <<
"moved to LP," << remotePending.size() << "moved to RP and with" << details.size() <<
"details";
mPriv->doMembersChangedDetailed(added, removed, localPending, remotePending, details);
}
void Channel::Private::doMembersChangedDetailed(
const UIntList &added, const UIntList &removed,
const UIntList &localPending, const UIntList &remotePending,
const QVariantMap &details)
{
if (!groupHaveMembers) {
debug() << "Still waiting for initial group members, "
"so ignoring delta signal...";
return;
}
if (added.isEmpty() && removed.isEmpty() &&
localPending.isEmpty() && remotePending.isEmpty()) {
debug() << "Nothing really changed, so skipping membersChanged";
return;
}
// let's store groupSelfContactRemoveInfo here as we may not have time
// to build the contacts in case self contact is removed,
// as Closed will be emitted right after
if (removed.contains(groupSelfHandle)) {
if (qdbus_cast<uint>(details.value(QLatin1String("change-reason"))) ==
ChannelGroupChangeReasonRenamed) {
if (removed.size() != 1 ||
(added.size() + localPending.size() + remotePending.size()) != 1) {
// spec-incompliant CM, ignoring members changed
warning() << "Received MembersChangedDetailed with reason "
"Renamed and removed.size != 1 or added.size + "
"localPending.size + remotePending.size != 1. Ignoring";
return;
}
uint newHandle = 0;
if (!added.isEmpty()) {
newHandle = added.first();
} else if (!localPending.isEmpty()) {
newHandle = localPending.first();
} else if (!remotePending.isEmpty()) {
newHandle = remotePending.first();
}
parent->onSelfHandleChanged(newHandle);
return;
}
// let's try to get the actor contact from contact manager if available
groupSelfContactRemoveInfo = GroupMemberChangeDetails(
connection->contactManager()->lookupContactByHandle(
qdbus_cast<uint>(details.value(QLatin1String("actor")))),
details);
}
HandleIdentifierMap contactIds = qdbus_cast<HandleIdentifierMap>(
details.value(GroupMembersChangedInfo::keyContactIds));
connection->lowlevel()->injectContactIds(contactIds);
groupMembersChangedQueue.enqueue(
new Private::GroupMembersChangedInfo(
added, removed,
localPending, remotePending,
details));
if (!buildingContacts) {
// if we are building contacts, we should wait it to finish so we don't
// present the user with wrong information
processMembersChanged();
}
}
void Channel::onHandleOwnersChanged(const HandleOwnerMap &added,
const UIntList &removed)
{
debug() << "Got Channel.Interface.Group::HandleOwnersChanged with" <<
added.size() << "added," << removed.size() << "removed";
if (!mPriv->groupAreHandleOwnersAvailable) {
debug() << "Still waiting for initial handle owners, so ignoring "
"delta signal...";
return;
}
UIntList emitAdded;
UIntList emitRemoved;
for (HandleOwnerMap::const_iterator i = added.begin();
i != added.end();
++i) {
uint handle = i.key();
uint global = i.value();
if (!mPriv->groupHandleOwners.contains(handle)
|| mPriv->groupHandleOwners[handle] != global) {
debug() << " +++/changed" << handle << "->" << global;
mPriv->groupHandleOwners[handle] = global;
emitAdded.append(handle);
}
}
foreach (uint handle, removed) {
if (mPriv->groupHandleOwners.contains(handle)) {
debug() << " ---" << handle;
mPriv->groupHandleOwners.remove(handle);
emitRemoved.append(handle);
}
}
// just emit groupHandleOwnersChanged if it really changed and
// we are ready
if ((emitAdded.size() || emitRemoved.size()) && isReady(Channel::FeatureCore)) {
debug() << "Emitting groupHandleOwnersChanged with" << emitAdded.size() <<
"added" << emitRemoved.size() << "removed";
emit groupHandleOwnersChanged(mPriv->groupHandleOwners,
emitAdded, emitRemoved);
}
}
void Channel::onSelfHandleChanged(uint selfHandle)
{
debug().nospace() << "Got Channel.Interface.Group::SelfHandleChanged";
if (selfHandle != mPriv->groupSelfHandle) {
mPriv->groupSelfHandle = selfHandle;
debug() << " Emitting groupSelfHandleChanged with new self handle" <<
selfHandle;
// FIXME: fix self contact building with no group
mPriv->pendingRetrieveGroupSelfContact = true;
}
}
void Channel::gotConferenceProperties(QDBusPendingCallWatcher *watcher)
{
QDBusPendingReply<QVariantMap> reply = *watcher;
QVariantMap props;
mPriv->introspectingConference = false;
if (!reply.isError()) {
debug() << "Got reply to Properties::GetAll(Channel.Interface.Conference)";
props = reply.value();
ConnectionPtr conn = connection();
ChannelFactoryConstPtr chanFactory = conn->channelFactory();
ObjectPathList channels =
qdbus_cast<ObjectPathList>(props[QLatin1String("Channels")]);
foreach (const QDBusObjectPath &channelPath, channels) {
if (mPriv->conferenceChannels.contains(channelPath.path())) {
continue;
}
PendingReady *readyOp = chanFactory->proxy(conn,
channelPath.path(), QVariantMap());
ChannelPtr channel(ChannelPtr::qObjectCast(readyOp->proxy()));
Q_ASSERT(!channel.isNull());
mPriv->conferenceChannels.insert(channelPath.path(), channel);
}
ObjectPathList initialChannels =
qdbus_cast<ObjectPathList>(props[QLatin1String("InitialChannels")]);
foreach (const QDBusObjectPath &channelPath, initialChannels) {
if (mPriv->conferenceInitialChannels.contains(channelPath.path())) {
continue;
}
PendingReady *readyOp = chanFactory->proxy(conn,
channelPath.path(), QVariantMap());
ChannelPtr channel(ChannelPtr::qObjectCast(readyOp->proxy()));
Q_ASSERT(!channel.isNull());
mPriv->conferenceInitialChannels.insert(channelPath.path(), channel);
}
mPriv->conferenceInitialInviteeHandles =
qdbus_cast<UIntList>(props[QLatin1String("InitialInviteeHandles")]);
QStringList conferenceInitialInviteeIds =
qdbus_cast<QStringList>(props[QLatin1String("InitialInviteeIDs")]);
if (mPriv->conferenceInitialInviteeHandles.size() == conferenceInitialInviteeIds.size()) {
HandleIdentifierMap contactIds;
int i = 0;
foreach (uint handle, mPriv->conferenceInitialInviteeHandles) {
contactIds.insert(handle, conferenceInitialInviteeIds.at(i++));
}
mPriv->connection->lowlevel()->injectContactIds(contactIds);
}
mPriv->conferenceInvitationMessage =
qdbus_cast<QString>(props[QLatin1String("InvitationMessage")]);
ChannelOriginatorMap originalChannels = qdbus_cast<ChannelOriginatorMap>(
props[QLatin1String("OriginalChannels")]);
for (ChannelOriginatorMap::const_iterator i = originalChannels.constBegin();
i != originalChannels.constEnd(); ++i) {
PendingReady *readyOp = chanFactory->proxy(conn,
i.value().path(), QVariantMap());
ChannelPtr channel(ChannelPtr::qObjectCast(readyOp->proxy()));
Q_ASSERT(!channel.isNull());
mPriv->conferenceOriginalChannels.insert(i.key(), channel);
}
} else {
warning().nospace() << "Properties::GetAll(Channel.Interface.Conference) "
"failed with " << reply.error().name() << ": " <<
reply.error().message();
}
mPriv->continueIntrospection();
}
void Channel::gotConferenceInitialInviteeContacts(PendingOperation *op)
{
PendingContacts *pending = qobject_cast<PendingContacts *>(op);
if (pending->isValid()) {
mPriv->conferenceInitialInviteeContacts = pending->contacts().toSet();
} else {
warning().nospace() << "Getting conference initial invitee contacts "
"failed with " << pending->errorName() << ":" <<
pending->errorMessage();
}
mPriv->readinessHelper->setIntrospectCompleted(
FeatureConferenceInitialInviteeContacts, true);
}
void Channel::onConferenceChannelMerged(const QDBusObjectPath &channelPath,
uint channelSpecificHandle, const QVariantMap &properties)
{
if (mPriv->conferenceChannels.contains(channelPath.path())) {
return;
}
ConnectionPtr conn = connection();
ChannelFactoryConstPtr chanFactory = conn->channelFactory();
PendingReady *readyOp = chanFactory->proxy(conn,
channelPath.path(), properties);
ChannelPtr channel(ChannelPtr::qObjectCast(readyOp->proxy()));
Q_ASSERT(!channel.isNull());
mPriv->conferenceChannels.insert(channelPath.path(), channel);
emit conferenceChannelMerged(channel);
if (channelSpecificHandle != 0) {
mPriv->conferenceOriginalChannels.insert(channelSpecificHandle, channel);
}
}
void Channel::onConferenceChannelMerged(const QDBusObjectPath &channelPath)
{
onConferenceChannelMerged(channelPath, 0, QVariantMap());
}
void Channel::onConferenceChannelRemoved(const QDBusObjectPath &channelPath,
const QVariantMap &details)
{
if (!mPriv->conferenceChannels.contains(channelPath.path())) {
return;
}
HandleIdentifierMap contactIds = qdbus_cast<HandleIdentifierMap>(
details.value(Private::GroupMembersChangedInfo::keyContactIds));
mPriv->connection->lowlevel()->injectContactIds(contactIds);
mPriv->conferenceChannelRemovedQueue.enqueue(
new Private::ConferenceChannelRemovedInfo(channelPath, details));
mPriv->processConferenceChannelRemoved();
}
void Channel::onConferenceChannelRemoved(const QDBusObjectPath &channelPath)
{
onConferenceChannelRemoved(channelPath, QVariantMap());
}
void Channel::gotConferenceChannelRemovedActorContact(PendingOperation *op)
{
ContactPtr actorContact;
if (op) {
PendingContacts *pc = qobject_cast<PendingContacts *>(op);
if (pc->isValid()) {
Q_ASSERT(pc->contacts().size() == 1);
actorContact = pc->contacts().first();
} else {
warning().nospace() << "Getting conference channel removed actor "
"failed with " << pc->errorName() << ":" <<
pc->errorMessage();
}
}
Private::ConferenceChannelRemovedInfo *info = mPriv->conferenceChannelRemovedQueue.dequeue();
ChannelPtr channel = mPriv->conferenceChannels[info->channelPath.path()];
mPriv->conferenceChannels.remove(info->channelPath.path());
emit conferenceChannelRemoved(channel, GroupMemberChangeDetails(actorContact,
info->details));
for (QHash<uint, ChannelPtr>::iterator i = mPriv->conferenceOriginalChannels.begin();
i != mPriv->conferenceOriginalChannels.end();) {
if (i.value() == channel) {
i = mPriv->conferenceOriginalChannels.erase(i);
} else {
++i;
}
}
delete info;
mPriv->buildingConferenceChannelRemovedActorContact = false;
mPriv->processConferenceChannelRemoved();
}
/**
* \fn void Channel::groupFlagsChanged(uint flags, uint added, uint removed)
*
* Emitted when the value of groupFlags() changes.
*
* \param flags The value which would now be returned by groupFlags().
* \param added Flags added compared to the previous value.
* \param removed Flags removed compared to the previous value.
*/
/**
* \fn void Channel::groupCanAddContactsChanged(bool canAddContacts)
*
* Emitted when the value of groupCanAddContacts() changes.
*
* \param canAddContacts Whether a contact can be added to this channel.
* \sa groupCanAddContacts()
*/
/**
* \fn void Channel::groupCanRemoveContactsChanged(bool canRemoveContacts)
*
* Emitted when the value of groupCanRemoveContacts() changes.
*
* \param canRemoveContacts Whether a contact can be removed from this channel.
* \sa groupCanRemoveContacts()
*/
/**
* \fn void Channel::groupCanRescindContactsChanged(bool canRescindContacts)
*
* Emitted when the value of groupCanRescindContacts() changes.
*
* \param canRescindContacts Whether contact invitations can be rescinded.
* \sa groupCanRescindContacts()
*/
/**
* \fn void Channel::groupMembersChanged(
* const Tp::Contacts &groupMembersAdded,
* const Tp::Contacts &groupLocalPendingMembersAdded,
* const Tp::Contacts &groupRemotePendingMembersAdded,
* const Tp::Contacts &groupMembersRemoved,
* const Channel::GroupMemberChangeDetails &details)
*
* Emitted when the value returned by groupContacts(), groupLocalPendingContacts() or
* groupRemotePendingContacts() changes.
*
* \param groupMembersAdded The contacts that were added to this channel.
* \param groupLocalPendingMembersAdded The local pending contacts that were
* added to this channel.
* \param groupRemotePendingMembersAdded The remote pending contacts that were
* added to this channel.
* \param groupMembersRemoved The contacts removed from this channel.
* \param details Additional details such as the contact requesting or causing
* the change.
*/
/**
* \fn void Channel::groupHandleOwnersChanged(const HandleOwnerMap &owners,
* const Tp::UIntList &added, const Tp::UIntList &removed)
*
* Emitted when the value returned by groupHandleOwners() changes.
*
* \param owners The value which would now be returned by
* groupHandleOwners().
* \param added Handles which have been added to the mapping as keys, or
* existing handle keys for which the mapped-to value has changed.
* \param removed Handles which have been removed from the mapping.
*/
/**
* \fn void Channel::groupSelfContactChanged()
*
* Emitted when the value returned by groupSelfContact() changes.
*/
/**
* \fn void Channel::conferenceChannelMerged(const Tp::ChannelPtr &channel)
*
* Emitted when a new channel is added to the value of conferenceChannels().
*
* \param channel The channel that was added to conferenceChannels().
*/
/**
* \fn void Channel::conferenceChannelRemoved(const Tp::ChannelPtr &channel,
* const Tp::Channel::GroupMemberChangeDetails &details)
*
* Emitted when a new channel is removed from the value of conferenceChannels().
*
* \param channel The channel that was removed from conferenceChannels().
* \param details The change details.
*/
} // Tp
| Telekinesis/Telepathy-qt4-0.8.0 | TelepathyQt4/channel.cpp | C++ | lgpl-2.1 | 130,256 |
package com.nutz.granola;
public class Reference {
public static final String MOD_ID = "granola";
public static final String MOD_NAME = "The Granola Mod";
public static final String VERSION = "alpha 0.3";
public static final String CLIENT_PROXY_CLASS = "com.nutz.granola.proxy.ClientProxy";
public static final String SERVER_PROXY_CLASS = "com.nutz.granola.proxy.CommonProxy";
}
| Nutzchannel/granola | src/main/java/com/nutz/granola/Reference.java | Java | lgpl-2.1 | 385 |
/*
* examples/sparsesolverat.C
*
* Copyright (C) The LinBox Group
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox 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
* ========LICENCE========
*/
/**\file examples/sparsesolverat.C
@example examples/sparsesolverat.C
@author Jean-Guillaume.Dumas@univ-grenoble-alpes.fr
* \brief Direct sparse solver over the rationals
* \ingroup examples
*/
#include <iostream>
#include "givaro/modular.h"
#include "linbox/matrix/sparse-matrix.h"
#include "linbox/solutions/solve.h"
#include "linbox/util/matrix-stream.h"
#include "linbox/solutions/methods.h"
using namespace LinBox;
template<typename DVector, typename EDom>
int rhs(DVector& B, const EDom& DD, bool createB, std::ifstream& invect) {
if (createB) {
std::cerr << "Creating a random {-1,1} vector " << std::endl;
for(auto it=B.begin(); it != B.end(); ++it)
if (drand48() <0.5)
*it = -1;
else
*it = 1;
} else {
for(auto&& it:B) invect >> it;
invect.close();
}
std::clog << "B is [";
for(auto it:B) DD.write(std::clog, it) << ' ';
std::clog << ']' << std::endl;
return 0;
}
int main (int argc, char **argv)
{
// set 2 to see Q L U P factorization;
// see fill-in with 2 and __LINBOX_ALL__ or __LINBOX_FILLIN__ defined
commentator().setMaxDetailLevel (1);
commentator().setMaxDepth (-1);
commentator().setReportStream (std::clog);
// commentator().setDefaultReportFile("/dev/stdout"); // to see activities
if (argc < 2 || argc > 4) {
std::cerr << "Usage: solve <matrix-file-in-supported-format> [<dense-vector-file>] [0/1 <integer solve>]" << std::endl;
return 0;
}
std::ifstream input (argv[1]);
if (!input) { std::cerr << "Error opening matrix file " << argv[1] << std::endl; return -1; }
std::ifstream invect;
bool createB = false;
if (argc == 2) {
createB = true;
}
bool integralsolve=false;
if (argc >= 3) {
invect.open (argv[2], std::ifstream::in);
if (!invect) {
createB = true;
integralsolve = atoi(argv[2]);
}
else {
createB = false;
}
}
if (argc >= 4)
integralsolve = atoi(argv[3]);
typedef Givaro::QField<Givaro::Rational> Rats;
Rats QQ;
typedef DenseVector<Rats> RVector;
if (integralsolve) {
std::clog << "Integral solving" << std::endl;
typedef Givaro::ZRing<Givaro::Integer> Ints;
Ints ZZ;
typedef DenseVector<Ints> ZVector;
MatrixStream<Rats> ms( QQ, input );
size_t nrow, ncol; ms.getDimensions(nrow,ncol);
SparseMatrix<Ints> A(ZZ,nrow,ncol);
ZVector X(ZZ, A.coldim()),B(ZZ, A.rowdim());
// Read rational matrix and rhs, then compute denominator LCM
{
SparseMatrix<Rats> RA ( ms );
std::clog << "A is " << RA.rowdim() << " by " << RA.coldim() << std::endl;
Givaro::Integer ABlcm(1);
for(auto iterow = RA.rowBegin() ; iterow != RA.rowEnd(); ++iterow) {
for(auto iter = iterow->begin(); iter != iterow->end(); ++iter) {
lcm(ABlcm, ABlcm, iter->second.deno());
}
}
std::clog << "A denominator lcm: " << ABlcm << std::endl;
RVector RB(QQ, RA.rowdim());
rhs(RB, QQ, createB, invect);
for(auto iter = RB.begin(); iter != RB.end(); ++iter) {
lcm(ABlcm, ABlcm, iter->deno());
}
std::clog << "A & B denominator lcm: " << ABlcm << std::endl;
// A x = b is equivalent to (l.A) x = (l.b)
auto iterow = RA.rowBegin();
auto iterit = A.rowBegin();
for(; iterow != RA.rowEnd(); ++iterow, ++iterit) {
for(auto iter = iterow->begin(); iter != iterow->end(); ++iter) {
iterit->emplace_back( iter->first, (iter->second.nume() * ABlcm) / iter->second.deno() );
}
}
auto iter = RB.begin();
auto itez = B.begin();
for( ; iter != RB.end(); ++iter, ++itez) {
*itez = (iter->nume() * ABlcm) / iter->deno();
}
}
Givaro::ZRing<Integer>::Element d;
Timer chrono;
std::clog << "Integral Sparse Elimination" << std::endl;
chrono.start();
solveInPlace (X, d, A, B, Method::SparseElimination());
chrono.stop();
std::cout << "(SparseElimination) Solution is [";
for(auto it:X) ZZ.write(std::cout, it) << ' ';
std::cout << "] / ";
ZZ.write(std::cout, d)<< std::endl;
std::clog << "CPU time (seconds): " << chrono.usertime() << std::endl;
} else {
MatrixStream<Rats> ms( QQ, input );
SparseMatrix<Rats> A ( ms );
std::clog << "A is " << A.rowdim() << " by " << A.coldim() << std::endl;
RVector X(QQ, A.coldim()),B(QQ, A.rowdim());
// Sparse Elimination
rhs(B, QQ, createB, invect);
Timer chrono;
std::clog << "Direct Rational Sparse Elimination" << std::endl;
chrono.start();
// @fixme Can't pass a Randiter anymore, we need an API through Method to set seed or such
// typename Rats::RandIter generator(QQ,0,BaseTimer::seed() );
// solveInPlace (X, A, B, Method::SparseElimination(), generator);
solveInPlace (X, A, B, Method::SparseElimination());
chrono.stop();
std::clog << "(SparseElimination) Solution is [";
for(auto it:X) QQ.write(std::cout, it) << ' ';
std::clog << ']' << std::endl;
std::clog << "CPU time (seconds): " << chrono.usertime() << std::endl;
}
return 0;
}
// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
| linbox-team/linbox | examples/sparsesolverat.C | C++ | lgpl-2.1 | 6,601 |
/*
* Latch integration for Meteor framework
* Copyright (C) 2015 Bruno Orcha García <gimcoo@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 Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
Session.setDefault('Meteor._latch.pairing', false);
Template._latchAccountLinks.helpers({
isPairing: function() {
return Session.get('Meteor._latch.pairing');
},
isPaired: Latch.isPaired
});
Template._latchAccountLinks.events({
"click #latch-pair-link" : function (evt, tmpl) {
Accounts._loginButtonsSession.resetMessages();
Tracker.flush();
var token = prompt("Open your Latch app and select 'Add a new service'.\nWrite down the token code shown.");
if (!token) return;
Session.set('Meteor._latch.pairing', true);
Latch.pair(token, function(err, res) {
Session.set('Meteor._latch.pairing', false);
if (err) {
Accounts._loginButtonsSession.errorMessage(err.reason);
} else {
Accounts._loginButtonsSession.infoMessage("Account protected with Latch!");
}
});
},
"click #latch-unpair-link" : function (evt, tmpl) {
Accounts._loginButtonsSession.resetMessages();
Tracker.flush();
if (!confirm("You're going to disable Latch protection for your account. Are your sure?")) return;
Latch.unpair(function(err, res) {
if (err) {
Accounts._loginButtonsSession.errorMessage(err.reason);
} else {
Accounts._loginButtonsSession.infoMessage("Account protection disabled.");
}
});
}
});
injectTemplate("_latchAccountLinks", "_loginButtonsLoggedInDropdownActions")
| gimco/meteor-accounts-ui-latch | accounts_ui_latch.js | JavaScript | lgpl-2.1 | 2,278 |
//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass implements a simple loop unroller. It works best when loops have
// been canonicalized by the -indvars pass, allowing it to determine the trip
// counts of loops easily.
//===----------------------------------------------------------------------===//
#include "llvm/ADT/SetVector.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/CodeMetrics.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/LoopUnrollAnalyzer.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Metadata.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/LoopUtils.h"
#include "llvm/Transforms/Utils/UnrollLoop.h"
#include <climits>
#include <utility>
using namespace llvm;
#define DEBUG_TYPE "loop-unroll"
static cl::opt<unsigned>
UnrollThreshold("unroll-threshold", cl::Hidden,
cl::desc("The baseline cost threshold for loop unrolling"));
static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold(
"unroll-percent-dynamic-cost-saved-threshold", cl::init(50), cl::Hidden,
cl::desc("The percentage of estimated dynamic cost which must be saved by "
"unrolling to allow unrolling up to the max threshold."));
static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount(
"unroll-dynamic-cost-savings-discount", cl::init(100), cl::Hidden,
cl::desc("This is the amount discounted from the total unroll cost when "
"the unrolled form has a high dynamic cost savings (triggered by "
"the '-unroll-perecent-dynamic-cost-saved-threshold' flag)."));
static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze(
"unroll-max-iteration-count-to-analyze", cl::init(10), cl::Hidden,
cl::desc("Don't allow loop unrolling to simulate more than this number of"
"iterations when checking full unroll profitability"));
static cl::opt<unsigned> UnrollCount(
"unroll-count", cl::Hidden,
cl::desc("Use this unroll count for all loops including those with "
"unroll_count pragma values, for testing purposes"));
static cl::opt<unsigned> UnrollMaxCount(
"unroll-max-count", cl::Hidden,
cl::desc("Set the max unroll count for partial and runtime unrolling, for"
"testing purposes"));
static cl::opt<unsigned> UnrollFullMaxCount(
"unroll-full-max-count", cl::Hidden,
cl::desc(
"Set the max unroll count for full unrolling, for testing purposes"));
static cl::opt<bool>
UnrollAllowPartial("unroll-allow-partial", cl::Hidden,
cl::desc("Allows loops to be partially unrolled until "
"-unroll-threshold loop size is reached."));
static cl::opt<bool> UnrollAllowRemainder(
"unroll-allow-remainder", cl::Hidden,
cl::desc("Allow generation of a loop remainder (extra iterations) "
"when unrolling a loop."));
static cl::opt<bool>
UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden,
cl::desc("Unroll loops with run-time trip counts"));
static cl::opt<unsigned> PragmaUnrollThreshold(
"pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden,
cl::desc("Unrolled size limit for loops with an unroll(full) or "
"unroll_count pragma."));
/// A magic value for use with the Threshold parameter to indicate
/// that the loop unroll should be performed regardless of how much
/// code expansion would result.
static const unsigned NoThreshold = UINT_MAX;
/// Default unroll count for loops with run-time trip count if
/// -unroll-count is not set
static const unsigned DefaultUnrollRuntimeCount = 8;
/// Gather the various unrolling parameters based on the defaults, compiler
/// flags, TTI overrides and user specified parameters.
static TargetTransformInfo::UnrollingPreferences gatherUnrollingPreferences(
Loop *L, const TargetTransformInfo &TTI, Optional<unsigned> UserThreshold,
Optional<unsigned> UserCount, Optional<bool> UserAllowPartial,
Optional<bool> UserRuntime) {
TargetTransformInfo::UnrollingPreferences UP;
// Set up the defaults
UP.Threshold = 150;
UP.PercentDynamicCostSavedThreshold = 50;
UP.DynamicCostSavingsDiscount = 100;
UP.OptSizeThreshold = 0;
UP.PartialThreshold = UP.Threshold;
UP.PartialOptSizeThreshold = 0;
UP.Count = 0;
UP.MaxCount = UINT_MAX;
UP.FullUnrollMaxCount = UINT_MAX;
UP.Partial = false;
UP.Runtime = false;
UP.AllowRemainder = true;
UP.AllowExpensiveTripCount = false;
UP.Force = false;
// Override with any target specific settings
TTI.getUnrollingPreferences(L, UP);
// Apply size attributes
if (L->getHeader()->getParent()->optForSize()) {
UP.Threshold = UP.OptSizeThreshold;
UP.PartialThreshold = UP.PartialOptSizeThreshold;
}
// Apply any user values specified by cl::opt
if (UnrollThreshold.getNumOccurrences() > 0) {
UP.Threshold = UnrollThreshold;
UP.PartialThreshold = UnrollThreshold;
}
if (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0)
UP.PercentDynamicCostSavedThreshold =
UnrollPercentDynamicCostSavedThreshold;
if (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0)
UP.DynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount;
if (UnrollMaxCount.getNumOccurrences() > 0)
UP.MaxCount = UnrollMaxCount;
if (UnrollFullMaxCount.getNumOccurrences() > 0)
UP.FullUnrollMaxCount = UnrollFullMaxCount;
if (UnrollAllowPartial.getNumOccurrences() > 0)
UP.Partial = UnrollAllowPartial;
if (UnrollAllowRemainder.getNumOccurrences() > 0)
UP.AllowRemainder = UnrollAllowRemainder;
if (UnrollRuntime.getNumOccurrences() > 0)
UP.Runtime = UnrollRuntime;
// Apply user values provided by argument
if (UserThreshold.hasValue()) {
UP.Threshold = *UserThreshold;
UP.PartialThreshold = *UserThreshold;
}
if (UserCount.hasValue())
UP.Count = *UserCount;
if (UserAllowPartial.hasValue())
UP.Partial = *UserAllowPartial;
if (UserRuntime.hasValue())
UP.Runtime = *UserRuntime;
return UP;
}
namespace {
/// A struct to densely store the state of an instruction after unrolling at
/// each iteration.
///
/// This is designed to work like a tuple of <Instruction *, int> for the
/// purposes of hashing and lookup, but to be able to associate two boolean
/// states with each key.
struct UnrolledInstState {
Instruction *I;
int Iteration : 30;
unsigned IsFree : 1;
unsigned IsCounted : 1;
};
/// Hashing and equality testing for a set of the instruction states.
struct UnrolledInstStateKeyInfo {
typedef DenseMapInfo<Instruction *> PtrInfo;
typedef DenseMapInfo<std::pair<Instruction *, int>> PairInfo;
static inline UnrolledInstState getEmptyKey() {
return {PtrInfo::getEmptyKey(), 0, 0, 0};
}
static inline UnrolledInstState getTombstoneKey() {
return {PtrInfo::getTombstoneKey(), 0, 0, 0};
}
static inline unsigned getHashValue(const UnrolledInstState &S) {
return PairInfo::getHashValue({S.I, S.Iteration});
}
static inline bool isEqual(const UnrolledInstState &LHS,
const UnrolledInstState &RHS) {
return PairInfo::isEqual({LHS.I, LHS.Iteration}, {RHS.I, RHS.Iteration});
}
};
}
namespace {
struct EstimatedUnrollCost {
/// \brief The estimated cost after unrolling.
int UnrolledCost;
/// \brief The estimated dynamic cost of executing the instructions in the
/// rolled form.
int RolledDynamicCost;
};
}
/// \brief Figure out if the loop is worth full unrolling.
///
/// Complete loop unrolling can make some loads constant, and we need to know
/// if that would expose any further optimization opportunities. This routine
/// estimates this optimization. It computes cost of unrolled loop
/// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By
/// dynamic cost we mean that we won't count costs of blocks that are known not
/// to be executed (i.e. if we have a branch in the loop and we know that at the
/// given iteration its condition would be resolved to true, we won't add up the
/// cost of the 'false'-block).
/// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If
/// the analysis failed (no benefits expected from the unrolling, or the loop is
/// too big to analyze), the returned value is None.
static Optional<EstimatedUnrollCost>
analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT,
ScalarEvolution &SE, const TargetTransformInfo &TTI,
int MaxUnrolledLoopSize) {
// We want to be able to scale offsets by the trip count and add more offsets
// to them without checking for overflows, and we already don't want to
// analyze *massive* trip counts, so we force the max to be reasonably small.
assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) &&
"The unroll iterations max is too large!");
// Only analyze inner loops. We can't properly estimate cost of nested loops
// and we won't visit inner loops again anyway.
if (!L->empty())
return None;
// Don't simulate loops with a big or unknown tripcount
if (!UnrollMaxIterationsCountToAnalyze || !TripCount ||
TripCount > UnrollMaxIterationsCountToAnalyze)
return None;
SmallSetVector<BasicBlock *, 16> BBWorklist;
SmallSetVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitWorklist;
DenseMap<Value *, Constant *> SimplifiedValues;
SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues;
// The estimated cost of the unrolled form of the loop. We try to estimate
// this by simplifying as much as we can while computing the estimate.
int UnrolledCost = 0;
// We also track the estimated dynamic (that is, actually executed) cost in
// the rolled form. This helps identify cases when the savings from unrolling
// aren't just exposing dead control flows, but actual reduced dynamic
// instructions due to the simplifications which we expect to occur after
// unrolling.
int RolledDynamicCost = 0;
// We track the simplification of each instruction in each iteration. We use
// this to recursively merge costs into the unrolled cost on-demand so that
// we don't count the cost of any dead code. This is essentially a map from
// <instruction, int> to <bool, bool>, but stored as a densely packed struct.
DenseSet<UnrolledInstState, UnrolledInstStateKeyInfo> InstCostMap;
// A small worklist used to accumulate cost of instructions from each
// observable and reached root in the loop.
SmallVector<Instruction *, 16> CostWorklist;
// PHI-used worklist used between iterations while accumulating cost.
SmallVector<Instruction *, 4> PHIUsedList;
// Helper function to accumulate cost for instructions in the loop.
auto AddCostRecursively = [&](Instruction &RootI, int Iteration) {
assert(Iteration >= 0 && "Cannot have a negative iteration!");
assert(CostWorklist.empty() && "Must start with an empty cost list");
assert(PHIUsedList.empty() && "Must start with an empty phi used list");
CostWorklist.push_back(&RootI);
for (;; --Iteration) {
do {
Instruction *I = CostWorklist.pop_back_val();
// InstCostMap only uses I and Iteration as a key, the other two values
// don't matter here.
auto CostIter = InstCostMap.find({I, Iteration, 0, 0});
if (CostIter == InstCostMap.end())
// If an input to a PHI node comes from a dead path through the loop
// we may have no cost data for it here. What that actually means is
// that it is free.
continue;
auto &Cost = *CostIter;
if (Cost.IsCounted)
// Already counted this instruction.
continue;
// Mark that we are counting the cost of this instruction now.
Cost.IsCounted = true;
// If this is a PHI node in the loop header, just add it to the PHI set.
if (auto *PhiI = dyn_cast<PHINode>(I))
if (PhiI->getParent() == L->getHeader()) {
assert(Cost.IsFree && "Loop PHIs shouldn't be evaluated as they "
"inherently simplify during unrolling.");
if (Iteration == 0)
continue;
// Push the incoming value from the backedge into the PHI used list
// if it is an in-loop instruction. We'll use this to populate the
// cost worklist for the next iteration (as we count backwards).
if (auto *OpI = dyn_cast<Instruction>(
PhiI->getIncomingValueForBlock(L->getLoopLatch())))
if (L->contains(OpI))
PHIUsedList.push_back(OpI);
continue;
}
// First accumulate the cost of this instruction.
if (!Cost.IsFree) {
UnrolledCost += TTI.getUserCost(I);
DEBUG(dbgs() << "Adding cost of instruction (iteration " << Iteration
<< "): ");
DEBUG(I->dump());
}
// We must count the cost of every operand which is not free,
// recursively. If we reach a loop PHI node, simply add it to the set
// to be considered on the next iteration (backwards!).
for (Value *Op : I->operands()) {
// Check whether this operand is free due to being a constant or
// outside the loop.
auto *OpI = dyn_cast<Instruction>(Op);
if (!OpI || !L->contains(OpI))
continue;
// Otherwise accumulate its cost.
CostWorklist.push_back(OpI);
}
} while (!CostWorklist.empty());
if (PHIUsedList.empty())
// We've exhausted the search.
break;
assert(Iteration > 0 &&
"Cannot track PHI-used values past the first iteration!");
CostWorklist.append(PHIUsedList.begin(), PHIUsedList.end());
PHIUsedList.clear();
}
};
// Ensure that we don't violate the loop structure invariants relied on by
// this analysis.
assert(L->isLoopSimplifyForm() && "Must put loop into normal form first.");
assert(L->isLCSSAForm(DT) &&
"Must have loops in LCSSA form to track live-out values.");
DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n");
// Simulate execution of each iteration of the loop counting instructions,
// which would be simplified.
// Since the same load will take different values on different iterations,
// we literally have to go through all loop's iterations.
for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n");
// Prepare for the iteration by collecting any simplified entry or backedge
// inputs.
for (Instruction &I : *L->getHeader()) {
auto *PHI = dyn_cast<PHINode>(&I);
if (!PHI)
break;
// The loop header PHI nodes must have exactly two input: one from the
// loop preheader and one from the loop latch.
assert(
PHI->getNumIncomingValues() == 2 &&
"Must have an incoming value only for the preheader and the latch.");
Value *V = PHI->getIncomingValueForBlock(
Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch());
Constant *C = dyn_cast<Constant>(V);
if (Iteration != 0 && !C)
C = SimplifiedValues.lookup(V);
if (C)
SimplifiedInputValues.push_back({PHI, C});
}
// Now clear and re-populate the map for the next iteration.
SimplifiedValues.clear();
while (!SimplifiedInputValues.empty())
SimplifiedValues.insert(SimplifiedInputValues.pop_back_val());
UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L);
BBWorklist.clear();
BBWorklist.insert(L->getHeader());
// Note that we *must not* cache the size, this loop grows the worklist.
for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
BasicBlock *BB = BBWorklist[Idx];
// Visit all instructions in the given basic block and try to simplify
// it. We don't change the actual IR, just count optimization
// opportunities.
for (Instruction &I : *BB) {
// Track this instruction's expected baseline cost when executing the
// rolled loop form.
RolledDynamicCost += TTI.getUserCost(&I);
// Visit the instruction to analyze its loop cost after unrolling,
// and if the visitor returns true, mark the instruction as free after
// unrolling and continue.
bool IsFree = Analyzer.visit(I);
bool Inserted = InstCostMap.insert({&I, (int)Iteration,
(unsigned)IsFree,
/*IsCounted*/ false}).second;
(void)Inserted;
assert(Inserted && "Cannot have a state for an unvisited instruction!");
if (IsFree)
continue;
// If the instruction might have a side-effect recursively account for
// the cost of it and all the instructions leading up to it.
if (I.mayHaveSideEffects())
AddCostRecursively(I, Iteration);
// Can't properly model a cost of a call.
// FIXME: With a proper cost model we should be able to do it.
if(isa<CallInst>(&I))
return None;
// If unrolled body turns out to be too big, bail out.
if (UnrolledCost > MaxUnrolledLoopSize) {
DEBUG(dbgs() << " Exceeded threshold.. exiting.\n"
<< " UnrolledCost: " << UnrolledCost
<< ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
<< "\n");
return None;
}
}
TerminatorInst *TI = BB->getTerminator();
// Add in the live successors by first checking whether we have terminator
// that may be simplified based on the values simplified by this call.
BasicBlock *KnownSucc = nullptr;
if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
if (BI->isConditional()) {
if (Constant *SimpleCond =
SimplifiedValues.lookup(BI->getCondition())) {
// Just take the first successor if condition is undef
if (isa<UndefValue>(SimpleCond))
KnownSucc = BI->getSuccessor(0);
else if (ConstantInt *SimpleCondVal =
dyn_cast<ConstantInt>(SimpleCond))
KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 1 : 0);
}
}
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
if (Constant *SimpleCond =
SimplifiedValues.lookup(SI->getCondition())) {
// Just take the first successor if condition is undef
if (isa<UndefValue>(SimpleCond))
KnownSucc = SI->getSuccessor(0);
else if (ConstantInt *SimpleCondVal =
dyn_cast<ConstantInt>(SimpleCond))
KnownSucc = SI->findCaseValue(SimpleCondVal).getCaseSuccessor();
}
}
if (KnownSucc) {
if (L->contains(KnownSucc))
BBWorklist.insert(KnownSucc);
else
ExitWorklist.insert({BB, KnownSucc});
continue;
}
// Add BB's successors to the worklist.
for (BasicBlock *Succ : successors(BB))
if (L->contains(Succ))
BBWorklist.insert(Succ);
else
ExitWorklist.insert({BB, Succ});
AddCostRecursively(*TI, Iteration);
}
// If we found no optimization opportunities on the first iteration, we
// won't find them on later ones too.
if (UnrolledCost == RolledDynamicCost) {
DEBUG(dbgs() << " No opportunities found.. exiting.\n"
<< " UnrolledCost: " << UnrolledCost << "\n");
return None;
}
}
while (!ExitWorklist.empty()) {
BasicBlock *ExitingBB, *ExitBB;
std::tie(ExitingBB, ExitBB) = ExitWorklist.pop_back_val();
for (Instruction &I : *ExitBB) {
auto *PN = dyn_cast<PHINode>(&I);
if (!PN)
break;
Value *Op = PN->getIncomingValueForBlock(ExitingBB);
if (auto *OpI = dyn_cast<Instruction>(Op))
if (L->contains(OpI))
AddCostRecursively(*OpI, TripCount - 1);
}
}
DEBUG(dbgs() << "Analysis finished:\n"
<< "UnrolledCost: " << UnrolledCost << ", "
<< "RolledDynamicCost: " << RolledDynamicCost << "\n");
return {{UnrolledCost, RolledDynamicCost}};
}
/// ApproximateLoopSize - Approximate the size of the loop.
static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls,
bool &NotDuplicatable, bool &Convergent,
const TargetTransformInfo &TTI,
AssumptionCache *AC) {
SmallPtrSet<const Value *, 32> EphValues;
CodeMetrics::collectEphemeralValues(L, AC, EphValues);
CodeMetrics Metrics;
for (BasicBlock *BB : L->blocks())
Metrics.analyzeBasicBlock(BB, TTI, EphValues);
NumCalls = Metrics.NumInlineCandidates;
NotDuplicatable = Metrics.notDuplicatable;
Convergent = Metrics.convergent;
unsigned LoopSize = Metrics.NumInsts;
// Don't allow an estimate of size zero. This would allows unrolling of loops
// with huge iteration counts, which is a compile time problem even if it's
// not a problem for code quality. Also, the code using this size may assume
// that each loop has at least three instructions (likely a conditional
// branch, a comparison feeding that branch, and some kind of loop increment
// feeding that comparison instruction).
LoopSize = std::max(LoopSize, 3u);
return LoopSize;
}
// Returns the loop hint metadata node with the given name (for example,
// "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is
// returned.
static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {
if (MDNode *LoopID = L->getLoopID())
return GetUnrollMetadata(LoopID, Name);
return nullptr;
}
// Returns true if the loop has an unroll(full) pragma.
static bool HasUnrollFullPragma(const Loop *L) {
return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full");
}
// Returns true if the loop has an unroll(enable) pragma. This metadata is used
// for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives.
static bool HasUnrollEnablePragma(const Loop *L) {
return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable");
}
// Returns true if the loop has an unroll(disable) pragma.
static bool HasUnrollDisablePragma(const Loop *L) {
return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable");
}
// Returns true if the loop has an runtime unroll(disable) pragma.
static bool HasRuntimeUnrollDisablePragma(const Loop *L) {
return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable");
}
// If loop has an unroll_count pragma return the (necessarily
// positive) value from the pragma. Otherwise return 0.
static unsigned UnrollCountPragmaValue(const Loop *L) {
MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count");
if (MD) {
assert(MD->getNumOperands() == 2 &&
"Unroll count hint metadata should have two operands.");
unsigned Count =
mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
assert(Count >= 1 && "Unroll count must be positive.");
return Count;
}
return 0;
}
// Remove existing unroll metadata and add unroll disable metadata to
// indicate the loop has already been unrolled. This prevents a loop
// from being unrolled more than is directed by a pragma if the loop
// unrolling pass is run more than once (which it generally is).
static void SetLoopAlreadyUnrolled(Loop *L) {
MDNode *LoopID = L->getLoopID();
// First remove any existing loop unrolling metadata.
SmallVector<Metadata *, 4> MDs;
// Reserve first location for self reference to the LoopID metadata node.
MDs.push_back(nullptr);
if (LoopID) {
for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
bool IsUnrollMetadata = false;
MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
if (MD) {
const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
}
if (!IsUnrollMetadata)
MDs.push_back(LoopID->getOperand(i));
}
}
// Add unroll(disable) metadata to disable future unrolling.
LLVMContext &Context = L->getHeader()->getContext();
SmallVector<Metadata *, 1> DisableOperands;
DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
MDNode *DisableNode = MDNode::get(Context, DisableOperands);
MDs.push_back(DisableNode);
MDNode *NewLoopID = MDNode::get(Context, MDs);
// Set operand 0 to refer to the loop id itself.
NewLoopID->replaceOperandWith(0, NewLoopID);
L->setLoopID(NewLoopID);
}
static bool canUnrollCompletely(Loop *L, unsigned Threshold,
unsigned PercentDynamicCostSavedThreshold,
unsigned DynamicCostSavingsDiscount,
uint64_t UnrolledCost,
uint64_t RolledDynamicCost) {
if (Threshold == NoThreshold) {
DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n");
return true;
}
if (UnrolledCost <= Threshold) {
DEBUG(dbgs() << " Can fully unroll, because unrolled cost: "
<< UnrolledCost << "<" << Threshold << "\n");
return true;
}
assert(UnrolledCost && "UnrolledCost can't be 0 at this point.");
assert(RolledDynamicCost >= UnrolledCost &&
"Cannot have a higher unrolled cost than a rolled cost!");
// Compute the percentage of the dynamic cost in the rolled form that is
// saved when unrolled. If unrolling dramatically reduces the estimated
// dynamic cost of the loop, we use a higher threshold to allow more
// unrolling.
unsigned PercentDynamicCostSaved =
(uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost;
if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold &&
(int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <=
(int64_t)Threshold) {
DEBUG(dbgs() << " Can fully unroll, because unrolling will reduce the "
"expected dynamic cost by "
<< PercentDynamicCostSaved << "% (threshold: "
<< PercentDynamicCostSavedThreshold << "%)\n"
<< " and the unrolled cost (" << UnrolledCost
<< ") is less than the max threshold ("
<< DynamicCostSavingsDiscount << ").\n");
return true;
}
DEBUG(dbgs() << " Too large to fully unroll:\n");
DEBUG(dbgs() << " Threshold: " << Threshold << "\n");
DEBUG(dbgs() << " Max threshold: " << DynamicCostSavingsDiscount << "\n");
DEBUG(dbgs() << " Percent cost saved threshold: "
<< PercentDynamicCostSavedThreshold << "%\n");
DEBUG(dbgs() << " Unrolled cost: " << UnrolledCost << "\n");
DEBUG(dbgs() << " Rolled dynamic cost: " << RolledDynamicCost << "\n");
DEBUG(dbgs() << " Percent cost saved: " << PercentDynamicCostSaved
<< "\n");
return false;
}
// Returns true if unroll count was set explicitly.
// Calculates unroll count and writes it to UP.Count.
static bool computeUnrollCount(Loop *L, const TargetTransformInfo &TTI,
DominatorTree &DT, LoopInfo *LI,
ScalarEvolution *SE, unsigned TripCount,
unsigned TripMultiple, unsigned LoopSize,
TargetTransformInfo::UnrollingPreferences &UP) {
// BEInsns represents number of instructions optimized when "back edge"
// becomes "fall through" in unrolled loop.
// For now we count a conditional branch on a backedge and a comparison
// feeding it.
unsigned BEInsns = 2;
// Check for explicit Count.
// 1st priority is unroll count set by "unroll-count" option.
bool UserUnrollCount = UnrollCount.getNumOccurrences() > 0;
if (UserUnrollCount) {
UP.Count = UnrollCount;
UP.AllowExpensiveTripCount = true;
UP.Force = true;
if (UP.AllowRemainder &&
(LoopSize - BEInsns) * UP.Count + BEInsns < UP.Threshold)
return true;
}
// 2nd priority is unroll count set by pragma.
unsigned PragmaCount = UnrollCountPragmaValue(L);
if (PragmaCount > 0) {
UP.Count = PragmaCount;
UP.Runtime = true;
UP.AllowExpensiveTripCount = true;
UP.Force = true;
if (UP.AllowRemainder &&
(LoopSize - BEInsns) * UP.Count + BEInsns < PragmaUnrollThreshold)
return true;
}
bool PragmaFullUnroll = HasUnrollFullPragma(L);
if (PragmaFullUnroll && TripCount != 0) {
UP.Count = TripCount;
if ((LoopSize - BEInsns) * UP.Count + BEInsns < PragmaUnrollThreshold)
return false;
}
bool PragmaEnableUnroll = HasUnrollEnablePragma(L);
bool ExplicitUnroll = PragmaCount > 0 || PragmaFullUnroll ||
PragmaEnableUnroll || UserUnrollCount;
uint64_t UnrolledSize;
DebugLoc LoopLoc = L->getStartLoc();
Function *F = L->getHeader()->getParent();
LLVMContext &Ctx = F->getContext();
if (ExplicitUnroll && TripCount != 0) {
// If the loop has an unrolling pragma, we want to be more aggressive with
// unrolling limits. Set thresholds to at least the PragmaThreshold value
// which is larger than the default limits.
UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold);
UP.PartialThreshold =
std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold);
}
// 3rd priority is full unroll count.
// Full unroll make sense only when TripCount could be staticaly calculated.
// Also we need to check if we exceed FullUnrollMaxCount.
if (TripCount && TripCount <= UP.FullUnrollMaxCount) {
// When computing the unrolled size, note that BEInsns are not replicated
// like the rest of the loop body.
UnrolledSize = (uint64_t)(LoopSize - BEInsns) * TripCount + BEInsns;
if (canUnrollCompletely(L, UP.Threshold, 100, UP.DynamicCostSavingsDiscount,
UnrolledSize, UnrolledSize)) {
UP.Count = TripCount;
return ExplicitUnroll;
} else {
// The loop isn't that small, but we still can fully unroll it if that
// helps to remove a significant number of instructions.
// To check that, run additional analysis on the loop.
if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost(
L, TripCount, DT, *SE, TTI,
UP.Threshold + UP.DynamicCostSavingsDiscount))
if (canUnrollCompletely(L, UP.Threshold,
UP.PercentDynamicCostSavedThreshold,
UP.DynamicCostSavingsDiscount,
Cost->UnrolledCost, Cost->RolledDynamicCost)) {
UP.Count = TripCount;
return ExplicitUnroll;
}
}
}
// 4rd priority is partial unrolling.
// Try partial unroll only when TripCount could be staticaly calculated.
if (TripCount) {
if (UP.Count == 0)
UP.Count = TripCount;
UP.Partial |= ExplicitUnroll;
if (!UP.Partial) {
DEBUG(dbgs() << " will not try to unroll partially because "
<< "-unroll-allow-partial not given\n");
UP.Count = 0;
return false;
}
if (UP.PartialThreshold != NoThreshold) {
// Reduce unroll count to be modulo of TripCount for partial unrolling.
UnrolledSize = (uint64_t)(LoopSize - BEInsns) * UP.Count + BEInsns;
if (UnrolledSize > UP.PartialThreshold)
UP.Count = (std::max(UP.PartialThreshold, 3u) - BEInsns) /
(LoopSize - BEInsns);
if (UP.Count > UP.MaxCount)
UP.Count = UP.MaxCount;
while (UP.Count != 0 && TripCount % UP.Count != 0)
UP.Count--;
if (UP.AllowRemainder && UP.Count <= 1) {
// If there is no Count that is modulo of TripCount, set Count to
// largest power-of-two factor that satisfies the threshold limit.
// As we'll create fixup loop, do the type of unrolling only if
// remainder loop is allowed.
UP.Count = DefaultUnrollRuntimeCount;
UnrolledSize = (LoopSize - BEInsns) * UP.Count + BEInsns;
while (UP.Count != 0 && UnrolledSize > UP.PartialThreshold) {
UP.Count >>= 1;
UnrolledSize = (LoopSize - BEInsns) * UP.Count + BEInsns;
}
}
if (UP.Count < 2) {
if (PragmaEnableUnroll)
emitOptimizationRemarkMissed(
Ctx, DEBUG_TYPE, *F, LoopLoc,
"Unable to unroll loop as directed by unroll(enable) pragma "
"because unrolled size is too large.");
UP.Count = 0;
}
} else {
UP.Count = TripCount;
}
if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount &&
UP.Count != TripCount)
emitOptimizationRemarkMissed(
Ctx, DEBUG_TYPE, *F, LoopLoc,
"Unable to fully unroll loop as directed by unroll pragma because "
"unrolled size is too large.");
return ExplicitUnroll;
}
assert(TripCount == 0 &&
"All cases when TripCount is constant should be covered here.");
if (PragmaFullUnroll)
emitOptimizationRemarkMissed(
Ctx, DEBUG_TYPE, *F, LoopLoc,
"Unable to fully unroll loop as directed by unroll(full) pragma "
"because loop has a runtime trip count.");
// 5th priority is runtime unrolling.
// Don't unroll a runtime trip count loop when it is disabled.
if (HasRuntimeUnrollDisablePragma(L)) {
UP.Count = 0;
return false;
}
// Reduce count based on the type of unrolling and the threshold values.
UP.Runtime |= PragmaEnableUnroll || PragmaCount > 0 || UserUnrollCount;
if (!UP.Runtime) {
DEBUG(dbgs() << " will not try to unroll loop with runtime trip count "
<< "-unroll-runtime not given\n");
UP.Count = 0;
return false;
}
if (UP.Count == 0)
UP.Count = DefaultUnrollRuntimeCount;
UnrolledSize = (LoopSize - BEInsns) * UP.Count + BEInsns;
// Reduce unroll count to be the largest power-of-two factor of
// the original count which satisfies the threshold limit.
while (UP.Count != 0 && UnrolledSize > UP.PartialThreshold) {
UP.Count >>= 1;
UnrolledSize = (LoopSize - BEInsns) * UP.Count + BEInsns;
}
#ifndef NDEBUG
unsigned OrigCount = UP.Count;
#endif
if (!UP.AllowRemainder && UP.Count != 0 && (TripMultiple % UP.Count) != 0) {
while (UP.Count != 0 && TripMultiple % UP.Count != 0)
UP.Count >>= 1;
DEBUG(dbgs() << "Remainder loop is restricted (that could architecture "
"specific or because the loop contains a convergent "
"instruction), so unroll count must divide the trip "
"multiple, "
<< TripMultiple << ". Reducing unroll count from "
<< OrigCount << " to " << UP.Count << ".\n");
if (PragmaCount > 0 && !UP.AllowRemainder)
emitOptimizationRemarkMissed(
Ctx, DEBUG_TYPE, *F, LoopLoc,
Twine("Unable to unroll loop the number of times directed by "
"unroll_count pragma because remainder loop is restricted "
"(that could architecture specific or because the loop "
"contains a convergent instruction) and so must have an unroll "
"count that divides the loop trip multiple of ") +
Twine(TripMultiple) + ". Unrolling instead " + Twine(UP.Count) +
" time(s).");
}
if (UP.Count > UP.MaxCount)
UP.Count = UP.MaxCount;
DEBUG(dbgs() << " partially unrolling with count: " << UP.Count << "\n");
if (UP.Count < 2)
UP.Count = 0;
return ExplicitUnroll;
}
static bool tryToUnrollLoop(Loop *L, DominatorTree &DT, LoopInfo *LI,
ScalarEvolution *SE, const TargetTransformInfo &TTI,
AssumptionCache &AC, bool PreserveLCSSA,
Optional<unsigned> ProvidedCount,
Optional<unsigned> ProvidedThreshold,
Optional<bool> ProvidedAllowPartial,
Optional<bool> ProvidedRuntime) {
DEBUG(dbgs() << "Loop Unroll: F[" << L->getHeader()->getParent()->getName()
<< "] Loop %" << L->getHeader()->getName() << "\n");
if (HasUnrollDisablePragma(L)) {
return false;
}
unsigned NumInlineCandidates;
bool NotDuplicatable;
bool Convergent;
unsigned LoopSize = ApproximateLoopSize(
L, NumInlineCandidates, NotDuplicatable, Convergent, TTI, &AC);
DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n");
if (NotDuplicatable) {
DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable"
<< " instructions.\n");
return false;
}
if (NumInlineCandidates != 0) {
DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n");
return false;
}
// Find trip count and trip multiple if count is not available
unsigned TripCount = 0;
unsigned TripMultiple = 1;
// If there are multiple exiting blocks but one of them is the latch, use the
// latch for the trip count estimation. Otherwise insist on a single exiting
// block for the trip count estimation.
BasicBlock *ExitingBlock = L->getLoopLatch();
if (!ExitingBlock || !L->isLoopExiting(ExitingBlock))
ExitingBlock = L->getExitingBlock();
if (ExitingBlock) {
TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
}
TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences(
L, TTI, ProvidedThreshold, ProvidedCount, ProvidedAllowPartial,
ProvidedRuntime);
// If the loop contains a convergent operation, the prelude we'd add
// to do the first few instructions before we hit the unrolled loop
// is unsafe -- it adds a control-flow dependency to the convergent
// operation. Therefore restrict remainder loop (try unrollig without).
//
// TODO: This is quite conservative. In practice, convergent_op()
// is likely to be called unconditionally in the loop. In this
// case, the program would be ill-formed (on most architectures)
// unless n were the same on all threads in a thread group.
// Assuming n is the same on all threads, any kind of unrolling is
// safe. But currently llvm's notion of convergence isn't powerful
// enough to express this.
if (Convergent)
UP.AllowRemainder = false;
bool IsCountSetExplicitly = computeUnrollCount(L, TTI, DT, LI, SE, TripCount,
TripMultiple, LoopSize, UP);
if (!UP.Count)
return false;
// Unroll factor (Count) must be less or equal to TripCount.
if (TripCount && UP.Count > TripCount)
UP.Count = TripCount;
// Unroll the loop.
if (!UnrollLoop(L, UP.Count, TripCount, UP.Force, UP.Runtime,
UP.AllowExpensiveTripCount, TripMultiple, LI, SE, &DT, &AC,
PreserveLCSSA))
return false;
// If loop has an unroll count pragma or unrolled by explicitly set count
// mark loop as unrolled to prevent unrolling beyond that requested.
if (IsCountSetExplicitly)
SetLoopAlreadyUnrolled(L);
return true;
}
namespace {
class LoopUnroll : public LoopPass {
public:
static char ID; // Pass ID, replacement for typeid
LoopUnroll(Optional<unsigned> Threshold = None,
Optional<unsigned> Count = None,
Optional<bool> AllowPartial = None, Optional<bool> Runtime = None)
: LoopPass(ID), ProvidedCount(std::move(Count)),
ProvidedThreshold(Threshold), ProvidedAllowPartial(AllowPartial),
ProvidedRuntime(Runtime) {
initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
}
Optional<unsigned> ProvidedCount;
Optional<unsigned> ProvidedThreshold;
Optional<bool> ProvidedAllowPartial;
Optional<bool> ProvidedRuntime;
bool runOnLoop(Loop *L, LPPassManager &) override {
if (skipLoop(L))
return false;
Function &F = *L->getHeader()->getParent();
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
const TargetTransformInfo &TTI =
getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
return tryToUnrollLoop(L, DT, LI, SE, TTI, AC, PreserveLCSSA, ProvidedCount,
ProvidedThreshold, ProvidedAllowPartial,
ProvidedRuntime);
}
/// This transformation requires natural loop information & requires that
/// loop preheaders be inserted into the CFG...
///
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<AssumptionCacheTracker>();
AU.addRequired<TargetTransformInfoWrapperPass>();
// FIXME: Loop passes are required to preserve domtree, and for now we just
// recreate dom info if anything gets unrolled.
getLoopAnalysisUsage(AU);
}
};
}
char LoopUnroll::ID = 0;
INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(LoopPass)
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial,
int Runtime) {
// TODO: It would make more sense for this function to take the optionals
// directly, but that's dangerous since it would silently break out of tree
// callers.
return new LoopUnroll(Threshold == -1 ? None : Optional<unsigned>(Threshold),
Count == -1 ? None : Optional<unsigned>(Count),
AllowPartial == -1 ? None
: Optional<bool>(AllowPartial),
Runtime == -1 ? None : Optional<bool>(Runtime));
}
Pass *llvm::createSimpleLoopUnrollPass() {
return llvm::createLoopUnrollPass(-1, -1, 0, 0);
}
| sawenzel/root | interpreter/llvm/src/lib/Transforms/Scalar/LoopUnrollPass.cpp | C++ | lgpl-2.1 | 43,203 |
############################################################################
##
## Copyright (C) 2016 The Qt Company Ltd.
## Contact: https://www.qt.io/licensing/
##
## This file is part of the examples of PySide2.
##
## $QT_BEGIN_LICENSE:BSD$
## 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 https://www.qt.io/terms-conditions. For further
## information use the contact form at https://www.qt.io/contact-us.
##
## BSD License Usage
## Alternatively, you may use this file under the terms of the BSD license
## as follows:
##
## "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 The Qt Company Ltd nor the names of its
## contributors may be used to endorse or promote products derived
## from this software without specific prior written permission.
##
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
##
## $QT_END_LICENSE$
##
############################################################################
//! [0]
def __init__(self, parent):
QSpinBox.__init__(self, parent)
//! [0]
//! [1]
def valueFromText(self, text):
regExp = QRegExp(tr("(\\d+)(\\s*[xx]\\s*\\d+)?"))
if regExp.exactMatch(text):
return regExp.cap(1).toInt()
else:
return 0
//! [1]
//! [2]
def textFromValue(self, value):
return self.tr("%1 x %1").arg(value)
//! [2]
| qtproject/pyside-pyside | doc/codesnippets/examples/widgets/icons/iconsizespinbox.cpp | C++ | lgpl-2.1 | 2,818 |
package islam.adhanalarm.widget;
import islam.adhanalarm.Schedule;
import islam.adhanalarm.util.LocaleManager;
import uz.efir.muazzin.Muazzin;
import uz.efir.muazzin.R;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.text.format.DateFormat;
import android.widget.RemoteViews;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
public class NextNotificationWidgetProvider extends AppWidgetProvider {
private static final int[] times = new int[] { R.string.fajr, R.string.sunrise, R.string.dhuhr,
R.string.asr, R.string.maghrib, R.string.ishaa, R.string.next_fajr };
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
setNextTime(context, appWidgetManager, appWidgetIds);
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
public static void setNextTime(Context context) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context,
NextNotificationWidgetProvider.class));
setNextTime(context, appWidgetManager, appWidgetIds);
}
private static void setNextTime(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
LocaleManager lm = LocaleManager.getInstance(context, false);
SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a", lm.getLocale(context));
if (DateFormat.is24HourFormat(context)) {
timeFormat = new SimpleDateFormat("k:mm", lm.getLocale(context));
}
final int nextTimeIndex = Schedule.today(context).nextTimeIndex();
final GregorianCalendar nextTime = Schedule.today(context).getTimes()[nextTimeIndex];
for (int i = 0; i < appWidgetIds.length; i++) {
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_next_notification);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context,
Muazzin.class), 0);
views.setOnClickPendingIntent(R.id.widget_next_notification, pendingIntent);
views.setTextViewText(R.id.time_name, context.getString(times[nextTimeIndex]));
views.setTextViewText(R.id.next_notification, timeFormat.format(nextTime.getTime()));
appWidgetManager.updateAppWidget(appWidgetIds[i], views);
}
}
}
| ozbek/al-muazzin | app/src/main/java/islam/adhanalarm/widget/NextNotificationWidgetProvider.java | Java | lgpl-2.1 | 2,682 |
/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "Material.h"
#include "SubProblem.h"
#include "MaterialData.h"
// system includes
#include <iostream>
template<>
InputParameters validParams<Material>()
{
InputParameters params = validParams<MooseObject>();
params += validParams<BlockRestrictable>();
params += validParams<BoundaryRestrictable>();
params.addParam<bool>("use_displaced_mesh", false, "Whether or not this object should use the displaced mesh for computation. Note that in the case this is true but no displacements are provided in the Mesh block the undisplaced mesh will still be used.");
// Outputs
params += validParams<OutputInterface>();
params.set<std::vector<OutputName> >("outputs") = std::vector<OutputName>(1, "none");
params.addParam<std::vector<std::string> >("output_properties", "List of material properties, from this material, to output (outputs must also be defined to an output type)");
params.addParamNamesToGroup("outputs output_properties", "Outputs");
params.addParamNamesToGroup("use_displaced_mesh", "Advanced");
params.registerBase("Material");
return params;
}
Material::Material(const std::string & name, InputParameters parameters) :
MooseObject(name, parameters),
BlockRestrictable(name, parameters),
BoundaryRestrictable(name, parameters),
SetupInterface(parameters),
Coupleable(parameters, false),
MooseVariableDependencyInterface(),
ScalarCoupleable(parameters),
FunctionInterface(parameters),
UserObjectInterface(parameters),
TransientInterface(parameters, name, "materials"),
MaterialPropertyInterface(name, parameters),
PostprocessorInterface(parameters),
DependencyResolverInterface(),
Restartable(name, parameters, "Materials"),
ZeroInterface(parameters),
MeshChangedInterface(parameters),
// The false flag disables the automatic call buildOutputVariableHideList;
// for Material objects the hide lists are handled by MaterialOutputAction
OutputInterface(name, parameters, false),
_subproblem(*parameters.get<SubProblem *>("_subproblem")),
_fe_problem(*parameters.get<FEProblem *>("_fe_problem")),
_tid(parameters.get<THREAD_ID>("_tid")),
_assembly(_subproblem.assembly(_tid)),
_bnd(parameters.get<bool>("_bnd")),
_neighbor(getParam<bool>("_neighbor")),
_material_data(*parameters.get<MaterialData *>("_material_data")),
_qp(std::numeric_limits<unsigned int>::max()),
_qrule(_bnd ? _assembly.qRuleFace() : _assembly.qRule()),
_JxW(_bnd ? _assembly.JxWFace() : _assembly.JxW()),
_coord(_assembly.coordTransformation()),
_q_point(_bnd ? _assembly.qPointsFace() : _assembly.qPoints()),
_normals(_assembly.normals()),
_current_elem(_neighbor ? _assembly.neighbor() : _assembly.elem()),
_current_side(_neighbor ? _assembly.neighborSide() : _assembly.side()),
_mesh(_subproblem.mesh()),
_coord_sys(_assembly.coordSystem()),
_has_stateful_property(false)
{
// Fill in the MooseVariable dependencies
const std::vector<MooseVariable *> & coupled_vars = getCoupledMooseVars();
for (unsigned int i=0; i<coupled_vars.size(); i++)
addMooseVariableDependency(coupled_vars[i]);
}
Material::~Material()
{
}
void
Material::computeProperties()
{
for (_qp = 0; _qp < _qrule->n_points(); ++_qp)
computeQpProperties();
}
void
Material::initStatefulProperties(unsigned int n_points)
{
if (_has_stateful_property)
for (_qp = 0; _qp < n_points; ++_qp)
initQpStatefulProperties();
}
void
Material::initQpStatefulProperties()
{
mooseDoOnce(mooseWarning(std::string("Material \"") + _name + "\" declares one or more stateful properties but initQpStatefulProperties() was not overridden in the derived class."));
}
void
Material::computeQpProperties()
{
}
void
Material::timeStepSetup()
{}
QpData *
Material::createData()
{
return NULL;
}
void
Material::checkStatefulSanity() const
{
for (std::map<std::string, int>::const_iterator it = _props_to_flags.begin(); it != _props_to_flags.end(); ++it)
{
if (static_cast<int>(it->second) % 2 == 0) // Only Stateful properties declared!
mooseError("Material '" << _name << "' has stateful properties declared but not associated \"current\" properties." << it->second);
}
}
void
Material::registerPropName(std::string prop_name, bool is_get, Material::Prop_State state)
{
if (!is_get)
{
_props_to_flags[prop_name] |= static_cast<int>(state);
if (static_cast<int>(state) % 2 == 0)
_has_stateful_property = true;
}
// Store material properties for block ids
for (std::set<SubdomainID>::const_iterator it = blockIDs().begin(); it != blockIDs().end(); ++it)
{
// Only save this prop as a "supplied" prop is it was registered as a result of a call to declareProperty not getMaterialProperty
if (!is_get)
_supplied_props.insert(prop_name);
_fe_problem.storeMatPropName(*it, prop_name);
_subproblem.storeMatPropName(*it, prop_name);
}
// Store material properties for the boundary ids
for (std::set<BoundaryID>::const_iterator it = boundaryIDs().begin(); it != boundaryIDs().end(); ++it)
{
/// \todo{see ticket #2192}
// Only save this prop as a "supplied" prop is it was registered as a result of a call to declareProperty not getMaterialProperty
if (!is_get)
_supplied_props.insert(prop_name);
_fe_problem.storeMatPropName(*it, prop_name);
_subproblem.storeMatPropName(*it, prop_name);
}
}
std::set<OutputName>
Material::getOutputs()
{
return std::set<OutputName>(getParam<std::vector<OutputName> >("outputs").begin(), getParam<std::vector<OutputName> >("outputs").end());
}
| cpritam/moose | framework/src/materials/Material.C | C++ | lgpl-2.1 | 6,500 |
package com.loovjo.bloovtech.tileentity;
import net.minecraft.tileentity.TileEntity;
public class TileEntityInfuser extends TileEntity {
}
| loovjo/Bloovtech | src/main/java/com/loovjo/bloovtech/tileentity/TileEntityInfuser.java | Java | lgpl-2.1 | 142 |
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
Daf-collage is made up of two Moodle modules which help in the process of
German language learning. It facilitates the content organization like
vocabulary or the main grammar features and gives the chance to create
exercises in order to consolidate knowledge.
Copyright (C) 2011
Coordination:
Ruth Burbat
Source code:
Francisco Javier Rodríguez López (seiyadesagitario@gmail.com)
Simeón Ruiz Romero (simeonruiz@gmail.com)
Serafina Molina Soto(finamolinasoto@gmail.com)
Original idea:
Ruth Burbat
Content design:
Ruth Burbat
AInmaculada Almahano Güeto
Andrea Bies
Julia Möller Runge
Blanca Rodríguez Gómez
Antonio Salmerón Matilla
María José Varela Salinas
Karin Vilar Sánchez
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. */
require_once("../../config.php");
require_once("lib.php");
require_once("ejercicios_clase_general.php");
require_once("ejercicios_form_creacion.php");
require_once("YoutubeVideoHelper.php");
$id_curso = optional_param('id_curso', 0, PARAM_INT);
$id_ejercicio = optional_param('id_ejercicio', 0, PARAM_INT);
$tipo_origen = optional_param('tipo_origen', 0, PARAM_INT);
$tipo_respuesta = optional_param('tr', 0, PARAM_INT);
$tipo_creacion = optional_param('tipocreacion', 0, PARAM_INT);
ECHO "MODIFICANDO";
$mform = new mod_ejercicios_mostrar_ejercicio_asociacion_simple($id_curso, $id_ejercicio, $tipo_origen, $tipo_respuesta, $tipocreacion);
$mform->mostrar_ejercicio_asociacion_simple($id_curso, $id_ejercicio, 0, $tipo_origen, $tipo_respuesta, $tipocreacion);
$numeropreguntas = optional_param('num_preg', 0, PARAM_INT);
echo "El numero de pregunas es" . $numeropreguntas;
$ejercicio_general = new Ejercicios_general();
$miejercicio=$ejercicio_general->obtener_uno($id_ejercicio);
$miejercicio->set_numpregunta($numeropreguntas);
$fuentes = optional_param('fuentes',PARAM_TEXT);
$miejercicio->set_fuentes($fuentes);
$miejercicio->alterar();
begin_sql();
if ($tipo_origen == 1) { //la pregunta es un texto
if ($tipo_respuesta == 1) {//Es un texto
//obtengo los id de las preguntas del ejercicio
$id_preguntas = array();
$mis_preguntas = new Ejercicios_texto_texto_preg();
$id_preguntas = $mis_preguntas->obtener_todas_preguntas_ejercicicio($id_ejercicio);
//borro las respuestas
for ($s = 0; $s < sizeof($id_preguntas); $s++) {
delete_records('ejercicios_texto_texto_resp', 'id_pregunta', $id_preguntas[$s]->get('id'));
}
} else {
if ($tipo_respuesta == 2) { //la respuesta es un audio
echo "actualizando audio";
//obtengo los id de las preguntas del ejercicio
$id_preguntas = array();
$mis_preguntas = new Ejercicios_texto_texto_preg();
$id_preguntas = $mis_preguntas->obtener_todas_preguntas_ejercicicio($id_ejercicio);
//borro las respuestas
for ($s = 0; $s < sizeof($id_preguntas); $s++) {
delete_records('ejercicios_audios_asociados', 'id_ejercicio', $id_ejercicio);
}
} else {
if ($tipo_respuesta == 3) {//video
echo "actualizando video";
//obtengo los id de las preguntas del ejercicio
$id_preguntas = array();
$mis_preguntas = new Ejercicios_texto_texto_preg();
$id_preguntas = $mis_preguntas->obtener_todas_preguntas_ejercicicio($id_ejercicio);
//borro las respuestas
for ($s = 0; $s < sizeof($id_preguntas); $s++) {
delete_records('ejercicios_videos_asociados', 'id_ejercicio', $id_ejercicio);
}
} else {
if ($tipo_respuesta == 4) {
echo "actualizando imagen";
//obtengo los id de las preguntas del ejercicio
$id_preguntas = array();
$mis_preguntas = new Ejercicios_texto_texto_preg();
$id_preguntas = $mis_preguntas->obtener_todas_preguntas_ejercicicio($id_ejercicio);
//borro las respuestas
for ($s = 0; $s < sizeof($id_preguntas); $s++) {
delete_records('ejercicios_imagenes_asociadas', 'id_ejercicio', $id_ejercicio);
}
}
}
}
}
//borro las preguntas
delete_records('ejercicios_texto_texto_preg', 'id_ejercicio', $id_ejercicio);
} else {
if ($tipo_origen == 2) { //Pregunta es un Audio
//borro las preguntas
$id_preguntas = array();
$mis_preguntas = new Ejercicios_texto_texto_preg();
$id_preguntas = $mis_preguntas->obtener_todas_preguntas_ejercicicio($id_ejercicio);
//borro las respuestas
for ($s = 0; $s < sizeof($id_preguntas); $s++) {
delete_records('ejercicios_audios_asociados', 'id_ejercicio', $id_ejercicio);
}
if ($tipo_respuesta == 1) { //La respuesta es un texto
//borro las respuestas
delete_records('ejercicios_texto_texto_preg', 'id_ejercicio', $id_ejercicio);
}
} else {
if ($tipo_origen == 3) {//video
echo "actualizando video";
//obtengo los id de las preguntas del ejercicio
$id_preguntas = array();
$mis_preguntas = new Ejercicios_texto_texto_preg();
$id_preguntas = $mis_preguntas->obtener_todas_preguntas_ejercicicio($id_ejercicio);
//borro las respuestas
for ($s = 0; $s < sizeof($id_preguntas); $s++) {
delete_records('ejercicios_videos_asociados', 'id_ejercicio', $id_ejercicio);
}
if ($tipo_respuesta == 1) { //La respuesta es un texto
//borro las respuestas
delete_records('ejercicios_texto_texto_preg', 'id_ejercicio', $id_ejercicio);
}
}
else if ($tipo_origen==4) //La pregunta es una imagen
{
if ($tipo_respuesta == 1) { //La respuesta es un texto
echo "actualizando imagen";
//obtengo los id de las preguntas del ejercicio
$id_preguntas = array();
$mis_preguntas = new Ejercicios_texto_texto_preg();
$id_preguntas = $mis_preguntas->obtener_todas_preguntas_ejercicicio($id_ejercicio);
//borro las respuestas
for ($s = 0; $s < sizeof($id_preguntas); $s++) {
delete_records('ejercicios_imagenes_asociadas', 'id_ejercicio', $id_ejercicio);
}
delete_records('ejercicios_texto_texto_preg', 'id_ejercicio', $id_ejercicio);
echo 'Borradas imagenes';
}
}
}
}
//Guardo las nuevas
for ($i = 0; $i < $numeropreguntas; $i++) {
//Obtengo el numero de respuestas a cada pregunta
$j = $i + 1;
if ($tipo_origen == 1) { //Si la pregunta es un texto
$preg = required_param('pregunta' . $j, PARAM_TEXT);
$ejercicio_texto_preg = new Ejercicios_texto_texto_preg(NULL, $id_ejercicio, $preg);
$id_pregunta = $ejercicio_texto_preg->insertar();
if ($tipo_respuesta == 1) { //Si la respuesta es un texto
$resp = required_param('respuesta' . $j, PARAM_TEXT);
$correcta = 0;
$ejercicio_texto_resp = new Ejercicios_texto_texto_resp(NULL, $id_pregunta, $resp, $correcta);
$ejercicio_texto_resp->insertar();
} else {
if ($tipo_respuesta == 2) { //es un audio
$ejercicio_texto_audio = new Ejercicios_audios_asociados($NULL, $id_ejercicio, $id_pregunta, 'audio_' . $id_ejercicio . "_" . $j . ".mp3");
$ejercicio_texto_audio->insertar();
} else {
if ($tipo_respuesta == 3) { //ES UN VIDEO
$resp = YoutubeVideoHelper::getVideoId(required_param('archivovideo' . $j, PARAM_TEXT));
echo "archivo video" . $resp;
$ejercicio_texto_video = new Ejercicios_videos_asociados(NULL, $id_ejercicio, $id_pregunta, $resp);
$ejercicio_texto_video->insertar();
} else {
if ($tipo_respuesta == 4) { //eS UNA IMAGEN
$ejercicio_texto_img = new Ejercicios_imagenes_asociadas($NULL, $id_ejercicio, $id_pregunta, 'foto_' . $id_ejercicio . "_" . $j . ".jpg");
$ejercicio_texto_img->insertar();
}
}
}
}
} else {
if ($tipo_origen == 2) { //la pregunta es un audio
// echo "entra";
$preg = required_param('pregunta' . $j, PARAM_TEXT);
$ejercicio_texto_preg = new Ejercicios_texto_texto_preg(NULL, $id_ejercicio, $preg);
$id_pregunta = $ejercicio_texto_preg->insertar();
if ($tipo_respuesta == 1) { //la respuesta es un texto
// echo "entra 2";
$ejercicio_texto_audio = new Ejercicios_audios_asociados($NULL, $id_ejercicio, $id_pregunta, 'audio_' . $id_ejercicio . "_" . $j . ".mp3");
$ejercicio_texto_audio->insertar();
}
} else {
if ($tipo_origen == 3) { //ES UN VIDEO
if (YoutubeVideoHelper::getVideoId(required_param('archivovideo' . $j, PARAM_TEXT)) != null){
$preg = required_param('pregunta' . $j, PARAM_TEXT);
$ejercicio_texto_preg = new Ejercicios_texto_texto_preg(NULL, $id_ejercicio, $preg);
$id_pregunta = $ejercicio_texto_preg->insertar();
$resp = YoutubeVideoHelper::getVideoId(required_param('archivovideo' . $j, PARAM_TEXT));
echo "archivo video" . $resp;
$ejercicio_texto_video = new Ejercicios_videos_asociados(NULL, $id_ejercicio, $id_pregunta, $resp);
$ejercicio_texto_video->insertar();
echo "insertado";
}
}
else if ($tipo_origen == 4) { // ES UNA IMAGEN
if ($tipo_respuesta == 1) { //La respuesta es un texto
$preg = required_param('pregunta' . $j, PARAM_TEXT);
$ejercicio_texto_preg = new Ejercicios_texto_texto_preg(NULL, $id_ejercicio, $preg);
$id_pregunta = $ejercicio_texto_preg->insertar();
$ejercicio_texto_img = new Ejercicios_imagenes_asociadas($NULL, $id_ejercicio, $id_pregunta, 'foto_' . $id_ejercicio . "_" . $j . ".jpg");
$ejercicio_texto_img->insertar();
}
}
}
}
}
commit_sql();
redirect('./view.php?id=' . $id_curso . '&opcion=9');
?>
| seiya64/dafcollage | ejercicios/ejercicios_modificar_asociacion_simple.php | PHP | lgpl-2.1 | 11,528 |
<?php
/**
* Limb Web Application Framework
*
* @link http://limb-project.com
*
* @copyright Copyright © 2004-2009 BIT
* @license LGPL http://www.gnu.org/copyleft/lesser.html
* @version $Id$
* @package web_app
*/
lmb_require('limb/web_app/src/controller/lmbController.class.php');
lmb_require('limb/view/src/wact/lmbWactHighlightHandler.class.php');
require_once('limb/view/lib/XML/HTMLSax3.php');
abstract class lmbWactTemplateSourceController extends lmbController
{
protected $template_for_hackers = 'template_source/error.html';
protected $history = array();
protected $highlight_page_url = 'wact_template_source';
function doDisplay()
{
require_once('limb/wact/src/compiler/templatecompiler.inc.php');
require_once('limb/view/src/lmbWactView.class.php');
$this->setTemplate('template_source/display.html');
if(($t = $this->request->get('t')) && is_array($t) && sizeof($t) > 0)
{
$this->history = $t;
$template_path = end($this->history);
}
else
{
$this->setTemplate($this->template_for_hackers);
return;
}
if(substr($template_path, -5, 5) != '.html')
$template_path = $this->template_for_hackers;
$wact_locator = $this->toolkit->getWactLocator();
if(!$source_file_path = $wact_locator->locateSourceTemplate($template_path))
{
$this->setTemplate($this->template_for_hackers);
return;
}
$template_contents = file_get_contents($source_file_path);
if(sizeof($this->history) > 1)
{
$tmp_history = $this->history;
$from_template_path = $tmp_history[sizeof($tmp_history) - 2];
$tmp_history = array_splice($tmp_history, 0, sizeof($tmp_history) - 1);
$history_query = 't[]=' . implode('&t[]=', $tmp_history);
$this->view->set('history_query', $this->highlight_page_url . '?' .$history_query);
$this->view->set('from_template_path', $from_template_path);
}
$this->view->set('template_path', $template_path);
$this->view->set('this_template_path', $this->view->getTemplate());
$this->view->set('template_content', $this->_processTemplateContent($template_contents));
}
function _processTemplateContent($template_contents)
{
$compiler = $this->view->getWactTemplate()->createCompiler();
$tag_dictionary = $compiler->getTagDictionary();
$parser = new XML_HTMLSax3();
$handler = new lmbWactHighlightHandler($tag_dictionary, $this->highlight_page_url);
$handler->setTemplatePathHistory($this->history);
$parser->set_object($handler);
$parser->set_element_handler('openHandler','closeHandler');
$parser->set_data_handler('dataHandler');
$parser->set_escape_handler('escapeHandler');
$parser->parse($template_contents);
$html = $handler->getHtml();
return $html;
}
}
| knevcher/limb | web_app/src/controller/lmbWactTemplateSourceController.class.php | PHP | lgpl-2.1 | 2,939 |
"""
ECE 4564
Final Project
Team: Immortal
Title: HomeGuard - Home Visitors Detection and Alert System
Filename: publisher.py
Members: Arun Rai, Mohammad Islam, and Yihan Pang
Date: 11/26/2014
---------------------------------------------------------------------
Description:
1. Receive host user information, and send it to the subscriber.
2. Receive visitors' message and send it to the subscriber.
3. Receive sensor reading, and send trigger signal to camera to the subscriber.
Network protocols: TCP/IP and AMQP
---------------------------------------------------------------------
"""
#!/usr/bin/python
import sys
import threading
from infoSetup import infoSetup
from getSensorData import getSensorData
from setVisitorMessage import setVisitorMessage
import time
import signal
import socket
import json
""" Default host IP address and port number """
HOST = "127.0.0.1"
PORT = 9000
class HostInformation:
def __init__(self):
self.senderNumber = '';
self.receiverNumber = ''
self.receiverEmail = 'sangpang20@gmail.com';
self.loop = True;
self.s = '';
self.emailOnly = True;
self.smsOnly = False;
self.both = False;
self.Message = {};
self.msgSignal = False;
""" Set receiver's phone number """
def setPhoneNumber(self, number):
self.receiverNumber = number;
self.smsOnly = True;
self.emailOnly = False;
self.both = False;
""" Set receiver's email id """
def setEmail(self, email):
self.receiverEmail = email;
self.emailOnly = True;
self.smsOnly = False;
self.both = False;
""" Set both email and phone nubmer """
def setBoth(self, email, phone):
self.receiverEmail = email;
self.receiverNumber = phone;
self.both = True;
self.emailOnly = False;
self.smsOnly = False;
def getReceiverNumber(self):
return self.receiverNumber;
def getReceiverEmail(self):
return self.receiverEmail;
def getSenderEmail(self):
return self.senderEmail;
def getSenderEmailPass(self):
return self.senderPassword;
def messageInEmail(self):
return self.emailOnly;
def messageInSms(self):
return self.smsOnly;
def messageInBoth(self):
return self.both;
def setLoopState(self, signal=None, frame=None):
print 'Gracefully closing the socket .................'
self.loop = False;
self.s.close();
""" Here, the message is of type dictionary """
def setMessage(self, message):
self.Message = message;
def getMessage(self):
return self.Message;
def setMessageSignal(self, sig):
self.msgSignal = sig;
def getMessageSignal(self):
return self.msgSignal;
def getLoopState(self):
return self.loop;
""" The function is called before the program exits
for gracefully closing the socket when user enters
Ctrl + c. """
def closeSocket(self, s):
self.s = s;
def main():
setHostInfo = HostInformation()
""" Sensor thread: sensor reading is performed"""
sensorThread = threading.Thread(target = getSensorData, args = [setHostInfo,]);
""" start the thread """
sensorThread.start()
""" Setup signal handlers to shutdown this app when SIGINT
or SIGTERM is sent to this app """
signal_num = signal.SIGINT
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
""" main thread """
while setHostInfo.getLoopState():
try:
setHostInfo.closeSocket(s);
signal.signal(signal_num, setHostInfo.setLoopState)
signal_num = signal.SIGTERM
signal.signal(signal_num, setHostInfo.setLoopState)
except ValueError as error1:
print "Warning: Greceful shutdown may not be possible: Unsupported"
print "Signal: " + signal_num
conn, addr = s.accept()
message = conn.recv(1024)
if len(message) > 3:
if message[0] == '$' and message[1] == '$' and message[2] == '$':
setVisitorMessage(setHostInfo, message)
else:
infoSetup(setHostInfo, message)
except socket.error, se:
print 'connection failed/socket closed. \n', se
if s:
s.close();
sensorThread.join()
if __name__ == '__main__':
main();
| raiarun/HomeGuard | publisher.py | Python | lgpl-2.1 | 4,016 |
<?php
/*"******************************************************************************************************
* (c) 2016 by Kajona, www.kajona.de *
* Published under the GNU LGPL v2.1, see /system/licence_lgpl.txt *
********************************************************************************************************/
/**
* @deprecated
*/
class class_pdf_tcpdf extends Kajona\Pdf\System\PdfTcpdf
{
}
| kajona/kajonacms | module_pdf/legacy/class_pdf_tcpdf.php | PHP | lgpl-2.1 | 516 |
#!/usr/bin/env python
#
# Generated Thu Jul 22 14:11:34 2010 by generateDS.py.
#
import sys
import getopt
from xml.dom import minidom
from xml.dom import Node
#
# If you have installed IPython you can uncomment and use the following.
# IPython is available from http://ipython.scipy.org/.
#
## from IPython.Shell import IPShellEmbed
## args = ''
## ipshell = IPShellEmbed(args,
## banner = 'Dropping into IPython',
## exit_msg = 'Leaving Interpreter, back to program.')
# Then use the following line where and when you want to drop into the
# IPython shell:
# ipshell('<some message> -- Entering ipshell.\nHit Ctrl-D to exit')
#
# Support/utility functions.
#
def showIndent(outfile, level):
for idx in range(level):
outfile.write(' ')
def quote_xml(inStr):
s1 = inStr
s1 = s1.replace('&', '&')
s1 = s1.replace('<', '<')
s1 = s1.replace('"', '"')
return s1
def quote_python(inStr):
s1 = inStr
if s1.find("'") == -1:
if s1.find('\n') == -1:
return "'%s'" % s1
else:
return "'''%s'''" % s1
else:
if s1.find('"') != -1:
s1 = s1.replace('"', '\\"')
if s1.find('\n') == -1:
return '"%s"' % s1
else:
return '"""%s"""' % s1
class MixedContainer:
# Constants for category:
CategoryNone = 0
CategoryText = 1
CategorySimple = 2
CategoryComplex = 3
# Constants for content_type:
TypeNone = 0
TypeText = 1
TypeString = 2
TypeInteger = 3
TypeFloat = 4
TypeDecimal = 5
TypeDouble = 6
TypeBoolean = 7
def __init__(self, category, content_type, name, value):
self.category = category
self.content_type = content_type
self.name = name
self.value = value
def getCategory(self):
return self.category
def getContenttype(self, content_type):
return self.content_type
def getValue(self):
return self.value
def getName(self):
return self.name
def export(self, outfile, level, name):
if self.category == MixedContainer.CategoryText:
outfile.write(self.value)
elif self.category == MixedContainer.CategorySimple:
self.exportSimple(outfile, level, name)
else: # category == MixedContainer.CategoryComplex
self.value.export(outfile, level, name)
def exportSimple(self, outfile, level, name):
if self.content_type == MixedContainer.TypeString:
outfile.write('<%s>%s</%s>' % (self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeInteger or \
self.content_type == MixedContainer.TypeBoolean:
outfile.write('<%s>%d</%s>' % (self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeFloat or \
self.content_type == MixedContainer.TypeDecimal:
outfile.write('<%s>%f</%s>' % (self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeDouble:
outfile.write('<%s>%g</%s>' % (self.name, self.value, self.name))
def exportLiteral(self, outfile, level, name):
if self.category == MixedContainer.CategoryText:
showIndent(outfile, level)
outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \
(self.category, self.content_type, self.name, self.value))
elif self.category == MixedContainer.CategorySimple:
showIndent(outfile, level)
outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \
(self.category, self.content_type, self.name, self.value))
else: # category == MixedContainer.CategoryComplex
showIndent(outfile, level)
outfile.write('MixedContainer(%d, %d, "%s",\n' % \
(self.category, self.content_type, self.name,))
self.value.exportLiteral(outfile, level + 1)
showIndent(outfile, level)
outfile.write(')\n')
#
# Data representation classes.
#
class GenerateModel:
subclass = None
def __init__(self, Module=None, PythonExport=None):
if Module is None:
self.Module = []
else:
self.Module = Module
if PythonExport is None:
self.PythonExport = []
else:
self.PythonExport = PythonExport
def factory(*args_, **kwargs_):
if GenerateModel.subclass:
return GenerateModel.subclass(*args_, **kwargs_)
else:
return GenerateModel(*args_, **kwargs_)
factory = staticmethod(factory)
def getModule(self): return self.Module
def setModule(self, Module): self.Module = Module
def addModule(self, value): self.Module.append(value)
def insertModule(self, index, value): self.Module[index] = value
def getPythonexport(self): return self.PythonExport
def setPythonexport(self, PythonExport): self.PythonExport = PythonExport
def addPythonexport(self, value): self.PythonExport.append(value)
def insertPythonexport(self, index, value): self.PythonExport[index] = value
def export(self, outfile, level, name_='GenerateModel'):
showIndent(outfile, level)
outfile.write('<%s>\n' % name_)
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write('</%s>\n' % name_)
def exportAttributes(self, outfile, level, name_='GenerateModel'):
pass
def exportChildren(self, outfile, level, name_='GenerateModel'):
for Module_ in self.getModule():
Module_.export(outfile, level)
for PythonExport_ in self.getPythonexport():
PythonExport_.export(outfile, level)
def exportLiteral(self, outfile, level, name_='GenerateModel'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Module=[\n')
level += 1
for Module in self.Module:
showIndent(outfile, level)
outfile.write('Module(\n')
Module.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('PythonExport=[\n')
level += 1
for PythonExport in self.PythonExport:
showIndent(outfile, level)
outfile.write('PythonExport(\n')
PythonExport.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Module':
obj_ = Module.factory()
obj_.build(child_)
self.Module.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'PythonExport':
obj_ = PythonExport.factory()
obj_.build(child_)
self.PythonExport.append(obj_)
# end class GenerateModel
class PythonExport:
subclass = None
def __init__(self, FatherNamespace='', RichCompare=0, Name='', Reference=0, FatherInclude='', Father='', Namespace='', Twin='', Constructor=0, TwinPointer='', Include='', NumberProtocol=0, Delete=0, Documentation=None, Methode=None, Attribute=None, Sequence=None, CustomAttributes='', ClassDeclarations='', Initialization=0):
self.FatherNamespace = FatherNamespace
self.RichCompare = RichCompare
self.Name = Name
self.Reference = Reference
self.FatherInclude = FatherInclude
self.Father = Father
self.Namespace = Namespace
self.Twin = Twin
self.Constructor = Constructor
self.TwinPointer = TwinPointer
self.Include = Include
self.NumberProtocol = NumberProtocol
self.Delete = Delete
self.Documentation = Documentation
self.Initialization = Initialization
if Methode is None:
self.Methode = []
else:
self.Methode = Methode
if Attribute is None:
self.Attribute = []
else:
self.Attribute = Attribute
self.Sequence = Sequence
self.CustomAttributes = CustomAttributes
self.ClassDeclarations = ClassDeclarations
def factory(*args_, **kwargs_):
if PythonExport.subclass:
return PythonExport.subclass(*args_, **kwargs_)
else:
return PythonExport(*args_, **kwargs_)
factory = staticmethod(factory)
def getInitialization(self): return self.Initialization
def setInitialization(self, Initialization): self.Initialization = Initialization
def getDocumentation(self): return self.Documentation
def setDocumentation(self, Documentation): self.Documentation = Documentation
def getMethode(self): return self.Methode
def setMethode(self, Methode): self.Methode = Methode
def addMethode(self, value): self.Methode.append(value)
def insertMethode(self, index, value): self.Methode[index] = value
def getAttribute(self): return self.Attribute
def setAttribute(self, Attribute): self.Attribute = Attribute
def addAttribute(self, value): self.Attribute.append(value)
def insertAttribute(self, index, value): self.Attribute[index] = value
def getSequence(self): return self.Sequence
def setSequence(self, Sequence): self.Sequence = Sequence
def getCustomattributes(self): return self.CustomAttributes
def setCustomattributes(self, CustomAttributes): self.CustomAttributes = CustomAttributes
def getClassdeclarations(self): return self.ClassDeclarations
def setClassdeclarations(self, ClassDeclarations): self.ClassDeclarations = ClassDeclarations
def getFathernamespace(self): return self.FatherNamespace
def setFathernamespace(self, FatherNamespace): self.FatherNamespace = FatherNamespace
def getRichcompare(self): return self.RichCompare
def setRichcompare(self, RichCompare): self.RichCompare = RichCompare
def getName(self): return self.Name
def setName(self, Name): self.Name = Name
def getReference(self): return self.Reference
def setReference(self, Reference): self.Reference = Reference
def getFatherinclude(self): return self.FatherInclude
def setFatherinclude(self, FatherInclude): self.FatherInclude = FatherInclude
def getFather(self): return self.Father
def setFather(self, Father): self.Father = Father
def getNamespace(self): return self.Namespace
def setNamespace(self, Namespace): self.Namespace = Namespace
def getTwin(self): return self.Twin
def setTwin(self, Twin): self.Twin = Twin
def getConstructor(self): return self.Constructor
def setConstructor(self, Constructor): self.Constructor = Constructor
def getTwinpointer(self): return self.TwinPointer
def setTwinpointer(self, TwinPointer): self.TwinPointer = TwinPointer
def getInclude(self): return self.Include
def setInclude(self, Include): self.Include = Include
def getNumberprotocol(self): return self.NumberProtocol
def setNumberprotocol(self, NumberProtocol): self.NumberProtocol = NumberProtocol
def getDelete(self): return self.Delete
def setDelete(self, Delete): self.Delete = Delete
def export(self, outfile, level, name_='PythonExport'):
showIndent(outfile, level)
outfile.write('<%s' % (name_, ))
self.exportAttributes(outfile, level, name_='PythonExport')
outfile.write('>\n')
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write('</%s>\n' % name_)
def exportAttributes(self, outfile, level, name_='PythonExport'):
outfile.write(' FatherNamespace="%s"' % (self.getFathernamespace(), ))
if self.getRichcompare() is not None:
outfile.write(' RichCompare="%s"' % (self.getRichcompare(), ))
outfile.write(' Name="%s"' % (self.getName(), ))
if self.getReference() is not None:
outfile.write(' Reference="%s"' % (self.getReference(), ))
outfile.write(' FatherInclude="%s"' % (self.getFatherinclude(), ))
outfile.write(' Father="%s"' % (self.getFather(), ))
outfile.write(' Namespace="%s"' % (self.getNamespace(), ))
outfile.write(' Twin="%s"' % (self.getTwin(), ))
if self.getConstructor() is not None:
outfile.write(' Constructor="%s"' % (self.getConstructor(), ))
if self.getInitialization() is not None:
outfile.write(' Initialization="%s"' % (self.getInitialization(), ))
outfile.write(' TwinPointer="%s"' % (self.getTwinpointer(), ))
outfile.write(' Include="%s"' % (self.getInclude(), ))
if self.getNumberprotocol() is not None:
outfile.write(' NumberProtocol="%s"' % (self.getNumberprotocol(), ))
if self.getDelete() is not None:
outfile.write(' Delete="%s"' % (self.getDelete(), ))
def exportChildren(self, outfile, level, name_='PythonExport'):
if self.Documentation:
self.Documentation.export(outfile, level)
for Methode_ in self.getMethode():
Methode_.export(outfile, level)
for Attribute_ in self.getAttribute():
Attribute_.export(outfile, level)
if self.Sequence:
self.Sequence.export(outfile, level)
showIndent(outfile, level)
outfile.write('<CustomAttributes>%s</CustomAttributes>\n' % quote_xml(self.getCustomattributes()))
showIndent(outfile, level)
outfile.write('<ClassDeclarations>%s</ClassDeclarations>\n' % quote_xml(self.getClassdeclarations()))
def exportLiteral(self, outfile, level, name_='PythonExport'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('FatherNamespace = "%s",\n' % (self.getFathernamespace(),))
showIndent(outfile, level)
outfile.write('RichCompare = "%s",\n' % (self.getRichcompare(),))
showIndent(outfile, level)
outfile.write('Name = "%s",\n' % (self.getName(),))
showIndent(outfile, level)
outfile.write('Reference = "%s",\n' % (self.getReference(),))
showIndent(outfile, level)
outfile.write('FatherInclude = "%s",\n' % (self.getFatherinclude(),))
showIndent(outfile, level)
outfile.write('Father = "%s",\n' % (self.getFather(),))
showIndent(outfile, level)
outfile.write('Namespace = "%s",\n' % (self.getNamespace(),))
showIndent(outfile, level)
outfile.write('Twin = "%s",\n' % (self.getTwin(),))
showIndent(outfile, level)
outfile.write('Constructor = "%s",\n' % (self.getConstructor(),))
showIndent(outfile, level)
outfile.write('Initialization = "%s",\n' % (self.getInitialization(),))
outfile.write('TwinPointer = "%s",\n' % (self.getTwinpointer(),))
showIndent(outfile, level)
outfile.write('Include = "%s",\n' % (self.getInclude(),))
showIndent(outfile, level)
outfile.write('NumberProtocol = "%s",\n' % (self.getNumberprotocol(),))
showIndent(outfile, level)
outfile.write('Delete = "%s",\n' % (self.getDelete(),))
def exportLiteralChildren(self, outfile, level, name_):
if self.Documentation:
showIndent(outfile, level)
outfile.write('Documentation=Documentation(\n')
self.Documentation.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('Methode=[\n')
level += 1
for Methode in self.Methode:
showIndent(outfile, level)
outfile.write('Methode(\n')
Methode.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Attribute=[\n')
level += 1
for Attribute in self.Attribute:
showIndent(outfile, level)
outfile.write('Attribute(\n')
Attribute.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
if self.Sequence:
showIndent(outfile, level)
outfile.write('Sequence=Sequence(\n')
self.Sequence.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('CustomAttributes=%s,\n' % quote_python(self.getCustomattributes()))
showIndent(outfile, level)
outfile.write('ClassDeclarations=%s,\n' % quote_python(self.getClassdeclarations()))
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('FatherNamespace'):
self.FatherNamespace = attrs.get('FatherNamespace').value
if attrs.get('RichCompare'):
if attrs.get('RichCompare').value in ('true', '1'):
self.RichCompare = 1
elif attrs.get('RichCompare').value in ('false', '0'):
self.RichCompare = 0
else:
raise ValueError('Bad boolean attribute (RichCompare)')
if attrs.get('Name'):
self.Name = attrs.get('Name').value
if attrs.get('Reference'):
if attrs.get('Reference').value in ('true', '1'):
self.Reference = 1
elif attrs.get('Reference').value in ('false', '0'):
self.Reference = 0
else:
raise ValueError('Bad boolean attribute (Reference)')
if attrs.get('FatherInclude'):
self.FatherInclude = attrs.get('FatherInclude').value
if attrs.get('Father'):
self.Father = attrs.get('Father').value
if attrs.get('Namespace'):
self.Namespace = attrs.get('Namespace').value
if attrs.get('Twin'):
self.Twin = attrs.get('Twin').value
if attrs.get('Constructor'):
if attrs.get('Constructor').value in ('true', '1'):
self.Constructor = 1
elif attrs.get('Constructor').value in ('false', '0'):
self.Constructor = 0
else:
raise ValueError('Bad boolean attribute (Constructor)')
if attrs.get('Initialization'):
if attrs.get('Initialization').value in ('true', '1'):
self.Initialization = 1
elif attrs.get('Initialization').value in ('false', '0'):
self.Initialization = 0
else:
raise ValueError('Bad boolean attribute (Initialization)')
if attrs.get('TwinPointer'):
self.TwinPointer = attrs.get('TwinPointer').value
if attrs.get('Include'):
self.Include = attrs.get('Include').value
if attrs.get('NumberProtocol'):
if attrs.get('NumberProtocol').value in ('true', '1'):
self.NumberProtocol = 1
elif attrs.get('NumberProtocol').value in ('false', '0'):
self.NumberProtocol = 0
else:
raise ValueError('Bad boolean attribute (NumberProtocol)')
if attrs.get('Delete'):
if attrs.get('Delete').value in ('true', '1'):
self.Delete = 1
elif attrs.get('Delete').value in ('false', '0'):
self.Delete = 0
else:
raise ValueError('Bad boolean attribute (Delete)')
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Documentation':
obj_ = Documentation.factory()
obj_.build(child_)
self.setDocumentation(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Methode':
obj_ = Methode.factory()
obj_.build(child_)
self.Methode.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Attribute':
obj_ = Attribute.factory()
obj_.build(child_)
self.Attribute.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Sequence':
obj_ = Sequence.factory()
obj_.build(child_)
self.setSequence(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'CustomAttributes':
CustomAttributes_ = ''
for text__content_ in child_.childNodes:
CustomAttributes_ += text__content_.nodeValue
self.CustomAttributes = CustomAttributes_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'ClassDeclarations':
ClassDeclarations_ = ''
for text__content_ in child_.childNodes:
ClassDeclarations_ += text__content_.nodeValue
self.ClassDeclarations = ClassDeclarations_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Initialization':
obj_ = Documentation.factory()
obj_.build(child_)
self.setDocumentation(obj_)
# end class PythonExport
class Methode:
subclass = None
def __init__(self, Const=0, Name='', Keyword=0, Documentation=None, Parameter=None):
self.Const = Const
self.Name = Name
self.Keyword = Keyword
self.Documentation = Documentation
if Parameter is None:
self.Parameter = []
else:
self.Parameter = Parameter
def factory(*args_, **kwargs_):
if Methode.subclass:
return Methode.subclass(*args_, **kwargs_)
else:
return Methode(*args_, **kwargs_)
factory = staticmethod(factory)
def getDocumentation(self): return self.Documentation
def setDocumentation(self, Documentation): self.Documentation = Documentation
def getParameter(self): return self.Parameter
def setParameter(self, Parameter): self.Parameter = Parameter
def addParameter(self, value): self.Parameter.append(value)
def insertParameter(self, index, value): self.Parameter[index] = value
def getConst(self): return self.Const
def setConst(self, Const): self.Const = Const
def getName(self): return self.Name
def setName(self, Name): self.Name = Name
def getKeyword(self): return self.Keyword
def setKeyword(self, Keyword): self.Keyword = Keyword
def export(self, outfile, level, name_='Methode'):
showIndent(outfile, level)
outfile.write('<%s' % (name_, ))
self.exportAttributes(outfile, level, name_='Methode')
outfile.write('>\n')
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write('</%s>\n' % name_)
def exportAttributes(self, outfile, level, name_='Methode'):
if self.getConst() is not None:
outfile.write(' Const="%s"' % (self.getConst(), ))
outfile.write(' Name="%s"' % (self.getName(), ))
if self.getKeyword() is not None:
outfile.write(' Keyword="%s"' % (self.getKeyword(), ))
def exportChildren(self, outfile, level, name_='Methode'):
if self.Documentation:
self.Documentation.export(outfile, level)
for Parameter_ in self.getParameter():
Parameter_.export(outfile, level)
def exportLiteral(self, outfile, level, name_='Methode'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Const = "%s",\n' % (self.getConst(),))
showIndent(outfile, level)
outfile.write('Name = "%s",\n' % (self.getName(),))
showIndent(outfile, level)
outfile.write('Keyword = "%s",\n' % (self.getKeyword(),))
def exportLiteralChildren(self, outfile, level, name_):
if self.Documentation:
showIndent(outfile, level)
outfile.write('Documentation=Documentation(\n')
self.Documentation.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('Parameter=[\n')
level += 1
for Parameter in self.Parameter:
showIndent(outfile, level)
outfile.write('Parameter(\n')
Parameter.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('Const'):
if attrs.get('Const').value in ('true', '1'):
self.Const = 1
elif attrs.get('Const').value in ('false', '0'):
self.Const = 0
else:
raise ValueError('Bad boolean attribute (Const)')
if attrs.get('Name'):
self.Name = attrs.get('Name').value
if attrs.get('Keyword'):
if attrs.get('Keyword').value in ('true', '1'):
self.Keyword = 1
elif attrs.get('Keyword').value in ('false', '0'):
self.Keyword = 0
else:
raise ValueError('Bad boolean attribute (Keyword)')
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Documentation':
obj_ = Documentation.factory()
obj_.build(child_)
self.setDocumentation(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Parameter':
obj_ = Parameter.factory()
obj_.build(child_)
self.Parameter.append(obj_)
# end class Methode
class Attribute:
subclass = None
def __init__(self, ReadOnly=0, Name='', Documentation=None, Parameter=None):
self.ReadOnly = ReadOnly
self.Name = Name
self.Documentation = Documentation
self.Parameter = Parameter
def factory(*args_, **kwargs_):
if Attribute.subclass:
return Attribute.subclass(*args_, **kwargs_)
else:
return Attribute(*args_, **kwargs_)
factory = staticmethod(factory)
def getDocumentation(self): return self.Documentation
def setDocumentation(self, Documentation): self.Documentation = Documentation
def getParameter(self): return self.Parameter
def setParameter(self, Parameter): self.Parameter = Parameter
def getReadonly(self): return self.ReadOnly
def setReadonly(self, ReadOnly): self.ReadOnly = ReadOnly
def getName(self): return self.Name
def setName(self, Name): self.Name = Name
def export(self, outfile, level, name_='Attribute'):
showIndent(outfile, level)
outfile.write('<%s' % (name_, ))
self.exportAttributes(outfile, level, name_='Attribute')
outfile.write('>\n')
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write('</%s>\n' % name_)
def exportAttributes(self, outfile, level, name_='Attribute'):
outfile.write(' ReadOnly="%s"' % (self.getReadonly(), ))
outfile.write(' Name="%s"' % (self.getName(), ))
def exportChildren(self, outfile, level, name_='Attribute'):
if self.Documentation:
self.Documentation.export(outfile, level)
if self.Parameter:
self.Parameter.export(outfile, level)
def exportLiteral(self, outfile, level, name_='Attribute'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('ReadOnly = "%s",\n' % (self.getReadonly(),))
showIndent(outfile, level)
outfile.write('Name = "%s",\n' % (self.getName(),))
def exportLiteralChildren(self, outfile, level, name_):
if self.Documentation:
showIndent(outfile, level)
outfile.write('Documentation=Documentation(\n')
self.Documentation.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Parameter:
showIndent(outfile, level)
outfile.write('Parameter=Parameter(\n')
self.Parameter.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('ReadOnly'):
if attrs.get('ReadOnly').value in ('true', '1'):
self.ReadOnly = 1
elif attrs.get('ReadOnly').value in ('false', '0'):
self.ReadOnly = 0
else:
raise ValueError('Bad boolean attribute (ReadOnly)')
if attrs.get('Name'):
self.Name = attrs.get('Name').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Documentation':
obj_ = Documentation.factory()
obj_.build(child_)
self.setDocumentation(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Parameter':
obj_ = Parameter.factory()
obj_.build(child_)
self.setParameter(obj_)
# end class Attribute
class Sequence:
subclass = None
def __init__(self, sq_slice=0, sq_item=0, sq_concat=0, sq_inplace_repeat=0, sq_ass_slice=0, sq_contains=0, sq_ass_item=0, sq_repeat=0, sq_length=0, sq_inplace_concat=0, valueOf_=''):
self.sq_slice = sq_slice
self.sq_item = sq_item
self.sq_concat = sq_concat
self.sq_inplace_repeat = sq_inplace_repeat
self.sq_ass_slice = sq_ass_slice
self.sq_contains = sq_contains
self.sq_ass_item = sq_ass_item
self.sq_repeat = sq_repeat
self.sq_length = sq_length
self.sq_inplace_concat = sq_inplace_concat
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if Sequence.subclass:
return Sequence.subclass(*args_, **kwargs_)
else:
return Sequence(*args_, **kwargs_)
factory = staticmethod(factory)
def getSq_slice(self): return self.sq_slice
def setSq_slice(self, sq_slice): self.sq_slice = sq_slice
def getSq_item(self): return self.sq_item
def setSq_item(self, sq_item): self.sq_item = sq_item
def getSq_concat(self): return self.sq_concat
def setSq_concat(self, sq_concat): self.sq_concat = sq_concat
def getSq_inplace_repeat(self): return self.sq_inplace_repeat
def setSq_inplace_repeat(self, sq_inplace_repeat): self.sq_inplace_repeat = sq_inplace_repeat
def getSq_ass_slice(self): return self.sq_ass_slice
def setSq_ass_slice(self, sq_ass_slice): self.sq_ass_slice = sq_ass_slice
def getSq_contains(self): return self.sq_contains
def setSq_contains(self, sq_contains): self.sq_contains = sq_contains
def getSq_ass_item(self): return self.sq_ass_item
def setSq_ass_item(self, sq_ass_item): self.sq_ass_item = sq_ass_item
def getSq_repeat(self): return self.sq_repeat
def setSq_repeat(self, sq_repeat): self.sq_repeat = sq_repeat
def getSq_length(self): return self.sq_length
def setSq_length(self, sq_length): self.sq_length = sq_length
def getSq_inplace_concat(self): return self.sq_inplace_concat
def setSq_inplace_concat(self, sq_inplace_concat): self.sq_inplace_concat = sq_inplace_concat
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, name_='Sequence'):
showIndent(outfile, level)
outfile.write('<%s' % (name_, ))
self.exportAttributes(outfile, level, name_='Sequence')
outfile.write('>\n')
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write('</%s>\n' % name_)
def exportAttributes(self, outfile, level, name_='Sequence'):
outfile.write(' sq_slice="%s"' % (self.getSq_slice(), ))
outfile.write(' sq_item="%s"' % (self.getSq_item(), ))
outfile.write(' sq_concat="%s"' % (self.getSq_concat(), ))
outfile.write(' sq_inplace_repeat="%s"' % (self.getSq_inplace_repeat(), ))
outfile.write(' sq_ass_slice="%s"' % (self.getSq_ass_slice(), ))
outfile.write(' sq_contains="%s"' % (self.getSq_contains(), ))
outfile.write(' sq_ass_item="%s"' % (self.getSq_ass_item(), ))
outfile.write(' sq_repeat="%s"' % (self.getSq_repeat(), ))
outfile.write(' sq_length="%s"' % (self.getSq_length(), ))
outfile.write(' sq_inplace_concat="%s"' % (self.getSq_inplace_concat(), ))
def exportChildren(self, outfile, level, name_='Sequence'):
outfile.write(self.valueOf_)
def exportLiteral(self, outfile, level, name_='Sequence'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('sq_slice = "%s",\n' % (self.getSq_slice(),))
showIndent(outfile, level)
outfile.write('sq_item = "%s",\n' % (self.getSq_item(),))
showIndent(outfile, level)
outfile.write('sq_concat = "%s",\n' % (self.getSq_concat(),))
showIndent(outfile, level)
outfile.write('sq_inplace_repeat = "%s",\n' % (self.getSq_inplace_repeat(),))
showIndent(outfile, level)
outfile.write('sq_ass_slice = "%s",\n' % (self.getSq_ass_slice(),))
showIndent(outfile, level)
outfile.write('sq_contains = "%s",\n' % (self.getSq_contains(),))
showIndent(outfile, level)
outfile.write('sq_ass_item = "%s",\n' % (self.getSq_ass_item(),))
showIndent(outfile, level)
outfile.write('sq_repeat = "%s",\n' % (self.getSq_repeat(),))
showIndent(outfile, level)
outfile.write('sq_length = "%s",\n' % (self.getSq_length(),))
showIndent(outfile, level)
outfile.write('sq_inplace_concat = "%s",\n' % (self.getSq_inplace_concat(),))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,))
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('sq_slice'):
if attrs.get('sq_slice').value in ('true', '1'):
self.sq_slice = 1
elif attrs.get('sq_slice').value in ('false', '0'):
self.sq_slice = 0
else:
raise ValueError('Bad boolean attribute (sq_slice)')
if attrs.get('sq_item'):
if attrs.get('sq_item').value in ('true', '1'):
self.sq_item = 1
elif attrs.get('sq_item').value in ('false', '0'):
self.sq_item = 0
else:
raise ValueError('Bad boolean attribute (sq_item)')
if attrs.get('sq_concat'):
if attrs.get('sq_concat').value in ('true', '1'):
self.sq_concat = 1
elif attrs.get('sq_concat').value in ('false', '0'):
self.sq_concat = 0
else:
raise ValueError('Bad boolean attribute (sq_concat)')
if attrs.get('sq_inplace_repeat'):
if attrs.get('sq_inplace_repeat').value in ('true', '1'):
self.sq_inplace_repeat = 1
elif attrs.get('sq_inplace_repeat').value in ('false', '0'):
self.sq_inplace_repeat = 0
else:
raise ValueError('Bad boolean attribute (sq_inplace_repeat)')
if attrs.get('sq_ass_slice'):
if attrs.get('sq_ass_slice').value in ('true', '1'):
self.sq_ass_slice = 1
elif attrs.get('sq_ass_slice').value in ('false', '0'):
self.sq_ass_slice = 0
else:
raise ValueError('Bad boolean attribute (sq_ass_slice)')
if attrs.get('sq_contains'):
if attrs.get('sq_contains').value in ('true', '1'):
self.sq_contains = 1
elif attrs.get('sq_contains').value in ('false', '0'):
self.sq_contains = 0
else:
raise ValueError('Bad boolean attribute (sq_contains)')
if attrs.get('sq_ass_item'):
if attrs.get('sq_ass_item').value in ('true', '1'):
self.sq_ass_item = 1
elif attrs.get('sq_ass_item').value in ('false', '0'):
self.sq_ass_item = 0
else:
raise ValueError('Bad boolean attribute (sq_ass_item)')
if attrs.get('sq_repeat'):
if attrs.get('sq_repeat').value in ('true', '1'):
self.sq_repeat = 1
elif attrs.get('sq_repeat').value in ('false', '0'):
self.sq_repeat = 0
else:
raise ValueError('Bad boolean attribute (sq_repeat)')
if attrs.get('sq_length'):
if attrs.get('sq_length').value in ('true', '1'):
self.sq_length = 1
elif attrs.get('sq_length').value in ('false', '0'):
self.sq_length = 0
else:
raise ValueError('Bad boolean attribute (sq_length)')
if attrs.get('sq_inplace_concat'):
if attrs.get('sq_inplace_concat').value in ('true', '1'):
self.sq_inplace_concat = 1
elif attrs.get('sq_inplace_concat').value in ('false', '0'):
self.sq_inplace_concat = 0
else:
raise ValueError('Bad boolean attribute (sq_inplace_concat)')
def buildChildren(self, child_, nodeName_):
self.valueOf_ = ''
for child in child_.childNodes:
if child.nodeType == Node.TEXT_NODE:
self.valueOf_ += child.nodeValue
# end class Sequence
class Module:
subclass = None
def __init__(self, Name='', Documentation=None, Dependencies=None, Content=None):
self.Name = Name
self.Documentation = Documentation
self.Dependencies = Dependencies
self.Content = Content
def factory(*args_, **kwargs_):
if Module.subclass:
return Module.subclass(*args_, **kwargs_)
else:
return Module(*args_, **kwargs_)
factory = staticmethod(factory)
def getDocumentation(self): return self.Documentation
def setDocumentation(self, Documentation): self.Documentation = Documentation
def getDependencies(self): return self.Dependencies
def setDependencies(self, Dependencies): self.Dependencies = Dependencies
def getContent(self): return self.Content
def setContent(self, Content): self.Content = Content
def getName(self): return self.Name
def setName(self, Name): self.Name = Name
def export(self, outfile, level, name_='Module'):
showIndent(outfile, level)
outfile.write('<%s' % (name_, ))
self.exportAttributes(outfile, level, name_='Module')
outfile.write('>\n')
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write('</%s>\n' % name_)
def exportAttributes(self, outfile, level, name_='Module'):
outfile.write(' Name="%s"' % (self.getName(), ))
def exportChildren(self, outfile, level, name_='Module'):
if self.Documentation:
self.Documentation.export(outfile, level)
if self.Dependencies:
self.Dependencies.export(outfile, level)
if self.Content:
self.Content.export(outfile, level)
def exportLiteral(self, outfile, level, name_='Module'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Name = "%s",\n' % (self.getName(),))
def exportLiteralChildren(self, outfile, level, name_):
if self.Documentation:
showIndent(outfile, level)
outfile.write('Documentation=Documentation(\n')
self.Documentation.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Dependencies:
showIndent(outfile, level)
outfile.write('Dependencies=Dependencies(\n')
self.Dependencies.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Content:
showIndent(outfile, level)
outfile.write('Content=Content(\n')
self.Content.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('Name'):
self.Name = attrs.get('Name').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Documentation':
obj_ = Documentation.factory()
obj_.build(child_)
self.setDocumentation(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Dependencies':
obj_ = Dependencies.factory()
obj_.build(child_)
self.setDependencies(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Content':
obj_ = Content.factory()
obj_.build(child_)
self.setContent(obj_)
# end class Module
class Dependencies:
subclass = None
def __init__(self, Module=None):
if Module is None:
self.Module = []
else:
self.Module = Module
def factory(*args_, **kwargs_):
if Dependencies.subclass:
return Dependencies.subclass(*args_, **kwargs_)
else:
return Dependencies(*args_, **kwargs_)
factory = staticmethod(factory)
def getModule(self): return self.Module
def setModule(self, Module): self.Module = Module
def addModule(self, value): self.Module.append(value)
def insertModule(self, index, value): self.Module[index] = value
def export(self, outfile, level, name_='Dependencies'):
showIndent(outfile, level)
outfile.write('<%s>\n' % name_)
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write('</%s>\n' % name_)
def exportAttributes(self, outfile, level, name_='Dependencies'):
pass
def exportChildren(self, outfile, level, name_='Dependencies'):
for Module_ in self.getModule():
Module_.export(outfile, level)
def exportLiteral(self, outfile, level, name_='Dependencies'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Module=[\n')
level += 1
for Module in self.Module:
showIndent(outfile, level)
outfile.write('Module(\n')
Module.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Module':
obj_ = Module.factory()
obj_.build(child_)
self.Module.append(obj_)
# end class Dependencies
class Content:
subclass = None
def __init__(self, Property=None, Feature=None, DocObject=None, GuiCommand=None, PreferencesPage=None):
if Property is None:
self.Property = []
else:
self.Property = Property
if Feature is None:
self.Feature = []
else:
self.Feature = Feature
if DocObject is None:
self.DocObject = []
else:
self.DocObject = DocObject
if GuiCommand is None:
self.GuiCommand = []
else:
self.GuiCommand = GuiCommand
if PreferencesPage is None:
self.PreferencesPage = []
else:
self.PreferencesPage = PreferencesPage
def factory(*args_, **kwargs_):
if Content.subclass:
return Content.subclass(*args_, **kwargs_)
else:
return Content(*args_, **kwargs_)
factory = staticmethod(factory)
def getProperty(self): return self.Property
def setProperty(self, Property): self.Property = Property
def addProperty(self, value): self.Property.append(value)
def insertProperty(self, index, value): self.Property[index] = value
def getFeature(self): return self.Feature
def setFeature(self, Feature): self.Feature = Feature
def addFeature(self, value): self.Feature.append(value)
def insertFeature(self, index, value): self.Feature[index] = value
def getDocobject(self): return self.DocObject
def setDocobject(self, DocObject): self.DocObject = DocObject
def addDocobject(self, value): self.DocObject.append(value)
def insertDocobject(self, index, value): self.DocObject[index] = value
def getGuicommand(self): return self.GuiCommand
def setGuicommand(self, GuiCommand): self.GuiCommand = GuiCommand
def addGuicommand(self, value): self.GuiCommand.append(value)
def insertGuicommand(self, index, value): self.GuiCommand[index] = value
def getPreferencespage(self): return self.PreferencesPage
def setPreferencespage(self, PreferencesPage): self.PreferencesPage = PreferencesPage
def addPreferencespage(self, value): self.PreferencesPage.append(value)
def insertPreferencespage(self, index, value): self.PreferencesPage[index] = value
def export(self, outfile, level, name_='Content'):
showIndent(outfile, level)
outfile.write('<%s>\n' % name_)
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write('</%s>\n' % name_)
def exportAttributes(self, outfile, level, name_='Content'):
pass
def exportChildren(self, outfile, level, name_='Content'):
for Property_ in self.getProperty():
Property_.export(outfile, level)
for Feature_ in self.getFeature():
Feature_.export(outfile, level)
for DocObject_ in self.getDocobject():
DocObject_.export(outfile, level)
for GuiCommand_ in self.getGuicommand():
showIndent(outfile, level)
outfile.write('<GuiCommand>%s</GuiCommand>\n' % quote_xml(GuiCommand_))
for PreferencesPage_ in self.getPreferencespage():
showIndent(outfile, level)
outfile.write('<PreferencesPage>%s</PreferencesPage>\n' % quote_xml(PreferencesPage_))
def exportLiteral(self, outfile, level, name_='Content'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Property=[\n')
level += 1
for Property in self.Property:
showIndent(outfile, level)
outfile.write('Property(\n')
Property.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Feature=[\n')
level += 1
for Feature in self.Feature:
showIndent(outfile, level)
outfile.write('Feature(\n')
Feature.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('DocObject=[\n')
level += 1
for DocObject in self.DocObject:
showIndent(outfile, level)
outfile.write('DocObject(\n')
DocObject.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('GuiCommand=[\n')
level += 1
for GuiCommand in self.GuiCommand:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(GuiCommand))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('PreferencesPage=[\n')
level += 1
for PreferencesPage in self.PreferencesPage:
showIndent(outfile, level)
outfile.write('%s,\n' % quote_python(PreferencesPage))
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Property':
obj_ = Property.factory()
obj_.build(child_)
self.Property.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Feature':
obj_ = Feature.factory()
obj_.build(child_)
self.Feature.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'DocObject':
obj_ = DocObject.factory()
obj_.build(child_)
self.DocObject.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'GuiCommand':
GuiCommand_ = ''
for text__content_ in child_.childNodes:
GuiCommand_ += text__content_.nodeValue
self.GuiCommand.append(GuiCommand_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'PreferencesPage':
PreferencesPage_ = ''
for text__content_ in child_.childNodes:
PreferencesPage_ += text__content_.nodeValue
self.PreferencesPage.append(PreferencesPage_)
# end class Content
class Feature:
subclass = None
def __init__(self, Name='', Documentation=None, Property=None, ViewProvider=None):
self.Name = Name
self.Documentation = Documentation
if Property is None:
self.Property = []
else:
self.Property = Property
self.ViewProvider = ViewProvider
def factory(*args_, **kwargs_):
if Feature.subclass:
return Feature.subclass(*args_, **kwargs_)
else:
return Feature(*args_, **kwargs_)
factory = staticmethod(factory)
def getDocumentation(self): return self.Documentation
def setDocumentation(self, Documentation): self.Documentation = Documentation
def getProperty(self): return self.Property
def setProperty(self, Property): self.Property = Property
def addProperty(self, value): self.Property.append(value)
def insertProperty(self, index, value): self.Property[index] = value
def getViewprovider(self): return self.ViewProvider
def setViewprovider(self, ViewProvider): self.ViewProvider = ViewProvider
def getName(self): return self.Name
def setName(self, Name): self.Name = Name
def export(self, outfile, level, name_='Feature'):
showIndent(outfile, level)
outfile.write('<%s' % (name_, ))
self.exportAttributes(outfile, level, name_='Feature')
outfile.write('>\n')
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write('</%s>\n' % name_)
def exportAttributes(self, outfile, level, name_='Feature'):
outfile.write(' Name="%s"' % (self.getName(), ))
def exportChildren(self, outfile, level, name_='Feature'):
if self.Documentation:
self.Documentation.export(outfile, level)
for Property_ in self.getProperty():
Property_.export(outfile, level)
if self.ViewProvider:
self.ViewProvider.export(outfile, level)
def exportLiteral(self, outfile, level, name_='Feature'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Name = "%s",\n' % (self.getName(),))
def exportLiteralChildren(self, outfile, level, name_):
if self.Documentation:
showIndent(outfile, level)
outfile.write('Documentation=Documentation(\n')
self.Documentation.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('Property=[\n')
level += 1
for Property in self.Property:
showIndent(outfile, level)
outfile.write('Property(\n')
Property.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
if self.ViewProvider:
showIndent(outfile, level)
outfile.write('ViewProvider=ViewProvider(\n')
self.ViewProvider.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('Name'):
self.Name = attrs.get('Name').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Documentation':
obj_ = Documentation.factory()
obj_.build(child_)
self.setDocumentation(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Property':
obj_ = Property.factory()
obj_.build(child_)
self.Property.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'ViewProvider':
obj_ = ViewProvider.factory()
obj_.build(child_)
self.setViewprovider(obj_)
# end class Feature
class DocObject:
subclass = None
def __init__(self, Name='', Documentation=None, Property=None):
self.Name = Name
self.Documentation = Documentation
if Property is None:
self.Property = []
else:
self.Property = Property
def factory(*args_, **kwargs_):
if DocObject.subclass:
return DocObject.subclass(*args_, **kwargs_)
else:
return DocObject(*args_, **kwargs_)
factory = staticmethod(factory)
def getDocumentation(self): return self.Documentation
def setDocumentation(self, Documentation): self.Documentation = Documentation
def getProperty(self): return self.Property
def setProperty(self, Property): self.Property = Property
def addProperty(self, value): self.Property.append(value)
def insertProperty(self, index, value): self.Property[index] = value
def getName(self): return self.Name
def setName(self, Name): self.Name = Name
def export(self, outfile, level, name_='DocObject'):
showIndent(outfile, level)
outfile.write('<%s' % (name_, ))
self.exportAttributes(outfile, level, name_='DocObject')
outfile.write('>\n')
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write('</%s>\n' % name_)
def exportAttributes(self, outfile, level, name_='DocObject'):
outfile.write(' Name="%s"' % (self.getName(), ))
def exportChildren(self, outfile, level, name_='DocObject'):
if self.Documentation:
self.Documentation.export(outfile, level)
for Property_ in self.getProperty():
Property_.export(outfile, level)
def exportLiteral(self, outfile, level, name_='DocObject'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Name = "%s",\n' % (self.getName(),))
def exportLiteralChildren(self, outfile, level, name_):
if self.Documentation:
showIndent(outfile, level)
outfile.write('Documentation=Documentation(\n')
self.Documentation.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('Property=[\n')
level += 1
for Property in self.Property:
showIndent(outfile, level)
outfile.write('Property(\n')
Property.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('Name'):
self.Name = attrs.get('Name').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Documentation':
obj_ = Documentation.factory()
obj_.build(child_)
self.setDocumentation(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Property':
obj_ = Property.factory()
obj_.build(child_)
self.Property.append(obj_)
# end class DocObject
class Property:
subclass = None
def __init__(self, Type='', Name='', StartValue='', Documentation=None):
self.Type = Type
self.Name = Name
self.StartValue = StartValue
self.Documentation = Documentation
def factory(*args_, **kwargs_):
if Property.subclass:
return Property.subclass(*args_, **kwargs_)
else:
return Property(*args_, **kwargs_)
factory = staticmethod(factory)
def getDocumentation(self): return self.Documentation
def setDocumentation(self, Documentation): self.Documentation = Documentation
def getType(self): return self.Type
def setType(self, Type): self.Type = Type
def getName(self): return self.Name
def setName(self, Name): self.Name = Name
def getStartvalue(self): return self.StartValue
def setStartvalue(self, StartValue): self.StartValue = StartValue
def export(self, outfile, level, name_='Property'):
showIndent(outfile, level)
outfile.write('<%s' % (name_, ))
self.exportAttributes(outfile, level, name_='Property')
outfile.write('>\n')
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write('</%s>\n' % name_)
def exportAttributes(self, outfile, level, name_='Property'):
outfile.write(' Type="%s"' % (self.getType(), ))
outfile.write(' Name="%s"' % (self.getName(), ))
if self.getStartvalue() is not None:
outfile.write(' StartValue="%s"' % (self.getStartvalue(), ))
def exportChildren(self, outfile, level, name_='Property'):
if self.Documentation:
self.Documentation.export(outfile, level)
def exportLiteral(self, outfile, level, name_='Property'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Type = "%s",\n' % (self.getType(),))
showIndent(outfile, level)
outfile.write('Name = "%s",\n' % (self.getName(),))
showIndent(outfile, level)
outfile.write('StartValue = "%s",\n' % (self.getStartvalue(),))
def exportLiteralChildren(self, outfile, level, name_):
if self.Documentation:
showIndent(outfile, level)
outfile.write('Documentation=Documentation(\n')
self.Documentation.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('Type'):
self.Type = attrs.get('Type').value
if attrs.get('Name'):
self.Name = attrs.get('Name').value
if attrs.get('StartValue'):
self.StartValue = attrs.get('StartValue').value
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Documentation':
obj_ = Documentation.factory()
obj_.build(child_)
self.setDocumentation(obj_)
# end class Property
class Documentation:
subclass = None
def __init__(self, Author=None, DeveloperDocu='', UserDocu=''):
self.Author = Author
self.DeveloperDocu = DeveloperDocu
self.UserDocu = UserDocu
def factory(*args_, **kwargs_):
if Documentation.subclass:
return Documentation.subclass(*args_, **kwargs_)
else:
return Documentation(*args_, **kwargs_)
factory = staticmethod(factory)
def getAuthor(self): return self.Author
def setAuthor(self, Author): self.Author = Author
def getDeveloperdocu(self): return self.DeveloperDocu
def setDeveloperdocu(self, DeveloperDocu): self.DeveloperDocu = DeveloperDocu
def getUserdocu(self): return self.UserDocu
def setUserdocu(self, UserDocu): self.UserDocu = UserDocu
def export(self, outfile, level, name_='Documentation'):
showIndent(outfile, level)
outfile.write('<%s>\n' % name_)
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write('</%s>\n' % name_)
def exportAttributes(self, outfile, level, name_='Documentation'):
pass
def exportChildren(self, outfile, level, name_='Documentation'):
if self.Author:
self.Author.export(outfile, level)
showIndent(outfile, level)
outfile.write('<DeveloperDocu>%s</DeveloperDocu>\n' % quote_xml(self.getDeveloperdocu()))
showIndent(outfile, level)
outfile.write('<UserDocu>%s</UserDocu>\n' % quote_xml(self.getUserdocu()))
def exportLiteral(self, outfile, level, name_='Documentation'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
if self.Author:
showIndent(outfile, level)
outfile.write('Author=Author(\n')
self.Author.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('DeveloperDocu=%s,\n' % quote_python(self.getDeveloperdocu()))
showIndent(outfile, level)
outfile.write('UserDocu=%s,\n' % quote_python(self.getUserdocu()))
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Author':
obj_ = Author.factory()
obj_.build(child_)
self.setAuthor(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'DeveloperDocu':
DeveloperDocu_ = ''
for text__content_ in child_.childNodes:
DeveloperDocu_ += text__content_.nodeValue
self.DeveloperDocu = DeveloperDocu_
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'UserDocu':
UserDocu_ = ''
for text__content_ in child_.childNodes:
UserDocu_ += text__content_.nodeValue
self.UserDocu = UserDocu_
# end class Documentation
class Author:
subclass = None
def __init__(self, Name='', Licence='', EMail='', valueOf_=''):
self.Name = Name
self.Licence = Licence
self.EMail = EMail
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if Author.subclass:
return Author.subclass(*args_, **kwargs_)
else:
return Author(*args_, **kwargs_)
factory = staticmethod(factory)
def getName(self): return self.Name
def setName(self, Name): self.Name = Name
def getLicence(self): return self.Licence
def setLicence(self, Licence): self.Licence = Licence
def getEmail(self): return self.EMail
def setEmail(self, EMail): self.EMail = EMail
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, name_='Author'):
showIndent(outfile, level)
outfile.write('<%s' % (name_, ))
self.exportAttributes(outfile, level, name_='Author')
outfile.write('>\n')
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write('</%s>\n' % name_)
def exportAttributes(self, outfile, level, name_='Author'):
outfile.write(' Name="%s"' % (self.getName(), ))
if self.getLicence() is not None:
outfile.write(' Licence="%s"' % (self.getLicence(), ))
outfile.write(' EMail="%s"' % (self.getEmail(), ))
def exportChildren(self, outfile, level, name_='Author'):
outfile.write(self.valueOf_)
def exportLiteral(self, outfile, level, name_='Author'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Name = "%s",\n' % (self.getName(),))
showIndent(outfile, level)
outfile.write('Licence = "%s",\n' % (self.getLicence(),))
showIndent(outfile, level)
outfile.write('EMail = "%s",\n' % (self.getEmail(),))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,))
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('Name'):
self.Name = attrs.get('Name').value
if attrs.get('Licence'):
self.Licence = attrs.get('Licence').value
if attrs.get('EMail'):
self.EMail = attrs.get('EMail').value
def buildChildren(self, child_, nodeName_):
self.valueOf_ = ''
for child in child_.childNodes:
if child.nodeType == Node.TEXT_NODE:
self.valueOf_ += child.nodeValue
# end class Author
class ViewProvider:
subclass = None
def __init__(self, Property=None):
if Property is None:
self.Property = []
else:
self.Property = Property
def factory(*args_, **kwargs_):
if ViewProvider.subclass:
return ViewProvider.subclass(*args_, **kwargs_)
else:
return ViewProvider(*args_, **kwargs_)
factory = staticmethod(factory)
def getProperty(self): return self.Property
def setProperty(self, Property): self.Property = Property
def addProperty(self, value): self.Property.append(value)
def insertProperty(self, index, value): self.Property[index] = value
def export(self, outfile, level, name_='ViewProvider'):
showIndent(outfile, level)
outfile.write('<%s>\n' % name_)
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write('</%s>\n' % name_)
def exportAttributes(self, outfile, level, name_='ViewProvider'):
pass
def exportChildren(self, outfile, level, name_='ViewProvider'):
for Property_ in self.getProperty():
Property_.export(outfile, level)
def exportLiteral(self, outfile, level, name_='ViewProvider'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Property=[\n')
level += 1
for Property in self.Property:
showIndent(outfile, level)
outfile.write('Property(\n')
Property.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
pass
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'Property':
obj_ = Property.factory()
obj_.build(child_)
self.Property.append(obj_)
# end class ViewProvider
class Parameter:
subclass = None
def __init__(self, Type='', Name='', valueOf_=''):
self.Type = Type
self.Name = Name
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if Parameter.subclass:
return Parameter.subclass(*args_, **kwargs_)
else:
return Parameter(*args_, **kwargs_)
factory = staticmethod(factory)
def getType(self): return self.Type
def setType(self, Type): self.Type = Type
def getName(self): return self.Name
def setName(self, Name): self.Name = Name
def getValueOf_(self): return self.valueOf_
def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, name_='Parameter'):
showIndent(outfile, level)
outfile.write('<%s' % (name_, ))
self.exportAttributes(outfile, level, name_='Parameter')
outfile.write('>\n')
self.exportChildren(outfile, level + 1, name_)
showIndent(outfile, level)
outfile.write('</%s>\n' % name_)
def exportAttributes(self, outfile, level, name_='Parameter'):
outfile.write(' Type="%s"' % (self.getType(), ))
outfile.write(' Name="%s"' % (self.getName(), ))
def exportChildren(self, outfile, level, name_='Parameter'):
outfile.write(self.valueOf_)
def exportLiteral(self, outfile, level, name_='Parameter'):
level += 1
self.exportLiteralAttributes(outfile, level, name_)
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Type = "%s",\n' % (self.getType(),))
showIndent(outfile, level)
outfile.write('Name = "%s",\n' % (self.getName(),))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,))
def build(self, node_):
attrs = node_.attributes
self.buildAttributes(attrs)
for child_ in node_.childNodes:
nodeName_ = child_.nodeName.split(':')[-1]
self.buildChildren(child_, nodeName_)
def buildAttributes(self, attrs):
if attrs.get('Type'):
self.Type = attrs.get('Type').value
if attrs.get('Name'):
self.Name = attrs.get('Name').value
def buildChildren(self, child_, nodeName_):
self.valueOf_ = ''
for child in child_.childNodes:
if child.nodeType == Node.TEXT_NODE:
self.valueOf_ += child.nodeValue
# end class Parameter
from xml.sax import handler, make_parser
class SaxStackElement:
def __init__(self, name='', obj=None):
self.name = name
self.obj = obj
self.content = ''
#
# SAX handler
#
class SaxGeneratemodelHandler(handler.ContentHandler):
def __init__(self):
self.stack = []
self.root = None
def getRoot(self):
return self.root
def setDocumentLocator(self, locator):
self.locator = locator
def showError(self, msg):
print '*** (showError):', msg
sys.exit(-1)
def startElement(self, name, attrs):
done = 0
if name == 'GenerateModel':
obj = GenerateModel.factory()
stackObj = SaxStackElement('GenerateModel', obj)
self.stack.append(stackObj)
done = 1
elif name == 'Module':
obj = Module.factory()
stackObj = SaxStackElement('Module', obj)
self.stack.append(stackObj)
done = 1
elif name == 'PythonExport':
obj = PythonExport.factory()
val = attrs.get('FatherNamespace', None)
if val is not None:
obj.setFathernamespace(val)
val = attrs.get('RichCompare', None)
if val is not None:
if val in ('true', '1'):
obj.setRichcompare(1)
elif val in ('false', '0'):
obj.setRichcompare(0)
else:
self.reportError('"RichCompare" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('Name', None)
if val is not None:
obj.setName(val)
val = attrs.get('Reference', None)
if val is not None:
if val in ('true', '1'):
obj.setReference(1)
elif val in ('false', '0'):
obj.setReference(0)
else:
self.reportError('"Reference" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('FatherInclude', None)
if val is not None:
obj.setFatherinclude(val)
val = attrs.get('Father', None)
if val is not None:
obj.setFather(val)
val = attrs.get('Namespace', None)
if val is not None:
obj.setNamespace(val)
val = attrs.get('Twin', None)
if val is not None:
obj.setTwin(val)
val = attrs.get('Constructor', None)
if val is not None:
if val in ('true', '1'):
obj.setConstructor(1)
elif val in ('false', '0'):
obj.setConstructor(0)
else:
self.reportError('"Constructor" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('Initialization', None)
if val is not None:
if val in ('true', '1'):
obj.setInitialization(1)
elif val in ('false', '0'):
obj.setInitialization(0)
else:
self.reportError('"Initialization" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('TwinPointer', None)
if val is not None:
obj.setTwinpointer(val)
val = attrs.get('Include', None)
if val is not None:
obj.setInclude(val)
val = attrs.get('NumberProtocol', None)
if val is not None:
if val in ('true', '1'):
obj.setNumberprotocol(1)
elif val in ('false', '0'):
obj.setNumberprotocol(0)
else:
self.reportError('"NumberProtocol" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('Delete', None)
if val is not None:
if val in ('true', '1'):
obj.setDelete(1)
elif val in ('false', '0'):
obj.setDelete(0)
else:
self.reportError('"Delete" attribute must be boolean ("true", "1", "false", "0")')
stackObj = SaxStackElement('PythonExport', obj)
self.stack.append(stackObj)
done = 1
elif name == 'Documentation':
obj = Documentation.factory()
stackObj = SaxStackElement('Documentation', obj)
self.stack.append(stackObj)
done = 1
elif name == 'Methode':
obj = Methode.factory()
val = attrs.get('Const', None)
if val is not None:
if val in ('true', '1'):
obj.setConst(1)
elif val in ('false', '0'):
obj.setConst(0)
else:
self.reportError('"Const" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('Name', None)
if val is not None:
obj.setName(val)
val = attrs.get('Keyword', None)
if val is not None:
if val in ('true', '1'):
obj.setKeyword(1)
elif val in ('false', '0'):
obj.setKeyword(0)
else:
self.reportError('"Keyword" attribute must be boolean ("true", "1", "false", "0")')
stackObj = SaxStackElement('Methode', obj)
self.stack.append(stackObj)
done = 1
elif name == 'Parameter':
obj = Parameter.factory()
val = attrs.get('Type', None)
if val is not None:
obj.setType(val)
val = attrs.get('Name', None)
if val is not None:
obj.setName(val)
stackObj = SaxStackElement('Parameter', obj)
self.stack.append(stackObj)
done = 1
elif name == 'Attribute':
obj = Attribute.factory()
val = attrs.get('ReadOnly', None)
if val is not None:
if val in ('true', '1'):
obj.setReadonly(1)
elif val in ('false', '0'):
obj.setReadonly(0)
else:
self.reportError('"ReadOnly" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('Name', None)
if val is not None:
obj.setName(val)
stackObj = SaxStackElement('Attribute', obj)
self.stack.append(stackObj)
done = 1
elif name == 'Sequence':
obj = Sequence.factory()
val = attrs.get('sq_slice', None)
if val is not None:
if val in ('true', '1'):
obj.setSq_slice(1)
elif val in ('false', '0'):
obj.setSq_slice(0)
else:
self.reportError('"sq_slice" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('sq_item', None)
if val is not None:
if val in ('true', '1'):
obj.setSq_item(1)
elif val in ('false', '0'):
obj.setSq_item(0)
else:
self.reportError('"sq_item" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('sq_concat', None)
if val is not None:
if val in ('true', '1'):
obj.setSq_concat(1)
elif val in ('false', '0'):
obj.setSq_concat(0)
else:
self.reportError('"sq_concat" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('sq_inplace_repeat', None)
if val is not None:
if val in ('true', '1'):
obj.setSq_inplace_repeat(1)
elif val in ('false', '0'):
obj.setSq_inplace_repeat(0)
else:
self.reportError('"sq_inplace_repeat" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('sq_ass_slice', None)
if val is not None:
if val in ('true', '1'):
obj.setSq_ass_slice(1)
elif val in ('false', '0'):
obj.setSq_ass_slice(0)
else:
self.reportError('"sq_ass_slice" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('sq_contains', None)
if val is not None:
if val in ('true', '1'):
obj.setSq_contains(1)
elif val in ('false', '0'):
obj.setSq_contains(0)
else:
self.reportError('"sq_contains" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('sq_ass_item', None)
if val is not None:
if val in ('true', '1'):
obj.setSq_ass_item(1)
elif val in ('false', '0'):
obj.setSq_ass_item(0)
else:
self.reportError('"sq_ass_item" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('sq_repeat', None)
if val is not None:
if val in ('true', '1'):
obj.setSq_repeat(1)
elif val in ('false', '0'):
obj.setSq_repeat(0)
else:
self.reportError('"sq_repeat" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('sq_length', None)
if val is not None:
if val in ('true', '1'):
obj.setSq_length(1)
elif val in ('false', '0'):
obj.setSq_length(0)
else:
self.reportError('"sq_length" attribute must be boolean ("true", "1", "false", "0")')
val = attrs.get('sq_inplace_concat', None)
if val is not None:
if val in ('true', '1'):
obj.setSq_inplace_concat(1)
elif val in ('false', '0'):
obj.setSq_inplace_concat(0)
else:
self.reportError('"sq_inplace_concat" attribute must be boolean ("true", "1", "false", "0")')
stackObj = SaxStackElement('Sequence', obj)
self.stack.append(stackObj)
done = 1
elif name == 'CustomAttributes':
stackObj = SaxStackElement('CustomAttributes', None)
self.stack.append(stackObj)
done = 1
elif name == 'ClassDeclarations':
stackObj = SaxStackElement('ClassDeclarations', None)
self.stack.append(stackObj)
done = 1
elif name == 'Dependencies':
obj = Dependencies.factory()
stackObj = SaxStackElement('Dependencies', obj)
self.stack.append(stackObj)
done = 1
elif name == 'Content':
obj = Content.factory()
stackObj = SaxStackElement('Content', obj)
self.stack.append(stackObj)
done = 1
elif name == 'Property':
obj = Property.factory()
stackObj = SaxStackElement('Property', obj)
self.stack.append(stackObj)
done = 1
elif name == 'Feature':
obj = Feature.factory()
val = attrs.get('Name', None)
if val is not None:
obj.setName(val)
stackObj = SaxStackElement('Feature', obj)
self.stack.append(stackObj)
done = 1
elif name == 'ViewProvider':
obj = ViewProvider.factory()
stackObj = SaxStackElement('ViewProvider', obj)
self.stack.append(stackObj)
done = 1
elif name == 'DocObject':
obj = DocObject.factory()
val = attrs.get('Name', None)
if val is not None:
obj.setName(val)
stackObj = SaxStackElement('DocObject', obj)
self.stack.append(stackObj)
done = 1
elif name == 'GuiCommand':
stackObj = SaxStackElement('GuiCommand', None)
self.stack.append(stackObj)
done = 1
elif name == 'PreferencesPage':
stackObj = SaxStackElement('PreferencesPage', None)
self.stack.append(stackObj)
done = 1
elif name == 'Author':
obj = Author.factory()
val = attrs.get('Name', None)
if val is not None:
obj.setName(val)
val = attrs.get('Licence', None)
if val is not None:
obj.setLicence(val)
val = attrs.get('EMail', None)
if val is not None:
obj.setEmail(val)
stackObj = SaxStackElement('Author', obj)
self.stack.append(stackObj)
done = 1
elif name == 'DeveloperDocu':
stackObj = SaxStackElement('DeveloperDocu', None)
self.stack.append(stackObj)
done = 1
elif name == 'UserDocu':
stackObj = SaxStackElement('UserDocu', None)
self.stack.append(stackObj)
done = 1
if not done:
self.reportError('"%s" element not allowed here.' % name)
def endElement(self, name):
done = 0
if name == 'GenerateModel':
if len(self.stack) == 1:
self.root = self.stack[-1].obj
self.stack.pop()
done = 1
elif name == 'Module':
if len(self.stack) >= 2:
self.stack[-2].obj.addModule(self.stack[-1].obj)
self.stack.pop()
done = 1
elif name == 'PythonExport':
if len(self.stack) >= 2:
self.stack[-2].obj.addPythonexport(self.stack[-1].obj)
self.stack.pop()
done = 1
elif name == 'Documentation':
if len(self.stack) >= 2:
self.stack[-2].obj.setDocumentation(self.stack[-1].obj)
self.stack.pop()
done = 1
elif name == 'Methode':
if len(self.stack) >= 2:
self.stack[-2].obj.addMethode(self.stack[-1].obj)
self.stack.pop()
done = 1
elif name == 'Parameter':
if len(self.stack) >= 2:
self.stack[-2].obj.addParameter(self.stack[-1].obj)
self.stack.pop()
done = 1
elif name == 'Attribute':
if len(self.stack) >= 2:
self.stack[-2].obj.addAttribute(self.stack[-1].obj)
self.stack.pop()
done = 1
elif name == 'Sequence':
if len(self.stack) >= 2:
self.stack[-2].obj.setSequence(self.stack[-1].obj)
self.stack.pop()
done = 1
elif name == 'CustomAttributes':
if len(self.stack) >= 2:
content = self.stack[-1].content
self.stack[-2].obj.setCustomattributes(content)
self.stack.pop()
done = 1
elif name == 'ClassDeclarations':
if len(self.stack) >= 2:
content = self.stack[-1].content
self.stack[-2].obj.setClassdeclarations(content)
self.stack.pop()
done = 1
elif name == 'Dependencies':
if len(self.stack) >= 2:
self.stack[-2].obj.setDependencies(self.stack[-1].obj)
self.stack.pop()
done = 1
elif name == 'Content':
if len(self.stack) >= 2:
self.stack[-2].obj.setContent(self.stack[-1].obj)
self.stack.pop()
done = 1
elif name == 'Property':
if len(self.stack) >= 2:
self.stack[-2].obj.addProperty(self.stack[-1].obj)
self.stack.pop()
done = 1
elif name == 'Feature':
if len(self.stack) >= 2:
self.stack[-2].obj.addFeature(self.stack[-1].obj)
self.stack.pop()
done = 1
elif name == 'ViewProvider':
if len(self.stack) >= 2:
self.stack[-2].obj.setViewprovider(self.stack[-1].obj)
self.stack.pop()
done = 1
elif name == 'DocObject':
if len(self.stack) >= 2:
self.stack[-2].obj.addDocobject(self.stack[-1].obj)
self.stack.pop()
done = 1
elif name == 'GuiCommand':
if len(self.stack) >= 2:
content = self.stack[-1].content
self.stack[-2].obj.addGuicommand(content)
self.stack.pop()
done = 1
elif name == 'PreferencesPage':
if len(self.stack) >= 2:
content = self.stack[-1].content
self.stack[-2].obj.addPreferencespage(content)
self.stack.pop()
done = 1
elif name == 'Author':
if len(self.stack) >= 2:
self.stack[-2].obj.setAuthor(self.stack[-1].obj)
self.stack.pop()
done = 1
elif name == 'DeveloperDocu':
if len(self.stack) >= 2:
content = self.stack[-1].content
self.stack[-2].obj.setDeveloperdocu(content)
self.stack.pop()
done = 1
elif name == 'UserDocu':
if len(self.stack) >= 2:
content = self.stack[-1].content
self.stack[-2].obj.setUserdocu(content)
self.stack.pop()
done = 1
if not done:
self.reportError('"%s" element not allowed here.' % name)
def characters(self, chrs, start, end):
if len(self.stack) > 0:
self.stack[-1].content += chrs[start:end]
def reportError(self, mesg):
locator = self.locator
sys.stderr.write('Doc: %s Line: %d Column: %d\n' % \
(locator.getSystemId(), locator.getLineNumber(),
locator.getColumnNumber() + 1))
sys.stderr.write(mesg)
sys.stderr.write('\n')
sys.exit(-1)
#raise RuntimeError
USAGE_TEXT = """
Usage: python <Parser>.py [ -s ] <in_xml_file>
Options:
-s Use the SAX parser, not the minidom parser.
"""
def usage():
print USAGE_TEXT
sys.exit(-1)
#
# SAX handler used to determine the top level element.
#
class SaxSelectorHandler(handler.ContentHandler):
def __init__(self):
self.topElementName = None
def getTopElementName(self):
return self.topElementName
def startElement(self, name, attrs):
self.topElementName = name
raise StopIteration
def parseSelect(inFileName):
infile = file(inFileName, 'r')
topElementName = None
parser = make_parser()
documentHandler = SaxSelectorHandler()
parser.setContentHandler(documentHandler)
try:
try:
parser.parse(infile)
except StopIteration:
topElementName = documentHandler.getTopElementName()
if topElementName is None:
raise RuntimeError, 'no top level element'
topElementName = topElementName.replace('-', '_').replace(':', '_')
if topElementName not in globals():
raise RuntimeError, 'no class for top element: %s' % topElementName
topElement = globals()[topElementName]
infile.seek(0)
doc = minidom.parse(infile)
finally:
infile.close()
rootNode = doc.childNodes[0]
rootObj = topElement.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('<?xml version="1.0" ?>\n')
rootObj.export(sys.stdout, 0)
return rootObj
def saxParse(inFileName):
parser = make_parser()
documentHandler = SaxGeneratemodelHandler()
parser.setDocumentHandler(documentHandler)
parser.parse('file:%s' % inFileName)
root = documentHandler.getRoot()
sys.stdout.write('<?xml version="1.0" ?>\n')
root.export(sys.stdout, 0)
return root
def saxParseString(inString):
parser = make_parser()
documentHandler = SaxGeneratemodelHandler()
parser.setDocumentHandler(documentHandler)
parser.feed(inString)
parser.close()
rootObj = documentHandler.getRoot()
#sys.stdout.write('<?xml version="1.0" ?>\n')
#rootObj.export(sys.stdout, 0)
return rootObj
def parse(inFileName):
doc = minidom.parse(inFileName)
rootNode = doc.documentElement
rootObj = GenerateModel.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('<?xml version="1.0" ?>\n')
rootObj.export(sys.stdout, 0, name_="GenerateModel")
return rootObj
def parseString(inString):
doc = minidom.parseString(inString)
rootNode = doc.documentElement
rootObj = GenerateModel.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('<?xml version="1.0" ?>\n')
rootObj.export(sys.stdout, 0, name_="GenerateModel")
return rootObj
def parseLiteral(inFileName):
doc = minidom.parse(inFileName)
rootNode = doc.documentElement
rootObj = GenerateModel.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('from generateModel_Module import *\n\n')
sys.stdout.write('rootObj = GenerateModel(\n')
rootObj.exportLiteral(sys.stdout, 0, name_="GenerateModel")
sys.stdout.write(')\n')
return rootObj
def main():
args = sys.argv[1:]
if len(args) == 2 and args[0] == '-s':
saxParse(args[1])
elif len(args) == 1:
parse(args[0])
else:
usage()
if __name__ == '__main__':
main()
#import pdb
#pdb.run('main()')
| wood-galaxy/FreeCAD | src/Tools/generateBase/generateModel_Module.py | Python | lgpl-2.1 | 101,247 |
package train.common.entity.rollingStock;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityMinecart;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import net.minecraftforge.common.util.Constants;
import train.common.Traincraft;
import train.common.api.LiquidManager;
import train.common.api.SteamTrain;
import train.common.library.EnumTrains;
import train.common.library.GuiIDs;
public class EntityLocoSteamBR80_DB extends SteamTrain {
public EntityLocoSteamBR80_DB(World world) {
super(world, EnumTrains.locoSteamBR80.getTankCapacity(), LiquidManager.WATER_FILTER);
initLocoSteam();
}
public void initLocoSteam() {
fuelTrain = 0;
locoInvent = new ItemStack[inventorySize];
}
public EntityLocoSteamBR80_DB(World world, double d, double d1, double d2) {
this(world);
setPosition(d, d1 + (double) yOffset, d2);
motionX = 0.0D;
motionY = 0.0D;
motionZ = 0.0D;
prevPosX = d;
prevPosY = d1;
prevPosZ = d2;
}
@Override
public void updateRiderPosition() {
double distance = -0.1;
double pitchRads = this.anglePitchClient * 3.141592653589793D / 180.0D;
float rotationCos1 = (float) Math.cos(Math.toRadians(this.renderYaw + 90));
float rotationSin1 = (float) Math.sin(Math.toRadians((this.renderYaw + 90)));
float pitch = (float) (posY + ((Math.tan(pitchRads)*distance)+getMountedYOffset()) + riddenByEntity.getYOffset()+0.45);
double bogieX1 = (this.posX + (rotationCos1 * distance));
double bogieZ1 = (this.posZ + (rotationSin1* distance));
if(anglePitchClient>20 && rotationCos1 == 1){
bogieX1-=pitchRads*0.9;
pitch-=pitchRads*0.3;
}
if(anglePitchClient>20 && rotationSin1 == 1){
bogieZ1-=pitchRads*0.9;
pitch-=pitchRads*0.3;
}
riddenByEntity.setPosition(bogieX1, pitch, bogieZ1);
//riddenByEntity.setPosition(posX, posY + getMountedYOffset() + riddenByEntity.getYOffset() + 0.45, posZ);
}
@Override
public void setDead() {
super.setDead();
isDead = true;
if (worldObj.isRemote) {
return;
}
label0: for (int i = 0; i < getSizeInventory(); i++) {
ItemStack itemstack = getStackInSlot(i);
if (itemstack == null) {
continue;
}
float f = rand.nextFloat() * 0.8F + 0.1F;
float f1 = rand.nextFloat() * 0.8F + 0.1F;
float f2 = rand.nextFloat() * 0.8F + 0.1F;
do {
if (itemstack.stackSize <= 0) {
continue label0;
}
int j = rand.nextInt(21) + 10;
if (j > itemstack.stackSize) {
j = itemstack.stackSize;
}
itemstack.stackSize -= j;
EntityItem entityitem = new EntityItem(worldObj, posX + (double) f, posY + (double) f1, posZ + (double) f2, new ItemStack(itemstack.getItem(), j, itemstack.getItemDamage()));
float f3 = 0.05F;
entityitem.motionX = (float) rand.nextGaussian() * f3;
entityitem.motionY = (float) rand.nextGaussian() * f3 + 0.2F;
entityitem.motionZ = (float) rand.nextGaussian() * f3;
worldObj.spawnEntityInWorld(entityitem);
} while (true);
}
}
@Override
public void pressKey(int i) {
if (i == 7 && riddenByEntity != null && riddenByEntity instanceof EntityPlayer) {
((EntityPlayer) riddenByEntity).openGui(Traincraft.instance, GuiIDs.LOCO, worldObj, (int) this.posX, (int) this.posY, (int) this.posZ);
}
}
@Override
public void onUpdate() {
checkInvent(locoInvent[0], locoInvent[1], this);
super.onUpdate();
}
@Override
protected void writeEntityToNBT(NBTTagCompound nbttagcompound) {
super.writeEntityToNBT(nbttagcompound);
nbttagcompound.setShort("fuelTrain", (short) fuelTrain);
NBTTagList nbttaglist = new NBTTagList();
for (int i = 0; i < locoInvent.length; i++) {
if (locoInvent[i] != null) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setByte("Slot", (byte) i);
locoInvent[i].writeToNBT(nbttagcompound1);
nbttaglist.appendTag(nbttagcompound1);
}
}
nbttagcompound.setTag("Items", nbttaglist);
}
@Override
protected void readEntityFromNBT(NBTTagCompound nbttagcompound) {
super.readEntityFromNBT(nbttagcompound);
fuelTrain = nbttagcompound.getShort("fuelTrain");
NBTTagList nbttaglist = nbttagcompound.getTagList("Items", Constants.NBT.TAG_COMPOUND);
locoInvent = new ItemStack[getSizeInventory()];
for (int i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbttaglist.getCompoundTagAt(i);
int j = nbttagcompound1.getByte("Slot") & 0xff;
if (j >= 0 && j < locoInvent.length) {
locoInvent[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1);
}
}
}
@Override
public int getSizeInventory() {
return inventorySize;
}
@Override
public String getInventoryName() {
return "BR80";
}
@Override
public boolean interactFirst(EntityPlayer entityplayer) {
playerEntity = entityplayer;
if ((super.interactFirst(entityplayer))) {
return false;
}
if (!worldObj.isRemote) {
if (riddenByEntity != null && (riddenByEntity instanceof EntityPlayer) && riddenByEntity != entityplayer) {
return true;
}
entityplayer.mountEntity(this);
}
return true;
}
@Override
public float getOptimalDistance(EntityMinecart cart) {
float dist = 1.1F;
return (dist);
}
@Override
public boolean canBeAdjusted(EntityMinecart cart) {
return canBeAdjusted;
}
@Override
public boolean isItemValidForSlot(int i, ItemStack itemstack) {
return true;
}
} | BlesseNtumble/Traincraft-5 | src/main/java/train/common/entity/rollingStock/EntityLocoSteamBR80_DB.java | Java | lgpl-2.1 | 5,508 |
package tsxdk.entity.meta;
import java.util.Collection;
import tsxdk.entity.TsEntity;
/**
* Generic Type for Entity-lists.
* Used For Channels, Clients, Complains
* @param <E> The entity stored in this list
* @param <S> The Slot for this entity (unique ID)
*/
public interface EntityList<E extends TsEntity, S> {
/**
* @param slot The identifier for this slot
* @return An Entity for given slot
*/
E acquire (S slot);
/**
* Sets all registered entities to the initial state
*/
void setInitial ();
/**
* Sets all registered entities to the touched state
*/
void setTouched();
/**
* Clears cached entities
*/
void clearCache();
/**
* Removes all unused Entities
*/
void cleanUp();
/**
* @return the count of entities in this list
*/
int getEntityCount ();
TsEntity[] getIterable();
Collection<? super E> getContentList();
}
| GerhardUlli/TSxBot | src/tsxdk/entity/meta/EntityList.java | Java | lgpl-2.1 | 928 |
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QTest>
#ifdef Q_OS_WIN
#include <winsock2.h>
#endif
#include <qcoreapplication.h>
#include <qdatastream.h>
#include <qhostaddress.h>
#include <qdatetime.h>
#ifdef Q_OS_UNIX
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#endif
#ifdef Q_OS_VXWORKS
#include <sockLib.h>
#endif
#include <stddef.h>
#define PLATFORMSOCKETENGINE QNativeSocketEngine
#define PLATFORMSOCKETENGINESTRING "QNativeSocketEngine"
#include <private/qnativesocketengine_p.h>
#include <qstringlist.h>
#include "../../../network-settings.h"
class tst_PlatformSocketEngine : public QObject
{
Q_OBJECT
public:
tst_PlatformSocketEngine();
virtual ~tst_PlatformSocketEngine();
public slots:
void initTestCase();
void init();
void cleanup();
private slots:
void construction();
void simpleConnectToIMAP();
void udpLoopbackTest();
void udpIPv6LoopbackTest();
void broadcastTest();
void serverTest();
void udpLoopbackPerformance();
void tcpLoopbackPerformance();
void readWriteBufferSize();
void bind();
void networkError();
void setSocketDescriptor();
void invalidSend();
void receiveUrgentData();
void tooManySockets();
};
tst_PlatformSocketEngine::tst_PlatformSocketEngine()
{
}
tst_PlatformSocketEngine::~tst_PlatformSocketEngine()
{
}
void tst_PlatformSocketEngine::initTestCase()
{
QVERIFY(QtNetworkSettings::verifyTestNetworkSettings());
}
void tst_PlatformSocketEngine::init()
{
}
void tst_PlatformSocketEngine::cleanup()
{
}
//---------------------------------------------------------------------------
void tst_PlatformSocketEngine::construction()
{
PLATFORMSOCKETENGINE socketDevice;
QVERIFY(!socketDevice.isValid());
// Initialize device
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
QVERIFY(socketDevice.isValid());
QVERIFY(socketDevice.protocol() == QAbstractSocket::IPv4Protocol);
QVERIFY(socketDevice.socketType() == QAbstractSocket::TcpSocket);
QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
QVERIFY(socketDevice.socketDescriptor() != -1);
QVERIFY(socketDevice.localAddress() == QHostAddress());
QVERIFY(socketDevice.localPort() == 0);
QVERIFY(socketDevice.peerAddress() == QHostAddress());
QVERIFY(socketDevice.peerPort() == 0);
QVERIFY(socketDevice.error() == QAbstractSocket::UnknownSocketError);
QTest::ignoreMessage(QtWarningMsg, PLATFORMSOCKETENGINESTRING "::bytesAvailable() was called in QAbstractSocket::UnconnectedState");
QVERIFY(socketDevice.bytesAvailable() == -1);
QTest::ignoreMessage(QtWarningMsg, PLATFORMSOCKETENGINESTRING "::hasPendingDatagrams() was called in QAbstractSocket::UnconnectedState");
QVERIFY(!socketDevice.hasPendingDatagrams());
}
//---------------------------------------------------------------------------
void tst_PlatformSocketEngine::simpleConnectToIMAP()
{
PLATFORMSOCKETENGINE socketDevice;
// Initialize device
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
const bool isConnected = socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143);
if (!isConnected) {
QVERIFY(socketDevice.state() == QAbstractSocket::ConnectingState);
QVERIFY(socketDevice.waitForWrite());
QVERIFY(socketDevice.state() == QAbstractSocket::ConnectedState);
}
QVERIFY(socketDevice.state() == QAbstractSocket::ConnectedState);
QVERIFY(socketDevice.peerAddress() == QtNetworkSettings::serverIP());
// Wait for the greeting
QVERIFY(socketDevice.waitForRead());
// Read the greeting
qint64 available = socketDevice.bytesAvailable();
QVERIFY(available > 0);
QByteArray array;
array.resize(available);
QVERIFY(socketDevice.read(array.data(), array.size()) == available);
// Check that the greeting is what we expect it to be
QVERIFY2(QtNetworkSettings::compareReplyIMAP(array), array.constData());
// Write a logout message
QByteArray array2 = "ZZZ LOGOUT\r\n";
QVERIFY(socketDevice.write(array2.data(),
array2.size()) == array2.size());
// Wait for the response
QVERIFY(socketDevice.waitForRead());
available = socketDevice.bytesAvailable();
QVERIFY(available > 0);
array.resize(available);
QVERIFY(socketDevice.read(array.data(), array.size()) == available);
// Check that the greeting is what we expect it to be
QCOMPARE(array.constData(),
"* BYE LOGOUT received\r\n"
"ZZZ OK Completed\r\n");
// Wait for the response
QVERIFY(socketDevice.waitForRead());
char c;
QVERIFY(socketDevice.read(&c, sizeof(c)) == -1);
QVERIFY(socketDevice.error() == QAbstractSocket::RemoteHostClosedError);
QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState);
}
//---------------------------------------------------------------------------
void tst_PlatformSocketEngine::udpLoopbackTest()
{
PLATFORMSOCKETENGINE udpSocket;
// Initialize device #1
QVERIFY(udpSocket.initialize(QAbstractSocket::UdpSocket));
QVERIFY(udpSocket.isValid());
QVERIFY(udpSocket.socketDescriptor() != -1);
QVERIFY(udpSocket.protocol() == QAbstractSocket::IPv4Protocol);
QVERIFY(udpSocket.socketType() == QAbstractSocket::UdpSocket);
QVERIFY(udpSocket.state() == QAbstractSocket::UnconnectedState);
// Bind #1 to localhost
QVERIFY(udpSocket.bind(QHostAddress("127.0.0.1"), 0));
QVERIFY(udpSocket.state() == QAbstractSocket::BoundState);
quint16 port = udpSocket.localPort();
QVERIFY(port != 0);
// Initialize device #2
PLATFORMSOCKETENGINE udpSocket2;
QVERIFY(udpSocket2.initialize(QAbstractSocket::UdpSocket));
// Connect device #2 to #1
QVERIFY(udpSocket2.connectToHost(QHostAddress("127.0.0.1"), port));
QVERIFY(udpSocket2.state() == QAbstractSocket::ConnectedState);
// Write a message to #1
QByteArray message1 = "hei der";
QVERIFY(udpSocket2.write(message1.data(),
message1.size()) == message1.size());
// Read the message from #2
QVERIFY(udpSocket.waitForRead());
QVERIFY(udpSocket.hasPendingDatagrams());
qint64 available = udpSocket.pendingDatagramSize();
QVERIFY(available > 0);
QByteArray answer;
answer.resize(available);
QHostAddress senderAddress;
quint16 senderPort = 0;
QVERIFY(udpSocket.readDatagram(answer.data(), answer.size(),
&senderAddress,
&senderPort) == message1.size());
QVERIFY(senderAddress == QHostAddress("127.0.0.1"));
QVERIFY(senderPort != 0);
}
//---------------------------------------------------------------------------
void tst_PlatformSocketEngine::udpIPv6LoopbackTest()
{
PLATFORMSOCKETENGINE udpSocket;
// Initialize device #1
bool init = udpSocket.initialize(QAbstractSocket::UdpSocket, QAbstractSocket::IPv6Protocol);
if (!init) {
QVERIFY(udpSocket.error() == QAbstractSocket::UnsupportedSocketOperationError);
} else {
QVERIFY(udpSocket.protocol() == QAbstractSocket::IPv6Protocol);
// Bind #1 to localhost
QVERIFY(udpSocket.bind(QHostAddress("::1"), 0));
QVERIFY(udpSocket.state() == QAbstractSocket::BoundState);
quint16 port = udpSocket.localPort();
QVERIFY(port != 0);
// Initialize device #2
PLATFORMSOCKETENGINE udpSocket2;
QVERIFY(udpSocket2.initialize(QAbstractSocket::UdpSocket, QAbstractSocket::IPv6Protocol));
// Connect device #2 to #1
QVERIFY(udpSocket2.connectToHost(QHostAddress("::1"), port));
QVERIFY(udpSocket2.state() == QAbstractSocket::ConnectedState);
// Write a message to #1
QByteArray message1 = "hei der";
QVERIFY(udpSocket2.write(message1.data(),
message1.size()) == message1.size());
// Read the message from #2
QVERIFY(udpSocket.waitForRead());
QVERIFY(udpSocket.hasPendingDatagrams());
qint64 available = udpSocket.pendingDatagramSize();
QVERIFY(available > 0);
QByteArray answer;
answer.resize(available);
QHostAddress senderAddress;
quint16 senderPort = 0;
QVERIFY(udpSocket.readDatagram(answer.data(), answer.size(),
&senderAddress,
&senderPort) == message1.size());
QVERIFY(senderAddress == QHostAddress("::1"));
QVERIFY(senderPort != 0);
}
}
//---------------------------------------------------------------------------
void tst_PlatformSocketEngine::broadcastTest()
{
#ifdef Q_OS_AIX
QSKIP("Broadcast does not work on darko");
#endif
PLATFORMSOCKETENGINE broadcastSocket;
// Initialize a regular Udp socket
QVERIFY(broadcastSocket.initialize(QAbstractSocket::UdpSocket, QAbstractSocket::AnyIPProtocol));
// Bind to any port on all interfaces
QVERIFY(broadcastSocket.bind(QHostAddress::Any, 0));
QVERIFY(broadcastSocket.state() == QAbstractSocket::BoundState);
quint16 port = broadcastSocket.localPort();
QVERIFY(port > 0);
// Broadcast an inappropriate troll message
QByteArray trollMessage
= "MOOT wtf is a MOOT? talk english not your sutpiD ENGLISH.";
qint64 written = broadcastSocket.writeDatagram(trollMessage.data(),
trollMessage.size(),
QHostAddress::Broadcast,
port);
QCOMPARE((int)written, trollMessage.size());
// Wait until we receive it ourselves
#if defined(Q_OS_FREEBSD)
QEXPECT_FAIL("", "Broadcasting to 255.255.255.255 does not work on FreeBSD", Abort);
#endif
QVERIFY(broadcastSocket.waitForRead());
QVERIFY(broadcastSocket.hasPendingDatagrams());
qlonglong available = broadcastSocket.pendingDatagramSize();
QByteArray response;
response.resize(available);
QVERIFY(broadcastSocket.readDatagram(response.data(), response.size())
== response.size());
QCOMPARE(response, trollMessage);
}
//---------------------------------------------------------------------------
void tst_PlatformSocketEngine::serverTest()
{
PLATFORMSOCKETENGINE server;
// Initialize a Tcp socket
QVERIFY(server.initialize(QAbstractSocket::TcpSocket));
// Bind to any port on all interfaces
QVERIFY(server.bind(QHostAddress("0.0.0.0"), 0));
QVERIFY(server.state() == QAbstractSocket::BoundState);
quint16 port = server.localPort();
// Listen for incoming connections
QVERIFY(server.listen());
QVERIFY(server.state() == QAbstractSocket::ListeningState);
// Initialize a Tcp socket
PLATFORMSOCKETENGINE client;
QVERIFY(client.initialize(QAbstractSocket::TcpSocket));
if (!client.connectToHost(QHostAddress("127.0.0.1"), port)) {
QVERIFY(client.state() == QAbstractSocket::ConnectingState);
QVERIFY(client.waitForWrite());
QVERIFY(client.state() == QAbstractSocket::ConnectedState);
}
// The server accepts the connection
int socketDescriptor = server.accept();
QVERIFY(socketDescriptor > 0);
// A socket device is initialized on the server side, passing the
// socket descriptor from accept(). It's pre-connected.
PLATFORMSOCKETENGINE serverSocket;
QVERIFY(serverSocket.initialize(socketDescriptor));
QVERIFY(serverSocket.state() == QAbstractSocket::ConnectedState);
// The server socket sends a greeting to the clietn
QByteArray greeting = "Greetings!";
QVERIFY(serverSocket.write(greeting.data(),
greeting.size()) == greeting.size());
// The client waits for the greeting to arrive
QVERIFY(client.waitForRead());
qint64 available = client.bytesAvailable();
QVERIFY(available > 0);
// The client reads the greeting and checks that it's correct
QByteArray response;
response.resize(available);
QVERIFY(client.read(response.data(),
response.size()) == response.size());
QCOMPARE(response, greeting);
}
//---------------------------------------------------------------------------
void tst_PlatformSocketEngine::udpLoopbackPerformance()
{
PLATFORMSOCKETENGINE udpSocket;
// Initialize device #1
QVERIFY(udpSocket.initialize(QAbstractSocket::UdpSocket));
QVERIFY(udpSocket.isValid());
QVERIFY(udpSocket.socketDescriptor() != -1);
QVERIFY(udpSocket.protocol() == QAbstractSocket::IPv4Protocol);
QVERIFY(udpSocket.socketType() == QAbstractSocket::UdpSocket);
QVERIFY(udpSocket.state() == QAbstractSocket::UnconnectedState);
// Bind #1 to localhost
QVERIFY(udpSocket.bind(QHostAddress("127.0.0.1"), 0));
QVERIFY(udpSocket.state() == QAbstractSocket::BoundState);
quint16 port = udpSocket.localPort();
QVERIFY(port != 0);
// Initialize device #2
PLATFORMSOCKETENGINE udpSocket2;
QVERIFY(udpSocket2.initialize(QAbstractSocket::UdpSocket));
// Connect device #2 to #1
QVERIFY(udpSocket2.connectToHost(QHostAddress("127.0.0.1"), port));
QVERIFY(udpSocket2.state() == QAbstractSocket::ConnectedState);
const int messageSize = 8192;
QByteArray message1(messageSize, '@');
QByteArray answer(messageSize, '@');
QHostAddress localhost = QHostAddress::LocalHost;
qlonglong readBytes = 0;
QTime timer;
timer.start();
while (timer.elapsed() < 5000) {
udpSocket2.write(message1.data(), message1.size());
udpSocket.waitForRead();
while (udpSocket.hasPendingDatagrams()) {
readBytes += (qlonglong) udpSocket.readDatagram(answer.data(),
answer.size());
}
}
qDebug("\t\t%.1fMB/%.1fs: %.1fMB/s",
readBytes / (1024.0 * 1024.0),
timer.elapsed() / 1024.0,
(readBytes / (timer.elapsed() / 1000.0)) / (1024 * 1024));
}
//---------------------------------------------------------------------------
void tst_PlatformSocketEngine::tcpLoopbackPerformance()
{
PLATFORMSOCKETENGINE server;
// Initialize a Tcp socket
QVERIFY(server.initialize(QAbstractSocket::TcpSocket));
// Bind to any port on all interfaces
QVERIFY(server.bind(QHostAddress("0.0.0.0"), 0));
QVERIFY(server.state() == QAbstractSocket::BoundState);
quint16 port = server.localPort();
// Listen for incoming connections
QVERIFY(server.listen());
QVERIFY(server.state() == QAbstractSocket::ListeningState);
// Initialize a Tcp socket
PLATFORMSOCKETENGINE client;
QVERIFY(client.initialize(QAbstractSocket::TcpSocket));
// Connect to our server
if (!client.connectToHost(QHostAddress("127.0.0.1"), port)) {
QVERIFY(client.state() == QAbstractSocket::ConnectingState);
QVERIFY(client.waitForWrite());
QVERIFY(client.state() == QAbstractSocket::ConnectedState);
}
// The server accepts the connection
int socketDescriptor = server.accept();
QVERIFY(socketDescriptor > 0);
// A socket device is initialized on the server side, passing the
// socket descriptor from accept(). It's pre-connected.
PLATFORMSOCKETENGINE serverSocket;
QVERIFY(serverSocket.initialize(socketDescriptor));
QVERIFY(serverSocket.state() == QAbstractSocket::ConnectedState);
const int messageSize = 1024 * 256;
QByteArray message1(messageSize, '@');
QByteArray answer(messageSize, '@');
QTime timer;
timer.start();
qlonglong readBytes = 0;
while (timer.elapsed() < 5000) {
qlonglong written = serverSocket.write(message1.data(), message1.size());
while (written > 0) {
client.waitForRead();
if (client.bytesAvailable() > 0) {
qlonglong readNow = client.read(answer.data(), answer.size());
written -= readNow;
readBytes += readNow;
}
}
}
qDebug("\t\t%.1fMB/%.1fs: %.1fMB/s",
readBytes / (1024.0 * 1024.0),
timer.elapsed() / 1024.0,
(readBytes / (timer.elapsed() / 1000.0)) / (1024 * 1024));
}
//---------------------------------------------------------------------------
void tst_PlatformSocketEngine::readWriteBufferSize()
{
PLATFORMSOCKETENGINE device;
QVERIFY(device.initialize(QAbstractSocket::TcpSocket));
qint64 bufferSize = device.receiveBufferSize();
QVERIFY(bufferSize != -1);
device.setReceiveBufferSize(bufferSize + 1);
#if defined(Q_OS_WINCE)
QEXPECT_FAIL(0, "Not supported by default on WinCE", Continue);
#endif
QVERIFY(device.receiveBufferSize() > bufferSize);
bufferSize = device.sendBufferSize();
QVERIFY(bufferSize != -1);
device.setSendBufferSize(bufferSize + 1);
QVERIFY(device.sendBufferSize() > bufferSize);
}
//---------------------------------------------------------------------------
void tst_PlatformSocketEngine::tooManySockets()
{
#if defined Q_OS_WIN
QSKIP("Certain windows machines suffocate and spend too much time in this test.");
#endif
QList<PLATFORMSOCKETENGINE *> sockets;
PLATFORMSOCKETENGINE *socketLayer = 0;
for (;;) {
socketLayer = new PLATFORMSOCKETENGINE;
sockets.append(socketLayer);
if (!socketLayer->initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol))
break;
}
QCOMPARE(socketLayer->error(), QAbstractSocket::SocketResourceError);
qDeleteAll(sockets);
}
//---------------------------------------------------------------------------
void tst_PlatformSocketEngine::bind()
{
#if !defined Q_OS_WIN
PLATFORMSOCKETENGINE binder;
QVERIFY(binder.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
QVERIFY(!binder.bind(QHostAddress::AnyIPv4, 82));
QVERIFY(binder.error() == QAbstractSocket::SocketAccessError);
#endif
PLATFORMSOCKETENGINE binder2;
QVERIFY(binder2.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
QVERIFY(binder2.bind(QHostAddress::AnyIPv4, 31180));
PLATFORMSOCKETENGINE binder3;
QVERIFY(binder3.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
QVERIFY(!binder3.bind(QHostAddress::AnyIPv4, 31180));
QVERIFY(binder3.error() == QAbstractSocket::AddressInUseError);
if (QtNetworkSettings::hasIPv6()) {
PLATFORMSOCKETENGINE binder4;
QVERIFY(binder4.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv6Protocol));
QVERIFY(binder4.bind(QHostAddress::AnyIPv6, 31180));
PLATFORMSOCKETENGINE binder5;
QVERIFY(binder5.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv6Protocol));
QVERIFY(!binder5.bind(QHostAddress::AnyIPv6, 31180));
QVERIFY(binder5.error() == QAbstractSocket::AddressInUseError);
}
PLATFORMSOCKETENGINE binder6;
QVERIFY(binder6.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::AnyIPProtocol));
QVERIFY(binder6.bind(QHostAddress::Any, 31181));
}
//---------------------------------------------------------------------------
void tst_PlatformSocketEngine::networkError()
{
PLATFORMSOCKETENGINE client;
QVERIFY(client.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
const bool isConnected = client.connectToHost(QtNetworkSettings::serverIP(), 143);
if (!isConnected) {
QVERIFY(client.state() == QAbstractSocket::ConnectingState);
QVERIFY(client.waitForWrite());
QVERIFY(client.state() == QAbstractSocket::ConnectedState);
}
QVERIFY(client.state() == QAbstractSocket::ConnectedState);
// An unexpected network error!
#ifdef Q_OS_WIN
// could use shutdown to produce different errors
::closesocket(client.socketDescriptor());
#else
::close(client.socketDescriptor());
#endif
QVERIFY(client.read(0, 0) == -1);
}
//---------------------------------------------------------------------------
void tst_PlatformSocketEngine::setSocketDescriptor()
{
PLATFORMSOCKETENGINE socket1;
QVERIFY(socket1.initialize(QAbstractSocket::TcpSocket));
PLATFORMSOCKETENGINE socket2;
QVERIFY(socket2.initialize(socket1.socketDescriptor()));
}
//---------------------------------------------------------------------------
void tst_PlatformSocketEngine::invalidSend()
{
PLATFORMSOCKETENGINE socket;
QVERIFY(socket.initialize(QAbstractSocket::TcpSocket));
QTest::ignoreMessage(QtWarningMsg, PLATFORMSOCKETENGINESTRING "::writeDatagram() was"
" called by a socket other than QAbstractSocket::UdpSocket");
QCOMPARE(socket.writeDatagram("hei", 3, QHostAddress::LocalHost, 143),
(qlonglong) -1);
}
//---------------------------------------------------------------------------
void tst_PlatformSocketEngine::receiveUrgentData()
{
PLATFORMSOCKETENGINE server;
QVERIFY(server.initialize(QAbstractSocket::TcpSocket));
// Bind to any port on all interfaces
QVERIFY(server.bind(QHostAddress("0.0.0.0"), 0));
QVERIFY(server.state() == QAbstractSocket::BoundState);
quint16 port = server.localPort();
QVERIFY(server.listen());
QVERIFY(server.state() == QAbstractSocket::ListeningState);
PLATFORMSOCKETENGINE client;
QVERIFY(client.initialize(QAbstractSocket::TcpSocket));
if (!client.connectToHost(QHostAddress("127.0.0.1"), port)) {
QVERIFY(client.state() == QAbstractSocket::ConnectingState);
QVERIFY(client.waitForWrite());
QVERIFY(client.state() == QAbstractSocket::ConnectedState);
}
int socketDescriptor = server.accept();
QVERIFY(socketDescriptor > 0);
PLATFORMSOCKETENGINE serverSocket;
QVERIFY(serverSocket.initialize(socketDescriptor));
QVERIFY(serverSocket.state() == QAbstractSocket::ConnectedState);
char msg;
int available;
QByteArray response;
// Native OOB data test doesn't work on HP-UX or WinCE
#if !defined(Q_OS_HPUX) && !defined(Q_OS_WINCE)
// The server sends an urgent message
msg = 'Q';
QCOMPARE(int(::send(socketDescriptor, &msg, sizeof(msg), MSG_OOB)), 1);
// The client receives the urgent message
QVERIFY(client.waitForRead());
available = client.bytesAvailable();
QCOMPARE(available, 1);
response.resize(available);
QCOMPARE(client.read(response.data(), response.size()), qint64(1));
QCOMPARE(response.at(0), msg);
// The client sends an urgent message
msg = 'T';
int clientDescriptor = client.socketDescriptor();
QCOMPARE(int(::send(clientDescriptor, &msg, sizeof(msg), MSG_OOB)), 1);
// The server receives the urgent message
QVERIFY(serverSocket.waitForRead());
available = serverSocket.bytesAvailable();
QCOMPARE(available, 1);
response.resize(available);
QCOMPARE(serverSocket.read(response.data(), response.size()), qint64(1));
QCOMPARE(response.at(0), msg);
#endif
}
QTEST_MAIN(tst_PlatformSocketEngine)
#include "tst_platformsocketengine.moc"
| CodeDJ/qt5-hidpi | qt/qtbase/tests/auto/network/socket/platformsocketengine/tst_platformsocketengine.cpp | C++ | lgpl-2.1 | 25,201 |
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 |
/**************************************************************************
**
** Copyright (c) 2014 BogDan Vatra <bog_dan_ro@yahoo.com>
** Copyright (C) 2014 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.
**
****************************************************************************/
#include "androiddeployqtwidget.h"
#include "ui_androiddeployqtwidget.h"
#include "androidcreatekeystorecertificate.h"
#include "androiddeployqtstep.h"
#include "androidmanager.h"
#include "createandroidmanifestwizard.h"
#include "androidextralibrarylistmodel.h"
#include <projectexplorer/target.h>
#include <qmakeprojectmanager/qmakebuildconfiguration.h>
#include <qmakeprojectmanager/qmakeproject.h>
#include <qmakeprojectmanager/qmakenodes.h>
#include <utils/fancylineedit.h>
#include <utils/pathchooser.h>
#include <QFileDialog>
#include <algorithm>
using namespace Android;
using namespace Internal;
AndroidDeployQtWidget::AndroidDeployQtWidget(AndroidDeployQtStep *step)
: ProjectExplorer::BuildStepConfigWidget(),
m_ui(new Ui::AndroidDeployQtWidget),
m_step(step),
m_currentBuildConfiguration(0),
m_ignoreChange(false)
{
m_ui->setupUi(this);
// Target sdk combobox
int minApiLevel = 9;
QStringList targets = AndroidConfig::apiLevelNamesFor(AndroidConfigurations::currentConfig().sdkTargets(minApiLevel));
m_ui->targetSDKComboBox->addItems(targets);
m_ui->targetSDKComboBox->setCurrentIndex(targets.indexOf(step->buildTargetSdk()));
// deployment option
switch (m_step->deployAction()) {
case AndroidDeployQtStep::MinistroDeployment:
m_ui->ministroOption->setChecked(true);
break;
case AndroidDeployQtStep::DebugDeployment:
m_ui->temporaryQtOption->setChecked(true);
break;
case AndroidDeployQtStep::BundleLibrariesDeployment:
m_ui->bundleQtOption->setChecked(true);
break;
default:
// can't happen
break;
}
// signing
m_ui->signPackageCheckBox->setChecked(m_step->signPackage());
m_ui->KeystoreLocationPathChooser->setExpectedKind(Utils::PathChooser::File);
m_ui->KeystoreLocationPathChooser->lineEdit()->setReadOnly(true);
m_ui->KeystoreLocationPathChooser->setPath(m_step->keystorePath().toUserOutput());
m_ui->KeystoreLocationPathChooser->setInitialBrowsePathBackup(QDir::homePath());
m_ui->KeystoreLocationPathChooser->setPromptDialogFilter(tr("Keystore files (*.keystore *.jks)"));
m_ui->KeystoreLocationPathChooser->setPromptDialogTitle(tr("Select keystore file"));
m_ui->signingDebugWarningIcon->hide();
m_ui->signingDebugWarningLabel->hide();
signPackageCheckBoxToggled(m_step->signPackage());
m_ui->verboseOutputCheckBox->setChecked(m_step->verboseOutput());
m_ui->openPackageLocationCheckBox->setChecked(m_step->openPackageLocation());
bool oldFiles = AndroidManager::checkForQt51Files(m_step->project()->projectDirectory().toString());
m_ui->oldFilesWarningIcon->setVisible(oldFiles);
m_ui->oldFilesWarningLabel->setVisible(oldFiles);
// target sdk
connect(m_ui->targetSDKComboBox, SIGNAL(activated(QString)), SLOT(setTargetSdk(QString)));
// deployment options
connect(m_ui->ministroOption, SIGNAL(clicked()), SLOT(setMinistro()));
connect(m_ui->temporaryQtOption, SIGNAL(clicked()), SLOT(setDeployLocalQtLibs()));
connect(m_ui->bundleQtOption, SIGNAL(clicked()), SLOT(setBundleQtLibs()));
connect(m_ui->installMinistroButton, SIGNAL(clicked()), SLOT(installMinistro()));
connect(m_ui->cleanLibsPushButton, SIGNAL(clicked()), SLOT(cleanLibsOnDevice()));
connect(m_ui->resetDefaultDevices, SIGNAL(clicked()), SLOT(resetDefaultDevices()));
connect(m_ui->openPackageLocationCheckBox, SIGNAL(toggled(bool)),
this, SLOT(openPackageLocationCheckBoxToggled(bool)));
connect(m_ui->verboseOutputCheckBox, SIGNAL(toggled(bool)),
this, SLOT(verboseOutputCheckBoxToggled(bool)));
//signing
connect(m_ui->signPackageCheckBox, SIGNAL(toggled(bool)),
this, SLOT(signPackageCheckBoxToggled(bool)));
connect(m_ui->KeystoreCreatePushButton, SIGNAL(clicked()),
this, SLOT(createKeyStore()));
connect(m_ui->KeystoreLocationPathChooser, SIGNAL(pathChanged(QString)),
SLOT(updateKeyStorePath(QString)));
connect(m_ui->certificatesAliasComboBox, SIGNAL(activated(QString)),
this, SLOT(certificatesAliasComboBoxActivated(QString)));
connect(m_ui->certificatesAliasComboBox, SIGNAL(currentIndexChanged(QString)),
this, SLOT(certificatesAliasComboBoxCurrentIndexChanged(QString)));
activeBuildConfigurationChanged();
connect(m_step->target(), SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
this, SLOT(activeBuildConfigurationChanged()));
connect(m_ui->inputFileComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(inputFileComboBoxIndexChanged()));
updateInputFileUi();
connect(m_step, SIGNAL(inputFileChanged()),
this, SLOT(updateInputFileUi()));
connect(m_ui->createAndroidManifestButton, SIGNAL(clicked()),
this, SLOT(createManifestButton()));
m_extraLibraryListModel = new AndroidExtraLibraryListModel(static_cast<QmakeProjectManager::QmakeProject *>(m_step->project()),
this);
m_ui->androidExtraLibsListView->setModel(m_extraLibraryListModel);
connect(m_ui->androidExtraLibsListView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(checkEnableRemoveButton()));
connect(m_ui->addAndroidExtraLibButton, SIGNAL(clicked()), this, SLOT(addAndroidExtraLib()));
connect(m_ui->removeAndroidExtraLibButton, SIGNAL(clicked()), this, SLOT(removeAndroidExtraLib()));
connect(m_extraLibraryListModel, SIGNAL(enabledChanged(bool)),
m_ui->additionalLibrariesGroupBox, SLOT(setEnabled(bool)));
m_ui->additionalLibrariesGroupBox->setEnabled(m_extraLibraryListModel->isEnabled());
}
AndroidDeployQtWidget::~AndroidDeployQtWidget()
{
delete m_ui;
}
void AndroidDeployQtWidget::createManifestButton()
{
CreateAndroidManifestWizard wizard(m_step->target());
wizard.exec();
}
void AndroidDeployQtWidget::updateInputFileUi()
{
QmakeProjectManager::QmakeProject *project
= static_cast<QmakeProjectManager::QmakeProject *>(m_step->project());
QList<QmakeProjectManager::QmakeProFileNode *> nodes = project->applicationProFiles();
int size = nodes.size();
if (size == 0 || size == 1) {
// there's nothing to select, e.g. before parsing
m_ui->inputFileLabel->setVisible(false);
m_ui->inputFileComboBox->setVisible(false);
} else {
m_ignoreChange = true;
m_ui->inputFileLabel->setVisible(true);
m_ui->inputFileComboBox->setVisible(true);
m_ui->inputFileComboBox->clear();
foreach (QmakeProjectManager::QmakeProFileNode *node, nodes)
m_ui->inputFileComboBox->addItem(node->displayName(), node->path());
int index = m_ui->inputFileComboBox->findData(m_step->proFilePathForInputFile());
m_ui->inputFileComboBox->setCurrentIndex(index);
m_ignoreChange = false;
}
}
void AndroidDeployQtWidget::inputFileComboBoxIndexChanged()
{
if (m_ignoreChange)
return;
QString proFilePath = m_ui->inputFileComboBox->itemData(m_ui->inputFileComboBox->currentIndex()).toString();
m_step->setProFilePathForInputFile(proFilePath);
}
QString AndroidDeployQtWidget::displayName() const
{
return tr("<b>Deploy configurations</b>");
}
QString AndroidDeployQtWidget::summaryText() const
{
return displayName();
}
void AndroidDeployQtWidget::setTargetSdk(const QString &sdk)
{
m_step->setBuildTargetSdk(sdk);
}
void AndroidDeployQtWidget::setMinistro()
{
m_step->setDeployAction(AndroidDeployQtStep::MinistroDeployment);
}
void AndroidDeployQtWidget::setDeployLocalQtLibs()
{
m_step->setDeployAction(AndroidDeployQtStep::DebugDeployment);
}
void AndroidDeployQtWidget::setBundleQtLibs()
{
m_step->setDeployAction(AndroidDeployQtStep::BundleLibrariesDeployment);
}
void AndroidDeployQtWidget::installMinistro()
{
QString packagePath =
QFileDialog::getOpenFileName(this, tr("Qt Android Smart Installer"),
QDir::homePath(), tr("Android package (*.apk)"));
if (!packagePath.isEmpty())
AndroidManager::installQASIPackage(m_step->target(), packagePath);
}
void AndroidDeployQtWidget::cleanLibsOnDevice()
{
AndroidManager::cleanLibsOnDevice(m_step->target());
}
void AndroidDeployQtWidget::resetDefaultDevices()
{
AndroidConfigurations::clearDefaultDevices(m_step->project());
}
void AndroidDeployQtWidget::signPackageCheckBoxToggled(bool checked)
{
m_ui->certificatesAliasComboBox->setEnabled(checked);
m_step->setSignPackage(checked);
updateSigningWarning();
if (!checked)
return;
if (!m_step->keystorePath().isEmpty())
setCertificates();
}
void AndroidDeployQtWidget::createKeyStore()
{
AndroidCreateKeystoreCertificate d;
if (d.exec() != QDialog::Accepted)
return;
m_ui->KeystoreLocationPathChooser->setPath(d.keystoreFilePath().toUserOutput());
m_step->setKeystorePath(d.keystoreFilePath());
m_step->setKeystorePassword(d.keystorePassword());
m_step->setCertificateAlias(d.certificateAlias());
m_step->setCertificatePassword(d.certificatePassword());
setCertificates();
}
void AndroidDeployQtWidget::setCertificates()
{
QAbstractItemModel *certificates = m_step->keystoreCertificates();
m_ui->signPackageCheckBox->setChecked(certificates);
m_ui->certificatesAliasComboBox->setModel(certificates);
}
void AndroidDeployQtWidget::updateKeyStorePath(const QString &path)
{
Utils::FileName file = Utils::FileName::fromString(path);
m_step->setKeystorePath(file);
m_ui->signPackageCheckBox->setChecked(!file.isEmpty());
if (!file.isEmpty())
setCertificates();
}
void AndroidDeployQtWidget::certificatesAliasComboBoxActivated(const QString &alias)
{
if (alias.length())
m_step->setCertificateAlias(alias);
}
void AndroidDeployQtWidget::certificatesAliasComboBoxCurrentIndexChanged(const QString &alias)
{
if (alias.length())
m_step->setCertificateAlias(alias);
}
void AndroidDeployQtWidget::openPackageLocationCheckBoxToggled(bool checked)
{
m_step->setOpenPackageLocation(checked);
}
void AndroidDeployQtWidget::verboseOutputCheckBoxToggled(bool checked)
{
m_step->setVerboseOutput(checked);
}
void AndroidDeployQtWidget::activeBuildConfigurationChanged()
{
if (m_currentBuildConfiguration)
disconnect(m_currentBuildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),
this, SLOT(updateSigningWarning()));
updateSigningWarning();
QmakeProjectManager::QmakeBuildConfiguration *bc
= qobject_cast<QmakeProjectManager::QmakeBuildConfiguration *>(m_step->target()->activeBuildConfiguration());
m_currentBuildConfiguration = bc;
if (bc)
connect(bc, SIGNAL(qmakeBuildConfigurationChanged()), this, SLOT(updateSigningWarning()));
m_currentBuildConfiguration = bc;
}
void AndroidDeployQtWidget::updateSigningWarning()
{
QmakeProjectManager::QmakeBuildConfiguration *bc = qobject_cast<QmakeProjectManager::QmakeBuildConfiguration *>(m_step->target()->activeBuildConfiguration());
bool debug = bc && (bc->qmakeBuildConfiguration() & QtSupport::BaseQtVersion::DebugBuild);
if (m_step->signPackage() && debug) {
m_ui->signingDebugWarningIcon->setVisible(true);
m_ui->signingDebugWarningLabel->setVisible(true);
} else {
m_ui->signingDebugWarningIcon->setVisible(false);
m_ui->signingDebugWarningLabel->setVisible(false);
}
}
void AndroidDeployQtWidget::addAndroidExtraLib()
{
QStringList fileNames = QFileDialog::getOpenFileNames(this,
tr("Select additional libraries"),
m_currentBuildConfiguration->target()->project()->projectDirectory().toString(),
tr("Libraries (*.so)"));
if (!fileNames.isEmpty())
m_extraLibraryListModel->addEntries(fileNames);
}
void AndroidDeployQtWidget::removeAndroidExtraLib()
{
QModelIndexList removeList = m_ui->androidExtraLibsListView->selectionModel()->selectedIndexes();
m_extraLibraryListModel->removeEntries(removeList);
}
void AndroidDeployQtWidget::checkEnableRemoveButton()
{
m_ui->removeAndroidExtraLibButton->setEnabled(m_ui->androidExtraLibsListView->selectionModel()->hasSelection());
}
| colede/qtcreator | src/plugins/android/androiddeployqtwidget.cpp | C++ | lgpl-2.1 | 14,080 |
// 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> </td><td> </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='&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 █
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 |
#!/usr/bin/python
# 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 Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# ola_rdm_get.py
# Copyright (C) 2010 Simon Newton
'''Automated testing for RDM responders.'''
__author__ = 'nomis52@gmail.com (Simon Newton)'
from ola.testing.rdm import TestDefinitions, TestRunner
from ola.testing.rdm.DMXSender import DMXSender
from ola.testing.rdm.TestState import TestState
import logging
import re
import sys
import textwrap
import time
from ola import PidStore
from ola.ClientWrapper import ClientWrapper
from ola.UID import UID
from optparse import OptionParser, OptionGroup, OptionValueError
def ParseOptions():
usage = 'Usage: %prog [options] <uid>'
description = textwrap.dedent("""\
Run a series of tests on a RDM responder to check the behaviour.
This requires the OLA server to be running, and the RDM device to have been
detected. You can confirm this by running ola_rdm_discover -u
UNIVERSE. This will send SET commands to the broadcast UIDs which means
the start address, device label etc. will be changed for all devices
connected to the responder. Think twice about running this on your
production lighting rig.
""")
parser = OptionParser(usage, description=description)
parser.add_option('-c', '--slot-count', default=10,
help='Number of slots to send when sending DMX.')
parser.add_option('-d', '--debug', action='store_true',
help='Print debug information to assist in diagnosing '
'failures.')
parser.add_option('-f', '--dmx-frame-rate', default=0,
type='int',
help='Send DMX frames at this rate in the background.')
parser.add_option('-l', '--log', metavar='FILE',
help='Also log to the file named FILE.uid.timestamp.')
parser.add_option('--list-tests', action='store_true',
help='Display a list of all tests')
parser.add_option('-p', '--pid-store', metavar='FILE',
help='The location of the PID definitions.')
parser.add_option('-s', '--skip-check', action='store_true',
help='Skip the check for multiple devices.')
parser.add_option('-t', '--tests', metavar='TEST1,TEST2',
help='A comma separated list of tests to run.')
parser.add_option('--timestamp', action='store_true',
help='Add timestamps to each test.')
parser.add_option('--no-factory-defaults', action='store_true',
help="Don't run the SET factory defaults tests")
parser.add_option('-w', '--broadcast-write-delay', default=0,
type='int',
help='The time in ms to wait after sending broadcast set'
'commands.')
parser.add_option('-u', '--universe', default=0,
type='int',
help='The universe number to use, default is universe 0.')
options, args = parser.parse_args()
if options.list_tests:
return options
if not args:
parser.print_help()
sys.exit(2)
uid = UID.FromString(args[0])
if uid is None:
parser.print_usage()
print 'Invalid UID: %s' % args[0]
sys.exit(2)
options.uid = uid
return options
class MyFilter(object):
"""Filter out the ascii coloring."""
def filter(self, record):
msg = record.msg
record.msg = re.sub('\x1b\[\d*m', '', str(msg))
return True
def SetupLogging(options):
"""Setup the logging for test results."""
level = logging.INFO
if options.debug:
level = logging.DEBUG
logging.basicConfig(
level=level,
format='%(message)s')
if options.log:
file_name = '%s.%s.%d' % (options.log, options.uid, time.time())
file_handler =logging.FileHandler(file_name, 'w')
file_handler.addFilter(MyFilter())
if options.debug:
file_handler.setLevel(logging.DEBUG)
logging.getLogger('').addHandler(file_handler)
def DisplaySummary(tests):
"""Print a summary of the tests."""
by_category = {}
warnings = []
advisories = []
count_by_state = {}
for test in tests:
state = test.state
count_by_state[state] = count_by_state.get(state, 0) + 1
warnings.extend(test.warnings)
advisories.extend(test.advisories)
by_category.setdefault(test.category, {})
by_category[test.category][state] = (1 +
by_category[test.category].get(state, 0))
total = sum(count_by_state.values())
logging.info('------------------- Warnings --------------------')
for warning in sorted(warnings):
logging.info(warning)
logging.info('------------------ Advisories -------------------')
for advisory in sorted(advisories):
logging.info(advisory)
logging.info('------------------ By Category ------------------')
for category, counts in by_category.iteritems():
passed = counts.get(TestState.PASSED, 0)
total_run = (passed + counts.get(TestState.FAILED, 0))
if total_run == 0:
continue
percent = 1.0 * passed / total_run
logging.info(' %26s: %3d / %3d %.0f%%' %
(category, passed, total_run, percent * 100))
logging.info('-------------------------------------------------')
logging.info('%d / %d tests run, %d passed, %d failed, %d broken' % (
total - count_by_state.get(TestState.NOT_RUN, 0),
total,
count_by_state.get(TestState.PASSED, 0),
count_by_state.get(TestState.FAILED, 0),
count_by_state.get(TestState.BROKEN, 0)))
def main():
options = ParseOptions()
test_classes = TestRunner.GetTestClasses(TestDefinitions)
if options.list_tests:
for test_name in sorted(c.__name__ for c in test_classes):
print test_name
sys.exit(0)
SetupLogging(options)
pid_store = PidStore.GetStore(options.pid_store, ('pids.proto',))
wrapper = ClientWrapper()
global uid_ok
uid_ok = False
def UIDList(state, uids):
wrapper.Stop()
global uid_ok
if not state.Succeeded():
logging.error('Fetch failed: %s' % state.message)
return
for uid in uids:
if uid == options.uid:
logging.debug('Found UID %s' % options.uid)
uid_ok = True
if not uid_ok:
logging.error('UID %s not found in universe %d' %
(options.uid, options.universe))
return
if len(uids) > 1:
logging.info(
'The following devices were detected and will be reconfigured')
for uid in uids:
logging.info(' %s' % uid)
if not options.skip_check:
logging.info('Continue ? [Y/n]')
response = raw_input().strip().lower()
uid_ok = response == 'y' or response == ''
logging.debug('Fetching UID list from server')
wrapper.Client().FetchUIDList(options.universe, UIDList)
wrapper.Run()
wrapper.Reset()
if not uid_ok:
sys.exit()
test_filter = None
if options.tests is not None:
logging.info('Restricting tests to %s' % options.tests)
test_filter = set(options.tests.split(','))
logging.info(
'Starting tests, universe %d, UID %s, broadcast write delay %dms' %
(options.universe, options.uid, options.broadcast_write_delay))
runner = TestRunner.TestRunner(options.universe,
options.uid,
options.broadcast_write_delay,
pid_store,
wrapper,
options.timestamp)
for test_class in test_classes:
runner.RegisterTest(test_class)
dmx_sender = DMXSender(wrapper,
options.universe,
options.dmx_frame_rate,
options.slot_count)
tests, device = runner.RunTests(test_filter, options.no_factory_defaults)
DisplaySummary(tests)
if __name__ == '__main__':
main()
| mlba-team/open-lighting | tools/rdm/rdm_responder_test.py | Python | lgpl-2.1 | 8,444 |
/*
* 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 |
/*
* Cacheonix Systems licenses this file to You under the LGPL 2.1
* (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.cacheonix.org/products/cacheonix/license-lgpl-2.1.htm
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cacheonix.impl.config;
import org.w3c.dom.Attr;
import org.w3c.dom.Node;
/**
* Class CoherenceConfiguration.
*/
public final class CoherenceConfiguration extends DocumentReader {
/**
* A parent.
*/
private PartitionedCacheStoreConfiguration partitionedCacheStoreConfiguration = null;
/**
* Field lease.
*/
private LeaseConfiguration lease = null;
/**
* Sets the parent.
*
* @param configuration the parent.
*/
public void setPartitionedCacheStoreConfiguration(final PartitionedCacheStoreConfiguration configuration) {
this.partitionedCacheStoreConfiguration = configuration;
}
/**
* Returns the parent.
*
* @return the parent.
*/
public PartitionedCacheStoreConfiguration getPartitionedCacheStoreConfiguration() {
return partitionedCacheStoreConfiguration;
}
/**
* Returns the value of field 'lease'.
*
* @return the value of field 'Lease'.
*/
public LeaseConfiguration getLease() {
return this.lease;
}
/**
* Sets the value of field 'lease'.
*
* @param lease the value of field 'lease'.
*/
public void setLease(final LeaseConfiguration lease) {
this.lease = lease;
}
public void setUpDefaults() {
// Create lease configuration
setUpDefaultLease();
}
private void setUpDefaultLease() {
lease = new LeaseConfiguration();
lease.setCoherenceConfiguration(this);
lease.setUpDefaults();
}
protected void readNode(final String nodeName, final Node node) {
if ("lease".equals(nodeName)) {
lease = new LeaseConfiguration();
lease.setCoherenceConfiguration(this);
lease.read(node);
}
}
protected void readAttribute(final String attributeName, final Attr attributeNode, final String attributeValue) {
// This element doesn't have attributes yet
}
protected void postProcessRead() {
if (lease == null) {
setUpDefaultLease();
}
}
public String toString() {
return "CoherenceConfiguration{" +
"lease=" + lease +
'}';
}
}
| cacheonix/cacheonix-core | src/org/cacheonix/impl/config/CoherenceConfiguration.java | Java | lgpl-2.1 | 2,778 |
/*
* 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 |
/*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h"
#include "platform/WebLayer.h"
#include "CompositorFakeWebGraphicsContext3D.h"
#include "WebCompositor.h"
#include "platform/WebContentLayer.h"
#include "platform/WebContentLayerClient.h"
#include "platform/WebExternalTextureLayer.h"
#include "platform/WebFloatPoint.h"
#include "platform/WebFloatRect.h"
#include "platform/WebLayerTreeView.h"
#include "platform/WebLayerTreeViewClient.h"
#include "platform/WebRect.h"
#include "platform/WebSize.h"
#include <gmock/gmock.h>
using namespace WebKit;
using testing::AnyNumber;
using testing::AtLeast;
using testing::Mock;
using testing::Test;
using testing::_;
namespace {
class MockWebLayerTreeViewClient : public WebLayerTreeViewClient {
public:
MOCK_METHOD0(scheduleComposite, void());
virtual void updateAnimations(double frameBeginTime) { }
virtual void didBeginFrame() { }
virtual void layout() { }
virtual void applyScrollAndScale(const WebSize& scrollDelta, float scaleFactor) { }
virtual WebGraphicsContext3D* createContext3D() { return CompositorFakeWebGraphicsContext3D::create(WebGraphicsContext3D::Attributes()).leakPtr(); }
virtual void didRebindGraphicsContext(bool success) { }
virtual void willCommit() { }
virtual void didCommitAndDrawFrame() { }
virtual void didCompleteSwapBuffers() { }
};
class MockWebContentLayerClient : public WebContentLayerClient {
public:
MOCK_METHOD3(paintContents, void(WebCanvas*, const WebRect& clip, WebFloatRect& opaque));
};
class WebLayerTest : public Test {
public:
virtual void SetUp()
{
// Initialize without threading support.
WebKit::WebCompositor::initialize(0);
m_rootLayer = WebLayer::create();
EXPECT_CALL(m_client, scheduleComposite()).Times(AnyNumber());
EXPECT_TRUE(m_view.initialize(&m_client, m_rootLayer, WebLayerTreeView::Settings()));
Mock::VerifyAndClearExpectations(&m_client);
}
virtual void TearDown()
{
// We may get any number of scheduleComposite calls during shutdown.
EXPECT_CALL(m_client, scheduleComposite()).Times(AnyNumber());
m_view.setRootLayer(0);
m_rootLayer.reset();
m_view.reset();
WebKit::WebCompositor::shutdown();
}
protected:
MockWebLayerTreeViewClient m_client;
WebLayer m_rootLayer;
WebLayerTreeView m_view;
};
// Tests that the client gets called to ask for a composite if we change the
// fields.
TEST_F(WebLayerTest, Client)
{
// Base layer.
EXPECT_CALL(m_client, scheduleComposite()).Times(AnyNumber());
WebLayer layer = WebLayer::create();
m_rootLayer.addChild(layer);
Mock::VerifyAndClearExpectations(&m_client);
WebFloatPoint point(3, 4);
EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1));
layer.setAnchorPoint(point);
Mock::VerifyAndClearExpectations(&m_client);
EXPECT_EQ(point, layer.anchorPoint());
EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1));
float anchorZ = 5;
layer.setAnchorPointZ(anchorZ);
Mock::VerifyAndClearExpectations(&m_client);
EXPECT_EQ(anchorZ, layer.anchorPointZ());
WebSize size(7, 8);
EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1));
layer.setBounds(size);
Mock::VerifyAndClearExpectations(&m_client);
EXPECT_EQ(size, layer.bounds());
EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1));
layer.setMasksToBounds(true);
Mock::VerifyAndClearExpectations(&m_client);
EXPECT_TRUE(layer.masksToBounds());
EXPECT_CALL(m_client, scheduleComposite()).Times(AnyNumber());
WebLayer otherLayer = WebLayer::create();
m_rootLayer.addChild(otherLayer);
EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1));
layer.setMaskLayer(otherLayer);
Mock::VerifyAndClearExpectations(&m_client);
EXPECT_EQ(otherLayer, layer.maskLayer());
EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1));
float opacity = 0.123f;
layer.setOpacity(opacity);
Mock::VerifyAndClearExpectations(&m_client);
EXPECT_EQ(opacity, layer.opacity());
EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1));
layer.setOpaque(true);
Mock::VerifyAndClearExpectations(&m_client);
EXPECT_TRUE(layer.opaque());
EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1));
layer.setPosition(point);
Mock::VerifyAndClearExpectations(&m_client);
EXPECT_EQ(point, layer.position());
// Texture layer.
EXPECT_CALL(m_client, scheduleComposite()).Times(AnyNumber());
WebExternalTextureLayer textureLayer = WebExternalTextureLayer::create();
m_rootLayer.addChild(textureLayer);
Mock::VerifyAndClearExpectations(&m_client);
EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1));
textureLayer.setTextureId(3);
Mock::VerifyAndClearExpectations(&m_client);
EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1));
textureLayer.setFlipped(true);
Mock::VerifyAndClearExpectations(&m_client);
EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1));
WebFloatRect uvRect(0.1f, 0.1f, 0.9f, 0.9f);
textureLayer.setUVRect(uvRect);
Mock::VerifyAndClearExpectations(&m_client);
// Content layer.
MockWebContentLayerClient contentClient;
EXPECT_CALL(contentClient, paintContents(_, _, _)).Times(AnyNumber());
EXPECT_CALL(m_client, scheduleComposite()).Times(AnyNumber());
WebContentLayer contentLayer = WebContentLayer::create(&contentClient);
m_rootLayer.addChild(contentLayer);
Mock::VerifyAndClearExpectations(&m_client);
EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1));
contentLayer.setDrawsContent(false);
Mock::VerifyAndClearExpectations(&m_client);
EXPECT_FALSE(contentLayer.drawsContent());
}
TEST_F(WebLayerTest, Hierarchy)
{
EXPECT_CALL(m_client, scheduleComposite()).Times(AnyNumber());
WebLayer layer1 = WebLayer::create();
WebLayer layer2 = WebLayer::create();
EXPECT_TRUE(layer1.parent().isNull());
EXPECT_TRUE(layer2.parent().isNull());
layer1.addChild(layer2);
EXPECT_TRUE(layer1.parent().isNull());
EXPECT_EQ(layer1, layer2.parent());
layer2.removeFromParent();
EXPECT_TRUE(layer2.parent().isNull());
layer1.addChild(layer2);
EXPECT_EQ(layer1, layer2.parent());
layer1.removeAllChildren();
EXPECT_TRUE(layer2.parent().isNull());
MockWebContentLayerClient contentClient;
EXPECT_CALL(contentClient, paintContents(_, _, _)).Times(AnyNumber());
WebContentLayer contentLayer = WebContentLayer::create(&contentClient);
WebExternalTextureLayer textureLayer = WebExternalTextureLayer::create();
textureLayer.addChild(contentLayer);
contentLayer.addChild(layer1);
layer1.addChild(layer2);
// Release reference on all layers, checking that destruction (which may
// generate calls to the client) doesn't crash.
layer2.reset();
layer1.reset();
contentLayer.reset();
textureLayer.reset();
}
}
| youfoh/webkit-efl | Source/WebKit/chromium/tests/WebLayerTest.cpp | C++ | lgpl-2.1 | 8,366 |
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 |
<?php
/**
* @author Laurent Jouanneau
* @copyright 2018 Laurent Jouanneau
* @link http://www.jelix.org
* @licence GNU Lesser General Public Licence see LICENCE file or http://www.gnu.org/licenses/lgpl.html
*/
use \Jelix\Installer\Module\API\ConfigurationHelpers;
class jminifyModuleConfigurator extends \Jelix\Installer\Module\Configurator {
public function getDefaultParameters()
{
return array(
'eps'=>array('index')
);
}
public function configure(ConfigurationHelpers $helpers) {
$this->parameters['eps'] = $helpers->cli()->askEntryPoints(
'Select entry points on which to setup jminify',
'classic',
true
);
$helpers->copyFile('files/minifyConfig.php', 'config:minifyConfig.php');
$helpers->copyFile('files/minifyGroupsConfig.php', 'config:minifyGroupsConfig.php');
foreach($this->getParameter('eps') as $epId) {
$this->configureEntryPoint($helpers, $epId);
}
}
public function configureEntryPoint(ConfigurationHelpers $helpers, $epId) {
$entryPoint = $helpers->getEntryPointsById($epId);
$config = $entryPoint->getConfigIni();
$plugins = $config->getValue('plugins','jResponseHtml');
if (strpos($plugins, 'minify') === false) {
$plugins .= ',minify';
$config->setValue('plugins',$plugins,'jResponseHtml', null, true);
}
if (null == $config->getValue('minifyCSS','jResponseHtml', null, true)) {
$config->setValue('minifyCSS','off','jResponseHtml', null, true);
}
if (null == $config->getValue('minifyJS','jResponseHtml', null, true)) {
$config->setValue('minifyJS','on','jResponseHtml', null, true);
}
if (null == $config->getValue('minifyExcludeCSS','jResponseHtml', null, true)) {
$config->setValue('minifyExcludeCSS','','jResponseHtml', null, true);
}
if (null == $config->getValue('minifyExcludeJS','jResponseHtml', null, true)) {
$config->setValue('minifyExcludeJS','jelix/wymeditor/jquery.wymeditor.js','jResponseHtml', null, true);
}
$entrypointMinify = $config->getValue('minifyEntryPoint','jResponseHtml', null, true);
if ($entrypointMinify === null) {
$config->setValue('minifyEntryPoint','minify.php','jResponseHtml', null, true);
$entrypointMinify = 'minify.php';
}
if (!file_exists(jApp::wwwPath($entrypointMinify))) {
$this->copyFile('files/minify.php', jApp::wwwPath($entrypointMinify));
}
}
public function unconfigure(ConfigurationHelpers $helpers) {
$helpers->removeFile('config:minifyConfig.php');
$helpers->removeFile('config:minifyGroupsConfig.php');
foreach($this->getParameter('eps') as $epId) {
$this->unconfigureEntryPoint($epId);
}
}
public function unconfigureEntryPoint(ConfigurationHelpers $helpers, $epId) {
$entryPoint = $helpers->getEntryPointsById($epId);
$config = $entryPoint->getConfigIni();
$plugins = $config->getValue('plugins','jResponseHtml');
if (strpos($plugins, 'minify') !== false) {
$plugins = str_replace('minify', '', $plugins);
$plugins = str_replace(',,', ',', $plugins);
$config->setValue('plugins',$plugins,'jResponseHtml', null, true);
}
$config->removeValue('minifyCSS', 'jResponseHtml');
$config->removeValue('minifyJS','jResponseHtml');
$config->removeValue('minifyExcludeCSS','jResponseHtml');
$config->removeValue('minifyExcludeJS','jResponseHtml');
$entrypointMinify = $config->getValue('minifyEntryPoint','jResponseHtml', null, true);
if ($entrypointMinify !== null) {
$config->removeValue('minifyEntryPoint','jResponseHtml');
}
if (file_exists(jApp::wwwPath($entrypointMinify))) {
unlink(jApp::wwwPath($entrypointMinify));
}
}
} | jelix/minify-module | jminify/install/configure.php | PHP | lgpl-2.1 | 4,071 |
#! /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 |
package org.geotools.data;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.awt.geom.AffineTransform;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import org.junit.Test;
public class WorldFileWriterTest {
@Test
public void testWrite() throws Exception {
AffineTransform at = new AffineTransform(42.34, 0, 0, -42.34, 347671.10, 5196940.18);
File tmp = File.createTempFile("write", "wld", new File("target"));
new WorldFileWriter(tmp, at);
try (BufferedReader r = new BufferedReader(new FileReader(tmp))) {
assertEquals(42.34, Double.parseDouble(r.readLine()), 0.1);
assertEquals(0, Double.parseDouble(r.readLine()), 0.1);
assertEquals(0, Double.parseDouble(r.readLine()), 0.1);
assertEquals(-42.34, Double.parseDouble(r.readLine()), 0.1);
assertEquals(347671.10, Double.parseDouble(r.readLine()), 0.1);
assertEquals(5196940.18, Double.parseDouble(r.readLine()), 0.1);
assertNull(r.readLine());
}
}
}
| geotools/geotools | modules/library/main/src/test/java/org/geotools/data/WorldFileWriterTest.java | Java | lgpl-2.1 | 1,127 |
/*
* 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) 2008 Miguel Rojas <miguelrojasch@yahoo.es>
*
* Contact: cdk-devel@lists.sourceforge.net
*
* 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.
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace NCDK.Reactions.Mechanisms
{
/// <summary>
/// Tests for TautomerizationMechanism implementations.
/// </summary>
// @cdk.module test-reaction
[TestClass()]
public class TautomerizationMechanismTest : ReactionMechanismTest
{
public TautomerizationMechanismTest()
: base()
{
SetMechanism(typeof(TautomerizationMechanism));
}
[TestMethod()]
public void TestTautomerizationMechanism()
{
var mechanism = new TautomerizationMechanism();
Assert.IsNotNull(mechanism);
}
[TestMethod()]
public void TestInitiate_IAtomContainerSet_ArrayList_ArrayList()
{
var mechanism = new TautomerizationMechanism();
Assert.IsNotNull(mechanism);
}
}
}
| kazuyaujihara/NCDK | NCDKTests/Reactions/Mechanisms/TautomerizationMechanismTest.cs | C# | lgpl-2.1 | 1,737 |
/****************************************************************************
**
** 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 |