code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* libquvi * Copyright (C) 2012 Toni Gundogdu <[email protected]> * * This file is part of libquvi <http://quvi.sourceforge.net/>. * * This library is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General * Public License along with this library. If not, see * <http://www.gnu.org/licenses/>. */ #include "config.h" #include <lauxlib.h> #include <lualib.h> #include <glib.h> #include "quvi.h" /* -- */ #include "_quvi_s.h" #include "_quvi_media_s.h" /* -- */ #include "lua/load_util_script.h" #include "lua/setfield.h" #include "lua/def.h" static const gchar script_fname[]= "resolve_redirections.lua"; static const gchar script_func[] = "resolve_redirections"; /* Resolve URL redirections with exception rules. */ gchar *l_exec_util_resolve_redirections(_quvi_t q, const gchar *url) { lua_State *l; gchar *r; q->status.rc = l_load_util_script(q, script_fname, script_func); if (quvi_ok(q) == QUVI_FALSE) return (NULL); l = q->handle.lua; l_setfield_s(l, US_INPUT_URL, url, -1); /* Set as qargs.input_url */ /* * 1=qargs [qargs: set in l_load_util_script] * 1=returns a string */ if (lua_pcall(l, 1, 1, 0)) { g_string_assign(q->status.errmsg, lua_tostring(l, -1)); /* Keep error code if it was set by a callback: quvi.resolve * calling the network callback responsible for resolving URL * redirections. The error is most likely a network error. */ if (q->status.rc != QUVI_ERROR_CALLBACK) q->status.rc = QUVI_ERROR_SCRIPT; return (NULL); } r = NULL; if (lua_isstring(l, -1)) { const gchar *s = lua_tostring(l, -1); if (g_strcmp0(s, url) != 0) /* Ignore, unless it is different. */ r = g_strdup(s); } else luaL_error(l, "%s: did not return a string", script_func); lua_pop(l, 1); /* quvi.resolve which is called from the script sets q->status.rc . */ return (r); } /* vim: set ts=2 sw=2 tw=72 expandtab: */
mogaal/libquvi
src/lua/util/exec_util_resolve_redirections.c
C
agpl-3.0
2,465
<?php /** * @defgroup plugins_citationFormats_apa */ /** * @file plugins/citationFormats/apa/index.php * * Copyright (c) 2003-2012 John Willinsky * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING. * * @ingroup plugins_citationFormats_apa * @brief Wrapper for APA citation plugin. * */ // $Id$ require_once('ApaCitationPlugin.inc.php'); return new ApaCitationPlugin(); ?>
ingmarschuster/MindResearchRepository
ojs-2.3.8/plugins/citationFormats/apa/index.php
PHP
agpl-3.0
417
require_relative '../test_helper' class PingControllerTest < ActionController::TestCase test "ping" do get :ping assert_equal "pong", @response.body assert @response.headers["Content-Type"] =~ /\btext\/plain\b/ end end
malmostad/kulturproceduren
test/functional/ping_controller_test.rb
Ruby
agpl-3.0
242
/* * digitalpetri OPC-UA SDK * * Copyright (C) 2015 Kevin Herron * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.digitalpetri.opcua.sdk.server.model.objects; import java.util.Optional; import com.digitalpetri.opcua.sdk.core.model.objects.StateType; import com.digitalpetri.opcua.sdk.server.api.UaNamespace; import com.digitalpetri.opcua.sdk.server.util.UaObjectType; import com.digitalpetri.opcua.stack.core.types.builtin.DataValue; import com.digitalpetri.opcua.stack.core.types.builtin.LocalizedText; import com.digitalpetri.opcua.stack.core.types.builtin.NodeId; import com.digitalpetri.opcua.stack.core.types.builtin.QualifiedName; import com.digitalpetri.opcua.stack.core.types.builtin.Variant; import com.digitalpetri.opcua.stack.core.types.builtin.unsigned.UByte; import com.digitalpetri.opcua.stack.core.types.builtin.unsigned.UInteger; @UaObjectType(name = "StateType") public class StateNode extends BaseObjectNode implements StateType { public StateNode( UaNamespace namespace, NodeId nodeId, QualifiedName browseName, LocalizedText displayName, Optional<LocalizedText> description, Optional<UInteger> writeMask, Optional<UInteger> userWriteMask, UByte eventNotifier) { super(namespace, nodeId, browseName, displayName, description, writeMask, userWriteMask, eventNotifier); } public UInteger getStateNumber() { Optional<UInteger> stateNumber = getProperty("StateNumber"); return stateNumber.orElse(null); } public synchronized void setStateNumber(UInteger stateNumber) { getPropertyNode("StateNumber").ifPresent(n -> { n.setValue(new DataValue(new Variant(stateNumber))); }); } }
bencaldwell/ua-server-sdk
ua-server/src/main/java/com/digitalpetri/opcua/sdk/server/model/objects/StateNode.java
Java
agpl-3.0
2,415
<%! from django.core.urlresolvers import reverse %> <%! from django.utils.translation import ugettext as _ %> <div class="wrapper-header wrapper" id="view-top"> <header class="primary" role="banner"> <div class="wrapper wrapper-l"> ## "edX Studio" should not be translated <h1 class="branding"><a href="/"><img src="/static/img/logo-edx-studio.png" alt="edX Studio" /></a></h1> % if context_course: <% ctx_loc = context_course.location %> <h2 class="info-course"> <span class="sr">${_("Current Course:")}</span> <a class="course-link" href="${reverse('course_index', kwargs=dict(org=ctx_loc.org, course=ctx_loc.course, name=ctx_loc.name))}"> <span class="course-org">${ctx_loc.org}</span><span class="course-number">${ctx_loc.course}</span> <span class="course-title" title="${context_course.display_name_with_default}">${context_course.display_name_with_default}</span> </a> </h2> <nav class="nav-course nav-dd ui-left"> <h2 class="sr">${_("{course_name}'s Navigation:").format(course_name=context_course.display_name_with_default)}</h2> <ol> <li class="nav-item nav-course-courseware"> <h3 class="title"><span class="label"><span class="label-prefix sr">${_("Course")} </span>${_("Content")}</span> <i class="icon-caret-down ui-toggle-dd"></i></h3> <div class="wrapper wrapper-nav-sub"> <div class="nav-sub"> <ul> <li class="nav-item nav-course-courseware-outline"> <a href="${reverse('course_index', kwargs=dict(org=ctx_loc.org, course=ctx_loc.course, name=ctx_loc.name))}">${_("Outline")}</a> </li> <li class="nav-item nav-course-courseware-updates"> <a href="${reverse('course_info', kwargs=dict(org=ctx_loc.org, course=ctx_loc.course, name=ctx_loc.name))}">${_("Updates")}</a> </li> <li class="nav-item nav-course-courseware-pages"> <a href="${reverse('edit_tabs', kwargs=dict(org=ctx_loc.org, course=ctx_loc.course, coursename=ctx_loc.name))}">${_("Static Pages")}</a> </li> <li class="nav-item nav-course-courseware-uploads"> <a href="${reverse('asset_index', kwargs=dict(org=ctx_loc.org, course=ctx_loc.course, name=ctx_loc.name))}">${_("Files &amp; Uploads")}</a> </li> <li class="nav-item nav-course-courseware-textbooks"> <a href="${reverse('textbook_index', kwargs=dict(org=ctx_loc.org, course=ctx_loc.course, name=ctx_loc.name))}">${_("Textbooks")}</a> </li> </ul> </div> </div> </li> <li class="nav-item nav-course-settings"> <h3 class="title"><span class="label"><span class="label-prefix sr">${_("Course")} </span>${_("Settings")}</span> <i class="icon-caret-down ui-toggle-dd"></i></h3> <div class="wrapper wrapper-nav-sub"> <div class="nav-sub"> <ul> <li class="nav-item nav-course-settings-schedule"> <a href="${reverse('contentstore.views.get_course_settings', kwargs=dict(org=ctx_loc.org, course=ctx_loc.course, name=ctx_loc.name))}">${_("Schedule &amp; Details")}</a> </li> <li class="nav-item nav-course-settings-grading"> <a href="${reverse('contentstore.views.course_config_graders_page', kwargs={'org' : ctx_loc.org, 'course' : ctx_loc.course, 'name': ctx_loc.name})}">${_("Grading")}</a> </li> <li class="nav-item nav-course-settings-team"> <a href="${reverse('manage_users', kwargs=dict(location=ctx_loc))}">${_("Course Team")}</a> </li> <li class="nav-item nav-course-settings-advanced"> <a href="${reverse('course_advanced_settings', kwargs={'org' : ctx_loc.org, 'course' : ctx_loc.course, 'name': ctx_loc.name})}">${_("Advanced Settings")}</a> </li> </ul> </div> </div> </li> <li class="nav-item nav-course-tools"> <h3 class="title"><span class="label">${_("Tools")}</span> <i class="icon-caret-down ui-toggle-dd"></i></h3> <div class="wrapper wrapper-nav-sub"> <div class="nav-sub"> <ul> <li class="nav-item nav-course-tools-checklists"> <a href="${reverse('checklists', kwargs=dict(org=ctx_loc.org, course=ctx_loc.course, name=ctx_loc.name))}">${_("Checklists")}</a> </li> <li class="nav-item nav-course-tools-import"> <a href="${reverse('import_course', kwargs=dict(org=ctx_loc.org, course=ctx_loc.course, name=ctx_loc.name))}">${_("Import")}</a> </li> <li class="nav-item nav-course-tools-export"> <a href="${reverse('export_course', kwargs=dict(org=ctx_loc.org, course=ctx_loc.course, name=ctx_loc.name))}">${_("Export")}</a> </li> </ul> </div> </div> </li> </ol> </nav> % endif </div> <div class="wrapper wrapper-r"> % if user.is_authenticated(): <nav class="nav-account nav-is-signedin nav-dd ui-right"> <h2 class="sr">${_("Help &amp; Account Navigation")}</h2> <ol> <li class="nav-item nav-account-help"> <h3 class="title"><span class="label">${_("Help")}</span> <i class="icon-caret-down ui-toggle-dd"></i></h3> <div class="wrapper wrapper-nav-sub"> <div class="nav-sub"> <ul> <li class="nav-item nav-help-documentation"> <a href="http://files.edx.org/Getting_Started_with_Studio.pdf" title="${_("This is a PDF Document")}">${_("Studio Documentation")}</a> </li> <li class="nav-item nav-help-helpcenter"> <a href="http://help.edge.edx.org/" rel="external">${_("Studio Help Center")}</a> </li> <li class="nav-item nav-help-feedback"> <a href="http://help.edge.edx.org/discussion/new" class="show-tender" title="${_("Use our feedback tool, Tender, to share your feedback")}">${_("Contact Us")}</a> </li> </ul> </div> </div> </li> <li class="nav-item nav-account-user"> <h3 class="title"><span class="label"><span class="label-prefix sr">${_("Currently signed in as:")}</span><span class="account-username" title="${ user.username }">${ user.username }</span></span> <i class="icon-caret-down ui-toggle-dd"></i></h3> <div class="wrapper wrapper-nav-sub"> <div class="nav-sub"> <ul> <li class="nav-item nav-account-dashboard"> <a href="/">${_("My Courses")}</a> </li> <li class="nav-item nav-account-signout"> <a class="action action-signout" href="${reverse('logout')}">${_("Sign Out")}</a> </li> </ul> </div> </div> </li> </ol> </nav> % else: <nav class="nav-not-signedin nav-pitch"> <h2 class="sr">${_("You're not currently signed in")}</h2> <ol> <li class="nav-item nav-not-signedin-hiw"> <a href="/">${_("How Studio Works")}</a> </li> <li class="nav-item nav-not-signedin-help"> <a href="http://help.edge.edx.org/" rel="external">${_("Studio Help")}</a> </li> <li class="nav-item nav-not-signedin-signup"> <a class="action action-signup" href="${reverse('signup')}">${_("Sign Up")}</a> </li> <li class="nav-item nav-not-signedin-signin"> <a class="action action-signin" href="${reverse('login')}">${_("Sign In")}</a> </li> </ol> </nav> % endif </div> </header> </div>
rationalAgent/edx-platform-custom
cms/templates/widgets/header.html
HTML
agpl-3.0
8,317
#ifndef GT_GTL_CHECKING_STATEMENT_DRIVER_HPP_INCLUDED #define GT_GTL_CHECKING_STATEMENT_DRIVER_HPP_INCLUDED ////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @file gt/gtl/checking_statement_driver.hpp * @brief Defines GT::GTL::CheckingStatementDriver class. * @copyright (C) 2013-2014 * @author Mateusz Kubuszok * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, * see [http://www.gnu.org/licenses/]. */ ////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace GT { namespace GTL { ////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @class CheckingStatementDriver * @brief Implementation used for handling statements via CheckingDriver. * * Performs only syntax/type checking on statements' tokens. * * @author Mateusz Kubuszok * * @see CheckingDriver * @see StatementDriver */ class CheckingStatementDriver final : public StatementDriver { /** * @brief Implementation of a main Driver. */ Driver* driver; public: /** * @brief Initiates CheckingStatementDriver with its parent. * * @param parentDriver parent Driver */ explicit CheckingStatementDriver( Driver* parentDriver ); /** * @brief Executes Definition saving Object under defined name. * * @param definition definition to execute */ virtual bool executeDefinition( const DefinitionPtr* definition ) override; /** * @brief Executes Query saving Object under defined name. * * @param query query to execute */ virtual bool executeQuery( const QueryPtr* query ) override; /** * @brief Creates Definition saving Object under defined name. * * @param inputLocation input location of created Definition * @param identifier name of defined Object * @param object defined Object * @return Definition */ virtual DefinitionPtr* createDefinition( const InputLocation& inputLocation, const IdentifierPtr* identifier, const ObjectPtr* object ) const override; /** * @brief Creates Query for given properties. * * @param inputLocation input location of created Definition * @param identifiers queried properties * @param objects queried Object * @param conditions Conditions * @return Query */ virtual QueryPtr* createQuery( const InputLocation& inputLocation, const IdentifiersPtr* identifiers, const ObjectsPtr* objects, const ConditionsPtr* conditions ) const override; /** * @brief CheckingStatementDriver's Message. * * @return message */ virtual Message toString() const override; }; /* END class CheckingStatementDriver */ ////////////////////////////////////////////////////////////////////////////////////////////////////////////// } /* END namespace GTL */ } /* END namespace GT */ #endif /* END #ifndef GT_GTL_CHECKING_STATEMENT_DRIVER_HPP_INCLUDED */
MateuszKubuszok/MasterThesis
src/gt/gtl/checking_statement_driver.hpp
C++
agpl-3.0
3,797
/* * RapidMiner * * Copyright (C) 2001-2014 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator.learner.bayes; import java.util.ArrayList; import java.util.Collection; import com.rapidminer.example.Attribute; import com.rapidminer.example.Attributes; import com.rapidminer.example.Example; import com.rapidminer.example.ExampleSet; import com.rapidminer.tools.Tools; import com.rapidminer.tools.math.VectorMath; import com.rapidminer.tools.math.distribution.DiscreteDistribution; import com.rapidminer.tools.math.distribution.Distribution; import com.rapidminer.tools.math.distribution.NormalDistribution; /** * DistributionModel is a model for learners which estimate distributions of attribute values from example sets like * NaiveBayes. * * Predictions are calculated as product of the conditional probabilities for all attributes times the class * probability. * * The basic learning concept is to simply count occurrences of classes and attribute values. This means no * probabilities are calculated during the learning step. This is only done before output. Optionally, this calculation * can apply a Laplace correction which means in particular that zero probabilities are avoided which would hide * information in distributions of other attributes. * * @author Tobias Malbrecht */ public class SimpleDistributionModel extends DistributionModel { private static final long serialVersionUID = -402827845291958569L; private static final String UNKNOWN_VALUE_NAME = "unknown"; public static final int INDEX_VALUE_SUM = 0; public static final int INDEX_SQUARED_VALUE_SUM = 1; public static final int INDEX_MISSING_WEIGHTS = 2; public static final int INDEX_MEAN = 0; public static final int INDEX_STANDARD_DEVIATION = 1; public static final int INDEX_LOG_FACTOR = 2; /** The number of classes. */ private int numberOfClasses; /** The number of attributes. */ private int numberOfAttributes; /** Flags indicating which attribute is nominal. */ private boolean[] nominal; /** Class name (used for result displaying). */ private String className; /** Class values (used for result displaying). */ private String[] classValues; /** Attribute names (used for result displaying). */ private String[] attributeNames; /** Nominal attribute values (used for result displaying). */ private String[][] attributeValues; /** Total weight (or number) of examples used to build the model. */ private double totalWeight; /** Total weight of examples belonging to the separate classes. */ private double[] classWeights; /** * Specifies the total weight of examples in which the different combinations of classes and (nominal) attribute * values co-occur. In the case of numeric attributes the (weighted) sum and the (weighted) sum of the squared * attribute values are stored which are needed to calculate the mean and the standard deviation/variance of the * resulting (assumed) normal distribution. * * Array dimensions: 1st: attributes 2nd: classes 3nd: nominal values or value sum (index=0) and squared value sum * (index=1) */ private double[][][] weightSums; /** Class log (!) a-priori probabilities. */ private double[] priors; /** * Specifies the a-postiori distributions. Contains the log (!) a-postiori probabilities that certain values occur * given the class value for nominal values. Contains the means and standard deviations for numerical attributes. * * Array dimensions: 1st: attributes 2nd: classes 3nd: nominal values or mean (index=0) and standard deviation * (index=1) */ private double[][][] distributionProperties; /** * Captures if laplace correction should be applied when calculating probabilities. */ boolean laplaceCorrectionEnabled; /** * Indicates if the model has recently been updated and the actual probabilities have to be calculated. */ private boolean modelRecentlyUpdated; /** * This constructor allows to build a distribution model from the given data characteristics. It is fully updateable. * For details on weightsSums, please take a look at the member variable weightSums. The ExampleSet is only used for * storing the header. The attributes and their values, including the class values, must be in the same order in the * headerSet as they are in the encoded in the weight sums. */ public SimpleDistributionModel(ExampleSet headerSet, double classWeights[], double[][][] weightSums) { super(headerSet); Attributes attributes = headerSet.getAttributes(); // label Attribute labelAttribute = attributes.getLabel(); this.className = labelAttribute.getName(); this.numberOfClasses = labelAttribute.getMapping().size(); this.classValues = new String[numberOfClasses]; int i = 0; for (String value : labelAttribute.getMapping().getValues()) { classValues[i] = value; i++; } // attributes this.numberOfAttributes = attributes.size(); this.attributeNames = new String[numberOfAttributes]; this.attributeValues = new String[numberOfAttributes][]; this.nominal = new boolean[numberOfAttributes]; i = 0; for (Attribute attribute : attributes) { attributeNames[i] = attribute.getName(); if (attribute.isNominal()) { nominal[i] = true; attributeValues[i] = new String[attribute.getMapping().size()]; int j = 0; for (String value : attribute.getMapping().getValues()) { attributeValues[i][j] = value; j++; } } i++; } // distribution properties this.weightSums = weightSums; this.classWeights = classWeights; this.totalWeight = VectorMath.sum(classWeights); // initializing other arrays this.distributionProperties = new double[numberOfAttributes][numberOfClasses][]; for (i = 0; i < numberOfAttributes; i++) { for (int j = 0; j < numberOfClasses; j++) { if (nominal[i]) distributionProperties[i][j] = new double[attributeValues[i].length]; else distributionProperties[i][j] = new double[3]; } } this.priors = new double[numberOfClasses]; // finally derive properties from data updateDistributionProperties(); } /** * This constructor will derive a complete distribution model on basis of the given trainings data with Laplace * correcture enabled. */ public SimpleDistributionModel(ExampleSet trainExampleSet) { this(trainExampleSet, true); } /** * This constructor will derive a complete distribution model on basis of the given trainings data with Laplace * correcture depending on the parameter. */ public SimpleDistributionModel(ExampleSet trainExampleSet, boolean laplaceCorrectionEnabled) { super(trainExampleSet); this.laplaceCorrectionEnabled = laplaceCorrectionEnabled; Attribute labelAttribute = trainExampleSet.getAttributes().getLabel(); numberOfClasses = labelAttribute.getMapping().size(); numberOfAttributes = trainExampleSet.getAttributes().size(); nominal = new boolean[numberOfAttributes]; attributeNames = new String[numberOfAttributes]; attributeValues = new String[numberOfAttributes][]; className = labelAttribute.getName(); classValues = new String[numberOfClasses]; for (int i = 0; i < numberOfClasses; i++) { classValues[i] = labelAttribute.getMapping().mapIndex(i); } int attributeIndex = 0; weightSums = new double[numberOfAttributes][numberOfClasses][]; distributionProperties = new double[numberOfAttributes][numberOfClasses][]; for (Attribute attribute : trainExampleSet.getAttributes()) { attributeNames[attributeIndex] = attribute.getName(); if (attribute.isNominal()) { nominal[attributeIndex] = true; int mappingSize = attribute.getMapping().size() + 1; attributeValues[attributeIndex] = new String[mappingSize]; for (int i = 0; i < mappingSize - 1; i++) { attributeValues[attributeIndex][i] = attribute.getMapping().mapIndex(i); } attributeValues[attributeIndex][mappingSize - 1] = UNKNOWN_VALUE_NAME; for (int i = 0; i < numberOfClasses; i++) { weightSums[attributeIndex][i] = new double[mappingSize]; distributionProperties[attributeIndex][i] = new double[mappingSize]; } } else { nominal[attributeIndex] = false; for (int i = 0; i < numberOfClasses; i++) { weightSums[attributeIndex][i] = new double[3]; distributionProperties[attributeIndex][i] = new double[3]; } } attributeIndex++; } // initialization of total and a priori weight counters totalWeight = 0.0d; classWeights = new double[numberOfClasses]; priors = new double[numberOfClasses]; // update the model update(trainExampleSet); // calculate the probabilities updateDistributionProperties(); } @Override public String[] getAttributeNames() { return this.attributeNames; } @Override public int getNumberOfAttributes() { return this.attributeNames.length; } /** * Updates the model by counting the occurrences of classes and attribute values in combination with the class * values. * * ATTENTION: only updates the weight counters, distribution properties are not updated, call * updateDistributionProperties() to accomplish this task */ @Override public void update(ExampleSet exampleSet) { Attribute weightAttribute = exampleSet.getAttributes().getWeight(); for (Example example : exampleSet) { double weight = weightAttribute == null ? 1.0d : example.getWeight(); totalWeight += weight; double labelValue = example.getLabel(); if (!Double.isNaN(labelValue)) { int classIndex = (int) example.getLabel(); classWeights[classIndex] += weight; int attributeIndex = 0; for (Attribute attribute : exampleSet.getAttributes()) { double attributeValue = example.getValue(attribute); if (nominal[attributeIndex]) { if (!Double.isNaN(attributeValue)) { if ((int) attributeValue < weightSums[attributeIndex][classIndex].length - 1) { weightSums[attributeIndex][classIndex][(int) attributeValue] += weight; } else { // extend weight array if attribute value is not in mapping for (int i = 0; i < numberOfClasses; i++) { double[] newWeightSums = new double[(int) attributeValue + 2]; newWeightSums[newWeightSums.length - 1] = weightSums[attributeIndex][i][weightSums[attributeIndex][i].length - 1]; for (int j = 0; j < weightSums[attributeIndex][i].length - 1; j++) { newWeightSums[j] = weightSums[attributeIndex][i][j]; } weightSums[attributeIndex][i] = newWeightSums; distributionProperties[attributeIndex][i] = new double[(int) attributeValue + 2]; } weightSums[attributeIndex][classIndex][(int) attributeValue] += weight; // recreate internal attribute value mapping attributeValues[attributeIndex] = new String[(int) attributeValue + 2]; for (int i = 0; i < attributeValues[attributeIndex].length - 1; i++) { attributeValues[attributeIndex][i] = attribute.getMapping().mapIndex(i); } attributeValues[attributeIndex][attributeValues[attributeIndex].length - 1] = UNKNOWN_VALUE_NAME; } } else { weightSums[attributeIndex][classIndex][weightSums[attributeIndex][classIndex].length - 1] += weight; } } else if (attribute.isNumerical()) { // numerical attribute if (!Double.isNaN(attributeValue)) { weightSums[attributeIndex][classIndex][INDEX_VALUE_SUM] += weight * attributeValue; weightSums[attributeIndex][classIndex][INDEX_SQUARED_VALUE_SUM] += weight * attributeValue * attributeValue; } else { // these are used to distinguish between total class weights and the current attribute's weights weightSums[attributeIndex][classIndex][INDEX_MISSING_WEIGHTS] += weight; } } attributeIndex++; } } } modelRecentlyUpdated = true; } /** * Updates the distribution properties by calculating the logged probabilities and distribution parameters on the * basis of the weight counters. */ private void updateDistributionProperties() { double f = laplaceCorrectionEnabled ? 1 / totalWeight : Double.MIN_VALUE; double logFactorCoefficient = Math.sqrt(2 * Math.PI); for (int i = 0; i < numberOfClasses; i++) { priors[i] = Math.log(classWeights[i] / totalWeight); } for (int i = 0; i < numberOfAttributes; i++) { if (nominal[i]) { for (int j = 0; j < numberOfClasses; j++) { for (int k = 0; k < weightSums[i][j].length; k++) { distributionProperties[i][j][k] = Math.log((weightSums[i][j][k] + f) / (classWeights[j] + f * weightSums[i][j].length)); } } } else { for (int j = 0; j < numberOfClasses; j++) { double classWeight = classWeights[j] - weightSums[i][j][INDEX_MISSING_WEIGHTS]; distributionProperties[i][j][INDEX_MEAN] = weightSums[i][j][INDEX_VALUE_SUM] / classWeight; double standardDeviationSquared = (weightSums[i][j][INDEX_SQUARED_VALUE_SUM] - weightSums[i][j][INDEX_VALUE_SUM] * weightSums[i][j][INDEX_VALUE_SUM] / classWeight) / (classWeight - 1); double standardDeviation = 1e-3; if (standardDeviationSquared > 0) { standardDeviation = Math.sqrt(standardDeviationSquared); if (Double.isNaN(standardDeviation) || standardDeviation <= 1e-3) { standardDeviation = 1e-3; } } distributionProperties[i][j][INDEX_STANDARD_DEVIATION] = standardDeviation; distributionProperties[i][j][INDEX_LOG_FACTOR] = Math.log(distributionProperties[i][j][INDEX_STANDARD_DEVIATION] * logFactorCoefficient); } } } modelRecentlyUpdated = false; } @Override public ExampleSet performPrediction(ExampleSet exampleSet, Attribute predictedLabel) { if (modelRecentlyUpdated) { updateDistributionProperties(); } double[] probabilities = new double[numberOfClasses]; for (Example example : exampleSet) { double maxLogProbability = Double.NEGATIVE_INFINITY; double probabilitySum = 0; int mostProbableClass = 0; int j = 0; for (int i = 0; i < numberOfClasses; i++) { probabilities[i] = priors[i]; } for (Attribute attribute : exampleSet.getAttributes()) { double value = example.getValue(attribute); if (nominal[j]) { if (!Double.isNaN(value)) { int intValue = (int) value; for (int i = 0; i < numberOfClasses; i++) { if (intValue < distributionProperties[j][i].length) { probabilities[i] += distributionProperties[j][i][intValue]; } } } else { for (int i = 0; i < numberOfClasses; i++) { probabilities[i] += distributionProperties[j][i][distributionProperties[j][i].length - 1]; } } } else { if (!Double.isNaN(value)) { for (int i = 0; i < numberOfClasses; i++) { double base = (value - distributionProperties[j][i][INDEX_MEAN]) / distributionProperties[j][i][INDEX_STANDARD_DEVIATION]; probabilities[i] -= distributionProperties[j][i][INDEX_LOG_FACTOR] + 0.5 * base * base; } } } j++; } for (int i = 0; i < numberOfClasses; i++) { if (!Double.isNaN(probabilities[i]) && probabilities[i] > maxLogProbability) { maxLogProbability = probabilities[i]; mostProbableClass = i; } } for (int i = 0; i < numberOfClasses; i++) { if (!Double.isNaN(probabilities[i])) { probabilities[i] = Math.exp(probabilities[i] - maxLogProbability); probabilitySum += probabilities[i]; } else { probabilities[i] = 0; } } if (maxLogProbability == Double.NEGATIVE_INFINITY) { example.setPredictedLabel(Double.NaN); for (int i = 0; i < numberOfClasses; i++) { example.setConfidence(classValues[i], Double.NaN); } } else { example.setPredictedLabel(mostProbableClass); for (int i = 0; i < numberOfClasses; i++) { example.setConfidence(classValues[i], probabilities[i] / probabilitySum); } } } return exampleSet; } public void setLaplaceCorrectionEnabled(boolean laplaceCorrectionEnabled) { this.laplaceCorrectionEnabled = laplaceCorrectionEnabled; } public boolean getLaplaceCorrectionEnabled() { return laplaceCorrectionEnabled; } @Override public double getLowerBound(int attributeIndex) { if (!nominal[attributeIndex]) { double lowerBound = Double.POSITIVE_INFINITY; for (int i = 0; i < numberOfClasses; i++) { double currentLowerBound = NormalDistribution.getLowerBound(distributionProperties[attributeIndex][i][INDEX_MEAN], distributionProperties[attributeIndex][i][INDEX_STANDARD_DEVIATION]); if (!Double.isNaN(currentLowerBound)) { lowerBound = Math.min(lowerBound, currentLowerBound); } } return lowerBound; } else { return Double.NaN; } } @Override public double getUpperBound(int attributeIndex) { if (!nominal[attributeIndex]) { double upperBound = Double.NEGATIVE_INFINITY; for (int i = 0; i < numberOfClasses; i++) { double currentUpperBound = NormalDistribution.getUpperBound(distributionProperties[attributeIndex][i][INDEX_MEAN], distributionProperties[attributeIndex][i][INDEX_STANDARD_DEVIATION]); if (!Double.isNaN(currentUpperBound)) { upperBound = Math.max(upperBound, currentUpperBound); } } return upperBound; } else { return Double.NaN; } } @Override public boolean isDiscrete(int attributeIndex) { if (attributeIndex >= 0 && attributeIndex < nominal.length) { return nominal[attributeIndex]; } return false; } @Override public Collection<Integer> getClassIndices() { Collection<Integer> classValueIndices = new ArrayList<Integer>(numberOfClasses); for (int i = 0; i < numberOfClasses; i++) { classValueIndices.add(i); } return classValueIndices; } @Override public int getNumberOfClasses() { return numberOfClasses; } @Override public String getClassName(int index) { return classValues[index]; } /** * This returns the raw numerical parameters of the distribution. Depends on the attribute value * type! Use with caution. */ public double[] getRawDistributionParameter(int classIndex, int attributeIndex) { return distributionProperties[attributeIndex][classIndex]; } @Override public Distribution getDistribution(int classIndex, int attributeIndex) { if (nominal[attributeIndex]) { double[] probabilities = new double[distributionProperties[attributeIndex][classIndex].length]; for (int i = 0; i < probabilities.length; i++) { probabilities[i] = Math.exp(distributionProperties[attributeIndex][classIndex][i]); } return new DiscreteDistribution(attributeNames[attributeIndex], probabilities, attributeValues[attributeIndex]); } else { return new NormalDistribution(distributionProperties[attributeIndex][classIndex][INDEX_MEAN], distributionProperties[attributeIndex][classIndex][INDEX_STANDARD_DEVIATION]); } } public double getTotalWeight() { return totalWeight; } public double[] getClassWeights() { return classWeights; } public double[] getAprioriProbabilities() { return priors; } @Override public String toString() { if (modelRecentlyUpdated) { updateDistributionProperties(); } StringBuffer buffer = new StringBuffer(); buffer.append("Distribution model for label attribute " + className); buffer.append(Tools.getLineSeparators(2)); for (int i = 0; i < numberOfClasses; i++) { String classTitle = "Class " + classValues[i] + " (" + Tools.formatNumber(Math.exp(priors[i])) + ")"; buffer.append(Tools.getLineSeparator()); buffer.append(classTitle); buffer.append(Tools.getLineSeparator()); buffer.append(attributeNames.length + " distributions"); buffer.append(Tools.getLineSeparator()); } return buffer.toString(); } }
rapidminer/rapidminer-5
src/com/rapidminer/operator/learner/bayes/SimpleDistributionModel.java
Java
agpl-3.0
20,417
'use strict'; module.exports = function () { return function (scope, element, attrs) { element.bind('keypress', function (event) { if (element['0'].textLength === 0) { scope.$eval(attrs.ngTimer); } if (event.which === 13) { scope.$apply(function () { scope.$eval(attrs.ngEnter); }); event.preventDefault(); } }); }; };
ddmck/Quill-Grammar
src/scripts/directives/grammarElements/ruleQuestion/ngEnter.js
JavaScript
agpl-3.0
398
/* -*- mode: C++; c-file-style: "stroustrup"; c-basic-offset: 4; -*- * * This file is part of the UPPAAL DBM library. * * The UPPAAL DBM library 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. * * The UPPAAL DBM library is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with the UPPAAL DBM library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA. */ // -*- mode: C++; c-file-style: "stroustrup"; c-basic-offset: 4; indent-tabs-mode: nil; -*- //////////////////////////////////////////////////////////////////// // // This file is a part of the UPPAAL toolkit. // Copyright (c) 1995 - 2006, Uppsala University and Aalborg University. // All right reserved. // /////////////////////////////////////////////////////////////////// #ifndef INCLUDE_IO_BASE64CODER_H #define INCLUDE_IO_BASE64CODER_H #include <string> #include <exception> namespace io { class Base64Coder { public: static std::string encode(const std::string&); static std::string decode(const std::string&) throw(std::exception); class IllegalLengthException : public std::exception { public: virtual const char *what() const throw (); }; class IllegalCharacterException : public std::exception { public: virtual const char *what() const throw (); }; private: static Base64Coder instance; Base64Coder(); char mapTo64[64]; char mapFrom64[128]; }; } #endif // INCLUDE_IO_BASE64CODER_H
osankur/udbml
uppaal-dbm/modules/include/io/Base64Coder.h
C
agpl-3.0
2,033
MODULE_TOPDIR = ../.. PGM = r.regression.line LIBES = $(RASTERLIB) $(GISLIB) $(MATHLIB) DEPENDENCIES = $(GISDEP) $(RASTERDEP) include $(MODULE_TOPDIR)/include/Make/Module.make default: cmd
AsherBond/MondocosmOS
grass_trunk/raster/r.regression.line/Makefile
Makefile
agpl-3.0
193
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <style> body { font-family: Helvetica, arial, sans-serif; font-size: 14px; line-height: 1.6; padding-top: 10px; padding-bottom: 10px; background-color: white; padding: 30px; color: #333; } body > *:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } a { color: #4183C4; text-decoration: none; } a.absent { color: #cc0000; } a.anchor { display: block; padding-left: 30px; margin-left: -30px; cursor: pointer; position: absolute; top: 0; left: 0; bottom: 0; } h1, h2, h3, h4, h5, h6 { margin: 20px 0 10px; padding: 0; font-weight: bold; -webkit-font-smoothing: antialiased; cursor: text; position: relative; } h2:first-child, h1:first-child, h1:first-child + h2, h3:first-child, h4:first-child, h5:first-child, h6:first-child { margin-top: 0; padding-top: 0; } h1:hover a.anchor, h2:hover a.anchor, h3:hover a.anchor, h4:hover a.anchor, h5:hover a.anchor, h6:hover a.anchor { text-decoration: none; } h1 tt, h1 code { font-size: inherit; } h2 tt, h2 code { font-size: inherit; } h3 tt, h3 code { font-size: inherit; } h4 tt, h4 code { font-size: inherit; } h5 tt, h5 code { font-size: inherit; } h6 tt, h6 code { font-size: inherit; } h1 { font-size: 28px; color: black; } h2 { font-size: 24px; border-bottom: 1px solid #cccccc; color: black; } h3 { font-size: 18px; } h4 { font-size: 16px; } h5 { font-size: 14px; } h6 { color: #777777; font-size: 14px; } p, blockquote, ul, ol, dl, li, table, pre { margin: 15px 0; } hr { background: transparent url("http://tinyurl.com/bq5kskr") repeat-x 0 0; border: 0 none; color: #cccccc; height: 4px; padding: 0; } body > h2:first-child { margin-top: 0; padding-top: 0; } body > h1:first-child { margin-top: 0; padding-top: 0; } body > h1:first-child + h2 { margin-top: 0; padding-top: 0; } body > h3:first-child, body > h4:first-child, body > h5:first-child, body > h6:first-child { margin-top: 0; padding-top: 0; } a:first-child h1, a:first-child h2, a:first-child h3, a:first-child h4, a:first-child h5, a:first-child h6 { margin-top: 0; padding-top: 0; } h1 p, h2 p, h3 p, h4 p, h5 p, h6 p { margin-top: 0; } li p.first { display: inline-block; } ul, ol { padding-left: 30px; } ul :first-child, ol :first-child { margin-top: 0; } ul :last-child, ol :last-child { margin-bottom: 0; } dl { padding: 0; } dl dt { font-size: 14px; font-weight: bold; font-style: italic; padding: 0; margin: 15px 0 5px; } dl dt:first-child { padding: 0; } dl dt > :first-child { margin-top: 0; } dl dt > :last-child { margin-bottom: 0; } dl dd { margin: 0 0 15px; padding: 0 15px; } dl dd > :first-child { margin-top: 0; } dl dd > :last-child { margin-bottom: 0; } blockquote { border-left: 4px solid #dddddd; padding: 0 15px; color: #777777; } blockquote > :first-child { margin-top: 0; } blockquote > :last-child { margin-bottom: 0; } table { padding: 0; } table tr { border-top: 1px solid #cccccc; background-color: white; margin: 0; padding: 0; } table tr:nth-child(2n) { background-color: #f8f8f8; } table tr th { font-weight: bold; border: 1px solid #cccccc; text-align: left; margin: 0; padding: 6px 13px; } table tr td { border: 1px solid #cccccc; text-align: left; margin: 0; padding: 6px 13px; } table tr th :first-child, table tr td :first-child { margin-top: 0; } table tr th :last-child, table tr td :last-child { margin-bottom: 0; } img { max-width: 100%; } span.frame { display: block; overflow: hidden; } span.frame > span { border: 1px solid #dddddd; display: block; float: left; overflow: hidden; margin: 13px 0 0; padding: 7px; width: auto; } span.frame span img { display: block; float: left; } span.frame span span { clear: both; color: #333333; display: block; padding: 5px 0 0; } span.align-center { display: block; overflow: hidden; clear: both; } span.align-center > span { display: block; overflow: hidden; margin: 13px auto 0; text-align: center; } span.align-center span img { margin: 0 auto; text-align: center; } span.align-right { display: block; overflow: hidden; clear: both; } span.align-right > span { display: block; overflow: hidden; margin: 13px 0 0; text-align: right; } span.align-right span img { margin: 0; text-align: right; } span.float-left { display: block; margin-right: 13px; overflow: hidden; float: left; } span.float-left span { margin: 13px 0 0; } span.float-right { display: block; margin-left: 13px; overflow: hidden; float: right; } span.float-right > span { display: block; overflow: hidden; margin: 13px auto 0; text-align: right; } code, tt { margin: 0 2px; padding: 0 5px; white-space: nowrap; border: 1px solid #eaeaea; background-color: #f8f8f8; border-radius: 3px; } pre code { margin: 0; padding: 0; white-space: pre; border: none; background: transparent; } .highlight pre { background-color: #f8f8f8; border: 1px solid #cccccc; font-size: 13px; line-height: 19px; overflow: auto; padding: 6px 10px; border-radius: 3px; } pre { background-color: #f8f8f8; border: 1px solid #cccccc; font-size: 13px; line-height: 19px; overflow: auto; padding: 6px 10px; border-radius: 3px; } pre code, pre tt { background-color: transparent; border: none; } </style> </head> <body> <pre id="license-text"> GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. &lt;http://fsf.org/&gt; Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. &lt;one line to give the program's name and a brief idea of what it does.&gt; Copyright (C) &lt;year&gt; &lt;name of author&gt; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see &lt;http://www.gnu.org/licenses/&gt;. Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see &lt;http://www.gnu.org/licenses/&gt;. </pre> </body> </html>
Maslosoft/Sigurd
LICENSE-AGPL.html
HTML
agpl-3.0
40,252
/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/range/irange.hpp> #include <boost/range/adaptors.hpp> #include <boost/range/algorithm.hpp> #include <boost/test/unit_test.hpp> #include <boost/multiprecision/cpp_int.hpp> #include "utils/big_decimal.hh" #include "exceptions/exceptions.hh" #include "tests/test-utils.hh" #include "tests/cql_test_env.hh" #include "tests/cql_assertions.hh" #include "core/future-util.hh" #include "transport/messages/result_message.hh" #include "db/config.hh" namespace { template<typename T> struct cql_type_name { }; template<> struct cql_type_name<int> { static constexpr char value[] = "int"; }; constexpr char cql_type_name<int>::value[]; template<> struct cql_type_name<long> { static constexpr char value[] = "bigint"; }; constexpr char cql_type_name<long>::value[]; template<> struct cql_type_name<float> { static constexpr char value[] = "float"; }; constexpr char cql_type_name<float>::value[]; template<> struct cql_type_name<double> { static constexpr char value[] = "double"; }; constexpr char cql_type_name<double>::value[]; template<typename RetType, typename Type> auto test_explicit_type_casting_in_avg_function() { return do_with_cql_env_thread([] (auto& e) { e.execute_cql(sprint("CREATE TABLE air_quality_data (sensor_id text, time timestamp, co_ppm %s, PRIMARY KEY (sensor_id, time));", cql_type_name<Type>::value)).get(); e.execute_cql( "begin unlogged batch \n" " INSERT INTO air_quality_data(sensor_id, time, co_ppm) VALUES ('my_home', '2016-08-30 07:01:00', 17); \n" " INSERT INTO air_quality_data(sensor_id, time, co_ppm) VALUES ('my_home', '2016-08-30 07:01:01', 18); \n" " INSERT INTO air_quality_data(sensor_id, time, co_ppm) VALUES ('my_home', '2016-08-30 07:01:02', 19); \n" " INSERT INTO air_quality_data(sensor_id, time, co_ppm) VALUES ('my_home', '2016-08-30 07:01:03', 20); \n" " INSERT INTO air_quality_data(sensor_id, time, co_ppm) VALUES ('my_home', '2016-08-30 07:01:04', 30); \n" " INSERT INTO air_quality_data(sensor_id, time, co_ppm) VALUES ('my_home', '2016-08-30 07:01:05', 31); \n" " INSERT INTO air_quality_data(sensor_id, time, co_ppm) VALUES ('my_home', '2016-08-30 07:01:10', 20); \n" "apply batch;").get(); auto msg = e.execute_cql(sprint("select avg(CAST(co_ppm AS %s)) from air_quality_data;", cql_type_name<RetType>::value)).get0(); assert_that(msg).is_rows().with_size(1).with_row({{data_type_for<RetType>()->decompose( RetType(17 + 18 + 19 + 20 + 30 + 31 + 20) / RetType(7) )}}); }); } } /* anonymous namespace */ SEASTAR_TEST_CASE(test_explicit_type_casting_in_avg_function_int) { return test_explicit_type_casting_in_avg_function<double, int>(); } SEASTAR_TEST_CASE(test_explicit_type_casting_in_avg_function_long) { return test_explicit_type_casting_in_avg_function<double, long>(); } SEASTAR_TEST_CASE(test_explicit_type_casting_in_avg_function_float) { return test_explicit_type_casting_in_avg_function<float, float>(); } SEASTAR_TEST_CASE(test_explicit_type_casting_in_avg_function_double) { return test_explicit_type_casting_in_avg_function<double, double>(); } SEASTAR_TEST_CASE(test_unsupported_conversions) { auto validate_request_failure = [] (cql_test_env& env, const sstring& request, const sstring& expected_message) { BOOST_REQUIRE_EXCEPTION(env.execute_cql(request).get(), exceptions::invalid_request_exception, [&expected_message](auto &&ire) { BOOST_REQUIRE_EQUAL(expected_message, ire.what()); return true; }); return make_ready_future<>(); }; return do_with_cql_env_thread([&] (auto& e) { e.execute_cql("CREATE TABLE air_quality_data_text (sensor_id text, time timestamp, co_ppm text, PRIMARY KEY (sensor_id, time));").get(); validate_request_failure(e, "select CAST(co_ppm AS int) from air_quality_data_text", "org.apache.cassandra.db.marshal.UTF8Type cannot be cast to org.apache.cassandra.db.marshal.Int32Type"); e.execute_cql("CREATE TABLE air_quality_data_ascii (sensor_id text, time timestamp, co_ppm ascii, PRIMARY KEY (sensor_id, time));").get(); validate_request_failure(e, "select CAST(co_ppm AS int) from air_quality_data_ascii", "org.apache.cassandra.db.marshal.AsciiType cannot be cast to org.apache.cassandra.db.marshal.Int32Type"); }); } SEASTAR_TEST_CASE(test_numeric_casts_in_selection_clause) { return do_with_cql_env_thread([&] (auto& e) { e.execute_cql("CREATE TABLE test (a tinyint primary key," " b smallint," " c int," " d bigint," " e float," " f double," " g decimal," " h varint," " i int)").get(); e.execute_cql("INSERT INTO test (a, b, c, d, e, f, g, h) VALUES (1, 2, 3, 4, 5.2, 6.3, 7.3, 8)").get(); { auto msg = e.execute_cql("SELECT CAST(a AS tinyint), " "CAST(b AS tinyint), " "CAST(c AS tinyint), " "CAST(d AS tinyint), " "CAST(e AS tinyint), " "CAST(f AS tinyint), " "CAST(g AS tinyint), " "CAST(h AS tinyint), " "CAST(i AS tinyint) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{byte_type->decompose(int8_t(1))}, {byte_type->decompose(int8_t(2))}, {byte_type->decompose(int8_t(3))}, {byte_type->decompose(int8_t(4))}, {byte_type->decompose(int8_t(5))}, {byte_type->decompose(int8_t(6))}, {byte_type->decompose(int8_t(7))}, {byte_type->decompose(int8_t(8))}, {}}); } { auto msg = e.execute_cql("SELECT CAST(a AS smallint), " "CAST(b AS smallint), " "CAST(c AS smallint), " "CAST(d AS smallint), " "CAST(e AS smallint), " "CAST(f AS smallint), " "CAST(g AS smallint), " "CAST(h AS smallint), " "CAST(i AS smallint) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{short_type->decompose(int16_t(1))}, {short_type->decompose(int16_t(2))}, {short_type->decompose(int16_t(3))}, {short_type->decompose(int16_t(4))}, {short_type->decompose(int16_t(5))}, {short_type->decompose(int16_t(6))}, {short_type->decompose(int16_t(7))}, {short_type->decompose(int16_t(8))}, {}}); } { auto msg = e.execute_cql("SELECT CAST(a AS int), " "CAST(b AS int), " "CAST(c AS int), " "CAST(d AS int), " "CAST(e AS int), " "CAST(f AS int), " "CAST(g AS int), " "CAST(h AS int), " "CAST(i AS int) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{int32_type->decompose(int32_t(1))}, {int32_type->decompose(int32_t(2))}, {int32_type->decompose(int32_t(3))}, {int32_type->decompose(int32_t(4))}, {int32_type->decompose(int32_t(5))}, {int32_type->decompose(int32_t(6))}, {int32_type->decompose(int32_t(7))}, {int32_type->decompose(int32_t(8))}, {}}); } { auto msg = e.execute_cql("SELECT CAST(a AS bigint), " "CAST(b AS bigint), " "CAST(c AS bigint), " "CAST(d AS bigint), " "CAST(e AS bigint), " "CAST(f AS bigint), " "CAST(g AS bigint), " "CAST(h AS bigint), " "CAST(i AS bigint) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{long_type->decompose(int64_t(1))}, {long_type->decompose(int64_t(2))}, {long_type->decompose(int64_t(3))}, {long_type->decompose(int64_t(4))}, {long_type->decompose(int64_t(5))}, {long_type->decompose(int64_t(6))}, {long_type->decompose(int64_t(7))}, {long_type->decompose(int64_t(8))}, {}}); } { auto msg = e.execute_cql("SELECT CAST(a AS float), " "CAST(b AS float), " "CAST(c AS float), " "CAST(d AS float), " "CAST(e AS float), " "CAST(f AS float), " "CAST(g AS float), " "CAST(h AS float), " "CAST(i AS float) FROM test").get0(); // Conversions that include floating point cannot be compared with assert_that(), because result // of such conversions may be slightly different from theoretical values. auto cmp = [&](::size_t index, float req) { auto row = dynamic_cast<cql_transport::messages::result_message::rows&>(*msg).rs().result_set().rows().front(); auto val = value_cast<float>( float_type->deserialize(row[index].value()) ); BOOST_CHECK_CLOSE(val, req, 1e-4); }; auto cmp_null = [&](::size_t index) { auto row = dynamic_cast<cql_transport::messages::result_message::rows&>(*msg).rs().result_set().rows().front(); BOOST_CHECK(!row[index]); }; cmp(0, 1.f); cmp(1, 2.f); cmp(2, 3.f); cmp(3, 4.f); cmp(4, 5.2f); cmp(5, 6.3f); cmp(6, 7.3f); cmp(7, 8.f); cmp_null(8); } { auto msg = e.execute_cql("SELECT CAST(a AS double), " "CAST(b AS double), " "CAST(c AS double), " "CAST(d AS double), " "CAST(e AS double), " "CAST(f AS double), " "CAST(g AS double), " "CAST(h AS double), " "CAST(i AS double) FROM test").get0(); // Conversions that include floating points cannot be compared with assert_that(), because result // of such conversions may be slightly different from theoretical values. auto cmp = [&](::size_t index, double req) { auto row = dynamic_cast<cql_transport::messages::result_message::rows&>(*msg).rs().result_set().rows().front(); auto val = value_cast<double>( double_type->deserialize(row[index].value()) ); BOOST_CHECK_CLOSE(val, req, 1e-4); }; auto cmp_null = [&](::size_t index) { auto row = dynamic_cast<cql_transport::messages::result_message::rows&>(*msg).rs().result_set().rows().front(); BOOST_CHECK(!row[index]); }; cmp(0, 1.d); cmp(1, 2.d); cmp(2, 3.d); cmp(3, 4.d); cmp(4, 5.2d); cmp(5, 6.3d); cmp(6, 7.3d); cmp(7, 8.d); cmp_null(8); } { auto msg = e.execute_cql("SELECT CAST(a AS decimal), " "CAST(b AS decimal), " "CAST(c AS decimal), " "CAST(d AS decimal), " "CAST(e AS decimal), " "CAST(f AS decimal), " "CAST(g AS decimal), " "CAST(h AS decimal), " "CAST(i AS decimal) FROM test").get0(); // Conversions that include floating points cannot be compared with assert_that(), because result // of such conversions may be slightly different from theoretical values. auto cmp = [&](::size_t index, double req) { auto row = dynamic_cast<cql_transport::messages::result_message::rows&>(*msg).rs().result_set().rows().front(); auto val = value_cast<big_decimal>( decimal_type->deserialize(row[index].value()) ); BOOST_CHECK_CLOSE(boost::lexical_cast<double>(val.to_string()), req, 1e-4); }; auto cmp_null = [&](::size_t index) { auto row = dynamic_cast<cql_transport::messages::result_message::rows&>(*msg).rs().result_set().rows().front(); BOOST_CHECK(!row[index]); }; cmp(0, 1.d); cmp(1, 2.d); cmp(2, 3.d); cmp(3, 4.d); cmp(4, 5.2d); cmp(5, 6.3d); cmp(6, 7.3d); cmp(7, 8.d); cmp_null(8); } { auto msg = e.execute_cql("SELECT CAST(a AS ascii), " "CAST(b AS ascii), " "CAST(c AS ascii), " "CAST(d AS ascii), " "CAST(e AS ascii), " "CAST(f AS ascii), " "CAST(g AS ascii), " "CAST(h AS ascii), " "CAST(i AS ascii) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{ascii_type->decompose("1")}, {ascii_type->decompose("2")}, {ascii_type->decompose("3")}, {ascii_type->decompose("4")}, {ascii_type->decompose("5.2")}, {ascii_type->decompose("6.3")}, {ascii_type->decompose("7.3")}, {ascii_type->decompose("8")}, {}}); } { auto msg = e.execute_cql("SELECT CAST(a AS text), " "CAST(b AS text), " "CAST(c AS text), " "CAST(d AS text), " "CAST(e AS text), " "CAST(f AS text), " "CAST(g AS text), " "CAST(h AS text), " "CAST(i AS text) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{utf8_type->decompose("1")}, {utf8_type->decompose("2")}, {utf8_type->decompose("3")}, {utf8_type->decompose("4")}, {utf8_type->decompose("5.2")}, {utf8_type->decompose("6.3")}, {utf8_type->decompose("7.3")}, {utf8_type->decompose("8")}, {}}); } }); } SEASTAR_TEST_CASE(test_integers_to_decimal_casts_in_selection_clause) { return do_with_cql_env_thread([&] (auto& e) { e.execute_cql("CREATE TABLE test (a tinyint primary key," " b smallint," " c int," " d bigint," " h varint)").get(); e.execute_cql("INSERT INTO test (a, b, c, d, h) VALUES (1, 2, 3, 4, 8)").get(); auto msg = e.execute_cql("SELECT CAST(a AS decimal), " "CAST(b AS decimal), " "CAST(c AS decimal), " "CAST(d AS decimal), " "CAST(h AS decimal) FROM test").get0(); auto cmp = [&](::size_t index, auto x) { auto row = dynamic_cast<cql_transport::messages::result_message::rows&>(*msg).rs().result_set().rows().front(); auto val = value_cast<big_decimal>( decimal_type->deserialize(row[index].value()) ); BOOST_CHECK_EQUAL(val.unscaled_value(), x*10); BOOST_CHECK_EQUAL(val.scale(), 1); }; cmp(0, 1); cmp(1, 2); cmp(2, 3); cmp(3, 4); cmp(4, 8); }); } SEASTAR_TEST_CASE(test_integers_to_decimal_casts_with_avg_in_selection_clause) { return do_with_cql_env_thread([&] (auto& e) { e.execute_cql("CREATE TABLE test (a tinyint primary key," " b smallint," " c int," " d bigint," " h varint)").get(); e.execute_cql("INSERT INTO test (a, b, c, d, h) VALUES (1, 2, 3, 4, 8)").get(); e.execute_cql("INSERT INTO test (a, b, c, d, h) VALUES (2, 3, 4, 5, 9)").get(); auto msg = e.execute_cql("SELECT CAST(avg(CAST(a AS decimal)) AS text), " "CAST(avg(CAST(b AS decimal)) AS text), " "CAST(avg(CAST(c AS decimal)) AS text), " "CAST(avg(CAST(d AS decimal)) AS text), " "CAST(avg(CAST(h AS decimal)) AS text) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{utf8_type->decompose("1.5")}, {utf8_type->decompose("2.5")}, {utf8_type->decompose("3.5")}, {utf8_type->decompose("4.5")}, {utf8_type->decompose("8.5")}}); }); } SEASTAR_TEST_CASE(test_time_casts_in_selection_clause) { return do_with_cql_env_thread([&] (auto& e) { e.execute_cql("CREATE TABLE test (a timeuuid primary key," "b timestamp," "c date," "d time)").get(); e.execute_cql("INSERT INTO test (a, b, c, d) VALUES (d2177dd0-eaa2-11de-a572-001b779c76e3, '2015-05-21 11:03:02+00', '2015-05-21', '11:03:02')").get(); { auto msg = e.execute_cql("SELECT CAST(a AS timestamp), CAST(a AS date), CAST(b as date), CAST(c AS timestamp) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{timestamp_type->from_string("2009-12-17t00:26:29.805+00")}, {simple_date_type->from_string("2009-12-17")}, {simple_date_type->from_string("2015-05-21")}, {timestamp_type->from_string("2015-05-21t00:00:00+00")}}); } { auto msg = e.execute_cql("SELECT CAST(CAST(a AS timestamp) AS text), CAST(CAST(a AS date) AS text), CAST(CAST(b as date) AS text), CAST(CAST(c AS timestamp) AS text) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{utf8_type->from_string("2009-12-17T00:26:29.805000")}, {utf8_type->from_string("2009-12-17")}, {utf8_type->from_string("2015-05-21")}, {utf8_type->from_string("2015-05-21T00:00:00")}}); } { auto msg = e.execute_cql("SELECT CAST(a AS text), CAST(b as text), CAST(c AS text), CAST(d AS text) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{utf8_type->from_string("d2177dd0-eaa2-11de-a572-001b779c76e3")}, {utf8_type->from_string("2015-05-21T11:03:02")}, {utf8_type->from_string("2015-05-21")}, {utf8_type->from_string("11:03:02.000000000")}}); } { auto msg = e.execute_cql("SELECT CAST(CAST(a AS timestamp) AS ascii), CAST(CAST(a AS date) AS ascii), CAST(CAST(b as date) AS ascii), CAST(CAST(c AS timestamp) AS ascii) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{ascii_type->from_string("2009-12-17T00:26:29.805000")}, {ascii_type->from_string("2009-12-17")}, {ascii_type->from_string("2015-05-21")}, {ascii_type->from_string("2015-05-21T00:00:00")}}); } { auto msg = e.execute_cql("SELECT CAST(a AS ascii), CAST(b as ascii), CAST(c AS ascii), CAST(d AS ascii) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{ascii_type->from_string("d2177dd0-eaa2-11de-a572-001b779c76e3")}, {ascii_type->from_string("2015-05-21T11:03:02")}, {ascii_type->from_string("2015-05-21")}, {ascii_type->from_string("11:03:02.000000000")}}); } }); } SEASTAR_TEST_CASE(test_other_type_casts_in_selection_clause) { return do_with_cql_env_thread([&] (auto& e) { e.execute_cql("CREATE TABLE test (a ascii primary key," "b inet," "c boolean)").get(); e.execute_cql("INSERT INTO test (a, b, c) VALUES ('test', '127.0.0.1', true)").get(); { auto msg = e.execute_cql("SELECT CAST(a AS text), CAST(b as text), CAST(c AS text) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{utf8_type->from_string("test")}, {utf8_type->from_string("127.0.0.1")}, {utf8_type->from_string("true")}}); } { auto msg = e.execute_cql("SELECT CAST(a AS ascii), CAST(b as ascii), CAST(c AS ascii) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{ascii_type->from_string("test")}, {ascii_type->from_string("127.0.0.1")}, {ascii_type->from_string("true")}}); } }); } SEASTAR_TEST_CASE(test_casts_with_revrsed_order_in_selection_clause) { return do_with_cql_env_thread([&] (auto& e) { e.execute_cql("CREATE TABLE test (a int," "b smallint," "c double," "primary key (a, b)) WITH CLUSTERING ORDER BY (b DESC)").get(); e.execute_cql("INSERT INTO test (a, b, c) VALUES (1, 2, 6.3)").get(); { auto msg = e.execute_cql("SELECT CAST(a AS tinyint), CAST(b as tinyint), CAST(c AS tinyint) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{byte_type->from_string("1")}, {byte_type->from_string("2")}, {byte_type->from_string("6")}}); } { auto msg = e.execute_cql("SELECT CAST(a AS smallint), CAST(b as smallint), CAST(c AS smallint) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{short_type->from_string("1")}, {short_type->from_string("2")}, {short_type->from_string("6")}}); } { auto msg = e.execute_cql("SELECT CAST(a AS double), CAST(b as double), CAST(c AS double) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{double_type->from_string("1")}, {double_type->from_string("2")}, {double_type->from_string("6.3")}}); } { auto msg = e.execute_cql("SELECT CAST(a AS text), CAST(b as text), CAST(c AS text) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{utf8_type->from_string("1")}, {utf8_type->from_string("2")}, {utf8_type->from_string("6.3")}}); } { auto msg = e.execute_cql("SELECT CAST(a AS ascii), CAST(b as ascii), CAST(c AS ascii) FROM test").get0(); assert_that(msg).is_rows().with_size(1).with_row({{ascii_type->from_string("1")}, {ascii_type->from_string("2")}, {ascii_type->from_string("6.3")}}); } }); } // FIXME: Add test with user-defined functions after they are available.
duarten/scylla
tests/castas_fcts_test.cc
C++
agpl-3.0
29,179
/****************************************************************************** * $Id: gdalhttp.cpp 22007 2011-03-21 20:44:14Z rouault $ * * Project: WMS Client Driver * Purpose: Implementation of Dataset and RasterBand classes for WMS * and other similar services. * Author: Adam Nowacki, [email protected] * ****************************************************************************** * Copyright (c) 2007, Adam Nowacki * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "stdinc.h" /* CURLINFO_RESPONSE_CODE was known as CURLINFO_HTTP_CODE in libcurl 7.10.7 and earlier */ #if LIBCURL_VERSION_NUM < 0x070a07 #define CURLINFO_RESPONSE_CODE CURLINFO_HTTP_CODE #endif static size_t CPLHTTPWriteFunc(void *buffer, size_t count, size_t nmemb, void *req) { CPLHTTPRequest *psRequest = reinterpret_cast<CPLHTTPRequest *>(req); size_t size = count * nmemb; if (size == 0) return 0; const size_t required_size = psRequest->nDataLen + size + 1; if (required_size > psRequest->nDataAlloc) { size_t new_size = required_size * 2; if (new_size < 512) new_size = 512; psRequest->nDataAlloc = new_size; GByte * pabyNewData = reinterpret_cast<GByte *>(VSIRealloc(psRequest->pabyData, new_size)); if (pabyNewData == NULL) { VSIFree(psRequest->pabyData); psRequest->pabyData = NULL; psRequest->pszError = CPLStrdup(CPLString().Printf("Out of memory allocating %u bytes for HTTP data buffer.", static_cast<int>(new_size))); psRequest->nDataAlloc = 0; psRequest->nDataLen = 0; return 0; } psRequest->pabyData = pabyNewData; } memcpy(psRequest->pabyData + psRequest->nDataLen, buffer, size); psRequest->nDataLen += size; psRequest->pabyData[psRequest->nDataLen] = 0; return nmemb; } void CPLHTTPInitializeRequest(CPLHTTPRequest *psRequest, const char *pszURL, const char *const *papszOptions) { psRequest->pszURL = CPLStrdup(pszURL); psRequest->papszOptions = CSLDuplicate(const_cast<char **>(papszOptions)); psRequest->nStatus = 0; psRequest->pszContentType = 0; psRequest->pszError = 0; psRequest->pabyData = 0; psRequest->nDataLen = 0; psRequest->nDataAlloc = 0; psRequest->m_curl_handle = 0; psRequest->m_headers = 0; psRequest->m_curl_error = 0; psRequest->m_curl_handle = curl_easy_init(); if (psRequest->m_curl_handle == NULL) { CPLError(CE_Fatal, CPLE_AppDefined, "CPLHTTPInitializeRequest(): Unable to create CURL handle."); } /* Set User-Agent */ const char *pszUserAgent = CSLFetchNameValue(const_cast<char **>(psRequest->papszOptions), "USERAGENT"); if (pszUserAgent == NULL) pszUserAgent = "GDAL WMS driver (http://www.gdal.org/frmt_wms.html)"; curl_easy_setopt(psRequest->m_curl_handle, CURLOPT_USERAGENT, pszUserAgent); /* Set Referer */ const char *pszReferer = CSLFetchNameValue(const_cast<char **>(psRequest->papszOptions), "REFERER"); if (pszReferer != NULL) curl_easy_setopt(psRequest->m_curl_handle, CURLOPT_REFERER, pszReferer); /* Set URL */ curl_easy_setopt(psRequest->m_curl_handle, CURLOPT_URL, psRequest->pszURL); /* Set timeout.*/ const char *timeout = CSLFetchNameValue(const_cast<char **>(psRequest->papszOptions), "TIMEOUT"); if (timeout != NULL) { curl_easy_setopt(psRequest->m_curl_handle, CURLOPT_TIMEOUT, atoi(timeout)); } /* Set Headers (copied&pasted from cpl_http.cpp, but unused by callers of CPLHTTPInitializeRequest) .*/ const char *headers = CSLFetchNameValue(const_cast<char **>(psRequest->papszOptions), "HEADERS"); if (headers != NULL) { psRequest->m_headers = curl_slist_append(psRequest->m_headers, headers); curl_easy_setopt(psRequest->m_curl_handle, CURLOPT_HTTPHEADER, psRequest->m_headers); } if (CSLFetchBoolean(const_cast<char **>(psRequest->papszOptions), "UNSAFESSL", 0)) { curl_easy_setopt(psRequest->m_curl_handle, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(psRequest->m_curl_handle, CURLOPT_SSL_VERIFYHOST, 0L); } /* Enable following redirections. Requires libcurl 7.10.1 at least */ curl_easy_setopt(psRequest->m_curl_handle, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(psRequest->m_curl_handle, CURLOPT_MAXREDIRS, 10); /* NOSIGNAL should be set to true for timeout to work in multithread environments on Unix, requires libcurl 7.10 or more recent. (this force avoiding the use of sgnal handlers) */ #ifdef CURLOPT_NOSIGNAL curl_easy_setopt(psRequest->m_curl_handle, CURLOPT_NOSIGNAL, 1); #endif curl_easy_setopt(psRequest->m_curl_handle, CURLOPT_WRITEDATA, psRequest); curl_easy_setopt(psRequest->m_curl_handle, CURLOPT_WRITEFUNCTION, CPLHTTPWriteFunc); psRequest->m_curl_error = reinterpret_cast<char *>(CPLMalloc(CURL_ERROR_SIZE + 1)); psRequest->m_curl_error[0] = '\0'; curl_easy_setopt(psRequest->m_curl_handle, CURLOPT_ERRORBUFFER, psRequest->m_curl_error); /* Set Proxy parameters */ const char* pszProxy = CSLFetchNameValue( const_cast<char **>(psRequest->papszOptions), "PROXY" ); if (pszProxy == NULL) pszProxy = CPLGetConfigOption("GDAL_HTTP_PROXY", NULL); if (pszProxy) curl_easy_setopt(psRequest->m_curl_handle,CURLOPT_PROXY,pszProxy); const char* pszProxyUserPwd = CSLFetchNameValue( const_cast<char **>(psRequest->papszOptions), "PROXYUSERPWD" ); if (pszProxyUserPwd == NULL) pszProxyUserPwd = CPLGetConfigOption("GDAL_HTTP_PROXYUSERPWD", NULL); if (pszProxyUserPwd) curl_easy_setopt(psRequest->m_curl_handle,CURLOPT_PROXYUSERPWD,pszProxyUserPwd); } void CPLHTTPCleanupRequest(CPLHTTPRequest *psRequest) { if (psRequest->m_curl_handle) { curl_easy_cleanup(psRequest->m_curl_handle); psRequest->m_curl_handle = 0; } if (psRequest->m_headers) { curl_slist_free_all(psRequest->m_headers); psRequest->m_headers = 0; } if (psRequest->m_curl_error) { CPLFree(psRequest->m_curl_error); psRequest->m_curl_error = 0; } if (psRequest->pszContentType) { CPLFree(psRequest->pszContentType); psRequest->pszContentType = 0; } if (psRequest->pszError) { CPLFree(psRequest->pszError); psRequest->pszError = 0; } if (psRequest->pabyData) { CPLFree(psRequest->pabyData); psRequest->pabyData = 0; psRequest->nDataLen = 0; psRequest->nDataAlloc = 0; } if (psRequest->papszOptions) { CSLDestroy(psRequest->papszOptions); psRequest->papszOptions = 0; } if (psRequest->pszURL) { CPLFree(psRequest->pszURL); psRequest->pszURL = 0; } } CPLErr CPLHTTPFetchMulti(CPLHTTPRequest *pasRequest, int nRequestCount, const char *const *papszOptions) { CPLErr ret = CE_None; CURLM *curl_multi = 0; int still_running; int max_conn; int i, conn_i; const char *max_conn_opt = CSLFetchNameValue(const_cast<char **>(papszOptions), "MAXCONN"); if (max_conn_opt && (max_conn_opt[0] != '\0')) { max_conn = MAX(1, MIN(atoi(max_conn_opt), 1000)); } else { max_conn = 5; } curl_multi = curl_multi_init(); if (curl_multi == NULL) { CPLError(CE_Fatal, CPLE_AppDefined, "CPLHTTPFetchMulti(): Unable to create CURL multi-handle."); } // add at most max_conn requests for (conn_i = 0; conn_i < MIN(nRequestCount, max_conn); ++conn_i) { CPLHTTPRequest *const psRequest = &pasRequest[conn_i]; CPLDebug("HTTP", "Requesting [%d/%d] %s", conn_i + 1, nRequestCount, pasRequest[conn_i].pszURL); curl_multi_add_handle(curl_multi, psRequest->m_curl_handle); } while (curl_multi_perform(curl_multi, &still_running) == CURLM_CALL_MULTI_PERFORM); while (still_running || (conn_i != nRequestCount)) { struct timeval timeout; fd_set fdread, fdwrite, fdexcep; int maxfd; CURLMsg *msg; int msgs_in_queue; do { msg = curl_multi_info_read(curl_multi, &msgs_in_queue); if (msg != NULL) { if (msg->msg == CURLMSG_DONE) { // transfer completed, check if we have more waiting and add them if (conn_i < nRequestCount) { CPLHTTPRequest *const psRequest = &pasRequest[conn_i]; CPLDebug("HTTP", "Requesting [%d/%d] %s", conn_i + 1, nRequestCount, pasRequest[conn_i].pszURL); curl_multi_add_handle(curl_multi, psRequest->m_curl_handle); ++conn_i; } } } } while (msg != NULL); FD_ZERO(&fdread); FD_ZERO(&fdwrite); FD_ZERO(&fdexcep); curl_multi_fdset(curl_multi, &fdread, &fdwrite, &fdexcep, &maxfd); timeout.tv_sec = 0; timeout.tv_usec = 100000; select(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); while (curl_multi_perform(curl_multi, &still_running) == CURLM_CALL_MULTI_PERFORM); } if (conn_i != nRequestCount) { // something gone really really wrong CPLError(CE_Fatal, CPLE_AppDefined, "CPLHTTPFetchMulti(): conn_i != nRequestCount, this should never happen ..."); } for (i = 0; i < nRequestCount; ++i) { CPLHTTPRequest *const psRequest = &pasRequest[i]; long response_code = 0; curl_easy_getinfo(psRequest->m_curl_handle, CURLINFO_RESPONSE_CODE, &response_code); psRequest->nStatus = response_code; char *content_type = 0; curl_easy_getinfo(psRequest->m_curl_handle, CURLINFO_CONTENT_TYPE, &content_type); if (content_type) psRequest->pszContentType = CPLStrdup(content_type); if ((psRequest->pszError == NULL) && (psRequest->m_curl_error != NULL) && (psRequest->m_curl_error[0] != '\0')) { psRequest->pszError = CPLStrdup(psRequest->m_curl_error); } /* In the case of a file:// URL, curl will return a status == 0, so if there's no */ /* error returned, patch the status code to be 200, as it would be for http:// */ if (strncmp(psRequest->pszURL, "file://", 7) == 0 && psRequest->nStatus == 0 && psRequest->pszError == NULL) { psRequest->nStatus = 200; } CPLDebug("HTTP", "Request [%d] %s : status = %d, content type = %s, error = %s", i, psRequest->pszURL, psRequest->nStatus, (psRequest->pszContentType) ? psRequest->pszContentType : "(null)", (psRequest->pszError) ? psRequest->pszError : "(null)"); curl_multi_remove_handle(curl_multi, pasRequest[i].m_curl_handle); } curl_multi_cleanup(curl_multi); return ret; }
AsherBond/MondocosmOS
gdal/frmts/wms/gdalhttp.cpp
C++
agpl-3.0
11,958
@extends('layouts/default') {{-- Page title --}} @section('title') @if ($user->id) {{ trans('admin/users/table.updateuser') }} {{ $user->present()->fullName() }} @else {{ trans('admin/users/table.createuser') }} @endif @parent @stop @section('header_right') <a href="{{ URL::previous() }}" class="btn btn-primary pull-right"> {{ trans('general.back') }}</a> @stop {{-- Page content --}} @section('content') <style> .form-horizontal .control-label { padding-top: 0px; } input[type='text'][disabled], input[disabled], textarea[disabled], input[readonly], textarea[readonly], .form-control[disabled], .form-control[readonly], fieldset[disabled] .form-control { background-color: white; color: #555555; cursor:text; } table.permissions { display:flex; flex-direction: column; } .permissions.table > thead, .permissions.table > tbody { margin: 15px; margin-top: 0px; } .permissions.table > tbody { border: 1px solid; } .header-row { border-bottom: 1px solid #ccc; } .permissions-row { display: flex; justify-content: space-between; align-items: center; } .table > tbody > tr > td.permissions-item { padding: 1px; padding-left: 8px; } .header-name { cursor: pointer; } </style> <div class="row"> <div class="col-md-8 col-md-offset-2"> <form class="form-horizontal" method="post" autocomplete="off" action="{{ (isset($user->id)) ? route('users.update', ['user' => $user->id]) : route('users.store') }}" enctype="multipart/form-data" id="userForm"> {{csrf_field()}} @if($user->id) {{ method_field('PUT') }} @endif <!-- Custom Tabs --> <div class="nav-tabs-custom"> <ul class="nav nav-tabs"> <li class="active"><a href="#tab_1" data-toggle="tab">Information</a></li> <li><a href="#tab_2" data-toggle="tab">Permissions</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="tab_1"> <div class="row"> <div class="col-md-12"> <!-- First Name --> <div class="form-group {{ $errors->has('first_name') ? 'has-error' : '' }}"> <label class="col-md-3 control-label" for="first_name">{{ trans('general.first_name') }}</label> <div class="col-md-6{{ (\App\Helpers\Helper::checkIfRequired($user, 'first_name')) ? ' required' : '' }}"> <input class="form-control" type="text" name="first_name" id="first_name" value="{{ old('first_name', $user->first_name) }}" /> {!! $errors->first('first_name', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> </div> <!-- Last Name --> <div class="form-group {{ $errors->has('last_name') ? 'has-error' : '' }}"> <label class="col-md-3 control-label" for="last_name">{{ trans('general.last_name') }} </label> <div class="col-md-6{{ (\App\Helpers\Helper::checkIfRequired($user, 'last_name')) ? ' required' : '' }}"> <input class="form-control" type="text" name="last_name" id="last_name" value="{{ old('last_name', $user->last_name) }}" /> {!! $errors->first('last_name', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> </div> <!-- Username --> <div class="form-group {{ $errors->has('username') ? 'has-error' : '' }}"> <label class="col-md-3 control-label" for="username">{{ trans('admin/users/table.username') }}</label> <div class="col-md-6{{ (\App\Helpers\Helper::checkIfRequired($user, 'username')) ? ' required' : '' }}"> @if ($user->ldap_import!='1') <input class="form-control" type="text" name="username" id="username" value="{{ Request::old('username', $user->username) }}" autocomplete="off" readonly onfocus="this.removeAttribute('readonly');" {{ ((config('app.lock_passwords') && ($user->id)) ? ' disabled' : '') }} > @if (config('app.lock_passwords') && ($user->id)) <p class="help-block">{{ trans('admin/users/table.lock_passwords') }}</p> @endif @else (Managed via LDAP) <input type="hidden" name="username" value="{{ Request::old('username', $user->username) }}"> @endif {!! $errors->first('username', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> </div> <!-- Password --> <div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}"> <label class="col-md-3 control-label" for="password"> {{ trans('admin/users/table.password') }} </label> <div class="col-md-6{{ (\App\Helpers\Helper::checkIfRequired($user, 'password')) ? ' required' : '' }}"> @if ($user->ldap_import!='1') <input type="password" name="password" class="form-control" id="password" value="" autocomplete="off" readonly onfocus="this.removeAttribute('readonly');" {{ ((config('app.lock_passwords') && ($user->id)) ? ' disabled' : '') }}> @else (Managed via LDAP) @endif <span id="generated-password"></span> {!! $errors->first('password', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> <div class="col-md-2"> @if ($user->ldap_import!='1') <a href="#" class="left" id="genPassword">Generate</a> @endif </div> </div> @if ($user->ldap_import!='1') <!-- Password Confirm --> <div class="form-group {{ $errors->has('password_confirmation') ? 'has-error' : '' }}"> <label class="col-md-3 control-label" for="password_confirmation"> {{ trans('admin/users/table.password_confirm') }} </label> <div class="col-md-6{{ ((\App\Helpers\Helper::checkIfRequired($user, 'first_name')) && (!$user->id)) ? ' required' : '' }}"> <input type="password" name="password_confirmation" id="password_confirm" class="form-control" value="" autocomplete="off" aria-label="password_confirmation" readonly onfocus="this.removeAttribute('readonly');" {{ ((config('app.lock_passwords') && ($user->id)) ? ' disabled' : '') }} > @if (config('app.lock_passwords') && ($user->id)) <p class="help-block">{{ trans('admin/users/table.lock_passwords') }}</p> @endif {!! $errors->first('password_confirmation', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> </div> @endif <!-- Email --> <div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}"> <label class="col-md-3 control-label" for="email">{{ trans('admin/users/table.email') }} </label> <div class="col-md-6{{ (\App\Helpers\Helper::checkIfRequired($user, 'email')) ? ' required' : '' }}"> <input class="form-control" type="text" name="email" id="email" value="{{ Request::old('email', $user->email) }}" {{ ((config('app.lock_passwords') && ($user->id)) ? ' disabled' : '') }} autocomplete="off" readonly onfocus="this.removeAttribute('readonly');"> @if (config('app.lock_passwords') && ($user->id)) <p class="help-block">{{ trans('admin/users/table.lock_passwords') }}</p> @endif {!! $errors->first('email', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> </div> <!-- Company --> @if (\App\Models\Company::canManageUsersCompanies()) @include ('partials.forms.edit.company-select', ['translated_name' => trans('general.select_company'), 'fieldname' => 'company_id']) @endif <!-- Image --> @if ($user->avatar) <div class="form-group {{ $errors->has('image_delete') ? 'has-error' : '' }}"> <label class="col-md-3 control-label" for="image_delete">{{ trans('general.image_delete') }}</label> <div class="col-md-5"> {{ Form::checkbox('image_delete') }} <img src="{{ Storage::disk('public')->url(app('users_upload_path').e($user->avatar)) }}" class="img-responsive" /> {!! $errors->first('image_delete', '<span class="alert-msg"><br>:message</span>') !!} </div> </div> @endif @include ('partials.forms.edit.image-upload', ['fieldname' => 'avatar']) <!-- language --> <div class="form-group {{ $errors->has('locale') ? 'has-error' : '' }}"> <label class="col-md-3 control-label" for="locale">{{ trans('general.language') }}</label> <div class="col-md-6"> {!! Form::locales('locale', old('locale', $user->locale), 'select2') !!} {!! $errors->first('locale', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> </div> <!-- Employee Number --> <div class="form-group {{ $errors->has('employee_num') ? 'has-error' : '' }}"> <label class="col-md-3 control-label" for="employee_num">{{ trans('admin/users/table.employee_num') }}</label> <div class="col-md-6"> <input class="form-control" type="text" aria-label="employee_num" name="employee_num" id="employee_num" value="{{ Request::old('employee_num', $user->employee_num) }}" /> {!! $errors->first('employee_num', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> </div> <!-- Jobtitle --> <div class="form-group {{ $errors->has('jobtitle') ? 'has-error' : '' }}"> <label class="col-md-3 control-label" for="jobtitle">{{ trans('admin/users/table.title') }}</label> <div class="col-md-6"> <input class="form-control" type="text" name="jobtitle" id="jobtitle" value="{{ Request::old('jobtitle', $user->jobtitle) }}" /> {!! $errors->first('jobtitle', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> </div> <!-- Manager --> @include ('partials.forms.edit.user-select', ['translated_name' => trans('admin/users/table.manager'), 'fieldname' => 'manager_id']) <!-- Department --> @include ('partials.forms.edit.department-select', ['translated_name' => trans('general.department'), 'fieldname' => 'department_id']) <!-- Location --> @include ('partials.forms.edit.location-select', ['translated_name' => trans('general.location'), 'fieldname' => 'location_id']) <!-- Phone --> <div class="form-group {{ $errors->has('phone') ? 'has-error' : '' }}"> <label class="col-md-3 control-label" for="phone">{{ trans('admin/users/table.phone') }}</label> <div class="col-md-6"> <input class="form-control" type="text" name="phone" id="phone" value="{{ old('phone', $user->phone) }}" /> {!! $errors->first('phone', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> </div> <!-- Website URL --> <div class="form-group {{ $errors->has('website') ? ' has-error' : '' }}"> <label for="website" class="col-md-3 control-label">{{ trans('general.website') }}</label> <div class="col-md-6"> <input class="form-control" type="text" name="website" id="website" value="{{ old('website', $user->website) }}" /> {!! $errors->first('website', '<span class="alert-msg" aria-hidden="true"><i class="fa fa-times" aria-hidden="true"></i> :message</span>') !!} </div> </div> <!-- Address --> <div class="form-group{{ $errors->has('address') ? ' has-error' : '' }}"> <label class="col-md-3 control-label" for="address">{{ trans('general.address') }}</label> <div class="col-md-6"> <input class="form-control" type="text" name="address" id="address" value="{{ old('address', $user->address) }}" /> {!! $errors->first('address', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> </div> <!-- City --> <div class="form-group{{ $errors->has('city') ? ' has-error' : '' }}"> <label class="col-md-3 control-label" for="city">{{ trans('general.city') }}</label> <div class="col-md-6"> <input class="form-control" type="text" name="city" id="city" aria-label="city" value="{{ old('city', $user->city) }}" /> {!! $errors->first('city', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> </div> <!-- State --> <div class="form-group{{ $errors->has('state') ? ' has-error' : '' }}"> <label class="col-md-3 control-label" for="state">{{ trans('general.state') }}</label> <div class="col-md-6"> <input class="form-control" type="text" name="state" id="state" value="{{ old('state', $user->state) }}" maxlength="3" /> {!! $errors->first('state', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> </div> <!-- Country --> <div class="form-group{{ $errors->has('country') ? ' has-error' : '' }}"> <label class="col-md-3 control-label" for="country">{{ trans('general.country') }}</label> <div class="col-md-6"> {!! Form::countries('country', old('country', $user->country), 'col-md-6 select2') !!} {!! $errors->first('country', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> </div> <!-- Zip --> <div class="form-group{{ $errors->has('zip') ? ' has-error' : '' }}"> <label class="col-md-3 control-label" for="zip">{{ trans('general.zip') }}</label> <div class="col-md-3"> <input class="form-control" type="text" name="zip" id="zip" value="{{ old('zip', $user->zip) }}" maxlength="10" /> {!! $errors->first('zip', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> </div> <!-- Activation Status --> <div class="form-group {{ $errors->has('activated') ? 'has-error' : '' }}"> <div class="form-group"> <div class="col-md-3 control-label"> {{ Form::label('activated', trans('admin/users/table.activated')) }} </div> <div class="col-md-9"> @if (config('app.lock_passwords')) <div class="icheckbox disabled" style="padding-left: 10px;"> <input type="checkbox" value="1" name="activated" class="minimal disabled" {{ (old('activated', $user->activated)) == '1' ? ' checked="checked"' : '' }} disabled="disabled" aria-label="activated"> <!-- this is necessary because the field is disabled and will reset --> <input type="hidden" name="activated" value="{{ $user->activated }}"> {{ trans('admin/users/general.activated_help_text') }} <p class="help-block">{{ trans('general.feature_disabled') }}</p> </div> @elseif ($user->id === Auth::user()->id) <div class="icheckbox disabled" style="padding-left: 10px;"> <input type="checkbox" value="1" name="activated" class="minimal disabled" {{ (old('activated', $user->activated)) == '1' ? ' checked="checked"' : '' }} disabled="disabled"> <!-- this is necessary because the field is disabled and will reset --> <input type="hidden" name="activated" value="1" aria-label="activated"> {{ trans('admin/users/general.activated_help_text') }} <p class="help-block">{{ trans('admin/users/general.activated_disabled_help_text') }}</p> </div> @else <div style="padding-left: 10px;"> <input type="checkbox" value="1" name="activated" class="minimal" {{ (old('activated', $user->activated)) == '1' ? ' checked="checked"' : '' }} aria-label="activated"> {{ trans('admin/users/general.activated_help_text') }} </div> @endif {!! $errors->first('activated', '<span class="alert-msg" aria-hidden="true">:message</span>') !!} </div> </div> </div> <!-- Email user --> @if (!$user->id) <div class="form-group" id="email_user_row" style="display: none;"> <div class="col-sm-3"> </div> <div class="col-md-9"> <div class="icheckbox disabled" id="email_user_div"> {{ Form::checkbox('email_user', '1', Request::old('email_user'),['class' => 'minimal', 'disabled'=>true, 'id' => 'email_user_checkbox']) }} Email this user their credentials? </div> <p class="help-block"> {{ trans('admin/users/general.send_email_help') }} </p> </div> </div> <!--/form-group--> @endif @if ($snipeSettings->two_factor_enabled!='') @if ($snipeSettings->two_factor_enabled=='1') <div class="form-group"> <div class="col-md-3 control-label"> {{ Form::label('two_factor_optin', trans('admin/settings/general.two_factor')) }} </div> <div class="col-md-9"> @if (config('app.lock_passwords')) <div class="icheckbox disabled"> {{ Form::checkbox('two_factor_optin', '1', Request::old('two_factor_optin', $user->two_factor_optin),['class' => 'minimal', 'disabled'=>'disabled']) }} {{ trans('admin/settings/general.two_factor_enabled_text') }} <p class="help-block">{{ trans('general.feature_disabled') }}</p> </div> @else {{ Form::checkbox('two_factor_optin', '1', Request::old('two_factor_optin', $user->two_factor_optin),['class' => 'minimal']) }} {{ trans('admin/settings/general.two_factor_enabled_text') }} <p class="help-block">{{ trans('admin/users/general.two_factor_admin_optin_help') }}</p> @endif </div> </div> @endif <!-- Reset Two Factor --> <div class="form-group"> <div class="col-md-8 col-md-offset-3 two_factor_resetrow"> <a class="btn btn-default btn-sm pull-left" id="two_factor_reset" style="margin-right: 10px;"> {{ trans('admin/settings/general.two_factor_reset') }}</a> <span id="two_factor_reseticon"> </span> <span id="two_factor_resetresult"> </span> <span id="two_factor_resetstatus"> </span> </div> <div class="col-md-8 col-md-offset-3 two_factor_resetrow"> <p class="help-block">{{ trans('admin/settings/general.two_factor_reset_help') }}</p> </div> </div> @endif <!-- Notes --> <div class="form-group{!! $errors->has('notes') ? ' has-error' : '' !!}"> <label for="notes" class="col-md-3 control-label">{{ trans('admin/users/table.notes') }}</label> <div class="col-md-6"> <textarea class="form-control" rows="5" id="notes" name="notes">{{ old('notes', $user->notes) }}</textarea> {!! $errors->first('notes', '<span class="alert-msg" aria-hidden="true"><i class="fa fa-times" aria-hidden="true"></i> :message</span>') !!} </div> </div> <!-- Groups --> <div class="form-group{{ $errors->has('groups') ? ' has-error' : '' }}"> <label class="col-md-3 control-label" for="groups[]"> {{ trans('general.groups') }}</label> <div class="col-md-6"> @if ((Config::get('app.lock_passwords') || (!Auth::user()->isSuperUser()))) @if (count($userGroups->keys()) > 0) <ul> @foreach ($groups as $id => $group) {!! ($userGroups->keys()->contains($id) ? '<li>'.e($group).'</li>' : '') !!} @endforeach </ul> @endif <span class="help-block">Only superadmins may edit group memberships.</p> @else <div class="controls"> <select name="groups[]" aria-label="groups[]" id="groups[]" multiple="multiple" class="form-control"> @foreach ($groups as $id => $group) <option value="{{ $id }}" {{ ($userGroups->keys()->contains($id) ? ' selected="selected"' : '') }}> {{ $group }} </option> @endforeach </select> <span class="help-block"> {{ trans('admin/users/table.groupnotes') }} </span> </div> @endif </div> </div> </div> <!--/col-md-12--> </div> </div><!-- /.tab-pane --> <div class="tab-pane" id="tab_2"> <div class="col-md-12"> @if (!Auth::user()->isSuperUser()) <p class="alert alert-warning">Only superadmins may grant a user superadmin access.</p> @endif </div> <table class="table table-striped permissions"> <thead> <tr class="permissions-row"> <th class="col-md-5">Permission</th> <th class="col-md-1">Grant</th> <th class="col-md-1">Deny</th> <th class="col-md-1">Inherit</th> </tr> </thead> @include('partials.forms.edit.permissions-base') </table> </div><!-- /.tab-pane --> </div><!-- /.tab-content --> <div class="box-footer text-right"> <button type="submit" class="btn btn-primary"><i class="fa fa-check icon-white" aria-hidden="true"></i> {{ trans('general.save') }}</button> </div> </div><!-- nav-tabs-custom --> </form> </div> <!--/col-md-8--> </div><!--/row--> @stop @section('moar_scripts') <script nonce="{{ csrf_token() }}"> $(document).ready(function() { $('#user_activated').on('ifChecked', function(event){ $("#email_user_row").show(); $('#email').on('keyup',function(){ event.preventDefault(); if(this.value.length > 5){ $('#email_user_checkbox').iCheck('enable'); } else { $('#email_user_checkbox').iCheck('disable').iCheck('uncheck'); } }); }); $('#user_activated').on('ifUnchecked', function(event){ $("#email_user_row").hide(); }); // Check/Uncheck all radio buttons in the group $('tr.header-row input:radio').on('ifClicked', function () { value = $(this).attr('value'); area = $(this).data('checker-group'); $('.radiochecker-'+area+'[value='+value+']').iCheck('check'); }); $('.header-name').click(function() { $(this).parent().nextUntil('tr.header-row').slideToggle(500); }); $('.tooltip-base').tooltip({container: 'body'}) $(".superuser").change(function() { var perms = $(this).val(); if (perms =='1') { $("#nonadmin").hide(); } else { $("#nonadmin").show(); } }); $('#genPassword').pGenerator({ 'bind': 'click', 'passwordElement': '#password', 'displayElement': '#generated-password', 'passwordLength': 16, 'uppercase': true, 'lowercase': true, 'numbers': true, 'specialChars': true, 'onPasswordGenerated': function(generatedPassword) { $('#password_confirm').val($('#password').val()); } }); $("#two_factor_reset").click(function(){ $("#two_factor_resetrow").removeClass('success'); $("#two_factor_resetrow").removeClass('danger'); $("#two_factor_resetstatus").html(''); $("#two_factor_reseticon").html('<i class="fa fa-spinner spin"></i>'); $.ajax({ url: '{{ route('api.users.two_factor_reset', ['id'=> $user->id]) }}', type: 'POST', data: {}, headers: { "X-Requested-With": 'XMLHttpRequest', "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr('content') }, dataType: 'json', success: function (data) { $("#two_factor_reseticon").html(''); $("#two_factor_resetstatus").html('<i class="fa fa-check text-success"></i>' + data.message); }, error: function (data) { $("#two_factor_reseticon").html(''); $("#two_factor_reseticon").html('<i class="fa fa-exclamation-triangle text-danger"></i>'); $('#two_factor_resetstatus').text(data.message); } }); }); }); </script> @stop
dmeltzer/snipe-it
resources/views/users/edit.blade.php
PHP
agpl-3.0
29,771
/*! \file gsd_prim.c \brief OGSF library - primitive drawing functions (lower level functions) GRASS OpenGL gsurf OGSF Library (C) 1999-2008 by the GRASS Development Team This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details. \author Bill Brown USACERL (January 1993) \author Doxygenized by Martin Landa <landa.martin gmail.com> (May 2008) */ #include <stdlib.h> #include <string.h> #include <grass/config.h> #if defined(OPENGL_X11) || defined(OPENGL_WINDOWS) #include <GL/gl.h> #include <GL/glu.h> #elif defined(OPENGL_AQUA) #include <OpenGL/gl.h> #include <OpenGL/glu.h> #endif #include <grass/gis.h> #include <grass/gstypes.h> #include <grass/glocale.h> #define USE_GL_NORMALIZE #define RED_MASK 0x000000FF #define GRN_MASK 0x0000FF00 #define BLU_MASK 0x00FF0000 #define ALP_MASK 0xFF000000 #define INT_TO_RED(i, r) (r = (i & RED_MASK)) #define INT_TO_GRN(i, g) (g = (i & GRN_MASK) >> 8) #define INT_TO_BLU(i, b) (b = (i & BLU_MASK) >> 16) #define INT_TO_ALP(i, a) (a = (i & ALP_MASK) >> 24) #define MAX_OBJS 64 /* ^ TMP - move to gstypes */ /* define border width (pixels) for viewport check */ #define border 15 static GLuint ObjList[MAX_OBJS]; static int numobjs = 0; static int Shade; static float ogl_light_amb[MAX_LIGHTS][4]; static float ogl_light_diff[MAX_LIGHTS][4]; static float ogl_light_spec[MAX_LIGHTS][4]; static float ogl_light_pos[MAX_LIGHTS][4]; static float ogl_mat_amb[4]; static float ogl_mat_diff[4]; static float ogl_mat_spec[4]; static float ogl_mat_emis[4]; static float ogl_mat_shin; /*! \brief Mostly for flushing drawing commands accross a network glFlush doesn't block, so if blocking is desired use glFinish. */ void gsd_flush(void) { glFlush(); return; } /*! \brief Set color mode Call glColorMaterial before enabling the GL_COLOR_MATERIAL \param cm color mode value */ void gsd_colormode(int cm) { switch (cm) { case CM_COLOR: glDisable(GL_COLOR_MATERIAL); glDisable(GL_LIGHTING); break; case CM_EMISSION: glColorMaterial(GL_FRONT_AND_BACK, GL_EMISSION); glEnable(GL_COLOR_MATERIAL); glEnable(GL_LIGHTING); break; case CM_DIFFUSE: glColorMaterial(GL_FRONT, GL_DIFFUSE); glEnable(GL_COLOR_MATERIAL); glEnable(GL_LIGHTING); break; case CM_AD: glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE); glEnable(GL_COLOR_MATERIAL); glEnable(GL_LIGHTING); break; case CM_NULL: /* OGLXXX * lmcolor: if LMC_NULL, use: * glDisable(GL_COLOR_MATERIAL); * LMC_NULL: use glDisable(GL_COLOR_MATERIAL); */ glDisable(GL_COLOR_MATERIAL); glEnable(GL_LIGHTING); break; default: glDisable(GL_COLOR_MATERIAL); break; } return; } /*! \brief Print color mode to stderr */ void show_colormode(void) { GLint mat; glGetIntegerv(GL_COLOR_MATERIAL_PARAMETER, &mat); G_message(_("Color Material: %d"), mat); return; } /*! \brief ADD \param x,y \param rad */ void gsd_circ(float x, float y, float rad) { GLUquadricObj *qobj = gluNewQuadric(); gluQuadricDrawStyle(qobj, GLU_SILHOUETTE); glPushMatrix(); glTranslatef(x, y, 0.); gluDisk(qobj, 0., rad, 32, 1); glPopMatrix(); gluDeleteQuadric(qobj); return; } /*! \brief ADD \param x,y,z \param rad */ void gsd_disc(float x, float y, float z, float rad) { GLUquadricObj *qobj = gluNewQuadric(); gluQuadricDrawStyle(qobj, GLU_FILL); glPushMatrix(); glTranslatef(x, y, z); gluDisk(qobj, 0., rad, 32, 1); glPopMatrix(); gluDeleteQuadric(qobj); return; } /*! \brief ADD \param center center-point \param siz size value */ void gsd_sphere(float *center, float siz) { static int first = 1; static GLUquadricObj *QOsphere; if (first) { QOsphere = gluNewQuadric(); if (QOsphere) { gluQuadricNormals(QOsphere, GLU_SMOOTH); /* default */ gluQuadricTexture(QOsphere, GL_FALSE); /* default */ gluQuadricOrientation(QOsphere, GLU_OUTSIDE); /* default */ gluQuadricDrawStyle(QOsphere, GLU_FILL); } first = 0; } glPushMatrix(); glTranslatef(center[0], center[1], center[2]); gluSphere(QOsphere, (double)siz, 24, 24); glPopMatrix(); return; } /*! \brief Write out z-mask Enable or disable writing into the depth buffer \param n Specifies whether the depth buffer is enabled for writing */ void gsd_zwritemask(unsigned long n) { /* OGLXXX glDepthMask is boolean only */ glDepthMask((GLboolean) (n)); return; } /*! \brief ADD \param n */ void gsd_backface(int n) { glCullFace(GL_BACK); (n) ? glEnable(GL_CULL_FACE) : glDisable(GL_CULL_FACE); return; } /*! \brief Set width of rasterized lines \param n line width */ void gsd_linewidth(short n) { glLineWidth((GLfloat) (n)); return; } /*! \brief ADD */ void gsd_bgnqstrip(void) { glBegin(GL_QUAD_STRIP); return; } /*! \brief ADD */ void gsd_endqstrip(void) { glEnd(); return; } /*! \brief ADD */ void gsd_bgntmesh(void) { glBegin(GL_TRIANGLE_STRIP); return; } /*! \brief ADD */ void gsd_endtmesh(void) { glEnd(); return; } /*! \brief ADD */ void gsd_bgntstrip(void) { glBegin(GL_TRIANGLE_STRIP); return; } /*! \brief ADD */ void gsd_endtstrip(void) { glEnd(); return; } /*! \brief ADD */ void gsd_bgntfan(void) { glBegin(GL_TRIANGLE_FAN); return; } /*! \brief ADD */ void gsd_endtfan(void) { glEnd(); return; } /*! \brief ADD */ void gsd_swaptmesh(void) { /* OGLXXX * swaptmesh not supported, maybe glBegin(GL_TRIANGLE_FAN) * swaptmesh() */ /*DELETED*/; return; } /*! \brief Delimit the vertices of a primitive or a group of like primitives */ void gsd_bgnpolygon(void) { /* OGLXXX * special cases for polygons: * independant quads: use GL_QUADS * independent triangles: use GL_TRIANGLES */ glBegin(GL_POLYGON); return; } /*! \brief Delimit the vertices of a primitive or a group of like primitives */ void gsd_endpolygon(void) { glEnd(); return; } /*! \brief Begin line */ void gsd_bgnline(void) { /* OGLXXX for multiple, independent line segments: use GL_LINES */ glBegin(GL_LINE_STRIP); return; } /*! \brief End line */ void gsd_endline(void) { glEnd(); return; } /*! \brief Set shaded model \param bool type non-zero for GL_SMOOTH otherwise GL_FLAT */ void gsd_shademodel(int bool) { Shade = bool; if (bool) { glShadeModel(GL_SMOOTH); } else { glShadeModel(GL_FLAT); } return; } /*! \brief Get shaded model \return shade */ int gsd_getshademodel(void) { return (Shade); } /*! \brief ADD */ void gsd_bothbuffer(void) { /* OGLXXX frontbuffer: other possibilities include GL_FRONT_AND_BACK */ glDrawBuffer(GL_FRONT_AND_BACK); return; } /*! \brief Specify which color buffers are to be drawn into \param bool non-zero for enable otherwise disable front buffer */ void gsd_frontbuffer(int bool) { /* OGLXXX frontbuffer: other possibilities include GL_FRONT_AND_BACK */ glDrawBuffer((bool) ? GL_FRONT : GL_BACK); return; } /*! \brief Specify which color buffers are to be drawn into \param bool non-zero for enable otherwise disable back buffer */ void gsd_backbuffer(int bool) { /* OGLXXX backbuffer: other possibilities include GL_FRONT_AND_BACK */ glDrawBuffer((bool) ? GL_BACK : GL_FRONT); return; } /*! \brief Swap buffers */ void gsd_swapbuffers(void) { /* OGLXXX swapbuffers: glXSwapBuffers(*display, window); replace display and window */ Swap_func(); return; } /*! \brief Pop the current matrix stack */ void gsd_popmatrix(void) { glPopMatrix(); return; } /*! \brief Push the current matrix stack */ void gsd_pushmatrix(void) { glPushMatrix(); return; } /*! \brief Multiply the current matrix by a general scaling matrix \param xs x scale value \param ys y scale value \param zs z scale value */ void gsd_scale(float xs, float ys, float zs) { glScalef(xs, ys, zs); return; } /*! \brief Multiply the current matrix by a translation matrix \param dx x translation value \param dy y translation value \param dz z translation value */ void gsd_translate(float dx, float dy, float dz) { glTranslatef(dx, dy, dz); return; } /*! \brief Get viewport \param[out] window \param viewport \param modelMatrix model matrix \param projMatrix projection matrix */ void gsd_getwindow(int *window, int *viewport, double *modelMatrix, double *projMatrix) { gsd_pushmatrix(); gsd_do_scale(1); glGetDoublev(GL_MODELVIEW_MATRIX, modelMatrix); glGetDoublev(GL_PROJECTION_MATRIX, projMatrix); glGetIntegerv(GL_VIEWPORT, viewport); gsd_popmatrix(); window[0] = viewport[1] + viewport[3] + border; window[1] = viewport[1] - border; window[2] = viewport[0] - border; window[3] = viewport[0] + viewport[2] + border; return; } /*! \brief ADD \param pt \param widnow \param viewport \param doubleMatrix \param projMatrix \return 0 \return 1 */ int gsd_checkpoint(float pt[4], int window[4], int viewport[4], double modelMatrix[16], double projMatrix[16]) { GLdouble fx, fy, fz; gluProject((GLdouble) pt[X], (GLdouble) pt[Y], (GLdouble) pt[Z], modelMatrix, projMatrix, viewport, &fx, &fy, &fz); if (fx < window[2] || fx > window[3] || fy < window[1] || fy > window[0]) return 1; else return 0; } /*! \brief ADD \param angle \param axis */ void gsd_rot(float angle, char axis) { GLfloat x; GLfloat y; GLfloat z; switch (axis) { case 'x': case 'X': x = 1.0; y = 0.0; z = 0.0; break; case 'y': case 'Y': x = 0.0; y = 1.0; z = 0.0; break; case 'z': case 'Z': x = 0.0; y = 0.0; z = 1.0; break; default: G_warning(_("gsd_rot(): %c is an invalid axis " "specification. Rotation ignored. " "Please advise GRASS developers of this error"), axis); return; } glRotatef((GLfloat) angle, x, y, z); return; } /*! \brief Set the current normal vector & specify vertex \param norm normal vector \param col color value \param pt point (model coordinates) */ void gsd_litvert_func(float *norm, unsigned long col, float *pt) { glNormal3fv(norm); gsd_color_func(col); glVertex3fv(pt); return; } /*! \brief ADD \param norm \param col \param pt */ void gsd_litvert_func2(float *norm, unsigned long col, float *pt) { glNormal3fv(norm); glVertex3fv(pt); return; } /*! \brief ADD \param pt */ void gsd_vert_func(float *pt) { glVertex3fv(pt); return; } /*! \brief Set current color \param col color value */ void gsd_color_func(unsigned int col) { GLbyte r, g, b, a; /* OGLXXX * cpack: if argument is not a variable * might need to be: * glColor4b(($1)&0xff, ($1)>>8&0xff, ($1)>>16&0xff, ($1)>>24&0xff) */ INT_TO_RED(col, r); INT_TO_GRN(col, g); INT_TO_BLU(col, b); INT_TO_ALP(col, a); glColor4ub(r, g, b, a); return; } /*! \brief Initialize model light */ void gsd_init_lightmodel(void) { glEnable(GL_LIGHTING); /* normal vector renormalization */ #ifdef USE_GL_NORMALIZE { glEnable(GL_NORMALIZE); } #endif /* OGLXXX * Ambient: * If this is a light model lmdef, then use * glLightModelf and GL_LIGHT_MODEL_AMBIENT. * Include ALPHA parameter with ambient */ /* Default is front face lighting, infinite viewer */ ogl_mat_amb[0] = 0.1; ogl_mat_amb[1] = 0.1; ogl_mat_amb[2] = 0.1; ogl_mat_amb[3] = 1.0; ogl_mat_diff[0] = 0.8; ogl_mat_diff[1] = 0.8; ogl_mat_diff[2] = 0.8; ogl_mat_diff[3] = 0.8; ogl_mat_spec[0] = 0.8; ogl_mat_spec[1] = 0.8; ogl_mat_spec[2] = 0.8; ogl_mat_spec[3] = 0.8; ogl_mat_emis[0] = 0.0; ogl_mat_emis[1] = 0.0; ogl_mat_emis[2] = 0.0; ogl_mat_emis[3] = 0.0; ogl_mat_shin = 25.0; /* OGLXXX * attenuation: see glLightf man page: (ignored for infinite lights) * Add GL_LINEAR_ATTENUATION. sgi_lmodel[0] = GL_CONSTANT_ATTENUATION; sgi_lmodel[1] = 1.0; sgi_lmodel[2] = 0.0; sgi_lmodel[3] = ; */ /* OGLXXX * lmdef other possibilities include: * glLightf(light, pname, *params); * glLightModelf(pname, param); * Check list numbering. * Translate params as needed. */ glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ogl_mat_amb); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, ogl_mat_diff); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, ogl_mat_spec); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, ogl_mat_emis); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, ogl_mat_shin); /* OGLXXX lmbind: check object numbering. */ /* OGLXXX * lmbind: check object numbering. * Use GL_FRONT in call to glMaterialf. * Use GL_FRONT in call to glMaterialf. if(1) {glCallList(1); glEnable(LMODEL);} else glDisable(LMODEL); if(1) {glCallList(1); glEnable(GL_FRONT);} else glDisable(GL_FRONT); */ return; } /*! \brief Set material \param set_shin,set_emis flags \param sh,em should be 0. - 1. \param emcolor packed colors to use for emission */ void gsd_set_material(int set_shin, int set_emis, float sh, float em, int emcolor) { if (set_shin) { ogl_mat_spec[0] = sh; ogl_mat_spec[1] = sh; ogl_mat_spec[2] = sh; ogl_mat_spec[3] = sh; glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, ogl_mat_spec); ogl_mat_shin = 60. + (int)(sh * 68.); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, ogl_mat_shin); } if (set_emis) { ogl_mat_emis[0] = (em * (emcolor & 0x0000FF)) / 255.; ogl_mat_emis[1] = (em * ((emcolor & 0x00FF00) >> 8)) / 255.; ogl_mat_emis[2] = (em * ((emcolor & 0xFF0000) >> 16)) / 255.; glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, ogl_mat_emis); } return; } /*! \brief Define light \param num light id (starts with 1) \param vals position(x,y,z,w), color, ambientm, emission */ void gsd_deflight(int num, struct lightdefs *vals) { if (num > 0 && num <= MAX_LIGHTS) { ogl_light_pos[num - 1][0] = vals->position[X]; ogl_light_pos[num - 1][1] = vals->position[Y]; ogl_light_pos[num - 1][2] = vals->position[Z]; ogl_light_pos[num - 1][3] = vals->position[W]; glLightfv(GL_LIGHT0 + num, GL_POSITION, ogl_light_pos[num - 1]); ogl_light_diff[num - 1][0] = vals->color[0]; ogl_light_diff[num - 1][1] = vals->color[1]; ogl_light_diff[num - 1][2] = vals->color[2]; ogl_light_diff[num - 1][3] = .3; glLightfv(GL_LIGHT0 + num, GL_DIFFUSE, ogl_light_diff[num - 1]); ogl_light_amb[num - 1][0] = vals->ambient[0]; ogl_light_amb[num - 1][1] = vals->ambient[1]; ogl_light_amb[num - 1][2] = vals->ambient[2]; ogl_light_amb[num - 1][3] = .3; glLightfv(GL_LIGHT0 + num, GL_AMBIENT, ogl_light_amb[num - 1]); ogl_light_spec[num - 1][0] = vals->color[0]; ogl_light_spec[num - 1][1] = vals->color[1]; ogl_light_spec[num - 1][2] = vals->color[2]; ogl_light_spec[num - 1][3] = .3; glLightfv(GL_LIGHT0 + num, GL_SPECULAR, ogl_light_spec[num - 1]); } return; } /*! \brief Switch light on/off \param num \param on 1 for 'on', 0 turns them off */ void gsd_switchlight(int num, int on) { short defin; defin = on ? num : 0; if (defin) { glEnable(GL_LIGHT0 + num); } else { glDisable(GL_LIGHT0 + num); } return; } /*! \brief Get image of current GL screen \param pixbuf data buffer \param[out] xsize,ysize picture dimension \return 0 on failure \return 1 on success */ int gsd_getimage(unsigned char **pixbuf, unsigned int *xsize, unsigned int *ysize) { GLuint l, r, b, t; /* OGLXXX * get GL_VIEWPORT: * You can probably do better than this. */ GLint tmp[4]; glGetIntegerv(GL_VIEWPORT, tmp); l = tmp[0]; r = tmp[0] + tmp[2] - 1; b = tmp[1]; t = tmp[1] + tmp[3] - 1; *xsize = r - l + 1; *ysize = t - b + 1; *pixbuf = (unsigned char *)G_malloc((*xsize) * (*ysize) * 4); /* G_fatal_error */ if (!*pixbuf) return (0); glReadBuffer(GL_FRONT); /* OGLXXX lrectread: see man page for glReadPixels */ glReadPixels(l, b, (r) - (l) + 1, (t) - (b) + 1, GL_RGBA, GL_UNSIGNED_BYTE, *pixbuf); return (1); } /*! \brief Get viewpoint \param tmp \param num \return 1 */ int gsd_getViewport(GLint tmp[4], GLint num[2]) { /* Save current viewport to tmp */ glGetIntegerv(GL_VIEWPORT, tmp); glGetIntegerv(GL_MAX_VIEWPORT_DIMS, num); return (1); } /*! \brief Write view \param pixbuf data buffer \param xsize,ysize picture dimension */ int gsd_writeView(unsigned char **pixbuf, unsigned int xsize, unsigned int ysize) { /* Malloc Buffer for image */ *pixbuf = (unsigned char *)G_malloc(xsize * ysize * 4); /* G_fatal_error */ if (!*pixbuf) { return (0); } /* Read image buffer */ glReadBuffer(GL_FRONT); /* Read Pixels into Buffer */ glReadPixels(0, 0, xsize, ysize, GL_RGBA, GL_UNSIGNED_BYTE, *pixbuf); return (1); } /*! \brief Specify pixel arithmetic \param yesno turn on/off */ void gsd_blend(int yesno) { if (yesno) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } else { glDisable(GL_BLEND); glBlendFunc(GL_ONE, GL_ZERO); } return; } /*! \brief Define clip plane \param num \param params */ void gsd_def_clipplane(int num, double *params) { int wason = 0; /* OGLXXX see man page for glClipPlane equation */ if (glIsEnabled(GL_CLIP_PLANE0 + (num))) { wason = 1; } glClipPlane(GL_CLIP_PLANE0 + (num), params); if (wason) { glEnable(GL_CLIP_PLANE0 + (num)); } else { glDisable(GL_CLIP_PLANE0 + (num)); } return; } /*! \brief Set clip plane \param num \param able */ void gsd_set_clipplane(int num, int able) { /* OGLXXX see man page for glClipPlane equation */ if (able) { glEnable(GL_CLIP_PLANE0 + (num)); } else { glDisable(GL_CLIP_PLANE0 + (num)); } return; } /*! \brief Finish Does nothing, only called from src.contrib/GMSL/NVIZ2.2/src/glwrappers.c */ void gsd_finish(void) { return; } /*! \brief Set the viewport <i>l</i>, <i>b</i> specify the lower left corner of the viewport rectangle, in pixels. <i>r</i>, <i>t</i> specify the width and height of the viewport. \param l left \param r right \param b bottom \param t top */ void gsd_viewport(int l, int r, int b, int t) { /* Screencoord */ glViewport(l, b, r, t); return; } /*! \brief ADD First time called, gets a bunch of objects, then hands them back when needed \return -1 on failure \return number of objects */ int gsd_makelist(void) { int i; if (numobjs) { if (numobjs < MAX_OBJS) { numobjs++; return (numobjs); } return (-1); } else { ObjList[0] = glGenLists(MAX_OBJS); for (i = 1; i < MAX_OBJS; i++) { ObjList[i] = ObjList[0] + i; } numobjs = 1; return (numobjs); } } /*! \brief ADD \param listno \param do_draw */ void gsd_bgnlist(int listno, int do_draw) { if (do_draw) { glNewList(ObjList[listno], GL_COMPILE_AND_EXECUTE); } else { glNewList(ObjList[listno], GL_COMPILE); } return; } /*! \brief End list */ void gsd_endlist(void) { glEndList(); return; } /*! \brief Delete list \param listno \param range */ void gsd_deletelist(GLuint listno, int range) { unsigned int i; for (i = 1; i < MAX_OBJS; i++) { if (i == listno) { glDeleteLists(ObjList[i], 1); numobjs--; if (numobjs < 1) numobjs = 1; return; } } } /*! \brief ADD \param listno */ void gsd_calllist(int listno) { glCallList(ObjList[listno]); return; } /*! \brief ADD \param listno */ void gsd_calllists(int listno) { int i; gsd_pushmatrix(); for (i = 1; i < MAX_OBJS; i++) { glCallList(ObjList[i]); glFlush(); } gsd_popmatrix(); gsd_call_label(); return; }
AsherBond/MondocosmOS
grass_trunk/lib/ogsf/gsd_prim.c
C
agpl-3.0
20,494
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated: 12/10/2015, 13:28 * */ package ims.correspondence.domain.objects; /** * * @author Neil McAnaspie * Generated. */ public class CorrespondenceDetails extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable { public static final int CLASSID = 1052100001; private static final long serialVersionUID = 1052100001L; public static final String CLASSVERSION = "${ClassVersion}"; @Override public boolean shouldCapQuery() { return true; } /** PAS Event */ private ims.core.admin.pas.domain.objects.PASEvent pasEvent; /** Current Status */ private ims.domain.lookups.LookupInstance currentStatus; /** Historic Status of CSP Details record * Collection of ims.correspondence.domain.objects.CorrespondenceStatusHistory. */ private java.util.Set cspStatusHistory; /** Discharge Categories * Collection of ims.correspondence.domain.objects.CategoryNotes. */ private java.util.List categories; /** document recipient(s) * Collection of ims.correspondence.domain.objects.Recipient. */ private java.util.List recipients; /** Current Document */ private ims.core.documents.domain.objects.Document currentDocument; /** Document Detail signed byMOS-HCP */ private ims.core.resource.people.domain.objects.Medic signedBy; /** Special Interest Type */ private ims.domain.lookups.LookupInstance specialInterest; /** Date Of Clinic */ private java.util.Date dateOfClinic; /** Admission Date */ private java.util.Date admissionDate; /** Discharge Date */ private java.util.Date dischargeDate; /** DictatedBy */ private ims.core.resource.people.domain.objects.MemberOfStaff dictatedBy; /** Dictated By Initials */ private String dictatedByInitials; /** TypedBy */ private ims.core.resource.people.domain.objects.MemberOfStaff typedBy; /** TypedByInitials */ private String typedByInitials; /** EnquiriesTo */ private ims.core.resource.people.domain.objects.MemberOfStaff enquiriesTo; /** WasTypedWithoutCaseNotes */ private Boolean wasTypedWithoutCaseNotes; /** SystemInformation */ private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation(); public CorrespondenceDetails (Integer id, int ver) { super(id, ver); } public CorrespondenceDetails () { super(); } public CorrespondenceDetails (Integer id, int ver, Boolean includeRecord) { super(id, ver, includeRecord); } public Class getRealDomainClass() { return ims.correspondence.domain.objects.CorrespondenceDetails.class; } public ims.core.admin.pas.domain.objects.PASEvent getPasEvent() { return pasEvent; } public static CorrespondenceDetails getCorrespondenceDetailsFromPasEvent(ims.domain.ILightweightDomainFactory factory, Integer id) { java.util.List l = factory.find("from CorrespondenceDetails c where c.pasEvent.id = " + id); if (l == null || l.size() == 0) return null; if (l.size() > 1) throw new ims.domain.exceptions.DomainRuntimeException("Non-unique get call. CorrespondenceDetails.pasEvent.id = " + id + " returned " + l.size() + " records. " ); return (CorrespondenceDetails)l.get(0); } public void setPasEvent(ims.core.admin.pas.domain.objects.PASEvent pasEvent) { this.pasEvent = pasEvent; } public ims.domain.lookups.LookupInstance getCurrentStatus() { return currentStatus; } public void setCurrentStatus(ims.domain.lookups.LookupInstance currentStatus) { this.currentStatus = currentStatus; } public java.util.Set getCspStatusHistory() { if ( null == cspStatusHistory ) { cspStatusHistory = new java.util.HashSet(); } return cspStatusHistory; } public void setCspStatusHistory(java.util.Set paramValue) { this.cspStatusHistory = paramValue; } public java.util.List getCategories() { if ( null == categories ) { categories = new java.util.ArrayList(); } return categories; } public void setCategories(java.util.List paramValue) { this.categories = paramValue; } public java.util.List getRecipients() { if ( null == recipients ) { recipients = new java.util.ArrayList(); } return recipients; } public void setRecipients(java.util.List paramValue) { this.recipients = paramValue; } public ims.core.documents.domain.objects.Document getCurrentDocument() { return currentDocument; } public void setCurrentDocument(ims.core.documents.domain.objects.Document currentDocument) { this.currentDocument = currentDocument; } public ims.core.resource.people.domain.objects.Medic getSignedBy() { return signedBy; } public void setSignedBy(ims.core.resource.people.domain.objects.Medic signedBy) { this.signedBy = signedBy; } public ims.domain.lookups.LookupInstance getSpecialInterest() { return specialInterest; } public void setSpecialInterest(ims.domain.lookups.LookupInstance specialInterest) { this.specialInterest = specialInterest; } public java.util.Date getDateOfClinic() { return dateOfClinic; } public void setDateOfClinic(java.util.Date dateOfClinic) { this.dateOfClinic = dateOfClinic; } public java.util.Date getAdmissionDate() { return admissionDate; } public void setAdmissionDate(java.util.Date admissionDate) { this.admissionDate = admissionDate; } public java.util.Date getDischargeDate() { return dischargeDate; } public void setDischargeDate(java.util.Date dischargeDate) { this.dischargeDate = dischargeDate; } public ims.core.resource.people.domain.objects.MemberOfStaff getDictatedBy() { return dictatedBy; } public void setDictatedBy(ims.core.resource.people.domain.objects.MemberOfStaff dictatedBy) { this.dictatedBy = dictatedBy; } public String getDictatedByInitials() { return dictatedByInitials; } public void setDictatedByInitials(String dictatedByInitials) { if ( null != dictatedByInitials && dictatedByInitials.length() > 10 ) { throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for dictatedByInitials. Tried to set value: "+ dictatedByInitials); } this.dictatedByInitials = dictatedByInitials; } public ims.core.resource.people.domain.objects.MemberOfStaff getTypedBy() { return typedBy; } public void setTypedBy(ims.core.resource.people.domain.objects.MemberOfStaff typedBy) { this.typedBy = typedBy; } public String getTypedByInitials() { return typedByInitials; } public void setTypedByInitials(String typedByInitials) { if ( null != typedByInitials && typedByInitials.length() > 10 ) { throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for typedByInitials. Tried to set value: "+ typedByInitials); } this.typedByInitials = typedByInitials; } public ims.core.resource.people.domain.objects.MemberOfStaff getEnquiriesTo() { return enquiriesTo; } public void setEnquiriesTo(ims.core.resource.people.domain.objects.MemberOfStaff enquiriesTo) { this.enquiriesTo = enquiriesTo; } public Boolean isWasTypedWithoutCaseNotes() { return wasTypedWithoutCaseNotes; } public void setWasTypedWithoutCaseNotes(Boolean wasTypedWithoutCaseNotes) { this.wasTypedWithoutCaseNotes = wasTypedWithoutCaseNotes; } public ims.domain.SystemInformation getSystemInformation() { if (systemInformation == null) systemInformation = new ims.domain.SystemInformation(); return systemInformation; } /** * isConfigurationObject * Taken from the Usage property of the business object, this method will return * a boolean indicating whether this is a configuration object or not * Configuration = true, Instantiation = false */ public static boolean isConfigurationObject() { if ( "Instantiation".equals("Configuration") ) return true; else return false; } public int getClassId() { return CLASSID; } public String getClassVersion() { return CLASSVERSION; } public String toAuditString() { StringBuffer auditStr = new StringBuffer(); auditStr.append("\r\n*pasEvent* :"); if (pasEvent != null) { auditStr.append(toShortClassName(pasEvent)); auditStr.append(pasEvent.getId()); } auditStr.append("; "); auditStr.append("\r\n*currentStatus* :"); if (currentStatus != null) auditStr.append(currentStatus.getText()); auditStr.append("; "); auditStr.append("\r\n*cspStatusHistory* :"); if (cspStatusHistory != null) { java.util.Iterator it3 = cspStatusHistory.iterator(); int i3=0; while (it3.hasNext()) { if (i3 > 0) auditStr.append(","); ims.correspondence.domain.objects.CorrespondenceStatusHistory obj = (ims.correspondence.domain.objects.CorrespondenceStatusHistory)it3.next(); if (obj != null) { if (i3 == 0) { auditStr.append(toShortClassName(obj)); auditStr.append("["); } auditStr.append(obj.getId()); } i3++; } if (i3 > 0) auditStr.append("] " + i3); } auditStr.append("; "); auditStr.append("\r\n*categories* :"); if (categories != null) { int i4=0; for (i4=0; i4<categories.size(); i4++) { if (i4 > 0) auditStr.append(","); ims.correspondence.domain.objects.CategoryNotes obj = (ims.correspondence.domain.objects.CategoryNotes)categories.get(i4); if (obj != null) { if (i4 == 0) { auditStr.append(toShortClassName(obj)); auditStr.append("["); } auditStr.append(obj.getId()); } } if (i4 > 0) auditStr.append("] " + i4); } auditStr.append("; "); auditStr.append("\r\n*recipients* :"); if (recipients != null) { int i5=0; for (i5=0; i5<recipients.size(); i5++) { if (i5 > 0) auditStr.append(","); ims.correspondence.domain.objects.Recipient obj = (ims.correspondence.domain.objects.Recipient)recipients.get(i5); if (obj != null) { if (i5 == 0) { auditStr.append(toShortClassName(obj)); auditStr.append("["); } auditStr.append(obj.getId()); } } if (i5 > 0) auditStr.append("] " + i5); } auditStr.append("; "); auditStr.append("\r\n*currentDocument* :"); if (currentDocument != null) { auditStr.append(toShortClassName(currentDocument)); auditStr.append(currentDocument.getId()); } auditStr.append("; "); auditStr.append("\r\n*signedBy* :"); if (signedBy != null) { auditStr.append(toShortClassName(signedBy)); auditStr.append(signedBy.getId()); } auditStr.append("; "); auditStr.append("\r\n*specialInterest* :"); if (specialInterest != null) auditStr.append(specialInterest.getText()); auditStr.append("; "); auditStr.append("\r\n*dateOfClinic* :"); auditStr.append(dateOfClinic); auditStr.append("; "); auditStr.append("\r\n*admissionDate* :"); auditStr.append(admissionDate); auditStr.append("; "); auditStr.append("\r\n*dischargeDate* :"); auditStr.append(dischargeDate); auditStr.append("; "); auditStr.append("\r\n*dictatedBy* :"); if (dictatedBy != null) { auditStr.append(toShortClassName(dictatedBy)); auditStr.append(dictatedBy.getId()); } auditStr.append("; "); auditStr.append("\r\n*dictatedByInitials* :"); auditStr.append(dictatedByInitials); auditStr.append("; "); auditStr.append("\r\n*typedBy* :"); if (typedBy != null) { auditStr.append(toShortClassName(typedBy)); auditStr.append(typedBy.getId()); } auditStr.append("; "); auditStr.append("\r\n*typedByInitials* :"); auditStr.append(typedByInitials); auditStr.append("; "); auditStr.append("\r\n*enquiriesTo* :"); if (enquiriesTo != null) { auditStr.append(toShortClassName(enquiriesTo)); auditStr.append(enquiriesTo.getId()); } auditStr.append("; "); auditStr.append("\r\n*wasTypedWithoutCaseNotes* :"); auditStr.append(wasTypedWithoutCaseNotes); auditStr.append("; "); return auditStr.toString(); } public String toXMLString() { return toXMLString(new java.util.HashMap()); } public String toXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); sb.append("<class type=\"" + this.getClass().getName() + "\" "); sb.append(" id=\"" + this.getId() + "\""); sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" "); sb.append(" classVersion=\"" + this.getClassVersion() + "\" "); sb.append(" component=\"" + this.getIsComponentClass() + "\" >"); if (domMap.get(this) == null) { domMap.put(this, this); sb.append(this.fieldsToXMLString(domMap)); } sb.append("</class>"); String keyClassName = "CorrespondenceDetails"; String externalSource = ims.configuration.EnvironmentConfig.getImportExportSourceName(); ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + this.getId()); if (impObj == null) { impObj = new ims.configuration.ImportedObject(); impObj.setExternalId(this.getId()); impObj.setExternalSource(externalSource); impObj.setDomainObject(this); impObj.setLocalId(this.getId()); impObj.setClassName(keyClassName); domMap.put(keyClassName + "_" + externalSource + "_" + this.getId(), impObj); } return sb.toString(); } public String fieldsToXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); if (this.getPasEvent() != null) { sb.append("<pasEvent>"); sb.append(this.getPasEvent().toXMLString(domMap)); sb.append("</pasEvent>"); } if (this.getCurrentStatus() != null) { sb.append("<currentStatus>"); sb.append(this.getCurrentStatus().toXMLString()); sb.append("</currentStatus>"); } if (this.getCspStatusHistory() != null) { if (this.getCspStatusHistory().size() > 0 ) { sb.append("<cspStatusHistory>"); sb.append(ims.domain.DomainObject.toXMLString(this.getCspStatusHistory(), domMap)); sb.append("</cspStatusHistory>"); } } if (this.getCategories() != null) { if (this.getCategories().size() > 0 ) { sb.append("<categories>"); sb.append(ims.domain.DomainObject.toXMLString(this.getCategories(), domMap)); sb.append("</categories>"); } } if (this.getRecipients() != null) { if (this.getRecipients().size() > 0 ) { sb.append("<recipients>"); sb.append(ims.domain.DomainObject.toXMLString(this.getRecipients(), domMap)); sb.append("</recipients>"); } } if (this.getCurrentDocument() != null) { sb.append("<currentDocument>"); sb.append(this.getCurrentDocument().toXMLString(domMap)); sb.append("</currentDocument>"); } if (this.getSignedBy() != null) { sb.append("<signedBy>"); sb.append(this.getSignedBy().toXMLString(domMap)); sb.append("</signedBy>"); } if (this.getSpecialInterest() != null) { sb.append("<specialInterest>"); sb.append(this.getSpecialInterest().toXMLString()); sb.append("</specialInterest>"); } if (this.getDateOfClinic() != null) { sb.append("<dateOfClinic>"); sb.append(new ims.framework.utils.DateTime(this.getDateOfClinic()).toString(ims.framework.utils.DateTimeFormat.MILLI)); sb.append("</dateOfClinic>"); } if (this.getAdmissionDate() != null) { sb.append("<admissionDate>"); sb.append(new ims.framework.utils.DateTime(this.getAdmissionDate()).toString(ims.framework.utils.DateTimeFormat.MILLI)); sb.append("</admissionDate>"); } if (this.getDischargeDate() != null) { sb.append("<dischargeDate>"); sb.append(new ims.framework.utils.DateTime(this.getDischargeDate()).toString(ims.framework.utils.DateTimeFormat.MILLI)); sb.append("</dischargeDate>"); } if (this.getDictatedBy() != null) { sb.append("<dictatedBy>"); sb.append(this.getDictatedBy().toXMLString(domMap)); sb.append("</dictatedBy>"); } if (this.getDictatedByInitials() != null) { sb.append("<dictatedByInitials>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.getDictatedByInitials().toString())); sb.append("</dictatedByInitials>"); } if (this.getTypedBy() != null) { sb.append("<typedBy>"); sb.append(this.getTypedBy().toXMLString(domMap)); sb.append("</typedBy>"); } if (this.getTypedByInitials() != null) { sb.append("<typedByInitials>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.getTypedByInitials().toString())); sb.append("</typedByInitials>"); } if (this.getEnquiriesTo() != null) { sb.append("<enquiriesTo>"); sb.append(this.getEnquiriesTo().toXMLString(domMap)); sb.append("</enquiriesTo>"); } if (this.isWasTypedWithoutCaseNotes() != null) { sb.append("<wasTypedWithoutCaseNotes>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.isWasTypedWithoutCaseNotes().toString())); sb.append("</wasTypedWithoutCaseNotes>"); } return sb.toString(); } public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception { if (list == null) list = new java.util.ArrayList(); fillListFromXMLString(list, el, factory, domMap); return list; } public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception { if (set == null) set = new java.util.HashSet(); fillSetFromXMLString(set, el, factory, domMap); return set; } private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); CorrespondenceDetails domainObject = getCorrespondenceDetailsfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!set.contains(domainObject)) set.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = set.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { set.remove(iter.next()); } } private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); CorrespondenceDetails domainObject = getCorrespondenceDetailsfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } int domIdx = list.indexOf(domainObject); if (domIdx == -1) { list.add(i, domainObject); } else if (i != domIdx && i < list.size()) { Object tmp = list.get(i); list.set(i, list.get(domIdx)); list.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=list.size(); while (i1 > size) { list.remove(i1-1); i1=list.size(); } } public static CorrespondenceDetails getCorrespondenceDetailsfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml)); return getCorrespondenceDetailsfromXML(doc.getRootElement(), factory, domMap); } public static CorrespondenceDetails getCorrespondenceDetailsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return null; String className = el.attributeValue("type"); if (!CorrespondenceDetails.class.getName().equals(className)) { Class clz = Class.forName(className); if (!CorrespondenceDetails.class.isAssignableFrom(clz)) throw new Exception("Element of type = " + className + " cannot be imported using the CorrespondenceDetails class"); String shortClassName = className.substring(className.lastIndexOf(".")+1); String methodName = "get" + shortClassName + "fromXML"; java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class}); return (CorrespondenceDetails)m.invoke(null, new Object[]{el, factory, domMap}); } String impVersion = el.attributeValue("classVersion"); if(!impVersion.equals(CorrespondenceDetails.CLASSVERSION)) { throw new Exception("Incompatible class structure found. Cannot import instance."); } CorrespondenceDetails ret = null; int extId = Integer.parseInt(el.attributeValue("id")); String externalSource = el.attributeValue("source"); ret = (CorrespondenceDetails)factory.getImportedDomainObject(CorrespondenceDetails.class, externalSource, extId); if (ret == null) { ret = new CorrespondenceDetails(); } String keyClassName = "CorrespondenceDetails"; ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + extId); if (impObj != null) { return (CorrespondenceDetails)impObj.getDomainObject(); } else { impObj = new ims.configuration.ImportedObject(); impObj.setExternalId(extId); impObj.setExternalSource(externalSource); impObj.setDomainObject(ret); domMap.put(keyClassName + "_" + externalSource + "_" + extId, impObj); } fillFieldsfromXML(el, factory, ret, domMap); return ret; } public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, CorrespondenceDetails obj, java.util.HashMap domMap) throws Exception { org.dom4j.Element fldEl; fldEl = el.element("pasEvent"); if(fldEl != null) { fldEl = fldEl.element("class"); obj.setPasEvent(ims.core.admin.pas.domain.objects.PASEvent.getPASEventfromXML(fldEl, factory, domMap)); } fldEl = el.element("currentStatus"); if(fldEl != null) { fldEl = fldEl.element("lki"); obj.setCurrentStatus(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory)); } fldEl = el.element("cspStatusHistory"); if(fldEl != null) { fldEl = fldEl.element("set"); obj.setCspStatusHistory(ims.correspondence.domain.objects.CorrespondenceStatusHistory.fromSetXMLString(fldEl, factory, obj.getCspStatusHistory(), domMap)); } fldEl = el.element("categories"); if(fldEl != null) { fldEl = fldEl.element("list"); obj.setCategories(ims.correspondence.domain.objects.CategoryNotes.fromListXMLString(fldEl, factory, obj.getCategories(), domMap)); } fldEl = el.element("recipients"); if(fldEl != null) { fldEl = fldEl.element("list"); obj.setRecipients(ims.correspondence.domain.objects.Recipient.fromListXMLString(fldEl, factory, obj.getRecipients(), domMap)); } fldEl = el.element("currentDocument"); if(fldEl != null) { fldEl = fldEl.element("class"); obj.setCurrentDocument(ims.core.documents.domain.objects.Document.getDocumentfromXML(fldEl, factory, domMap)); } fldEl = el.element("signedBy"); if(fldEl != null) { fldEl = fldEl.element("class"); obj.setSignedBy(ims.core.resource.people.domain.objects.Medic.getMedicfromXML(fldEl, factory, domMap)); } fldEl = el.element("specialInterest"); if(fldEl != null) { fldEl = fldEl.element("lki"); obj.setSpecialInterest(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory)); } fldEl = el.element("dateOfClinic"); if(fldEl != null) { obj.setDateOfClinic(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim())); } fldEl = el.element("admissionDate"); if(fldEl != null) { obj.setAdmissionDate(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim())); } fldEl = el.element("dischargeDate"); if(fldEl != null) { obj.setDischargeDate(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim())); } fldEl = el.element("dictatedBy"); if(fldEl != null) { fldEl = fldEl.element("class"); obj.setDictatedBy(ims.core.resource.people.domain.objects.MemberOfStaff.getMemberOfStafffromXML(fldEl, factory, domMap)); } fldEl = el.element("dictatedByInitials"); if(fldEl != null) { obj.setDictatedByInitials(new String(fldEl.getTextTrim())); } fldEl = el.element("typedBy"); if(fldEl != null) { fldEl = fldEl.element("class"); obj.setTypedBy(ims.core.resource.people.domain.objects.MemberOfStaff.getMemberOfStafffromXML(fldEl, factory, domMap)); } fldEl = el.element("typedByInitials"); if(fldEl != null) { obj.setTypedByInitials(new String(fldEl.getTextTrim())); } fldEl = el.element("enquiriesTo"); if(fldEl != null) { fldEl = fldEl.element("class"); obj.setEnquiriesTo(ims.core.resource.people.domain.objects.MemberOfStaff.getMemberOfStafffromXML(fldEl, factory, domMap)); } fldEl = el.element("wasTypedWithoutCaseNotes"); if(fldEl != null) { obj.setWasTypedWithoutCaseNotes(new Boolean(fldEl.getTextTrim())); } } public static String[] getCollectionFields() { return new String[]{ "cspStatusHistory" , "categories" , "recipients" }; } public static class FieldNames { public static final String ID = "id"; public static final String PasEvent = "pasEvent"; public static final String CurrentStatus = "currentStatus"; public static final String CspStatusHistory = "cspStatusHistory"; public static final String Categories = "categories"; public static final String Recipients = "recipients"; public static final String CurrentDocument = "currentDocument"; public static final String SignedBy = "signedBy"; public static final String SpecialInterest = "specialInterest"; public static final String DateOfClinic = "dateOfClinic"; public static final String AdmissionDate = "admissionDate"; public static final String DischargeDate = "dischargeDate"; public static final String DictatedBy = "dictatedBy"; public static final String DictatedByInitials = "dictatedByInitials"; public static final String TypedBy = "typedBy"; public static final String TypedByInitials = "typedByInitials"; public static final String EnquiriesTo = "enquiriesTo"; public static final String WasTypedWithoutCaseNotes = "wasTypedWithoutCaseNotes"; } }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/DomainObjects/src/ims/correspondence/domain/objects/CorrespondenceDetails.java
Java
agpl-3.0
29,975
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.ocs_if.vo.beans; public class IfOrdSpecLiteVoBean extends ims.vo.ValueObjectBean { public IfOrdSpecLiteVoBean() { } public IfOrdSpecLiteVoBean(ims.ocs_if.vo.IfOrdSpecLiteVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.colldatetimeplacer = vo.getCollDateTimePlacer() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getCollDateTimePlacer().getBean(); this.colldatetimefiller = vo.getCollDateTimeFiller() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getCollDateTimeFiller().getBean(); this.coltimefillersupplied = vo.getColTimeFillerSupplied(); this.collenddatetimeplacer = vo.getCollEndDateTimePlacer() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getCollEndDateTimePlacer().getBean(); this.collenddatetimefiller = vo.getCollEndDateTimeFiller() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getCollEndDateTimeFiller().getBean(); this.sitetext = vo.getSiteText(); this.specimensource = vo.getSpecimenSource() == null ? null : (ims.vo.LookupInstanceBean)vo.getSpecimenSource().getBean(); this.discipline = vo.getDiscipline() == null ? null : (ims.core.vo.beans.ServiceLiteVoBean)vo.getDiscipline().getBean(); this.collectingmos = vo.getCollectingMos() == null ? null : (ims.core.vo.beans.MemberOfStaffLiteVoBean)vo.getCollectingMos().getBean(); this.ispatientcollect = vo.getIsPatientCollect(); this.isawaitingcollection = vo.getIsAwaitingCollection(); this.receiveddatetime = vo.getReceivedDateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getReceivedDateTime().getBean(); this.receivedtimesupplied = vo.getReceivedTimeSupplied(); this.fillerordnum = vo.getFillerOrdNum(); this.collectorcomment = vo.getCollectorComment(); this.sitecd = vo.getSiteCd() == null ? null : (ims.vo.LookupInstanceBean)vo.getSiteCd().getBean(); this.wasprocessed = vo.getWasProcessed(); this.placerordnum = vo.getPlacerOrdNum(); this.dftspecimenresulted = vo.getDftSpecimenResulted() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getDftSpecimenResulted().getBean(); this.dftspecimenresultedtimesupplied = vo.getDftSpecimenResultedTimeSupplied(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.ocs_if.vo.IfOrdSpecLiteVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.colldatetimeplacer = vo.getCollDateTimePlacer() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getCollDateTimePlacer().getBean(); this.colldatetimefiller = vo.getCollDateTimeFiller() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getCollDateTimeFiller().getBean(); this.coltimefillersupplied = vo.getColTimeFillerSupplied(); this.collenddatetimeplacer = vo.getCollEndDateTimePlacer() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getCollEndDateTimePlacer().getBean(); this.collenddatetimefiller = vo.getCollEndDateTimeFiller() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getCollEndDateTimeFiller().getBean(); this.sitetext = vo.getSiteText(); this.specimensource = vo.getSpecimenSource() == null ? null : (ims.vo.LookupInstanceBean)vo.getSpecimenSource().getBean(); this.discipline = vo.getDiscipline() == null ? null : (ims.core.vo.beans.ServiceLiteVoBean)vo.getDiscipline().getBean(map); this.collectingmos = vo.getCollectingMos() == null ? null : (ims.core.vo.beans.MemberOfStaffLiteVoBean)vo.getCollectingMos().getBean(map); this.ispatientcollect = vo.getIsPatientCollect(); this.isawaitingcollection = vo.getIsAwaitingCollection(); this.receiveddatetime = vo.getReceivedDateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getReceivedDateTime().getBean(); this.receivedtimesupplied = vo.getReceivedTimeSupplied(); this.fillerordnum = vo.getFillerOrdNum(); this.collectorcomment = vo.getCollectorComment(); this.sitecd = vo.getSiteCd() == null ? null : (ims.vo.LookupInstanceBean)vo.getSiteCd().getBean(); this.wasprocessed = vo.getWasProcessed(); this.placerordnum = vo.getPlacerOrdNum(); this.dftspecimenresulted = vo.getDftSpecimenResulted() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getDftSpecimenResulted().getBean(); this.dftspecimenresultedtimesupplied = vo.getDftSpecimenResultedTimeSupplied(); } public ims.ocs_if.vo.IfOrdSpecLiteVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.ocs_if.vo.IfOrdSpecLiteVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.ocs_if.vo.IfOrdSpecLiteVo vo = null; if(map != null) vo = (ims.ocs_if.vo.IfOrdSpecLiteVo)map.getValueObject(this); if(vo == null) { vo = new ims.ocs_if.vo.IfOrdSpecLiteVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.framework.utils.beans.DateTimeBean getCollDateTimePlacer() { return this.colldatetimeplacer; } public void setCollDateTimePlacer(ims.framework.utils.beans.DateTimeBean value) { this.colldatetimeplacer = value; } public ims.framework.utils.beans.DateTimeBean getCollDateTimeFiller() { return this.colldatetimefiller; } public void setCollDateTimeFiller(ims.framework.utils.beans.DateTimeBean value) { this.colldatetimefiller = value; } public Boolean getColTimeFillerSupplied() { return this.coltimefillersupplied; } public void setColTimeFillerSupplied(Boolean value) { this.coltimefillersupplied = value; } public ims.framework.utils.beans.DateTimeBean getCollEndDateTimePlacer() { return this.collenddatetimeplacer; } public void setCollEndDateTimePlacer(ims.framework.utils.beans.DateTimeBean value) { this.collenddatetimeplacer = value; } public ims.framework.utils.beans.DateTimeBean getCollEndDateTimeFiller() { return this.collenddatetimefiller; } public void setCollEndDateTimeFiller(ims.framework.utils.beans.DateTimeBean value) { this.collenddatetimefiller = value; } public String getSiteText() { return this.sitetext; } public void setSiteText(String value) { this.sitetext = value; } public ims.vo.LookupInstanceBean getSpecimenSource() { return this.specimensource; } public void setSpecimenSource(ims.vo.LookupInstanceBean value) { this.specimensource = value; } public ims.core.vo.beans.ServiceLiteVoBean getDiscipline() { return this.discipline; } public void setDiscipline(ims.core.vo.beans.ServiceLiteVoBean value) { this.discipline = value; } public ims.core.vo.beans.MemberOfStaffLiteVoBean getCollectingMos() { return this.collectingmos; } public void setCollectingMos(ims.core.vo.beans.MemberOfStaffLiteVoBean value) { this.collectingmos = value; } public Boolean getIsPatientCollect() { return this.ispatientcollect; } public void setIsPatientCollect(Boolean value) { this.ispatientcollect = value; } public Boolean getIsAwaitingCollection() { return this.isawaitingcollection; } public void setIsAwaitingCollection(Boolean value) { this.isawaitingcollection = value; } public ims.framework.utils.beans.DateTimeBean getReceivedDateTime() { return this.receiveddatetime; } public void setReceivedDateTime(ims.framework.utils.beans.DateTimeBean value) { this.receiveddatetime = value; } public Boolean getReceivedTimeSupplied() { return this.receivedtimesupplied; } public void setReceivedTimeSupplied(Boolean value) { this.receivedtimesupplied = value; } public String getFillerOrdNum() { return this.fillerordnum; } public void setFillerOrdNum(String value) { this.fillerordnum = value; } public String getCollectorComment() { return this.collectorcomment; } public void setCollectorComment(String value) { this.collectorcomment = value; } public ims.vo.LookupInstanceBean getSiteCd() { return this.sitecd; } public void setSiteCd(ims.vo.LookupInstanceBean value) { this.sitecd = value; } public Boolean getWasProcessed() { return this.wasprocessed; } public void setWasProcessed(Boolean value) { this.wasprocessed = value; } public String getPlacerOrdNum() { return this.placerordnum; } public void setPlacerOrdNum(String value) { this.placerordnum = value; } public ims.framework.utils.beans.DateTimeBean getDftSpecimenResulted() { return this.dftspecimenresulted; } public void setDftSpecimenResulted(ims.framework.utils.beans.DateTimeBean value) { this.dftspecimenresulted = value; } public Boolean getDftSpecimenResultedTimeSupplied() { return this.dftspecimenresultedtimesupplied; } public void setDftSpecimenResultedTimeSupplied(Boolean value) { this.dftspecimenresultedtimesupplied = value; } private Integer id; private int version; private ims.framework.utils.beans.DateTimeBean colldatetimeplacer; private ims.framework.utils.beans.DateTimeBean colldatetimefiller; private Boolean coltimefillersupplied; private ims.framework.utils.beans.DateTimeBean collenddatetimeplacer; private ims.framework.utils.beans.DateTimeBean collenddatetimefiller; private String sitetext; private ims.vo.LookupInstanceBean specimensource; private ims.core.vo.beans.ServiceLiteVoBean discipline; private ims.core.vo.beans.MemberOfStaffLiteVoBean collectingmos; private Boolean ispatientcollect; private Boolean isawaitingcollection; private ims.framework.utils.beans.DateTimeBean receiveddatetime; private Boolean receivedtimesupplied; private String fillerordnum; private String collectorcomment; private ims.vo.LookupInstanceBean sitecd; private Boolean wasprocessed; private String placerordnum; private ims.framework.utils.beans.DateTimeBean dftspecimenresulted; private Boolean dftspecimenresultedtimesupplied; }
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/ocs_if/vo/beans/IfOrdSpecLiteVoBean.java
Java
agpl-3.0
12,235
<?php /* * This work is hereby released into the Public Domain. * To view a copy of the public domain dedication, * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. * */ /** * Handle ticks * * @package Artichow */ class awTick { /** * Ticks style * * @var int */ protected $style = awTick::IN; /** * Ticks size * * @var int */ protected $size; /** * Ticks color * * @var Color */ protected $color; /** * Ticks number * * @var int */ protected $number; /** * Ticks number by other tick * * @var array */ protected $numberByTick; /** * Ticks interval * * @var int */ protected $interval = 1; /** * Hide ticks * * @var bool */ protected $hide = FALSE; /** * Hide first tick * * @var bool */ protected $hideFirst = FALSE; /** * Hide last tick * * @var bool */ protected $hideLast = FALSE; /** * In mode * * @param int */ const IN = 0; /** * Out mode * * @param int */ const OUT = 1; /** * In and out mode * * @param int */ const IN_OUT = 2; /** * Build the ticks * * @param int $number Number of ticks * @param int $size Ticks size */ public function __construct($number, $size) { $this->setSize($size); $this->setNumber($number); $this->setColor(new awBlack); $this->style = awTick::IN; } /** * Change ticks style * * @param int $style */ public function setStyle($style) { $this->style = (int)$style; } /** * Get ticks style * * @return int */ public function getStyle() { return $this->style; } /** * Change ticks color * * @param awColor $color */ public function setColor(awColor $color) { $this->color = $color; } /** * Change ticks size * * @param int $size */ public function setSize($size) { $this->size = (int)$size; } /** * Change interval of ticks * * @param int $interval */ public function setInterval($interval) { $this->interval = (int)$interval; } /** * Get interval between each tick * * @return int */ public function getInterval() { return $this->interval; } /** * Change number of ticks * * @param int $number */ public function setNumber($number) { $this->number = (int)$number; } /** * Get number of ticks * * @return int */ public function getNumber() { return $this->number; } /** * Change number of ticks relative to others ticks * * @param awTick $tick Ticks reference * @param int $number Number of ticks */ public function setNumberByTick(awTick $tick, $number) { $this->numberByTick = array($tick, (int)$number); } /** * Hide ticks * * @param bool $hide */ public function hide($hide) { $this->hide = (bool)$hide; } /** * Hide first tick * * @param bool $hide */ public function hideFirst($hide) { $this->hideFirst = (bool)$hide; } /** * Hide last tick * * @param bool $hide */ public function hideLast($hide) { $this->hideLast = (bool)$hide; } /** * Draw ticks on a vector * * @param awDriver $driver A driver * @param awVector $vector A vector */ public function draw(awDriver $driver, awVector $vector) { if($this->numberByTick !== NULL) { list($tick, $number) = $this->numberByTick; $this->number = 1 + ($tick->getNumber() - 1) * ($number + 1); $this->interval = $tick->getInterval(); } if($this->number < 2 or $this->hide) { return; } $angle = $vector->getAngle(); // echo "INIT:".$angle."<br>"; switch($this->style) { case awTick::IN : $this->drawTicks($driver, $vector, NULL, $angle + M_PI / 2); break; case awTick::OUT : $this->drawTicks($driver, $vector, $angle + 3 * M_PI / 2, NULL); break; default : $this->drawTicks($driver, $vector, $angle + M_PI / 2, $angle + 3 * M_PI / 2); break; } } protected function drawTicks(awDriver $driver, awVector $vector, $from, $to) { // Draw last tick if($this->hideLast === FALSE) { //echo '<b>'; if(($this->number - 1) % $this->interval === 0) { $this->drawTick($driver, $vector->p2, $from, $to); } //echo '</b>'; } $number = $this->number - 1; $size = $vector->getSize(); // Get tick increment in pixels $inc = $size / $number; // Check if we must hide the first tick $start = $this->hideFirst ? $inc : 0; $stop = $inc * $number; $position = 0; for($i = $start; round($i, 6) < $stop; $i += $inc) { if($position % $this->interval === 0) { $p = $vector->p1->move( round($i * cos($vector->getAngle()), 6), round($i * sin($vector->getAngle() * -1), 6) ); $this->drawTick($driver, $p, $from, $to); } $position++; } //echo '<br><br>'; } protected function drawTick(awDriver $driver, awPoint $p, $from, $to) { // echo $this->size.':'.$angle.'|<b>'.cos($angle).'</b>/'; // The round avoid some errors in the calcul // For example, 12.00000008575245 becomes 12 $p1 = $p; $p2 = $p; if($from !== NULL) { $p1 = $p1->move( round($this->size * cos($from), 6), round($this->size * sin($from) * -1, 6) ); } if($to !== NULL) { $p2 = $p2->move( round($this->size * cos($to), 6), round($this->size * sin($to) * -1, 6) ); } //echo $p1->x.':'.$p2->x.'('.$p1->y.':'.$p2->y.')'.'/'; $vector = new awVector( $p1, $p2 ); $driver->line( $this->color, $vector ); } }
zcorrecteurs/zcorrecteurs.fr
lib/Artichow/inc/Tick.class.php
PHP
agpl-3.0
5,573
/* Copyright (C) 1999 Claude SIMON (http://q37.info/contact/). This file is part of the Epeios framework. The Epeios framework is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The Epeios framework 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with the Epeios framework. If not, see <http://www.gnu.org/licenses/> */ #define SCK_COMPILATION_ #include "sck.h" #ifdef CPE_S_POSIX # define SCK__IGNORE_SIGPIPE #endif #ifdef SCK__IGNORE_SIGPIPE # include <signal.h> #endif using namespace sck; #ifdef CPE_S_WIN bool sck::Ready_ = false; // 'ssize_t' does not exist in Windows. // It is used as return type for 'select' and 'recv' // under POSIX, so we use the type returned by same // functions under windows. typedef int ssize_t; #else bool sck::Ready_ = true; #endif flw::size__ sck::Read( socket__ Socket, flw::size__ Amount, void *Buffer, duration__ Timeout ) { fd_set fds; ssize_t Result; FD_ZERO( &fds ); FD_SET( Socket, &fds ); if ( Timeout == SCK_INFINITE ) Result = select( (int)( Socket + 1 ), &fds, NULL, NULL, NULL ); else { timeval TV; TV.tv_sec = Timeout; TV.tv_usec = 0; Result = select( (int)( Socket + 1 ), &fds, NULL, NULL, &TV ); } if ( Result == 1 ) { Result = recv( Socket, (cast__)Buffer, (int)Amount, 0 ); if ( Result == SCK_SOCKET_ERROR ) { Result = SCK_DISCONNECTED; if ( Error() != SCK_ECONNRESET ) qRLbr(); } else if ( !Result && Amount ) Result = SCK_DISCONNECTED; } else if ( Result == SCK_SOCKET_ERROR ) qRLbr(); else if ( Result == 0 ) qRLbr(); else qRSys(); return Result; } flw::size__ sck::Write( socket__ Socket, const void *Buffer, flw::size__ Amount, duration__ Timeout ) { fd_set fds; int Result; FD_ZERO( &fds ); FD_SET( Socket, &fds ); if ( Timeout == SCK_INFINITE ) Result = select( (int)( Socket + 1 ), NULL, &fds, NULL, NULL ); else { timeval TV; TV.tv_sec = Timeout; TV.tv_usec = 0; Result = select( (int)( Socket + 1 ), NULL, &fds, NULL, &TV ); } if ( Result == 1 ) { Result = send( Socket, (const cast__)Buffer, (int)Amount, 0 ); if ( Result == SCK_SOCKET_ERROR ) { Result = SCK_DISCONNECTED; if ( Error() != SCK_ECONNRESET ) qRLbr(); } else if ( !Result && Amount ) // I assume that, because the send is call immediatly after the select, this can not be happen. qRFwk(); } else if ( Result == SCK_SOCKET_ERROR ) qRLbr(); else if ( Result == 0 ) qRLbr(); else qRSys(); return Result; } #ifdef SCK__WIN # define SHUT_RDWR 2 // Workaround, 'SD_BOTH' being not available because inclusion of 'winsock2.h' fails. #elif defined( SCK__POSIX ) # define ioctlsocket ioctl # define closesocket close #else # error #endif bso::sBool sck::Shutdown( socket__ Socket, qRPN ) { if ( shutdown( Socket, SHUT_RDWR ) != 0 ) { if ( qRPT ) qRLbr(); return false; } else return true; } // Some errors are ignored. bso::sBool sck::Close( socket__ Socket, qRPN ) // To set to 'qRPU' when called from destructors ! { u_long Mode = 1; // Non-blocking. bso::sBool Error = ioctlsocket( Socket, FIONBIO, &Mode ) != 0; Error |= !Shutdown(Socket, qRPU); if ( (closesocket( Socket ) != 0) || Error ) { if ( qRPT ) qRLbr(); return false; } return true; } Q37_GCTOR( sck ) { #ifdef SCK__IGNORE_SIGPIPE signal( SIGPIPE, SIG_IGN ); #endif }
epeios-q37/epeios
stable/sck.cpp
C++
agpl-3.0
3,783
module ActiveScaffold::Actions module Subform def edit_associated @parent_record = params[:id].nil? ? active_scaffold_config.model.new : find_if_allowed(params[:id], :update) @column = active_scaffold_config.columns[params[:association]] # NOTE: we don't check whether the user is allowed to update this record, because if not, we'll still let them associate the record. we'll just refuse to do more than associate, is all. @record = @column.association.klass.find(params[:associated_id]) if params[:associated_id] @record ||= @column.association.klass.new @scope = "[#{@column.name}]" @scope += (@record.new_record?) ? "[#{(Time.now.to_f*1000).to_i.to_s}]" : "[#{@record.id}]" if @column.plural_association? render :action => 'edit_associated.rjs', :layout => false end end end
andrewroth/project_application_tool
vendor/plugins/active_scaffold/lib/active_scaffold/actions/subform.rb
Ruby
agpl-3.0
842
cur_frm.add_fetch('sample_no', 'barcode', 'bottle_no'); cur_frm.fields_dict.sample_no.get_query = function(doc, cdt, cdn) { return{ query:"test.doctype.register.register.get_samples" } } // cur_frm.cscript.others = function(doc,cdt,cdn){ // if(doc.sample_no){ // //console.log("in employee trigger") // get_server_fields('get_test_details','','',doc,cdt,cdn,1,function(r,rt){refresh_field('test_details')}); // } // else // msgprint("Sample No Can Not Be Blank...") // }
saurabh6790/trufil_app
test/doctype/register/register.js
JavaScript
agpl-3.0
494
#include <windows.h> #include <stdio.h> int main(int argc, const char ** argv) { int nsecs; if (argc != 2) { fputs("usage: bsleep <n>\n n = number of seconds\n", stderr); exit(1); } if (sscanf(argv[1], "%d", &nsecs) != 1) { fputs("sleep: incorrect argument, must be number of seconds to sleep\n", stderr); exit(1); } Sleep(nsecs * 1000); exit(0); }
gagoel/bacula
src/win32/scripts/bsleep.c
C
agpl-3.0
409
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated: 12/10/2015, 13:28 * */ package ims.choose_book.domain.objects; /** * * @author Barbara Worwood * Generated. */ public class ActionRequest extends ims.domain.DomainObject implements java.io.Serializable { public static final int CLASSID = 1069100000; private static final long serialVersionUID = 1069100000L; public static final String CLASSVERSION = "${ClassVersion}"; @Override public boolean shouldCapQuery() { return true; } /** Request Type */ private ims.domain.lookups.LookupInstance requestType; /** Date the request was made */ private java.util.Date requestDate; /** ConversationID */ private String convId; private String cpaId; /** Contains the Message Details to Action agains */ private String msgDetails; /** Is this an active action request */ private Boolean active; /** Various comment - reason status is set to false etc.. */ private String statComment; /** Comment with details of progress ie. error or processed successfully */ private String progressComment; public ActionRequest (Integer id, int ver) { super(id, ver); } public ActionRequest () { super(); } public ActionRequest (Integer id, int ver, Boolean includeRecord) { super(id, ver, includeRecord); } public Class getRealDomainClass() { return ims.choose_book.domain.objects.ActionRequest.class; } public ims.domain.lookups.LookupInstance getRequestType() { return requestType; } public void setRequestType(ims.domain.lookups.LookupInstance requestType) { this.requestType = requestType; } public java.util.Date getRequestDate() { return requestDate; } public void setRequestDate(java.util.Date requestDate) { this.requestDate = requestDate; } public String getConvId() { return convId; } public void setConvId(String convId) { if ( null != convId && convId.length() > 100 ) { throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for convId. Tried to set value: "+ convId); } this.convId = convId; } public String getCpaId() { return cpaId; } public void setCpaId(String cpaId) { if ( null != cpaId && cpaId.length() > 100 ) { throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for cpaId. Tried to set value: "+ cpaId); } this.cpaId = cpaId; } public String getMsgDetails() { return msgDetails; } public void setMsgDetails(String msgDetails) { if ( null != msgDetails && msgDetails.length() > 2000 ) { throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for msgDetails. Tried to set value: "+ msgDetails); } this.msgDetails = msgDetails; } public Boolean isActive() { return active; } public void setActive(Boolean active) { this.active = active; } public String getStatComment() { return statComment; } public void setStatComment(String statComment) { if ( null != statComment && statComment.length() > 255 ) { throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for statComment. Tried to set value: "+ statComment); } this.statComment = statComment; } public String getProgressComment() { return progressComment; } public void setProgressComment(String progressComment) { if ( null != progressComment && progressComment.length() > 255 ) { throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for progressComment. Tried to set value: "+ progressComment); } this.progressComment = progressComment; } /** * isConfigurationObject * Taken from the Usage property of the business object, this method will return * a boolean indicating whether this is a configuration object or not * Configuration = true, Instantiation = false */ public static boolean isConfigurationObject() { if ( "Instantiation".equals("Configuration") ) return true; else return false; } public int getClassId() { return CLASSID; } public String getClassVersion() { return CLASSVERSION; } public String toAuditString() { StringBuffer auditStr = new StringBuffer(); auditStr.append("\r\n*requestType* :"); if (requestType != null) auditStr.append(requestType.getText()); auditStr.append("; "); auditStr.append("\r\n*requestDate* :"); auditStr.append(requestDate); auditStr.append("; "); auditStr.append("\r\n*convId* :"); auditStr.append(convId); auditStr.append("; "); auditStr.append("\r\n*cpaId* :"); auditStr.append(cpaId); auditStr.append("; "); auditStr.append("\r\n*msgDetails* :"); auditStr.append(msgDetails); auditStr.append("; "); auditStr.append("\r\n*active* :"); auditStr.append(active); auditStr.append("; "); auditStr.append("\r\n*statComment* :"); auditStr.append(statComment); auditStr.append("; "); auditStr.append("\r\n*progressComment* :"); auditStr.append(progressComment); auditStr.append("; "); return auditStr.toString(); } public String toXMLString() { return toXMLString(new java.util.HashMap()); } public String toXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); sb.append("<class type=\"" + this.getClass().getName() + "\" "); sb.append(" id=\"" + this.getId() + "\""); sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" "); sb.append(" classVersion=\"" + this.getClassVersion() + "\" "); sb.append(" component=\"" + this.getIsComponentClass() + "\" >"); if (domMap.get(this) == null) { domMap.put(this, this); sb.append(this.fieldsToXMLString(domMap)); } sb.append("</class>"); String keyClassName = "ActionRequest"; String externalSource = ims.configuration.EnvironmentConfig.getImportExportSourceName(); ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + this.getId()); if (impObj == null) { impObj = new ims.configuration.ImportedObject(); impObj.setExternalId(this.getId()); impObj.setExternalSource(externalSource); impObj.setDomainObject(this); impObj.setLocalId(this.getId()); impObj.setClassName(keyClassName); domMap.put(keyClassName + "_" + externalSource + "_" + this.getId(), impObj); } return sb.toString(); } public String fieldsToXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); if (this.getRequestType() != null) { sb.append("<requestType>"); sb.append(this.getRequestType().toXMLString()); sb.append("</requestType>"); } if (this.getRequestDate() != null) { sb.append("<requestDate>"); sb.append(new ims.framework.utils.DateTime(this.getRequestDate()).toString(ims.framework.utils.DateTimeFormat.MILLI)); sb.append("</requestDate>"); } if (this.getConvId() != null) { sb.append("<convId>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.getConvId().toString())); sb.append("</convId>"); } if (this.getCpaId() != null) { sb.append("<cpaId>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.getCpaId().toString())); sb.append("</cpaId>"); } if (this.getMsgDetails() != null) { sb.append("<msgDetails>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.getMsgDetails().toString())); sb.append("</msgDetails>"); } if (this.isActive() != null) { sb.append("<active>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.isActive().toString())); sb.append("</active>"); } if (this.getStatComment() != null) { sb.append("<statComment>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.getStatComment().toString())); sb.append("</statComment>"); } if (this.getProgressComment() != null) { sb.append("<progressComment>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.getProgressComment().toString())); sb.append("</progressComment>"); } return sb.toString(); } public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception { if (list == null) list = new java.util.ArrayList(); fillListFromXMLString(list, el, factory, domMap); return list; } public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception { if (set == null) set = new java.util.HashSet(); fillSetFromXMLString(set, el, factory, domMap); return set; } private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); ActionRequest domainObject = getActionRequestfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!set.contains(domainObject)) set.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = set.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { set.remove(iter.next()); } } private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); ActionRequest domainObject = getActionRequestfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } int domIdx = list.indexOf(domainObject); if (domIdx == -1) { list.add(i, domainObject); } else if (i != domIdx && i < list.size()) { Object tmp = list.get(i); list.set(i, list.get(domIdx)); list.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=list.size(); while (i1 > size) { list.remove(i1-1); i1=list.size(); } } public static ActionRequest getActionRequestfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml)); return getActionRequestfromXML(doc.getRootElement(), factory, domMap); } public static ActionRequest getActionRequestfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return null; String className = el.attributeValue("type"); if (!ActionRequest.class.getName().equals(className)) { Class clz = Class.forName(className); if (!ActionRequest.class.isAssignableFrom(clz)) throw new Exception("Element of type = " + className + " cannot be imported using the ActionRequest class"); String shortClassName = className.substring(className.lastIndexOf(".")+1); String methodName = "get" + shortClassName + "fromXML"; java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class}); return (ActionRequest)m.invoke(null, new Object[]{el, factory, domMap}); } String impVersion = el.attributeValue("classVersion"); if(!impVersion.equals(ActionRequest.CLASSVERSION)) { throw new Exception("Incompatible class structure found. Cannot import instance."); } ActionRequest ret = null; int extId = Integer.parseInt(el.attributeValue("id")); String externalSource = el.attributeValue("source"); ret = (ActionRequest)factory.getImportedDomainObject(ActionRequest.class, externalSource, extId); if (ret == null) { ret = new ActionRequest(); } String keyClassName = "ActionRequest"; ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + extId); if (impObj != null) { return (ActionRequest)impObj.getDomainObject(); } else { impObj = new ims.configuration.ImportedObject(); impObj.setExternalId(extId); impObj.setExternalSource(externalSource); impObj.setDomainObject(ret); domMap.put(keyClassName + "_" + externalSource + "_" + extId, impObj); } fillFieldsfromXML(el, factory, ret, domMap); return ret; } public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, ActionRequest obj, java.util.HashMap domMap) throws Exception { org.dom4j.Element fldEl; fldEl = el.element("requestType"); if(fldEl != null) { fldEl = fldEl.element("lki"); obj.setRequestType(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory)); } fldEl = el.element("requestDate"); if(fldEl != null) { obj.setRequestDate(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim())); } fldEl = el.element("convId"); if(fldEl != null) { obj.setConvId(new String(fldEl.getTextTrim())); } fldEl = el.element("cpaId"); if(fldEl != null) { obj.setCpaId(new String(fldEl.getTextTrim())); } fldEl = el.element("msgDetails"); if(fldEl != null) { obj.setMsgDetails(new String(fldEl.getTextTrim())); } fldEl = el.element("active"); if(fldEl != null) { obj.setActive(new Boolean(fldEl.getTextTrim())); } fldEl = el.element("statComment"); if(fldEl != null) { obj.setStatComment(new String(fldEl.getTextTrim())); } fldEl = el.element("progressComment"); if(fldEl != null) { obj.setProgressComment(new String(fldEl.getTextTrim())); } } public static String[] getCollectionFields() { return new String[]{ }; } public static class FieldNames { public static final String ID = "id"; public static final String RequestType = "requestType"; public static final String RequestDate = "requestDate"; public static final String ConvId = "convId"; public static final String CpaId = "cpaId"; public static final String MsgDetails = "msgDetails"; public static final String Active = "active"; public static final String StatComment = "statComment"; public static final String ProgressComment = "progressComment"; } }
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/DomainObjects/src/ims/choose_book/domain/objects/ActionRequest.java
Java
agpl-3.0
17,726
Logging guidelines ------- **Description:** The logging should contain some guidelines in order to organise your logging file in such a way it becomes clear and easy to find information **Solution:** The logging file should at least contain, a timestamp from a reliable source, severity level of the event, an indication that this is a security relevant event (if mixed with other logs), the identity of the user that caused the event (if there is a user associated with the event), the source IP address of the request associated with the event, whether the event succeeded or failed, and a description of the event. Also verify that log fields from trusted and untrusted sources are distinguishable in log entries.
Jessevanbekkum/skf-flask
skf/markdown/knowledge_base/99-knowledge_base--Logging_guidelines--.md
Markdown
agpl-3.0
733
#include <NTL/ZZ_pEXFactoring.h> #include <NTL/FacVec.h> #include <NTL/fileio.h> #include <NTL/new.h> NTL_START_IMPL static void IterPower(ZZ_pE& c, const ZZ_pE& a, long n) { ZZ_pE res; long i; res = a; for (i = 0; i < n; i++) power(res, res, ZZ_p::modulus()); c = res; } void SquareFreeDecomp(vec_pair_ZZ_pEX_long& u, const ZZ_pEX& ff) { ZZ_pEX f = ff; if (!IsOne(LeadCoeff(f))) LogicError("SquareFreeDecomp: bad args"); ZZ_pEX r, t, v, tmp1; long m, j, finished, done; u.SetLength(0); if (deg(f) == 0) return; m = 1; finished = 0; do { j = 1; diff(tmp1, f); GCD(r, f, tmp1); div(t, f, r); if (deg(t) > 0) { done = 0; do { GCD(v, r, t); div(tmp1, t, v); if (deg(tmp1) > 0) append(u, cons(tmp1, j*m)); if (deg(v) > 0) { div(r, r, v); t = v; j++; } else done = 1; } while (!done); if (deg(r) == 0) finished = 1; } if (!finished) { /* r is a p-th power */ long k, d; long p = to_long(ZZ_p::modulus()); d = deg(r)/p; f.rep.SetLength(d+1); for (k = 0; k <= d; k++) IterPower(f.rep[k], r.rep[k*p], ZZ_pE::degree()-1); m = m*p; } } while (!finished); } static void AbsTraceMap(ZZ_pEX& h, const ZZ_pEX& a, const ZZ_pEXModulus& F) { ZZ_pEX res, tmp; long k = NumBits(ZZ_pE::cardinality())-1; res = a; tmp = a; long i; for (i = 0; i < k-1; i++) { SqrMod(tmp, tmp, F); add(res, res, tmp); } h = res; } void FrobeniusMap(ZZ_pEX& h, const ZZ_pEXModulus& F) { PowerXMod(h, ZZ_pE::cardinality(), F); } static void RecFindRoots(vec_ZZ_pE& x, const ZZ_pEX& f) { if (deg(f) == 0) return; if (deg(f) == 1) { long k = x.length(); x.SetLength(k+1); negate(x[k], ConstTerm(f)); return; } ZZ_pEX h; ZZ_pEX r; { ZZ_pEXModulus F; build(F, f); do { random(r, deg(F)); if (IsOdd(ZZ_pE::cardinality())) { PowerMod(h, r, RightShift(ZZ_pE::cardinality(), 1), F); sub(h, h, 1); } else { AbsTraceMap(h, r, F); } GCD(h, h, f); } while (deg(h) <= 0 || deg(h) == deg(f)); } RecFindRoots(x, h); div(h, f, h); RecFindRoots(x, h); } void FindRoots(vec_ZZ_pE& x, const ZZ_pEX& ff) { ZZ_pEX f = ff; if (!IsOne(LeadCoeff(f))) LogicError("FindRoots: bad args"); x.SetMaxLength(deg(f)); x.SetLength(0); RecFindRoots(x, f); } void split(ZZ_pEX& f1, ZZ_pEX& g1, ZZ_pEX& f2, ZZ_pEX& g2, const ZZ_pEX& f, const ZZ_pEX& g, const vec_ZZ_pE& roots, long lo, long mid) { long r = mid-lo+1; ZZ_pEXModulus F; build(F, f); vec_ZZ_pE lroots(INIT_SIZE, r); long i; for (i = 0; i < r; i++) lroots[i] = roots[lo+i]; ZZ_pEX h, a, d; BuildFromRoots(h, lroots); CompMod(a, h, g, F); GCD(f1, a, f); div(f2, f, f1); rem(g1, g, f1); rem(g2, g, f2); } void RecFindFactors(vec_ZZ_pEX& factors, const ZZ_pEX& f, const ZZ_pEX& g, const vec_ZZ_pE& roots, long lo, long hi) { long r = hi-lo+1; if (r == 0) return; if (r == 1) { append(factors, f); return; } ZZ_pEX f1, g1, f2, g2; long mid = (lo+hi)/2; split(f1, g1, f2, g2, f, g, roots, lo, mid); RecFindFactors(factors, f1, g1, roots, lo, mid); RecFindFactors(factors, f2, g2, roots, mid+1, hi); } void FindFactors(vec_ZZ_pEX& factors, const ZZ_pEX& f, const ZZ_pEX& g, const vec_ZZ_pE& roots) { long r = roots.length(); factors.SetMaxLength(r); factors.SetLength(0); RecFindFactors(factors, f, g, roots, 0, r-1); } void IterFindFactors(vec_ZZ_pEX& factors, const ZZ_pEX& f, const ZZ_pEX& g, const vec_ZZ_pE& roots) { long r = roots.length(); long i; ZZ_pEX h; factors.SetLength(r); for (i = 0; i < r; i++) { sub(h, g, roots[i]); GCD(factors[i], f, h); } } void TraceMap(ZZ_pEX& w, const ZZ_pEX& a, long d, const ZZ_pEXModulus& F, const ZZ_pEX& b) { if (d < 0) LogicError("TraceMap: bad args"); ZZ_pEX y, z, t; z = b; y = a; clear(w); while (d) { if (d == 1) { if (IsZero(w)) w = y; else { CompMod(w, w, z, F); add(w, w, y); } } else if ((d & 1) == 0) { Comp2Mod(z, t, z, y, z, F); add(y, t, y); } else if (IsZero(w)) { w = y; Comp2Mod(z, t, z, y, z, F); add(y, t, y); } else { Comp3Mod(z, t, w, z, y, w, z, F); add(w, w, y); add(y, t, y); } d = d >> 1; } } void PowerCompose(ZZ_pEX& y, const ZZ_pEX& h, long q, const ZZ_pEXModulus& F) { if (q < 0) LogicError("PowerCompose: bad args"); ZZ_pEX z(INIT_SIZE, F.n); long sw; z = h; SetX(y); while (q) { sw = 0; if (q > 1) sw = 2; if (q & 1) { if (IsX(y)) y = z; else sw = sw | 1; } switch (sw) { case 0: break; case 1: CompMod(y, y, z, F); break; case 2: CompMod(z, z, z, F); break; case 3: Comp2Mod(y, z, y, z, z, F); break; } q = q >> 1; } } long ProbIrredTest(const ZZ_pEX& f, long iter) { long n = deg(f); if (n <= 0) return 0; if (n == 1) return 1; ZZ_pEXModulus F; build(F, f); ZZ_pEX b, r, s; FrobeniusMap(b, F); long all_zero = 1; long i; for (i = 0; i < iter; i++) { random(r, n); TraceMap(s, r, n, F, b); all_zero = all_zero && IsZero(s); if (deg(s) > 0) return 0; } if (!all_zero || (n & 1)) return 1; PowerCompose(s, b, n/2, F); return !IsX(s); } NTL_CHEAP_THREAD_LOCAL long ZZ_pEX_BlockingFactor = 10; void RootEDF(vec_ZZ_pEX& factors, const ZZ_pEX& f, long verbose) { vec_ZZ_pE roots; double t; if (verbose) { cerr << "finding roots..."; t = GetTime(); } FindRoots(roots, f); if (verbose) { cerr << (GetTime()-t) << "\n"; } long r = roots.length(); factors.SetLength(r); for (long j = 0; j < r; j++) { SetX(factors[j]); sub(factors[j], factors[j], roots[j]); } } void EDFSplit(vec_ZZ_pEX& v, const ZZ_pEX& f, const ZZ_pEX& b, long d) { ZZ_pEX a, g, h; ZZ_pEXModulus F; vec_ZZ_pE roots; build(F, f); long n = F.n; long r = n/d; random(a, n); TraceMap(g, a, d, F, b); MinPolyMod(h, g, F, r); FindRoots(roots, h); FindFactors(v, f, g, roots); } void RecEDF(vec_ZZ_pEX& factors, const ZZ_pEX& f, const ZZ_pEX& b, long d, long verbose) { vec_ZZ_pEX v; long i; ZZ_pEX bb; if (verbose) cerr << "+"; EDFSplit(v, f, b, d); for (i = 0; i < v.length(); i++) { if (deg(v[i]) == d) { append(factors, v[i]); } else { ZZ_pEX bb; rem(bb, b, v[i]); RecEDF(factors, v[i], bb, d, verbose); } } } void EDF(vec_ZZ_pEX& factors, const ZZ_pEX& ff, const ZZ_pEX& bb, long d, long verbose) { ZZ_pEX f = ff; ZZ_pEX b = bb; if (!IsOne(LeadCoeff(f))) LogicError("EDF: bad args"); long n = deg(f); long r = n/d; if (r == 0) { factors.SetLength(0); return; } if (r == 1) { factors.SetLength(1); factors[0] = f; return; } if (d == 1) { RootEDF(factors, f, verbose); return; } double t; if (verbose) { cerr << "computing EDF(" << d << "," << r << ")..."; t = GetTime(); } factors.SetLength(0); RecEDF(factors, f, b, d, verbose); if (verbose) cerr << (GetTime()-t) << "\n"; } void SFCanZass(vec_ZZ_pEX& factors, const ZZ_pEX& ff, long verbose) { ZZ_pEX f = ff; if (!IsOne(LeadCoeff(f))) LogicError("SFCanZass: bad args"); if (deg(f) == 0) { factors.SetLength(0); return; } if (deg(f) == 1) { factors.SetLength(1); factors[0] = f; return; } factors.SetLength(0); double t; ZZ_pEXModulus F; build(F, f); ZZ_pEX h; if (verbose) { cerr << "computing X^p..."; t = GetTime(); } FrobeniusMap(h, F); if (verbose) { cerr << (GetTime()-t) << "\n"; } vec_pair_ZZ_pEX_long u; if (verbose) { cerr << "computing DDF..."; t = GetTime(); } NewDDF(u, f, h, verbose); if (verbose) { t = GetTime()-t; cerr << "DDF time: " << t << "\n"; } ZZ_pEX hh; vec_ZZ_pEX v; long i; for (i = 0; i < u.length(); i++) { const ZZ_pEX& g = u[i].a; long d = u[i].b; long r = deg(g)/d; if (r == 1) { // g is already irreducible append(factors, g); } else { // must perform EDF if (d == 1) { // root finding RootEDF(v, g, verbose); append(factors, v); } else { // general case rem(hh, h, g); EDF(v, g, hh, d, verbose); append(factors, v); } } } } void CanZass(vec_pair_ZZ_pEX_long& factors, const ZZ_pEX& f, long verbose) { if (!IsOne(LeadCoeff(f))) LogicError("CanZass: bad args"); double t; vec_pair_ZZ_pEX_long sfd; vec_ZZ_pEX x; if (verbose) { cerr << "square-free decomposition..."; t = GetTime(); } SquareFreeDecomp(sfd, f); if (verbose) cerr << (GetTime()-t) << "\n"; factors.SetLength(0); long i, j; for (i = 0; i < sfd.length(); i++) { if (verbose) { cerr << "factoring multiplicity " << sfd[i].b << ", deg = " << deg(sfd[i].a) << "\n"; } SFCanZass(x, sfd[i].a, verbose); for (j = 0; j < x.length(); j++) append(factors, cons(x[j], sfd[i].b)); } } void mul(ZZ_pEX& f, const vec_pair_ZZ_pEX_long& v) { long i, j, n; n = 0; for (i = 0; i < v.length(); i++) n += v[i].b*deg(v[i].a); ZZ_pEX g(INIT_SIZE, n+1); set(g); for (i = 0; i < v.length(); i++) for (j = 0; j < v[i].b; j++) { mul(g, g, v[i].a); } f = g; } long BaseCase(const ZZ_pEX& h, long q, long a, const ZZ_pEXModulus& F) { long b, e; ZZ_pEX lh(INIT_SIZE, F.n); lh = h; b = 1; e = 0; while (e < a-1 && !IsX(lh)) { e++; b *= q; PowerCompose(lh, lh, q, F); } if (!IsX(lh)) b *= q; return b; } void TandemPowerCompose(ZZ_pEX& y1, ZZ_pEX& y2, const ZZ_pEX& h, long q1, long q2, const ZZ_pEXModulus& F) { ZZ_pEX z(INIT_SIZE, F.n); long sw; z = h; SetX(y1); SetX(y2); while (q1 || q2) { sw = 0; if (q1 > 1 || q2 > 1) sw = 4; if (q1 & 1) { if (IsX(y1)) y1 = z; else sw = sw | 2; } if (q2 & 1) { if (IsX(y2)) y2 = z; else sw = sw | 1; } switch (sw) { case 0: break; case 1: CompMod(y2, y2, z, F); break; case 2: CompMod(y1, y1, z, F); break; case 3: Comp2Mod(y1, y2, y1, y2, z, F); break; case 4: CompMod(z, z, z, F); break; case 5: Comp2Mod(z, y2, z, y2, z, F); break; case 6: Comp2Mod(z, y1, z, y1, z, F); break; case 7: Comp3Mod(z, y1, y2, z, y1, y2, z, F); break; } q1 = q1 >> 1; q2 = q2 >> 1; } } long RecComputeDegree(long u, const ZZ_pEX& h, const ZZ_pEXModulus& F, FacVec& fvec) { if (IsX(h)) return 1; if (fvec[u].link == -1) return BaseCase(h, fvec[u].q, fvec[u].a, F); ZZ_pEX h1, h2; long q1, q2, r1, r2; q1 = fvec[fvec[u].link].val; q2 = fvec[fvec[u].link+1].val; TandemPowerCompose(h1, h2, h, q1, q2, F); r1 = RecComputeDegree(fvec[u].link, h2, F, fvec); r2 = RecComputeDegree(fvec[u].link+1, h1, F, fvec); return r1*r2; } long RecComputeDegree(const ZZ_pEX& h, const ZZ_pEXModulus& F) // f = F.f is assumed to be an "equal degree" polynomial // h = X^p mod f // the common degree of the irreducible factors of f is computed { if (F.n == 1 || IsX(h)) return 1; FacVec fvec; FactorInt(fvec, F.n); return RecComputeDegree(fvec.length()-1, h, F, fvec); } void FindRoot(ZZ_pE& root, const ZZ_pEX& ff) // finds a root of ff. // assumes that ff is monic and splits into distinct linear factors { ZZ_pEXModulus F; ZZ_pEX h, h1, f; ZZ_pEX r; f = ff; if (!IsOne(LeadCoeff(f))) LogicError("FindRoot: bad args"); if (deg(f) == 0) LogicError("FindRoot: bad args"); while (deg(f) > 1) { build(F, f); random(r, deg(F)); if (IsOdd(ZZ_pE::cardinality())) { PowerMod(h, r, RightShift(ZZ_pE::cardinality(), 1), F); sub(h, h, 1); } else { AbsTraceMap(h, r, F); } GCD(h, h, f); if (deg(h) > 0 && deg(h) < deg(f)) { if (deg(h) > deg(f)/2) div(f, f, h); else f = h; } } negate(root, ConstTerm(f)); } static long power(long a, long e) { long i, res; res = 1; for (i = 1; i <= e; i++) res = res * a; return res; } static long IrredBaseCase(const ZZ_pEX& h, long q, long a, const ZZ_pEXModulus& F) { long e; ZZ_pEX X, s, d; e = power(q, a-1); PowerCompose(s, h, e, F); SetX(X); sub(s, s, X); GCD(d, F.f, s); return IsOne(d); } static long RecIrredTest(long u, const ZZ_pEX& h, const ZZ_pEXModulus& F, const FacVec& fvec) { long q1, q2; ZZ_pEX h1, h2; if (IsX(h)) return 0; if (fvec[u].link == -1) { return IrredBaseCase(h, fvec[u].q, fvec[u].a, F); } q1 = fvec[fvec[u].link].val; q2 = fvec[fvec[u].link+1].val; TandemPowerCompose(h1, h2, h, q1, q2, F); return RecIrredTest(fvec[u].link, h2, F, fvec) && RecIrredTest(fvec[u].link+1, h1, F, fvec); } long DetIrredTest(const ZZ_pEX& f) { if (deg(f) <= 0) return 0; if (deg(f) == 1) return 1; ZZ_pEXModulus F; build(F, f); ZZ_pEX h; FrobeniusMap(h, F); ZZ_pEX s; PowerCompose(s, h, F.n, F); if (!IsX(s)) return 0; FacVec fvec; FactorInt(fvec, F.n); return RecIrredTest(fvec.length()-1, h, F, fvec); } long IterIrredTest(const ZZ_pEX& f) { if (deg(f) <= 0) return 0; if (deg(f) == 1) return 1; ZZ_pEXModulus F; build(F, f); ZZ_pEX h; FrobeniusMap(h, F); long CompTableSize = 2*SqrRoot(deg(f)); ZZ_pEXArgument H; build(H, h, F, CompTableSize); long i, d, limit, limit_sqr; ZZ_pEX g, X, t, prod; SetX(X); i = 0; g = h; d = 1; limit = 2; limit_sqr = limit*limit; set(prod); while (2*d <= deg(f)) { sub(t, g, X); MulMod(prod, prod, t, F); i++; if (i == limit_sqr) { GCD(t, f, prod); if (!IsOne(t)) return 0; set(prod); limit++; limit_sqr = limit*limit; i = 0; } d = d + 1; if (2*d <= deg(f)) { CompMod(g, g, H, F); } } if (i > 0) { GCD(t, f, prod); if (!IsOne(t)) return 0; } return 1; } static void MulByXPlusY(vec_ZZ_pEX& h, const ZZ_pEX& f, const ZZ_pEX& g) // h represents the bivariate polynomial h[0] + h[1]*Y + ... + h[n-1]*Y^k, // where the h[i]'s are polynomials in X, each of degree < deg(f), // and k < deg(g). // h is replaced by the bivariate polynomial h*(X+Y) (mod f(X), g(Y)). { long n = deg(g); long k = h.length()-1; if (k < 0) return; if (k < n-1) { h.SetLength(k+2); h[k+1] = h[k]; for (long i = k; i >= 1; i--) { MulByXMod(h[i], h[i], f); add(h[i], h[i], h[i-1]); } MulByXMod(h[0], h[0], f); } else { ZZ_pEX b, t; b = h[n-1]; for (long i = n-1; i >= 1; i--) { mul(t, b, g.rep[i]); MulByXMod(h[i], h[i], f); add(h[i], h[i], h[i-1]); sub(h[i], h[i], t); } mul(t, b, g.rep[0]); MulByXMod(h[0], h[0], f); sub(h[0], h[0], t); } // normalize k = h.length()-1; while (k >= 0 && IsZero(h[k])) k--; h.SetLength(k+1); } static void IrredCombine(ZZ_pEX& x, const ZZ_pEX& f, const ZZ_pEX& g) { if (deg(f) < deg(g)) { IrredCombine(x, g, f); return; } // deg(f) >= deg(g)...not necessary, but maybe a little more // time & space efficient long df = deg(f); long dg = deg(g); long m = df*dg; vec_ZZ_pEX h(INIT_SIZE, dg); long i; for (i = 0; i < dg; i++) h[i].SetMaxLength(df); h.SetLength(1); set(h[0]); vec_ZZ_pE a; a.SetLength(2*m); for (i = 0; i < 2*m; i++) { a[i] = ConstTerm(h[0]); if (i < 2*m-1) MulByXPlusY(h, f, g); } MinPolySeq(x, a, m); } static void BuildPrimePowerIrred(ZZ_pEX& f, long q, long e) { long n = power(q, e); do { random(f, n); SetCoeff(f, n); } while (!IterIrredTest(f)); } static void RecBuildIrred(ZZ_pEX& f, long u, const FacVec& fvec) { if (fvec[u].link == -1) BuildPrimePowerIrred(f, fvec[u].q, fvec[u].a); else { ZZ_pEX g, h; RecBuildIrred(g, fvec[u].link, fvec); RecBuildIrred(h, fvec[u].link+1, fvec); IrredCombine(f, g, h); } } void BuildIrred(ZZ_pEX& f, long n) { if (n <= 0) LogicError("BuildIrred: n must be positive"); if (NTL_OVERFLOW(n, 1, 0)) ResourceError("overflow in BuildIrred"); if (n == 1) { SetX(f); return; } FacVec fvec; FactorInt(fvec, n); RecBuildIrred(f, fvec.length()-1, fvec); } #if 0 void BuildIrred(ZZ_pEX& f, long n) { if (n <= 0) LogicError("BuildIrred: n must be positive"); if (n == 1) { SetX(f); return; } ZZ_pEX g; do { random(g, n); SetCoeff(g, n); } while (!IterIrredTest(g)); f = g; } #endif void BuildRandomIrred(ZZ_pEX& f, const ZZ_pEX& g) { ZZ_pEXModulus G; ZZ_pEX h, ff; build(G, g); do { random(h, deg(g)); IrredPolyMod(ff, h, G); } while (deg(ff) < deg(g)); f = ff; } /************* NEW DDF ****************/ NTL_CHEAP_THREAD_LOCAL long ZZ_pEX_GCDTableSize = 4; NTL_CHEAP_THREAD_LOCAL double ZZ_pEXFileThresh = NTL_FILE_THRESH; static NTL_CHEAP_THREAD_LOCAL vec_ZZ_pEX *BabyStepFile=0; static NTL_CHEAP_THREAD_LOCAL vec_ZZ_pEX *GiantStepFile=0; static NTL_CHEAP_THREAD_LOCAL long use_files; static double CalcTableSize(long n, long k) { double sz = ZZ_p::storage(); sz = sz*ZZ_pE::degree(); sz = sz + NTL_VECTOR_HEADER_SIZE + sizeof(vec_ZZ_p); sz = sz*n; sz = sz + NTL_VECTOR_HEADER_SIZE + sizeof(vec_ZZ_pE); sz = sz * k; sz = sz/1024; return sz; } static void GenerateBabySteps(ZZ_pEX& h1, const ZZ_pEX& f, const ZZ_pEX& h, long k, FileList& flist, long verbose) { double t; if (verbose) { cerr << "generating baby steps..."; t = GetTime(); } ZZ_pEXModulus F; build(F, f); ZZ_pEXArgument H; #if 0 double n2 = sqrt(double(F.n)); double n4 = sqrt(n2); double n34 = n2*n4; long sz = long(ceil(n34/sqrt(sqrt(2.0)))); #else long sz = 2*SqrRoot(F.n); #endif build(H, h, F, sz); h1 = h; long i; if (!use_files) { (*BabyStepFile).SetLength(k-1); } for (i = 1; i <= k-1; i++) { if (use_files) { ofstream s; OpenWrite(s, FileName("baby", i), flist); s << h1 << "\n"; CloseWrite(s); } else (*BabyStepFile)(i) = h1; CompMod(h1, h1, H, F); if (verbose) cerr << "+"; } if (verbose) cerr << (GetTime()-t) << "\n"; } static void GenerateGiantSteps(const ZZ_pEX& f, const ZZ_pEX& h, long l, FileList& flist, long verbose) { double t; if (verbose) { cerr << "generating giant steps..."; t = GetTime(); } ZZ_pEXModulus F; build(F, f); ZZ_pEXArgument H; #if 0 double n2 = sqrt(double(F.n)); double n4 = sqrt(n2); double n34 = n2*n4; long sz = long(ceil(n34/sqrt(sqrt(2.0)))); #else long sz = 2*SqrRoot(F.n); #endif build(H, h, F, sz); ZZ_pEX h1; h1 = h; long i; if (!use_files) { (*GiantStepFile).SetLength(l); } for (i = 1; i <= l-1; i++) { if (use_files) { ofstream s; OpenWrite(s, FileName("giant", i), flist); s << h1 << "\n"; CloseWrite(s); } else (*GiantStepFile)(i) = h1; CompMod(h1, h1, H, F); if (verbose) cerr << "+"; } if (use_files) { ofstream s; OpenWrite(s, FileName("giant", i), flist); s << h1 << "\n"; CloseWrite(s); } else (*GiantStepFile)(i) = h1; if (verbose) cerr << (GetTime()-t) << "\n"; } static void NewAddFactor(vec_pair_ZZ_pEX_long& u, const ZZ_pEX& g, long m, long verbose) { long len = u.length(); u.SetLength(len+1); u[len].a = g; u[len].b = m; if (verbose) { cerr << "split " << m << " " << deg(g) << "\n"; } } static void NewProcessTable(vec_pair_ZZ_pEX_long& u, ZZ_pEX& f, const ZZ_pEXModulus& F, vec_ZZ_pEX& buf, long size, long StartInterval, long IntervalLength, long verbose) { if (size == 0) return; ZZ_pEX& g = buf[size-1]; long i; for (i = 0; i < size-1; i++) MulMod(g, g, buf[i], F); GCD(g, f, g); if (deg(g) == 0) return; div(f, f, g); long d = (StartInterval-1)*IntervalLength + 1; i = 0; long interval = StartInterval; while (i < size-1 && 2*d <= deg(g)) { GCD(buf[i], buf[i], g); if (deg(buf[i]) > 0) { NewAddFactor(u, buf[i], interval, verbose); div(g, g, buf[i]); } i++; interval++; d += IntervalLength; } if (deg(g) > 0) { if (i == size-1) NewAddFactor(u, g, interval, verbose); else NewAddFactor(u, g, (deg(g)+IntervalLength-1)/IntervalLength, verbose); } } static void FetchGiantStep(ZZ_pEX& g, long gs, const ZZ_pEXModulus& F) { if (use_files) { ifstream s; OpenRead(s, FileName("giant", gs)); NTL_INPUT_CHECK_ERR(s >> g); } else g = (*GiantStepFile)(gs); rem(g, g, F); } static void FetchBabySteps(vec_ZZ_pEX& v, long k) { v.SetLength(k); SetX(v[0]); long i; for (i = 1; i <= k-1; i++) { if (use_files) { ifstream s; OpenRead(s, FileName("baby", i)); NTL_INPUT_CHECK_ERR(s >> v[i]); } else v[i] = (*BabyStepFile)(i); } } static void GiantRefine(vec_pair_ZZ_pEX_long& u, const ZZ_pEX& ff, long k, long l, long verbose) { double t; if (verbose) { cerr << "giant refine..."; t = GetTime(); } u.SetLength(0); vec_ZZ_pEX BabyStep; FetchBabySteps(BabyStep, k); vec_ZZ_pEX buf(INIT_SIZE, ZZ_pEX_GCDTableSize); ZZ_pEX f; f = ff; ZZ_pEXModulus F; build(F, f); ZZ_pEX g; ZZ_pEX h; long size = 0; long first_gs; long d = 1; while (2*d <= deg(f)) { long old_n = deg(f); long gs = (d+k-1)/k; long bs = gs*k - d; if (bs == k-1) { size++; if (size == 1) first_gs = gs; FetchGiantStep(g, gs, F); sub(buf[size-1], g, BabyStep[bs]); } else { sub(h, g, BabyStep[bs]); MulMod(buf[size-1], buf[size-1], h, F); } if (verbose && bs == 0) cerr << "+"; if (size == ZZ_pEX_GCDTableSize && bs == 0) { NewProcessTable(u, f, F, buf, size, first_gs, k, verbose); if (verbose) cerr << "*"; size = 0; } d++; if (2*d <= deg(f) && deg(f) < old_n) { build(F, f); long i; for (i = 1; i <= k-1; i++) rem(BabyStep[i], BabyStep[i], F); } } if (size > 0) { NewProcessTable(u, f, F, buf, size, first_gs, k, verbose); if (verbose) cerr << "*"; } if (deg(f) > 0) NewAddFactor(u, f, 0, verbose); if (verbose) { t = GetTime()-t; cerr << "giant refine time: " << t << "\n"; } } static void IntervalRefine(vec_pair_ZZ_pEX_long& factors, const ZZ_pEX& ff, long k, long gs, const vec_ZZ_pEX& BabyStep, long verbose) { vec_ZZ_pEX buf(INIT_SIZE, ZZ_pEX_GCDTableSize); ZZ_pEX f; f = ff; ZZ_pEXModulus F; build(F, f); ZZ_pEX g; FetchGiantStep(g, gs, F); long size = 0; long first_d; long d = (gs-1)*k + 1; long bs = k-1; while (bs >= 0 && 2*d <= deg(f)) { long old_n = deg(f); if (size == 0) first_d = d; rem(buf[size], BabyStep[bs], F); sub(buf[size], buf[size], g); size++; if (size == ZZ_pEX_GCDTableSize) { NewProcessTable(factors, f, F, buf, size, first_d, 1, verbose); size = 0; } d++; bs--; if (bs >= 0 && 2*d <= deg(f) && deg(f) < old_n) { build(F, f); rem(g, g, F); } } NewProcessTable(factors, f, F, buf, size, first_d, 1, verbose); if (deg(f) > 0) NewAddFactor(factors, f, deg(f), verbose); } static void BabyRefine(vec_pair_ZZ_pEX_long& factors, const vec_pair_ZZ_pEX_long& u, long k, long l, long verbose) { double t; if (verbose) { cerr << "baby refine..."; t = GetTime(); } factors.SetLength(0); vec_ZZ_pEX BabyStep; long i; for (i = 0; i < u.length(); i++) { const ZZ_pEX& g = u[i].a; long gs = u[i].b; if (gs == 0 || 2*((gs-1)*k+1) > deg(g)) NewAddFactor(factors, g, deg(g), verbose); else { if (BabyStep.length() == 0) FetchBabySteps(BabyStep, k); IntervalRefine(factors, g, k, gs, BabyStep, verbose); } } if (verbose) { t = GetTime()-t; cerr << "baby refine time: " << t << "\n"; } } void NewDDF(vec_pair_ZZ_pEX_long& factors, const ZZ_pEX& f, const ZZ_pEX& h, long verbose) { if (!IsOne(LeadCoeff(f))) LogicError("NewDDF: bad args"); if (deg(f) == 0) { factors.SetLength(0); return; } if (deg(f) == 1) { factors.SetLength(0); append(factors, cons(f, 1L)); return; } long B = deg(f)/2; long k = SqrRoot(B); long l = (B+k-1)/k; ZZ_pEX h1; if (CalcTableSize(deg(f), k + l - 1) > ZZ_pEXFileThresh) use_files = 1; else use_files = 0; FileList flist; vec_ZZ_pEX local_BabyStepFile; vec_ZZ_pEX local_GiantStepFile; BabyStepFile = &local_BabyStepFile; GiantStepFile = &local_GiantStepFile; GenerateBabySteps(h1, f, h, k, flist, verbose); GenerateGiantSteps(f, h1, l, flist, verbose); vec_pair_ZZ_pEX_long u; GiantRefine(u, f, k, l, verbose); BabyRefine(factors, u, k, l, verbose); } long IterComputeDegree(const ZZ_pEX& h, const ZZ_pEXModulus& F) { long n = deg(F); if (n == 1 || IsX(h)) return 1; long B = n/2; long k = SqrRoot(B); long l = (B+k-1)/k; ZZ_pEXArgument H; #if 0 double n2 = sqrt(double(n)); double n4 = sqrt(n2); double n34 = n2*n4; long sz = long(ceil(n34/sqrt(sqrt(2.0)))); #else long sz = 2*SqrRoot(F.n); #endif build(H, h, F, sz); ZZ_pEX h1; h1 = h; vec_ZZ_pEX baby; baby.SetLength(k); SetX(baby[0]); long i; for (i = 1; i <= k-1; i++) { baby[i] = h1; CompMod(h1, h1, H, F); if (IsX(h1)) return i+1; } build(H, h1, F, sz); long j; for (j = 2; j <= l; j++) { CompMod(h1, h1, H, F); for (i = k-1; i >= 0; i--) { if (h1 == baby[i]) return j*k-i; } } return n; } NTL_END_IMPL
cris-iisc/mpc-primitives
crislib/libscapi/lib/NTL/unix/src/ZZ_pEXFactoring.c
C
agpl-3.0
28,130
// Copyright 2010-2013 RethinkDB, all rights reserved. #ifndef RDB_PROTOCOL_META_UTILS_HPP_ #define RDB_PROTOCOL_META_UTILS_HPP_ #include <string> #include "clustering/administration/metadata.hpp" #include "clustering/administration/namespace_interface_repository.hpp" void wait_for_rdb_table_readiness( base_namespace_repo_t<rdb_protocol_t> *ns_repo, namespace_id_t namespace_id, signal_t *interruptor, boost::shared_ptr<semilattice_readwrite_view_t<cluster_semilattice_metadata_t> > semilattice_metadata) THROWS_ONLY(interrupted_exc_t); namespace ql { template<class T, class U, class V> uuid_u meta_get_uuid(T *searcher, const U &predicate, const std::string &message, V *caller) { metadata_search_status_t status; typename T::iterator entry = searcher->find_uniq(predicate, &status); rcheck_target(caller, base_exc_t::GENERIC, status == METADATA_SUCCESS, message); return entry->first; } } // namespace ql #endif // RDB_PROTOCOL_META_UTILS_HPP_
krahman/rethinkdb
src/rdb_protocol/meta_utils.hpp
C++
agpl-3.0
1,034
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.ocrr.forms.newresultsinpatienttabcomponent; import ims.framework.delegates.*; abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode { abstract protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onFormDialogClosed(ims.framework.FormName formName, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onQmbReviewingHCPValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onQmbReviewingHCPTextSubmited(String value) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onImbRemoveDisciplineClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onImbAddDisciplineClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onGrdDisciplinesSelectionChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onDteToValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onDteFromValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onCmbDaysValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onChkCurrentIPValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onChkOrderValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onQmbOrderingLocationTextSubmited(String value) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onCmbHospitalValueChanged() throws ims.framework.exceptions.PresentationLogicException; public final void setContext(ims.framework.UIComponentEngine engine, GenForm form) { this.engine = engine; this.form = form; this.form.setFormOpenEvent(new FormOpen() { private static final long serialVersionUID = 1L; public void handle(Object[] args) throws ims.framework.exceptions.PresentationLogicException { onFormOpen(args); } }); this.form.setFormDialogClosedEvent(new FormDialogClosed() { private static final long serialVersionUID = 1L; public void handle(ims.framework.FormName formName, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException { onFormDialogClosed(formName, result); } }); this.form.qmbReviewingHCP().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onQmbReviewingHCPValueChanged(); } }); this.form.qmbReviewingHCP().setSearchEvent(new ComboBoxSearch() { private static final long serialVersionUID = 1L; public void handle(String value) throws ims.framework.exceptions.PresentationLogicException { onQmbReviewingHCPTextSubmited(value); } }); this.form.imbRemoveDiscipline().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onImbRemoveDisciplineClick(); } }); this.form.imbAddDiscipline().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onImbAddDisciplineClick(); } }); this.form.grdDisciplines().setSelectionChangedEvent(new GridSelectionChanged() { private static final long serialVersionUID = 1L; public void handle(ims.framework.enumerations.MouseButton mouseButton) throws ims.framework.exceptions.PresentationLogicException { onGrdDisciplinesSelectionChanged(); } }); this.form.dteTo().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onDteToValueChanged(); } }); this.form.dteFrom().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onDteFromValueChanged(); } }); this.form.cmbDays().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onCmbDaysValueChanged(); } }); this.form.chkCurrentIP().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onChkCurrentIPValueChanged(); } }); this.form.chkOrder().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onChkOrderValueChanged(); } }); this.form.qmbOrderingLocation().setSearchEvent(new ComboBoxSearch() { private static final long serialVersionUID = 1L; public void handle(String value) throws ims.framework.exceptions.PresentationLogicException { onQmbOrderingLocationTextSubmited(value); } }); this.form.cmbHospital().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onCmbHospitalValueChanged(); } }); } public void free() { this.engine = null; this.form = null; } protected ims.framework.UIComponentEngine engine; protected GenForm form; }
open-health-hub/openmaxims-linux
openmaxims_workspace/OCRR/src/ims/ocrr/forms/newresultsinpatienttabcomponent/Handlers.java
Java
agpl-3.0
7,684
<?php /* * This file is part of MailSo. * * (c) 2014 Usenko Timur * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace MailSo\Base; /** * @category MailSo * @package Base */ class HtmlUtils { static $KOS = '@@_KOS_@@'; /** * @access private */ private function __construct() { } /** * @param \DOMElement $oElement * * @return array */ public static function GetElementAttributesAsArray($oElement) { $aResult = array(); if ($oElement) { if ($oElement->hasAttributes() && isset($oElement->attributes) && $oElement->attributes) { foreach ($oElement->attributes as $oAttr) { if ($oAttr && !empty($oAttr->nodeName)) { $sAttrName = \trim(\strtolower($oAttr->nodeName)); $aResult[$sAttrName] = $oAttr->nodeValue; } } } } return $aResult; } /** * @param string $sText * * @return \DOMDocument|bool */ public static function GetDomFromText($sText) { $bState = true; if (\MailSo\Base\Utils::FunctionExistsAndEnabled('libxml_use_internal_errors')) { $bState = \libxml_use_internal_errors(true); } $sHtmlAttrs = $sBodyAttrs = ''; $sText = \MailSo\Base\HtmlUtils::FixSchemas($sText); $sText = \MailSo\Base\HtmlUtils::ClearFastTags($sText); $sText = \MailSo\Base\HtmlUtils::ClearBodyAndHtmlTag($sText, $sHtmlAttrs, $sBodyAttrs); $oDom = self::createDOMDocument(); @$oDom->loadHTML('<'.'?xml version="1.0" encoding="utf-8"?'.'>'. '<html '.$sHtmlAttrs.'><head>'. '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head>'. '<body '.$sBodyAttrs.'>'.\MailSo\Base\Utils::Utf8Clear($sText).'</body></html>'); @$oDom->normalizeDocument(); if (\MailSo\Base\Utils::FunctionExistsAndEnabled('libxml_clear_errors')) { @\libxml_clear_errors(); } if (\MailSo\Base\Utils::FunctionExistsAndEnabled('libxml_use_internal_errors')) { \libxml_use_internal_errors($bState); } return $oDom; } /** * @return \DOMDocument */ private static function createDOMDocument() { $oDoc = new \DOMDocument('1.0', 'UTF-8'); $oDoc->encoding = 'UTF-8'; $oDoc->strictErrorChecking = false; $oDoc->formatOutput = false; $oDoc->preserveWhiteSpace = false; return $oDoc; } /** * @return boolean */ private static function comparedVersion() { return \version_compare(PHP_VERSION, '5.3.6') >= 0; } /** * @param \DOMDocument|\DOMElement $oElem * * @return string */ private static function domToString($oElem, $oDom = null) { $sResult = ''; if ($oElem instanceof \DOMDocument) { if (isset($oElem->documentElement) && self::comparedVersion()) { $sResult = $oElem->saveHTML($oElem->documentElement); } else { $sResult = $oElem->saveHTML(); } } else if ($oElem) { if ($oDom && self::comparedVersion()) { $sResult = $oDom->saveHTML($oElem); } else { $oTempDoc = self::createDOMDocument(); $oTempDoc->appendChild($oTempDoc->importNode($oElem->cloneNode(true), true)); $sResult = $oTempDoc->saveHTML(); } } return \trim($sResult); } /** * @param \DOMDocument $oDom * @param bool $bWrapByFakeHtmlAndBodyDiv = true * * @return string */ public static function GetTextFromDom_($oDom, $bWrapByFakeHtmlAndBodyDiv = true) { $sResult = ''; $aHtmlAttrs = $aBodylAttrs = array(); if ($bWrapByFakeHtmlAndBodyDiv) { $oHtml = $oDom->getElementsByTagName('html')->item(0); $oBody = $oDom->getElementsByTagName('body')->item(0); $aHtmlAttrs = \MailSo\Base\HtmlUtils::GetElementAttributesAsArray($oHtml); $aBodylAttrs = \MailSo\Base\HtmlUtils::GetElementAttributesAsArray($oBody); } $oDiv = $oDom->getElementsByTagName('div')->item(0); if ($oDiv && $oDiv->hasAttribute('data-wrp') && 'rainloop' === $oDiv->getAttribute('data-wrp')) { $oDiv->removeAttribute('data-wrp'); if ($bWrapByFakeHtmlAndBodyDiv) { $oWrap = $oDom->createElement('div'); $oWrap->setAttribute('data-x-div-type', 'html'); foreach ($aHtmlAttrs as $sKey => $sValue) { $oWrap->setAttribute($sKey, $sValue); } $oDiv->setAttribute('data-x-div-type', 'body'); foreach ($aBodylAttrs as $sKey => $sValue) { $oDiv->setAttribute($sKey, $sValue); } $oWrap->appendChild($oDiv); $sResult = self::domToString($oWrap, $oDom); } else { $sResult = self::domToString($oDiv, $oDom); } } else { $sResult = self::domToString($oDom); } $sResult = \str_replace(\MailSo\Base\HtmlUtils::$KOS, ':', $sResult); $sResult = \MailSo\Base\Utils::StripSpaces($sResult); return $sResult; } /** * @param \DOMDocument $oDom * @param bool $bWrapByFakeHtmlAndBodyDiv = true * * @return string */ public static function GetTextFromDom($oDom, $bWrapByFakeHtmlAndBodyDiv = true) { $sResult = ''; $oHtml = $oDom->getElementsByTagName('html')->item(0); $oBody = $oDom->getElementsByTagName('body')->item(0); foreach ($oBody->childNodes as $oChild) { $sResult .= $oDom->saveHTML($oChild); } if ($bWrapByFakeHtmlAndBodyDiv) { $aHtmlAttrs = \MailSo\Base\HtmlUtils::GetElementAttributesAsArray($oHtml); $aBodylAttrs = \MailSo\Base\HtmlUtils::GetElementAttributesAsArray($oBody); $oWrapHtml = $oDom->createElement('div'); $oWrapHtml->setAttribute('data-x-div-type', 'html'); foreach ($aHtmlAttrs as $sKey => $sValue) { $oWrapHtml->setAttribute($sKey, $sValue); } $oWrapDom = $oDom->createElement('div', '___xxx___'); $oWrapDom->setAttribute('data-x-div-type', 'body'); foreach ($aBodylAttrs as $sKey => $sValue) { $oWrapDom->setAttribute($sKey, $sValue); } $oWrapHtml->appendChild($oWrapDom); $sWrp = $oDom->saveHTML($oWrapHtml); $sResult = \str_replace('___xxx___', $sResult, $sWrp); } $sResult = \str_replace(\MailSo\Base\HtmlUtils::$KOS, ':', $sResult); $sResult = \MailSo\Base\Utils::StripSpaces($sResult); return $sResult; } /** * @param string $sHtml * @param string $sHtmlAttrs = '' * @param string $sBodyAttrs = '' * * @return string */ public static function ClearBodyAndHtmlTag($sHtml, &$sHtmlAttrs = '', &$sBodyAttrs = '') { $aMatch = array(); if (\preg_match('/<html([^>]+)>/im', $sHtml, $aMatch) && !empty($aMatch[1])) { $sHtmlAttrs = $aMatch[1]; } $aMatch = array(); if (\preg_match('/<body([^>]+)>/im', $sHtml, $aMatch) && !empty($aMatch[1])) { $sBodyAttrs = $aMatch[1]; } $sHtml = \preg_replace('/<head([^>]*)>/si', '', $sHtml); $sHtml = \preg_replace('/<body([^>]*)>/si', '', $sHtml); $sHtml = \preg_replace('/<\/body>/i', '', $sHtml); $sHtml = \preg_replace('/<html([^>]*)>/i', '', $sHtml); $sHtml = \preg_replace('/<\/html>/i', '', $sHtml); $sHtmlAttrs = \preg_replace('/xmlns:[a-z]="[^"]*"/i', '', $sHtmlAttrs); $sHtmlAttrs = \preg_replace('/xmlns:[a-z]=\'[^\']*\'/i', '', $sHtmlAttrs); $sHtmlAttrs = \preg_replace('/xmlns="[^"]*"/i', '', $sHtmlAttrs); $sHtmlAttrs = \preg_replace('/xmlns=\'[^\']*\'/i', '', $sHtmlAttrs); $sBodyAttrs = \preg_replace('/xmlns:[a-z]="[^"]*"/i', '', $sBodyAttrs); $sBodyAttrs = \preg_replace('/xmlns:[a-z]=\'[^\']*\'/i', '', $sBodyAttrs); $sHtmlAttrs = trim($sHtmlAttrs); $sBodyAttrs = trim($sBodyAttrs); return $sHtml; } /** * @param string $sHtml * @param bool $bClearEmpty = true * * @return string */ public static function FixSchemas($sHtml, $bClearEmpty = true) { if ($bClearEmpty) { $sHtml = \str_replace('<o:p></o:p>', '', $sHtml); } $sHtml = \str_replace('<o:p>', '<span>', $sHtml); $sHtml = \str_replace('</o:p>', '</span>', $sHtml); return $sHtml; } /** * @param string $sHtml * * @return string */ public static function ClearFastTags($sHtml) { return \preg_replace(array( '/<p[^>]*><\/p>/i', '/<!doctype[^>]*>/i', '/<\?xml [^>]*\?>/i' ), '', $sHtml); } /** * @param mixed $oDom */ public static function ClearComments(&$oDom) { $aRemove = array(); $oXpath = new \DOMXpath($oDom); $oComments = $oXpath->query('//comment()'); if ($oComments) { foreach ($oComments as $oComment) { $aRemove[] = $oComment; } } unset($oXpath, $oComments); foreach ($aRemove as /* @var $oElement \DOMElement */ $oElement) { if (isset($oElement->parentNode)) { @$oElement->parentNode->removeChild($oElement); } } } /** * @param mixed $oDom * @param bool $bClearStyleAndHead = true */ public static function ClearTags(&$oDom, $bClearStyleAndHead = true) { $aRemoveTags = array( 'svg', 'link', 'base', 'meta', 'title', 'x-script', 'script', 'bgsound', 'keygen', 'source', 'object', 'embed', 'applet', 'mocha', 'iframe', 'frame', 'frameset', 'video', 'audio', 'area', 'map' ); if ($bClearStyleAndHead) { $aRemoveTags[] = 'head'; $aRemoveTags[] = 'style'; } $aHtmlAllowedTags = isset(\MailSo\Config::$HtmlStrictAllowedTags) && \is_array(\MailSo\Config::$HtmlStrictAllowedTags) && 0 < \count(\MailSo\Config::$HtmlStrictAllowedTags) ? \MailSo\Config::$HtmlStrictAllowedTags : null; $aRemove = array(); $aNodes = $oDom->getElementsByTagName('*'); foreach ($aNodes as /* @var $oElement \DOMElement */ $oElement) { if ($oElement) { $sTagNameLower = \trim(\strtolower($oElement->tagName)); if ('' !== $sTagNameLower) { if (\in_array($sTagNameLower, $aRemoveTags) || ($aHtmlAllowedTags && !\in_array($sTagNameLower, $aHtmlAllowedTags))) { $aRemove[] = @$oElement; } } } } foreach ($aRemove as /* @var $oElement \DOMElement */ $oElement) { if (isset($oElement->parentNode)) { @$oElement->parentNode->removeChild($oElement); } } } /* // public static function ClearStyleUrlValueParserHelper($oUrlValue, $oRule, $oRuleSet, // $oElem = null, // &$bHasExternals = false, &$aFoundCIDs = array(), // $aContentLocationUrls = array(), &$aFoundedContentLocationUrls = array(), // $bDoNotReplaceExternalUrl = false, $fAdditionalExternalFilter = null // ) // { // if ($oUrlValue instanceof \Sabberworm\CSS\Value\URL) // { // $oNewRule = new \Sabberworm\CSS\Rule\Rule('x-rl-orig-'.$oRule->getRule()); // $oNewRule->setValue((string) $oRule->getValue()); // $oNewRule->setIsImportant($oRule->getIsImportant()); // // $oRuleSet->addRule($oNewRule); // // $oUrl = $oUrlValue->getURL(); // $sUrl = $oUrl ? $oUrl->getString() : ''; // // if ('cid:' === \strtolower(\substr($sUrl, 0, 4))) // { // $aFoundCIDs[] = \substr($sUrl, 4); // // $oRule->setRule('x-rl-mod-'.$oRule->getRule()); // // if ($oElem) // { // $oElem->setAttribute('data-x-style-mod', '1'); // } // } // else // { // if (\preg_match('/http[s]?:\/\//i', $sUrl) || '//' === \substr($sUrl, 0, 2)) // { // $oRule->setRule('x-rl-mod-'.$oRule->getRule()); // // if (\in_array($sUrl, $aContentLocationUrls)) // { // $aFoundedContentLocationUrls[] = $sUrl; // } // else // { // $bHasExternals = true; // if (!$bDoNotReplaceExternalUrl) // { // if ($fAdditionalExternalFilter) // { // $sAdditionalResult = \call_user_func($fAdditionalExternalFilter, $sUrl); // if (0 < \strlen($sAdditionalResult) && $oUrl) // { // $oUrl->setString($sAdditionalResult); // } // } // } // } // // if ($oElem) // { // $oElem->setAttribute('data-x-style-mod', '1'); // } // } // else if ('data:image/' !== \strtolower(\substr(\trim($sUrl), 0, 11))) // { // $oRuleSet->removeRule($oRule); // } // } // } // else if ($oRule instanceof \Sabberworm\CSS\Rule\Rule) // { // if ('x-rl-' !== \substr($oRule->getRule(), 0, 5)) // { // $oValue = $oRule->getValue(); // if ($oValue instanceof \Sabberworm\CSS\Value\URL) // { // \MailSo\Base\HtmlUtils::ClearStyleUrlValueParserHelper($oValue, $oRule, $oRuleSet, $oElem, // $bHasExternals, $aFoundCIDs, // $aContentLocationUrls, $aFoundedContentLocationUrls, // $bDoNotReplaceExternalUrl, $fAdditionalExternalFilter); // } // else if ($oValue instanceof \Sabberworm\CSS\Value\RuleValueList) // { // $aComps = $oValue->getListComponents(); // foreach ($aComps as $oValue) // { // if ($oValue instanceof \Sabberworm\CSS\Value\URL) // { // \MailSo\Base\HtmlUtils::ClearStyleUrlValueParserHelper($oValue, $oRule, $oRuleSet, $oElem, // $bHasExternals, $aFoundCIDs, // $aContentLocationUrls, $aFoundedContentLocationUrls, // $bDoNotReplaceExternalUrl, $fAdditionalExternalFilter); // } // } // } // } // } // } // // public static function ClearStyleSmart($sStyle, $oElement = null, // &$bHasExternals = false, &$aFoundCIDs = array(), // $aContentLocationUrls = array(), &$aFoundedContentLocationUrls = array(), // $bDoNotReplaceExternalUrl = false, $fAdditionalExternalFilter = null, // $sSelectorPrefix = '') // { // $mResult = false; // $oCss = null; // // if (!\class_exists('Sabberworm\CSS\Parser')) // { // return $mResult; // } // // $sStyle = \trim($sStyle); // if (empty($sStyle)) // { // return ''; // } // // $sStyle = \trim(\preg_replace('/[\r\n\t\s]+/', ' ', $sStyle)); // // try // { // $oSettings = \Sabberworm\CSS\Settings::create(); // $oSettings->beStrict(); // $oSettings->withMultibyteSupport(false); // // $oCssParser = new \Sabberworm\CSS\Parser($sStyle, $oSettings); // $oCss = $oCssParser->parse(); // } // catch (\Exception $oEception) // { // unset($oEception); // $mResult = false; // } // // if ($oCss) // { // foreach ($oCss->getAllDeclarationBlocks() as $oBlock) // { // foreach($oBlock->getSelectors() as $oSelector) // { // $sS = ' '.\trim($oSelector->getSelector()).' '; // $sS = \preg_replace('/ body([\.# ])/i', ' [data-x-div-type="body"]$1', $sS); // $sS = \preg_replace('/ html([\.# ])/i', ' [data-x-div-type="html"]$1', $sS); // // if (0 < \strlen($sSelectorPrefix)) // { // $sS = \trim($sSelectorPrefix.' '.\trim($sS)); // } // // $oSelector->setSelector(\trim($sS)); // } // } // // $aRulesToRemove = array( // 'pointer-events', 'content', 'behavior', 'cursor', // ); // // foreach($oCss->getAllRuleSets() as $oRuleSet) // { // foreach ($aRulesToRemove as $sRuleToRemove) // { // $oRuleSet->removeRule($sRuleToRemove); // } // // // position: fixed -> position: fixed -> absolute // $aRules = $oRuleSet->getRules('position'); // if (\is_array($aRules)) // { // foreach ($aRules as $oRule) // { // $mValue = $oRule->getValue(); // if (\is_string($mValue) && 'fixed' === \trim(\strtolower($mValue))) // { // $oRule->setValue('absolute'); // } // } // } // } // // foreach($oCss->getAllDeclarationBlocks() as $oRuleSet) // { // if ($oRuleSet instanceof \Sabberworm\CSS\RuleSet\RuleSet) // { // if ($oRuleSet instanceof \Sabberworm\CSS\RuleSet\DeclarationBlock) // { // $oRuleSet->expandBackgroundShorthand(); // $oRuleSet->expandListStyleShorthand(); // } // // $aRules = $oRuleSet->getRules(); // if (\is_array($aRules) && 0 < \count($aRules)) // { // foreach ($aRules as $oRule) // { // if ($oRule instanceof \Sabberworm\CSS\Rule\Rule) // { // \MailSo\Base\HtmlUtils::ClearStyleUrlValueParserHelper(null, $oRule, $oRuleSet, // $oElement, // $bHasExternals, $aFoundCIDs, // $aContentLocationUrls, $aFoundedContentLocationUrls, // $bDoNotReplaceExternalUrl, $fAdditionalExternalFilter // ); // } // } // } // } // } // // try // { // $mResult = $oCss->render(\Sabberworm\CSS\OutputFormat::createCompact()); // } // catch (\Exception $oEception) // { // unset($oEception); // $mResult = false; // } // } // // return $mResult; // } */ /** * * @param string $sStyle * @param \DOMElement $oElement * @param bool $bHasExternals * @param array $aFoundCIDs * @param array $aContentLocationUrls * @param array $aFoundedContentLocationUrls * @param bool $bDoNotReplaceExternalUrl = false * @param callback|null $fAdditionalExternalFilter = null * * @return string */ public static function ClearStyle($sStyle, $oElement, &$bHasExternals, &$aFoundCIDs, $aContentLocationUrls, &$aFoundedContentLocationUrls, $bDoNotReplaceExternalUrl = false, $fAdditionalExternalFilter = null) { $sStyle = \trim($sStyle); $aOutStyles = array(); $aStyles = \explode(';', $sStyle); if ($fAdditionalExternalFilter && !\is_callable($fAdditionalExternalFilter)) { $fAdditionalExternalFilter = null; } $aMatch = array(); foreach ($aStyles as $sStyleItem) { $aStyleValue = \explode(':', $sStyleItem, 2); $sName = \trim(\strtolower($aStyleValue[0])); $sValue = isset($aStyleValue[1]) ? \trim($aStyleValue[1]) : ''; if ('position' === $sName && 'fixed' === \strtolower($sValue)) { $sValue = 'absolute'; } if (0 === \strlen($sName) || 0 === \strlen($sValue)) { continue; } $sStyleItem = $sName.': '.$sValue; $aStyleValue = array($sName, $sValue); /*if (\in_array($sName, array('position', 'left', 'right', 'top', 'bottom', 'behavior', 'cursor'))) { // skip } else */if (\in_array($sName, array('behavior', 'pointer-events')) || ('cursor' === $sName && !\in_array(\strtolower($sValue), array('none', 'cursor'))) || ('display' === $sName && 'none' === \strtolower($sValue)) || \preg_match('/expression/i', $sValue) || ('text-indent' === $sName && '-' === \substr(trim($sValue), 0, 1)) ) { // skip } else if (\in_array($sName, array('background-image', 'background', 'list-style', 'list-style-image', 'content')) && \preg_match('/url[\s]?\(([^)]+)\)/im', $sValue, $aMatch) && !empty($aMatch[1])) { $sFullUrl = \trim($aMatch[0], '"\' '); $sUrl = \trim($aMatch[1], '"\' '); $sStyleValue = \trim(\preg_replace('/[\s]+/', ' ', \str_replace($sFullUrl, '', $sValue))); $sStyleItem = empty($sStyleValue) ? '' : $sName.': '.$sStyleValue; if ('cid:' === \strtolower(\substr($sUrl, 0, 4))) { if ($oElement) { $oElement->setAttribute('data-x-style-cid-name', 'background' === $sName ? 'background-image' : $sName); $oElement->setAttribute('data-x-style-cid', \substr($sUrl, 4)); $aFoundCIDs[] = \substr($sUrl, 4); } } else { if ($oElement) { if (\preg_match('/http[s]?:\/\//i', $sUrl) || '//' === \substr($sUrl, 0, 2)) { $bHasExternals = true; if (!$bDoNotReplaceExternalUrl) { if (\in_array($sName, array('background-image', 'list-style-image', 'content'))) { $sStyleItem = ''; } $sTemp = ''; if ($oElement->hasAttribute('data-x-style-url')) { $sTemp = \trim($oElement->getAttribute('data-x-style-url')); } $sTemp = empty($sTemp) ? '' : (';' === \substr($sTemp, -1) ? $sTemp.' ' : $sTemp.'; '); $oElement->setAttribute('data-x-style-url', \trim($sTemp. ('background' === $sName ? 'background-image' : $sName).': '.$sFullUrl, ' ;')); if ($fAdditionalExternalFilter) { $sAdditionalResult = \call_user_func($fAdditionalExternalFilter, $sUrl); if (0 < \strlen($sAdditionalResult)) { $oElement->setAttribute('data-x-additional-style-url', ('background' === $sName ? 'background-image' : $sName).': url('.$sAdditionalResult.')'); } } } } else if ('data:image/' !== \strtolower(\substr(\trim($sUrl), 0, 11))) { $oElement->setAttribute('data-x-broken-style-src', $sFullUrl); } } } if (!empty($sStyleItem)) { $aOutStyles[] = $sStyleItem; } } else if ('height' === $sName) { // $aOutStyles[] = 'min-'.ltrim($sStyleItem); $aOutStyles[] = $sStyleItem; } else { $aOutStyles[] = $sStyleItem; } } return \implode(';', $aOutStyles); } /** * @param \DOMDocument $oDom */ public static function FindLinksInDOM(&$oDom) { $aNodes = $oDom->getElementsByTagName('*'); foreach ($aNodes as /* @var $oElement \DOMElement */ $oElement) { $sTagNameLower = \strtolower($oElement->tagName); $sParentTagNameLower = isset($oElement->parentNode) && isset($oElement->parentNode->tagName) ? \strtolower($oElement->parentNode->tagName) : ''; if (!\in_array($sTagNameLower, array('html', 'meta', 'head', 'style', 'script', 'img', 'button', 'input', 'textarea', 'a')) && 'a' !== $sParentTagNameLower && $oElement->childNodes && 0 < $oElement->childNodes->length) { $oSubItem = null; $aTextNodes = array(); $iIndex = $oElement->childNodes->length - 1; while ($iIndex > -1) { $oSubItem = $oElement->childNodes->item($iIndex); if ($oSubItem && XML_TEXT_NODE === $oSubItem->nodeType) { $aTextNodes[] = $oSubItem; } $iIndex--; } unset($oSubItem); foreach ($aTextNodes as $oTextNode) { if ($oTextNode && 0 < \strlen($oTextNode->wholeText)/* && \preg_match('/http[s]?:\/\//i', $oTextNode->wholeText)*/) { $sText = \MailSo\Base\LinkFinder::NewInstance() ->Text($oTextNode->wholeText) ->UseDefaultWrappers(true) ->CompileText() ; $oSubDom = \MailSo\Base\HtmlUtils::GetDomFromText($sText); if ($oSubDom) { $oBodyNodes = $oSubDom->getElementsByTagName('body'); if ($oBodyNodes && 0 < $oBodyNodes->length) { $oBodyChildNodes = $oBodyNodes->item(0)->childNodes; if ($oBodyChildNodes && $oBodyChildNodes->length) { for ($iIndex = 0, $iLen = $oBodyChildNodes->length; $iIndex < $iLen; $iIndex++) { $oSubItem = $oBodyChildNodes->item($iIndex); if ($oSubItem) { if (XML_ELEMENT_NODE === $oSubItem->nodeType && 'a' === \strtolower($oSubItem->tagName)) { $oLink = $oDom->createElement('a', \str_replace(':', \MailSo\Base\HtmlUtils::$KOS, \htmlspecialchars($oSubItem->nodeValue))); $sHref = $oSubItem->getAttribute('href'); if ($sHref) { $oLink->setAttribute('href', $sHref); } $oElement->insertBefore($oLink, $oTextNode); } else { $oElement->insertBefore($oDom->importNode($oSubItem), $oTextNode); } } } $oElement->removeChild($oTextNode); } } unset($oBodyNodes); } unset($oSubDom, $sText); } } } } unset($aNodes); } /** * @param string $sHtml * @param bool $bDoNotReplaceExternalUrl = false * @param bool $bFindLinksInHtml = false * @param bool $bWrapByFakeHtmlAndBodyDiv = true * * @return string */ public static function ClearHtmlSimple($sHtml, $bDoNotReplaceExternalUrl = false, $bFindLinksInHtml = false, $bWrapByFakeHtmlAndBodyDiv = true) { $bHasExternals = false; $aFoundCIDs = array(); $aContentLocationUrls = array(); $aFoundedContentLocationUrls = array(); $fAdditionalExternalFilter = null; $fAdditionalDomReader = null; $bTryToDetectHiddenImages = false; return \MailSo\Base\HtmlUtils::ClearHtml($sHtml, $bHasExternals, $aFoundCIDs, $aContentLocationUrls, $aFoundedContentLocationUrls, $bDoNotReplaceExternalUrl, $bFindLinksInHtml, $fAdditionalExternalFilter, $fAdditionalDomReader, $bTryToDetectHiddenImages, $bWrapByFakeHtmlAndBodyDiv); } /** * @param string $sHtml * @param bool $bHasExternals = false * @param array $aFoundCIDs = array() * @param array $aContentLocationUrls = array() * @param array $aFoundedContentLocationUrls = array() * @param bool $bDoNotReplaceExternalUrl = false * @param bool $bFindLinksInHtml = false * @param callback|null $fAdditionalExternalFilter = null * @param callback|null $fAdditionalDomReader = null * @param bool $bTryToDetectHiddenImages = false * @param bool $bWrapByFakeHtmlAndBodyDiv = true * * @return string */ public static function ClearHtml($sHtml, &$bHasExternals = false, &$aFoundCIDs = array(), $aContentLocationUrls = array(), &$aFoundedContentLocationUrls = array(), $bDoNotReplaceExternalUrl = false, $bFindLinksInHtml = false, $fAdditionalExternalFilter = null, $fAdditionalDomReader = false, $bTryToDetectHiddenImages = false, $bWrapByFakeHtmlAndBodyDiv = true) { $sResult = ''; $sHtml = null === $sHtml ? '' : (string) $sHtml; $sHtml = \trim($sHtml); if (0 === \strlen($sHtml)) { return ''; } if ($fAdditionalExternalFilter && !\is_callable($fAdditionalExternalFilter)) { $fAdditionalExternalFilter = null; } if ($fAdditionalDomReader && !\is_callable($fAdditionalDomReader)) { $fAdditionalDomReader = null; } $bHasExternals = false; // Dom Part $oDom = \MailSo\Base\HtmlUtils::GetDomFromText($sHtml); unset($sHtml); if (!$oDom) { return ''; } if ($fAdditionalDomReader) { $oResDom = \call_user_func($fAdditionalDomReader, $oDom); if ($oResDom) { $oDom = $oResDom; } unset($oResDom); } if ($bFindLinksInHtml) { \MailSo\Base\HtmlUtils::FindLinksInDOM($oDom); } \MailSo\Base\HtmlUtils::ClearComments($oDom); \MailSo\Base\HtmlUtils::ClearTags($oDom); $sLinkColor = ''; $aNodes = $oDom->getElementsByTagName('*'); foreach ($aNodes as /* @var $oElement \DOMElement */ $oElement) { $aRemovedAttrs = array(); $sTagNameLower = \strtolower($oElement->tagName); // convert body attributes to styles if ('body' === $sTagNameLower) { $aAttrs = array( 'link' => '', 'text' => '', 'topmargin' => '', 'leftmargin' => '', 'bottommargin' => '', 'rightmargin' => '' ); if (isset($oElement->attributes)) { foreach ($oElement->attributes as $sAttrName => /* @var $oAttributeNode \DOMNode */ $oAttributeNode) { if ($oAttributeNode && isset($oAttributeNode->nodeValue)) { $sAttrNameLower = \trim(\strtolower($sAttrName)); if (isset($aAttrs[$sAttrNameLower]) && '' === $aAttrs[$sAttrNameLower]) { $aAttrs[$sAttrNameLower] = array($sAttrName, \trim($oAttributeNode->nodeValue)); } } } } $aStyles = array(); foreach ($aAttrs as $sIndex => $aItem) { if (\is_array($aItem)) { $oElement->removeAttribute($aItem[0]); switch ($sIndex) { case 'link': $sLinkColor = \trim($aItem[1]); if (!\preg_match('/^#[abcdef0-9]{3,6}$/i', $sLinkColor)) { $sLinkColor = ''; } break; case 'text': $aStyles[] = 'color: '.$aItem[1]; break; case 'topmargin': $aStyles[] = 'margin-top: '.((int) $aItem[1]).'px'; break; case 'leftmargin': $aStyles[] = 'margin-left: '.((int) $aItem[1]).'px'; break; case 'bottommargin': $aStyles[] = 'margin-bottom: '.((int) $aItem[1]).'px'; break; case 'rightmargin': $aStyles[] = 'margin-right: '.((int) $aItem[1]).'px'; break; } } } if (0 < \count($aStyles)) { $sStyles = $oElement->hasAttribute('style') ? \trim(\trim(\trim($oElement->getAttribute('style')), ';')) : ''; $oElement->setAttribute('style', (empty($sStyles) ? '' : $sStyles.'; ').\implode('; ', $aStyles)); } } if ('iframe' === $sTagNameLower || 'frame' === $sTagNameLower) { $oElement->setAttribute('src', 'javascript:false'); } if ('a' === $sTagNameLower && !empty($sLinkColor)) { $sStyles = $oElement->hasAttribute('style') ? \trim(\trim(\trim($oElement->getAttribute('style')), ';')) : ''; $oElement->setAttribute('style', 'color: '.$sLinkColor.\trim((empty($sStyles) ? '' : '; '.$sStyles))); } if ($oElement->hasAttributes() && isset($oElement->attributes) && $oElement->attributes) { $aHtmlAllowedAttributes = isset(\MailSo\Config::$HtmlStrictAllowedAttributes) && \is_array(\MailSo\Config::$HtmlStrictAllowedAttributes) && 0 < \count(\MailSo\Config::$HtmlStrictAllowedAttributes) ? \MailSo\Config::$HtmlStrictAllowedAttributes : null; $sAttrsForRemove = array(); foreach ($oElement->attributes as $sAttrName => $oAttr) { if ($sAttrName && $oAttr) { $sAttrNameLower = \trim(\strtolower($sAttrName)); if ($aHtmlAllowedAttributes && !\in_array($sAttrNameLower, $aHtmlAllowedAttributes)) { $sAttrsForRemove[] = $sAttrName; } else if ('on' === \substr($sAttrNameLower, 0, 2) || in_array($sAttrNameLower, array( 'id', 'class', 'contenteditable', 'designmode', 'formaction', 'manifest', 'action', 'data-bind', 'data-reactid', 'xmlns', 'srcset', 'data-x-skip-style', 'fscommand', 'seeksegmenttime' ))) { $sAttrsForRemove[] = $sAttrName; } } } if (0 < \count($sAttrsForRemove)) { foreach ($sAttrsForRemove as $sName) { @$oElement->removeAttribute($sName); $aRemovedAttrs[\trim(\strtolower($sName))] = true; } } unset($sAttrsForRemove); } if ($oElement->hasAttribute('href')) { $sHref = \trim($oElement->getAttribute('href')); if (!\preg_match('/^(http[s]?|ftp|skype|mailto):/i', $sHref) && '//' !== \substr($sHref, 0, 2)) { $oElement->setAttribute('data-x-broken-href', $sHref); $oElement->setAttribute('href', 'javascript:false'); } if ('a' === $sTagNameLower) { $oElement->setAttribute('rel', 'external nofollow noopener noreferrer'); } } if (\in_array($sTagNameLower, array('a', 'form', 'area'))) { $oElement->setAttribute('target', '_blank'); } if (\in_array($sTagNameLower, array('a', 'form', 'area', 'input', 'button', 'textarea'))) { $oElement->setAttribute('tabindex', '-1'); } if ($bTryToDetectHiddenImages && 'img' === $sTagNameLower) { $sAlt = $oElement->hasAttribute('alt') ? \trim($oElement->getAttribute('alt')) : ''; if ($oElement->hasAttribute('src') && '' === $sAlt) { $aH = array( 'email.microsoftemail.com/open', 'github.com/notifications/beacon/', 'mandrillapp.com/track/open', 'list-manage.com/track/open' ); $sH = $oElement->hasAttribute('height') ? \trim($oElement->getAttribute('height')) : ''; // $sW = $oElement->hasAttribute('width') // ? \trim($oElement->getAttribute('width')) : ''; $sStyles = $oElement->hasAttribute('style') ? \preg_replace('/[\s]+/', '', \trim(\trim(\trim($oElement->getAttribute('style')), ';'))) : ''; $sSrc = \trim($oElement->getAttribute('src')); $bC = \in_array($sH, array('1', '0', '1px', '0px')) || \preg_match('/(display:none|visibility:hidden|height:0|height:[01][a-z][a-z])/i', $sStyles); if (!$bC) { $sSrcLower = \strtolower($sSrc); foreach ($aH as $sLine) { if (false !== \strpos($sSrcLower, $sLine)) { $bC = true; break; } } } if ($bC) { $oElement->setAttribute('style', 'display:none'); $oElement->setAttribute('data-x-skip-style', 'true'); $oElement->setAttribute('data-x-hidden-src', $sSrc); $oElement->removeAttribute('src'); } } } if ($oElement->hasAttribute('src')) { $sSrc = \trim($oElement->getAttribute('src')); $oElement->removeAttribute('src'); if (\in_array($sSrc, $aContentLocationUrls)) { $oElement->setAttribute('data-x-src-location', $sSrc); $aFoundedContentLocationUrls[] = $sSrc; } else if ('cid:' === \strtolower(\substr($sSrc, 0, 4))) { $oElement->setAttribute('data-x-src-cid', \substr($sSrc, 4)); $aFoundCIDs[] = \substr($sSrc, 4); } else { if (\preg_match('/^http[s]?:\/\//i', $sSrc) || '//' === \substr($sSrc, 0, 2)) { if ($bDoNotReplaceExternalUrl) { $oElement->setAttribute('src', $sSrc); } else { $oElement->setAttribute('data-x-src', $sSrc); if ($fAdditionalExternalFilter) { $sCallResult = \call_user_func($fAdditionalExternalFilter, $sSrc); if (0 < \strlen($sCallResult)) { $oElement->setAttribute('data-x-additional-src', $sCallResult); } } } $bHasExternals = true; } else if ('data:image/' === \strtolower(\substr($sSrc, 0, 11))) { $oElement->setAttribute('src', $sSrc); } else { $oElement->setAttribute('data-x-broken-src', $sSrc); } } } $sBackground = $oElement->hasAttribute('background') ? \trim($oElement->getAttribute('background')) : ''; $sBackgroundColor = $oElement->hasAttribute('bgcolor') ? \trim($oElement->getAttribute('bgcolor')) : ''; if (!empty($sBackground) || !empty($sBackgroundColor)) { $aStyles = array(); $sStyles = $oElement->hasAttribute('style') ? \trim(\trim(\trim($oElement->getAttribute('style')), ';')) : ''; if (!empty($sBackground)) { $aStyles[] = 'background-image: url(\''.$sBackground.'\')'; $oElement->removeAttribute('background'); } if (!empty($sBackgroundColor)) { $aStyles[] = 'background-color: '.$sBackgroundColor; $oElement->removeAttribute('bgcolor'); } $oElement->setAttribute('style', (empty($sStyles) ? '' : $sStyles.'; ').\implode('; ', $aStyles)); } if ($oElement->hasAttribute('style') && !$oElement->hasAttribute('data-x-skip-style')) { $oElement->setAttribute('style', \MailSo\Base\HtmlUtils::ClearStyle($oElement->getAttribute('style'), $oElement, $bHasExternals, $aFoundCIDs, $aContentLocationUrls, $aFoundedContentLocationUrls, $bDoNotReplaceExternalUrl, $fAdditionalExternalFilter)); } $oElement->removeAttribute('data-x-skip-style'); if (\MailSo\Config::$HtmlStrictDebug && 0 < \count($aRemovedAttrs)) { unset($aRemovedAttrs['class'], $aRemovedAttrs['target'], $aRemovedAttrs['id'], $aRemovedAttrs['name'], $aRemovedAttrs['itemprop'], $aRemovedAttrs['itemscope'], $aRemovedAttrs['itemtype']); $aRemovedAttrs = \array_keys($aRemovedAttrs); if (0 < \count($aRemovedAttrs)) { $oElement->setAttribute('data-removed-attrs', \implode(',', $aRemovedAttrs)); } } } $sResult = \MailSo\Base\HtmlUtils::GetTextFromDom($oDom, $bWrapByFakeHtmlAndBodyDiv); unset($oDom); return $sResult; } /** * @param string $sHtml * @param array $aFoundCids = array() * @param array|null $mFoundDataURL = null * @param array $aFoundedContentLocationUrls = array() * * @return string */ public static function BuildHtml($sHtml, &$aFoundCids = array(), &$mFoundDataURL = null, &$aFoundedContentLocationUrls = array()) { $oDom = \MailSo\Base\HtmlUtils::GetDomFromText($sHtml); \MailSo\Base\HtmlUtils::ClearTags($oDom); unset($sHtml); $aNodes = $oDom->getElementsByTagName('*'); foreach ($aNodes as /* @var $oElement \DOMElement */ $oElement) { $sTagNameLower = \strtolower($oElement->tagName); if ($oElement->hasAttribute('data-x-src-cid')) { $sCid = $oElement->getAttribute('data-x-src-cid'); $oElement->removeAttribute('data-x-src-cid'); if (!empty($sCid)) { $aFoundCids[] = $sCid; @$oElement->removeAttribute('src'); $oElement->setAttribute('src', 'cid:'.$sCid); } } if ($oElement->hasAttribute('data-x-src-location')) { $sSrc = $oElement->getAttribute('data-x-src-location'); $oElement->removeAttribute('data-x-src-location'); if (!empty($sSrc)) { $aFoundedContentLocationUrls[] = $sSrc; @$oElement->removeAttribute('src'); $oElement->setAttribute('src', $sSrc); } } if ($oElement->hasAttribute('data-x-broken-src')) { $oElement->setAttribute('src', $oElement->getAttribute('data-x-broken-src')); $oElement->removeAttribute('data-x-broken-src'); } if ($oElement->hasAttribute('data-x-src')) { $oElement->setAttribute('src', $oElement->getAttribute('data-x-src')); $oElement->removeAttribute('data-x-src'); } if ($oElement->hasAttribute('data-x-href')) { $oElement->setAttribute('href', $oElement->getAttribute('data-x-href')); $oElement->removeAttribute('data-x-href'); } if ($oElement->hasAttribute('data-x-style-cid-name') && $oElement->hasAttribute('data-x-style-cid')) { $sCidName = $oElement->getAttribute('data-x-style-cid-name'); $sCid = $oElement->getAttribute('data-x-style-cid'); $oElement->removeAttribute('data-x-style-cid-name'); $oElement->removeAttribute('data-x-style-cid'); if (!empty($sCidName) && !empty($sCid) && \in_array($sCidName, array('background-image', 'background', 'list-style-image', 'content'))) { $sStyles = ''; if ($oElement->hasAttribute('style')) { $sStyles = \trim(\trim($oElement->getAttribute('style')), ';'); } $sBack = $sCidName.': url(cid:'.$sCid.')'; $sStyles = \preg_replace('/'.\preg_quote($sCidName, '/').':\s?[^;]+/i', $sBack, $sStyles); if (false === \strpos($sStyles, $sBack)) { $sStyles .= empty($sStyles) ? '': '; '; $sStyles .= $sBack; } $oElement->setAttribute('style', $sStyles); $aFoundCids[] = $sCid; } } foreach (array( 'data-x-additional-src', 'data-x-additional-style-url', 'data-removed-attrs', 'data-original', 'data-x-div-type', 'data-wrp', 'data-bind' ) as $sName) { if ($oElement->hasAttribute($sName)) { $oElement->removeAttribute($sName); } } if ($oElement->hasAttribute('data-x-style-url')) { $sAddStyles = $oElement->getAttribute('data-x-style-url'); $oElement->removeAttribute('data-x-style-url'); if (!empty($sAddStyles)) { $sStyles = ''; if ($oElement->hasAttribute('style')) { $sStyles = \trim(\trim($oElement->getAttribute('style')), ';'); } $oElement->setAttribute('style', (empty($sStyles) ? '' : $sStyles.'; ').$sAddStyles); } } if ('img' === $sTagNameLower && \is_array($mFoundDataURL)) { $sSrc = $oElement->getAttribute('src'); if ('data:image/' === \strtolower(\substr($sSrc, 0, 11))) { $sHash = \md5($sSrc); $mFoundDataURL[$sHash] = $sSrc; $oElement->setAttribute('src', 'cid:'.$sHash); } } } $sResult = \MailSo\Base\HtmlUtils::GetTextFromDom($oDom, false); unset($oDom); return '<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>'. '<body>'.$sResult.'</body></html>'; } /** * @param string $sText * @param bool $bLinksWithTargetBlank = true * * @return string */ public static function ConvertPlainToHtml($sText, $bLinksWithTargetBlank = true) { $sText = \trim($sText); if (0 === \strlen($sText)) { return ''; } $sText = \MailSo\Base\LinkFinder::NewInstance() ->Text($sText) ->UseDefaultWrappers($bLinksWithTargetBlank) ->CompileText() ; $sText = \str_replace("\r", '', $sText); $aText = \explode("\n", $sText); unset($sText); $bIn = false; $bDo = true; do { $bDo = false; $aNextText = array(); foreach ($aText as $sTextLine) { $bStart = 0 === \strpos(\ltrim($sTextLine), '&gt;'); if ($bStart && !$bIn) { $bDo = true; $bIn = true; $aNextText[] = '<blockquote>'; $aNextText[] = \substr(\ltrim($sTextLine), 4); } else if (!$bStart && $bIn) { $bIn = false; $aNextText[] = '</blockquote>'; $aNextText[] = $sTextLine; } else if ($bStart && $bIn) { $aNextText[] = \substr(\ltrim($sTextLine), 4); } else { $aNextText[] = $sTextLine; } } if ($bIn) { $bIn = false; $aNextText[] = '</blockquote>'; } $aText = $aNextText; } while ($bDo); $sText = \join("\n", $aText); unset($aText); $sText = \preg_replace('/[\n][ ]+/', "\n", $sText); // $sText = \preg_replace('/[\s]+([\s])/', '\\1', $sText); $sText = \preg_replace('/<blockquote>[\s]+/i', '<blockquote>', $sText); $sText = \preg_replace('/[\s]+<\/blockquote>/i', '</blockquote>', $sText); $sText = \preg_replace('/<\/blockquote>([\n]{0,2})<blockquote>/i', '\\1', $sText); $sText = \preg_replace('/[\n]{3,}/', "\n\n", $sText); $sText = \strtr($sText, array( "\n" => "<br />", "\t" => '&nbsp;&nbsp;&nbsp;', ' ' => '&nbsp;&nbsp;' )); return $sText; } /** * @param string $sText * * @return string */ public static function ConvertHtmlToPlain($sText) { $sText = \trim(\stripslashes($sText)); $sText = \MailSo\Base\Utils::StripSpaces($sText); $sText = \preg_replace(array( "/\r/", "/[\n\t]+/", '/<script[^>]*>.*?<\/script>/i', '/<style[^>]*>.*?<\/style>/i', '/<title[^>]*>.*?<\/title>/i', '/<h[123][^>]*>(.+?)<\/h[123]>/i', '/<h[456][^>]*>(.+?)<\/h[456]>/i', '/<p[^>]*>/i', '/<br[^>]*>/i', '/<b[^>]*>(.+?)<\/b>/i', '/<i[^>]*>(.+?)<\/i>/i', '/(<ul[^>]*>|<\/ul>)/i', '/(<ol[^>]*>|<\/ol>)/i', '/<li[^>]*>/i', '/<a[^>]*href="([^"]+)"[^>]*>(.+?)<\/a>/i', '/<hr[^>]*>/i', '/(<table[^>]*>|<\/table>)/i', '/(<tr[^>]*>|<\/tr>)/i', '/<td[^>]*>(.+?)<\/td>/i', '/<th[^>]*>(.+?)<\/th>/i', '/&nbsp;/i', '/&quot;/i', '/&gt;/i', '/&lt;/i', '/&amp;/i', '/&copy;/i', '/&trade;/i', '/&#8220;/', '/&#8221;/', '/&#8211;/', '/&#8217;/', '/&#38;/', '/&#169;/', '/&#8482;/', '/&#151;/', '/&#147;/', '/&#148;/', '/&#149;/', '/&reg;/i', '/&bull;/i', '/&[&;]+;/i', '/&#39;/', '/&#160;/' ), array( '', ' ', '', '', '', "\n\n\\1\n\n", "\n\n\\1\n\n", "\n\n\t", "\n", '\\1', '\\1', "\n\n", "\n\n", "\n\t* ", '\\2 (\\1)', "\n------------------------------------\n", "\n", "\n", "\t\\1\n", "\t\\1\n", ' ', '"', '>', '<', '&', '(c)', '(tm)', '"', '"', '-', "'", '&', '(c)', '(tm)', '--', '"', '"', '*', '(R)', '*', '', '\'', '' ), $sText); $sText = \str_ireplace('<div>',"\n<div>", $sText); $sText = \strip_tags($sText, ''); $sText = \preg_replace("/\n\\s+\n/", "\n", $sText); $sText = \preg_replace("/[\n]{3,}/", "\n\n", $sText); return \trim($sText); } }
Oygron/rainloop-webmail
rainloop/v/0.0.0/app/libraries/MailSo/Base/HtmlUtils.php
PHP
agpl-3.0
44,211
# Generated by Django 3.2.8 on 2021-12-02 10:49 import time from django.db import migrations def noop(apps, schema_editor): # pragma: no cover pass def populate_flow_results_word_cloud(apps, schema_editor): # pragma: no cover Org = apps.get_model("orgs", "Org") PollWordCloud = apps.get_model("stats", "PollWordCloud") start_time = time.time() orgs = Org.objects.all().order_by("id") count = 0 for org in orgs: word_clouds = PollWordCloud.objects.filter(org=org).select_related("question", "flow_result") total = word_clouds.count() for word_cloud in word_clouds: if not word_cloud.flow_result: word_cloud.flow_result = word_cloud.question.flow_result word_cloud.save() count += 1 elapsed = time.time() - start_time print( f"Migrated flow_result for {count} of {total} polls word clouds on org #{org.id} in {elapsed:.1f} seconds" ) print(f"Finished migrating polls word clouds on org #{org.id}") def apply_manual(): # pragma: no cover from django.apps import apps populate_flow_results_word_cloud(apps, None) class Migration(migrations.Migration): dependencies = [ ("stats", "0025_more_indexes"), ] operations = [migrations.RunPython(populate_flow_results_word_cloud, noop)]
rapidpro/ureport
ureport/stats/migrations/0026_populate_flow_result_word_clouds.py
Python
agpl-3.0
1,413
# # This file is part of Plinth. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ Plinth module to configure matrix-synapse server. """ import logging import os from django.urls import reverse_lazy from django.utils.translation import ugettext_lazy as _ from ruamel.yaml.util import load_yaml_guess_indent from plinth import action_utils from plinth import actions from plinth import frontpage from plinth import service as service_module from plinth.menu import main_menu version = 1 managed_services = ['matrix-synapse'] managed_packages = ['matrix-synapse'] name = _('Matrix Synapse') short_description = _('Chat Server') description = [ _('<a href="https://matrix.org/docs/guides/faq.html">Matrix</a> is an new ' 'ecosystem for open, federated instant messaging and VoIP. Synapse is a ' 'server implementing the Matrix protocol. It provides chat groups, ' 'audio/video calls, end-to-end encryption, multiple device ' 'synchronization and does not require phone numbers to work. Users on a ' 'given Matrix server can converse with users on all other Matrix servers ' 'via federation.'), _('To communicate, you can use the ' '<a href="https://matrix.org/docs/projects/">available clients</a> ' 'for mobile, desktop and the web. <a href="https://riot.im/">Riot</a> ' 'client is recommended.') ] service = None logger = logging.getLogger(__name__) SERVER_NAME_PATH = "/etc/matrix-synapse/conf.d/server_name.yaml" def init(): """Initialize the matrix-synapse module.""" menu = main_menu.get('apps') menu.add_urlname(name, 'glyphicon-comment', 'matrixsynapse:index', short_description) global service setup_helper = globals()['setup_helper'] if setup_helper.get_state() != 'needs-setup': service = service_module.Service( 'matrix-synapse', name, ports=['matrix-synapse-plinth'], is_external=True, is_enabled=is_enabled, enable=enable, disable=disable) if is_enabled(): add_shortcut() def setup(helper, old_version=None): """Install and configure the module.""" helper.install(managed_packages) global service if service is None: service = service_module.Service( 'matrix-synapse', name, ports=['matrix-synapse-plinth'], is_external=True, is_enabled=is_enabled, enable=enable, disable=disable) helper.call('post', actions.superuser_run, 'matrixsynapse', ['post-install']) helper.call('post', service.notify_enabled, None, True) helper.call('post', add_shortcut) def add_shortcut(): """Add a shortcut to the frontpage.""" frontpage.add_shortcut('matrixsynapse', name, details=description, short_description=short_description, configure_url=reverse_lazy('matrixsynapse:index'), login_required=True) def is_setup(): """Return whether the Matrix Synapse server is setup.""" return os.path.exists(SERVER_NAME_PATH) def is_enabled(): """Return whether the module is enabled.""" return action_utils.service_is_enabled('matrix-synapse') def enable(): """Enable the module.""" actions.superuser_run('matrixsynapse', ['enable']) add_shortcut() def disable(): """Enable the module.""" actions.superuser_run('matrixsynapse', ['disable']) frontpage.remove_shortcut('matrixsynapse') def diagnose(): """Run diagnostics and return the results.""" results = [] results.append(action_utils.diagnose_port_listening(8008, 'tcp4')) results.append(action_utils.diagnose_port_listening(8448, 'tcp4')) results.extend(action_utils.diagnose_url_on_all( 'https://{host}/_matrix', check_certificate=False)) return results def get_configured_domain_name(): """Return the currently configured domain name.""" if not is_setup(): return None with open(SERVER_NAME_PATH) as config_file: config, _, _ = load_yaml_guess_indent(config_file) return config['server_name']
kkampardi/Plinth
plinth/modules/matrixsynapse/__init__.py
Python
agpl-3.0
4,738
/* Copyright (C) 2010 Fredrik Johansson This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */ #include "flint.h" #include "ulong_extras.h" mp_limb_t n_euler_phi(mp_limb_t n) { int i; mp_limb_t phi; n_factor_t fac; if (n < 2) return n; n_factor_init(&fac); n_factor(&fac, n, 1); phi = UWORD(1); for (i = 0; i < fac.num; i++) phi *= (fac.p[i]-1) * n_pow(fac.p[i], fac.exp[i]-1); return phi; }
wbhart/flint2
ulong_extras/euler_phi.c
C
lgpl-2.1
739
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * 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, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #ifndef SOFA_SIMULATION_TREE_GNODE_H #define SOFA_SIMULATION_TREE_GNODE_H #include <SofaSimulationTree/tree.h> #include <sofa/simulation/Node.h> namespace sofa { namespace simulation { namespace tree { /** Define the structure of the scene. Contains (as pointer lists) Component objects and children GNode objects. */ class SOFA_SIMULATION_TREE_API GNode : public simulation::Node { public: typedef Node::DisplayFlags DisplayFlags; SOFA_CLASS(GNode, simulation::Node); protected: GNode( const std::string& name="", GNode* parent=NULL ); virtual ~GNode(); public: //Pure Virtual method from Node virtual Node::SPtr createChild(const std::string& nodeName); //Pure Virtual method from BaseNode /// Add a child node virtual void addChild(BaseNode::SPtr node); /// Remove a child node virtual void removeChild(BaseNode::SPtr node); /// Move a node from another node virtual void moveChild(BaseNode::SPtr obj); /// Add an object and return this. Detect the implemented interfaces and add the object to the corresponding lists. virtual bool addObject(core::objectmodel::BaseObject::SPtr obj) { return simulation::Node::addObject(obj); } /// Remove an object virtual bool removeObject(core::objectmodel::BaseObject::SPtr obj) { return simulation::Node::removeObject(obj); } /// Remove the current node from the graph: consists in removing the link to its parent virtual void detachFromGraph(); /// Get a list of parent node virtual Parents getParents() const; /// returns number of parents virtual size_t getNbParents() const; /// return the first parent (returns NULL if no parent) virtual BaseNode* getFirstParent() const; /// Test if the given node is a parent of this node. bool hasParent(const BaseNode* node) const { return parent() == node; } /// Test if the given context is a parent of this context. bool hasParent(const BaseContext* context) const { if (context == NULL) return parent() == NULL; else return parent()->getContext() == context; } /// Test if the given context is an ancestor of this context. /// An ancestor is a parent or (recursively) the parent of an ancestor. bool hasAncestor(const BaseNode* node) const { return hasAncestor(node->getContext()); } /// Test if the given context is an ancestor of this context. /// An ancestor is a parent or (recursively) the parent of an ancestor. bool hasAncestor(const BaseContext* context) const; /// Generic object access, given a set of required tags, possibly searching up or down from the current context /// /// Note that the template wrapper method should generally be used to have the correct return type, virtual void* getObject(const sofa::core::objectmodel::ClassInfo& class_info, const sofa::core::objectmodel::TagSet& tags, SearchDirection dir = SearchUp) const; /// Generic object access, given a path from the current context /// /// Note that the template wrapper method should generally be used to have the correct return type, virtual void* getObject(const sofa::core::objectmodel::ClassInfo& class_info, const std::string& path) const; /// Generic list of objects access, given a set of required tags, possibly searching up or down from the current context /// /// Note that the template wrapper method should generally be used to have the correct return type, virtual void getObjects(const sofa::core::objectmodel::ClassInfo& class_info, GetObjectsCallBack& container, const sofa::core::objectmodel::TagSet& tags, SearchDirection dir = SearchUp) const; /// Called during initialization to corectly propagate the visual context to the children virtual void initVisualContext(); /// Update the whole context values, based on parent and local ContextObjects virtual void updateContext(); /// Update the simulation context values(gravity, time...), based on parent and local ContextObjects virtual void updateSimulationContext(); static GNode::SPtr create(GNode*, core::objectmodel::BaseObjectDescription* arg) { GNode::SPtr obj = GNode::SPtr(); obj->parse(arg); return obj; } /// return the smallest common parent between this and node2 (returns NULL if separated sub-graphes) virtual Node* findCommonParent( simulation::Node* node2 ); protected: inline GNode* parent() const { return l_parent.get(); } SingleLink<GNode,GNode,BaseLink::FLAG_DOUBLELINK> l_parent; virtual void doAddChild(GNode::SPtr node); void doRemoveChild(GNode::SPtr node); /// Execute a recursive action starting from this node. void doExecuteVisitor(simulation::Visitor* action, bool=false); // VisitorScheduler can use doExecuteVisitor() method friend class simulation::VisitorScheduler; }; } // namespace tree } // namespace simulation } // namespace sofa #endif
hdeling/sofa
SofaKernel/modules/SofaSimulationTree/GNode.h
C
lgpl-2.1
6,689
<? if(isset($_GET["lng"])) { $lng_id = $_GET["lng"]; } else { if(isset($_COOKIE["lang"])) { $lng_id = $_COOKIE["lang"]; } else { $lng_id = 0; } } global $main_url; $m_id=cookie_get("mem_id"); $m_pass=cookie_get("mem_pass"); login_test($m_id,$m_pass); $p_id=form_get("p_id"); $sql_query="select * from members where mem_id='$p_id'"; $mem=sql_execute($sql_query,'get'); $sql_query="select * from profiles where mem_id='$p_id'"; $pro=sql_execute($sql_query,'get'); $sql_query="select * from musicprofile where mem_id='$p_id'"; $musicpro=sql_execute($sql_query,'get'); show_header(); ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="36%" valign="top"><table width="100%" border="0" cellspacing="3" cellpadding="3"> <tr> <td colspan="2" style="padding-left: 5"> <strong><? echo musical_band($p_id); ?></strong><br> <span class="small"><? echo musical_genre($p_id); ?></span> </td> </tr> <tr> <td width="50%" align="center"><? echo show_profile_photo($p_id); ?><br><? echo show_online($p_id); ?> </td> <td width="50%" class="small" valign="middle" style="padding-left: 7"> "<?=stripslashes($musicpro->headline)?>"<br><br> <? echo show_location($p_id); ?><br><>=LNG_PROFILE_ZONE?>: <?=stripslashes($mem->rapzone)?><br><br> <?=LNG_PROFILE_PV?>: <? echo show_views($p_id); ?><br> <?=LNG_PROFILE_LAST_LGIN?>: <? echo show_visit_like("m/d/Y",$p_id); ?> </td> </tr> <tr> <td width="50%" class="body" style="padding-left: 25"> <? echo photo_album_link($p_id); ?></td> <td class="small">&nbsp;</td> </tr> <tr> <td colspan="2" style="height: 20"></td> </tr> </table> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="1%" align="left" valign="top"><img src="images/titleleft.gif" border="0"></td> <td class="hometitle" width="98%" style="padding-left: 7"><b><?=LNG_WHT_CAN_U_DO?></b></td> <td width="2%" align="right" valign="top"><img src="images/titleright.gif" border="0"></td> </tr> </table> <table width="100%" border="0" cellspacing="0" cellpadding="0" class="homelined"> <tr> <td valign="top"> <? if($m_id!=$p_id) { echo "<table width=\"100%\" border=\"0\" cellspacing=\"4\" cellpadding=\"4\" class=\"body\">"; $sql_link="select bmr_id from bmarks where mem_id='$m_id' and type='member' and sec_id='$p_id'"; $res=sql_execute($sql_link,'res'); echo "<tr>"; if(!mysql_num_rows($res)) { echo "<td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=user&act=bmarks&pro=add&sec_id=$p_id&type=member&lng=$lng_id'>" . LNG_BOOKMARKS . "</a></td>"; } else { $bmr=sql_execute($sql_link,'get'); echo "<td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=user&act=bmarks&pro=del&bmr_id=$bmr->bmr_id&lng=$lng_id'>" . LNG_PROFILE_UN_BK_MARK . "</a></td>"; } echo "<td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=messages&act=compose&rec_id=$p_id&lng=$lng_id'>" . LNG_PROFILE_SM . "</a></td>"; echo "</tr>"; $sql_link="select * from network where mem_id='$m_id' and frd_id='$p_id'"; $res=sql_execute($sql_link,'res'); echo "<tr>"; if(mysql_num_rows($res)) { echo "<td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=user&act=friends&pro=remove&frd_id=$p_id&lng=$lng_id'>" . LNG_PROFILE_RFR . "</a></td>"; } else { $bmr=sql_execute($sql_link,'get'); echo "<td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=user&act=friends&pro=add&frd_id=$p_id&lng=$lng_id'>" . LNG_PROFILE_ADD_FRIND . "</a></td>"; } echo "<td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=user&act=intro&p_id=$p_id&lng=$lng_id'>" . LNG_PROFILE_MK_INTRO . "</a></td>"; echo "</tr>"; echo "<tr>"; echo "<td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=user&act=invite_tribe&p_id=$p_id&lng=$lng_id'>" . LNG_PROFILE_ITG . "</a></td>"; $sql_query="select ignore_list from members where mem_id='$m_id'"; $mem=sql_execute($sql_query,'get'); $ignore=split("\|",$mem->ignore_list); $ignore=if_empty($ignore); if($ignore!='') { $status=0; foreach($ignore as $ign) { if($ign==$p_id) { $status=1; break; } }//foreach } else $status=0; if($status==0) { echo "<td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=user&act=ignore&pro=add&p_id=$p_id&lng=$lng_id'>" . LNG_PROFILE_ADD_IGNORE_LST . "</a></td>"; } elseif($status==1) { echo "<td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=user&act=ignore&pro=del&p_id=$p_id&lng=$lng_id'>" . LNG_PROFILE_RFG . "</a></td>"; } echo "</tr>"; echo "</table>"; } else { echo "<table width=\"100%\" border=\"0\" cellspacing=\"4\" cellpadding=\"4\" class=\"body\">"; echo "<tr><td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=user&act=profile&pro=edit&lng=$lng_id'>" . LNG_EDIT_PROFILE . "</a></td>"; echo "<td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=user&act=bmarks&lng=$lng_id'>" . LNG_PROFILE_EDT_BMARK . "</a></td></tr>"; echo "<tr><td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=user&act=ignore&lng=$lng_id'>" . LNG_PROFILE_EDT_I_LST . "</a></td>"; echo "<td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=user&act=listings&lng=$lng_id'>" . LNG_PROFILE_UR_LSTING . "</a></td></tr>"; echo "<tr><td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=user&act=friends&lng=$lng_id'>" . LNG_YOUR_FRIENDS . "</a></td>"; echo "<td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=listing&act=create&lng=$lng_id'>" . LNG_PROFILE_CRT_LISTING . "</a></td></tr>"; echo "<tr><td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=messages&act=inbox&lng=$lng_id'>" . LNG_PROFILE_MSG_CNTR . "</a></td>"; echo "<td style=\"padding-left: 3\"><font size=\"3\" color=\"#FFFFFF\"><strong>&raquo;</strong></font>&nbsp;<a href='index.php?mode=user&act=inv&lng=$lng_id'>" . LNG_INVITE_A_FRIEND . "</a></td></tr>"; echo "</table>"; } ?> </td> </tr> </table> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr><td height="15"></td></tr> <tr> <td class="hometitle" height="20" width="98%" style="padding-left: 7"><? echo ucwords(name_header($p_id,$m_id)); ?>'<?=LNG_PROFILE_GENERAL_INFO?></td> </tr> </table> <table width="100%" border="0" cellspacing="5" cellpadding="3" class="homelined"> <tr> <td valign="top" width="40%"><strong><?=LNG_PROFILE_MS?></strong></td> <td valign="top" width="60%"><? echo member_since_like("F j, Y g:i a",$p_id); ?></td> </tr> <tr> <td valign="top"><strong><?=LNG_PROFILE_BND_WEBSITE?></strong></td> <td valign="top"><?=$pro->website?></td> </tr> <tr> <td valign="top"><strong><?=LNG_PROFILE_BND_MEM?></strong></td> <td valign="top"><?=stripslashes($musicpro->bandmembers)?></td> </tr> <tr> <td valign="top"><strong><?=LNG_PROFILE_INFLU?></strong></td> <td valign="top"><?=stripslashes($musicpro->influences)?></td> </tr> <tr> <td valign="top"><strong><?=LNG_PROFILE_SND_LIKE?></strong></td> <td valign="top"><?=stripslashes($musicpro->soundslike)?></td> </tr> <tr> <td valign="top"><strong><?=LNG_PROFILE_RCD_LVL?></strong></td> <td valign="top"><?=stripslashes($musicpro->recordlabel)?></td> </tr> <tr> <td valign="top"><strong><?=LNG_PROFILE_RCD_TLVL?></strong></td> <td valign="top"><?=stripslashes($musicpro->labeltype)?></td> </tr> </table> </td> <td width="64%" valign="top" style="padding-left: 5"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr><td height="15"></td></tr> <tr> <td align="right" style="padding-right: 7"><? echo auto_play($p_id); ?></td> </tr> <tr><td height="15"></td></tr> <tr> <td align="right" style="padding-right: 7" class="body">[<a href="<?=$main_url?>/blog/<? echo mem_profilenam($p_id); ?>"><strong><?=LNG_PROFILE_RCD_VIEW_A_BLG?></strong></a>]</td> </tr> <tr> <td valign="top"><? echo show_blogs($p_id,3); ?></td> </tr> <? if(!empty($pro->about)) { ?> <tr><td height="5"></td></tr> <tr> <td class="hometitle" height="20" style="padding-left: 7"><?=LNG_ABOUT?> <? echo ucwords(name_header($p_id,$m_id)); ?></td> </tr> <tr><td height="5"></td></tr> <tr> <td align="justify" class="body" style="padding-left: 10"><?=stripslashes($pro->about)?></td> </tr> <? } ?> <tr><td height="5"></td></tr> <tr> <td class="hometitle" height="20" style="padding-left: 7"><? echo ucwords(name_header($p_id,$m_id)); ?>'<?=LNG_PROFILE_FRND?></td> </tr> <tr><td height="5"></td></tr> <tr> <td valign="top"><? echo my_friends($p_id,''); ?></td> </tr> <tr><td height="5"></td></tr> <tr> <td class="hometitle" height="20" style="padding-left: 7"><?=LNG_LISTINGS_FROM?> <? echo ucwords(name_header($p_id,$m_id)); ?> & <?=LNG_FRIENDS?></td> </tr> <tr><td height="5"></td></tr> <tr> <td valign="top" class="body"><? echo show_listings("inprofile",$p_id,''); ?></td> </tr> <tr><td height="5"></td></tr> <tr> <td class="hometitle" height="20" style="padding-left: 7"><?=LNG_PROFILE_TST_FOR?> <? echo ucwords(name_header($p_id,$m_id)); ?></td> </tr> <tr><td height="5"></td></tr> <tr> <td valign="top" class="body"><? echo show_testimonials($p_id,$m_id); ?></td> </tr> <? $sql_query="select mem_id from network where mem_id='$p_id' and frd_id='$m_id'"; $num=sql_execute($sql_query,'num'); if(($num!=0) && ($p_id!=$m_id)) { ?> <tr><td height="5"></td></tr> <tr> <td valign="top" class="body" style="padding-left: 12"> <strong><?=LNG_PROFILE_TELL_OTHER?> <? echo ucwords(name_header($p_id,$m_id)); ?></strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="button" onClick="window.location='index.php?mode=user&act=tst&p_id=<?=$p_id?>&lng=<?=$lng_id?>'" value="<?=LNG_WRITE_TESTIMONIAL?>"> </td> </tr> <? } ?> </table> </td> </tr> </table></td> </tr> <tr> <td>&nbsp;</td> </tr> </table> <? show_footer(); ?>
centaurustech/createaband
profile.php
PHP
lgpl-2.1
12,326
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * 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 * *****************************************************************************/ #ifndef SHAPE_IO_HPP #define SHAPE_IO_HPP // mapnik #include <mapnik/box2d.hpp> #include <mapnik/util/noncopyable.hpp> // boost #include <boost/optional.hpp> // stl #include <memory> #include "dbfile.hpp" #include "shapefile.hpp" struct shape_io : mapnik::util::noncopyable { public: enum shapeType { shape_null = 0, shape_point = 1, shape_polyline = 3, shape_polygon = 5, shape_multipoint = 8, shape_pointz = 11, shape_polylinez = 13, shape_polygonz = 15, shape_multipointz = 18, shape_pointm = 21, shape_polylinem = 23, shape_polygonm = 25, shape_multipointm = 28, shape_multipatch = 31 }; shape_io(std::string const& shape_name, bool open_index=true); ~shape_io(); shape_file& shp(); dbf_file& dbf(); inline boost::optional<shape_file&> index() { if (index_) return boost::optional<shape_file&>(*index_); return boost::optional<shape_file&>(); } inline bool has_index() const { return (index_ && index_->is_open()); } void move_to(std::streampos pos); static void read_bbox(shape_file::record_type & record, mapnik::box2d<double> & bbox); static mapnik::geometry::geometry<double> read_polyline(shape_file::record_type & record); static mapnik::geometry::geometry<double> read_polygon(shape_file::record_type & record); shapeType type_; shape_file shp_; dbf_file dbf_; std::unique_ptr<shape_file> index_; unsigned reclength_; unsigned id_; box2d<double> cur_extent_; static const std::string SHP; static const std::string DBF; static const std::string INDEX; }; #endif //SHAPE_IO_HPP
Airphrame/mapnik
plugins/input/shape/shape_io.hpp
C++
lgpl-2.1
2,745
@charset "utf-8"; /* NHN ([email protected]) */ /* Calendar */ .calendar{position:relative;display:inline-block;*display:inline;font-size:12px} .calendar .btnCalendar{position:relative;width:19px;height:19px;border:0;padding:0;background:url(../img/buttonCalendar.gif) no-repeat center center;cursor:pointer;vertical-align:middle} .calendar .btnCalendar span{position:absolute;width:0;height:0;overflow:hidden;font-size:0;line-height:0;z-index:-1;visibility:hidden} .calendar .layerCalendar{display:none;padding:25px 15px 15px 15px;position:absolute;border:2px solid #737373;background:#fff;color:#333} .calendar .layerCalendar.open{display:block} .calendar .close{position:absolute;top:10px;right:15px;width:17px;height:17px;border:0;padding:0;background:url(../img/buttonCloseLayerX.gif) no-repeat center center;cursor:pointer} .calendar .close span{position:absolute;width:0;height:0;font-size:0;line-height:0;overflow:hidden;z-index:-1;visibility:hidden} .calendar .layerCalendar table{border:0;border-spacing:0;_width:200px} .calendar caption{font-weight:bold;text-align:center;position:relative} .calendar caption span{display:block;position:relative;padding:10px 0 15px 0;zoom:1} .calendar caption .today{font-size:11px;border:0;padding:0;border-bottom:1px solid;background:none;cursor:pointer} .calendar caption .today span{text-decoration:underline} .calendar caption .navi{position:absolute;top:10px;border:0;padding:0;width:17px;height:18px;background-color:transparent;background-image:url(../img/buttonPaginate.gif);background-repeat:no-repeat;cursor:pointer} .calendar caption .navi span{position:absolute;width:0;height:0;overflow:hidden;font-size:0;line-height:0;z-index:-1;visibility:hidden} .calendar caption .navi.prev{left:0;background-position:left top} .calendar caption .navi.next{right:0;background-position:right top} .calendar th, .calendar td{border:0;text-align:center} .calendar th{color:#666;background:#f2f2f2;padding:3px 8px} .calendar td{font-size:11px;padding:3px 8px} .calendar td button{padding:0;border:0;background:none;cursor:pointer;width:20px;font-size:11px;font-family:Tahoma, Sans-serif} .calendar td button.today{font-weight:bold} .calendar td button.book, .calendar td button.active, .calendar tr.active td{background:#ff4747} .calendar tr.active button{background:#ff4747;color:#fff} .calendar tr.active button.active{font-weight:bold} .calendar tr.active .overlap button{background:#fc6;color:#fff} .calendar .sun, .calendar .sun button{color:#ff1a1a} .calendar .overlap button{color:#ccc} .calendar table.month{border-top:1px solid #f2f2f2;border-left:1px solid #f2f2f2} .calendar table.month td{border-right:1px solid #f2f2f2;border-bottom:1px solid #f2f2f2} .calendar table.month td button{width:50px;color:#bababa} .calendar table.month td button.past{color:#333} .calendar table.month td button.active{color:#fff} .contentNavigation .calendar{padding:0 50px;zoom:1} .contentNavigation .calendar .h4{margin:0;display:inline;font-size:18px;vertical-align:middle} .contentNavigation .calendar .prevData, .contentNavigation .calendar .nextData{position:absolute;top:0;border:0;padding:0;width:18px;height:19px;background-color:transparent;background-image:url(../img/buttonPagination.gif);background-repeat:no-repeat;cursor:pointer} .contentNavigation .calendar .prevData{background-position:left top;left:0} .contentNavigation .calendar .nextData{background-position:right top;right:0} .contentNavigation .calendar .prevData span, .contentNavigation .calendar .nextData span{position:absolute;width:0;height:0;overflow:hidden;font-size:0;line-height:0;z-index:-1;visibility:hidden} .contentNavigation .calendar .layerCalendar{top:22px;left:52px}
xpressengine/xe-module-shop
tpl/css/calendar.css
CSS
lgpl-2.1
3,709
/* * wiigee - accelerometerbased gesture recognition * Copyright (C) 2007, 2008 Benjamin Poppinga * * Developed at University of Oldenburg * Contact: [email protected] * * This file is part of wiigee. * * wiigee 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package filter; public class IdleStateFilter extends Filter { private double sensivity; /** * Since an acceleration sensor usually provides information even * if it doesn't move, this filter removes the data if it's in the * idle state. */ public IdleStateFilter() { super(); this.sensivity = 0.1; } public double[] filterAlgorithm(double[] vector) { // calculate values needed for filtering: // absolute value double absvalue = Math.sqrt((vector[0]*vector[0])+ (vector[1]*vector[1])+(vector[2]*vector[2])); // filter formulaes and return values if(absvalue > 1+this.sensivity || absvalue < 1-this.sensivity) { return vector; } else { return null; } } /** * Defines the absolute value when the wiimote should react to acceleration. * This is a parameter for the first of the two filters: idle state * filter. For example: sensivity=0.2 makes the wiimote react to acceleration * where the absolute value is equal or greater than 1.2g. The default value 0.1 * should work well. Only change if you are sure what you're doing. * * @param sensivity * acceleration data values smaller than this value wouldn't be detected. */ public void setSensivity(double sensivity) { this.sensivity = sensivity; } public double getSensivity() { return this.sensivity; } }
orenjp/andgee
andgee2/src/filter/IdleStateFilter.java
Java
lgpl-2.1
2,324
#ifndef LDA_MODEL_H #define LDA_MODEL_H #include <stdlib.h> #include <stdio.h> #include <math.h> #include "lda.h" #include "lda-alpha.h" #include "cokus.h" #define myrand() (double) (((unsigned long) randomMT()) / 4294967296.) #define NUM_INIT 1 void free_lda_model(lda_model*); void save_lda_model(lda_model*, char*); lda_model* new_lda_model(int, int); lda_suffstats* new_lda_suffstats(lda_model* model); void corpus_initialize_ss(lda_suffstats* ss, lda_model* model, corpus* c); void manual_initialize_ss(char *seedfile, lda_suffstats* ss, lda_model* model, corpus* c); void random_initialize_ss(lda_suffstats* ss, lda_model* model); void zero_initialize_ss(lda_suffstats* ss, lda_model* model); void lda_mle(lda_model* model, lda_suffstats* ss, int estimate_alpha); lda_model* load_lda_model(char* model_root); #endif
RenqinCai/lda-c
lda-model.h
C
lgpl-2.1
826
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>adddouble (TokyoCabinet::ADB)</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" /> </head> <body class="standalone-code"> <pre><span class="ruby-comment cmt"># File tokyocabinet-doc.rb, line 1471</span> <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">adddouble</span>(<span class="ruby-identifier">key</span>, <span class="ruby-identifier">num</span>) <span class="ruby-comment cmt"># (native code)</span> <span class="ruby-keyword kw">end</span></pre> </body> </html>
roma/tokyocabinet-ruby
doc/classes/TokyoCabinet/ADB.src/M000159.html
HTML
lgpl-2.1
821
YUI.add('aui-state-interaction-deprecated', function (A, NAME) { var Lang = A.Lang, isBoolean = Lang.isBoolean, isString = Lang.isString, getClassName = A.getClassName, STATE = 'state', CSS_STATE_DEFAULT = getClassName(STATE, 'default'), CSS_STATE_HOVER = getClassName(STATE, 'hover'), CSS_STATE_ACTIVE = getClassName(STATE, 'active'); var StateInteraction = A.Component.create( { NAME: 'stateinteraction', NS: 'StateInteraction', ATTRS: { active: { value: false }, activeState: { value: true, validator: isBoolean }, bubbleTarget: { value: null }, classNames: { value: {} }, 'default': { value: false }, defaultState: { value: true, validator: isBoolean }, hover: { value: false }, hoverState: { value: true, validator: isBoolean }, node: { value: null } }, EXTENDS: A.Plugin.Base, constructor: function(config) { var host = config.host; var node = host; if (A.Widget && host instanceof A.Widget) { node = host.get('contentBox'); } config.node = node; StateInteraction.superclass.constructor.apply(this, arguments); }, prototype: { initializer: function() { var instance = this; var activeClass = instance.get('classNames.active'); var defaultClass = instance.get('classNames.default'); var hoverClass = instance.get('classNames.hover'); instance._CSS_STATES = { active: isString(activeClass) ? activeClass : CSS_STATE_ACTIVE, 'default': isString(defaultClass) ? defaultClass : CSS_STATE_DEFAULT, hover: isString(hoverClass) ? hoverClass : CSS_STATE_HOVER }; if (instance.get('defaultState')) { instance.get('node').addClass(instance._CSS_STATES['default']); } instance._createEvents(); instance._attachInteractionEvents(); }, _attachInteractionEvents: function() { var instance = this; var node = instance.get('node'); node.on('click', instance._fireEvents, instance); node.on('mouseenter', A.rbind(instance._fireEvents, instance, 'mouseover')); node.on('mouseleave', A.rbind(instance._fireEvents, instance, 'mouseout')); instance.after('activeChange', instance._uiSetState); instance.after('hoverChange', instance._uiSetState); instance.after('defaultChange', instance._uiSetState); }, _fireEvents: function(event, officialType) { var instance = this; var bubbleTarget = instance.get('bubbleTarget'); officialType = officialType || event.type; if (bubbleTarget) { bubbleTarget.fire(officialType); } return instance.fire(officialType); }, _createEvents: function() { var instance = this; var bubbleTarget = instance.get('bubbleTarget'); if (bubbleTarget) { instance.addTarget(bubbleTarget); } instance.publish( 'click', { defaultFn: instance._defClickFn, emitFacade: true } ); instance.publish( 'mouseout', { defaultFn: instance._defMouseOutFn, emitFacade: true } ); instance.publish( 'mouseover', { defaultFn: instance._defMouseOverFn, emitFacade: true } ); }, _defClickFn: function(event) { var instance = this; instance.set('active', !instance.get('active')); }, _defMouseOutFn: function() { var instance = this; instance.set('hover', false); }, _defMouseOverFn: function() { var instance = this; instance.set('hover', true); }, _uiSetState: function(event) { var instance = this; var attrName = event.attrName; if (instance.get(attrName + 'State')) { var action = 'addClass'; if (!event.newVal) { action = 'removeClass'; } instance.get('node')[action](instance._CSS_STATES[attrName]); } } } } ); A.namespace('Plugin').StateInteraction = StateInteraction; }, '2.0.0', {"requires": ["aui-base-deprecated", "plugin"]});
FuadEfendi/lpotal
tomcat-7.0.57/webapps/ROOT/html/js/aui/aui-state-interaction-deprecated/aui-state-interaction-deprecated.js
JavaScript
lgpl-2.1
3,989
/* Test of test for initial conversion state. Copyright (C) 2008 Free Software Foundation, Inc. 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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/>. */ /* Written by Bruno Haible <[email protected]>, 2008. */ #include <config.h> #include <wchar.h> #include <locale.h> #include <stdio.h> #include <stdlib.h> #define ASSERT(expr) \ do \ { \ if (!(expr)) \ { \ fprintf (stderr, "%s:%d: assertion failed\n", __FILE__, __LINE__); \ fflush (stderr); \ abort (); \ } \ } \ while (0) int main (int argc, char *argv[]) { static mbstate_t state; ASSERT (mbsinit (&state)); if (argc > 1) { static const char input[1] = "\303"; wchar_t wc; size_t ret; /* configure should already have checked that the locale is supported. */ if (setlocale (LC_ALL, "") == NULL) return 1; ret = mbrtowc (&wc, input, 1, &state); ASSERT (ret == (size_t)(-2)); ASSERT (!mbsinit (&state)); } return 0; }
Distrotech/regex
tests/test-mbsinit.c
C
lgpl-2.1
1,700
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Designer 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$ ** ****************************************************************************/ #ifndef CONTAINERWIDGER_TASKMENU_H #define CONTAINERWIDGER_TASKMENU_H #include <qdesigner_taskmenu_p.h> #include <shared_enums_p.h> #include <extensionfactory_p.h> #include <QtCore/QPointer> QT_BEGIN_NAMESPACE class QDesignerFormWindowInterface; class QDesignerFormEditorInterface; class QDesignerContainerExtension; class QAction; class QMdiArea; class QWorkspace; class QMenu; class QWizard; namespace qdesigner_internal { class PromotionTaskMenu; // ContainerWidgetTaskMenu: Task menu for containers with extension class ContainerWidgetTaskMenu: public QDesignerTaskMenu { Q_OBJECT public: explicit ContainerWidgetTaskMenu(QWidget *widget, ContainerType type, QObject *parent = 0); virtual ~ContainerWidgetTaskMenu(); virtual QAction *preferredEditAction() const; virtual QList<QAction*> taskActions() const; private slots: void removeCurrentPage(); void addPage(); void addPageAfter(); protected: QDesignerContainerExtension *containerExtension() const; QList<QAction*> &containerActions() { return m_taskActions; } int pageCount() const; private: QDesignerFormWindowInterface *formWindow() const; private: static QString pageMenuText(ContainerType ct, int index, int count); bool canDeletePage() const; const ContainerType m_type; QWidget *m_containerWidget; QDesignerFormEditorInterface *m_core; PromotionTaskMenu *m_pagePromotionTaskMenu; QAction *m_pageMenuAction; QMenu *m_pageMenu; QList<QAction*> m_taskActions; QAction *m_actionDeletePage; }; // WizardContainerWidgetTaskMenu: Provide next/back since QWizard // has modes in which the "Back" button is not visible. class WizardContainerWidgetTaskMenu : public ContainerWidgetTaskMenu { Q_OBJECT public: explicit WizardContainerWidgetTaskMenu(QWizard *w, QObject *parent = 0); virtual QList<QAction*> taskActions() const; private: QAction *m_nextAction; QAction *m_previousAction; }; // MdiContainerWidgetTaskMenu: Provide tile/cascade for MDI containers in addition class MdiContainerWidgetTaskMenu : public ContainerWidgetTaskMenu { Q_OBJECT public: explicit MdiContainerWidgetTaskMenu(QMdiArea *m, QObject *parent = 0); explicit MdiContainerWidgetTaskMenu(QWorkspace *m, QObject *parent = 0); virtual QList<QAction*> taskActions() const; private: void initializeActions(); QAction *m_nextAction; QAction *m_previousAction; QAction *m_tileAction; QAction *m_cascadeAction; }; class ContainerWidgetTaskMenuFactory: public QExtensionFactory { Q_OBJECT public: explicit ContainerWidgetTaskMenuFactory(QDesignerFormEditorInterface *core, QExtensionManager *extensionManager = 0); protected: virtual QObject *createExtension(QObject *object, const QString &iid, QObject *parent) const; private: QDesignerFormEditorInterface *m_core; }; } // namespace qdesigner_internal QT_END_NAMESPACE #endif // CONTAINERWIDGER_TASKMENU_H
nonrational/qt-everywhere-opensource-src-4.8.6
tools/designer/src/components/taskmenu/containerwidget_taskmenu.h
C
lgpl-2.1
4,940
/**************************************************************************** ** ** 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. ** ****************************************************************************/ #ifndef NEWDIALOG_H #define NEWDIALOG_H #include "../iwizardfactory.h" #include <QDialog> #include <QIcon> #include <QList> QT_BEGIN_NAMESPACE class QAbstractProxyModel; class QModelIndex; class QSortFilterProxyModel; class QPushButton; class QStandardItem; class QStandardItemModel; class QStringList; QT_END_NAMESPACE namespace Core { namespace Internal { namespace Ui { class NewDialog; } class NewDialog : public QDialog { Q_OBJECT public: explicit NewDialog(QWidget *parent); virtual ~NewDialog(); void setWizardFactories(QList<IWizardFactory*> factories, const QString &defaultLocation, const QVariantMap &extraVariables); void showDialog(); QString selectedPlatform() const; protected: bool event(QEvent *); private slots: void currentCategoryChanged(const QModelIndex &); void currentItemChanged(const QModelIndex &); void okButtonClicked(); void reject(); void updateOkButton(); void setSelectedPlatform(const QString &platform); private: Core::IWizardFactory *currentWizardFactory() const; void addItem(QStandardItem *topLevelCategoryItem, IWizardFactory *factory); void saveState(); static QString m_lastCategory; Ui::NewDialog *m_ui; QStandardItemModel *m_model; QAbstractProxyModel *m_twoLevelProxyModel; QSortFilterProxyModel *m_filterProxyModel; QPushButton *m_okButton; QIcon m_dummyIcon; QList<QStandardItem*> m_categoryItems; QString m_defaultLocation; QVariantMap m_extraVariables; }; } // namespace Internal } // namespace Core #endif // NEWDIALOG_H
maui-packages/qt-creator
src/plugins/coreplugin/dialogs/newdialog.h
C
lgpl-2.1
3,045
/* * ngfd - Non-graphic feedback daemon * * Copyright (C) 2010 Nokia Corporation. * Contact: Xun Chen <[email protected]> * * This work 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 work 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 work; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <ngf/hook.h> #include <glib.h> #include <string.h> typedef struct _NHookSlot { NHook *hook; int priority; NHookCallback callback; void *userdata; } NHookSlot; static void n_hook_slot_free (NHookSlot *slot) { if (!slot) return; g_slice_free (NHookSlot, slot); } void n_hook_init (NHook *hook) { memset (hook, 0, sizeof (NHook)); } static int n_hook_sort_slot_cb (gconstpointer in_a, gconstpointer in_b) { NHookSlot *a = (NHookSlot*) in_a; NHookSlot *b = (NHookSlot*) in_b; if (a->priority > b->priority) return -1; else if (b->priority > a->priority) return 1; return 0; } int n_hook_connect (NHook *hook, int priority, NHookCallback callback, void *userdata) { NHookSlot *slot = NULL; if (!hook || !callback) return FALSE; slot = g_slice_new0 (NHookSlot); slot->hook = hook; slot->callback = callback; slot->userdata = userdata; slot->priority = priority; hook->slots = g_list_append (hook->slots, slot); hook->slots = g_list_sort (hook->slots, n_hook_sort_slot_cb); return TRUE; } void n_hook_disconnect (NHook *hook, NHookCallback callback, void *userdata) { GList *iter = NULL; if (!hook || !callback) return; for (iter = g_list_first (hook->slots); iter; iter = g_list_next (iter)) { NHookSlot *slot = (NHookSlot*) iter->data; if (slot->callback == callback && slot->userdata == userdata) { hook->slots = g_list_remove (hook->slots, slot); n_hook_slot_free (slot); return; } } } int n_hook_fire (NHook *hook, void *data) { GList *iter = NULL; if (!hook) return FALSE; for (iter = g_list_first (hook->slots); iter; iter = g_list_next (iter)) { NHookSlot *slot = (NHookSlot*) iter->data; slot->callback (hook, data, slot->userdata); } return TRUE; }
android-808/ngfd
src/ngf/hook.c
C
lgpl-2.1
2,843
/** * Solve * - \Delta u = 1 */ #include "FemusInit.hpp" #include "MultiLevelSolution.hpp" #include "MultiLevelProblem.hpp" #include "VTKWriter.hpp" #include "NonLinearImplicitSystem.hpp" #include "NumericVector.hpp" #include "CurrentElem.hpp" #include "ElemType_template.hpp" #include "Assemble_jacobian.hpp" #include "Assemble_unknown_jacres.hpp" using namespace femus; /// @todo Laplace beltrami on a flat domain does not give the same numbers, need to check that double InitialValueU(const MultiLevelProblem * ml_prob, const std::vector < double >& x, const char name[]) { return 0.; } bool SetBoundaryCondition(const MultiLevelProblem * ml_prob, const std::vector < double >& x, const char name[], double& value, const int face_name, const double time) { bool dirichlet = false; value = 0.; const double tolerance = 1.e-5; if (ml_prob->GetMLMesh()->GetDimension() == 1 ) { if (face_name == 1) { dirichlet = true; value = 0.; //Dirichlet value } else if (face_name == 2) { dirichlet = false; value = 1.; //Neumann value } } if (ml_prob->GetMLMesh()->GetDimension() == 2 ) { if (face_name == 1) { dirichlet = true; value = 0.; } else if (face_name == 2) { dirichlet = true; value = 0.; } else if (face_name == 3) { dirichlet = true; value = 0.; } else if (face_name == 4) { dirichlet = false; value = 1. * ( x[0] * x[0]); //Neumann function, here we specify the WHOLE normal derivative, which is a scalar, not each Cartesian component } } return dirichlet; } //====== NEUMANN LOOP 1D ============================================= void neumann_loop_1d(const MultiLevelProblem * ml_prob, const Mesh * msh, const MultiLevelSolution * ml_sol, const unsigned iel, CurrentElem < double > & geom_element, const unsigned xType, const std::string solname_u, const unsigned solFEType_u, std::vector< double > & Res ) { double grad_u_dot_n; for (unsigned jface = 0; jface < msh->GetElementFaceNumber(iel); jface++) { geom_element.set_coords_at_dofs_bdry_3d(iel, jface, xType); geom_element.set_elem_center_bdry_3d(); std::vector < double > xx_face_elem_center(3, 0.); xx_face_elem_center = geom_element.get_elem_center_bdry_3d(); const int boundary_index = msh->el->GetFaceElementIndex(iel, jface); if ( boundary_index < 0) { //I am on the boundary unsigned int face = - (boundary_index + 1); bool is_dirichlet = ml_sol->GetBdcFunctionMLProb()(ml_prob, xx_face_elem_center, solname_u.c_str(), grad_u_dot_n, face, 0.); //we have to be careful here, because in GenerateBdc those coordinates are passed as NODE coordinates, //while here we pass the FACE ELEMENT CENTER coordinates. // So, if we use this for enforcing space-dependent Dirichlet or Neumann values, we need to be careful! if ( !(is_dirichlet) && (grad_u_dot_n != 0.) ) { //dirichlet == false and nonhomogeneous Neumann unsigned n_dofs_face = msh->GetElementFaceDofNumber(iel, jface, solFEType_u); for (unsigned i = 0; i < n_dofs_face; i++) { unsigned int i_vol = msh->GetLocalFaceVertexIndex(iel, jface, i); Res[i_vol] += grad_u_dot_n /* * phi[node] = 1. */; } } } } } template < class real_num, class real_num_mov > void neumann_loop_2d3d(const MultiLevelProblem * ml_prob, const Mesh * msh, const MultiLevelSolution * ml_sol, const unsigned iel, CurrentElem < double > & geom_element, const unsigned solType_coords, const std::string solname_u, const unsigned solFEType_u, std::vector< double > & Res, //----------- std::vector < std::vector < /*const*/ elem_type_templ_base<real_num, real_num_mov> * > > elem_all, const unsigned dim, const unsigned space_dim, const unsigned max_size ) { /// @todo - should put these outside the iel loop -- std::vector < std::vector < double > > JacI_iqp_bdry(space_dim); std::vector < std::vector < double > > Jac_iqp_bdry(dim-1); for (unsigned d = 0; d < Jac_iqp_bdry.size(); d++) { Jac_iqp_bdry[d].resize(space_dim); } for (unsigned d = 0; d < JacI_iqp_bdry.size(); d++) { JacI_iqp_bdry[d].resize(dim-1); } double detJac_iqp_bdry; double weight_iqp_bdry = 0.; // --- //boundary state shape functions vector <double> phi_u_bdry; vector <double> phi_u_x_bdry; phi_u_bdry.reserve(max_size); phi_u_x_bdry.reserve(max_size * space_dim); // --- double grad_u_dot_n; for (unsigned jface = 0; jface < msh->GetElementFaceNumber(iel); jface++) { geom_element.set_coords_at_dofs_bdry_3d(iel, jface, solType_coords); geom_element.set_elem_center_bdry_3d(); const unsigned ielGeom_bdry = msh->GetElementFaceType(iel, jface); std::vector < double > xx_face_elem_center(3, 0.); xx_face_elem_center = geom_element.get_elem_center_bdry_3d(); const int boundary_index = msh->el->GetFaceElementIndex(iel, jface); if ( boundary_index < 0) { //I am on the boundary unsigned int face = - (boundary_index + 1); bool is_dirichlet = ml_sol->GetBdcFunctionMLProb()(ml_prob, xx_face_elem_center, solname_u.c_str(), grad_u_dot_n, face, 0.); //we have to be careful here, because in GenerateBdc those coordinates are passed as NODE coordinates, //while here we pass the FACE ELEMENT CENTER coordinates. // So, if we use this for enforcing space-dependent Dirichlet or Neumann values, we need to be careful! if ( !(is_dirichlet) /* && (grad_u_dot_n != 0.)*/ ) { //dirichlet == false and nonhomogeneous Neumann const unsigned n_gauss_bdry = ml_prob->GetQuadratureRule(ielGeom_bdry).GetGaussPointsNumber(); for(unsigned ig_bdry = 0; ig_bdry < n_gauss_bdry; ig_bdry++) { elem_all[ielGeom_bdry][solType_coords]->JacJacInv(geom_element.get_coords_at_dofs_bdry_3d(), ig_bdry, Jac_iqp_bdry, JacI_iqp_bdry, detJac_iqp_bdry, space_dim); // elem_all[ielGeom_bdry][solType_coords]->compute_normal(Jac_iqp_bdry, normal); weight_iqp_bdry = detJac_iqp_bdry * ml_prob->GetQuadratureRule(ielGeom_bdry).GetGaussWeightsPointer()[ig_bdry]; elem_all[ielGeom_bdry][solFEType_u ]->shape_funcs_current_elem(ig_bdry, JacI_iqp_bdry, phi_u_bdry, phi_u_x_bdry, boost::none, space_dim); unsigned n_dofs_face = msh->GetElementFaceDofNumber(iel, jface, solFEType_u); for (unsigned i_bdry = 0; i_bdry < n_dofs_face; i_bdry++) { unsigned int i_vol = msh->GetLocalFaceVertexIndex(iel, jface, i_bdry); Res[i_vol] += weight_iqp_bdry * grad_u_dot_n * phi_u_bdry[i_bdry]; } } } } } } template < class real_num, class real_num_mov > void AssembleProblemDirNeu(MultiLevelProblem& ml_prob); int main(int argc, char** args) { // init Petsc-MPI communicator FemusInit mpinit(argc, args, MPI_COMM_WORLD); // ======= Files ======================== const bool use_output_time_folder = false; const bool redirect_cout_to_file = false; Files files; files.CheckIODirectories(use_output_time_folder); files.RedirectCout(redirect_cout_to_file); // ======= Quad Rule ======================== std::string fe_quad_rule("seventh"); // ======= Mesh ================== std::vector<std::string> mesh_files; mesh_files.push_back("Mesh_1_x_dir_neu_fine.med"); // mesh_files.push_back("Mesh_2_xy_boundaries_groups_4x4.med"); // mesh_files.push_back("Mesh_1_x_all_dir.med"); // mesh_files.push_back("Mesh_1_y_all_dir.med"); // mesh_files.push_back("Mesh_1_z_all_dir.med"); // mesh_files.push_back("Mesh_2_xz_all_dir.med"); // mesh_files.push_back("Mesh_2_yz_all_dir.med"); // mesh_files.push_back("Mesh_3_xyz_all_dir.med"); // mesh_files.push_back("dome_tri.med"); // mesh_files.push_back("dome_quad.med"); // mesh_files.push_back("disk_quad.med"); // mesh_files.push_back("disk_quad_45x.med"); // mesh_files.push_back("disk_quad_90x.med"); // mesh_files.push_back("disk_tri.med"); // mesh_files.push_back("disk_tri_45x.med"); // mesh_files.push_back("disk_tri_90x.med"); for (unsigned int m = 0; m < mesh_files.size(); m++) { // ======= Mesh ================== // define multilevel mesh MultiLevelMesh ml_mesh; double scalingFactor = 1.; const bool read_groups = true; //with this being false, we don't read any group at all. Therefore, we cannot even read the boundary groups that specify what are the boundary faces, for the boundary conditions const bool read_boundary_groups = true; std::string mesh_file_tot = "./input/" + mesh_files[m]; ml_mesh.ReadCoarseMesh(mesh_file_tot.c_str(), fe_quad_rule.c_str(), scalingFactor, read_groups, read_boundary_groups); // ml_mesh.GenerateCoarseBoxMesh(2,0,0,0.,1.,0.,0.,0.,0.,EDGE3,fe_quad_rule.c_str()); // ml_mesh.GenerateCoarseBoxMesh(0,2,0,0.,0.,0.,1.,0.,0.,EDGE3,fe_quad_rule.c_str()); unsigned numberOfUniformLevels = /*1*/4; unsigned numberOfSelectiveLevels = 0; ml_mesh.RefineMesh(numberOfUniformLevels , numberOfUniformLevels + numberOfSelectiveLevels, NULL); ml_mesh.EraseCoarseLevels(numberOfUniformLevels + numberOfSelectiveLevels - 1); ml_mesh.PrintInfo(); // ======= Solution ================== MultiLevelSolution ml_sol(&ml_mesh); ml_sol.SetWriter(VTK); ml_sol.GetWriter()->SetDebugOutput(true); // ======= Problem ======================== // define the multilevel problem attach the ml_sol object to it MultiLevelProblem ml_prob(&ml_sol); // add variables to ml_sol ml_sol.AddSolution("u", LAGRANGE, FIRST/*DISCONTINUOUS_POLYNOMIAL, ZERO*/); // ======= Solution: Initial Conditions ================== ml_sol.Initialize("All"); // initialize all variables to zero ml_sol.Initialize("u", InitialValueU, & ml_prob); // ======= Solution: Boundary Conditions ================== ml_sol.AttachSetBoundaryConditionFunction(SetBoundaryCondition); ml_sol.GenerateBdc("u", "Steady", & ml_prob); // ======= Problem, II ======================== ml_prob.SetFilesHandler(&files); ml_prob.SetQuadratureRuleAllGeomElems(fe_quad_rule); ml_prob.set_all_abstract_fe_multiple(); // std::vector < std::vector < const elem_type_templ_base<double, double> * > > elem_all = ml_prob.evaluate_all_fe<double, double>(); // ======= System ======================== // add system in ml_prob as a Linear Implicit System NonLinearImplicitSystem& system = ml_prob.add_system < NonLinearImplicitSystem > ("Laplace"); system.SetDebugNonlinear(true); system.AddSolutionToSystemPDE("u"); // attach the assembling function to system system.SetAssembleFunction(AssembleProblemDirNeu<double, double>); // system.SetMaxNumberOfLinearIterations(2); // initialize and solve the system system.SetMgType(V_CYCLE/*F_CYCLE*//*M_CYCLE*/); //it doesn't matter if I use only 1 level system.SetOuterSolver(GMRES); system.init(); system.MGsolve(); // ======= Print ======================== // print solutions const std::string print_order = "biquadratic"; //"linear", "quadratic", "biquadratic" std::vector < std::string > variablesToBePrinted; variablesToBePrinted.push_back("all"); ml_sol.GetWriter()->Write(mesh_files[m], files.GetOutputPath(), print_order.c_str(), variablesToBePrinted); } return 0; } template < class real_num, class real_num_mov > void AssembleProblemDirNeu(MultiLevelProblem& ml_prob) { NonLinearImplicitSystem* mlPdeSys = &ml_prob.get_system<NonLinearImplicitSystem> ("Laplace"); const unsigned level = mlPdeSys->GetLevelToAssemble(); const bool assembleMatrix = mlPdeSys->GetAssembleMatrix(); Mesh* msh = ml_prob._ml_msh->GetLevel(level); elem* el = msh->el; MultiLevelSolution* ml_sol = ml_prob._ml_sol; Solution* sol = ml_prob._ml_sol->GetSolutionLevel(level); LinearEquationSolver* pdeSys = mlPdeSys->_LinSolver[level]; SparseMatrix* JAC = pdeSys->_KK; NumericVector* RES = pdeSys->_RES; const unsigned dim = msh->GetDimension(); unsigned dim2 = (3 * (dim - 1) + !(dim - 1)); const unsigned maxSize = static_cast< unsigned >(ceil(pow(3, dim))); unsigned iproc = msh->processor_id(); //=============== Geometry ======================================== unsigned xType = BIQUADR_FE; // the FE for the domain need not be biquadratic CurrentElem < double > geom_element(dim, msh); // must be adept if the domain is moving, otherwise double constexpr unsigned int space_dim = 3; //*************************************************** //******************** quadrature ******************************* double jacXweight_qp; //********************* unknowns *********************** //*************************************************** const int n_vars = mlPdeSys->GetSolPdeIndex().size(); std::cout << "************" << n_vars << "************"; std::vector <double> phi_u; std::vector <double> phi_u_x; std::vector <double> phi_u_xx; phi_u.reserve(maxSize); phi_u_x.reserve(maxSize * space_dim); phi_u_xx.reserve(maxSize * dim2); const std::string solname_u = "u"; unsigned solIndex_u; solIndex_u = ml_sol->GetIndex(solname_u.c_str()); unsigned solFEType_u = ml_sol->GetSolutionType(solIndex_u); unsigned solPdeIndex_u; solPdeIndex_u = mlPdeSys->GetSolPdeIndex(solname_u.c_str()); std::vector < double > sol_u; sol_u.reserve(maxSize); std::vector< int > l2GMap_u; l2GMap_u.reserve(maxSize); //*************************************************** //*************************************************** //*************************************************** //********* WHOLE SET OF VARIABLES ****************** std::vector< int > l2GMap_AllVars; l2GMap_AllVars.reserve(n_vars*maxSize); // local to global mapping std::vector< double > Res; Res.reserve(n_vars*maxSize); // local redidual vector std::vector < double > Jac; Jac.reserve(n_vars*maxSize * n_vars*maxSize); //*************************************************** RES->zero(); if (assembleMatrix) JAC->zero(); //*************************************************** std::vector < std::vector < real_num_mov > > JacI_qp(space_dim); std::vector < std::vector < real_num_mov > > Jac_qp(dim); for (unsigned d = 0; d < dim; d++) { Jac_qp[d].resize(space_dim); } for (unsigned d = 0; d < space_dim; d++) { JacI_qp[d].resize(dim); } real_num_mov detJac_qp; std::vector < std::vector < real_num_mov > > JacJacT(dim); for (unsigned d = 0; d < dim; d++) { JacJacT[d].resize(dim); } std::vector < std::vector < real_num_mov > > JacJacT_inv(dim); for (unsigned d = 0; d < dim; d++) { JacJacT_inv[d].resize(dim); } //prepare Abstract quantities for all fe fams for all geom elems: all quadrature evaluations are performed beforehand in the main function std::vector < std::vector < /*const*/ elem_type_templ_base<real_num, real_num_mov> * > > elem_all; ml_prob.get_all_abstract_fe(elem_all); //*************************************************** // element loop: each process loops only on the elements that owns for (int iel = msh->_elementOffset[iproc]; iel < msh->_elementOffset[iproc + 1]; iel++) { geom_element.set_coords_at_dofs_and_geom_type(iel, xType); const short unsigned ielGeom = geom_element.geom_type(); //**************** state **************************** unsigned nDof_u = msh->GetElementDofNumber(iel, solFEType_u); sol_u .resize(nDof_u); l2GMap_u.resize(nDof_u); // local storage of global mapping and solution for (unsigned i = 0; i < sol_u.size(); i++) { unsigned solDof_u = msh->GetSolutionDof(i, iel, solFEType_u); sol_u[i] = (*sol->_Sol[solIndex_u])(solDof_u); l2GMap_u[i] = pdeSys->GetSystemDof(solIndex_u, solPdeIndex_u, i, iel); } //*************************************************** //******************** ALL VARS ********************* unsigned nDof_AllVars = nDof_u; int nDof_max = nDof_u; // TODO COMPUTE MAXIMUM maximum number of element dofs for one scalar variable Res.resize(nDof_AllVars); std::fill(Res.begin(), Res.end(), 0.); Jac.resize(nDof_AllVars * nDof_AllVars); std::fill(Jac.begin(), Jac.end(), 0.); l2GMap_AllVars.resize(0); l2GMap_AllVars.insert(l2GMap_AllVars.end(),l2GMap_u.begin(),l2GMap_u.end()); //*************************************************** //========= BOUNDARY ================== if (dim == 1) neumann_loop_1d(& ml_prob, msh, ml_sol, iel, geom_element, xType, solname_u, solFEType_u, Res ); if (dim == 2 || dim == 3) neumann_loop_2d3d(& ml_prob, msh, ml_sol, iel, geom_element, xType, solname_u, solFEType_u, Res, elem_all, dim, space_dim, maxSize ); //========= VOLUME ================== //========= gauss value quantities ================== std::vector<double> sol_u_x_gss(space_dim); std::fill(sol_u_x_gss.begin(), sol_u_x_gss.end(), 0.); //=================================================== // *** Quadrature point loop *** for (unsigned i_qp = 0; i_qp < ml_prob.GetQuadratureRule(ielGeom).GetGaussPointsNumber(); i_qp++) { // *** get gauss point weight, test function and test function partial derivatives *** // msh->_finiteElement[ielGeom][solFEType_u]->Jacobian(geom_element.get_coords_at_dofs_3d(), i_qp, weight, phi_u, phi_u_x, boost::none /*phi_u_xx*/); elem_all[ielGeom][xType]->JacJacInv(geom_element.get_coords_at_dofs_3d(), i_qp, Jac_qp, JacI_qp, detJac_qp, space_dim); jacXweight_qp = detJac_qp * ml_prob.GetQuadratureRule(ielGeom).GetGaussWeightsPointer()[i_qp]; elem_all[ielGeom][solFEType_u]->shape_funcs_current_elem(i_qp, JacI_qp, phi_u, phi_u_x, boost::none /*phi_u_xx*/, space_dim); elem_all[ielGeom][xType]->jac_jacT(Jac_qp, JacJacT, space_dim); elem_all[ielGeom][xType]->jac_jacT_inv(JacJacT, JacJacT_inv, space_dim); //-------------- std::fill(sol_u_x_gss.begin(), sol_u_x_gss.end(), 0.); for (unsigned i = 0; i < nDof_u; i++) { // sol_u_gss += sol_u[i] * phi_u[i]; for (unsigned d = 0; d < sol_u_x_gss.size(); d++) sol_u_x_gss[d] += sol_u[i] * phi_u_x[i * space_dim + d]; } //-------------- //==========FILLING WITH THE EQUATIONS =========== // *** phi_i loop *** for (unsigned i = 0; i < nDof_max; i++) { //-------------- double laplace_res_du_u_i = 0.; if ( i < nDof_u ) { for (unsigned kdim = 0; kdim < space_dim; kdim++) { laplace_res_du_u_i += phi_u_x [i * space_dim + kdim] * sol_u_x_gss[kdim]; } } //-------------- //-------------- double laplace_beltrami_res_du_u_i = 0.; if ( i < nDof_u ) { for (unsigned kdim = 0; kdim < dim; kdim++) { for (unsigned ldim = 0; ldim < dim; ldim++) { laplace_beltrami_res_du_u_i += elem_all[ielGeom][solFEType_u]->get_dphidxi_ref(kdim, i_qp, i) * JacJacT_inv[kdim][ldim] /*phi_u_x [i * space_dim + kdim]*/ * sol_u_x_gss[ldim]; } } } //-------------- //======================Residuals======================= // FIRST ROW if (i < nDof_u) Res[0 + i] += jacXweight_qp * ( phi_u[i] * ( 1. ) - laplace_res_du_u_i); // if (i < nDof_u) Res[0 + i] += jacXweight_qp * ( phi_u[i] * ( 1. ) - laplace_beltrami_res_du_u_i); //======================Residuals======================= if (assembleMatrix) { // *** phi_j loop *** for (unsigned j = 0; j < nDof_max; j++) { //-------------- double laplace_mat_du_u_i_j = 0.; if ( i < nDof_u && j < nDof_u ) { for (unsigned kdim = 0; kdim < space_dim; kdim++) { laplace_mat_du_u_i_j += phi_u_x [i * space_dim + kdim] * phi_u_x [j * space_dim + kdim]; } } //-------------- //-------------- double laplace_beltrami_mat_du_u_i_j = 0.; if ( i < nDof_u && j < nDof_u ) { for (unsigned kdim = 0; kdim < dim; kdim++) { for (unsigned ldim = 0; ldim < dim; ldim++) { laplace_beltrami_mat_du_u_i_j += elem_all[ielGeom][solFEType_u]->get_dphidxi_ref(kdim,i_qp,i)/*phi_u_x [i * space_dim + kdim]*/ * JacJacT_inv[kdim][ldim] * elem_all[ielGeom][solFEType_u]->get_dphidxi_ref(ldim,i_qp,j)/*phi_u_x [j * space_dim + ldim]*/; } } } //-------------- //============ delta_state row ============================ //DIAG BLOCK delta_state - state if ( i < nDof_u && j < nDof_u ) Jac[ (0 + i) * nDof_AllVars + (0 + j) ] += jacXweight_qp * laplace_mat_du_u_i_j; // if ( i < nDof_u && j < nDof_u ) Jac[ (0 + i) * nDof_AllVars + (0 + j) ] += jacXweight_qp * laplace_beltrami_mat_du_u_i_j; ///@todo On a flat domain, this must coincide with the standard Laplacian, so we can do a double check with this } // end phi_j loop } // endif assemble_matrix } // end phi_i loop } // end gauss point loop RES->add_vector_blocked(Res, l2GMap_AllVars); if (assembleMatrix) { JAC->add_matrix_blocked(Jac, l2GMap_AllVars, l2GMap_AllVars); } } //end element loop for each process RES->close(); if (assembleMatrix) JAC->close(); //print JAC and RES to files const unsigned nonlin_iter = 0/*mlPdeSys->GetNonlinearIt()*/; assemble_jacobian< double, double >::print_global_jacobian(assembleMatrix, ml_prob, JAC, nonlin_iter); assemble_jacobian< double, double >::print_global_residual(ml_prob, RES, nonlin_iter); // ***************** END ASSEMBLY ******************* return; }
FeMTTU/femus
applications/2021_fall/aderezende/aderezende.cpp
C++
lgpl-2.1
24,664
/*************************************************************************** * Copyright © 2012 José Manuel Santamaría Lema <[email protected]> * * * * 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. * ***************************************************************************/ #ifndef KRECATEGORIESLISTWIDGET_H #define KRECATEGORIESLISTWIDGET_H #include <QWidget> #include "kregenericlistwidget.h" class Element; class QStandardItem; class KreCategoriesListWidget : public KreGenericListWidget { Q_OBJECT public: KreCategoriesListWidget( QWidget *parent, RecipeDB *db ); protected slots: virtual void createCategory( const Element & category, int parent_id ); virtual void removeCategory( int id ); protected: virtual int elementCount(); virtual void load(int limit, int offset); virtual void cancelLoad(){} virtual int idColumn(); void populate ( QStandardItem * item, int id ); }; #endif //KRECATEGORIESLISTWIDGET_H
eliovir/krecipes
src/widgets/krecategorieslistwidget.h
C
lgpl-2.1
1,277
/* Copyright (C) 2011 Fredrik Johansson This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <http://www.gnu.org/licenses/>. */ #include "fmpz_mat.h" void fmpz_mat_scalar_divexact_si(fmpz_mat_t B, const fmpz_mat_t A, slong c) { slong i, j; for (i = 0; i < A->r; i++) for (j = 0; j < A->c; j++) fmpz_divexact_si(fmpz_mat_entry(B,i,j), fmpz_mat_entry(A,i,j), c); }
dsroche/flint2
fmpz_mat/scalar_divexact_si.c
C
lgpl-2.1
649
/** * @author Marcos Portnoi * @date August 2013 * * @copyright Copyright (C) 2013 University of Delaware. * @copyright QCNSim uses elements of TARVOS simulator, Copyright (C) 2005, 2006, 2007 Marcos Portnoi. * @par * This file is part of QCNSim. QCNSim is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version.<br> * QCNSim 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.<br> * You should have received a copy of the GNU Lesser General Public License * along with QCNSim. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "TrafficGenerator.h" #include "EventType.h" #include "ProtocolDataUnit.h" #include <memory> /** * @brief ConstantRateTrafficGenerator class. * * @par Description * This class implements a constant-rate traffic generator (or a CBR - Constant Bit Rate generator). * Events generated from this class will be distributed in time according to a constant, fixed number. * */ class ConstantRateTrafficGenerator: public TrafficGenerator { private: double interval; //!< Fixed, constant time interval for this generator. public: ConstantRateTrafficGenerator(SimulatorGlobals &simulatorGlobals, Scheduler &scheduler, EventType eventType, std::shared_ptr<Entity> tokenContents, std::shared_ptr<Entity> source, std::shared_ptr<Entity> destination, int priority, double interval); std::shared_ptr<Token> createInstanceTrafficEvent(bool recordRoute = false) override; std::shared_ptr<Token> createInstanceTrafficEvent(std::shared_ptr<Entity> tokenContents, bool recordRoute = false) override; std::shared_ptr<Token> createInstanceTrafficEvent(std::vector<std::shared_ptr<Entity>> explicitRoute, bool recordRoute = false) override; std::shared_ptr<Token> createInstanceTrafficEvent(std::shared_ptr<Entity> tokenContents, std::vector<std::shared_ptr<Entity>> explicitRoute, bool recordRoute = false) override; std::shared_ptr<ProtocolDataUnit> createInstanceTrafficEventPdu(unsigned int pduSize, bool recordRoute = false) override; std::shared_ptr<ProtocolDataUnit> createInstanceTrafficEventPdu(unsigned int pduSize, std::shared_ptr<Entity> tokenContents, bool recordRoute = false) override; std::shared_ptr<ProtocolDataUnit> createInstanceTrafficEventPdu(unsigned int pduSize, std::vector<std::shared_ptr<Entity>> explicitRoute, bool recordRoute = false) override; std::shared_ptr<ProtocolDataUnit> createInstanceTrafficEventPdu(unsigned int pduSize, std::shared_ptr<Entity> tokenContents, std::vector<std::shared_ptr<Entity>> explicitRoute, bool recordRoute = false) override; double getInterval() const; };
locksmithone/qcnsim
trunk/QcnSim/ConstantRateTrafficGenerator.h
C
lgpl-2.1
2,953
void Gtk2Gui_Dialog_Extend(GWEN_DIALOG *dlg) { GTK2_GUI_DIALOG *xdlg; GWEN_NEW_OBJECT(GTK2_GUI_DIALOG, xdlg); GWEN_INHERIT_SETDATA(GWEN_DIALOG, GTK2_GUI_DIALOG, dlg, xdlg, Gtk2Gui_Dialog_FreeData); /* set virtual functions */ xdlg->setIntPropertyFn=GWEN_Dialog_SetSetIntPropertyFn(dlg, Gtk2Gui_Dialog_SetIntProperty); xdlg->getIntPropertyFn=GWEN_Dialog_SetGetIntPropertyFn(dlg, Gtk2Gui_Dialog_GetIntProperty); xdlg->setCharPropertyFn=GWEN_Dialog_SetSetCharPropertyFn(dlg, Gtk2Gui_Dialog_SetCharProperty); xdlg->getCharPropertyFn=GWEN_Dialog_SetGetCharPropertyFn(dlg, Gtk2Gui_Dialog_GetCharProperty); }
aqbanking/gwenhywfar
doc/ex_widget_extenddlg.c
C
lgpl-2.1
621
package net.minecraft.client.particle; import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.entity.Entity; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class EntityPortalFX extends EntityFX { private float portalParticleScale; private double portalPosX; private double portalPosY; private double portalPosZ; private static final String __OBFID = "CL_00000921"; protected EntityPortalFX(World worldIn, double p_i46351_2_, double p_i46351_4_, double p_i46351_6_, double p_i46351_8_, double p_i46351_10_, double p_i46351_12_) { super(worldIn, p_i46351_2_, p_i46351_4_, p_i46351_6_, p_i46351_8_, p_i46351_10_, p_i46351_12_); this.motionX = p_i46351_8_; this.motionY = p_i46351_10_; this.motionZ = p_i46351_12_; this.portalPosX = this.posX = p_i46351_2_; this.portalPosY = this.posY = p_i46351_4_; this.portalPosZ = this.posZ = p_i46351_6_; float f = this.rand.nextFloat() * 0.6F + 0.4F; this.portalParticleScale = this.particleScale = this.rand.nextFloat() * 0.2F + 0.5F; this.particleRed = this.particleGreen = this.particleBlue = 1.0F * f; this.particleGreen *= 0.3F; this.particleRed *= 0.9F; this.particleMaxAge = (int)(Math.random() * 10.0D) + 40; this.noClip = true; this.setParticleTextureIndex((int)(Math.random() * 8.0D)); } public void func_180434_a(WorldRenderer p_180434_1_, Entity p_180434_2_, float p_180434_3_, float p_180434_4_, float p_180434_5_, float p_180434_6_, float p_180434_7_, float p_180434_8_) { float f6 = ((float)this.particleAge + p_180434_3_) / (float)this.particleMaxAge; f6 = 1.0F - f6; f6 *= f6; f6 = 1.0F - f6; this.particleScale = this.portalParticleScale * f6; super.func_180434_a(p_180434_1_, p_180434_2_, p_180434_3_, p_180434_4_, p_180434_5_, p_180434_6_, p_180434_7_, p_180434_8_); } public int getBrightnessForRender(float p_70070_1_) { int i = super.getBrightnessForRender(p_70070_1_); float f1 = (float)this.particleAge / (float)this.particleMaxAge; f1 *= f1; f1 *= f1; int j = i & 255; int k = i >> 16 & 255; k += (int)(f1 * 15.0F * 16.0F); if (k > 240) { k = 240; } return j | k << 16; } /** * Gets how bright this entity is. */ public float getBrightness(float p_70013_1_) { float f1 = super.getBrightness(p_70013_1_); float f2 = (float)this.particleAge / (float)this.particleMaxAge; f2 = f2 * f2 * f2 * f2; return f1 * (1.0F - f2) + f2; } /** * Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; float f = (float)this.particleAge / (float)this.particleMaxAge; float f1 = f; f = -f + f * f * 2.0F; f = 1.0F - f; this.posX = this.portalPosX + this.motionX * (double)f; this.posY = this.portalPosY + this.motionY * (double)f + (double)(1.0F - f1); this.posZ = this.portalPosZ + this.motionZ * (double)f; if (this.particleAge++ >= this.particleMaxAge) { this.setDead(); } } @SideOnly(Side.CLIENT) public static class Factory implements IParticleFactory { private static final String __OBFID = "CL_00002590"; public EntityFX getEntityFX(int p_178902_1_, World worldIn, double p_178902_3_, double p_178902_5_, double p_178902_7_, double p_178902_9_, double p_178902_11_, double p_178902_13_, int ... p_178902_15_) { return new EntityPortalFX(worldIn, p_178902_3_, p_178902_5_, p_178902_7_, p_178902_9_, p_178902_11_, p_178902_13_); } } }
trixmot/mod1
build/tmp/recompileMc/sources/net/minecraft/client/particle/EntityPortalFX.java
Java
lgpl-2.1
4,040
<?php /* ActiveFusions 2015/10/05 9:44 */ namespace Plugin\Holiday; use Eccube\Plugin\AbstractPluginManager; class PluginManager extends AbstractPluginManager{ /** * Image folder path (cop source) * @var type */ protected $imgSrc; /** *Image folder path (copy destination) * @var type */ protected $imgDst; public function __construct(){ } public function install($config, $app){ $this->migrationSchema($app, __DIR__ . '/Migration', $config['code']); } public function uninstall($config, $app){ $this->migrationSchema($app, __DIR__ . '/Migration', $config['code'], 0); } public function enable($config, $app){ } public function disable($config, $app){ } public function update($config, $app){ } }
ActiveFusion/Holiday
PluginManager.php
PHP
lgpl-2.1
738
/* * eXist-db Open Source Native XML Database * Copyright (C) 2001 The eXist-db Authors * * [email protected] * http://www.exist-db.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 USA */ package org.exist.test.runner; import com.evolvedbinary.j8fu.tuple.Tuple2; import org.exist.EXistException; import org.exist.security.PermissionDeniedException; import org.exist.source.ClassLoaderSource; import org.exist.source.Source; import org.exist.source.StringSource; import org.exist.util.DatabaseConfigurationException; import org.exist.xquery.FunctionCall; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.AnyURIValue; import org.exist.xquery.value.FunctionReference; import org.exist.xquery.value.Sequence; import org.junit.runner.Description; import org.junit.runner.notification.RunNotifier; import org.junit.runners.model.InitializationError; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * A JUnit test runner which can run the XQuery tests (XQSuite) * of eXist-db using $EXIST_HOME/src/org/exist/xquery/lib/xqsuite/xqsuite.xql. * * @author Adam Retter */ public class XQueryTestRunner extends AbstractTestRunner { private final XQueryTestInfo info; /** * @param path The path to the XQuery file containing the XQSuite tests * @param parallel whether the tests should be run in parallel. * * @throws InitializationError if the test runner could not be constructed. */ public XQueryTestRunner(final Path path, final boolean parallel) throws InitializationError { super(path, parallel); this.info = extractTestInfo(path); } private static XQueryTestInfo extractTestInfo(final Path path) throws InitializationError { try { final Source query = new StringSource("inspect:inspect-module(xs:anyURI(\"" + path.toAbsolutePath().toString() + "\"))"); final Sequence inspectionResults = executeQuery(query, Collections.emptyList()); // extract the details String prefix = null; String namespace = null; final List<XQueryTestInfo.TestFunctionDef> testFunctions = new ArrayList<>(); if(inspectionResults != null && inspectionResults.hasOne()) { final Element moduleElement = (Element)inspectionResults.itemAt(0); prefix = moduleElement.getAttribute("prefix"); namespace = moduleElement.getAttribute("uri"); final NodeList children = moduleElement.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { final Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE && child.getNamespaceURI() == null) { if(child.getNodeName().equals("function")) { boolean isTestFunction = false; final NamedNodeMap functionAttributes = child.getAttributes(); final String name = functionAttributes.getNamedItem("name").getNodeValue(); String testFunctionAnnotatedName = null; final NodeList functionChildren = child.getChildNodes(); for(int j = 0; j < functionChildren.getLength(); j++) { final Node functionChild = functionChildren.item(j); if (functionChild.getNodeType() == Node.ELEMENT_NODE && functionChild.getNamespaceURI() == null) { // filter functions by annotations... we only want the test:assert* annotated ones! if(functionChild.getNodeName().equals("annotation")) { final NamedNodeMap annotationAttributes = functionChild.getAttributes(); final Node annotationAttributeName = annotationAttributes.getNamedItem("name"); if(annotationAttributeName.getNodeValue().startsWith("test:assert")) { isTestFunction = true; } else if(annotationAttributeName.getNodeValue().equals("test:name")) { final NodeList annotationChildren = functionChild.getChildNodes(); for(int k = 0; k < annotationChildren.getLength(); k++) { final Node annotationChild = annotationChildren.item(k); if(annotationChild.getNodeType() == Node.ELEMENT_NODE && annotationChild.getNamespaceURI() == null) { if(annotationChild.getNodeName().equals("value")) { testFunctionAnnotatedName = annotationChild.getTextContent(); } } } } } } } if(isTestFunction) { // strip module prefix from function name String testFunctionLocalName = testFunctionAnnotatedName != null ? testFunctionAnnotatedName : name; if(testFunctionLocalName.startsWith(prefix + ':')) { testFunctionLocalName = testFunctionLocalName.substring(testFunctionLocalName.indexOf(':') + 1); testFunctions.add(new XQueryTestInfo.TestFunctionDef(testFunctionLocalName)); } } } } } } return new XQueryTestInfo(prefix, namespace, testFunctions); } catch(final DatabaseConfigurationException | IOException | EXistException | PermissionDeniedException | XPathException e) { throw new InitializationError(e); } } private String getSuiteName() { return namespaceToPackageName(info.getNamespace()); } private String namespaceToPackageName(final String namespace) { try { final URI uri = new URI(namespace); final StringBuilder packageName = new StringBuilder(); hostNameToPackageName(uri.getHost(), packageName); pathToPackageName(uri.getPath(), packageName); packageName.insert(0, "xqts."); // add "xqts." prefix return packageName.toString(); } catch (final URISyntaxException e) { throw new RuntimeException(e); } } private void hostNameToPackageName(String host, final StringBuilder buffer) { while (host != null && !host.isEmpty()) { if (buffer.length() > 0) { buffer.append('.'); } final int idx = host.lastIndexOf('.'); if (idx > -1) { buffer.append(host.substring(idx + 1)); host = host.substring(0, idx); } else { buffer.append(host); host = null; } } } private void pathToPackageName(String path, final StringBuilder buffer) { path = path.replace('.', '_'); path = path.replace('/', '.'); buffer.append(path); } @Override public Description getDescription() { final Description description = Description.createSuiteDescription(getSuiteName(), (java.lang.annotation.Annotation[]) null); for (final XQueryTestInfo.TestFunctionDef testFunctionDef : info.getTestFunctions()) { description.addChild(Description.createTestDescription(getSuiteName(), testFunctionDef.getLocalName(), (java.lang.annotation.Annotation) null)); } return description; } @Override public void run(final RunNotifier notifier) { try { final String pkgName = getClass().getPackage().getName().replace('.', '/'); final Source query = new ClassLoaderSource(pkgName + "/xquery-test-runner.xq"); final URI testModuleUri = path.toAbsolutePath().toUri(); final List<java.util.function.Function<XQueryContext, Tuple2<String, Object>>> externalVariableDeclarations = Arrays.asList( context -> new Tuple2<>("test-module-uri", new AnyURIValue(testModuleUri)), // set callback functions for notifying junit! context -> new Tuple2<>("test-ignored-function", new FunctionReference(new FunctionCall(context, new ExtTestIgnoredFunction(context, getSuiteName(), notifier)))), context -> new Tuple2<>("test-started-function", new FunctionReference(new FunctionCall(context, new ExtTestStartedFunction(context, getSuiteName(), notifier)))), context -> new Tuple2<>("test-failure-function", new FunctionReference(new FunctionCall(context, new ExtTestFailureFunction(context, getSuiteName(), notifier)))), context -> new Tuple2<>("test-assumption-failed-function", new FunctionReference(new FunctionCall(context, new ExtTestAssumptionFailedFunction(context, getSuiteName(), notifier)))), context -> new Tuple2<>("test-error-function", new FunctionReference(new FunctionCall(context, new ExtTestErrorFunction(context, getSuiteName(), notifier)))), context -> new Tuple2<>("test-finished-function", new FunctionReference(new FunctionCall(context, new ExtTestFinishedFunction(context, getSuiteName(), notifier)))) ); executeQuery(query, externalVariableDeclarations); } catch(final DatabaseConfigurationException | IOException | EXistException | PermissionDeniedException | XPathException e) { //TODO(AR) what to do here? throw new RuntimeException(e); } } private static class XQueryTestInfo { private final String prefix; private final String namespace; private final List<TestFunctionDef> testFunctions; private XQueryTestInfo(final String prefix, final String namespace, final List<TestFunctionDef> testFunctions) { this.prefix = prefix; this.namespace = namespace; this.testFunctions = testFunctions; } public String getPrefix() { return prefix; } public String getNamespace() { return namespace; } public List<TestFunctionDef> getTestFunctions() { return testFunctions; } private static class TestFunctionDef { private final String localName; private TestFunctionDef(final String localName) { this.localName = localName; } public String getLocalName() { return localName; } } } }
lcahlander/exist
exist-core/src/main/java/org/exist/test/runner/XQueryTestRunner.java
Java
lgpl-2.1
12,177
package net.minecraft.client.particle; import net.minecraft.client.renderer.VertexBuffer; import net.minecraft.entity.Entity; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class ParticlePortal extends Particle { private final float portalParticleScale; private final double portalPosX; private final double portalPosY; private final double portalPosZ; protected ParticlePortal(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn) { super(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn); this.motionX = xSpeedIn; this.motionY = ySpeedIn; this.motionZ = zSpeedIn; this.posX = xCoordIn; this.posY = yCoordIn; this.posZ = zCoordIn; this.portalPosX = this.posX; this.portalPosY = this.posY; this.portalPosZ = this.posZ; float f = this.rand.nextFloat() * 0.6F + 0.4F; this.particleScale = this.rand.nextFloat() * 0.2F + 0.5F; this.portalParticleScale = this.particleScale; this.particleRed = f * 0.9F; this.particleGreen = f * 0.3F; this.particleBlue = f; this.particleMaxAge = (int)(Math.random() * 10.0D) + 40; this.setParticleTextureIndex((int)(Math.random() * 8.0D)); } public void moveEntity(double x, double y, double z) { this.setEntityBoundingBox(this.getEntityBoundingBox().offset(x, y, z)); this.resetPositionToBB(); } /** * Renders the particle */ public void renderParticle(VertexBuffer worldRendererIn, Entity entityIn, float partialTicks, float rotationX, float rotationZ, float rotationYZ, float rotationXY, float rotationXZ) { float f = ((float)this.particleAge + partialTicks) / (float)this.particleMaxAge; f = 1.0F - f; f = f * f; f = 1.0F - f; this.particleScale = this.portalParticleScale * f; super.renderParticle(worldRendererIn, entityIn, partialTicks, rotationX, rotationZ, rotationYZ, rotationXY, rotationXZ); } public int getBrightnessForRender(float p_189214_1_) { int i = super.getBrightnessForRender(p_189214_1_); float f = (float)this.particleAge / (float)this.particleMaxAge; f = f * f; f = f * f; int j = i & 255; int k = i >> 16 & 255; k = k + (int)(f * 15.0F * 16.0F); if (k > 240) { k = 240; } return j | k << 16; } public void onUpdate() { this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; float f = (float)this.particleAge / (float)this.particleMaxAge; float f1 = -f + f * f * 2.0F; float f2 = 1.0F - f1; this.posX = this.portalPosX + this.motionX * (double)f2; this.posY = this.portalPosY + this.motionY * (double)f2 + (double)(1.0F - f); this.posZ = this.portalPosZ + this.motionZ * (double)f2; if (this.particleAge++ >= this.particleMaxAge) { this.setExpired(); } } @SideOnly(Side.CLIENT) public static class Factory implements IParticleFactory { public Particle getEntityFX(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_) { return new ParticlePortal(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn); } } }
Im-Jrotica/forge_latest
build/tmp/recompileMc/sources/net/minecraft/client/particle/ParticlePortal.java
Java
lgpl-2.1
3,691
/* Copyright (C) 2000, 2001, 2004, 2007 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C 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. The GNU C 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 the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #if !defined _MATH_H && !defined _COMPLEX_H # error "Never use <bits/mathdef.h> directly; include <math.h> instead" #endif #if defined __USE_ISOC99 && defined _MATH_H && !defined _MATH_H_MATHDEF # define _MATH_H_MATHDEF 1 /* Xtensa has `float' and `double' operations. */ typedef float float_t; /* `float' expressions are evaluated as `float'. */ typedef double double_t; /* `double' expressions are evaluated as `double'. */ /* The values returned by `ilogb' for 0 and NaN respectively. */ # define FP_ILOGB0 (-2147483647) # define FP_ILOGBNAN 2147483647 #endif /* ISO C99 */ #if !defined __NO_LONG_DOUBLE_MATH && !defined __UCLIBC_HAS_LONG_DOUBLE_MATH__ # define __NO_LONG_DOUBLE_MATH 1 #endif
wbx-github/uclibc-ng
libc/sysdeps/linux/xtensa/bits/mathdef.h
C
lgpl-2.1
1,525
/* libinfinity - a GObject-based infinote implementation * Copyright (C) 2007-2015 Armin Burgmeier <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef __INFD_XMPP_SERVER_H__ #define __INFD_XMPP_SERVER_H__ #include <libinfinity/server/infd-tcp-server.h> #include <libinfinity/common/inf-xmpp-connection.h> #include <libinfinity/common/inf-certificate-credentials.h> #include <unistd.h> /* Get ssize_t on MSVC, required by gnutls.h */ #include <gnutls/gnutls.h> #include <glib-object.h> G_BEGIN_DECLS #define INFD_TYPE_XMPP_SERVER (infd_xmpp_server_get_type()) #define INFD_XMPP_SERVER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), INFD_TYPE_XMPP_SERVER, InfdXmppServer)) #define INFD_XMPP_SERVER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), INFD_TYPE_XMPP_SERVER, InfdXmppServerClass)) #define INFD_IS_XMPP_SERVER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), INFD_TYPE_XMPP_SERVER)) #define INFD_IS_XMPP_SERVER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), INFD_TYPE_XMPP_SERVER)) #define INFD_XMPP_SERVER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), INFD_TYPE_XMPP_SERVER, InfdXmppServerClass)) typedef struct _InfdXmppServer InfdXmppServer; typedef struct _InfdXmppServerClass InfdXmppServerClass; struct _InfdXmppServerClass { GObjectClass parent_class; /* Signals */ void (*error)(InfdXmppServer* server, GError* error); }; struct _InfdXmppServer { GObject parent; }; GType infd_xmpp_server_get_type(void) G_GNUC_CONST; InfdXmppServer* infd_xmpp_server_new(InfdTcpServer* tcp, InfXmppConnectionSecurityPolicy policy, InfCertificateCredentials* creds, InfSaslContext* sasl_context, const gchar* sasl_mechanisms); void infd_xmpp_server_set_security_policy(InfdXmppServer* server, InfXmppConnectionSecurityPolicy policy); InfXmppConnectionSecurityPolicy infd_xmpp_server_get_security_policy(InfdXmppServer* server); G_END_DECLS #endif /* __INFD_XMPP_SERVER_H__ */ /* vim:set et sw=2 ts=2: */
gobby/libinfinity
libinfinity/server/infd-xmpp-server.h
C
lgpl-2.1
2,834
/* Copyright (c) 2015 MariaDB Foundation. 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mariadb.h" #include "sql_type.h" #include "sql_const.h" #include "sql_class.h" #include "sql_time.h" #include "item.h" #include "log.h" Type_handler_row type_handler_row; Type_handler_null type_handler_null; Type_handler_tiny type_handler_tiny; Type_handler_short type_handler_short; Type_handler_long type_handler_long; Type_handler_int24 type_handler_int24; Type_handler_longlong type_handler_longlong; Type_handler_longlong type_handler_ulonglong; // Only used for CAST() for now Type_handler_vers_trx_id type_handler_vers_trx_id; Type_handler_float type_handler_float; Type_handler_double type_handler_double; Type_handler_bit type_handler_bit; Type_handler_olddecimal type_handler_olddecimal; Type_handler_newdecimal type_handler_newdecimal; Type_handler_year type_handler_year; Type_handler_time type_handler_time; Type_handler_date type_handler_date; Type_handler_timestamp type_handler_timestamp; Type_handler_timestamp2 type_handler_timestamp2; Type_handler_datetime type_handler_datetime; Type_handler_time2 type_handler_time2; Type_handler_newdate type_handler_newdate; Type_handler_datetime2 type_handler_datetime2; Type_handler_enum type_handler_enum; Type_handler_set type_handler_set; Type_handler_string type_handler_string; Type_handler_var_string type_handler_var_string; Type_handler_varchar type_handler_varchar; static Type_handler_varchar_compressed type_handler_varchar_compressed; Type_handler_tiny_blob type_handler_tiny_blob; Type_handler_medium_blob type_handler_medium_blob; Type_handler_long_blob type_handler_long_blob; Type_handler_blob type_handler_blob; static Type_handler_blob_compressed type_handler_blob_compressed; #ifdef HAVE_SPATIAL Type_handler_geometry type_handler_geometry; #endif bool Type_handler_data::init() { #ifdef HAVE_SPATIAL #ifndef DBUG_OFF if (m_type_aggregator_non_commutative_test.add(&type_handler_geometry, &type_handler_geometry, &type_handler_geometry) || m_type_aggregator_non_commutative_test.add(&type_handler_geometry, &type_handler_varchar, &type_handler_long_blob)) return true; #endif return m_type_aggregator_for_result.add(&type_handler_geometry, &type_handler_null, &type_handler_geometry) || m_type_aggregator_for_result.add(&type_handler_geometry, &type_handler_geometry, &type_handler_geometry) || m_type_aggregator_for_result.add(&type_handler_geometry, &type_handler_tiny_blob, &type_handler_long_blob) || m_type_aggregator_for_result.add(&type_handler_geometry, &type_handler_blob, &type_handler_long_blob) || m_type_aggregator_for_result.add(&type_handler_geometry, &type_handler_medium_blob, &type_handler_long_blob) || m_type_aggregator_for_result.add(&type_handler_geometry, &type_handler_long_blob, &type_handler_long_blob) || m_type_aggregator_for_result.add(&type_handler_geometry, &type_handler_varchar, &type_handler_long_blob) || m_type_aggregator_for_result.add(&type_handler_geometry, &type_handler_string, &type_handler_long_blob) || m_type_aggregator_for_comparison.add(&type_handler_geometry, &type_handler_geometry, &type_handler_geometry) || m_type_aggregator_for_comparison.add(&type_handler_geometry, &type_handler_null, &type_handler_geometry) || m_type_aggregator_for_comparison.add(&type_handler_geometry, &type_handler_long_blob, &type_handler_long_blob); #endif return false; } Type_handler_data *type_handler_data= NULL; void Type_std_attributes::set(const Field *field) { decimals= field->decimals(); unsigned_flag= MY_TEST(field->flags & UNSIGNED_FLAG); collation.set(field->charset(), field->derivation(), field->repertoire()); fix_char_length(field->char_length()); } uint Type_std_attributes::count_max_decimals(Item **item, uint nitems) { uint res= 0; for (uint i= 0; i < nitems; i++) set_if_bigger(res, item[i]->decimals); return res; } /** Set max_length/decimals of function if function is fixed point and result length/precision depends on argument ones. */ void Type_std_attributes::count_decimal_length(Item **item, uint nitems) { int max_int_part= 0; decimals= 0; unsigned_flag= 1; for (uint i=0 ; i < nitems ; i++) { set_if_bigger(decimals, item[i]->decimals); set_if_bigger(max_int_part, item[i]->decimal_int_part()); set_if_smaller(unsigned_flag, item[i]->unsigned_flag); } int precision= MY_MIN(max_int_part + decimals, DECIMAL_MAX_PRECISION); fix_char_length(my_decimal_precision_to_length_no_truncation(precision, (uint8) decimals, unsigned_flag)); } /** Set max_length of if it is maximum length of its arguments. */ void Type_std_attributes::count_only_length(Item **item, uint nitems) { uint32 char_length= 0; unsigned_flag= 0; for (uint i= 0; i < nitems ; i++) { set_if_bigger(char_length, item[i]->max_char_length()); set_if_bigger(unsigned_flag, item[i]->unsigned_flag); } fix_char_length(char_length); } void Type_std_attributes::count_octet_length(Item **item, uint nitems) { max_length= 0; unsigned_flag= 0; for (uint i= 0; i < nitems ; i++) { set_if_bigger(max_length, item[i]->max_length); set_if_bigger(unsigned_flag, item[i]->unsigned_flag); } } /** Set max_length/decimals of function if function is floating point and result length/precision depends on argument ones. */ void Type_std_attributes::count_real_length(Item **items, uint nitems) { uint32 length= 0; decimals= 0; max_length= 0; unsigned_flag= false; for (uint i=0 ; i < nitems ; i++) { if (decimals < FLOATING_POINT_DECIMALS) { set_if_bigger(decimals, items[i]->decimals); /* Will be ignored if items[i]->decimals >= FLOATING_POINT_DECIMALS */ set_if_bigger(length, (items[i]->max_length - items[i]->decimals)); } set_if_bigger(max_length, items[i]->max_length); } if (decimals < FLOATING_POINT_DECIMALS) { max_length= length; length+= decimals; if (length < max_length) // If previous operation gave overflow max_length= UINT_MAX32; else max_length= length; } // Corner case: COALESCE(DOUBLE(255,4), DOUBLE(255,3)) -> FLOAT(255, 4) set_if_smaller(max_length, MAX_FIELD_CHARLENGTH); } /** Calculate max_length and decimals for string functions. @param field_type Field type. @param items Argument array. @param nitems Number of arguments. @retval False on success, true on error. */ bool Type_std_attributes::count_string_length(const char *func_name, Item **items, uint nitems) { if (agg_arg_charsets_for_string_result(collation, func_name, items, nitems, 1)) return true; if (collation.collation == &my_charset_bin) count_octet_length(items, nitems); else count_only_length(items, nitems); decimals= max_length ? NOT_FIXED_DEC : 0; return false; } /** This method is used by: - Item_user_var_as_out_param::field_type() - Item_func_udf_str::field_type() - Item_empty_string::make_field() TODO: type_handler_adjusted_to_max_octet_length() and string_type_handler() provide very similar functionality, to properly choose between VARCHAR/VARBINARY vs TEXT/BLOB variations taking into accoung maximum possible octet length. We should probably get rid of either of them and use the same method all around the code. */ const Type_handler * Type_handler::string_type_handler(uint max_octet_length) { if (max_octet_length >= 16777216) return &type_handler_long_blob; else if (max_octet_length >= 65536) return &type_handler_medium_blob; return &type_handler_varchar; } const Type_handler * Type_handler::varstring_type_handler(const Item *item) { if (!item->max_length) return &type_handler_string; if (item->too_big_for_varchar()) return blob_type_handler(item->max_length); return &type_handler_varchar; } const Type_handler * Type_handler::blob_type_handler(uint max_octet_length) { if (max_octet_length <= 255) return &type_handler_tiny_blob; if (max_octet_length <= 65535) return &type_handler_blob; if (max_octet_length <= 16777215) return &type_handler_medium_blob; return &type_handler_long_blob; } const Type_handler * Type_handler::blob_type_handler(const Item *item) { return blob_type_handler(item->max_length); } /** This method is used by: - Item_sum_hybrid, e.g. MAX(item), MIN(item). - Item_func_set_user_var */ const Type_handler * Type_handler_string_result::type_handler_adjusted_to_max_octet_length( uint max_octet_length, CHARSET_INFO *cs) const { if (max_octet_length / cs->mbmaxlen <= CONVERT_IF_BIGGER_TO_BLOB) return &type_handler_varchar; // See also Item::too_big_for_varchar() if (max_octet_length >= 16777216) return &type_handler_long_blob; else if (max_octet_length >= 65536) return &type_handler_medium_blob; return &type_handler_blob; } CHARSET_INFO *Type_handler::charset_for_protocol(const Item *item) const { /* For backward compatibility, to make numeric data types return "binary" charset in client-side metadata. */ return &my_charset_bin; } bool Type_handler::Item_func_or_sum_illegal_param(const char *funcname) const { my_error(ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION, MYF(0), name().ptr(), funcname); return true; } bool Type_handler::Item_func_or_sum_illegal_param(const Item_func_or_sum *it) const { return Item_func_or_sum_illegal_param(it->func_name()); } CHARSET_INFO * Type_handler_string_result::charset_for_protocol(const Item *item) const { return item->collation.collation; } const Type_handler * Type_handler::get_handler_by_cmp_type(Item_result type) { switch (type) { case REAL_RESULT: return &type_handler_double; case INT_RESULT: return &type_handler_longlong; case DECIMAL_RESULT: return &type_handler_newdecimal; case STRING_RESULT: return &type_handler_long_blob; case TIME_RESULT: return &type_handler_datetime; case ROW_RESULT: return &type_handler_row; } DBUG_ASSERT(0); return &type_handler_string; } Type_handler_hybrid_field_type::Type_handler_hybrid_field_type() :m_type_handler(&type_handler_double) { } /***************************************************************************/ /* number of bytes to store second_part part of the TIMESTAMP(N) */ uint Type_handler_timestamp::m_sec_part_bytes[MAX_DATETIME_PRECISION + 1]= { 0, 1, 1, 2, 2, 3, 3 }; /* number of bytes to store DATETIME(N) */ uint Type_handler_datetime::m_hires_bytes[MAX_DATETIME_PRECISION + 1]= { 5, 6, 6, 7, 7, 7, 8 }; /* number of bytes to store TIME(N) */ uint Type_handler_time::m_hires_bytes[MAX_DATETIME_PRECISION + 1]= { 3, 4, 4, 5, 5, 5, 6 }; /***************************************************************************/ const Name Type_handler_row::m_name_row(C_STRING_WITH_LEN("row")); const Name Type_handler_null::m_name_null(C_STRING_WITH_LEN("null")); const Name Type_handler_string::m_name_char(C_STRING_WITH_LEN("char")), Type_handler_var_string::m_name_var_string(C_STRING_WITH_LEN("varchar")), Type_handler_varchar::m_name_varchar(C_STRING_WITH_LEN("varchar")), Type_handler_tiny_blob::m_name_tinyblob(C_STRING_WITH_LEN("tinyblob")), Type_handler_medium_blob::m_name_mediumblob(C_STRING_WITH_LEN("mediumblob")), Type_handler_long_blob::m_name_longblob(C_STRING_WITH_LEN("longblob")), Type_handler_blob::m_name_blob(C_STRING_WITH_LEN("blob")); const Name Type_handler_enum::m_name_enum(C_STRING_WITH_LEN("enum")), Type_handler_set::m_name_set(C_STRING_WITH_LEN("set")); const Name Type_handler_tiny::m_name_tiny(C_STRING_WITH_LEN("tinyint")), Type_handler_short::m_name_short(C_STRING_WITH_LEN("smallint")), Type_handler_long::m_name_int(C_STRING_WITH_LEN("int")), Type_handler_longlong::m_name_longlong(C_STRING_WITH_LEN("bigint")), Type_handler_int24::m_name_mediumint(C_STRING_WITH_LEN("mediumint")), Type_handler_year::m_name_year(C_STRING_WITH_LEN("year")), Type_handler_bit::m_name_bit(C_STRING_WITH_LEN("bit")); const Name Type_handler_float::m_name_float(C_STRING_WITH_LEN("float")), Type_handler_double::m_name_double(C_STRING_WITH_LEN("double")); const Name Type_handler_olddecimal::m_name_decimal(C_STRING_WITH_LEN("decimal")), Type_handler_newdecimal::m_name_decimal(C_STRING_WITH_LEN("decimal")); const Name Type_handler_time_common::m_name_time(C_STRING_WITH_LEN("time")), Type_handler_date_common::m_name_date(C_STRING_WITH_LEN("date")), Type_handler_datetime_common::m_name_datetime(C_STRING_WITH_LEN("datetime")), Type_handler_timestamp_common::m_name_timestamp(C_STRING_WITH_LEN("timestamp")); /***************************************************************************/ const Type_handler *Type_handler_null::type_handler_for_comparison() const { return &type_handler_null; } const Type_handler *Type_handler_int_result::type_handler_for_comparison() const { return &type_handler_longlong; } const Type_handler *Type_handler_string_result::type_handler_for_comparison() const { return &type_handler_long_blob; } const Type_handler *Type_handler_decimal_result::type_handler_for_comparison() const { return &type_handler_newdecimal; } const Type_handler *Type_handler_real_result::type_handler_for_comparison() const { return &type_handler_double; } const Type_handler *Type_handler_time_common::type_handler_for_comparison() const { return &type_handler_time; } const Type_handler *Type_handler_date_common::type_handler_for_comparison() const { return &type_handler_newdate; } const Type_handler *Type_handler_datetime_common::type_handler_for_comparison() const { return &type_handler_datetime; } const Type_handler *Type_handler_timestamp_common::type_handler_for_comparison() const { return &type_handler_datetime; } const Type_handler *Type_handler_row::type_handler_for_comparison() const { return &type_handler_row; } /***************************************************************************/ const Type_handler *Type_handler_typelib::type_handler_for_item_field() const { return &type_handler_string; } const Type_handler *Type_handler_typelib::cast_to_int_type_handler() const { return &type_handler_longlong; } /***************************************************************************/ bool Type_handler_hybrid_field_type::aggregate_for_result(const Type_handler *other) { if (m_type_handler->is_traditional_type() && other->is_traditional_type()) { m_type_handler= Type_handler::aggregate_for_result_traditional(m_type_handler, other); return false; } other= type_handler_data-> m_type_aggregator_for_result.find_handler(m_type_handler, other); if (!other) return true; m_type_handler= other; return false; } const Type_handler * Type_handler::type_handler_long_or_longlong(uint max_char_length) { if (max_char_length <= MY_INT32_NUM_DECIMAL_DIGITS - 2) return &type_handler_long; return &type_handler_longlong; } /* This method is called for CASE (and its abbreviations) and LEAST/GREATEST when data type aggregation returned LONGLONG and there were some BIT expressions. This helps to adjust the data type from LONGLONG to LONG if all expressions fit. */ const Type_handler * Type_handler::bit_and_int_mixture_handler(uint max_char_length) { if (max_char_length <= MY_INT32_NUM_DECIMAL_DIGITS) return &type_handler_long; return &type_handler_longlong; } /** @brief Aggregates field types from the array of items. @param[in] items array of items to aggregate the type from @param[in] nitems number of items in the array @param[in] treat_bit_as_number - if BIT should be aggregated to a non-BIT counterpart as a LONGLONG number or as a VARBINARY string. Currently behaviour depends on the function: - LEAST/GREATEST treat BIT as VARBINARY when aggregating with a non-BIT counterpart. Note, UNION also works this way. - CASE, COALESCE, IF, IFNULL treat BIT as LONGLONG when aggregating with a non-BIT counterpart; This inconsistency may be changed in the future. See MDEV-8867. Note, independently from "treat_bit_as_number": - a single BIT argument gives BIT as a result - two BIT couterparts give BIT as a result @details This function aggregates field types from the array of items. Found type is supposed to be used later as the result field type of a multi-argument function. Aggregation itself is performed by Type_handler::aggregate_for_result(). @note The term "aggregation" is used here in the sense of inferring the result type of a function from its argument types. @retval false - on success @retval true - on error */ bool Type_handler_hybrid_field_type::aggregate_for_result(const char *funcname, Item **items, uint nitems, bool treat_bit_as_number) { bool bit_and_non_bit_mixture_found= false; uint32 max_display_length; if (!nitems || items[0]->result_type() == ROW_RESULT) { DBUG_ASSERT(0); set_handler(&type_handler_null); return true; } set_handler(items[0]->type_handler()); max_display_length= items[0]->max_display_length(); for (uint i= 1 ; i < nitems ; i++) { const Type_handler *cur= items[i]->type_handler(); set_if_bigger(max_display_length, items[i]->max_display_length()); if (treat_bit_as_number && ((type_handler() == &type_handler_bit) ^ (cur == &type_handler_bit))) { bit_and_non_bit_mixture_found= true; if (type_handler() == &type_handler_bit) set_handler(&type_handler_longlong); // BIT + non-BIT else cur= &type_handler_longlong; // non-BIT + BIT } if (aggregate_for_result(cur)) { my_error(ER_ILLEGAL_PARAMETER_DATA_TYPES2_FOR_OPERATION, MYF(0), type_handler()->name().ptr(), cur->name().ptr(), funcname); return true; } } if (bit_and_non_bit_mixture_found && type_handler() == &type_handler_longlong) set_handler(Type_handler::bit_and_int_mixture_handler(max_display_length)); return false; } /** Collect built-in data type handlers for comparison. This method is very similar to item_cmp_type() defined in item.cc. Now they coexist. Later item_cmp_type() will be removed. In addition to item_cmp_type(), this method correctly aggregates TIME with DATETIME/TIMESTAMP/DATE, so no additional find_date_time_item() is needed after this call. */ bool Type_handler_hybrid_field_type::aggregate_for_comparison(const Type_handler *h) { DBUG_ASSERT(m_type_handler == m_type_handler->type_handler_for_comparison()); DBUG_ASSERT(h == h->type_handler_for_comparison()); if (!m_type_handler->is_traditional_type() || !h->is_traditional_type()) { h= type_handler_data-> m_type_aggregator_for_comparison.find_handler(m_type_handler, h); if (!h) return true; m_type_handler= h; DBUG_ASSERT(m_type_handler == m_type_handler->type_handler_for_comparison()); return false; } Item_result a= cmp_type(); Item_result b= h->cmp_type(); if (m_vers_trx_id && (a == STRING_RESULT || b == STRING_RESULT)) m_type_handler= &type_handler_datetime; else if (a == STRING_RESULT && b == STRING_RESULT) m_type_handler= &type_handler_long_blob; else if (a == INT_RESULT && b == INT_RESULT) m_type_handler= &type_handler_longlong; else if (a == ROW_RESULT || b == ROW_RESULT) m_type_handler= &type_handler_row; else if (a == TIME_RESULT || b == TIME_RESULT) { if ((a == TIME_RESULT) + (b == TIME_RESULT) == 1) { /* We're here if there's only one temporal data type: either m_type_handler or h. */ if (b == TIME_RESULT) m_type_handler= h; // Temporal types bit non-temporal types } else { /* We're here if both m_type_handler and h are temporal data types. - If both data types are TIME, we preserve TIME. - If both data types are DATE, we preserve DATE. Preserving DATE is needed for EXPLAIN FORMAT=JSON, to print DATE constants using proper format: 'YYYY-MM-DD' rather than 'YYYY-MM-DD 00:00:00'. */ if (m_type_handler->field_type() != h->field_type()) m_type_handler= &type_handler_datetime; } } else if ((a == INT_RESULT || a == DECIMAL_RESULT) && (b == INT_RESULT || b == DECIMAL_RESULT)) { m_type_handler= &type_handler_newdecimal; } else m_type_handler= &type_handler_double; DBUG_ASSERT(m_type_handler == m_type_handler->type_handler_for_comparison()); return false; } /** Aggregate data type handler for LEAST/GRATEST. aggregate_for_min_max() is close to aggregate_for_comparison(), but tries to preserve the exact type handler for string, int and temporal data types (instead of converting to super-types). FLOAT is not preserved and is converted to its super-type (DOUBLE). This should probably fixed eventually, for symmetry. */ bool Type_handler_hybrid_field_type::aggregate_for_min_max(const Type_handler *h) { if (!m_type_handler->is_traditional_type() || !h->is_traditional_type()) { /* If at least one data type is non-traditional, do aggregation for result immediately. For now we suppose that these two expressions: - LEAST(type1, type2) - COALESCE(type1, type2) return the same data type (or both expressions return error) if type1 and/or type2 are non-traditional. This may change in the future. */ h= type_handler_data-> m_type_aggregator_for_result.find_handler(m_type_handler, h); if (!h) return true; m_type_handler= h; return false; } Item_result a= cmp_type(); Item_result b= h->cmp_type(); DBUG_ASSERT(a != ROW_RESULT); // Disallowed by check_cols() in fix_fields() DBUG_ASSERT(b != ROW_RESULT); // Disallowed by check_cols() in fix_fields() if (a == STRING_RESULT && b == STRING_RESULT) m_type_handler= Type_handler::aggregate_for_result_traditional(m_type_handler, h); else if (a == INT_RESULT && b == INT_RESULT) { // BIT aggregates with non-BIT as BIGINT if (m_type_handler != h) { if (m_type_handler == &type_handler_bit) m_type_handler= &type_handler_longlong; else if (h == &type_handler_bit) h= &type_handler_longlong; } m_type_handler= Type_handler::aggregate_for_result_traditional(m_type_handler, h); } else if (a == TIME_RESULT || b == TIME_RESULT) { if ((a == TIME_RESULT) + (b == TIME_RESULT) == 1) { /* We're here if there's only one temporal data type: either m_type_handler or h. */ if (b == TIME_RESULT) m_type_handler= h; // Temporal types bit non-temporal types } else { /* We're here if both m_type_handler and h are temporal data types. */ m_type_handler= Type_handler::aggregate_for_result_traditional(m_type_handler, h); } } else if ((a == INT_RESULT || a == DECIMAL_RESULT) && (b == INT_RESULT || b == DECIMAL_RESULT)) { m_type_handler= &type_handler_newdecimal; } else { // Preserve FLOAT if two FLOATs, set to DOUBLE otherwise. if (m_type_handler != &type_handler_float || h != &type_handler_float) m_type_handler= &type_handler_double; } return false; } bool Type_handler_hybrid_field_type::aggregate_for_min_max(const char *funcname, Item **items, uint nitems) { bool bit_and_non_bit_mixture_found= false; uint32 max_display_length; // LEAST/GREATEST require at least two arguments DBUG_ASSERT(nitems > 1); set_handler(items[0]->type_handler()); max_display_length= items[0]->max_display_length(); for (uint i= 1; i < nitems; i++) { const Type_handler *cur= items[i]->type_handler(); set_if_bigger(max_display_length, items[i]->max_display_length()); // Check if BIT + non-BIT, or non-BIT + BIT bit_and_non_bit_mixture_found|= (m_type_handler == &type_handler_bit) != (cur == &type_handler_bit); if (aggregate_for_min_max(cur)) { my_error(ER_ILLEGAL_PARAMETER_DATA_TYPES2_FOR_OPERATION, MYF(0), type_handler()->name().ptr(), cur->name().ptr(), funcname); return true; } } if (bit_and_non_bit_mixture_found && type_handler() == &type_handler_longlong) set_handler(Type_handler::bit_and_int_mixture_handler(max_display_length)); return false; } const Type_handler * Type_handler::aggregate_for_num_op_traditional(const Type_handler *h0, const Type_handler *h1) { Item_result r0= h0->cmp_type(); Item_result r1= h1->cmp_type(); if (r0 == REAL_RESULT || r1 == REAL_RESULT || r0 == STRING_RESULT || r1 ==STRING_RESULT) return &type_handler_double; if (r0 == TIME_RESULT || r1 == TIME_RESULT) return &type_handler_datetime; if (r0 == DECIMAL_RESULT || r1 == DECIMAL_RESULT) return &type_handler_newdecimal; DBUG_ASSERT(r0 == INT_RESULT && r1 == INT_RESULT); return &type_handler_longlong; } const Type_aggregator::Pair* Type_aggregator::find_pair(const Type_handler *handler1, const Type_handler *handler2) const { for (uint i= 0; i < m_array.elements(); i++) { const Pair& el= m_array.at(i); if (el.eq(handler1, handler2) || (m_is_commutative && el.eq(handler2, handler1))) return &el; } return NULL; } bool Type_handler_hybrid_field_type::aggregate_for_num_op(const Type_aggregator *agg, const Type_handler *h0, const Type_handler *h1) { const Type_handler *hres; if (h0->is_traditional_type() && h1->is_traditional_type()) { set_handler(Type_handler::aggregate_for_num_op_traditional(h0, h1)); return false; } if ((hres= agg->find_handler(h0, h1))) { set_handler(hres); return false; } return true; } /***************************************************************************/ const Type_handler * Type_handler::get_handler_by_field_type(enum_field_types type) { switch (type) { case MYSQL_TYPE_DECIMAL: return &type_handler_olddecimal; case MYSQL_TYPE_NEWDECIMAL: return &type_handler_newdecimal; case MYSQL_TYPE_TINY: return &type_handler_tiny; case MYSQL_TYPE_SHORT: return &type_handler_short; case MYSQL_TYPE_LONG: return &type_handler_long; case MYSQL_TYPE_LONGLONG: return &type_handler_longlong; case MYSQL_TYPE_INT24: return &type_handler_int24; case MYSQL_TYPE_YEAR: return &type_handler_year; case MYSQL_TYPE_BIT: return &type_handler_bit; case MYSQL_TYPE_FLOAT: return &type_handler_float; case MYSQL_TYPE_DOUBLE: return &type_handler_double; case MYSQL_TYPE_NULL: return &type_handler_null; case MYSQL_TYPE_VARCHAR: return &type_handler_varchar; case MYSQL_TYPE_TINY_BLOB: return &type_handler_tiny_blob; case MYSQL_TYPE_MEDIUM_BLOB: return &type_handler_medium_blob; case MYSQL_TYPE_LONG_BLOB: return &type_handler_long_blob; case MYSQL_TYPE_BLOB: return &type_handler_blob; case MYSQL_TYPE_VAR_STRING: return &type_handler_varchar; // Map to VARCHAR case MYSQL_TYPE_STRING: return &type_handler_string; case MYSQL_TYPE_ENUM: return &type_handler_varchar; // Map to VARCHAR case MYSQL_TYPE_SET: return &type_handler_varchar; // Map to VARCHAR case MYSQL_TYPE_GEOMETRY: #ifdef HAVE_SPATIAL return &type_handler_geometry; #else return NULL; #endif case MYSQL_TYPE_TIMESTAMP: return &type_handler_timestamp2;// Map to timestamp2 case MYSQL_TYPE_TIMESTAMP2: return &type_handler_timestamp2; case MYSQL_TYPE_DATE: return &type_handler_newdate; // Map to newdate case MYSQL_TYPE_TIME: return &type_handler_time2; // Map to time2 case MYSQL_TYPE_TIME2: return &type_handler_time2; case MYSQL_TYPE_DATETIME: return &type_handler_datetime2; // Map to datetime2 case MYSQL_TYPE_DATETIME2: return &type_handler_datetime2; case MYSQL_TYPE_NEWDATE: /* NEWDATE is actually a real_type(), not a field_type(), but it's used around the code in field_type() context. We should probably clean up the code not to use MYSQL_TYPE_NEWDATE in field_type() context and add DBUG_ASSERT(0) here. */ return &type_handler_newdate; case MYSQL_TYPE_VARCHAR_COMPRESSED: case MYSQL_TYPE_BLOB_COMPRESSED: break; }; DBUG_ASSERT(0); return &type_handler_string; } const Type_handler * Type_handler::get_handler_by_real_type(enum_field_types type) { switch (type) { case MYSQL_TYPE_DECIMAL: return &type_handler_olddecimal; case MYSQL_TYPE_NEWDECIMAL: return &type_handler_newdecimal; case MYSQL_TYPE_TINY: return &type_handler_tiny; case MYSQL_TYPE_SHORT: return &type_handler_short; case MYSQL_TYPE_LONG: return &type_handler_long; case MYSQL_TYPE_LONGLONG: return &type_handler_longlong; case MYSQL_TYPE_INT24: return &type_handler_int24; case MYSQL_TYPE_YEAR: return &type_handler_year; case MYSQL_TYPE_BIT: return &type_handler_bit; case MYSQL_TYPE_FLOAT: return &type_handler_float; case MYSQL_TYPE_DOUBLE: return &type_handler_double; case MYSQL_TYPE_NULL: return &type_handler_null; case MYSQL_TYPE_VARCHAR: return &type_handler_varchar; case MYSQL_TYPE_VARCHAR_COMPRESSED: return &type_handler_varchar_compressed; case MYSQL_TYPE_TINY_BLOB: return &type_handler_tiny_blob; case MYSQL_TYPE_MEDIUM_BLOB: return &type_handler_medium_blob; case MYSQL_TYPE_LONG_BLOB: return &type_handler_long_blob; case MYSQL_TYPE_BLOB: return &type_handler_blob; case MYSQL_TYPE_BLOB_COMPRESSED: return &type_handler_blob_compressed; case MYSQL_TYPE_VAR_STRING: /* VAR_STRING is actually a field_type(), not a real_type(), but it's used around the code in real_type() context. We should clean up the code and add DBUG_ASSERT(0) here. */ return &type_handler_string; case MYSQL_TYPE_STRING: return &type_handler_string; case MYSQL_TYPE_ENUM: return &type_handler_enum; case MYSQL_TYPE_SET: return &type_handler_set; case MYSQL_TYPE_GEOMETRY: #ifdef HAVE_SPATIAL return &type_handler_geometry; #else return NULL; #endif case MYSQL_TYPE_TIMESTAMP: return &type_handler_timestamp; case MYSQL_TYPE_TIMESTAMP2: return &type_handler_timestamp2; case MYSQL_TYPE_DATE: return &type_handler_date; case MYSQL_TYPE_TIME: return &type_handler_time; case MYSQL_TYPE_TIME2: return &type_handler_time2; case MYSQL_TYPE_DATETIME: return &type_handler_datetime; case MYSQL_TYPE_DATETIME2: return &type_handler_datetime2; case MYSQL_TYPE_NEWDATE: return &type_handler_newdate; }; DBUG_ASSERT(0); return &type_handler_string; } /** Create a DOUBLE field by default. */ Field * Type_handler::make_num_distinct_aggregator_field(MEM_ROOT *mem_root, const Item *item) const { return new(mem_root) Field_double(NULL, item->max_length, (uchar *) (item->maybe_null ? "" : 0), item->maybe_null ? 1 : 0, Field::NONE, &item->name, (uint8) item->decimals, 0, item->unsigned_flag); } Field * Type_handler_float::make_num_distinct_aggregator_field(MEM_ROOT *mem_root, const Item *item) const { return new(mem_root) Field_float(NULL, item->max_length, (uchar *) (item->maybe_null ? "" : 0), item->maybe_null ? 1 : 0, Field::NONE, &item->name, (uint8) item->decimals, 0, item->unsigned_flag); } Field * Type_handler_decimal_result::make_num_distinct_aggregator_field( MEM_ROOT *mem_root, const Item *item) const { DBUG_ASSERT(item->decimals <= DECIMAL_MAX_SCALE); return new (mem_root) Field_new_decimal(NULL, item->max_length, (uchar *) (item->maybe_null ? "" : 0), item->maybe_null ? 1 : 0, Field::NONE, &item->name, (uint8) item->decimals, 0, item->unsigned_flag); } Field * Type_handler_int_result::make_num_distinct_aggregator_field(MEM_ROOT *mem_root, const Item *item) const { /** Make a longlong field for all INT-alike types. It could create smaller fields for TINYINT, SMALLINT, MEDIUMINT, INT though. */ return new(mem_root) Field_longlong(NULL, item->max_length, (uchar *) (item->maybe_null ? "" : 0), item->maybe_null ? 1 : 0, Field::NONE, &item->name, 0, item->unsigned_flag); } /***********************************************************************/ Field *Type_handler_tiny::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { /* As we don't know if the integer was signed or not on the master, assume we have same sign on master and slave. This is true when not using conversions so it should be true also when using conversions. */ bool unsigned_flag= ((Field_num*) target)->unsigned_flag; return new (table->in_use->mem_root) Field_tiny(NULL, 4 /*max_length*/, (uchar *) "", 1, Field::NONE, &empty_clex_str, 0/*zerofill*/, unsigned_flag); } Field *Type_handler_short::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { bool unsigned_flag= ((Field_num*) target)->unsigned_flag; return new (table->in_use->mem_root) Field_short(NULL, 6 /*max_length*/, (uchar *) "", 1, Field::NONE, &empty_clex_str, 0/*zerofill*/, unsigned_flag); } Field *Type_handler_int24::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { bool unsigned_flag= ((Field_num*) target)->unsigned_flag; return new (table->in_use->mem_root) Field_medium(NULL, 9 /*max_length*/, (uchar *) "", 1, Field::NONE, &empty_clex_str, 0/*zerofill*/, unsigned_flag); } Field *Type_handler_long::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { bool unsigned_flag= ((Field_num*) target)->unsigned_flag; return new (table->in_use->mem_root) Field_long(NULL, 11 /*max_length*/, (uchar *) "", 1, Field::NONE, &empty_clex_str, 0/*zerofill*/, unsigned_flag); } Field *Type_handler_longlong::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { bool unsigned_flag= ((Field_num*) target)->unsigned_flag; return new (table->in_use->mem_root) Field_longlong(NULL, 20 /*max_length*/,(uchar *) "", 1, Field::NONE, &empty_clex_str, 0/*zerofill*/, unsigned_flag); } Field *Type_handler_float::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new (table->in_use->mem_root) Field_float(NULL, 12 /*max_length*/, (uchar *) "", 1, Field::NONE, &empty_clex_str, 0/*dec*/, 0/*zerofill*/, 0/*unsigned_flag*/); } Field *Type_handler_double::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new (table->in_use->mem_root) Field_double(NULL, 22 /*max_length*/, (uchar *) "", 1, Field::NONE, &empty_clex_str, 0/*dec*/, 0/*zerofill*/, 0/*unsigned_flag*/); } Field *Type_handler_newdecimal::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { int precision= metadata >> 8; uint8 decimals= metadata & 0x00ff; uint32 max_length= my_decimal_precision_to_length(precision, decimals, false); DBUG_ASSERT(decimals <= DECIMAL_MAX_SCALE); return new (table->in_use->mem_root) Field_new_decimal(NULL, max_length, (uchar *) "", 1, Field::NONE, &empty_clex_str, decimals, 0/*zerofill*/, 0/*unsigned*/); } Field *Type_handler_olddecimal::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { sql_print_error("In RBR mode, Slave received incompatible DECIMAL field " "(old-style decimal field) from Master while creating " "conversion table. Please consider changing datatype on " "Master to new style decimal by executing ALTER command for" " column Name: %s.%s.%s.", target->table->s->db.str, target->table->s->table_name.str, target->field_name.str); return NULL; } Field *Type_handler_year::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new(table->in_use->mem_root) Field_year(NULL, 4, (uchar *) "", 1, Field::NONE, &empty_clex_str); } Field *Type_handler_null::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new(table->in_use->mem_root) Field_null(NULL, 0, Field::NONE, &empty_clex_str, target->charset()); } Field *Type_handler_timestamp::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new_Field_timestamp(table->in_use->mem_root, NULL, (uchar *) "", 1, Field::NONE, &empty_clex_str, table->s, target->decimals()); } Field *Type_handler_timestamp2::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new(table->in_use->mem_root) Field_timestampf(NULL, (uchar *) "", 1, Field::NONE, &empty_clex_str, table->s, metadata); } Field *Type_handler_newdate::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new(table->in_use->mem_root) Field_newdate(NULL, (uchar *) "", 1, Field::NONE, &empty_clex_str); } Field *Type_handler_date::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new(table->in_use->mem_root) Field_date(NULL, (uchar *) "", 1, Field::NONE, &empty_clex_str); } Field *Type_handler_time::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new_Field_time(table->in_use->mem_root, NULL, (uchar *) "", 1, Field::NONE, &empty_clex_str, target->decimals()); } Field *Type_handler_time2::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new(table->in_use->mem_root) Field_timef(NULL, (uchar *) "", 1, Field::NONE, &empty_clex_str, metadata); } Field *Type_handler_datetime::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new_Field_datetime(table->in_use->mem_root, NULL, (uchar *) "", 1, Field::NONE, &empty_clex_str, target->decimals()); } Field *Type_handler_datetime2::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new(table->in_use->mem_root) Field_datetimef(NULL, (uchar *) "", 1, Field::NONE, &empty_clex_str, metadata); } Field *Type_handler_bit::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { DBUG_ASSERT((metadata & 0xff) <= 7); uint32 max_length= 8 * (metadata >> 8U) + (metadata & 0x00ff); return new(table->in_use->mem_root) Field_bit_as_char(NULL, max_length, (uchar *) "", 1, Field::NONE, &empty_clex_str); } Field *Type_handler_string::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { /* This is taken from Field_string::unpack. */ uint32 max_length= (((metadata >> 4) & 0x300) ^ 0x300) + (metadata & 0x00ff); return new(table->in_use->mem_root) Field_string(NULL, max_length, (uchar *) "", 1, Field::NONE, &empty_clex_str, target->charset()); } Field *Type_handler_varchar::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new(table->in_use->mem_root) Field_varstring(NULL, metadata, HA_VARCHAR_PACKLENGTH(metadata), (uchar *) "", 1, Field::NONE, &empty_clex_str, table->s, target->charset()); } Field *Type_handler_varchar_compressed::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new(table->in_use->mem_root) Field_varstring_compressed(NULL, metadata, HA_VARCHAR_PACKLENGTH(metadata), (uchar *) "", 1, Field::NONE, &empty_clex_str, table->s, target->charset(), zlib_compression_method); } Field *Type_handler_tiny_blob::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new(table->in_use->mem_root) Field_blob(NULL, (uchar *) "", 1, Field::NONE, &empty_clex_str, table->s, 1, target->charset()); } Field *Type_handler_blob::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new(table->in_use->mem_root) Field_blob(NULL, (uchar *) "", 1, Field::NONE, &empty_clex_str, table->s, 2, target->charset()); } Field *Type_handler_blob_compressed::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new(table->in_use->mem_root) Field_blob_compressed(NULL, (uchar *) "", 1, Field::NONE, &empty_clex_str, table->s, 2, target->charset(), zlib_compression_method); } Field *Type_handler_medium_blob::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new(table->in_use->mem_root) Field_blob(NULL, (uchar *) "", 1, Field::NONE, &empty_clex_str, table->s, 3, target->charset()); } Field *Type_handler_long_blob::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { return new(table->in_use->mem_root) Field_blob(NULL, (uchar *) "", 1, Field::NONE, &empty_clex_str, table->s, 4, target->charset()); } #ifdef HAVE_SPATIAL const Name Type_handler_geometry::m_name_geometry(C_STRING_WITH_LEN("geometry")); const Type_handler *Type_handler_geometry::type_handler_for_comparison() const { return &type_handler_geometry; } Field *Type_handler_geometry::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { DBUG_ASSERT(target->type() == MYSQL_TYPE_GEOMETRY); /* We do not do not update feature_gis statistics here: status_var_increment(target->table->in_use->status_var.feature_gis); as this is only a temporary field. The statistics was already incremented when "target" was created. */ return new(table->in_use->mem_root) Field_geom(NULL, (uchar *) "", 1, Field::NONE, &empty_clex_str, table->s, 4, ((const Field_geom*) target)->geom_type, ((const Field_geom*) target)->srid); } #endif Field *Type_handler_enum::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { DBUG_ASSERT(target->type() == MYSQL_TYPE_STRING); DBUG_ASSERT(target->real_type() == MYSQL_TYPE_ENUM); return new(table->in_use->mem_root) Field_enum(NULL, target->field_length, (uchar *) "", 1, Field::NONE, &empty_clex_str, metadata & 0x00ff/*pack_length()*/, ((const Field_enum*) target)->typelib, target->charset()); } Field *Type_handler_set::make_conversion_table_field(TABLE *table, uint metadata, const Field *target) const { DBUG_ASSERT(target->type() == MYSQL_TYPE_STRING); DBUG_ASSERT(target->real_type() == MYSQL_TYPE_SET); return new(table->in_use->mem_root) Field_set(NULL, target->field_length, (uchar *) "", 1, Field::NONE, &empty_clex_str, metadata & 0x00ff/*pack_length()*/, ((const Field_enum*) target)->typelib, target->charset()); } /*************************************************************************/ bool Type_handler_null:: Column_definition_fix_attributes(Column_definition *def) const { return false; } bool Type_handler_tiny:: Column_definition_fix_attributes(Column_definition *def) const { return def->fix_attributes_int(MAX_TINYINT_WIDTH + def->sign_length()); } bool Type_handler_short:: Column_definition_fix_attributes(Column_definition *def) const { return def->fix_attributes_int(MAX_SMALLINT_WIDTH + def->sign_length()); } bool Type_handler_int24:: Column_definition_fix_attributes(Column_definition *def) const { return def->fix_attributes_int(MAX_MEDIUMINT_WIDTH + def->sign_length()); } bool Type_handler_long:: Column_definition_fix_attributes(Column_definition *def) const { return def->fix_attributes_int(MAX_INT_WIDTH + def->sign_length()); } bool Type_handler_longlong:: Column_definition_fix_attributes(Column_definition *def) const { return def->fix_attributes_int(MAX_BIGINT_WIDTH/*no sign_length() added*/); } bool Type_handler_newdecimal:: Column_definition_fix_attributes(Column_definition *def) const { return def->fix_attributes_decimal(); } bool Type_handler_olddecimal:: Column_definition_fix_attributes(Column_definition *def) const { DBUG_ASSERT(0); // Obsolete return true; } bool Type_handler_var_string:: Column_definition_fix_attributes(Column_definition *def) const { DBUG_ASSERT(0); // Obsolete return true; } bool Type_handler_varchar:: Column_definition_fix_attributes(Column_definition *def) const { /* Long VARCHAR's are automaticly converted to blobs in mysql_prepare_table if they don't have a default value */ return def->check_length(ER_TOO_BIG_DISPLAYWIDTH, MAX_FIELD_BLOBLENGTH); } bool Type_handler_string:: Column_definition_fix_attributes(Column_definition *def) const { return def->check_length(ER_TOO_BIG_FIELDLENGTH, MAX_FIELD_CHARLENGTH); } bool Type_handler_blob_common:: Column_definition_fix_attributes(Column_definition *def) const { def->flags|= BLOB_FLAG; return def->check_length(ER_TOO_BIG_DISPLAYWIDTH, MAX_FIELD_BLOBLENGTH); } #ifdef HAVE_SPATIAL bool Type_handler_geometry:: Column_definition_fix_attributes(Column_definition *def) const { def->flags|= BLOB_FLAG; return false; } #endif bool Type_handler_year:: Column_definition_fix_attributes(Column_definition *def) const { if (!def->length || def->length != 2) def->length= 4; // Default length def->flags|= ZEROFILL_FLAG | UNSIGNED_FLAG; return false; } bool Type_handler_float:: Column_definition_fix_attributes(Column_definition *def) const { return def->fix_attributes_real(MAX_FLOAT_STR_LENGTH); } bool Type_handler_double:: Column_definition_fix_attributes(Column_definition *def) const { return def->fix_attributes_real(DBL_DIG + 7); } bool Type_handler_timestamp_common:: Column_definition_fix_attributes(Column_definition *def) const { def->flags|= UNSIGNED_FLAG; return def->fix_attributes_temporal_with_time(MAX_DATETIME_WIDTH); } bool Type_handler_date_common:: Column_definition_fix_attributes(Column_definition *def) const { // We don't support creation of MYSQL_TYPE_DATE anymore def->set_handler(&type_handler_newdate); def->length= MAX_DATE_WIDTH; return false; } bool Type_handler_time_common:: Column_definition_fix_attributes(Column_definition *def) const { return def->fix_attributes_temporal_with_time(MIN_TIME_WIDTH); } bool Type_handler_datetime_common:: Column_definition_fix_attributes(Column_definition *def) const { return def->fix_attributes_temporal_with_time(MAX_DATETIME_WIDTH); } bool Type_handler_set:: Column_definition_fix_attributes(Column_definition *def) const { def->pack_length= get_set_pack_length(def->interval_list.elements); return false; } bool Type_handler_enum:: Column_definition_fix_attributes(Column_definition *def) const { def->pack_length= get_enum_pack_length(def->interval_list.elements); return false; } bool Type_handler_bit:: Column_definition_fix_attributes(Column_definition *def) const { return def->fix_attributes_bit(); } /*************************************************************************/ bool Type_handler:: Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *def, handler *file, ulonglong table_flags) const { def->create_length_to_internal_length_simple(); return false; } bool Type_handler_null:: Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *def, handler *file, ulonglong table_flags) const { def->create_length_to_internal_length_null(); return false; } bool Type_handler_row:: Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *def, handler *file, ulonglong table_flags) const { def->create_length_to_internal_length_null(); return false; } bool Type_handler_newdecimal:: Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *def, handler *file, ulonglong table_flags) const { def->create_length_to_internal_length_newdecimal(); return false; } bool Type_handler_bit:: Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *def, handler *file, ulonglong table_flags) const { return def->prepare_stage1_bit(thd, mem_root, file, table_flags); } bool Type_handler_typelib:: Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *def, handler *file, ulonglong table_flags) const { return def->prepare_stage1_typelib(thd, mem_root, file, table_flags); } bool Type_handler_string_result:: Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *def, handler *file, ulonglong table_flags) const { return def->prepare_stage1_string(thd, mem_root, file, table_flags); } #ifdef HAVE_SPATIAL bool Type_handler_geometry:: Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *def, handler *file, ulonglong table_flags) const { def->create_length_to_internal_length_string(); return def->prepare_blob_field(thd); } #endif /*************************************************************************/ bool Type_handler:: Column_definition_redefine_stage1(Column_definition *def, const Column_definition *dup, const handler *file, const Schema_specification_st *schema) const { def->redefine_stage1_common(dup, file, schema); def->create_length_to_internal_length_simple(); return false; } bool Type_handler_null:: Column_definition_redefine_stage1(Column_definition *def, const Column_definition *dup, const handler *file, const Schema_specification_st *schema) const { def->redefine_stage1_common(dup, file, schema); def->create_length_to_internal_length_null(); return false; } bool Type_handler_newdecimal:: Column_definition_redefine_stage1(Column_definition *def, const Column_definition *dup, const handler *file, const Schema_specification_st *schema) const { def->redefine_stage1_common(dup, file, schema); def->create_length_to_internal_length_newdecimal(); return false; } bool Type_handler_string_result:: Column_definition_redefine_stage1(Column_definition *def, const Column_definition *dup, const handler *file, const Schema_specification_st *schema) const { def->redefine_stage1_common(dup, file, schema); def->set_compression_method(dup->compression_method()); def->create_length_to_internal_length_string(); return false; } bool Type_handler_typelib:: Column_definition_redefine_stage1(Column_definition *def, const Column_definition *dup, const handler *file, const Schema_specification_st *schema) const { def->redefine_stage1_common(dup, file, schema); def->create_length_to_internal_length_typelib(); return false; } bool Type_handler_bit:: Column_definition_redefine_stage1(Column_definition *def, const Column_definition *dup, const handler *file, const Schema_specification_st *schema) const { def->redefine_stage1_common(dup, file, schema); /* If we are replacing a field with a BIT field, we need to initialize pack_flag. */ def->pack_flag= FIELDFLAG_NUMBER; if (!(file->ha_table_flags() & HA_CAN_BIT_FIELD)) def->pack_flag|= FIELDFLAG_TREAT_BIT_AS_CHAR; def->create_length_to_internal_length_bit(); return false; } /*************************************************************************/ bool Type_handler:: Column_definition_prepare_stage2_legacy(Column_definition *def, enum_field_types type) const { def->pack_flag= f_settype((uint) type); return false; } bool Type_handler:: Column_definition_prepare_stage2_legacy_num(Column_definition *def, enum_field_types type) const { def->pack_flag= def->pack_flag_numeric(def->decimals) | f_settype((uint) type); return false; } bool Type_handler:: Column_definition_prepare_stage2_legacy_real(Column_definition *def, enum_field_types type) const { uint dec= def->decimals; /* User specified FLOAT() or DOUBLE() without precision. Change to FLOATING_POINT_DECIMALS to keep things compatible with earlier MariaDB versions. */ if (dec >= FLOATING_POINT_DECIMALS) dec= FLOATING_POINT_DECIMALS; def->pack_flag= def->pack_flag_numeric(dec) | f_settype((uint) type); return false; } bool Type_handler_newdecimal:: Column_definition_prepare_stage2(Column_definition *def, handler *file, ulonglong table_flags) const { def->pack_flag= def->pack_flag_numeric(def->decimals); return false; } bool Type_handler_blob_common:: Column_definition_prepare_stage2(Column_definition *def, handler *file, ulonglong table_flags) const { return def->prepare_stage2_blob(file, table_flags, FIELDFLAG_BLOB); } #ifdef HAVE_SPATIAL bool Type_handler_geometry:: Column_definition_prepare_stage2(Column_definition *def, handler *file, ulonglong table_flags) const { if (!(table_flags & HA_CAN_GEOMETRY)) { my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "GEOMETRY"); return true; } return def->prepare_stage2_blob(file, table_flags, FIELDFLAG_GEOM); } #endif bool Type_handler_varchar:: Column_definition_prepare_stage2(Column_definition *def, handler *file, ulonglong table_flags) const { return def->prepare_stage2_varchar(table_flags); } bool Type_handler_string:: Column_definition_prepare_stage2(Column_definition *def, handler *file, ulonglong table_flags) const { def->pack_flag= (def->charset->state & MY_CS_BINSORT) ? FIELDFLAG_BINARY : 0; return false; } bool Type_handler_enum:: Column_definition_prepare_stage2(Column_definition *def, handler *file, ulonglong table_flags) const { uint dummy; return def->prepare_stage2_typelib("ENUM", FIELDFLAG_INTERVAL, &dummy); } bool Type_handler_set:: Column_definition_prepare_stage2(Column_definition *def, handler *file, ulonglong table_flags) const { uint dup_count; if (def->prepare_stage2_typelib("SET", FIELDFLAG_BITFIELD, &dup_count)) return true; /* Check that count of unique members is not more then 64 */ if (def->interval->count - dup_count > sizeof(longlong)*8) { my_error(ER_TOO_BIG_SET, MYF(0), def->field_name.str); return true; } return false; } bool Type_handler_bit:: Column_definition_prepare_stage2(Column_definition *def, handler *file, ulonglong table_flags) const { /* We have sql_field->pack_flag already set here, see mysql_prepare_create_table(). */ return false; } /*************************************************************************/ uint32 Type_handler_time::calc_pack_length(uint32 length) const { return length > MIN_TIME_WIDTH ? hires_bytes(length - 1 - MIN_TIME_WIDTH) : 3; } uint32 Type_handler_time2::calc_pack_length(uint32 length) const { return length > MIN_TIME_WIDTH ? my_time_binary_length(length - MIN_TIME_WIDTH - 1) : 3; } uint32 Type_handler_timestamp::calc_pack_length(uint32 length) const { return length > MAX_DATETIME_WIDTH ? 4 + sec_part_bytes(length - 1 - MAX_DATETIME_WIDTH) : 4; } uint32 Type_handler_timestamp2::calc_pack_length(uint32 length) const { return length > MAX_DATETIME_WIDTH ? my_timestamp_binary_length(length - MAX_DATETIME_WIDTH - 1) : 4; } uint32 Type_handler_datetime::calc_pack_length(uint32 length) const { return length > MAX_DATETIME_WIDTH ? hires_bytes(length - 1 - MAX_DATETIME_WIDTH) : 8; } uint32 Type_handler_datetime2::calc_pack_length(uint32 length) const { return length > MAX_DATETIME_WIDTH ? my_datetime_binary_length(length - MAX_DATETIME_WIDTH - 1) : 5; } uint32 Type_handler_tiny_blob::calc_pack_length(uint32 length) const { return 1 + portable_sizeof_char_ptr; } uint32 Type_handler_blob::calc_pack_length(uint32 length) const { return 2 + portable_sizeof_char_ptr; } uint32 Type_handler_medium_blob::calc_pack_length(uint32 length) const { return 3 + portable_sizeof_char_ptr; } uint32 Type_handler_long_blob::calc_pack_length(uint32 length) const { return 4 + portable_sizeof_char_ptr; } #ifdef HAVE_SPATIAL uint32 Type_handler_geometry::calc_pack_length(uint32 length) const { return 4 + portable_sizeof_char_ptr; } #endif uint32 Type_handler_newdecimal::calc_pack_length(uint32 length) const { abort(); // This shouldn't happen return 0; } uint32 Type_handler_set::calc_pack_length(uint32 length) const { abort(); // This shouldn't happen return 0; } uint32 Type_handler_enum::calc_pack_length(uint32 length) const { abort(); // This shouldn't happen return 0; } /*************************************************************************/ Field *Type_handler::make_and_init_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { Field *field= make_table_field(name, addr, attr, table); if (field) field->init(table); return field; } Field *Type_handler_tiny::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_tiny(addr.ptr, attr.max_char_length(), addr.null_ptr, addr.null_bit, Field::NONE, name, 0/*zerofill*/, attr.unsigned_flag); } Field *Type_handler_short::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_short(addr.ptr, attr.max_char_length(), addr.null_ptr, addr.null_bit, Field::NONE, name, 0/*zerofill*/, attr.unsigned_flag); } Field *Type_handler_int24::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_medium(addr.ptr, attr.max_char_length(), addr.null_ptr, addr.null_bit, Field::NONE, name, 0/*zerofill*/, attr.unsigned_flag); } Field *Type_handler_long::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_long(addr.ptr, attr.max_char_length(), addr.null_ptr, addr.null_bit, Field::NONE, name, 0/*zerofill*/, attr.unsigned_flag); } Field *Type_handler_longlong::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_longlong(addr.ptr, attr.max_char_length(), addr.null_ptr, addr.null_bit, Field::NONE, name, 0/*zerofill*/, attr.unsigned_flag); } Field *Type_handler_vers_trx_id::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_vers_trx_id(addr.ptr, attr.max_char_length(), addr.null_ptr, addr.null_bit, Field::NONE, name, 0/*zerofill*/, attr.unsigned_flag); } Field *Type_handler_float::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_float(addr.ptr, attr.max_char_length(), addr.null_ptr, addr.null_bit, Field::NONE, name, (uint8) attr.decimals, 0/*zerofill*/, attr.unsigned_flag); } Field *Type_handler_double::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_double(addr.ptr, attr.max_char_length(), addr.null_ptr, addr.null_bit, Field::NONE, name, (uint8) attr.decimals, 0/*zerofill*/, attr.unsigned_flag); } Field * Type_handler_olddecimal::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { /* Currently make_table_field() is used for Item purpose only. On Item level we have type_handler_newdecimal only. For now we have DBUG_ASSERT(0). It will be removed when we reuse Type_handler::make_table_field() in make_field() in field.cc, to open old tables with old decimal. */ DBUG_ASSERT(0); return new (table->in_use->mem_root) Field_decimal(addr.ptr, attr.max_length, addr.null_ptr, addr.null_bit, Field::NONE, name, (uint8) attr.decimals, 0/*zerofill*/,attr.unsigned_flag); } Field * Type_handler_newdecimal::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { uint8 dec= (uint8) attr.decimals; uint8 intg= (uint8) (attr.decimal_precision() - dec); uint32 len= attr.max_char_length(); /* Trying to put too many digits overall in a DECIMAL(prec,dec) will always throw a warning. We must limit dec to DECIMAL_MAX_SCALE however to prevent an assert() later. */ if (dec > 0) { signed int overflow; dec= MY_MIN(dec, DECIMAL_MAX_SCALE); /* If the value still overflows the field with the corrected dec, we'll throw out decimals rather than integers. This is still bad and of course throws a truncation warning. +1: for decimal point */ const int required_length= my_decimal_precision_to_length(intg + dec, dec, attr.unsigned_flag); overflow= required_length - len; if (overflow > 0) dec= MY_MAX(0, dec - overflow); // too long, discard fract else /* Corrected value fits. */ len= required_length; } return new (table->in_use->mem_root) Field_new_decimal(addr.ptr, len, addr.null_ptr, addr.null_bit, Field::NONE, name, dec, 0/*zerofill*/, attr.unsigned_flag); } Field *Type_handler_year::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_year(addr.ptr, attr.max_length, addr.null_ptr, addr.null_bit, Field::NONE, name); } Field *Type_handler_null::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_null(addr.ptr, attr.max_length, Field::NONE, name, attr.collation.collation); } Field *Type_handler_timestamp::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new_Field_timestamp(table->in_use->mem_root, addr.ptr, addr.null_ptr, addr.null_bit, Field::NONE, name, table->s, attr.decimals); } Field *Type_handler_timestamp2::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { /* Will be changed to "new Field_timestampf" when we reuse make_table_field() for make_field() purposes in field.cc. */ return new_Field_timestamp(table->in_use->mem_root, addr.ptr, addr.null_ptr, addr.null_bit, Field::NONE, name, table->s, attr.decimals); } Field *Type_handler_newdate::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_newdate(addr.ptr, addr.null_ptr, addr.null_bit, Field::NONE, name); } Field *Type_handler_date::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { /* DBUG_ASSERT will be removed when we reuse make_table_field() for make_field() in field.cc */ DBUG_ASSERT(0); return new (table->in_use->mem_root) Field_date(addr.ptr, addr.null_ptr, addr.null_bit, Field::NONE, name); } Field *Type_handler_time::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new_Field_time(table->in_use->mem_root, addr.ptr, addr.null_ptr, addr.null_bit, Field::NONE, name, attr.decimals); } Field *Type_handler_time2::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { /* Will be changed to "new Field_timef" when we reuse make_table_field() for make_field() purposes in field.cc. */ return new_Field_time(table->in_use->mem_root, addr.ptr, addr.null_ptr, addr.null_bit, Field::NONE, name, attr.decimals); } Field *Type_handler_datetime::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new_Field_datetime(table->in_use->mem_root, addr.ptr, addr.null_ptr, addr.null_bit, Field::NONE, name, attr.decimals); } Field *Type_handler_datetime2::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { /* Will be changed to "new Field_datetimef" when we reuse make_table_field() for make_field() purposes in field.cc. */ return new_Field_datetime(table->in_use->mem_root, addr.ptr, addr.null_ptr, addr.null_bit, Field::NONE, name, attr.decimals); } Field *Type_handler_bit::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_bit_as_char(addr.ptr, attr.max_length, addr.null_ptr, addr.null_bit, Field::NONE, name); } Field *Type_handler_string::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_string(addr.ptr, attr.max_length, addr.null_ptr, addr.null_bit, Field::NONE, name, attr.collation); } Field *Type_handler_varchar::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_varstring(addr.ptr, attr.max_length, HA_VARCHAR_PACKLENGTH(attr.max_length), addr.null_ptr, addr.null_bit, Field::NONE, name, table->s, attr.collation); } Field *Type_handler_tiny_blob::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_blob(addr.ptr, addr.null_ptr, addr.null_bit, Field::NONE, name, table->s, 1, attr.collation); } Field *Type_handler_blob::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_blob(addr.ptr, addr.null_ptr, addr.null_bit, Field::NONE, name, table->s, 2, attr.collation); } Field * Type_handler_medium_blob::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_blob(addr.ptr, addr.null_ptr, addr.null_bit, Field::NONE, name, table->s, 3, attr.collation); } Field *Type_handler_long_blob::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_blob(addr.ptr, addr.null_ptr, addr.null_bit, Field::NONE, name, table->s, 4, attr.collation); } #ifdef HAVE_SPATIAL Field *Type_handler_geometry::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { return new (table->in_use->mem_root) Field_geom(addr.ptr, addr.null_ptr, addr.null_bit, Field::NONE, name, table->s, 4, (Field::geometry_type) attr.uint_geometry_type(), 0); } #endif Field *Type_handler_enum::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { TYPELIB *typelib= attr.get_typelib(); DBUG_ASSERT(typelib); return new (table->in_use->mem_root) Field_enum(addr.ptr, attr.max_length, addr.null_ptr, addr.null_bit, Field::NONE, name, get_enum_pack_length(typelib->count), typelib, attr.collation); } Field *Type_handler_set::make_table_field(const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const { TYPELIB *typelib= attr.get_typelib(); DBUG_ASSERT(typelib); return new (table->in_use->mem_root) Field_set(addr.ptr, attr.max_length, addr.null_ptr, addr.null_bit, Field::NONE, name, get_enum_pack_length(typelib->count), typelib, attr.collation); } /*************************************************************************/ /* If length is not specified for a varchar parameter, set length to the maximum length of the actual argument. Goals are: - avoid to allocate too much unused memory for m_var_table - allow length check inside the callee rather than during copy of returned values in output variables. - allow varchar parameter size greater than 4000 Default length has been stored in "decimal" member during parse. */ bool Type_handler_varchar::adjust_spparam_type(Spvar_definition *def, Item *from) const { if (def->decimals) { uint def_max_char_length= MAX_FIELD_VARCHARLENGTH / def->charset->mbmaxlen; uint arg_max_length= from->max_char_length(); set_if_smaller(arg_max_length, def_max_char_length); def->length= arg_max_length > 0 ? arg_max_length : def->decimals; def->create_length_to_internal_length_string(); } return false; } /*************************************************************************/ uint32 Type_handler_decimal_result::max_display_length(const Item *item) const { return item->max_length; } uint32 Type_handler_temporal_result::max_display_length(const Item *item) const { return item->max_length; } uint32 Type_handler_string_result::max_display_length(const Item *item) const { return item->max_length; } uint32 Type_handler_year::max_display_length(const Item *item) const { return item->max_length; } uint32 Type_handler_bit::max_display_length(const Item *item) const { return item->max_length; } /*************************************************************************/ int Type_handler_time_common::Item_save_in_field(Item *item, Field *field, bool no_conversions) const { return item->save_time_in_field(field, no_conversions); } int Type_handler_temporal_with_date::Item_save_in_field(Item *item, Field *field, bool no_conversions) const { return item->save_date_in_field(field, no_conversions); } int Type_handler_string_result::Item_save_in_field(Item *item, Field *field, bool no_conversions) const { return item->save_str_in_field(field, no_conversions); } int Type_handler_real_result::Item_save_in_field(Item *item, Field *field, bool no_conversions) const { return item->save_real_in_field(field, no_conversions); } int Type_handler_decimal_result::Item_save_in_field(Item *item, Field *field, bool no_conversions) const { return item->save_decimal_in_field(field, no_conversions); } int Type_handler_int_result::Item_save_in_field(Item *item, Field *field, bool no_conversions) const { return item->save_int_in_field(field, no_conversions); } /***********************************************************************/ bool Type_handler_row::set_comparator_func(Arg_comparator *cmp) const { return cmp->set_cmp_func_row(); } bool Type_handler_int_result::set_comparator_func(Arg_comparator *cmp) const { return cmp->set_cmp_func_int(); } bool Type_handler_real_result::set_comparator_func(Arg_comparator *cmp) const { return cmp->set_cmp_func_real(); } bool Type_handler_decimal_result::set_comparator_func(Arg_comparator *cmp) const { return cmp->set_cmp_func_decimal(); } bool Type_handler_string_result::set_comparator_func(Arg_comparator *cmp) const { return cmp->set_cmp_func_string(); } bool Type_handler_time_common::set_comparator_func(Arg_comparator *cmp) const { return cmp->set_cmp_func_time(); } bool Type_handler_temporal_with_date::set_comparator_func(Arg_comparator *cmp) const { return cmp->set_cmp_func_datetime(); } /*************************************************************************/ bool Type_handler_temporal_result:: can_change_cond_ref_to_const(Item_bool_func2 *target, Item *target_expr, Item *target_value, Item_bool_func2 *source, Item *source_expr, Item *source_const) const { if (source->compare_type_handler()->cmp_type() != TIME_RESULT) return false; /* Can't rewrite: WHERE COALESCE(time_column)='00:00:00' AND COALESCE(time_column)=DATE'2015-09-11' to WHERE DATE'2015-09-11'='00:00:00' AND COALESCE(time_column)=DATE'2015-09-11' because the left part will erroneously try to parse '00:00:00' as DATE, not as TIME. TODO: It could still be rewritten to: WHERE DATE'2015-09-11'=TIME'00:00:00' AND COALESCE(time_column)=DATE'2015-09-11' i.e. we need to replace both target_expr and target_value at the same time. This is not supported yet. */ return target_value->cmp_type() == TIME_RESULT; } bool Type_handler_string_result:: can_change_cond_ref_to_const(Item_bool_func2 *target, Item *target_expr, Item *target_value, Item_bool_func2 *source, Item *source_expr, Item *source_const) const { if (source->compare_type_handler()->cmp_type() != STRING_RESULT) return false; /* In this example: SET NAMES utf8 COLLATE utf8_german2_ci; DROP TABLE IF EXISTS t1; CREATE TABLE t1 (a CHAR(10) CHARACTER SET utf8); INSERT INTO t1 VALUES ('o-umlaut'),('oe'); SELECT * FROM t1 WHERE a='oe' COLLATE utf8_german2_ci AND a='oe'; the query should return only the row with 'oe'. It should not return 'o-umlaut', because 'o-umlaut' does not match the right part of the condition: a='oe' ('o-umlaut' is not equal to 'oe' in utf8_general_ci, which is the collation of the field "a"). If we change the right part from: ... AND a='oe' to ... AND 'oe' COLLATE utf8_german2_ci='oe' it will be evalulated to TRUE and removed from the condition, so the overall query will be simplified to: SELECT * FROM t1 WHERE a='oe' COLLATE utf8_german2_ci; which will erroneously start to return both 'oe' and 'o-umlaut'. So changing "expr" to "const" is not possible if the effective collations of "target" and "source" are not exactly the same. Note, the code before the fix for MDEV-7152 only checked that collations of "source_const" and "target_value" are the same. This was not enough, as the bug report demonstrated. */ return target->compare_collation() == source->compare_collation() && target_value->collation.collation == source_const->collation.collation; } bool Type_handler_numeric:: can_change_cond_ref_to_const(Item_bool_func2 *target, Item *target_expr, Item *target_value, Item_bool_func2 *source, Item *source_expr, Item *source_const) const { /* The collations of "target" and "source" do not make sense for numeric data types. */ return target->compare_type_handler() == source->compare_type_handler(); } /*************************************************************************/ Item_cache * Type_handler_row::Item_get_cache(THD *thd, const Item *item) const { return new (thd->mem_root) Item_cache_row(thd); } Item_cache * Type_handler_int_result::Item_get_cache(THD *thd, const Item *item) const { return new (thd->mem_root) Item_cache_int(thd, item->type_handler()); } Item_cache * Type_handler_real_result::Item_get_cache(THD *thd, const Item *item) const { return new (thd->mem_root) Item_cache_real(thd); } Item_cache * Type_handler_decimal_result::Item_get_cache(THD *thd, const Item *item) const { return new (thd->mem_root) Item_cache_decimal(thd); } Item_cache * Type_handler_string_result::Item_get_cache(THD *thd, const Item *item) const { return new (thd->mem_root) Item_cache_str(thd, item); } Item_cache * Type_handler_timestamp_common::Item_get_cache(THD *thd, const Item *item) const { return new (thd->mem_root) Item_cache_datetime(thd); } Item_cache * Type_handler_datetime_common::Item_get_cache(THD *thd, const Item *item) const { return new (thd->mem_root) Item_cache_datetime(thd); } Item_cache * Type_handler_time_common::Item_get_cache(THD *thd, const Item *item) const { return new (thd->mem_root) Item_cache_time(thd); } Item_cache * Type_handler_date_common::Item_get_cache(THD *thd, const Item *item) const { return new (thd->mem_root) Item_cache_date(thd); } /*************************************************************************/ bool Type_handler_int_result:: Item_hybrid_func_fix_attributes(THD *thd, const char *func_name, Type_handler_hybrid_field_type *handler, Type_all_attributes *func, Item **items, uint nitems) const { uint unsigned_flag= items[0]->unsigned_flag; for (uint i= 1; i < nitems; i++) { if (unsigned_flag != items[i]->unsigned_flag) { // Convert a mixture of signed and unsigned int to decimal handler->set_handler(&type_handler_newdecimal); func->aggregate_attributes_decimal(items, nitems); return false; } } func->aggregate_attributes_int(items, nitems); return false; } bool Type_handler_real_result:: Item_hybrid_func_fix_attributes(THD *thd, const char *func_name, Type_handler_hybrid_field_type *handler, Type_all_attributes *func, Item **items, uint nitems) const { func->aggregate_attributes_real(items, nitems); return false; } bool Type_handler_decimal_result:: Item_hybrid_func_fix_attributes(THD *thd, const char *func_name, Type_handler_hybrid_field_type *handler, Type_all_attributes *func, Item **items, uint nitems) const { func->aggregate_attributes_decimal(items, nitems); return false; } bool Type_handler_string_result:: Item_hybrid_func_fix_attributes(THD *thd, const char *func_name, Type_handler_hybrid_field_type *handler, Type_all_attributes *func, Item **items, uint nitems) const { return func->aggregate_attributes_string(func_name, items, nitems); } /* We can have enum/set type after merging only if we have one enum|set field (or MIN|MAX(enum|set field)) and number of NULL fields */ bool Type_handler_typelib:: Item_hybrid_func_fix_attributes(THD *thd, const char *func_name, Type_handler_hybrid_field_type *handler, Type_all_attributes *func, Item **items, uint nitems) const { TYPELIB *typelib= NULL; for (uint i= 0; i < nitems; i++) { if ((typelib= items[i]->get_typelib())) break; } DBUG_ASSERT(typelib); // There must be at least one typelib func->set_typelib(typelib); return func->aggregate_attributes_string(func_name, items, nitems); } bool Type_handler_blob_common:: Item_hybrid_func_fix_attributes(THD *thd, const char *func_name, Type_handler_hybrid_field_type *handler, Type_all_attributes *func, Item **items, uint nitems) const { if (func->aggregate_attributes_string(func_name, items, nitems)) return true; handler->set_handler(blob_type_handler(func->max_length)); return false; } bool Type_handler_date_common:: Item_hybrid_func_fix_attributes(THD *thd, const char *func_name, Type_handler_hybrid_field_type *handler, Type_all_attributes *func, Item **items, uint nitems) const { func->fix_attributes_date(); return false; } bool Type_handler_time_common:: Item_hybrid_func_fix_attributes(THD *thd, const char *func_name, Type_handler_hybrid_field_type *handler, Type_all_attributes *func, Item **items, uint nitems) const { func->aggregate_attributes_temporal(MIN_TIME_WIDTH, items, nitems); return false; } bool Type_handler_datetime_common:: Item_hybrid_func_fix_attributes(THD *thd, const char *func_name, Type_handler_hybrid_field_type *handler, Type_all_attributes *func, Item **items, uint nitems) const { func->aggregate_attributes_temporal(MAX_DATETIME_WIDTH, items, nitems); return false; } bool Type_handler_timestamp_common:: Item_hybrid_func_fix_attributes(THD *thd, const char *func_name, Type_handler_hybrid_field_type *handler, Type_all_attributes *func, Item **items, uint nitems) const { func->aggregate_attributes_temporal(MAX_DATETIME_WIDTH, items, nitems); return false; } #ifdef HAVE_SPATIAL bool Type_handler_geometry:: Item_hybrid_func_fix_attributes(THD *thd, const char *func_name, Type_handler_hybrid_field_type *handler, Type_all_attributes *func, Item **items, uint nitems) const { DBUG_ASSERT(nitems > 0); Type_geometry_attributes gattr(items[0]->type_handler(), items[0]); for (uint i= 1; i < nitems; i++) gattr.join(items[i]); func->set_geometry_type(gattr.get_geometry_type()); func->collation.set(&my_charset_bin); func->unsigned_flag= false; func->decimals= 0; func->max_length= (uint32) UINT_MAX32; func->set_maybe_null(true); return false; } #endif /*************************************************************************/ bool Type_handler:: Item_func_min_max_fix_attributes(THD *thd, Item_func_min_max *func, Item **items, uint nitems) const { /* Aggregating attributes for LEAST/GREATES is exactly the same with aggregating for CASE-alike functions (e.g. COALESCE) for the majority of data type handlers. */ return Item_hybrid_func_fix_attributes(thd, func->func_name(), func, func, items, nitems); } bool Type_handler_real_result:: Item_func_min_max_fix_attributes(THD *thd, Item_func_min_max *func, Item **items, uint nitems) const { /* DOUBLE is an exception and aggregates attributes differently for LEAST/GREATEST vs CASE-alike functions. See the comment in Item_func_min_max::aggregate_attributes_real(). */ func->aggregate_attributes_real(items, nitems); return false; } /*************************************************************************/ /** MAX/MIN for the traditional numeric types preserve the exact data type from Fields, but do not preserve the exact type from Items: MAX(float_field) -> FLOAT MAX(smallint_field) -> LONGLONG MAX(COALESCE(float_field)) -> DOUBLE MAX(COALESCE(smallint_field)) -> LONGLONG QQ: Items should probably be fixed to preserve the exact type. */ bool Type_handler_numeric:: Item_sum_hybrid_fix_length_and_dec_numeric(Item_sum_hybrid *func, const Type_handler *handler) const { Item *item= func->arguments()[0]; Item *item2= item->real_item(); func->Type_std_attributes::set(item); /* MIN/MAX can return NULL for empty set indepedent of the used column */ func->maybe_null= func->null_value= true; if (item2->type() == Item::FIELD_ITEM) func->set_handler(item2->type_handler()); else func->set_handler(handler); return false; } bool Type_handler_int_result:: Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *func) const { return Item_sum_hybrid_fix_length_and_dec_numeric(func, &type_handler_longlong); } bool Type_handler_real_result:: Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *func) const { (void) Item_sum_hybrid_fix_length_and_dec_numeric(func, &type_handler_double); func->max_length= func->float_length(func->decimals); return false; } bool Type_handler_decimal_result:: Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *func) const { return Item_sum_hybrid_fix_length_and_dec_numeric(func, &type_handler_newdecimal); } /** MAX(str_field) converts ENUM/SET to CHAR, and preserve all other types for Fields. QQ: This works differently from UNION, which preserve the exact data type for ENUM/SET if the joined ENUM/SET fields are equally defined. Perhaps should be fixed. MAX(str_item) chooses the best suitable string type. */ bool Type_handler_string_result:: Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *func) const { Item *item= func->arguments()[0]; Item *item2= item->real_item(); func->Type_std_attributes::set(item); func->maybe_null= func->null_value= true; if (item2->type() == Item::FIELD_ITEM) { // Fields: convert ENUM/SET to CHAR, preserve the type otherwise. func->set_handler(item->type_handler()); } else { // Items: choose VARCHAR/BLOB/MEDIUMBLOB/LONGBLOB, depending on length. func->set_handler(type_handler_varchar. type_handler_adjusted_to_max_octet_length(func->max_length, func->collation.collation)); } return false; } /** Traditional temporal types always preserve the type of the argument. */ bool Type_handler_temporal_result:: Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *func) const { Item *item= func->arguments()[0]; func->Type_std_attributes::set(item); func->maybe_null= func->null_value= true; func->set_handler(item->type_handler()); return false; } /*************************************************************************/ bool Type_handler_int_result:: Item_sum_sum_fix_length_and_dec(Item_sum_sum *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_decimal_result:: Item_sum_sum_fix_length_and_dec(Item_sum_sum *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_temporal_result:: Item_sum_sum_fix_length_and_dec(Item_sum_sum *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_real_result:: Item_sum_sum_fix_length_and_dec(Item_sum_sum *item) const { item->fix_length_and_dec_double(); return false; } bool Type_handler_string_result:: Item_sum_sum_fix_length_and_dec(Item_sum_sum *item) const { item->fix_length_and_dec_double(); return false; } #ifdef HAVE_SPATIAL bool Type_handler_geometry:: Item_sum_sum_fix_length_and_dec(Item_sum_sum *item) const { return Item_func_or_sum_illegal_param("sum"); } #endif /*************************************************************************/ bool Type_handler_int_result:: Item_sum_avg_fix_length_and_dec(Item_sum_avg *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_decimal_result:: Item_sum_avg_fix_length_and_dec(Item_sum_avg *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_temporal_result:: Item_sum_avg_fix_length_and_dec(Item_sum_avg *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_real_result:: Item_sum_avg_fix_length_and_dec(Item_sum_avg *item) const { item->fix_length_and_dec_double(); return false; } bool Type_handler_string_result:: Item_sum_avg_fix_length_and_dec(Item_sum_avg *item) const { item->fix_length_and_dec_double(); return false; } #ifdef HAVE_SPATIAL bool Type_handler_geometry:: Item_sum_avg_fix_length_and_dec(Item_sum_avg *item) const { return Item_func_or_sum_illegal_param("avg"); } #endif /*************************************************************************/ bool Type_handler_int_result:: Item_sum_variance_fix_length_and_dec(Item_sum_variance *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_decimal_result:: Item_sum_variance_fix_length_and_dec(Item_sum_variance *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_temporal_result:: Item_sum_variance_fix_length_and_dec(Item_sum_variance *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_real_result:: Item_sum_variance_fix_length_and_dec(Item_sum_variance *item) const { item->fix_length_and_dec_double(); return false; } bool Type_handler_string_result:: Item_sum_variance_fix_length_and_dec(Item_sum_variance *item) const { item->fix_length_and_dec_double(); return false; } #ifdef HAVE_SPATIAL bool Type_handler_geometry:: Item_sum_variance_fix_length_and_dec(Item_sum_variance *item) const { return Item_func_or_sum_illegal_param(item); } #endif /*************************************************************************/ bool Type_handler_real_result::Item_val_bool(Item *item) const { return item->val_real() != 0.0; } bool Type_handler_int_result::Item_val_bool(Item *item) const { return item->val_int() != 0; } bool Type_handler_decimal_result::Item_val_bool(Item *item) const { my_decimal decimal_value; my_decimal *val= item->val_decimal(&decimal_value); if (val) return !my_decimal_is_zero(val); return false; } bool Type_handler_temporal_result::Item_val_bool(Item *item) const { return item->val_real() != 0.0; } bool Type_handler_string_result::Item_val_bool(Item *item) const { return item->val_real() != 0.0; } /*************************************************************************/ longlong Type_handler_real_result:: Item_val_int_signed_typecast(Item *item) const { return item->val_int(); } longlong Type_handler_int_result:: Item_val_int_signed_typecast(Item *item) const { return item->val_int(); } longlong Type_handler_decimal_result:: Item_val_int_signed_typecast(Item *item) const { return item->val_int(); } longlong Type_handler_temporal_result:: Item_val_int_signed_typecast(Item *item) const { return item->val_int(); } longlong Type_handler_string_result:: Item_val_int_signed_typecast(Item *item) const { return item->val_int_signed_typecast_from_str(); } /*************************************************************************/ longlong Type_handler_real_result:: Item_val_int_unsigned_typecast(Item *item) const { return item->val_int_unsigned_typecast_from_int(); } longlong Type_handler_int_result:: Item_val_int_unsigned_typecast(Item *item) const { return item->val_int_unsigned_typecast_from_int(); } longlong Type_handler_decimal_result:: Item_val_int_unsigned_typecast(Item *item) const { return item->val_int_unsigned_typecast_from_decimal(); } longlong Type_handler_temporal_result:: Item_val_int_unsigned_typecast(Item *item) const { return item->val_int_unsigned_typecast_from_int(); } longlong Type_handler_string_result:: Item_val_int_unsigned_typecast(Item *item) const { return item->val_int_unsigned_typecast_from_str(); } /*************************************************************************/ String * Type_handler_real_result::Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) const { return item->val_str_ascii_from_val_real(str); } String * Type_handler_decimal_result::Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) const { return item->val_str_ascii_from_val_real(str); } String * Type_handler_int_result::Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) const { return item->val_str_ascii_from_val_int(str); } String * Type_handler_temporal_result::Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) const { return item->val_str_ascii_from_val_str(str); } String * Type_handler_string_result::Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) const { return item->val_str_ascii_from_val_str(str); } /***************************************************************************/ String * Type_handler_decimal_result::Item_func_hybrid_field_type_val_str( Item_func_hybrid_field_type *item, String *str) const { return item->val_str_from_decimal_op(str); } double Type_handler_decimal_result::Item_func_hybrid_field_type_val_real( Item_func_hybrid_field_type *item) const { return item->val_real_from_decimal_op(); } longlong Type_handler_decimal_result::Item_func_hybrid_field_type_val_int( Item_func_hybrid_field_type *item) const { return item->val_int_from_decimal_op(); } my_decimal * Type_handler_decimal_result::Item_func_hybrid_field_type_val_decimal( Item_func_hybrid_field_type *item, my_decimal *dec) const { return item->val_decimal_from_decimal_op(dec); } bool Type_handler_decimal_result::Item_func_hybrid_field_type_get_date( Item_func_hybrid_field_type *item, MYSQL_TIME *ltime, ulonglong fuzzydate) const { return item->get_date_from_decimal_op(ltime, fuzzydate); } /***************************************************************************/ String * Type_handler_int_result::Item_func_hybrid_field_type_val_str( Item_func_hybrid_field_type *item, String *str) const { return item->val_str_from_int_op(str); } double Type_handler_int_result::Item_func_hybrid_field_type_val_real( Item_func_hybrid_field_type *item) const { return item->val_real_from_int_op(); } longlong Type_handler_int_result::Item_func_hybrid_field_type_val_int( Item_func_hybrid_field_type *item) const { return item->val_int_from_int_op(); } my_decimal * Type_handler_int_result::Item_func_hybrid_field_type_val_decimal( Item_func_hybrid_field_type *item, my_decimal *dec) const { return item->val_decimal_from_int_op(dec); } bool Type_handler_int_result::Item_func_hybrid_field_type_get_date( Item_func_hybrid_field_type *item, MYSQL_TIME *ltime, ulonglong fuzzydate) const { return item->get_date_from_int_op(ltime, fuzzydate); } /***************************************************************************/ String * Type_handler_real_result::Item_func_hybrid_field_type_val_str( Item_func_hybrid_field_type *item, String *str) const { return item->val_str_from_real_op(str); } double Type_handler_real_result::Item_func_hybrid_field_type_val_real( Item_func_hybrid_field_type *item) const { return item->val_real_from_real_op(); } longlong Type_handler_real_result::Item_func_hybrid_field_type_val_int( Item_func_hybrid_field_type *item) const { return item->val_int_from_real_op(); } my_decimal * Type_handler_real_result::Item_func_hybrid_field_type_val_decimal( Item_func_hybrid_field_type *item, my_decimal *dec) const { return item->val_decimal_from_real_op(dec); } bool Type_handler_real_result::Item_func_hybrid_field_type_get_date( Item_func_hybrid_field_type *item, MYSQL_TIME *ltime, ulonglong fuzzydate) const { return item->get_date_from_real_op(ltime, fuzzydate); } /***************************************************************************/ String * Type_handler_temporal_result::Item_func_hybrid_field_type_val_str( Item_func_hybrid_field_type *item, String *str) const { return item->val_str_from_date_op(str); } double Type_handler_temporal_result::Item_func_hybrid_field_type_val_real( Item_func_hybrid_field_type *item) const { return item->val_real_from_date_op(); } longlong Type_handler_temporal_result::Item_func_hybrid_field_type_val_int( Item_func_hybrid_field_type *item) const { return item->val_int_from_date_op(); } my_decimal * Type_handler_temporal_result::Item_func_hybrid_field_type_val_decimal( Item_func_hybrid_field_type *item, my_decimal *dec) const { return item->val_decimal_from_date_op(dec); } bool Type_handler_temporal_result::Item_func_hybrid_field_type_get_date( Item_func_hybrid_field_type *item, MYSQL_TIME *ltime, ulonglong fuzzydate) const { return item->get_date_from_date_op(ltime, fuzzydate); } /***************************************************************************/ String * Type_handler_string_result::Item_func_hybrid_field_type_val_str( Item_func_hybrid_field_type *item, String *str) const { return item->val_str_from_str_op(str); } double Type_handler_string_result::Item_func_hybrid_field_type_val_real( Item_func_hybrid_field_type *item) const { return item->val_real_from_str_op(); } longlong Type_handler_string_result::Item_func_hybrid_field_type_val_int( Item_func_hybrid_field_type *item) const { return item->val_int_from_str_op(); } my_decimal * Type_handler_string_result::Item_func_hybrid_field_type_val_decimal( Item_func_hybrid_field_type *item, my_decimal *dec) const { return item->val_decimal_from_str_op(dec); } bool Type_handler_string_result::Item_func_hybrid_field_type_get_date( Item_func_hybrid_field_type *item, MYSQL_TIME *ltime, ulonglong fuzzydate) const { return item->get_date_from_str_op(ltime, fuzzydate); } /***************************************************************************/ bool Type_handler_numeric:: Item_func_between_fix_length_and_dec(Item_func_between *func) const { return func->fix_length_and_dec_numeric(current_thd); } bool Type_handler_temporal_result:: Item_func_between_fix_length_and_dec(Item_func_between *func) const { return func->fix_length_and_dec_temporal(current_thd); } bool Type_handler_string_result:: Item_func_between_fix_length_and_dec(Item_func_between *func) const { return func->fix_length_and_dec_string(current_thd); } longlong Type_handler_row:: Item_func_between_val_int(Item_func_between *func) const { DBUG_ASSERT(0); func->null_value= true; return 0; } longlong Type_handler_string_result:: Item_func_between_val_int(Item_func_between *func) const { return func->val_int_cmp_string(); } longlong Type_handler_temporal_result:: Item_func_between_val_int(Item_func_between *func) const { return func->val_int_cmp_temporal(); } longlong Type_handler_int_result:: Item_func_between_val_int(Item_func_between *func) const { return func->val_int_cmp_int(); } longlong Type_handler_real_result:: Item_func_between_val_int(Item_func_between *func) const { return func->val_int_cmp_real(); } longlong Type_handler_decimal_result:: Item_func_between_val_int(Item_func_between *func) const { return func->val_int_cmp_decimal(); } /***************************************************************************/ cmp_item *Type_handler_int_result::make_cmp_item(THD *thd, CHARSET_INFO *cs) const { return new (thd->mem_root) cmp_item_int; } cmp_item *Type_handler_real_result::make_cmp_item(THD *thd, CHARSET_INFO *cs) const { return new (thd->mem_root) cmp_item_real; } cmp_item *Type_handler_decimal_result::make_cmp_item(THD *thd, CHARSET_INFO *cs) const { return new (thd->mem_root) cmp_item_decimal; } cmp_item *Type_handler_string_result::make_cmp_item(THD *thd, CHARSET_INFO *cs) const { return new (thd->mem_root) cmp_item_sort_string(cs); } cmp_item *Type_handler_row::make_cmp_item(THD *thd, CHARSET_INFO *cs) const { return new (thd->mem_root) cmp_item_row; } cmp_item *Type_handler_time_common::make_cmp_item(THD *thd, CHARSET_INFO *cs) const { return new (thd->mem_root) cmp_item_time; } cmp_item *Type_handler_temporal_with_date::make_cmp_item(THD *thd, CHARSET_INFO *cs) const { return new (thd->mem_root) cmp_item_datetime; } /***************************************************************************/ static int srtcmp_in(CHARSET_INFO *cs, const String *x,const String *y) { return cs->coll->strnncollsp(cs, (uchar *) x->ptr(),x->length(), (uchar *) y->ptr(),y->length()); } in_vector *Type_handler_string_result::make_in_vector(THD *thd, const Item_func_in *func, uint nargs) const { return new (thd->mem_root) in_string(thd, nargs, (qsort2_cmp) srtcmp_in, func->compare_collation()); } in_vector *Type_handler_int_result::make_in_vector(THD *thd, const Item_func_in *func, uint nargs) const { return new (thd->mem_root) in_longlong(thd, nargs); } in_vector *Type_handler_real_result::make_in_vector(THD *thd, const Item_func_in *func, uint nargs) const { return new (thd->mem_root) in_double(thd, nargs); } in_vector *Type_handler_decimal_result::make_in_vector(THD *thd, const Item_func_in *func, uint nargs) const { return new (thd->mem_root) in_decimal(thd, nargs); } in_vector *Type_handler_time_common::make_in_vector(THD *thd, const Item_func_in *func, uint nargs) const { return new (thd->mem_root) in_time(thd, nargs); } in_vector * Type_handler_temporal_with_date::make_in_vector(THD *thd, const Item_func_in *func, uint nargs) const { return new (thd->mem_root) in_datetime(thd, nargs); } in_vector *Type_handler_row::make_in_vector(THD *thd, const Item_func_in *func, uint nargs) const { return new (thd->mem_root) in_row(thd, nargs, 0); } /***************************************************************************/ bool Type_handler_string_result:: Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *func) const { if (func->agg_all_arg_charsets_for_comparison()) return true; if (func->compatible_types_scalar_bisection_possible()) { return func->value_list_convert_const_to_int(thd) || func->fix_for_scalar_comparison_using_bisection(thd); } return func->fix_for_scalar_comparison_using_cmp_items(thd, 1U << (uint) STRING_RESULT); } bool Type_handler_int_result:: Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *func) const { /* Does not need to call value_list_convert_const_to_int() as already handled by int handler. */ return func->compatible_types_scalar_bisection_possible() ? func->fix_for_scalar_comparison_using_bisection(thd) : func->fix_for_scalar_comparison_using_cmp_items(thd, 1U << (uint) INT_RESULT); } bool Type_handler_real_result:: Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *func) const { return func->compatible_types_scalar_bisection_possible() ? (func->value_list_convert_const_to_int(thd) || func->fix_for_scalar_comparison_using_bisection(thd)) : func->fix_for_scalar_comparison_using_cmp_items(thd, 1U << (uint) REAL_RESULT); } bool Type_handler_decimal_result:: Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *func) const { return func->compatible_types_scalar_bisection_possible() ? (func->value_list_convert_const_to_int(thd) || func->fix_for_scalar_comparison_using_bisection(thd)) : func->fix_for_scalar_comparison_using_cmp_items(thd, 1U << (uint) DECIMAL_RESULT); } bool Type_handler_temporal_result:: Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *func) const { return func->compatible_types_scalar_bisection_possible() ? (func->value_list_convert_const_to_int(thd) || func->fix_for_scalar_comparison_using_bisection(thd)) : func->fix_for_scalar_comparison_using_cmp_items(thd, 1U << (uint) TIME_RESULT); } bool Type_handler_row::Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *func) const { return func->compatible_types_row_bisection_possible() ? func->fix_for_row_comparison_using_bisection(thd) : func->fix_for_row_comparison_using_cmp_items(thd); } /***************************************************************************/ String *Type_handler_string_result:: Item_func_min_max_val_str(Item_func_min_max *func, String *str) const { return func->val_str_native(str); } String *Type_handler_temporal_result:: Item_func_min_max_val_str(Item_func_min_max *func, String *str) const { return func->val_string_from_date(str); } String *Type_handler_int_result:: Item_func_min_max_val_str(Item_func_min_max *func, String *str) const { return func->val_string_from_int(str); } String *Type_handler_decimal_result:: Item_func_min_max_val_str(Item_func_min_max *func, String *str) const { return func->val_string_from_decimal(str); } String *Type_handler_real_result:: Item_func_min_max_val_str(Item_func_min_max *func, String *str) const { return func->val_string_from_real(str); } double Type_handler_string_result:: Item_func_min_max_val_real(Item_func_min_max *func) const { return func->val_real_native(); } double Type_handler_temporal_result:: Item_func_min_max_val_real(Item_func_min_max *func) const { MYSQL_TIME ltime; if (func->get_date(&ltime, 0)) return 0; return TIME_to_double(&ltime); } double Type_handler_numeric:: Item_func_min_max_val_real(Item_func_min_max *func) const { return func->val_real_native(); } longlong Type_handler_string_result:: Item_func_min_max_val_int(Item_func_min_max *func) const { return func->val_int_native(); } longlong Type_handler_temporal_result:: Item_func_min_max_val_int(Item_func_min_max *func) const { MYSQL_TIME ltime; if (func->get_date(&ltime, 0)) return 0; return TIME_to_ulonglong(&ltime); } longlong Type_handler_numeric:: Item_func_min_max_val_int(Item_func_min_max *func) const { return func->val_int_native(); } my_decimal *Type_handler_string_result:: Item_func_min_max_val_decimal(Item_func_min_max *func, my_decimal *dec) const { return func->val_decimal_native(dec); } my_decimal *Type_handler_numeric:: Item_func_min_max_val_decimal(Item_func_min_max *func, my_decimal *dec) const { return func->val_decimal_native(dec); } my_decimal *Type_handler_temporal_result:: Item_func_min_max_val_decimal(Item_func_min_max *func, my_decimal *dec) const { MYSQL_TIME ltime; if (func->get_date(&ltime, 0)) return 0; return date2my_decimal(&ltime, dec); } bool Type_handler_string_result:: Item_func_min_max_get_date(Item_func_min_max *func, MYSQL_TIME *ltime, ulonglong fuzzydate) const { /* just like ::val_int() method of a string item can be called, for example, SELECT CONCAT("10", "12") + 1, ::get_date() can be called for non-temporal values, for example, SELECT MONTH(GREATEST("2011-11-21", "2010-10-09")) */ return func->Item::get_date(ltime, fuzzydate); } bool Type_handler_numeric:: Item_func_min_max_get_date(Item_func_min_max *func, MYSQL_TIME *ltime, ulonglong fuzzydate) const { return func->Item::get_date(ltime, fuzzydate); } bool Type_handler_temporal_result:: Item_func_min_max_get_date(Item_func_min_max *func, MYSQL_TIME *ltime, ulonglong fuzzydate) const { return func->get_date_native(ltime, fuzzydate); } /***************************************************************************/ /** Get a string representation of the Item value. See sql_type.h for details. */ String *Type_handler_row:: print_item_value(THD *thd, Item *item, String *str) const { CHARSET_INFO *cs= thd->variables.character_set_client; StringBuffer<STRING_BUFFER_USUAL_SIZE> val(cs); str->append(C_STRING_WITH_LEN("ROW(")); for (uint i= 0 ; i < item->cols(); i++) { if (i > 0) str->append(','); Item *elem= item->element_index(i); String *tmp= elem->type_handler()->print_item_value(thd, elem, &val); if (tmp) str->append(*tmp); else str->append(STRING_WITH_LEN("NULL")); } str->append(C_STRING_WITH_LEN(")")); return str; } /** Get a string representation of the Item value, using the character string format with its charset and collation, e.g. latin1 'string' COLLATE latin1_german2_ci */ String *Type_handler:: print_item_value_csstr(THD *thd, Item *item, String *str) const { String *result= item->val_str(str); if (!result) return NULL; StringBuffer<STRING_BUFFER_USUAL_SIZE> buf(result->charset()); CHARSET_INFO *cs= thd->variables.character_set_client; buf.append('_'); buf.append(result->charset()->csname); if (cs->escape_with_backslash_is_dangerous) buf.append(' '); append_query_string(cs, &buf, result->ptr(), result->length(), thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES); buf.append(" COLLATE '"); buf.append(item->collation.collation->name); buf.append('\''); str->copy(buf); return str; } String *Type_handler_numeric:: print_item_value(THD *thd, Item *item, String *str) const { return item->val_str(str); } String *Type_handler:: print_item_value_temporal(THD *thd, Item *item, String *str, const Name &type_name, String *buf) const { String *result= item->val_str(buf); return !result || str->realloc(type_name.length() + result->length() + 2) || str->copy(type_name.ptr(), type_name.length(), &my_charset_latin1) || str->append('\'') || str->append(result->ptr(), result->length()) || str->append('\'') ? NULL : str; } String *Type_handler_time_common:: print_item_value(THD *thd, Item *item, String *str) const { StringBuffer<MAX_TIME_FULL_WIDTH+1> buf; return print_item_value_temporal(thd, item, str, Name(C_STRING_WITH_LEN("TIME")), &buf); } String *Type_handler_date_common:: print_item_value(THD *thd, Item *item, String *str) const { StringBuffer<MAX_DATE_WIDTH+1> buf; return print_item_value_temporal(thd, item, str, Name(C_STRING_WITH_LEN("DATE")), &buf); } String *Type_handler_datetime_common:: print_item_value(THD *thd, Item *item, String *str) const { StringBuffer<MAX_DATETIME_FULL_WIDTH+1> buf; return print_item_value_temporal(thd, item, str, Name(C_STRING_WITH_LEN("TIMESTAMP")), &buf); } String *Type_handler_timestamp_common:: print_item_value(THD *thd, Item *item, String *str) const { StringBuffer<MAX_DATETIME_FULL_WIDTH+1> buf; return print_item_value_temporal(thd, item, str, Name(C_STRING_WITH_LEN("TIMESTAMP")), &buf); } /***************************************************************************/ bool Type_handler_row:: Item_func_round_fix_length_and_dec(Item_func_round *item) const { DBUG_ASSERT(0); return false; } bool Type_handler_int_result:: Item_func_round_fix_length_and_dec(Item_func_round *item) const { item->fix_arg_int(); return false; } bool Type_handler_real_result:: Item_func_round_fix_length_and_dec(Item_func_round *item) const { item->fix_arg_double(); return false; } bool Type_handler_decimal_result:: Item_func_round_fix_length_and_dec(Item_func_round *item) const { item->fix_arg_decimal(); return false; } bool Type_handler_temporal_result:: Item_func_round_fix_length_and_dec(Item_func_round *item) const { item->fix_arg_double(); return false; } bool Type_handler_string_result:: Item_func_round_fix_length_and_dec(Item_func_round *item) const { item->fix_arg_double(); return false; } #ifdef HAVE_SPATIAL bool Type_handler_geometry:: Item_func_round_fix_length_and_dec(Item_func_round *item) const { return Item_func_or_sum_illegal_param(item); } #endif /***************************************************************************/ bool Type_handler_row:: Item_func_int_val_fix_length_and_dec(Item_func_int_val *item) const { DBUG_ASSERT(0); return false; } bool Type_handler_int_result:: Item_func_int_val_fix_length_and_dec(Item_func_int_val *item) const { item->fix_length_and_dec_int_or_decimal(); return false; } bool Type_handler_real_result:: Item_func_int_val_fix_length_and_dec(Item_func_int_val *item) const { item->fix_length_and_dec_double(); return false; } bool Type_handler_decimal_result:: Item_func_int_val_fix_length_and_dec(Item_func_int_val *item) const { item->fix_length_and_dec_int_or_decimal(); return false; } bool Type_handler_temporal_result:: Item_func_int_val_fix_length_and_dec(Item_func_int_val *item) const { item->fix_length_and_dec_int_or_decimal(); return false; } bool Type_handler_string_result:: Item_func_int_val_fix_length_and_dec(Item_func_int_val *item) const { item->fix_length_and_dec_double(); return false; } #ifdef HAVE_SPATIAL bool Type_handler_geometry:: Item_func_int_val_fix_length_and_dec(Item_func_int_val *item) const { return Item_func_or_sum_illegal_param(item); } #endif /***************************************************************************/ bool Type_handler_row:: Item_func_abs_fix_length_and_dec(Item_func_abs *item) const { DBUG_ASSERT(0); return false; } bool Type_handler_int_result:: Item_func_abs_fix_length_and_dec(Item_func_abs *item) const { item->fix_length_and_dec_int(); return false; } bool Type_handler_real_result:: Item_func_abs_fix_length_and_dec(Item_func_abs *item) const { item->fix_length_and_dec_double(); return false; } bool Type_handler_decimal_result:: Item_func_abs_fix_length_and_dec(Item_func_abs *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_temporal_result:: Item_func_abs_fix_length_and_dec(Item_func_abs *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_string_result:: Item_func_abs_fix_length_and_dec(Item_func_abs *item) const { item->fix_length_and_dec_double(); return false; } #ifdef HAVE_SPATIAL bool Type_handler_geometry:: Item_func_abs_fix_length_and_dec(Item_func_abs *item) const { return Item_func_or_sum_illegal_param(item); } #endif /***************************************************************************/ bool Type_handler_row:: Item_func_neg_fix_length_and_dec(Item_func_neg *item) const { DBUG_ASSERT(0); return false; } bool Type_handler_int_result:: Item_func_neg_fix_length_and_dec(Item_func_neg *item) const { item->fix_length_and_dec_int(); return false; } bool Type_handler_real_result:: Item_func_neg_fix_length_and_dec(Item_func_neg *item) const { item->fix_length_and_dec_double(); return false; } bool Type_handler_decimal_result:: Item_func_neg_fix_length_and_dec(Item_func_neg *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_temporal_result:: Item_func_neg_fix_length_and_dec(Item_func_neg *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_string_result:: Item_func_neg_fix_length_and_dec(Item_func_neg *item) const { item->fix_length_and_dec_double(); return false; } #ifdef HAVE_SPATIAL bool Type_handler_geometry:: Item_func_neg_fix_length_and_dec(Item_func_neg *item) const { return Item_func_or_sum_illegal_param(item); } #endif /***************************************************************************/ bool Type_handler:: Item_func_signed_fix_length_and_dec(Item_func_signed *item) const { item->fix_length_and_dec_generic(); return false; } bool Type_handler:: Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *item) const { const Item *arg= item->arguments()[0]; if (!arg->unsigned_flag && arg->val_int_min() < 0) { /* Negative arguments produce long results: CAST(1-2 AS UNSIGNED) -> 18446744073709551615 */ item->max_length= MAX_BIGINT_WIDTH; return false; } item->fix_length_and_dec_generic(); return false; } bool Type_handler_string_result:: Item_func_signed_fix_length_and_dec(Item_func_signed *item) const { item->fix_length_and_dec_string(); return false; } bool Type_handler_string_result:: Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *item) const { const Item *arg= item->arguments()[0]; if (!arg->unsigned_flag && // Not HEX hybrid arg->max_char_length() > 1) // Can be negative { // String arguments can give long results: '-1' -> 18446744073709551614 item->max_length= MAX_BIGINT_WIDTH; return false; } item->fix_length_and_dec_string(); return false; } bool Type_handler_real_result:: Item_func_signed_fix_length_and_dec(Item_func_signed *item) const { item->fix_length_and_dec_double(); return false; } bool Type_handler_real_result:: Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *item) const { item->fix_length_and_dec_double(); return false; } bool Type_handler:: Item_double_typecast_fix_length_and_dec(Item_double_typecast *item) const { item->fix_length_and_dec_generic(); return false; } bool Type_handler:: Item_decimal_typecast_fix_length_and_dec(Item_decimal_typecast *item) const { item->fix_length_and_dec_generic(); return false; } bool Type_handler:: Item_char_typecast_fix_length_and_dec(Item_char_typecast *item) const { item->fix_length_and_dec_generic(); return false; } bool Type_handler_numeric:: Item_char_typecast_fix_length_and_dec(Item_char_typecast *item) const { item->fix_length_and_dec_numeric(); return false; } bool Type_handler_string_result:: Item_char_typecast_fix_length_and_dec(Item_char_typecast *item) const { item->fix_length_and_dec_str(); return false; } bool Type_handler:: Item_time_typecast_fix_length_and_dec(Item_time_typecast *item) const { uint dec= item->decimals == NOT_FIXED_DEC ? item->arguments()[0]->time_precision() : item->decimals; item->fix_attributes_temporal(MIN_TIME_WIDTH, dec); item->maybe_null= true; return false; } bool Type_handler:: Item_date_typecast_fix_length_and_dec(Item_date_typecast *item) const { item->fix_attributes_temporal(MAX_DATE_WIDTH, 0); item->maybe_null= true; return false; } bool Type_handler:: Item_datetime_typecast_fix_length_and_dec(Item_datetime_typecast *item) const { uint dec= item->decimals == NOT_FIXED_DEC ? item->arguments()[0]->datetime_precision() : item->decimals; item->fix_attributes_temporal(MAX_DATETIME_WIDTH, dec); item->maybe_null= true; return false; } bool Type_handler:: Item_longlong_typecast_fix_length_and_dec(Item_longlong_typecast *item) const { item->fix_length_and_dec_generic(); return false; } #ifdef HAVE_SPATIAL bool Type_handler_geometry:: Item_func_signed_fix_length_and_dec(Item_func_signed *item) const { return Item_func_or_sum_illegal_param(item); } bool Type_handler_geometry:: Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *item) const { return Item_func_or_sum_illegal_param(item); } bool Type_handler_geometry:: Item_double_typecast_fix_length_and_dec(Item_double_typecast *item) const { return Item_func_or_sum_illegal_param(item); } bool Type_handler_geometry:: Item_decimal_typecast_fix_length_and_dec(Item_decimal_typecast *item) const { return Item_func_or_sum_illegal_param(item); } bool Type_handler_geometry:: Item_char_typecast_fix_length_and_dec(Item_char_typecast *item) const { if (item->cast_charset() != &my_charset_bin) return Item_func_or_sum_illegal_param(item); // CAST(geom AS CHAR) item->fix_length_and_dec_str(); return false; // CAST(geom AS BINARY) } bool Type_handler_geometry:: Item_time_typecast_fix_length_and_dec(Item_time_typecast *item) const { return Item_func_or_sum_illegal_param(item); } bool Type_handler_geometry:: Item_date_typecast_fix_length_and_dec(Item_date_typecast *item) const { return Item_func_or_sum_illegal_param(item); } bool Type_handler_geometry:: Item_datetime_typecast_fix_length_and_dec(Item_datetime_typecast *item) const { return Item_func_or_sum_illegal_param(item); } #endif /* HAVE_SPATIAL */ /***************************************************************************/ bool Type_handler_row:: Item_func_plus_fix_length_and_dec(Item_func_plus *item) const { DBUG_ASSERT(0); return true; } bool Type_handler_int_result:: Item_func_plus_fix_length_and_dec(Item_func_plus *item) const { item->fix_length_and_dec_int(); return false; } bool Type_handler_real_result:: Item_func_plus_fix_length_and_dec(Item_func_plus *item) const { item->fix_length_and_dec_double(); return false; } bool Type_handler_decimal_result:: Item_func_plus_fix_length_and_dec(Item_func_plus *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_temporal_result:: Item_func_plus_fix_length_and_dec(Item_func_plus *item) const { item->fix_length_and_dec_temporal(); return false; } bool Type_handler_string_result:: Item_func_plus_fix_length_and_dec(Item_func_plus *item) const { item->fix_length_and_dec_double(); return false; } /***************************************************************************/ bool Type_handler_row:: Item_func_minus_fix_length_and_dec(Item_func_minus *item) const { DBUG_ASSERT(0); return true; } bool Type_handler_int_result:: Item_func_minus_fix_length_and_dec(Item_func_minus *item) const { item->fix_length_and_dec_int(); return false; } bool Type_handler_real_result:: Item_func_minus_fix_length_and_dec(Item_func_minus *item) const { item->fix_length_and_dec_double(); return false; } bool Type_handler_decimal_result:: Item_func_minus_fix_length_and_dec(Item_func_minus *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_temporal_result:: Item_func_minus_fix_length_and_dec(Item_func_minus *item) const { item->fix_length_and_dec_temporal(); return false; } bool Type_handler_string_result:: Item_func_minus_fix_length_and_dec(Item_func_minus *item) const { item->fix_length_and_dec_double(); return false; } /***************************************************************************/ bool Type_handler_row:: Item_func_mul_fix_length_and_dec(Item_func_mul *item) const { DBUG_ASSERT(0); return true; } bool Type_handler_int_result:: Item_func_mul_fix_length_and_dec(Item_func_mul *item) const { item->fix_length_and_dec_int(); return false; } bool Type_handler_real_result:: Item_func_mul_fix_length_and_dec(Item_func_mul *item) const { item->fix_length_and_dec_double(); return false; } bool Type_handler_decimal_result:: Item_func_mul_fix_length_and_dec(Item_func_mul *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_temporal_result:: Item_func_mul_fix_length_and_dec(Item_func_mul *item) const { item->fix_length_and_dec_temporal(); return false; } bool Type_handler_string_result:: Item_func_mul_fix_length_and_dec(Item_func_mul *item) const { item->fix_length_and_dec_double(); return false; } /***************************************************************************/ bool Type_handler_row:: Item_func_div_fix_length_and_dec(Item_func_div *item) const { DBUG_ASSERT(0); return true; } bool Type_handler_int_result:: Item_func_div_fix_length_and_dec(Item_func_div *item) const { item->fix_length_and_dec_int(); return false; } bool Type_handler_real_result:: Item_func_div_fix_length_and_dec(Item_func_div *item) const { item->fix_length_and_dec_double(); return false; } bool Type_handler_decimal_result:: Item_func_div_fix_length_and_dec(Item_func_div *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_temporal_result:: Item_func_div_fix_length_and_dec(Item_func_div *item) const { item->fix_length_and_dec_temporal(); return false; } bool Type_handler_string_result:: Item_func_div_fix_length_and_dec(Item_func_div *item) const { item->fix_length_and_dec_double(); return false; } /***************************************************************************/ bool Type_handler_row:: Item_func_mod_fix_length_and_dec(Item_func_mod *item) const { DBUG_ASSERT(0); return true; } bool Type_handler_int_result:: Item_func_mod_fix_length_and_dec(Item_func_mod *item) const { item->fix_length_and_dec_int(); return false; } bool Type_handler_real_result:: Item_func_mod_fix_length_and_dec(Item_func_mod *item) const { item->fix_length_and_dec_double(); return false; } bool Type_handler_decimal_result:: Item_func_mod_fix_length_and_dec(Item_func_mod *item) const { item->fix_length_and_dec_decimal(); return false; } bool Type_handler_temporal_result:: Item_func_mod_fix_length_and_dec(Item_func_mod *item) const { item->fix_length_and_dec_temporal(); return false; } bool Type_handler_string_result:: Item_func_mod_fix_length_and_dec(Item_func_mod *item) const { item->fix_length_and_dec_double(); return false; } /***************************************************************************/ uint Type_handler::Item_time_precision(Item *item) const { return MY_MIN(item->decimals, TIME_SECOND_PART_DIGITS); } uint Type_handler::Item_datetime_precision(Item *item) const { return MY_MIN(item->decimals, TIME_SECOND_PART_DIGITS); } uint Type_handler_string_result::Item_temporal_precision(Item *item, bool is_time) const { MYSQL_TIME ltime; StringBuffer<64> buf; String *tmp; MYSQL_TIME_STATUS status; DBUG_ASSERT(item->fixed); if ((tmp= item->val_str(&buf)) && !(is_time ? str_to_time(tmp->charset(), tmp->ptr(), tmp->length(), &ltime, TIME_TIME_ONLY, &status) : str_to_datetime(tmp->charset(), tmp->ptr(), tmp->length(), &ltime, TIME_FUZZY_DATES, &status))) return MY_MIN(status.precision, TIME_SECOND_PART_DIGITS); return MY_MIN(item->decimals, TIME_SECOND_PART_DIGITS); } /***************************************************************************/ uint Type_handler::Item_decimal_scale(const Item *item) const { return item->decimals < NOT_FIXED_DEC ? item->decimals : MY_MIN(item->max_length, DECIMAL_MAX_SCALE); } uint Type_handler_temporal_result:: Item_decimal_scale_with_seconds(const Item *item) const { return item->decimals < NOT_FIXED_DEC ? item->decimals : TIME_SECOND_PART_DIGITS; } uint Type_handler::Item_divisor_precision_increment(const Item *item) const { return item->decimals; } uint Type_handler_temporal_result:: Item_divisor_precision_increment_with_seconds(const Item *item) const { return item->decimals < NOT_FIXED_DEC ? item->decimals : TIME_SECOND_PART_DIGITS; } /***************************************************************************/ uint Type_handler_string_result::Item_decimal_precision(const Item *item) const { uint res= item->max_char_length(); /* Return at least one decimal digit, even if Item::max_char_length() returned 0. This is important to avoid attempts to create fields of types INT(0) or DECIMAL(0,0) when converting NULL or empty strings to INT/DECIMAL: CREATE TABLE t1 AS SELECT CONVERT(NULL,SIGNED) AS a; */ return res ? MY_MIN(res, DECIMAL_MAX_PRECISION) : 1; } uint Type_handler_real_result::Item_decimal_precision(const Item *item) const { uint res= item->max_char_length(); return res ? MY_MIN(res, DECIMAL_MAX_PRECISION) : 1; } uint Type_handler_decimal_result::Item_decimal_precision(const Item *item) const { uint prec= my_decimal_length_to_precision(item->max_char_length(), item->decimals, item->unsigned_flag); return MY_MIN(prec, DECIMAL_MAX_PRECISION); } uint Type_handler_int_result::Item_decimal_precision(const Item *item) const { uint prec= my_decimal_length_to_precision(item->max_char_length(), item->decimals, item->unsigned_flag); return MY_MIN(prec, DECIMAL_MAX_PRECISION); } uint Type_handler_time_common::Item_decimal_precision(const Item *item) const { return 7 + MY_MIN(item->decimals, TIME_SECOND_PART_DIGITS); } uint Type_handler_date_common::Item_decimal_precision(const Item *item) const { return 8; } uint Type_handler_datetime_common::Item_decimal_precision(const Item *item) const { return 14 + MY_MIN(item->decimals, TIME_SECOND_PART_DIGITS); } uint Type_handler_timestamp_common::Item_decimal_precision(const Item *item) const { return 14 + MY_MIN(item->decimals, TIME_SECOND_PART_DIGITS); } /***************************************************************************/ bool Type_handler_real_result:: subquery_type_allows_materialization(const Item *inner, const Item *outer) const { DBUG_ASSERT(inner->cmp_type() == REAL_RESULT); return outer->cmp_type() == REAL_RESULT; } bool Type_handler_int_result:: subquery_type_allows_materialization(const Item *inner, const Item *outer) const { DBUG_ASSERT(inner->cmp_type() == INT_RESULT); return outer->cmp_type() == INT_RESULT; } bool Type_handler_decimal_result:: subquery_type_allows_materialization(const Item *inner, const Item *outer) const { DBUG_ASSERT(inner->cmp_type() == DECIMAL_RESULT); return outer->cmp_type() == DECIMAL_RESULT; } bool Type_handler_string_result:: subquery_type_allows_materialization(const Item *inner, const Item *outer) const { DBUG_ASSERT(inner->cmp_type() == STRING_RESULT); return outer->cmp_type() == STRING_RESULT && outer->collation.collation == inner->collation.collation && /* Materialization also is unable to work when create_tmp_table() will create a blob column because item->max_length is too big. The following test is copied from varstring_type_handler(). */ !inner->too_big_for_varchar(); } bool Type_handler_temporal_result:: subquery_type_allows_materialization(const Item *inner, const Item *outer) const { DBUG_ASSERT(inner->cmp_type() == TIME_RESULT); return mysql_timestamp_type() == outer->type_handler()->mysql_timestamp_type(); } /***************************************************************************/ const Type_handler * Type_handler_null::type_handler_for_tmp_table(const Item *item) const { return &type_handler_string; } const Type_handler * Type_handler_null::type_handler_for_union(const Item *item) const { return &type_handler_string; } const Type_handler * Type_handler_olddecimal::type_handler_for_tmp_table(const Item *item) const { return &type_handler_newdecimal; } const Type_handler * Type_handler_olddecimal::type_handler_for_union(const Item *item) const { return &type_handler_newdecimal; } /***************************************************************************/ bool Type_handler::check_null(const Item *item, st_value *value) const { if (item->null_value) { value->m_type= DYN_COL_NULL; return true; } return false; } bool Type_handler_null:: Item_save_in_value(Item *item, st_value *value) const { value->m_type= DYN_COL_NULL; return true; } bool Type_handler_row:: Item_save_in_value(Item *item, st_value *value) const { DBUG_ASSERT(0); value->m_type= DYN_COL_NULL; return true; } bool Type_handler_int_result:: Item_save_in_value(Item *item, st_value *value) const { value->m_type= item->unsigned_flag ? DYN_COL_UINT : DYN_COL_INT; value->value.m_longlong= item->val_int(); return check_null(item, value); } bool Type_handler_real_result:: Item_save_in_value(Item *item, st_value *value) const { value->m_type= DYN_COL_DOUBLE; value->value.m_double= item->val_real(); return check_null(item, value); } bool Type_handler_decimal_result:: Item_save_in_value(Item *item, st_value *value) const { value->m_type= DYN_COL_DECIMAL; my_decimal *dec= item->val_decimal(&value->m_decimal); if (dec != &value->m_decimal && !item->null_value) my_decimal2decimal(dec, &value->m_decimal); return check_null(item, value); } bool Type_handler_string_result:: Item_save_in_value(Item *item, st_value *value) const { value->m_type= DYN_COL_STRING; String *str= item->val_str(&value->m_string); if (str != &value->m_string && !item->null_value) value->m_string.set(str->ptr(), str->length(), str->charset()); return check_null(item, value); } bool Type_handler_temporal_with_date:: Item_save_in_value(Item *item, st_value *value) const { value->m_type= DYN_COL_DATETIME; item->get_date(&value->value.m_time, sql_mode_for_dates(current_thd)); return check_null(item, value); } bool Type_handler_time_common:: Item_save_in_value(Item *item, st_value *value) const { value->m_type= DYN_COL_DATETIME; item->get_time(&value->value.m_time); return check_null(item, value); } /***************************************************************************/ bool Type_handler_row:: Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *val) const { DBUG_ASSERT(0); param->set_null(); return true; } bool Type_handler_real_result:: Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *val) const { param->unsigned_flag= attr->unsigned_flag; param->set_double(val->value.m_double); return false; } bool Type_handler_int_result:: Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *val) const { param->unsigned_flag= attr->unsigned_flag; param->set_int(val->value.m_longlong, attr->max_length); return false; } bool Type_handler_decimal_result:: Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *val) const { param->unsigned_flag= attr->unsigned_flag; param->set_decimal(&val->m_decimal, attr->unsigned_flag); return false; } bool Type_handler_string_result:: Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *val) const { param->unsigned_flag= false; param->setup_conversion_string(thd, attr->collation.collation); /* Exact value of max_length is not known unless data is converted to charset of connection, so we have to set it later. */ return param->set_str(val->m_string.ptr(), val->m_string.length(), attr->collation.collation, attr->collation.collation); } bool Type_handler_temporal_result:: Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *val) const { param->unsigned_flag= attr->unsigned_flag; param->set_time(&val->value.m_time, attr->max_length, attr->decimals); return false; } #ifdef HAVE_SPATIAL bool Type_handler_geometry:: Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *val) const { param->unsigned_flag= false; param->setup_conversion_blob(thd); param->set_geometry_type(attr->uint_geometry_type()); return param->set_str(val->m_string.ptr(), val->m_string.length(), &my_charset_bin, &my_charset_bin); } #endif /***************************************************************************/ bool Type_handler_null:: Item_send(Item *item, Protocol *protocol, st_value *buf) const { return protocol->store_null(); } bool Type_handler:: Item_send_str(Item *item, Protocol *protocol, st_value *buf) const { String *res; if ((res= item->val_str(&buf->m_string))) { DBUG_ASSERT(!item->null_value); return protocol->store(res->ptr(), res->length(), res->charset()); } DBUG_ASSERT(item->null_value); return protocol->store_null(); } bool Type_handler:: Item_send_tiny(Item *item, Protocol *protocol, st_value *buf) const { longlong nr= item->val_int(); if (!item->null_value) return protocol->store_tiny(nr); return protocol->store_null(); } bool Type_handler:: Item_send_short(Item *item, Protocol *protocol, st_value *buf) const { longlong nr= item->val_int(); if (!item->null_value) return protocol->store_short(nr); return protocol->store_null(); } bool Type_handler:: Item_send_long(Item *item, Protocol *protocol, st_value *buf) const { longlong nr= item->val_int(); if (!item->null_value) return protocol->store_long(nr); return protocol->store_null(); } bool Type_handler:: Item_send_longlong(Item *item, Protocol *protocol, st_value *buf) const { longlong nr= item->val_int(); if (!item->null_value) return protocol->store_longlong(nr, item->unsigned_flag); return protocol->store_null(); } bool Type_handler:: Item_send_float(Item *item, Protocol *protocol, st_value *buf) const { float nr= (float) item->val_real(); if (!item->null_value) return protocol->store(nr, item->decimals, &buf->m_string); return protocol->store_null(); } bool Type_handler:: Item_send_double(Item *item, Protocol *protocol, st_value *buf) const { double nr= item->val_real(); if (!item->null_value) return protocol->store(nr, item->decimals, &buf->m_string); return protocol->store_null(); } bool Type_handler:: Item_send_datetime(Item *item, Protocol *protocol, st_value *buf) const { item->get_date(&buf->value.m_time, sql_mode_for_dates(current_thd)); if (!item->null_value) return protocol->store(&buf->value.m_time, item->decimals); return protocol->store_null(); } bool Type_handler:: Item_send_date(Item *item, Protocol *protocol, st_value *buf) const { item->get_date(&buf->value.m_time, sql_mode_for_dates(current_thd)); if (!item->null_value) return protocol->store_date(&buf->value.m_time); return protocol->store_null(); } bool Type_handler:: Item_send_time(Item *item, Protocol *protocol, st_value *buf) const { item->get_time(&buf->value.m_time); if (!item->null_value) return protocol->store_time(&buf->value.m_time, item->decimals); return protocol->store_null(); } /***************************************************************************/ Item *Type_handler_int_result:: make_const_item_for_comparison(THD *thd, Item *item, const Item *cmp) const { longlong result= item->val_int(); if (item->null_value) return new (thd->mem_root) Item_null(thd, item->name.str); return new (thd->mem_root) Item_int(thd, item->name.str, result, item->max_length); } Item *Type_handler_real_result:: make_const_item_for_comparison(THD *thd, Item *item, const Item *cmp) const { double result= item->val_real(); if (item->null_value) return new (thd->mem_root) Item_null(thd, item->name.str); return new (thd->mem_root) Item_float(thd, item->name.str, result, item->decimals, item->max_length); } Item *Type_handler_decimal_result:: make_const_item_for_comparison(THD *thd, Item *item, const Item *cmp) const { my_decimal decimal_value; my_decimal *result= item->val_decimal(&decimal_value); if (item->null_value) return new (thd->mem_root) Item_null(thd, item->name.str); return new (thd->mem_root) Item_decimal(thd, item->name.str, result, item->max_length, item->decimals); } Item *Type_handler_string_result:: make_const_item_for_comparison(THD *thd, Item *item, const Item *cmp) const { StringBuffer<MAX_FIELD_WIDTH> tmp; String *result= item->val_str(&tmp); if (item->null_value) return new (thd->mem_root) Item_null(thd, item->name.str); uint length= result->length(); char *tmp_str= thd->strmake(result->ptr(), length); return new (thd->mem_root) Item_string(thd, item->name.str, tmp_str, length, result->charset()); } Item *Type_handler_time_common:: make_const_item_for_comparison(THD *thd, Item *item, const Item *cmp) const { Item_cache_temporal *cache; longlong value= item->val_time_packed(); if (item->null_value) return new (thd->mem_root) Item_null(thd, item->name.str); cache= new (thd->mem_root) Item_cache_time(thd); if (cache) cache->store_packed(value, item); return cache; } Item *Type_handler_temporal_with_date:: make_const_item_for_comparison(THD *thd, Item *item, const Item *cmp) const { Item_cache_temporal *cache; longlong value= item->val_datetime_packed(); if (item->null_value) return new (thd->mem_root) Item_null(thd, item->name.str); cache= new (thd->mem_root) Item_cache_datetime(thd); if (cache) cache->store_packed(value, item); return cache; } Item *Type_handler_row:: make_const_item_for_comparison(THD *thd, Item *item, const Item *cmp) const { if (item->type() == Item::ROW_ITEM && cmp->type() == Item::ROW_ITEM) { /* Substitute constants only in Item_row's. Don't affect other Items with ROW_RESULT (eg Item_singlerow_subselect). For such Items more optimal is to detect if it is constant and replace it with Item_row. This would optimize queries like this: SELECT * FROM t1 WHERE (a,b) = (SELECT a,b FROM t2 LIMIT 1); */ Item_row *item_row= (Item_row*) item; Item_row *comp_item_row= (Item_row*) cmp; uint col; /* If item and comp_item are both Item_row's and have same number of cols then process items in Item_row one by one. We can't ignore NULL values here as this item may be used with <=>, in which case NULL's are significant. */ DBUG_ASSERT(item->result_type() == cmp->result_type()); DBUG_ASSERT(item_row->cols() == comp_item_row->cols()); col= item_row->cols(); while (col-- > 0) resolve_const_item(thd, item_row->addr(col), comp_item_row->element_index(col)); } return NULL; } /***************************************************************************/ static const char* item_name(Item *a, String *str) { if (a->name.str) return a->name.str; str->length(0); a->print(str, QT_ORDINARY); return str->c_ptr_safe(); } static void wrong_precision_error(uint errcode, Item *a, ulonglong number, uint maximum) { StringBuffer<1024> buf(system_charset_info); my_error(errcode, MYF(0), number, item_name(a, &buf), maximum); } /** Get precision and scale for a declaration return 0 ok 1 error */ bool get_length_and_scale(ulonglong length, ulonglong decimals, uint *out_length, uint *out_decimals, uint max_precision, uint max_scale, Item *a) { if (length > (ulonglong) max_precision) { wrong_precision_error(ER_TOO_BIG_PRECISION, a, length, max_precision); return 1; } if (decimals > (ulonglong) max_scale) { wrong_precision_error(ER_TOO_BIG_SCALE, a, decimals, max_scale); return 1; } *out_decimals= (uint) decimals; my_decimal_trim(&length, out_decimals); *out_length= (uint) length; if (*out_length < *out_decimals) { my_error(ER_M_BIGGER_THAN_D, MYF(0), ""); return 1; } return 0; } Item *Type_handler_longlong:: create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const { if (this != &type_handler_ulonglong) return new (thd->mem_root) Item_func_signed(thd, item); return new (thd->mem_root) Item_func_unsigned(thd, item); } Item *Type_handler_date_common:: create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const { return new (thd->mem_root) Item_date_typecast(thd, item); } Item *Type_handler_time_common:: create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const { if (attr.decimals() > MAX_DATETIME_PRECISION) { wrong_precision_error(ER_TOO_BIG_PRECISION, item, attr.decimals(), MAX_DATETIME_PRECISION); return 0; } return new (thd->mem_root) Item_time_typecast(thd, item, (uint) attr.decimals()); } Item *Type_handler_datetime_common:: create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const { if (attr.decimals() > MAX_DATETIME_PRECISION) { wrong_precision_error(ER_TOO_BIG_PRECISION, item, attr.decimals(), MAX_DATETIME_PRECISION); return 0; } return new (thd->mem_root) Item_datetime_typecast(thd, item, (uint) attr.decimals()); } Item *Type_handler_decimal_result:: create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const { uint len, dec; if (get_length_and_scale(attr.length(), attr.decimals(), &len, &dec, DECIMAL_MAX_PRECISION, DECIMAL_MAX_SCALE, item)) return NULL; return new (thd->mem_root) Item_decimal_typecast(thd, item, len, dec); } Item *Type_handler_double:: create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const { uint len, dec; if (!attr.length_specified()) return new (thd->mem_root) Item_double_typecast(thd, item, DBL_DIG + 7, NOT_FIXED_DEC); if (get_length_and_scale(attr.length(), attr.decimals(), &len, &dec, DECIMAL_MAX_PRECISION, NOT_FIXED_DEC - 1, item)) return NULL; return new (thd->mem_root) Item_double_typecast(thd, item, len, dec); } Item *Type_handler_long_blob:: create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const { int len= -1; CHARSET_INFO *real_cs= attr.charset() ? attr.charset() : thd->variables.collation_connection; if (attr.length_specified()) { if (attr.length() > MAX_FIELD_BLOBLENGTH) { char buff[1024]; String buf(buff, sizeof(buff), system_charset_info); my_error(ER_TOO_BIG_DISPLAYWIDTH, MYF(0), item_name(item, &buf), MAX_FIELD_BLOBLENGTH); return NULL; } len= (int) attr.length(); } return new (thd->mem_root) Item_char_typecast(thd, item, len, real_cs); } /***************************************************************************/ void Type_handler_string_result::Item_param_setup_conversion(THD *thd, Item_param *param) const { param->setup_conversion_string(thd, thd->variables.character_set_client); } void Type_handler_blob_common::Item_param_setup_conversion(THD *thd, Item_param *param) const { param->setup_conversion_blob(thd); } void Type_handler_tiny::Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const { param->set_param_tiny(pos, len); } void Type_handler_short::Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const { param->set_param_short(pos, len); } void Type_handler_long::Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const { param->set_param_int32(pos, len); } void Type_handler_longlong::Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const { param->set_param_int64(pos, len); } void Type_handler_float::Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const { param->set_param_float(pos, len); } void Type_handler_double::Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const { param->set_param_double(pos, len); } void Type_handler_decimal_result::Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const { param->set_param_decimal(pos, len); } void Type_handler_string_result::Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const { param->set_param_str(pos, len); } void Type_handler_time_common::Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const { param->set_param_time(pos, len); } void Type_handler_date_common::Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const { param->set_param_date(pos, len); } void Type_handler_datetime_common::Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const { param->set_param_datetime(pos, len); } void Type_handler_timestamp_common::Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const { param->set_param_datetime(pos, len); } void Type_handler::Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const { param->set_null(); // Not possible type code in the client-server protocol } void Type_handler_typelib::Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const { param->set_null(); // Not possible type code in the client-server protocol } #ifdef HAVE_SPATIAL void Type_handler_geometry::Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const { param->set_null(); // Not possible type code in the client-server protocol } #endif /***************************************************************************/
natsys/mariadb_10.2
sql/sql_type.cc
C++
lgpl-2.1
176,857
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** 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 [email protected]. ** **************************************************************************/ #include <utils/ssh/sftpchannel.h> #include <utils/ssh/sshconnection.h> #include <utils/ssh/sshremoteprocess.h> #include <QtCore/QCoreApplication> #include <QtCore/QList> #include <QtCore/QObject> #include <QtCore/QPair> #include <QtCore/QTimer> using namespace Utils; class Test : public QObject { Q_OBJECT public: Test() { m_timeoutTimer.setSingleShot(true); m_connection = SshConnection::create(SshConnectionParameters(SshConnectionParameters::DefaultProxy)); if (m_connection->state() != SshConnection::Unconnected) { qDebug("Error: Newly created SSH connection has state %d.", m_connection->state()); } if (m_connection->createRemoteProcess("")) qDebug("Error: Unconnected SSH connection creates remote process."); if (m_connection->createSftpChannel()) qDebug("Error: Unconnected SSH connection creates SFTP channel."); SshConnectionParameters noHost=SshConnectionParameters(SshConnectionParameters::DefaultProxy); noHost.host = QLatin1String("hgdfxgfhgxfhxgfchxgcf"); noHost.port = 12345; noHost.timeout = 10; SshConnectionParameters noUser=SshConnectionParameters(SshConnectionParameters::DefaultProxy); noUser.host = QLatin1String("localhost"); noUser.port = 22; noUser.timeout = 30; noUser.authenticationType = SshConnectionParameters::AuthenticationByPassword; noUser.userName = QLatin1String("dumdidumpuffpuff"); noUser.password = QLatin1String("whatever"); SshConnectionParameters wrongPwd=SshConnectionParameters(SshConnectionParameters::DefaultProxy); wrongPwd.host = QLatin1String("localhost"); wrongPwd.port = 22; wrongPwd.timeout = 30; wrongPwd.authenticationType = SshConnectionParameters::AuthenticationByPassword; wrongPwd.userName = QLatin1String("root"); noUser.password = QLatin1String("thiscantpossiblybeapasswordcanit"); SshConnectionParameters invalidKeyFile=SshConnectionParameters(SshConnectionParameters::DefaultProxy); invalidKeyFile.host = QLatin1String("localhost"); invalidKeyFile.port = 22; invalidKeyFile.timeout = 30; invalidKeyFile.authenticationType = SshConnectionParameters::AuthenticationByKey; invalidKeyFile.userName = QLatin1String("root"); invalidKeyFile.privateKeyFile = QLatin1String("somefilenamethatwedontexpecttocontainavalidkey"); // TODO: Create a valid key file and check for authentication error. m_testSet << TestItem("Behavior with non-existing host", noHost, ErrorList() << SshSocketError); m_testSet << TestItem("Behavior with non-existing user", noUser, ErrorList() << SshSocketError << SshTimeoutError << SshAuthenticationError); m_testSet << TestItem("Behavior with wrong password", wrongPwd, ErrorList() << SshSocketError << SshTimeoutError << SshAuthenticationError); m_testSet << TestItem("Behavior with invalid key file", invalidKeyFile, ErrorList() << SshSocketError << SshTimeoutError << SshKeyFileError); runNextTest(); } ~Test(); private slots: void handleConnected() { qDebug("Error: Received unexpected connected() signal."); qApp->quit(); } void handleDisconnected() { qDebug("Error: Received unexpected disconnected() signal."); qApp->quit(); } void handleDataAvailable(const QString &msg) { qDebug("Error: Received unexpected dataAvailable() signal. " "Message was: '%s'.", qPrintable(msg)); qApp->quit(); } void handleError(Utils::SshError error) { if (m_testSet.isEmpty()) { qDebug("Error: Received error %d, but no test was running.", error); qApp->quit(); } const TestItem testItem = m_testSet.takeFirst(); if (testItem.allowedErrors.contains(error)) { qDebug("Received error %d, as expected.", error); if (m_testSet.isEmpty()) { qDebug("All tests finished successfully."); qApp->quit(); } else { runNextTest(); } } else { qDebug("Received unexpected error %d.", error); qApp->quit(); } } void handleTimeout() { if (m_testSet.isEmpty()) { qDebug("Error: timeout, but no test was running."); qApp->quit(); } const TestItem testItem = m_testSet.takeFirst(); qDebug("Error: The following test timed out: %s", testItem.description); } private: void runNextTest() { if (m_connection) disconnect(m_connection.data(), 0, this, 0); m_connection = SshConnection::create(m_testSet.first().params); connect(m_connection.data(), SIGNAL(connected()), this, SLOT(handleConnected())); connect(m_connection.data(), SIGNAL(disconnected()), this, SLOT(handleDisconnected())); connect(m_connection.data(), SIGNAL(dataAvailable(QString)), this, SLOT(handleDataAvailable(QString))); connect(m_connection.data(), SIGNAL(error(Utils::SshError)), this, SLOT(handleError(Utils::SshError))); const TestItem &nextItem = m_testSet.first(); m_timeoutTimer.stop(); m_timeoutTimer.setInterval(qMax(10000, nextItem.params.timeout * 1000)); qDebug("Testing: %s", nextItem.description); m_connection->connectToHost(); } SshConnection::Ptr m_connection; typedef QList<SshError> ErrorList; struct TestItem { TestItem(const char *d, const SshConnectionParameters &p, const ErrorList &e) : description(d), params(p), allowedErrors(e) {} const char *description; SshConnectionParameters params; ErrorList allowedErrors; }; QList<TestItem> m_testSet; QTimer m_timeoutTimer; }; Test::~Test() {} int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Test t; return a.exec(); } #include "main.moc"
renatofilho/QtCreator
tests/manual/ssh/errorhandling/main.cpp
C++
lgpl-2.1
7,540
OpenFlow 1.3 TODO LIST ============================= Please take a look on the list of new features added, ongoing work and to do items. B.11.1 Refactor capabilities negotiation ---------------------------------------- TODO - Enable ’multipart’ requests (requests spanning multiple messages). ONGOING DONE - Pack and unpack of new and modified messages. - Rename ’stats’ framework into the ’multipart’ framework. - Move port list description to its own multipart request/reply. - Create flexible property structure to express table capabilities. - Add capabilities for table-miss flow entries. - Add next-table (i.e. goto) capabilities - Move table capabilities to its own multipart request/reply. B.11.2 More flexible table miss support ----------------------------------------- TODO ONGOING DONE - Add capabilities to describe the table-miss flow entry (EXT-123). - Remove table-miss config flags (EXT-108). - Define table-miss flow entry as the all wildcard, lowest priority flow entry (EXT-108). - Mandate support of the table-miss flow entry in every table to process table-miss packets (EXT-108) - Change table-miss default to drop packets (EXT-119). B.11.3 IPv6 Extension Header handling support ---------------------------------------------- TODO ONGOING DONE - Hop-by-hop IPv6 extension header is present. - Router IPv6 extension header is present. - Fragmentation IPv6 extension header is present. - Destination options IPv6 extension headers is present. - Authentication IPv6 extension header is present. - Encrypted Security Payload IPv6 extension header is present. - No Next Header IPv6 extension header is present. - IPv6 extension headers out of preferred order. - Unexpected IPv6 extension header encountered B.11.4 Per flow meters ----------------------- TODO ONGOING DONE - Simple rate-limiter support (drop packets). - Flexible meter framework based on per-flow meters and meter bands. - Meter statistics, including per band statistics. - Enable to attach meters flexibly to flow entries. B.11.5 Per connection event filtering -------------------------------------- TODO ONGOING - Set default filter value to match OpenFlow 1.2 behaviour. DONE - Add asynchronous message filter for each controller connection. - Controller message to set/get the asynchronous message filter. - Remove OFPC_INVALID_TTL_TO_CONTROLLER config flag. B.11.6 Auxiliary connections ----------------------------- TODO - Enable switch to create auxiliary connections to the controller. - Mandate that auxiliary connection can not exist when main connection is not alive. - Add auxiliary-id to the protocol to disambiguate the type of connection. - Enable auxiliary connection over UDP and DTLS. ONGOING DONE B.11.7 MPLS BoS matching -------------------------- TODO ONGOING DONE - A new OXM field OXM_OF_MPLS_BOS has been added to match the Bottom of Stack bit (BoS) from the MPLS header (EXT-85) B.11.8 Provider Backbone Bridging tagging ------------------------------------------- TODO ONGOING DONE - Push and Pop operation to add PBB header as a tag. - New OXM field to match I-SID for the PBB header. B.11.9 Rework tag order ------------------------ TODO ONGOING DONE B.11.10 Tunnel-ID metadata --------------------------- - Remove defined order of tags in packet from the specification. - Tags are now always added in the outermost possible position. - Action-list can add tags in arbitrary order. - Tag order is predefined for tagging in the action-set.TODO ONGOING DONE - New OXM Field to match tunnel-id. Duration for stats ------------------- TODO ONGOING DONE - Duration for meter stats. - Done for port, queue and group stats Cookies in packet-in ---------------------- TODO ONGOING DONE - Cookie field was added to the packet-in message (EXT-7). - This field takes its value from the flow the sends the packet to the controller. If the packet was not sent by a flow, this field is set to 0xffffffffffffffff. B.11.13 On demand flow counters -------------------------------- TODO ONGOING DONE - New flow-mod flags have been added to disable packet and byte counters on a per-flow basis. Disabling such counters may improve flow handling performance in the switch.
MeshSr/ofs-sw
TODO.md
Markdown
lgpl-2.1
4,262
/* Copyright (C) 2016 Fredrik Johansson This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */ #include <string.h> #include <ctype.h> #include "fmpz_poly.h" #include "profiler.h" int main(int argc, char * argv[]) { fmpz_poly_t f, g, h; fmpz_t c, d; slong bits, len, k, nthreads, minlen, maxlen, minbits, maxbits; double incbits, inclen; flint_rand_t state; flint_randinit(state); fmpz_poly_init(f); fmpz_poly_init(g); fmpz_poly_init(h); fmpz_init(c); fmpz_init(d); fmpz_one(d); nthreads = 1; minlen = 32; maxlen = 100000; inclen = 1.5; minbits = 32; maxbits = 400000; incbits = 2.0; for (k = 0; k < argc - 1; k++) { if (strcmp(argv[k], "-len") == 0) { minlen = maxlen = atoi(argv[k + 1]); if (k + 2 < argc && isdigit(argv[k + 2][0])) maxlen = atoi(argv[k + 2]); if (k + 3 < argc && isdigit(argv[k + 3][0])) inclen = atof(argv[k + 3]); } if (strcmp(argv[k], "-bits") == 0) { minbits = maxbits = atoi(argv[k + 1]); if (k + 2 < argc && isdigit(argv[k + 2][0])) maxbits = atoi(argv[k + 2]); if (k + 3 < argc && isdigit(argv[k + 3][0])) incbits = atof(argv[k + 3]); } if (strcmp(argv[k], "-threads") == 0) nthreads = atoi(argv[k + 1]); } flint_printf("len sizes: "); for (len = minlen; len <= maxlen; len = FLINT_MAX(len + 1, len * inclen)) flint_printf("%wd ", len); flint_printf("\nbit sizes: "); for (bits = minbits; bits <= maxbits; bits = FLINT_MAX(bits + 1, bits * incbits)) flint_printf("%wd ", bits); flint_printf("\nusing up to %wd threads\n\n", nthreads); for (len = minlen; len <= maxlen; len = FLINT_MAX(len + 1, len * inclen)) { for (bits = minbits; bits <= maxbits; bits = FLINT_MAX(bits + 1, bits * incbits)) { fmpz_poly_zero(f); for (k = 0; k < len; k++) { fmpz_randbits(c, state, bits); fmpz_poly_set_coeff_fmpz(f, k, c); } flint_printf("%wd %wd default ", len, bits); TIMEIT_START fmpz_poly_taylor_shift(g, f, d); TIMEIT_STOP /* flint_printf("%wd %wd compose ", len, bits); TIMEIT_START fmpz_poly_one(h); fmpz_poly_set_coeff_si(h, 1, 1); fmpz_poly_compose_divconquer(h, f, h); TIMEIT_STOP */ flint_printf("%wd %wd horner ", len, bits); TIMEIT_START fmpz_poly_taylor_shift_horner(g, f, d); TIMEIT_STOP for (k = 1; k <= nthreads; k *= 2) { flint_printf("%wd %wd dc%wd ", len, bits, k); flint_set_num_threads(k); TIMEIT_START fmpz_poly_taylor_shift_divconquer(g, f, d); TIMEIT_STOP flint_set_num_threads(1); } for (k = 1; k <= nthreads; k *= 2) { flint_printf("%wd %wd mm%wd ", len, bits, k); flint_set_num_threads(k); TIMEIT_START fmpz_poly_taylor_shift_multi_mod(g, f, d); TIMEIT_STOP flint_set_num_threads(1); } flint_printf("\n"); } } fmpz_poly_clear(f); fmpz_poly_clear(g); fmpz_poly_clear(h); fmpz_clear(c); fmpz_clear(d); flint_randclear(state); flint_cleanup(); return 0; }
wbhart/flint2
fmpz_poly/profile/p-taylor_shift.c
C
lgpl-2.1
3,907
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Linguist 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 "proitems.h" #include <QtCore/QFileInfo> #include <QtCore/QSet> QT_BEGIN_NAMESPACE using namespace ProStringConstants; // from qhash.cpp uint ProString::hash(const QChar *p, int n) { uint h = 0; while (n--) { h = (h << 4) + (*p++).unicode(); h ^= (h & 0xf0000000) >> 23; h &= 0x0fffffff; } return h; } ProString::ProString() : m_offset(0), m_length(0), m_file(0), m_hash(0x80000000) { } ProString::ProString(const ProString &other) : m_string(other.m_string), m_offset(other.m_offset), m_length(other.m_length), m_file(other.m_file), m_hash(other.m_hash) { } ProString::ProString(const ProString &other, OmitPreHashing) : m_string(other.m_string), m_offset(other.m_offset), m_length(other.m_length), m_file(other.m_file), m_hash(0x80000000) { } ProString::ProString(const QString &str) : m_string(str), m_offset(0), m_length(str.length()), m_file(0) { updatedHash(); } ProString::ProString(const QString &str, OmitPreHashing) : m_string(str), m_offset(0), m_length(str.length()), m_file(0), m_hash(0x80000000) { } ProString::ProString(const char *str) : m_string(QString::fromLatin1(str)), m_offset(0), m_length(qstrlen(str)), m_file(0) { updatedHash(); } ProString::ProString(const char *str, OmitPreHashing) : m_string(QString::fromLatin1(str)), m_offset(0), m_length(qstrlen(str)), m_file(0), m_hash(0x80000000) { } ProString::ProString(const QString &str, int offset, int length) : m_string(str), m_offset(offset), m_length(length), m_file(0) { updatedHash(); } ProString::ProString(const QString &str, int offset, int length, uint hash) : m_string(str), m_offset(offset), m_length(length), m_file(0), m_hash(hash) { } ProString::ProString(const QString &str, int offset, int length, ProStringConstants::OmitPreHashing) : m_string(str), m_offset(offset), m_length(length), m_file(0), m_hash(0x80000000) { } void ProString::setValue(const QString &str) { m_string = str, m_offset = 0, m_length = str.length(); updatedHash(); } void ProString::setValue(const QString &str, OmitPreHashing) { m_string = str, m_offset = 0, m_length = str.length(), m_hash = 0x80000000; } uint ProString::updatedHash() const { return (m_hash = hash(m_string.constData() + m_offset, m_length)); } uint qHash(const ProString &str) { if (!(str.m_hash & 0x80000000)) return str.m_hash; return str.updatedHash(); } QString ProString::toQString() const { return m_string.mid(m_offset, m_length); } QString &ProString::toQString(QString &tmp) const { return tmp.setRawData(m_string.constData() + m_offset, m_length); } bool ProString::operator==(const ProString &other) const { if (m_length != other.m_length) return false; return !memcmp(m_string.constData() + m_offset, other.m_string.constData() + other.m_offset, m_length * 2); } bool ProString::operator==(const QString &other) const { if (m_length != other.length()) return false; return !memcmp(m_string.constData() + m_offset, other.constData(), m_length * 2); } bool ProString::operator==(const QLatin1String &other) const { const ushort *uc = (ushort *)m_string.constData() + m_offset; const ushort *e = uc + m_length; const uchar *c = (uchar *)other.latin1(); if (!c) return isEmpty(); while (*c) { if (uc == e || *uc != *c) return false; ++uc; ++c; } return (uc == e); } QChar *ProString::prepareAppend(int extraLen) { if (m_string.isDetached() && m_length + extraLen <= m_string.capacity()) { m_string.reserve(0); // Prevent the resize() below from reallocating QChar *ptr = (QChar *)m_string.constData(); if (m_offset) memmove(ptr, ptr + m_offset, m_length * 2); ptr += m_length; m_offset = 0; m_length += extraLen; m_string.resize(m_length); m_hash = 0x80000000; return ptr; } else { QString neu(m_length + extraLen, Qt::Uninitialized); QChar *ptr = (QChar *)neu.constData(); memcpy(ptr, m_string.constData() + m_offset, m_length * 2); ptr += m_length; *this = ProString(neu, NoHash); return ptr; } } // If pending != 0, prefix with space if appending to non-empty non-pending ProString &ProString::append(const ProString &other, bool *pending) { if (other.m_length) { if (!m_length) { *this = other; } else { QChar *ptr; if (pending && !*pending) { ptr = prepareAppend(1 + other.m_length); *ptr++ = 32; } else { ptr = prepareAppend(other.m_length); } memcpy(ptr, other.m_string.constData() + other.m_offset, other.m_length * 2); if (other.m_file) m_file = other.m_file; } if (pending) *pending = true; } return *this; } ProString &ProString::append(const ProStringList &other, bool *pending, bool skipEmpty1st) { if (const int sz = other.size()) { int startIdx = 0; if (pending && !*pending && skipEmpty1st && other.at(0).isEmpty()) { if (sz == 1) return *this; startIdx = 1; } if (!m_length && sz == startIdx + 1) { *this = other.at(startIdx); } else { int totalLength = sz - startIdx; for (int i = startIdx; i < sz; ++i) totalLength += other.at(i).size(); bool putSpace = false; if (pending && !*pending && m_length) putSpace = true; else totalLength--; QChar *ptr = prepareAppend(totalLength); for (int i = startIdx; i < sz; ++i) { if (putSpace) *ptr++ = 32; else putSpace = true; const ProString &str = other.at(i); memcpy(ptr, str.m_string.constData() + str.m_offset, str.m_length * 2); ptr += str.m_length; } if (other.last().m_file) m_file = other.last().m_file; } if (pending) *pending = true; } return *this; } QString operator+(const ProString &one, const ProString &two) { if (two.m_length) { if (!one.m_length) { return two.toQString(); } else { QString neu(one.m_length + two.m_length, Qt::Uninitialized); ushort *ptr = (ushort *)neu.constData(); memcpy(ptr, one.m_string.constData() + one.m_offset, one.m_length * 2); memcpy(ptr + one.m_length, two.m_string.constData() + two.m_offset, two.m_length * 2); return neu; } } return one.toQString(); } ProString ProString::mid(int off, int len) const { ProString ret(*this, NoHash); if (off > m_length) off = m_length; ret.m_offset += off; ret.m_length -= off; if (ret.m_length > len) ret.m_length = len; return ret; } ProString ProString::trimmed() const { ProString ret(*this, NoHash); int cur = m_offset; int end = cur + m_length; const QChar *data = m_string.constData(); for (; cur < end; cur++) if (!data[cur].isSpace()) { // No underrun check - we know there is at least one non-whitespace while (data[end - 1].isSpace()) end--; break; } ret.m_offset = cur; ret.m_length = end - cur; return ret; } QString ProStringList::join(const QString &sep) const { int totalLength = 0; const int sz = size(); for (int i = 0; i < sz; ++i) totalLength += at(i).size(); if (sz) totalLength += sep.size() * (sz - 1); QString res(totalLength, Qt::Uninitialized); QChar *ptr = (QChar *)res.constData(); for (int i = 0; i < sz; ++i) { if (i) { memcpy(ptr, sep.constData(), sep.size() * 2); ptr += sep.size(); } memcpy(ptr, at(i).constData(), at(i).size() * 2); ptr += at(i).size(); } return res; } void ProStringList::removeDuplicates() { int n = size(); int j = 0; QSet<ProString> seen; seen.reserve(n); for (int i = 0; i < n; ++i) { const ProString &s = at(i); if (seen.contains(s)) continue; seen.insert(s); if (j != i) (*this)[j] = s; ++j; } if (n != j) erase(begin() + j, end()); } ProFile::ProFile(const QString &fileName) : m_refCount(1), m_fileName(fileName), m_ok(true) { if (!fileName.startsWith(QLatin1Char('('))) m_directoryName = QFileInfo( // qmake sickness: canonicalize only the directory! fileName.left(fileName.lastIndexOf(QLatin1Char('/')))).canonicalFilePath(); } ProFile::~ProFile() { } QT_END_NAMESPACE
eric100lin/Qt-4.8.6
tools/linguist/shared/proitems.cpp
C++
lgpl-2.1
10,960
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * 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 <mapnik/config.hpp> #include "boost_std_shared_shim.hpp" // boost #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> // mapnik #include <mapnik/value_error.hpp> #include <mapnik/rule.hpp> #include "mapnik_enumeration.hpp" #include <mapnik/feature_type_style.hpp> #include <mapnik/image_filter_types.hpp> // generate_image_filters using mapnik::feature_type_style; using mapnik::rules; using mapnik::rule; std::string get_image_filters(feature_type_style & style) { std::string filters_str; std::back_insert_iterator<std::string> sink(filters_str); generate_image_filters(sink, style.image_filters()); return filters_str; } void set_image_filters(feature_type_style & style, std::string const& filters) { std::vector<mapnik::filter::filter_type> new_filters; bool result = parse_image_filters(filters, new_filters); if (!result) { throw mapnik::value_error("failed to parse image-filters: '" + filters + "'"); } #ifdef _WINDOWS style.image_filters() = new_filters; // FIXME : https://svn.boost.org/trac/boost/ticket/2839 #else style.image_filters() = std::move(new_filters); #endif } void export_style() { using namespace boost::python; mapnik::enumeration_<mapnik::filter_mode_e>("filter_mode") .value("ALL",mapnik::FILTER_ALL) .value("FIRST",mapnik::FILTER_FIRST) ; class_<rules>("Rules",init<>("default ctor")) .def(vector_indexing_suite<rules>()) ; class_<feature_type_style>("Style",init<>("default style constructor")) .add_property("rules",make_function (&feature_type_style::get_rules, return_value_policy<reference_existing_object>()), "List of rules belonging to a style as rule objects.\n" "\n" "Usage:\n" ">>> for r in m.find_style('style 1').rules:\n" ">>> print r\n" "<mapnik._mapnik.Rule object at 0x100549910>\n" "<mapnik._mapnik.Rule object at 0x100549980>\n" ) .add_property("filter_mode", &feature_type_style::get_filter_mode, &feature_type_style::set_filter_mode, "Set/get the filter mode of the style") .add_property("opacity", &feature_type_style::get_opacity, &feature_type_style::set_opacity, "Set/get the opacity of the style") .add_property("comp_op", &feature_type_style::comp_op, &feature_type_style::set_comp_op, "Set/get the comp-op (composite operation) of the style") .add_property("image_filters_inflate", &feature_type_style::image_filters_inflate, &feature_type_style::image_filters_inflate, "Set/get the image_filters_inflate property of the style") .add_property("image_filters", get_image_filters, set_image_filters, "Set/get the comp-op (composite operation) of the style") ; }
TemplateVoid/mapnik
bindings/python/mapnik_style.cpp
C++
lgpl-2.1
4,310
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.16"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>CQRS.NET: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(initResizable); /* @license-end */</script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ extensions: ["tex2jax.js"], jax: ["input/TeX","output/HTML-CSS"], }); </script><script type="text/javascript" async="async" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">CQRS.NET &#160;<span id="projectnumber">4.1</span> </div> <div id="projectbrief">A lightweight enterprise Function as a Service (FaaS) framework to write function based serverless and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.16 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(function(){initNavTree('classCqrs_1_1Azure_1_1BlobStorage_1_1EventDataTableEntity.html','');}); /* @license-end */ </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">Cqrs.Azure.BlobStorage.EventDataTableEntity&lt; TEventData &gt; Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1EventDataTableEntity.html">Cqrs.Azure.BlobStorage.EventDataTableEntity&lt; TEventData &gt;</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1TableEntity_ab7a9041c7d8e5237cfb81ad98b6b3980.html#ab7a9041c7d8e5237cfb81ad98b6b3980">DefaultSettings</a></td><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1TableEntity.html">Cqrs.Azure.BlobStorage.TableEntity&lt; TEventData &gt;</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1TableEntity_a5a5b53a3a2427a368f2ebe404f04f4ff.html#a5a5b53a3a2427a368f2ebe404f04f4ff">Deserialise</a>(string json)</td><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1TableEntity.html">Cqrs.Azure.BlobStorage.TableEntity&lt; TEventData &gt;</a></td><td class="entry"><span class="mlabel">protected</span><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1EventDataTableEntity_a906bcb5198f91069413fc1d8e848866a.html#a906bcb5198f91069413fc1d8e848866a">EventData</a></td><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1EventDataTableEntity.html">Cqrs.Azure.BlobStorage.EventDataTableEntity&lt; TEventData &gt;</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1EventDataTableEntity_a96b0a7c91d33d469e047c6bd5089d8de.html#a96b0a7c91d33d469e047c6bd5089d8de">EventDataContent</a></td><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1EventDataTableEntity.html">Cqrs.Azure.BlobStorage.EventDataTableEntity&lt; TEventData &gt;</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1EventDataTableEntity_a90c39733d651a5a71497909089e67c1a.html#a90c39733d651a5a71497909089e67c1a">EventDataTableEntity</a>(TEventData eventData, bool isCorrelationIdTableStorageStore=false)</td><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1EventDataTableEntity.html">Cqrs.Azure.BlobStorage.EventDataTableEntity&lt; TEventData &gt;</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1EventDataTableEntity_a6785ad2dd88c6db1ec4a2d8d474b557d.html#a6785ad2dd88c6db1ec4a2d8d474b557d">EventDataTableEntity</a>()</td><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1EventDataTableEntity.html">Cqrs.Azure.BlobStorage.EventDataTableEntity&lt; TEventData &gt;</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1TableEntity_aa36736f412df5a1667d7b0e5c0bd3035.html#aa36736f412df5a1667d7b0e5c0bd3035">GetSerialisationSettings</a>()</td><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1TableEntity.html">Cqrs.Azure.BlobStorage.TableEntity&lt; TEventData &gt;</a></td><td class="entry"><span class="mlabel">protected</span><span class="mlabel">virtual</span></td></tr> <tr><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1TableEntity_a18d1b7ecf408a921cd0e2e6a8d0f6c74.html#a18d1b7ecf408a921cd0e2e6a8d0f6c74">GetSerialiser</a>()</td><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1TableEntity.html">Cqrs.Azure.BlobStorage.TableEntity&lt; TEventData &gt;</a></td><td class="entry"><span class="mlabel">protected</span><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1TableEntity_af7467b1194756dd32029dc40f690c4ad.html#af7467b1194756dd32029dc40f690c4ad">Serialise</a>(TData data)</td><td class="entry"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1TableEntity.html">Cqrs.Azure.BlobStorage.TableEntity&lt; TEventData &gt;</a></td><td class="entry"><span class="mlabel">protected</span><span class="mlabel">virtual</span></td></tr> </table></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.16 </li> </ul> </div> </body> </html>
Chinchilla-Software-Com/CQRS
wiki/docs/4.1/html/classCqrs_1_1Azure_1_1BlobStorage_1_1EventDataTableEntity-members.html
HTML
lgpl-2.1
8,847
# This file is part of fedmsg. # Copyright (C) 2012 - 2014 Red Hat, Inc. # # fedmsg 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. # # fedmsg 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 fedmsg; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Authors: Ralph Bean <[email protected]> # import six import zmq import inspect import subprocess try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict def set_high_water_mark(socket, config): """ Set a high water mark on the zmq socket. Do so in a way that is cross-compatible with zeromq2 and zeromq3. """ if config['high_water_mark']: if hasattr(zmq, 'HWM'): # zeromq2 socket.setsockopt(zmq.HWM, config['high_water_mark']) else: # zeromq3 socket.setsockopt(zmq.SNDHWM, config['high_water_mark']) socket.setsockopt(zmq.RCVHWM, config['high_water_mark']) # TODO -- this should be in kitchen, not fedmsg def guess_calling_module(default=None): # Iterate up the call-stack and return the first new top-level module for frame in (f[0] for f in inspect.stack()): modname = frame.f_globals['__name__'].split('.')[0] if modname != "fedmsg": return modname # Otherwise, give up and just return the default. return default def set_tcp_keepalive(socket, config): """ Set a series of TCP keepalive options on the socket if and only if 1) they are specified explicitly in the config and 2) the version of pyzmq has been compiled with support We ran into a problem in FedoraInfrastructure where long-standing connections between some hosts would suddenly drop off the map silently. Because PUB/SUB sockets don't communicate regularly, nothing in the TCP stack would automatically try and fix the connection. With TCP_KEEPALIVE options (introduced in libzmq 3.2 and pyzmq 2.2.0.1) hopefully that will be fixed. See the following - http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html - http://api.zeromq.org/3-2:zmq-setsockopt """ keepalive_options = { # Map fedmsg config keys to zeromq socket constants 'zmq_tcp_keepalive': 'TCP_KEEPALIVE', 'zmq_tcp_keepalive_cnt': 'TCP_KEEPALIVE_CNT', 'zmq_tcp_keepalive_idle': 'TCP_KEEPALIVE_IDLE', 'zmq_tcp_keepalive_intvl': 'TCP_KEEPALIVE_INTVL', } for key, const in keepalive_options.items(): if key in config: attr = getattr(zmq, const, None) if attr: socket.setsockopt(attr, config[key]) def set_tcp_reconnect(socket, config): """ Set a series of TCP reconnect options on the socket if and only if 1) they are specified explicitly in the config and 2) the version of pyzmq has been compiled with support Once our fedmsg bus grew to include many hundreds of endpoints, we started notices a *lot* of SYN-ACKs in the logs. By default, if an endpoint is unavailable, zeromq will attempt to reconnect every 100ms until it gets a connection. With this code, you can reconfigure that to back off exponentially to some max delay (like 1000ms) to reduce reconnect storm spam. See the following - http://api.zeromq.org/3-2:zmq-setsockopt """ reconnect_options = { # Map fedmsg config keys to zeromq socket constants 'zmq_reconnect_ivl': 'RECONNECT_IVL', 'zmq_reconnect_ivl_max': 'RECONNECT_IVL_MAX', } for key, const in reconnect_options.items(): if key in config: attr = getattr(zmq, const, None) if attr: socket.setsockopt(attr, config[key]) def load_class(location): """ Take a string of the form 'fedmsg.consumers.ircbot:IRCBotConsumer' and return the IRCBotConsumer class. """ mod_name, cls_name = location = location.strip().split(':') tokens = mod_name.split('.') fromlist = '[]' if len(tokens) > 1: fromlist = '.'.join(tokens[:-1]) module = __import__(mod_name, fromlist=fromlist) try: return getattr(module, cls_name) except AttributeError: raise ImportError("%r not found in %r" % (cls_name, mod_name)) def dict_query(dic, query): """ Query a dict with 'dotted notation'. Returns an OrderedDict. A query of "foo.bar.baz" would retrieve 'wat' from this:: dic = { 'foo': { 'bar': { 'baz': 'wat', } } } Multiple queries can be specified if comma-separated. For instance, the query "foo.bar.baz,foo.bar.something_else" would return this:: OrderedDict({ "foo.bar.baz": "wat", "foo.bar.something_else": None, }) """ if not isinstance(query, six.string_types): raise ValueError("query must be a string, not %r" % type(query)) def _browse(tokens, d): """ Recurse through a dict to retrieve a value. """ current, rest = tokens[0], tokens[1:] if not rest: return d.get(current, None) if current in d: if isinstance(d[current], dict): return _browse(rest, d[current]) elif rest: return None else: return d[current] keys = [key.strip().split('.') for key in query.split(',')] return OrderedDict([ ('.'.join(tokens), _browse(tokens, dic)) for tokens in keys ]) def cowsay_output(message): """ Invoke a shell command to print cowsay output. Primary replacement for os.system calls. """ command = 'cowsay "%s"' % message ret = subprocess.Popen( command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) output, error = ret.communicate() return output, error
chaiku/fedmsg
fedmsg/utils.py
Python
lgpl-2.1
6,474
/* * esx_storage_backend_vmfs.c: ESX storage driver backend for * managing VMFS datastores * * Copyright (C) 2010-2014 Red Hat, Inc. * Copyright (C) 2010-2012 Matthias Bolte <[email protected]> * Copyright (C) 2012 Ata E Husain Bohra <[email protected]> * * 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/>. * */ #include <config.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include "internal.h" #include "md5.h" #include "viralloc.h" #include "virfile.h" #include "virlog.h" #include "viruuid.h" #include "storage_conf.h" #include "virstoragefile.h" #include "esx_storage_backend_vmfs.h" #include "esx_private.h" #include "esx_vi.h" #include "esx_vi_methods.h" #include "esx_util.h" #include "virstring.h" #define VIR_FROM_THIS VIR_FROM_ESX VIR_LOG_INIT("esx.esx_storage_backend_vmfs"); /* * The UUID of a storage pool is the MD5 sum of its mount path. Therefore, * verify that UUID and MD5 sum match in size, because we rely on that. */ verify(MD5_DIGEST_SIZE == VIR_UUID_BUFLEN); static int esxLookupVMFSStoragePoolType(esxVI_Context *ctx, const char *poolName, int *poolType) { int result = -1; esxVI_String *propertyNameList = NULL; esxVI_ObjectContent *datastore = NULL; esxVI_DynamicProperty *dynamicProperty = NULL; esxVI_DatastoreInfo *datastoreInfo = NULL; if (esxVI_String_AppendValueToList(&propertyNameList, "info") < 0 || esxVI_LookupDatastoreByName(ctx, poolName, propertyNameList, &datastore, esxVI_Occurrence_OptionalItem) < 0) { goto cleanup; } if (!datastore) { /* Not found, let the base storage driver handle error reporting */ goto cleanup; } for (dynamicProperty = datastore->propSet; dynamicProperty; dynamicProperty = dynamicProperty->_next) { if (STREQ(dynamicProperty->name, "info")) { if (esxVI_DatastoreInfo_CastFromAnyType(dynamicProperty->val, &datastoreInfo) < 0) { goto cleanup; } break; } } if (esxVI_LocalDatastoreInfo_DynamicCast(datastoreInfo)) { *poolType = VIR_STORAGE_POOL_DIR; } else if (esxVI_NasDatastoreInfo_DynamicCast(datastoreInfo)) { *poolType = VIR_STORAGE_POOL_NETFS; } else if (esxVI_VmfsDatastoreInfo_DynamicCast(datastoreInfo)) { *poolType = VIR_STORAGE_POOL_FS; } else { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("DatastoreInfo has unexpected type")); goto cleanup; } result = 0; cleanup: esxVI_String_Free(&propertyNameList); esxVI_ObjectContent_Free(&datastore); esxVI_DatastoreInfo_Free(&datastoreInfo); return result; } static int esxConnectNumOfStoragePools(virConnectPtr conn) { int count = 0; esxPrivate *priv = conn->privateData; esxVI_ObjectContent *datastoreList = NULL; esxVI_ObjectContent *datastore = NULL; if (esxVI_LookupDatastoreList(priv->primary, NULL, &datastoreList) < 0) return -1; for (datastore = datastoreList; datastore; datastore = datastore->_next) { ++count; } esxVI_ObjectContent_Free(&datastoreList); return count; } static int esxConnectListStoragePools(virConnectPtr conn, char **const names, const int maxnames) { bool success = false; esxPrivate *priv = conn->privateData; esxVI_String *propertyNameList = NULL; esxVI_DynamicProperty *dynamicProperty = NULL; esxVI_ObjectContent *datastoreList = NULL; esxVI_ObjectContent *datastore = NULL; int count = 0; size_t i; if (maxnames == 0) return 0; if (esxVI_String_AppendValueToList(&propertyNameList, "summary.name") < 0 || esxVI_LookupDatastoreList(priv->primary, propertyNameList, &datastoreList) < 0) { goto cleanup; } for (datastore = datastoreList; datastore; datastore = datastore->_next) { for (dynamicProperty = datastore->propSet; dynamicProperty; dynamicProperty = dynamicProperty->_next) { if (STREQ(dynamicProperty->name, "summary.name")) { if (esxVI_AnyType_ExpectType(dynamicProperty->val, esxVI_Type_String) < 0) { goto cleanup; } if (VIR_STRDUP(names[count], dynamicProperty->val->string) < 0) goto cleanup; ++count; break; } else { VIR_WARN("Unexpected '%s' property", dynamicProperty->name); } } } success = true; cleanup: if (! success) { for (i = 0; i < count; ++i) VIR_FREE(names[i]); count = -1; } esxVI_String_Free(&propertyNameList); esxVI_ObjectContent_Free(&datastoreList); return count; } static virStoragePoolPtr esxStoragePoolLookupByName(virConnectPtr conn, const char *name) { esxPrivate *priv = conn->privateData; esxVI_ObjectContent *datastore = NULL; esxVI_DatastoreHostMount *hostMount = NULL; /* MD5_DIGEST_SIZE = VIR_UUID_BUFLEN = 16 */ unsigned char md5[MD5_DIGEST_SIZE]; virStoragePoolPtr pool = NULL; if (esxVI_LookupDatastoreByName(priv->primary, name, NULL, &datastore, esxVI_Occurrence_OptionalItem) < 0) { goto cleanup; } if (!datastore) { /* Not found, let the base storage driver handle error reporting */ goto cleanup; } /* * Datastores don't have a UUID, but we can use the 'host.mountInfo.path' * property as source for a UUID. The mount path is unique per host and * cannot change during the lifetime of the datastore. * * The MD5 sum of the mount path can be used as UUID, assuming MD5 is * considered to be collision-free enough for this use case. */ if (esxVI_LookupDatastoreHostMount(priv->primary, datastore->obj, &hostMount, esxVI_Occurrence_OptionalItem) < 0) { goto cleanup; } if (!hostMount) { /* Not found, let the base storage driver handle error reporting */ goto cleanup; } md5_buffer(hostMount->mountInfo->path, strlen(hostMount->mountInfo->path), md5); pool = virGetStoragePool(conn, name, md5, &esxStorageBackendVMFS, NULL); cleanup: esxVI_ObjectContent_Free(&datastore); esxVI_DatastoreHostMount_Free(&hostMount); return pool; } static virStoragePoolPtr esxStoragePoolLookupByUUID(virConnectPtr conn, const unsigned char *uuid) { esxPrivate *priv = conn->privateData; esxVI_String *propertyNameList = NULL; esxVI_ObjectContent *datastoreList = NULL; esxVI_ObjectContent *datastore = NULL; esxVI_DatastoreHostMount *hostMount = NULL; /* MD5_DIGEST_SIZE = VIR_UUID_BUFLEN = 16 */ unsigned char md5[MD5_DIGEST_SIZE]; char *name = NULL; virStoragePoolPtr pool = NULL; if (esxVI_String_AppendValueToList(&propertyNameList, "summary.name") < 0 || esxVI_LookupDatastoreList(priv->primary, propertyNameList, &datastoreList) < 0) { goto cleanup; } for (datastore = datastoreList; datastore; datastore = datastore->_next) { esxVI_DatastoreHostMount_Free(&hostMount); if (esxVI_LookupDatastoreHostMount(priv->primary, datastore->obj, &hostMount, esxVI_Occurrence_OptionalItem) < 0) { goto cleanup; } if (!hostMount) { /* * Storage pool is not of VMFS type, leave error reporting to the * base storage driver. */ goto cleanup; } md5_buffer(hostMount->mountInfo->path, strlen(hostMount->mountInfo->path), md5); if (memcmp(uuid, md5, VIR_UUID_BUFLEN) == 0) break; } if (!datastore) { /* Not found, let the base storage driver handle error reporting */ goto cleanup; } if (esxVI_GetStringValue(datastore, "summary.name", &name, esxVI_Occurrence_RequiredItem) < 0) { goto cleanup; } pool = virGetStoragePool(conn, name, uuid, &esxStorageBackendVMFS, NULL); cleanup: esxVI_String_Free(&propertyNameList); esxVI_ObjectContent_Free(&datastoreList); esxVI_DatastoreHostMount_Free(&hostMount); return pool; } static int esxStoragePoolRefresh(virStoragePoolPtr pool, unsigned int flags) { int result = -1; esxPrivate *priv = pool->conn->privateData; esxVI_ObjectContent *datastore = NULL; virCheckFlags(0, -1); if (esxVI_LookupDatastoreByName(priv->primary, pool->name, NULL, &datastore, esxVI_Occurrence_RequiredItem) < 0 || esxVI_RefreshDatastore(priv->primary, datastore->obj) < 0) { goto cleanup; } result = 0; cleanup: esxVI_ObjectContent_Free(&datastore); return result; } static int esxStoragePoolGetInfo(virStoragePoolPtr pool, virStoragePoolInfoPtr info) { int result = -1; esxPrivate *priv = pool->conn->privateData; esxVI_String *propertyNameList = NULL; esxVI_ObjectContent *datastore = NULL; esxVI_DynamicProperty *dynamicProperty = NULL; esxVI_Boolean accessible = esxVI_Boolean_Undefined; if (esxVI_String_AppendValueListToList(&propertyNameList, "summary.accessible\0" "summary.capacity\0" "summary.freeSpace\0") < 0 || esxVI_LookupDatastoreByName(priv->primary, pool->name, propertyNameList, &datastore, esxVI_Occurrence_RequiredItem) < 0 || esxVI_GetBoolean(datastore, "summary.accessible", &accessible, esxVI_Occurrence_RequiredItem) < 0) { goto cleanup; } if (accessible == esxVI_Boolean_True) { info->state = VIR_STORAGE_POOL_RUNNING; for (dynamicProperty = datastore->propSet; dynamicProperty; dynamicProperty = dynamicProperty->_next) { if (STREQ(dynamicProperty->name, "summary.capacity")) { if (esxVI_AnyType_ExpectType(dynamicProperty->val, esxVI_Type_Long) < 0) { goto cleanup; } info->capacity = dynamicProperty->val->int64; } else if (STREQ(dynamicProperty->name, "summary.freeSpace")) { if (esxVI_AnyType_ExpectType(dynamicProperty->val, esxVI_Type_Long) < 0) { goto cleanup; } info->available = dynamicProperty->val->int64; } } info->allocation = info->capacity - info->available; } else { info->state = VIR_STORAGE_POOL_INACCESSIBLE; } result = 0; cleanup: esxVI_String_Free(&propertyNameList); esxVI_ObjectContent_Free(&datastore); return result; } static char * esxStoragePoolGetXMLDesc(virStoragePoolPtr pool, unsigned int flags) { esxPrivate *priv = pool->conn->privateData; esxVI_String *propertyNameList = NULL; esxVI_ObjectContent *datastore = NULL; esxVI_DatastoreHostMount *hostMount = NULL; esxVI_DynamicProperty *dynamicProperty = NULL; esxVI_Boolean accessible = esxVI_Boolean_Undefined; virStoragePoolDef def; esxVI_DatastoreInfo *info = NULL; esxVI_NasDatastoreInfo *nasInfo = NULL; char *xml = NULL; virCheckFlags(0, NULL); memset(&def, 0, sizeof(def)); if (esxVI_String_AppendValueListToList(&propertyNameList, "summary.accessible\0" "summary.capacity\0" "summary.freeSpace\0" "info\0") < 0 || esxVI_LookupDatastoreByName(priv->primary, pool->name, propertyNameList, &datastore, esxVI_Occurrence_RequiredItem) < 0 || esxVI_GetBoolean(datastore, "summary.accessible", &accessible, esxVI_Occurrence_RequiredItem) < 0 || esxVI_LookupDatastoreHostMount(priv->primary, datastore->obj, &hostMount, esxVI_Occurrence_RequiredItem) < 0) { goto cleanup; } def.name = pool->name; memcpy(def.uuid, pool->uuid, VIR_UUID_BUFLEN); def.target.path = hostMount->mountInfo->path; if (accessible == esxVI_Boolean_True) { for (dynamicProperty = datastore->propSet; dynamicProperty; dynamicProperty = dynamicProperty->_next) { if (STREQ(dynamicProperty->name, "summary.capacity")) { if (esxVI_AnyType_ExpectType(dynamicProperty->val, esxVI_Type_Long) < 0) { goto cleanup; } def.capacity = dynamicProperty->val->int64; } else if (STREQ(dynamicProperty->name, "summary.freeSpace")) { if (esxVI_AnyType_ExpectType(dynamicProperty->val, esxVI_Type_Long) < 0) { goto cleanup; } def.available = dynamicProperty->val->int64; } } def.allocation = def.capacity - def.available; } for (dynamicProperty = datastore->propSet; dynamicProperty; dynamicProperty = dynamicProperty->_next) { if (STREQ(dynamicProperty->name, "info")) { if (esxVI_DatastoreInfo_CastFromAnyType(dynamicProperty->val, &info) < 0) { goto cleanup; } break; } } /* See vSphere API documentation about HostDatastoreSystem for details */ if (esxVI_LocalDatastoreInfo_DynamicCast(info)) { def.type = VIR_STORAGE_POOL_DIR; } else if ((nasInfo = esxVI_NasDatastoreInfo_DynamicCast(info))) { if (VIR_ALLOC_N(def.source.hosts, 1) < 0) goto cleanup; def.type = VIR_STORAGE_POOL_NETFS; def.source.nhost = 1; def.source.hosts[0].name = nasInfo->nas->remoteHost; def.source.dir = nasInfo->nas->remotePath; if (STRCASEEQ(nasInfo->nas->type, "NFS")) { def.source.format = VIR_STORAGE_POOL_NETFS_NFS; } else if (STRCASEEQ(nasInfo->nas->type, "CIFS")) { def.source.format = VIR_STORAGE_POOL_NETFS_CIFS; } else { virReportError(VIR_ERR_INTERNAL_ERROR, _("Datastore has unexpected type '%s'"), nasInfo->nas->type); goto cleanup; } } else if (esxVI_VmfsDatastoreInfo_DynamicCast(info)) { def.type = VIR_STORAGE_POOL_FS; /* * FIXME: I'm not sure how to represent the source and target of a * VMFS based datastore in libvirt terms */ } else { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("DatastoreInfo has unexpected type")); goto cleanup; } xml = virStoragePoolDefFormat(&def); cleanup: VIR_FREE(def.source.hosts); esxVI_String_Free(&propertyNameList); esxVI_ObjectContent_Free(&datastore); esxVI_DatastoreHostMount_Free(&hostMount); esxVI_DatastoreInfo_Free(&info); return xml; } static int esxStoragePoolNumOfVolumes(virStoragePoolPtr pool) { bool success = false; esxPrivate *priv = pool->conn->privateData; esxVI_HostDatastoreBrowserSearchResults *searchResultsList = NULL; esxVI_HostDatastoreBrowserSearchResults *searchResults = NULL; esxVI_FileInfo *fileInfo = NULL; int count = 0; if (esxVI_LookupDatastoreContentByDatastoreName(priv->primary, pool->name, &searchResultsList) < 0) { goto cleanup; } /* Interpret search result */ for (searchResults = searchResultsList; searchResults; searchResults = searchResults->_next) { for (fileInfo = searchResults->file; fileInfo; fileInfo = fileInfo->_next) { ++count; } } success = true; cleanup: esxVI_HostDatastoreBrowserSearchResults_Free(&searchResultsList); return success ? count : -1; } static int esxStoragePoolListVolumes(virStoragePoolPtr pool, char **const names, int maxnames) { bool success = false; esxPrivate *priv = pool->conn->privateData; esxVI_HostDatastoreBrowserSearchResults *searchResultsList = NULL; esxVI_HostDatastoreBrowserSearchResults *searchResults = NULL; esxVI_FileInfo *fileInfo = NULL; char *directoryAndFileName = NULL; size_t length; int count = 0; size_t i; if (!names || maxnames < 0) { virReportError(VIR_ERR_INVALID_ARG, "%s", _("Invalid argument")); return -1; } if (maxnames == 0) return 0; if (esxVI_LookupDatastoreContentByDatastoreName(priv->primary, pool->name, &searchResultsList) < 0) { goto cleanup; } /* Interpret search result */ for (searchResults = searchResultsList; searchResults; searchResults = searchResults->_next) { VIR_FREE(directoryAndFileName); if (esxUtil_ParseDatastorePath(searchResults->folderPath, NULL, NULL, &directoryAndFileName) < 0) { goto cleanup; } /* Strip trailing separators */ length = strlen(directoryAndFileName); while (length > 0 && directoryAndFileName[length - 1] == '/') { directoryAndFileName[length - 1] = '\0'; --length; } /* Build volume names */ for (fileInfo = searchResults->file; fileInfo; fileInfo = fileInfo->_next) { if (length < 1) { if (VIR_STRDUP(names[count], fileInfo->path) < 0) goto cleanup; } else if (virAsprintf(&names[count], "%s/%s", directoryAndFileName, fileInfo->path) < 0) { goto cleanup; } ++count; } } success = true; cleanup: if (! success) { for (i = 0; i < count; ++i) VIR_FREE(names[i]); count = -1; } esxVI_HostDatastoreBrowserSearchResults_Free(&searchResultsList); VIR_FREE(directoryAndFileName); return count; } static virStorageVolPtr esxStorageVolLookupByName(virStoragePoolPtr pool, const char *name) { virStorageVolPtr volume = NULL; esxPrivate *priv = pool->conn->privateData; char *datastorePath = NULL; char *key = NULL; if (virAsprintf(&datastorePath, "[%s] %s", pool->name, name) < 0) goto cleanup; if (esxVI_LookupStorageVolumeKeyByDatastorePath(priv->primary, datastorePath, &key) < 0) { goto cleanup; } volume = virGetStorageVol(pool->conn, pool->name, name, key, &esxStorageBackendVMFS, NULL); cleanup: VIR_FREE(datastorePath); VIR_FREE(key); return volume; } static virStorageVolPtr esxStorageVolLookupByPath(virConnectPtr conn, const char *path) { virStorageVolPtr volume = NULL; esxPrivate *priv = conn->privateData; char *datastoreName = NULL; char *directoryAndFileName = NULL; char *key = NULL; if (esxUtil_ParseDatastorePath(path, &datastoreName, NULL, &directoryAndFileName) < 0) { goto cleanup; } if (esxVI_LookupStorageVolumeKeyByDatastorePath(priv->primary, path, &key) < 0) { goto cleanup; } volume = virGetStorageVol(conn, datastoreName, directoryAndFileName, key, &esxStorageBackendVMFS, NULL); cleanup: VIR_FREE(datastoreName); VIR_FREE(directoryAndFileName); VIR_FREE(key); return volume; } static virStorageVolPtr esxStorageVolLookupByKey(virConnectPtr conn, const char *key) { virStorageVolPtr volume = NULL; esxPrivate *priv = conn->privateData; esxVI_String *propertyNameList = NULL; esxVI_ObjectContent *datastoreList = NULL; esxVI_ObjectContent *datastore = NULL; char *datastoreName = NULL; esxVI_HostDatastoreBrowserSearchResults *searchResultsList = NULL; esxVI_HostDatastoreBrowserSearchResults *searchResults = NULL; char *directoryAndFileName = NULL; size_t length; char *datastorePath = NULL; char *volumeName = NULL; esxVI_FileInfo *fileInfo = NULL; char *uuid_string = NULL; char key_candidate[VIR_UUID_STRING_BUFLEN] = ""; if (STRPREFIX(key, "[")) { /* Key is probably a datastore path */ return esxStorageVolLookupByPath(conn, key); } if (!priv->primary->hasQueryVirtualDiskUuid) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("QueryVirtualDiskUuid not available, " "cannot lookup storage volume by UUID")); return NULL; } /* Lookup all datastores */ if (esxVI_String_AppendValueToList(&propertyNameList, "summary.name") < 0 || esxVI_LookupDatastoreList(priv->primary, propertyNameList, &datastoreList) < 0) { goto cleanup; } for (datastore = datastoreList; datastore; datastore = datastore->_next) { datastoreName = NULL; if (esxVI_GetStringValue(datastore, "summary.name", &datastoreName, esxVI_Occurrence_RequiredItem) < 0) { goto cleanup; } /* Lookup datastore content */ esxVI_HostDatastoreBrowserSearchResults_Free(&searchResultsList); if (esxVI_LookupDatastoreContentByDatastoreName (priv->primary, datastoreName, &searchResultsList) < 0) { goto cleanup; } /* Interpret search result */ for (searchResults = searchResultsList; searchResults; searchResults = searchResults->_next) { VIR_FREE(directoryAndFileName); if (esxUtil_ParseDatastorePath(searchResults->folderPath, NULL, NULL, &directoryAndFileName) < 0) { goto cleanup; } /* Strip trailing separators */ length = strlen(directoryAndFileName); while (length > 0 && directoryAndFileName[length - 1] == '/') { directoryAndFileName[length - 1] = '\0'; --length; } /* Build datastore path and query the UUID */ for (fileInfo = searchResults->file; fileInfo; fileInfo = fileInfo->_next) { VIR_FREE(datastorePath); if (length < 1) { if (VIR_STRDUP(volumeName, fileInfo->path) < 0) goto cleanup; } else if (virAsprintf(&volumeName, "%s/%s", directoryAndFileName, fileInfo->path) < 0) { goto cleanup; } if (virAsprintf(&datastorePath, "[%s] %s", datastoreName, volumeName) < 0) goto cleanup; if (!esxVI_VmDiskFileInfo_DynamicCast(fileInfo)) { /* Only a VirtualDisk has a UUID */ continue; } VIR_FREE(uuid_string); if (esxVI_QueryVirtualDiskUuid (priv->primary, datastorePath, priv->primary->datacenter->_reference, &uuid_string) < 0) { goto cleanup; } if (esxUtil_ReformatUuid(uuid_string, key_candidate) < 0) goto cleanup; if (STREQ(key, key_candidate)) { /* Found matching UUID */ volume = virGetStorageVol(conn, datastoreName, volumeName, key, &esxStorageBackendVMFS, NULL); goto cleanup; } } } } cleanup: esxVI_String_Free(&propertyNameList); esxVI_ObjectContent_Free(&datastoreList); esxVI_HostDatastoreBrowserSearchResults_Free(&searchResultsList); VIR_FREE(directoryAndFileName); VIR_FREE(datastorePath); VIR_FREE(volumeName); VIR_FREE(uuid_string); return volume; } static virStorageVolPtr esxStorageVolCreateXML(virStoragePoolPtr pool, const char *xmldesc, unsigned int flags) { virStorageVolPtr volume = NULL; esxPrivate *priv = pool->conn->privateData; virStoragePoolDef poolDef; virStorageVolDefPtr def = NULL; char *tmp; char *unescapedDatastorePath = NULL; char *unescapedDirectoryName = NULL; char *unescapedDirectoryAndFileName = NULL; char *directoryName = NULL; char *fileName = NULL; char *datastorePathWithoutFileName = NULL; char *datastorePath = NULL; esxVI_FileInfo *fileInfo = NULL; esxVI_FileBackedVirtualDiskSpec *virtualDiskSpec = NULL; esxVI_ManagedObjectReference *task = NULL; esxVI_TaskInfoState taskInfoState; char *taskInfoErrorMessage = NULL; char *uuid_string = NULL; char *key = NULL; virCheckFlags(0, NULL); memset(&poolDef, 0, sizeof(poolDef)); if (esxLookupVMFSStoragePoolType(priv->primary, pool->name, &poolDef.type) < 0) { goto cleanup; } /* Parse config */ def = virStorageVolDefParseString(&poolDef, xmldesc, 0); if (!def) goto cleanup; if (def->type != VIR_STORAGE_VOL_FILE) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Creating non-file volumes is not supported")); goto cleanup; } /* Validate config */ tmp = strrchr(def->name, '/'); if (!tmp || *def->name == '/' || tmp[1] == '\0') { virReportError(VIR_ERR_INTERNAL_ERROR, _("Volume name '%s' doesn't have expected format " "'<directory>/<file>'"), def->name); goto cleanup; } if (! virFileHasSuffix(def->name, ".vmdk")) { virReportError(VIR_ERR_INTERNAL_ERROR, _("Volume name '%s' has unsupported suffix, " "expecting '.vmdk'"), def->name); goto cleanup; } if (virAsprintf(&unescapedDatastorePath, "[%s] %s", pool->name, def->name) < 0) goto cleanup; if (def->target.format == VIR_STORAGE_FILE_VMDK) { /* Parse and escape datastore path */ if (esxUtil_ParseDatastorePath(unescapedDatastorePath, NULL, &unescapedDirectoryName, &unescapedDirectoryAndFileName) < 0) { goto cleanup; } directoryName = esxUtil_EscapeDatastoreItem(unescapedDirectoryName); if (!directoryName) goto cleanup; fileName = esxUtil_EscapeDatastoreItem(unescapedDirectoryAndFileName + strlen(unescapedDirectoryName) + 1); if (!fileName) goto cleanup; if (virAsprintf(&datastorePathWithoutFileName, "[%s] %s", pool->name, directoryName) < 0) goto cleanup; if (virAsprintf(&datastorePath, "[%s] %s/%s", pool->name, directoryName, fileName) < 0) goto cleanup; /* Create directory, if it doesn't exist yet */ if (esxVI_LookupFileInfoByDatastorePath (priv->primary, datastorePathWithoutFileName, true, &fileInfo, esxVI_Occurrence_OptionalItem) < 0) { goto cleanup; } if (!fileInfo) { if (esxVI_MakeDirectory(priv->primary, datastorePathWithoutFileName, priv->primary->datacenter->_reference, esxVI_Boolean_True) < 0) { goto cleanup; } } /* Create VirtualDisk */ if (esxVI_FileBackedVirtualDiskSpec_Alloc(&virtualDiskSpec) < 0 || esxVI_Long_Alloc(&virtualDiskSpec->capacityKb) < 0) { goto cleanup; } /* From the vSphere API documentation about VirtualDiskType ... */ if (def->target.allocation == def->target.capacity) { /* * "A preallocated disk has all space allocated at creation time * and the space is zeroed on demand as the space is used." */ virtualDiskSpec->diskType = (char *)"preallocated"; } else if (def->target.allocation == 0) { /* * "Space required for thin-provisioned virtual disk is allocated * and zeroed on demand as the space is used." */ virtualDiskSpec->diskType = (char *)"thin"; } else { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Unsupported capacity-to-allocation relation")); goto cleanup; } /* * FIXME: The adapter type is a required parameter, but there is no * way to let the user specify it in the volume XML config. Therefore, * default to 'lsilogic' here. */ virtualDiskSpec->adapterType = (char *)"lsilogic"; virtualDiskSpec->capacityKb->value = VIR_DIV_UP(def->target.capacity, 1024); /* Scale from byte to kilobyte */ if (esxVI_CreateVirtualDisk_Task (priv->primary, datastorePath, priv->primary->datacenter->_reference, esxVI_VirtualDiskSpec_DynamicCast(virtualDiskSpec), &task) < 0 || esxVI_WaitForTaskCompletion(priv->primary, task, NULL, esxVI_Occurrence_None, priv->parsedUri->autoAnswer, &taskInfoState, &taskInfoErrorMessage) < 0) { goto cleanup; } if (taskInfoState != esxVI_TaskInfoState_Success) { virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not create volume: %s"), taskInfoErrorMessage); goto cleanup; } if (priv->primary->hasQueryVirtualDiskUuid) { if (VIR_ALLOC_N(key, VIR_UUID_STRING_BUFLEN) < 0) goto cleanup; if (esxVI_QueryVirtualDiskUuid(priv->primary, datastorePath, priv->primary->datacenter->_reference, &uuid_string) < 0) { goto cleanup; } if (esxUtil_ReformatUuid(uuid_string, key) < 0) goto cleanup; } else { /* Fall back to the path as key */ if (VIR_STRDUP(key, datastorePath) < 0) goto cleanup; } } else { virReportError(VIR_ERR_INTERNAL_ERROR, _("Creation of %s volumes is not supported"), virStorageFileFormatTypeToString(def->target.format)); goto cleanup; } volume = virGetStorageVol(pool->conn, pool->name, def->name, key, &esxStorageBackendVMFS, NULL); cleanup: if (virtualDiskSpec) { virtualDiskSpec->diskType = NULL; virtualDiskSpec->adapterType = NULL; } virStorageVolDefFree(def); VIR_FREE(unescapedDatastorePath); VIR_FREE(unescapedDirectoryName); VIR_FREE(unescapedDirectoryAndFileName); VIR_FREE(directoryName); VIR_FREE(fileName); VIR_FREE(datastorePathWithoutFileName); VIR_FREE(datastorePath); esxVI_FileInfo_Free(&fileInfo); esxVI_FileBackedVirtualDiskSpec_Free(&virtualDiskSpec); esxVI_ManagedObjectReference_Free(&task); VIR_FREE(taskInfoErrorMessage); VIR_FREE(uuid_string); VIR_FREE(key); return volume; } static virStorageVolPtr esxStorageVolCreateXMLFrom(virStoragePoolPtr pool, const char *xmldesc, virStorageVolPtr sourceVolume, unsigned int flags) { virStorageVolPtr volume = NULL; esxPrivate *priv = pool->conn->privateData; virStoragePoolDef poolDef; char *sourceDatastorePath = NULL; virStorageVolDefPtr def = NULL; char *tmp; char *unescapedDatastorePath = NULL; char *unescapedDirectoryName = NULL; char *unescapedDirectoryAndFileName = NULL; char *directoryName = NULL; char *fileName = NULL; char *datastorePathWithoutFileName = NULL; char *datastorePath = NULL; esxVI_FileInfo *fileInfo = NULL; esxVI_ManagedObjectReference *task = NULL; esxVI_TaskInfoState taskInfoState; char *taskInfoErrorMessage = NULL; char *uuid_string = NULL; char *key = NULL; virCheckFlags(0, NULL); memset(&poolDef, 0, sizeof(poolDef)); if (esxLookupVMFSStoragePoolType(priv->primary, pool->name, &poolDef.type) < 0) { goto cleanup; } if (virAsprintf(&sourceDatastorePath, "[%s] %s", sourceVolume->pool, sourceVolume->name) < 0) goto cleanup; /* Parse config */ def = virStorageVolDefParseString(&poolDef, xmldesc, 0); if (!def) goto cleanup; if (def->type != VIR_STORAGE_VOL_FILE) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Creating non-file volumes is not supported")); goto cleanup; } /* Validate config */ tmp = strrchr(def->name, '/'); if (!tmp || *def->name == '/' || tmp[1] == '\0') { virReportError(VIR_ERR_INTERNAL_ERROR, _("Volume name '%s' doesn't have expected format " "'<directory>/<file>'"), def->name); goto cleanup; } if (! virFileHasSuffix(def->name, ".vmdk")) { virReportError(VIR_ERR_INTERNAL_ERROR, _("Volume name '%s' has unsupported suffix, " "expecting '.vmdk'"), def->name); goto cleanup; } if (virAsprintf(&unescapedDatastorePath, "[%s] %s", pool->name, def->name) < 0) goto cleanup; if (def->target.format == VIR_STORAGE_FILE_VMDK) { /* Parse and escape datastore path */ if (esxUtil_ParseDatastorePath(unescapedDatastorePath, NULL, &unescapedDirectoryName, &unescapedDirectoryAndFileName) < 0) { goto cleanup; } directoryName = esxUtil_EscapeDatastoreItem(unescapedDirectoryName); if (!directoryName) goto cleanup; fileName = esxUtil_EscapeDatastoreItem(unescapedDirectoryAndFileName + strlen(unescapedDirectoryName) + 1); if (!fileName) goto cleanup; if (virAsprintf(&datastorePathWithoutFileName, "[%s] %s", pool->name, directoryName) < 0) goto cleanup; if (virAsprintf(&datastorePath, "[%s] %s/%s", pool->name, directoryName, fileName) < 0) goto cleanup; /* Create directory, if it doesn't exist yet */ if (esxVI_LookupFileInfoByDatastorePath (priv->primary, datastorePathWithoutFileName, true, &fileInfo, esxVI_Occurrence_OptionalItem) < 0) { goto cleanup; } if (!fileInfo) { if (esxVI_MakeDirectory(priv->primary, datastorePathWithoutFileName, priv->primary->datacenter->_reference, esxVI_Boolean_True) < 0) { goto cleanup; } } /* Copy VirtualDisk */ if (esxVI_CopyVirtualDisk_Task(priv->primary, sourceDatastorePath, priv->primary->datacenter->_reference, datastorePath, priv->primary->datacenter->_reference, NULL, esxVI_Boolean_False, &task) < 0 || esxVI_WaitForTaskCompletion(priv->primary, task, NULL, esxVI_Occurrence_None, priv->parsedUri->autoAnswer, &taskInfoState, &taskInfoErrorMessage) < 0) { goto cleanup; } if (taskInfoState != esxVI_TaskInfoState_Success) { virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not copy volume: %s"), taskInfoErrorMessage); goto cleanup; } if (priv->primary->hasQueryVirtualDiskUuid) { if (VIR_ALLOC_N(key, VIR_UUID_STRING_BUFLEN) < 0) goto cleanup; if (esxVI_QueryVirtualDiskUuid(priv->primary, datastorePath, priv->primary->datacenter->_reference, &uuid_string) < 0) { goto cleanup; } if (esxUtil_ReformatUuid(uuid_string, key) < 0) goto cleanup; } else { /* Fall back to the path as key */ if (VIR_STRDUP(key, datastorePath) < 0) goto cleanup; } } else { virReportError(VIR_ERR_INTERNAL_ERROR, _("Creation of %s volumes is not supported"), virStorageFileFormatTypeToString(def->target.format)); goto cleanup; } volume = virGetStorageVol(pool->conn, pool->name, def->name, key, &esxStorageBackendVMFS, NULL); cleanup: VIR_FREE(sourceDatastorePath); virStorageVolDefFree(def); VIR_FREE(unescapedDatastorePath); VIR_FREE(unescapedDirectoryName); VIR_FREE(unescapedDirectoryAndFileName); VIR_FREE(directoryName); VIR_FREE(fileName); VIR_FREE(datastorePathWithoutFileName); VIR_FREE(datastorePath); esxVI_FileInfo_Free(&fileInfo); esxVI_ManagedObjectReference_Free(&task); VIR_FREE(taskInfoErrorMessage); VIR_FREE(uuid_string); VIR_FREE(key); return volume; } static int esxStorageVolDelete(virStorageVolPtr volume, unsigned int flags) { int result = -1; esxPrivate *priv = volume->conn->privateData; char *datastorePath = NULL; esxVI_ManagedObjectReference *task = NULL; esxVI_TaskInfoState taskInfoState; char *taskInfoErrorMessage = NULL; virCheckFlags(0, -1); if (virAsprintf(&datastorePath, "[%s] %s", volume->pool, volume->name) < 0) goto cleanup; if (esxVI_DeleteVirtualDisk_Task(priv->primary, datastorePath, priv->primary->datacenter->_reference, &task) < 0 || esxVI_WaitForTaskCompletion(priv->primary, task, NULL, esxVI_Occurrence_None, priv->parsedUri->autoAnswer, &taskInfoState, &taskInfoErrorMessage) < 0) { goto cleanup; } if (taskInfoState != esxVI_TaskInfoState_Success) { virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not delete volume: %s"), taskInfoErrorMessage); goto cleanup; } result = 0; cleanup: VIR_FREE(datastorePath); esxVI_ManagedObjectReference_Free(&task); VIR_FREE(taskInfoErrorMessage); return result; } static int esxStorageVolWipe(virStorageVolPtr volume, unsigned int flags) { int result = -1; esxPrivate *priv = volume->conn->privateData; char *datastorePath = NULL; esxVI_ManagedObjectReference *task = NULL; esxVI_TaskInfoState taskInfoState; char *taskInfoErrorMessage = NULL; virCheckFlags(0, -1); if (virAsprintf(&datastorePath, "[%s] %s", volume->pool, volume->name) < 0) goto cleanup; if (esxVI_ZeroFillVirtualDisk_Task(priv->primary, datastorePath, priv->primary->datacenter->_reference, &task) < 0 || esxVI_WaitForTaskCompletion(priv->primary, task, NULL, esxVI_Occurrence_None, priv->parsedUri->autoAnswer, &taskInfoState, &taskInfoErrorMessage) < 0) { goto cleanup; } if (taskInfoState != esxVI_TaskInfoState_Success) { virReportError(VIR_ERR_INTERNAL_ERROR, _("Could not wipe volume: %s"), taskInfoErrorMessage); goto cleanup; } result = 0; cleanup: VIR_FREE(datastorePath); esxVI_ManagedObjectReference_Free(&task); VIR_FREE(taskInfoErrorMessage); return result; } static int esxStorageVolGetInfo(virStorageVolPtr volume, virStorageVolInfoPtr info) { int result = -1; esxPrivate *priv = volume->conn->privateData; char *datastorePath = NULL; esxVI_FileInfo *fileInfo = NULL; esxVI_VmDiskFileInfo *vmDiskFileInfo = NULL; memset(info, 0, sizeof(*info)); if (virAsprintf(&datastorePath, "[%s] %s", volume->pool, volume->name) < 0) goto cleanup; if (esxVI_LookupFileInfoByDatastorePath(priv->primary, datastorePath, false, &fileInfo, esxVI_Occurrence_RequiredItem) < 0) { goto cleanup; } vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(fileInfo); info->type = VIR_STORAGE_VOL_FILE; if (vmDiskFileInfo) { /* Scale from kilobyte to byte */ info->capacity = vmDiskFileInfo->capacityKb->value * 1024; info->allocation = vmDiskFileInfo->fileSize->value; } else { info->capacity = fileInfo->fileSize->value; info->allocation = fileInfo->fileSize->value; } result = 0; cleanup: VIR_FREE(datastorePath); esxVI_FileInfo_Free(&fileInfo); return result; } static char * esxStorageVolGetXMLDesc(virStorageVolPtr volume, unsigned int flags) { esxPrivate *priv = volume->conn->privateData; virStoragePoolDef pool; char *datastorePath = NULL; esxVI_FileInfo *fileInfo = NULL; esxVI_VmDiskFileInfo *vmDiskFileInfo = NULL; esxVI_IsoImageFileInfo *isoImageFileInfo = NULL; esxVI_FloppyImageFileInfo *floppyImageFileInfo = NULL; virStorageVolDef def; char *xml = NULL; virCheckFlags(0, NULL); memset(&pool, 0, sizeof(pool)); memset(&def, 0, sizeof(def)); if (esxLookupVMFSStoragePoolType(priv->primary, volume->pool, &pool.type) < 0) { return NULL; } /* Lookup file info */ if (virAsprintf(&datastorePath, "[%s] %s", volume->pool, volume->name) < 0) goto cleanup; if (esxVI_LookupFileInfoByDatastorePath(priv->primary, datastorePath, false, &fileInfo, esxVI_Occurrence_RequiredItem) < 0) { goto cleanup; } vmDiskFileInfo = esxVI_VmDiskFileInfo_DynamicCast(fileInfo); isoImageFileInfo = esxVI_IsoImageFileInfo_DynamicCast(fileInfo); floppyImageFileInfo = esxVI_FloppyImageFileInfo_DynamicCast(fileInfo); def.name = volume->name; if (esxVI_LookupStorageVolumeKeyByDatastorePath(priv->primary, datastorePath, &def.key) < 0) { goto cleanup; } def.type = VIR_STORAGE_VOL_FILE; def.target.path = datastorePath; if (vmDiskFileInfo) { /* Scale from kilobyte to byte */ def.target.capacity = vmDiskFileInfo->capacityKb->value * 1024; def.target.allocation = vmDiskFileInfo->fileSize->value; def.target.format = VIR_STORAGE_FILE_VMDK; } else if (isoImageFileInfo) { def.target.capacity = fileInfo->fileSize->value; def.target.allocation = fileInfo->fileSize->value; def.target.format = VIR_STORAGE_FILE_ISO; } else if (floppyImageFileInfo) { def.target.capacity = fileInfo->fileSize->value; def.target.allocation = fileInfo->fileSize->value; def.target.format = VIR_STORAGE_FILE_RAW; } else { virReportError(VIR_ERR_INTERNAL_ERROR, _("File '%s' has unknown type"), datastorePath); goto cleanup; } xml = virStorageVolDefFormat(&pool, &def); cleanup: VIR_FREE(datastorePath); esxVI_FileInfo_Free(&fileInfo); VIR_FREE(def.key); return xml; } static char * esxStorageVolGetPath(virStorageVolPtr volume) { char *path; ignore_value(virAsprintf(&path, "[%s] %s", volume->pool, volume->name)); return path; } virStorageDriver esxStorageBackendVMFS = { .connectNumOfStoragePools = esxConnectNumOfStoragePools, /* 0.8.2 */ .connectListStoragePools = esxConnectListStoragePools, /* 0.8.2 */ .storagePoolLookupByName = esxStoragePoolLookupByName, /* 0.8.2 */ .storagePoolLookupByUUID = esxStoragePoolLookupByUUID, /* 0.8.2 */ .storagePoolRefresh = esxStoragePoolRefresh, /* 0.8.2 */ .storagePoolGetInfo = esxStoragePoolGetInfo, /* 0.8.2 */ .storagePoolGetXMLDesc = esxStoragePoolGetXMLDesc, /* 0.8.2 */ .storagePoolNumOfVolumes = esxStoragePoolNumOfVolumes, /* 0.8.4 */ .storagePoolListVolumes = esxStoragePoolListVolumes, /* 0.8.4 */ .storageVolLookupByName = esxStorageVolLookupByName, /* 0.8.4 */ .storageVolLookupByPath = esxStorageVolLookupByPath, /* 0.8.4 */ .storageVolLookupByKey = esxStorageVolLookupByKey, /* 0.8.4 */ .storageVolCreateXML = esxStorageVolCreateXML, /* 0.8.4 */ .storageVolCreateXMLFrom = esxStorageVolCreateXMLFrom, /* 0.8.7 */ .storageVolDelete = esxStorageVolDelete, /* 0.8.7 */ .storageVolWipe = esxStorageVolWipe, /* 0.8.7 */ .storageVolGetInfo = esxStorageVolGetInfo, /* 0.8.4 */ .storageVolGetXMLDesc = esxStorageVolGetXMLDesc, /* 0.8.4 */ .storageVolGetPath = esxStorageVolGetPath, /* 0.8.4 */ };
VenkatDatta/libvirt
src/esx/esx_storage_backend_vmfs.c
C
lgpl-2.1
47,967
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.16"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>CQRS.NET: Cqrs.Repositories.Queries.CollectionResultQuery&lt; TQueryStrategy, TData &gt; Class Template Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(initResizable); /* @license-end */</script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ extensions: ["tex2jax.js"], jax: ["input/TeX","output/HTML-CSS"], }); </script><script type="text/javascript" async="async" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">CQRS.NET &#160;<span id="projectnumber">4.0</span> </div> <div id="projectbrief">A lightweight enterprise Function as a Service (FaaS) framework to write function based serverless and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.16 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(function(){initNavTree('classCqrs_1_1Repositories_1_1Queries_1_1CollectionResultQuery.html','');}); /* @license-end */ </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">Cqrs.Repositories.Queries.CollectionResultQuery&lt; TQueryStrategy, TData &gt; Class Template Reference</div> </div> </div><!--header--> <div class="contents"> <p>A query that will produce a result that contains a collection of <em>TData</em> items. <a href="classCqrs_1_1Repositories_1_1Queries_1_1CollectionResultQuery.html#details">More...</a></p> <div id="dynsection-0" onclick="return toggleVisibility(this)" class="dynheader closed" style="cursor:pointer;"> <img id="dynsection-0-trigger" src="closed.png" alt="+"/> Inheritance diagram for Cqrs.Repositories.Queries.CollectionResultQuery&lt; TQueryStrategy, TData &gt;:</div> <div id="dynsection-0-summary" class="dynsummary" style="display:block;"> </div> <div id="dynsection-0-content" class="dyncontent" style="display:none;"> <div class="center"> <img src="classCqrs_1_1Repositories_1_1Queries_1_1CollectionResultQuery.png" usemap="#Cqrs.Repositories.Queries.CollectionResultQuery_3C_20TQueryStrategy_2C_20TData_20_3E_map" alt=""/> <map id="Cqrs.Repositories.Queries.CollectionResultQuery_3C_20TQueryStrategy_2C_20TData_20_3E_map" name="Cqrs.Repositories.Queries.CollectionResultQuery_3C_20TQueryStrategy_2C_20TData_20_3E_map"> <area href="interfaceCqrs_1_1Repositories_1_1Queries_1_1ICollectionResultQuery.html" alt="Cqrs.Repositories.Queries.ICollectionResultQuery&lt; TQueryStrategy, TData &gt;" shape="rect" coords="459,0,908,24"/> </map> </div></div> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>A query that will produce a result that contains a collection of <em>TData</em> items. </p> <dl class="tparams"><dt>Template Parameters</dt><dd> <table class="tparams"> <tr><td class="paramname">TQueryStrategy</td><td>The Type of the <a class="el" href="interfaceCqrs_1_1Repositories_1_1Queries_1_1IQueryStrategy.html" title="A specification for a query to execute.">IQueryStrategy</a>.</td></tr> <tr><td class="paramname">TData</td><td>The Type of data in the result collection.</td></tr> </table> </dd> </dl> <div class="typeconstraint"> <dl><dt><b>Type Constraints</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"><em>TQueryStrategy</em></td><td>&#160;:</td><td valign="top"><em><a class="el" href="interfaceCqrs_1_1Repositories_1_1Queries_1_1IQueryStrategy.html">IQueryStrategy</a></em></td><td>&#160;</td></tr> </table> </dd> </dl> </div> </div></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Repositories.html">Repositories</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Repositories_1_1Queries.html">Queries</a></li><li class="navelem"><a class="el" href="classCqrs_1_1Repositories_1_1Queries_1_1CollectionResultQuery.html">CollectionResultQuery</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.16 </li> </ul> </div> </body> </html>
Chinchilla-Software-Com/CQRS
wiki/docs/4.0/html/classCqrs_1_1Repositories_1_1Queries_1_1CollectionResultQuery.html
HTML
lgpl-2.1
7,421
/* GStreamer * Copyright (C) 2007-2008 Wouter Cloetens <[email protected]> * * 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 */ /** * SECTION:element-souphttpsrc * * This plugin reads data from a remote location specified by a URI. * Supported protocols are 'http', 'https'. * * An HTTP proxy must be specified by its URL. * If the "http_proxy" environment variable is set, its value is used. * If built with libsoup's GNOME integration features, the GNOME proxy * configuration will be used, or failing that, proxy autodetection. * The #GstSoupHTTPSrc:proxy property can be used to override the default. * * In case the #GstSoupHTTPSrc:iradio-mode property is set and the location is * an HTTP resource, souphttpsrc will send special Icecast HTTP headers to the * server to request additional Icecast meta-information. * If the server is not an Icecast server, it will behave as if the * #GstSoupHTTPSrc:iradio-mode property were not set. If it is, souphttpsrc will * output data with a media type of application/x-icy, in which case you will * need to use the #ICYDemux element as follow-up element to extract the Icecast * metadata and to determine the underlying media type. * * <refsect2> * <title>Example launch line</title> * |[ * gst-launch -v souphttpsrc location=https://some.server.org/index.html * ! filesink location=/home/joe/server.html * ]| The above pipeline reads a web page from a server using the HTTPS protocol * and writes it to a local file. * |[ * gst-launch -v souphttpsrc user-agent="FooPlayer 0.99 beta" * automatic-redirect=false proxy=http://proxy.intranet.local:8080 * location=http://music.foobar.com/demo.mp3 ! mad ! audioconvert * ! audioresample ! alsasink * ]| The above pipeline will read and decode and play an mp3 file from a * web server using the HTTP protocol. If the server sends redirects, * the request fails instead of following the redirect. The specified * HTTP proxy server is used. The User-Agent HTTP request header * is set to a custom string instead of "GStreamer souphttpsrc." * |[ * gst-launch -v souphttpsrc location=http://10.11.12.13/mjpeg * do-timestamp=true ! multipartdemux * ! image/jpeg,width=640,height=480 ! matroskamux * ! filesink location=mjpeg.mkv * ]| The above pipeline reads a motion JPEG stream from an IP camera * using the HTTP protocol, encoded as mime/multipart image/jpeg * parts, and writes a Matroska motion JPEG file. The width and * height properties are set in the caps to provide the Matroska * multiplexer with the information to set this in the header. * Timestamps are set on the buffers as they arrive from the camera. * These are used by the mime/multipart demultiplexer to emit timestamps * on the JPEG-encoded video frame buffers. This allows the Matroska * multiplexer to timestamp the frames in the resulting file. * </refsect2> */ #define GLIB_DISABLE_DEPRECATION_WARNINGS #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <string.h> #ifdef HAVE_STDLIB_H #include <stdlib.h> /* atoi() */ #endif #include <gst/gstelement.h> #include <gst/gst-i18n-plugin.h> #ifdef HAVE_LIBSOUP_GNOME #include <libsoup/soup-gnome.h> #else #include <libsoup/soup.h> #endif #include "gstsouphttpsrc.h" #include <gst/tag/tag.h> GST_DEBUG_CATEGORY_STATIC (souphttpsrc_debug); #define GST_CAT_DEFAULT souphttpsrc_debug static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS_ANY); enum { PROP_0, PROP_LOCATION, PROP_IS_LIVE, PROP_USER_AGENT, PROP_AUTOMATIC_REDIRECT, PROP_PROXY, PROP_USER_ID, PROP_USER_PW, PROP_PROXY_ID, PROP_PROXY_PW, PROP_COOKIES, PROP_IRADIO_MODE, PROP_IRADIO_NAME, PROP_IRADIO_GENRE, PROP_IRADIO_URL, PROP_IRADIO_TITLE, PROP_TIMEOUT, PROP_EXTRA_HEADERS }; #define DEFAULT_USER_AGENT "GStreamer souphttpsrc " static void gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data); static void gst_soup_http_src_finalize (GObject * gobject); static void gst_soup_http_src_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_soup_http_src_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); static GstFlowReturn gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf); static gboolean gst_soup_http_src_start (GstBaseSrc * bsrc); static gboolean gst_soup_http_src_stop (GstBaseSrc * bsrc); static gboolean gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size); static gboolean gst_soup_http_src_is_seekable (GstBaseSrc * bsrc); static gboolean gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment); static gboolean gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query); static gboolean gst_soup_http_src_unlock (GstBaseSrc * bsrc); static gboolean gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc); static gboolean gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri); static gboolean gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri); static char *gst_soup_http_src_unicodify (const char *str); static gboolean gst_soup_http_src_build_message (GstSoupHTTPSrc * src); static void gst_soup_http_src_cancel_message (GstSoupHTTPSrc * src); static void gst_soup_http_src_queue_message (GstSoupHTTPSrc * src); static gboolean gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src, guint64 offset); static void gst_soup_http_src_session_unpause_message (GstSoupHTTPSrc * src); static void gst_soup_http_src_session_pause_message (GstSoupHTTPSrc * src); static void gst_soup_http_src_session_close (GstSoupHTTPSrc * src); static void gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src); static void gst_soup_http_src_chunk_free (gpointer gstbuf); static SoupBuffer *gst_soup_http_src_chunk_allocator (SoupMessage * msg, gsize max_len, gpointer user_data); static void gst_soup_http_src_got_chunk_cb (SoupMessage * msg, SoupBuffer * chunk, GstSoupHTTPSrc * src); static void gst_soup_http_src_response_cb (SoupSession * session, SoupMessage * msg, GstSoupHTTPSrc * src); static void gst_soup_http_src_got_headers_cb (SoupMessage * msg, GstSoupHTTPSrc * src); static void gst_soup_http_src_got_body_cb (SoupMessage * msg, GstSoupHTTPSrc * src); static void gst_soup_http_src_finished_cb (SoupMessage * msg, GstSoupHTTPSrc * src); static void gst_soup_http_src_authenticate_cb (SoupSession * session, SoupMessage * msg, SoupAuth * auth, gboolean retrying, GstSoupHTTPSrc * src); static void _do_init (GType type) { static const GInterfaceInfo urihandler_info = { gst_soup_http_src_uri_handler_init, NULL, NULL }; g_type_add_interface_static (type, GST_TYPE_URI_HANDLER, &urihandler_info); GST_DEBUG_CATEGORY_INIT (souphttpsrc_debug, "souphttpsrc", 0, "SOUP HTTP src"); } GST_BOILERPLATE_FULL (GstSoupHTTPSrc, gst_soup_http_src, GstPushSrc, GST_TYPE_PUSH_SRC, _do_init); static void gst_soup_http_src_base_init (gpointer g_class) { GstElementClass *element_class = GST_ELEMENT_CLASS (g_class); gst_element_class_add_static_pad_template (element_class, &srctemplate); gst_element_class_set_details_simple (element_class, "HTTP client source", "Source/Network", "Receive data as a client over the network via HTTP using SOUP", "Wouter Cloetens <[email protected]>"); } static void gst_soup_http_src_class_init (GstSoupHTTPSrcClass * klass) { GObjectClass *gobject_class; GstBaseSrcClass *gstbasesrc_class; GstPushSrcClass *gstpushsrc_class; gobject_class = (GObjectClass *) klass; gstbasesrc_class = (GstBaseSrcClass *) klass; gstpushsrc_class = (GstPushSrcClass *) klass; gobject_class->set_property = gst_soup_http_src_set_property; gobject_class->get_property = gst_soup_http_src_get_property; gobject_class->finalize = gst_soup_http_src_finalize; g_object_class_install_property (gobject_class, PROP_LOCATION, g_param_spec_string ("location", "Location", "Location to read from", "", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_USER_AGENT, g_param_spec_string ("user-agent", "User-Agent", "Value of the User-Agent HTTP request header field", DEFAULT_USER_AGENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_AUTOMATIC_REDIRECT, g_param_spec_boolean ("automatic-redirect", "automatic-redirect", "Automatically follow HTTP redirects (HTTP Status Code 3xx)", TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_PROXY, g_param_spec_string ("proxy", "Proxy", "HTTP proxy server URI", "", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_USER_ID, g_param_spec_string ("user-id", "user-id", "HTTP location URI user id for authentication", "", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_USER_PW, g_param_spec_string ("user-pw", "user-pw", "HTTP location URI user password for authentication", "", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_PROXY_ID, g_param_spec_string ("proxy-id", "proxy-id", "HTTP proxy URI user id for authentication", "", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_PROXY_PW, g_param_spec_string ("proxy-pw", "proxy-pw", "HTTP proxy URI user password for authentication", "", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_COOKIES, g_param_spec_boxed ("cookies", "Cookies", "HTTP request cookies", G_TYPE_STRV, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_IS_LIVE, g_param_spec_boolean ("is-live", "is-live", "Act like a live source", FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_TIMEOUT, g_param_spec_uint ("timeout", "timeout", "Value in seconds to timeout a blocking I/O (0 = No timeout).", 0, 3600, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_EXTRA_HEADERS, g_param_spec_boxed ("extra-headers", "Extra Headers", "Extra headers to append to the HTTP request", GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /* icecast stuff */ g_object_class_install_property (gobject_class, PROP_IRADIO_MODE, g_param_spec_boolean ("iradio-mode", "iradio-mode", "Enable internet radio mode (extraction of shoutcast/icecast metadata)", FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_IRADIO_NAME, g_param_spec_string ("iradio-name", "iradio-name", "Name of the stream", NULL, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_IRADIO_GENRE, g_param_spec_string ("iradio-genre", "iradio-genre", "Genre of the stream", NULL, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_IRADIO_URL, g_param_spec_string ("iradio-url", "iradio-url", "Homepage URL for radio stream", NULL, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_IRADIO_TITLE, g_param_spec_string ("iradio-title", "iradio-title", "Name of currently playing song", NULL, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_soup_http_src_start); gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_soup_http_src_stop); gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock); gstbasesrc_class->unlock_stop = GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock_stop); gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_soup_http_src_get_size); gstbasesrc_class->is_seekable = GST_DEBUG_FUNCPTR (gst_soup_http_src_is_seekable); gstbasesrc_class->do_seek = GST_DEBUG_FUNCPTR (gst_soup_http_src_do_seek); gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_soup_http_src_query); gstpushsrc_class->create = GST_DEBUG_FUNCPTR (gst_soup_http_src_create); } static void gst_soup_http_src_reset (GstSoupHTTPSrc * src) { src->interrupted = FALSE; src->retry = FALSE; src->have_size = FALSE; src->seekable = FALSE; src->read_position = 0; src->request_position = 0; src->content_size = 0; gst_caps_replace (&src->src_caps, NULL); g_free (src->iradio_name); src->iradio_name = NULL; g_free (src->iradio_genre); src->iradio_genre = NULL; g_free (src->iradio_url); src->iradio_url = NULL; g_free (src->iradio_title); src->iradio_title = NULL; } static void gst_soup_http_src_init (GstSoupHTTPSrc * src, GstSoupHTTPSrcClass * g_class) { const gchar *proxy; src->location = NULL; src->automatic_redirect = TRUE; src->user_agent = g_strdup (DEFAULT_USER_AGENT); src->user_id = NULL; src->user_pw = NULL; src->proxy_id = NULL; src->proxy_pw = NULL; src->cookies = NULL; src->iradio_mode = FALSE; src->loop = NULL; src->context = NULL; src->session = NULL; src->msg = NULL; proxy = g_getenv ("http_proxy"); if (proxy && !gst_soup_http_src_set_proxy (src, proxy)) { GST_WARNING_OBJECT (src, "The proxy in the http_proxy env var (\"%s\") cannot be parsed.", proxy); } gst_soup_http_src_reset (src); } static void gst_soup_http_src_finalize (GObject * gobject) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject); GST_DEBUG_OBJECT (src, "finalize"); g_free (src->location); g_free (src->user_agent); if (src->proxy != NULL) { soup_uri_free (src->proxy); } g_free (src->user_id); g_free (src->user_pw); g_free (src->proxy_id); g_free (src->proxy_pw); g_strfreev (src->cookies); G_OBJECT_CLASS (parent_class)->finalize (gobject); } static void gst_soup_http_src_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object); switch (prop_id) { case PROP_LOCATION: { const gchar *location; location = g_value_get_string (value); if (location == NULL) { GST_WARNING ("location property cannot be NULL"); goto done; } if (!gst_soup_http_src_set_location (src, location)) { GST_WARNING ("badly formatted location"); goto done; } break; } case PROP_USER_AGENT: if (src->user_agent) g_free (src->user_agent); src->user_agent = g_value_dup_string (value); break; case PROP_IRADIO_MODE: src->iradio_mode = g_value_get_boolean (value); break; case PROP_AUTOMATIC_REDIRECT: src->automatic_redirect = g_value_get_boolean (value); break; case PROP_PROXY: { const gchar *proxy; proxy = g_value_get_string (value); if (proxy == NULL) { GST_WARNING ("proxy property cannot be NULL"); goto done; } if (!gst_soup_http_src_set_proxy (src, proxy)) { GST_WARNING ("badly formatted proxy URI"); goto done; } break; } case PROP_COOKIES: g_strfreev (src->cookies); src->cookies = g_strdupv (g_value_get_boxed (value)); break; case PROP_IS_LIVE: gst_base_src_set_live (GST_BASE_SRC (src), g_value_get_boolean (value)); break; case PROP_USER_ID: if (src->user_id) g_free (src->user_id); src->user_id = g_value_dup_string (value); break; case PROP_USER_PW: if (src->user_pw) g_free (src->user_pw); src->user_pw = g_value_dup_string (value); break; case PROP_PROXY_ID: if (src->proxy_id) g_free (src->proxy_id); src->proxy_id = g_value_dup_string (value); break; case PROP_PROXY_PW: if (src->proxy_pw) g_free (src->proxy_pw); src->proxy_pw = g_value_dup_string (value); break; case PROP_TIMEOUT: src->timeout = g_value_get_uint (value); break; case PROP_EXTRA_HEADERS:{ const GstStructure *s = gst_value_get_structure (value); if (src->extra_headers) gst_structure_free (src->extra_headers); src->extra_headers = s ? gst_structure_copy (s) : NULL; break; } default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } done: return; } static void gst_soup_http_src_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object); switch (prop_id) { case PROP_LOCATION: g_value_set_string (value, src->location); break; case PROP_USER_AGENT: g_value_set_string (value, src->user_agent); break; case PROP_AUTOMATIC_REDIRECT: g_value_set_boolean (value, src->automatic_redirect); break; case PROP_PROXY: if (src->proxy == NULL) g_value_set_static_string (value, ""); else { char *proxy = soup_uri_to_string (src->proxy, FALSE); g_value_set_string (value, proxy); g_free (proxy); } break; case PROP_COOKIES: g_value_set_boxed (value, g_strdupv (src->cookies)); break; case PROP_IS_LIVE: g_value_set_boolean (value, gst_base_src_is_live (GST_BASE_SRC (src))); break; case PROP_IRADIO_MODE: g_value_set_boolean (value, src->iradio_mode); break; case PROP_IRADIO_NAME: g_value_set_string (value, src->iradio_name); break; case PROP_IRADIO_GENRE: g_value_set_string (value, src->iradio_genre); break; case PROP_IRADIO_URL: g_value_set_string (value, src->iradio_url); break; case PROP_IRADIO_TITLE: g_value_set_string (value, src->iradio_title); break; case PROP_USER_ID: g_value_set_string (value, src->user_id); break; case PROP_USER_PW: g_value_set_string (value, src->user_pw); break; case PROP_PROXY_ID: g_value_set_string (value, src->proxy_id); break; case PROP_PROXY_PW: g_value_set_string (value, src->proxy_pw); break; case PROP_TIMEOUT: g_value_set_uint (value, src->timeout); break; case PROP_EXTRA_HEADERS: gst_value_set_structure (value, src->extra_headers); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static gchar * gst_soup_http_src_unicodify (const gchar * str) { const gchar *env_vars[] = { "GST_ICY_TAG_ENCODING", "GST_TAG_ENCODING", NULL }; return gst_tag_freeform_string_to_utf8 (str, -1, env_vars); } static void gst_soup_http_src_cancel_message (GstSoupHTTPSrc * src) { if (src->msg != NULL) { src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED; soup_session_cancel_message (src->session, src->msg, SOUP_STATUS_CANCELLED); } src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE; src->msg = NULL; } static void gst_soup_http_src_queue_message (GstSoupHTTPSrc * src) { soup_session_queue_message (src->session, src->msg, (SoupSessionCallback) gst_soup_http_src_response_cb, src); src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_QUEUED; } static gboolean gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src, guint64 offset) { gchar buf[64]; gint rc; soup_message_headers_remove (src->msg->request_headers, "Range"); if (offset) { rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-", offset); if (rc > sizeof (buf) || rc < 0) return FALSE; soup_message_headers_append (src->msg->request_headers, "Range", buf); } src->read_position = offset; return TRUE; } static gboolean _append_extra_header (GQuark field_id, const GValue * value, gpointer user_data) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (user_data); const gchar *field_name = g_quark_to_string (field_id); gchar *field_content = NULL; if (G_VALUE_TYPE (value) == G_TYPE_STRING) { field_content = g_value_dup_string (value); } else { GValue dest = { 0, }; g_value_init (&dest, G_TYPE_STRING); if (g_value_transform (value, &dest)) { field_content = g_value_dup_string (&dest); } } if (field_content == NULL) { GST_ERROR_OBJECT (src, "extra-headers field '%s' contains no value " "or can't be converted to a string", field_name); return FALSE; } GST_DEBUG_OBJECT (src, "Appending extra header: \"%s: %s\"", field_name, field_content); soup_message_headers_append (src->msg->request_headers, field_name, field_content); g_free (field_content); return TRUE; } static gboolean _append_extra_headers (GQuark field_id, const GValue * value, gpointer user_data) { if (G_VALUE_TYPE (value) == GST_TYPE_ARRAY) { guint n = gst_value_array_get_size (value); guint i; for (i = 0; i < n; i++) { const GValue *v = gst_value_array_get_value (value, i); if (!_append_extra_header (field_id, v, user_data)) return FALSE; } } else if (G_VALUE_TYPE (value) == GST_TYPE_LIST) { guint n = gst_value_list_get_size (value); guint i; for (i = 0; i < n; i++) { const GValue *v = gst_value_list_get_value (value, i); if (!_append_extra_header (field_id, v, user_data)) return FALSE; } } else { return _append_extra_header (field_id, value, user_data); } return TRUE; } static gboolean gst_soup_http_src_add_extra_headers (GstSoupHTTPSrc * src) { if (!src->extra_headers) return TRUE; return gst_structure_foreach (src->extra_headers, _append_extra_headers, src); } static void gst_soup_http_src_session_unpause_message (GstSoupHTTPSrc * src) { soup_session_unpause_message (src->session, src->msg); } static void gst_soup_http_src_session_pause_message (GstSoupHTTPSrc * src) { soup_session_pause_message (src->session, src->msg); } static void gst_soup_http_src_session_close (GstSoupHTTPSrc * src) { if (src->session) { soup_session_abort (src->session); /* This unrefs the message. */ g_object_unref (src->session); src->session = NULL; src->msg = NULL; } } static void gst_soup_http_src_authenticate_cb (SoupSession * session, SoupMessage * msg, SoupAuth * auth, gboolean retrying, GstSoupHTTPSrc * src) { if (!retrying) { /* First time authentication only, if we fail and are called again with retry true fall through */ if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) { if (src->user_id && src->user_pw) soup_auth_authenticate (auth, src->user_id, src->user_pw); } else if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) { if (src->proxy_id && src->proxy_pw) soup_auth_authenticate (auth, src->proxy_id, src->proxy_pw); } } } static void gst_soup_http_src_headers_foreach (const gchar * name, const gchar * val, gpointer src) { GST_DEBUG_OBJECT (src, " %s: %s", name, val); } static void gst_soup_http_src_got_headers_cb (SoupMessage * msg, GstSoupHTTPSrc * src) { const char *value; GstTagList *tag_list; GstBaseSrc *basesrc; guint64 newsize; GHashTable *params = NULL; GST_DEBUG_OBJECT (src, "got headers:"); soup_message_headers_foreach (msg->response_headers, gst_soup_http_src_headers_foreach, src); if (msg->status_code == 407 && src->proxy_id && src->proxy_pw) return; if (src->automatic_redirect && SOUP_STATUS_IS_REDIRECTION (msg->status_code)) { GST_DEBUG_OBJECT (src, "%u redirect to \"%s\"", msg->status_code, soup_message_headers_get_one (msg->response_headers, "Location")); return; } if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) return; src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING; /* Parse Content-Length. */ if (soup_message_headers_get_encoding (msg->response_headers) == SOUP_ENCODING_CONTENT_LENGTH) { newsize = src->request_position + soup_message_headers_get_content_length (msg->response_headers); if (!src->have_size || (src->content_size != newsize)) { src->content_size = newsize; src->have_size = TRUE; src->seekable = TRUE; GST_DEBUG_OBJECT (src, "size = %" G_GUINT64_FORMAT, src->content_size); basesrc = GST_BASE_SRC_CAST (src); gst_segment_set_duration (&basesrc->segment, GST_FORMAT_BYTES, src->content_size); gst_element_post_message (GST_ELEMENT (src), gst_message_new_duration (GST_OBJECT (src), GST_FORMAT_BYTES, src->content_size)); } } /* Icecast stuff */ tag_list = gst_tag_list_new (); if ((value = soup_message_headers_get_one (msg->response_headers, "icy-metaint")) != NULL) { gint icy_metaint = atoi (value); GST_DEBUG_OBJECT (src, "icy-metaint: %s (parsed: %d)", value, icy_metaint); if (icy_metaint > 0) { if (src->src_caps) gst_caps_unref (src->src_caps); src->src_caps = gst_caps_new_simple ("application/x-icy", "metadata-interval", G_TYPE_INT, icy_metaint, NULL); } } if ((value = soup_message_headers_get_content_type (msg->response_headers, &params)) != NULL) { GST_DEBUG_OBJECT (src, "Content-Type: %s", value); if (g_ascii_strcasecmp (value, "audio/L16") == 0) { gint channels = 2; gint rate = 44100; char *param; if (src->src_caps) gst_caps_unref (src->src_caps); param = g_hash_table_lookup (params, "channels"); if (param != NULL) channels = atol (param); param = g_hash_table_lookup (params, "rate"); if (param != NULL) rate = atol (param); src->src_caps = gst_caps_new_simple ("audio/x-raw-int", "channels", G_TYPE_INT, channels, "rate", G_TYPE_INT, rate, "width", G_TYPE_INT, 16, "depth", G_TYPE_INT, 16, "signed", G_TYPE_BOOLEAN, TRUE, "endianness", G_TYPE_INT, G_BIG_ENDIAN, NULL); } else { /* Set the Content-Type field on the caps */ if (src->src_caps) gst_caps_set_simple (src->src_caps, "content-type", G_TYPE_STRING, value, NULL); } } if (params != NULL) g_hash_table_destroy (params); if ((value = soup_message_headers_get_one (msg->response_headers, "icy-name")) != NULL) { g_free (src->iradio_name); src->iradio_name = gst_soup_http_src_unicodify (value); if (src->iradio_name) { g_object_notify (G_OBJECT (src), "iradio-name"); gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION, src->iradio_name, NULL); } } if ((value = soup_message_headers_get_one (msg->response_headers, "icy-genre")) != NULL) { g_free (src->iradio_genre); src->iradio_genre = gst_soup_http_src_unicodify (value); if (src->iradio_genre) { g_object_notify (G_OBJECT (src), "iradio-genre"); gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE, src->iradio_genre, NULL); } } if ((value = soup_message_headers_get_one (msg->response_headers, "icy-url")) != NULL) { g_free (src->iradio_url); src->iradio_url = gst_soup_http_src_unicodify (value); if (src->iradio_url) { g_object_notify (G_OBJECT (src), "iradio-url"); gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION, src->iradio_url, NULL); } } if (!gst_tag_list_is_empty (tag_list)) { GST_DEBUG_OBJECT (src, "calling gst_element_found_tags with %" GST_PTR_FORMAT, tag_list); gst_element_found_tags (GST_ELEMENT_CAST (src), tag_list); } else { gst_tag_list_free (tag_list); } /* Handle HTTP errors. */ gst_soup_http_src_parse_status (msg, src); /* Check if Range header was respected. */ if (src->ret == GST_FLOW_CUSTOM_ERROR && src->read_position && msg->status_code != SOUP_STATUS_PARTIAL_CONTENT) { src->seekable = FALSE; GST_ELEMENT_ERROR (src, RESOURCE, SEEK, (_("Server does not support seeking.")), ("Server does not accept Range HTTP header, URL: %s", src->location)); src->ret = GST_FLOW_ERROR; } } /* Have body. Signal EOS. */ static void gst_soup_http_src_got_body_cb (SoupMessage * msg, GstSoupHTTPSrc * src) { if (G_UNLIKELY (msg != src->msg)) { GST_DEBUG_OBJECT (src, "got body, but not for current message"); return; } if (G_UNLIKELY (src->session_io_status != GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) { /* Probably a redirect. */ return; } GST_DEBUG_OBJECT (src, "got body"); src->ret = GST_FLOW_UNEXPECTED; if (src->loop) g_main_loop_quit (src->loop); gst_soup_http_src_session_pause_message (src); } /* Finished. Signal EOS. */ static void gst_soup_http_src_finished_cb (SoupMessage * msg, GstSoupHTTPSrc * src) { if (G_UNLIKELY (msg != src->msg)) { GST_DEBUG_OBJECT (src, "finished, but not for current message"); return; } GST_DEBUG_OBJECT (src, "finished"); src->ret = GST_FLOW_UNEXPECTED; if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED) { /* gst_soup_http_src_cancel_message() triggered this; probably a seek * that occurred in the QUEUEING state; i.e. before the connection setup * was complete. Do nothing */ } else if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING && src->read_position > 0) { /* The server disconnected while streaming. Reconnect and seeking to the * last location. */ src->retry = TRUE; src->ret = GST_FLOW_CUSTOM_ERROR; } else if (G_UNLIKELY (src->session_io_status != GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) { /* FIXME: reason_phrase is not translated, add proper error message */ GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, ("%s", msg->reason_phrase), ("libsoup status code %d", msg->status_code)); } if (src->loop) g_main_loop_quit (src->loop); } /* Buffer lifecycle management. * * gst_soup_http_src_create() runs the GMainLoop for this element, to let * Soup take control. * A GstBuffer is allocated in gst_soup_http_src_chunk_allocator() and * associated with a SoupBuffer. * Soup reads HTTP data in the GstBuffer's data buffer. * The gst_soup_http_src_got_chunk_cb() is then called with the SoupBuffer. * That sets gst_soup_http_src_create()'s return argument to the GstBuffer, * increments its refcount (to 2), pauses the flow of data from the HTTP * source to prevent gst_soup_http_src_got_chunk_cb() from being called * again and breaks out of the GMainLoop. * Because the SOUP_MESSAGE_OVERWRITE_CHUNKS flag is set, Soup frees the * SoupBuffer and calls gst_soup_http_src_chunk_free(), which decrements the * refcount (to 1). * gst_soup_http_src_create() returns the GstBuffer. It will be freed by a * downstream element. * If Soup fails to read HTTP data, it does not call * gst_soup_http_src_got_chunk_cb(), but still frees the SoupBuffer and * calls gst_soup_http_src_chunk_free(), which decrements the GstBuffer's * refcount to 0, freeing it. */ static void gst_soup_http_src_chunk_free (gpointer gstbuf) { gst_buffer_unref (GST_BUFFER_CAST (gstbuf)); } static SoupBuffer * gst_soup_http_src_chunk_allocator (SoupMessage * msg, gsize max_len, gpointer user_data) { GstSoupHTTPSrc *src = (GstSoupHTTPSrc *) user_data; GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src); GstBuffer *gstbuf; SoupBuffer *soupbuf; gsize length; GstFlowReturn rc; if (max_len) length = MIN (basesrc->blocksize, max_len); else length = basesrc->blocksize; GST_DEBUG_OBJECT (src, "alloc %" G_GSIZE_FORMAT " bytes <= %" G_GSIZE_FORMAT, length, max_len); rc = gst_pad_alloc_buffer (GST_BASE_SRC_PAD (basesrc), GST_BUFFER_OFFSET_NONE, length, src->src_caps ? src->src_caps : GST_PAD_CAPS (GST_BASE_SRC_PAD (basesrc)), &gstbuf); if (G_UNLIKELY (rc != GST_FLOW_OK)) { /* Failed to allocate buffer. Stall SoupSession and return error code * to create(). */ src->ret = rc; g_main_loop_quit (src->loop); return NULL; } soupbuf = soup_buffer_new_with_owner (GST_BUFFER_DATA (gstbuf), length, gstbuf, gst_soup_http_src_chunk_free); return soupbuf; } static void gst_soup_http_src_got_chunk_cb (SoupMessage * msg, SoupBuffer * chunk, GstSoupHTTPSrc * src) { GstBaseSrc *basesrc; guint64 new_position; if (G_UNLIKELY (msg != src->msg)) { GST_DEBUG_OBJECT (src, "got chunk, but not for current message"); return; } if (G_UNLIKELY (src->session_io_status != GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) { /* Probably a redirect. */ return; } basesrc = GST_BASE_SRC_CAST (src); GST_DEBUG_OBJECT (src, "got chunk of %" G_GSIZE_FORMAT " bytes", chunk->length); /* Extract the GstBuffer from the SoupBuffer and set its fields. */ *src->outbuf = GST_BUFFER_CAST (soup_buffer_get_owner (chunk)); GST_BUFFER_SIZE (*src->outbuf) = chunk->length; GST_BUFFER_OFFSET (*src->outbuf) = basesrc->segment.last_stop; gst_buffer_set_caps (*src->outbuf, (src->src_caps) ? src->src_caps : GST_PAD_CAPS (GST_BASE_SRC_PAD (basesrc))); gst_buffer_ref (*src->outbuf); new_position = src->read_position + chunk->length; if (G_LIKELY (src->request_position == src->read_position)) src->request_position = new_position; src->read_position = new_position; src->ret = GST_FLOW_OK; g_main_loop_quit (src->loop); gst_soup_http_src_session_pause_message (src); } static void gst_soup_http_src_response_cb (SoupSession * session, SoupMessage * msg, GstSoupHTTPSrc * src) { if (G_UNLIKELY (msg != src->msg)) { GST_DEBUG_OBJECT (src, "got response %d: %s, but not for current message", msg->status_code, msg->reason_phrase); return; } if (G_UNLIKELY (src->session_io_status != GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING) && SOUP_STATUS_IS_REDIRECTION (msg->status_code)) { /* Ignore redirections. */ return; } GST_DEBUG_OBJECT (src, "got response %d: %s", msg->status_code, msg->reason_phrase); if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING && src->read_position > 0) { /* The server disconnected while streaming. Reconnect and seeking to the * last location. */ src->retry = TRUE; } else gst_soup_http_src_parse_status (msg, src); /* The session's SoupMessage object expires after this callback returns. */ src->msg = NULL; g_main_loop_quit (src->loop); } #define SOUP_HTTP_SRC_ERROR(src,soup_msg,cat,code,error_message) \ GST_ELEMENT_ERROR ((src), cat, code, ("%s", error_message), \ ("%s (%d), URL: %s", (soup_msg)->reason_phrase, \ (soup_msg)->status_code, (src)->location)); static void gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src) { if (SOUP_STATUS_IS_TRANSPORT_ERROR (msg->status_code)) { switch (msg->status_code) { case SOUP_STATUS_CANT_RESOLVE: case SOUP_STATUS_CANT_RESOLVE_PROXY: SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND, _("Could not resolve server name.")); src->ret = GST_FLOW_ERROR; break; case SOUP_STATUS_CANT_CONNECT: case SOUP_STATUS_CANT_CONNECT_PROXY: SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ, _("Could not establish connection to server.")); src->ret = GST_FLOW_ERROR; break; case SOUP_STATUS_SSL_FAILED: SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ, _("Secure connection setup failed.")); src->ret = GST_FLOW_ERROR; break; case SOUP_STATUS_IO_ERROR: SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ, _("A network error occured, or the server closed the connection " "unexpectedly.")); src->ret = GST_FLOW_ERROR; break; case SOUP_STATUS_MALFORMED: SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ, _("Server sent bad data.")); src->ret = GST_FLOW_ERROR; break; case SOUP_STATUS_CANCELLED: /* No error message when interrupted by program. */ break; } } else if (SOUP_STATUS_IS_CLIENT_ERROR (msg->status_code) || SOUP_STATUS_IS_REDIRECTION (msg->status_code) || SOUP_STATUS_IS_SERVER_ERROR (msg->status_code)) { /* Report HTTP error. */ /* FIXME: reason_phrase is not translated and not suitable for user * error dialog according to libsoup documentation. * FIXME: error code (OPEN_READ vs. READ) should depend on http status? */ GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, ("%s", msg->reason_phrase), ("%s (%d), URL: %s", msg->reason_phrase, msg->status_code, src->location)); src->ret = GST_FLOW_ERROR; } } static gboolean gst_soup_http_src_build_message (GstSoupHTTPSrc * src) { src->msg = soup_message_new (SOUP_METHOD_GET, src->location); if (!src->msg) { GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, ("Error parsing URL."), ("URL: %s", src->location)); return FALSE; } src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE; soup_message_headers_append (src->msg->request_headers, "Connection", "close"); if (src->iradio_mode) { soup_message_headers_append (src->msg->request_headers, "icy-metadata", "1"); } if (src->cookies) { gchar **cookie; for (cookie = src->cookies; *cookie != NULL; cookie++) { soup_message_headers_append (src->msg->request_headers, "Cookie", *cookie); } } src->retry = FALSE; g_signal_connect (src->msg, "got_headers", G_CALLBACK (gst_soup_http_src_got_headers_cb), src); g_signal_connect (src->msg, "got_body", G_CALLBACK (gst_soup_http_src_got_body_cb), src); g_signal_connect (src->msg, "finished", G_CALLBACK (gst_soup_http_src_finished_cb), src); g_signal_connect (src->msg, "got_chunk", G_CALLBACK (gst_soup_http_src_got_chunk_cb), src); soup_message_set_flags (src->msg, SOUP_MESSAGE_OVERWRITE_CHUNKS | (src->automatic_redirect ? 0 : SOUP_MESSAGE_NO_REDIRECT)); soup_message_set_chunk_allocator (src->msg, gst_soup_http_src_chunk_allocator, src, NULL); gst_soup_http_src_add_range_header (src, src->request_position); gst_soup_http_src_add_extra_headers (src); GST_DEBUG_OBJECT (src, "request headers:"); soup_message_headers_foreach (src->msg->request_headers, gst_soup_http_src_headers_foreach, src); return TRUE; } static GstFlowReturn gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf) { GstSoupHTTPSrc *src; src = GST_SOUP_HTTP_SRC (psrc); if (src->msg && (src->request_position != src->read_position)) { if (src->content_size != 0 && src->request_position >= src->content_size) { GST_WARNING_OBJECT (src, "Seeking behind the end of file -- EOS"); return GST_FLOW_UNEXPECTED; } else if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE) { gst_soup_http_src_add_range_header (src, src->request_position); } else { GST_DEBUG_OBJECT (src, "Seek from position %" G_GUINT64_FORMAT " to %" G_GUINT64_FORMAT ": requeueing connection request", src->read_position, src->request_position); gst_soup_http_src_cancel_message (src); } } if (!src->msg) if (!gst_soup_http_src_build_message (src)) return GST_FLOW_ERROR; src->ret = GST_FLOW_CUSTOM_ERROR; src->outbuf = outbuf; do { if (src->interrupted) { GST_DEBUG_OBJECT (src, "interrupted"); break; } if (src->retry) { GST_DEBUG_OBJECT (src, "Reconnecting"); if (!gst_soup_http_src_build_message (src)) return GST_FLOW_ERROR; src->retry = FALSE; continue; } if (!src->msg) { GST_DEBUG_OBJECT (src, "EOS reached"); break; } switch (src->session_io_status) { case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE: GST_DEBUG_OBJECT (src, "Queueing connection request"); gst_soup_http_src_queue_message (src); break; case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_QUEUED: break; case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING: gst_soup_http_src_session_unpause_message (src); break; case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED: /* Impossible. */ break; } if (src->ret == GST_FLOW_CUSTOM_ERROR) g_main_loop_run (src->loop); } while (src->ret == GST_FLOW_CUSTOM_ERROR); if (src->ret == GST_FLOW_CUSTOM_ERROR) src->ret = GST_FLOW_UNEXPECTED; return src->ret; } static gboolean gst_soup_http_src_start (GstBaseSrc * bsrc) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc); GST_DEBUG_OBJECT (src, "start(\"%s\")", src->location); if (!src->location) { GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (_("No URL set.")), ("Missing location property")); return FALSE; } src->context = g_main_context_new (); src->loop = g_main_loop_new (src->context, TRUE); if (!src->loop) { GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL), ("Failed to start GMainLoop")); g_main_context_unref (src->context); return FALSE; } if (src->proxy == NULL) { src->session = soup_session_async_new_with_options (SOUP_SESSION_ASYNC_CONTEXT, src->context, SOUP_SESSION_USER_AGENT, src->user_agent, SOUP_SESSION_TIMEOUT, src->timeout, #ifdef HAVE_LIBSOUP_GNOME SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_PROXY_RESOLVER_GNOME, #endif NULL); } else { src->session = soup_session_async_new_with_options (SOUP_SESSION_ASYNC_CONTEXT, src->context, SOUP_SESSION_PROXY_URI, src->proxy, SOUP_SESSION_TIMEOUT, src->timeout, SOUP_SESSION_USER_AGENT, src->user_agent, NULL); } if (!src->session) { GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL), ("Failed to create async session")); return FALSE; } g_signal_connect (src->session, "authenticate", G_CALLBACK (gst_soup_http_src_authenticate_cb), src); return TRUE; } static gboolean gst_soup_http_src_stop (GstBaseSrc * bsrc) { GstSoupHTTPSrc *src; src = GST_SOUP_HTTP_SRC (bsrc); GST_DEBUG_OBJECT (src, "stop()"); gst_soup_http_src_session_close (src); if (src->loop) { g_main_loop_unref (src->loop); g_main_context_unref (src->context); src->loop = NULL; src->context = NULL; } if (src->extra_headers) { gst_structure_free (src->extra_headers); src->extra_headers = NULL; } gst_soup_http_src_reset (src); return TRUE; } /* Interrupt a blocking request. */ static gboolean gst_soup_http_src_unlock (GstBaseSrc * bsrc) { GstSoupHTTPSrc *src; src = GST_SOUP_HTTP_SRC (bsrc); GST_DEBUG_OBJECT (src, "unlock()"); src->interrupted = TRUE; if (src->loop) g_main_loop_quit (src->loop); return TRUE; } /* Interrupt interrupt. */ static gboolean gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc) { GstSoupHTTPSrc *src; src = GST_SOUP_HTTP_SRC (bsrc); GST_DEBUG_OBJECT (src, "unlock_stop()"); src->interrupted = FALSE; return TRUE; } static gboolean gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size) { GstSoupHTTPSrc *src; src = GST_SOUP_HTTP_SRC (bsrc); if (src->have_size) { GST_DEBUG_OBJECT (src, "get_size() = %" G_GUINT64_FORMAT, src->content_size); *size = src->content_size; return TRUE; } GST_DEBUG_OBJECT (src, "get_size() = FALSE"); return FALSE; } static gboolean gst_soup_http_src_is_seekable (GstBaseSrc * bsrc) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc); return src->seekable; } static gboolean gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc); GST_DEBUG_OBJECT (src, "do_seek(%" G_GUINT64_FORMAT ")", segment->start); if (src->read_position == segment->start && src->request_position == src->read_position) { GST_DEBUG_OBJECT (src, "Seek to current read position and no seek pending"); return TRUE; } if (!src->seekable) { GST_WARNING_OBJECT (src, "Not seekable"); return FALSE; } if (segment->rate < 0.0 || segment->format != GST_FORMAT_BYTES) { GST_WARNING_OBJECT (src, "Invalid seek segment"); return FALSE; } if (src->content_size != 0 && segment->start >= src->content_size) { GST_WARNING_OBJECT (src, "Seeking behind end of file, will go to EOS soon"); } /* Wait for create() to handle the jump in offset. */ src->request_position = segment->start; return TRUE; } static gboolean gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc); gboolean ret; switch (GST_QUERY_TYPE (query)) { case GST_QUERY_URI: gst_query_set_uri (query, src->location); ret = TRUE; break; default: ret = FALSE; break; } if (!ret) ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query); return ret; } static gboolean gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri) { const char *alt_schemes[] = { "icy://", "icyx://" }; guint i; if (src->location) { g_free (src->location); src->location = NULL; } if (uri == NULL) return FALSE; for (i = 0; i < G_N_ELEMENTS (alt_schemes); i++) { if (g_str_has_prefix (uri, alt_schemes[i])) { src->location = g_strdup_printf ("http://%s", uri + strlen (alt_schemes[i])); return TRUE; } } src->location = g_strdup (uri); return TRUE; } static gboolean gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri) { if (src->proxy) { soup_uri_free (src->proxy); src->proxy = NULL; } if (g_str_has_prefix (uri, "http://")) { src->proxy = soup_uri_new (uri); } else { gchar *new_uri = g_strconcat ("http://", uri, NULL); src->proxy = soup_uri_new (new_uri); g_free (new_uri); } return TRUE; } static guint gst_soup_http_src_uri_get_type (void) { return GST_URI_SRC; } static gchar ** gst_soup_http_src_uri_get_protocols (void) { static const gchar *protocols[] = { "http", "https", "icy", "icyx", NULL }; return (gchar **) protocols; } static const gchar * gst_soup_http_src_uri_get_uri (GstURIHandler * handler) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler); return src->location; } static gboolean gst_soup_http_src_uri_set_uri (GstURIHandler * handler, const gchar * uri) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler); return gst_soup_http_src_set_location (src, uri); } static void gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data) { GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface; iface->get_type = gst_soup_http_src_uri_get_type; iface->get_protocols = gst_soup_http_src_uri_get_protocols; iface->get_uri = gst_soup_http_src_uri_get_uri; iface->set_uri = gst_soup_http_src_uri_set_uri; }
knuesel/gst-plugins-good
ext/soup/gstsouphttpsrc.c
C
lgpl-2.1
48,209
/* * Clutter. * * An OpenGL based 'interactive canvas' library. * * Copyright (C) 2010 Intel Corp. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * * Author: Damien Lespiau <[email protected]> */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <linux/input.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <unistd.h> #include <glib.h> #include <gudev/gudev.h> #include "clutter-backend.h" #include "clutter-debug.h" #include "clutter-device-manager.h" #include "clutter-device-manager-private.h" #include "clutter-event-private.h" #include "clutter-input-device-evdev.h" #include "clutter-main.h" #include "clutter-private.h" #include "clutter-stage-manager.h" #include "clutter-xkb-utils.h" #include "clutter-backend-private.h" #include "clutter-evdev.h" #include "clutter-device-manager-evdev.h" #define CLUTTER_DEVICE_MANAGER_EVDEV_GET_PRIVATE(obj) \ (G_TYPE_INSTANCE_GET_PRIVATE ((obj), \ CLUTTER_TYPE_DEVICE_MANAGER_EVDEV, \ ClutterDeviceManagerEvdevPrivate)) G_DEFINE_TYPE (ClutterDeviceManagerEvdev, clutter_device_manager_evdev, CLUTTER_TYPE_DEVICE_MANAGER); struct _ClutterDeviceManagerEvdevPrivate { GUdevClient *udev_client; ClutterStage *stage; gboolean released; GSList *devices; /* list of ClutterInputDeviceEvdevs */ GSList *event_sources; /* list of the event sources */ ClutterInputDevice *core_pointer; ClutterInputDevice *core_keyboard; ClutterStageManager *stage_manager; guint stage_added_handler; guint stage_removed_handler; }; static const gchar *subsystems[] = { "input", NULL }; /* * ClutterEventSource management * * The device manager is responsible for managing the GSource when devices * appear and disappear from the system. * * FIXME: For now, we associate a GSource with every single device. Starting * from glib 2.28 we can use g_source_add_child_source() to have a single * GSource for the device manager, each device becoming a child source. Revisit * this once we depend on glib >= 2.28. */ static const char *option_xkb_layout = "us"; static const char *option_xkb_variant = ""; static const char *option_xkb_options = ""; /* * ClutterEventSource for reading input devices */ typedef struct _ClutterEventSource ClutterEventSource; struct _ClutterEventSource { GSource source; ClutterInputDeviceEvdev *device; /* back pointer to the evdev device */ GPollFD event_poll_fd; /* file descriptor of the /dev node */ struct xkb_state *xkb; /* XKB state object */ gint x, y; /* last x, y position for pointers */ guint32 modifier_state; /* key modifiers */ }; static gboolean clutter_event_prepare (GSource *source, gint *timeout) { gboolean retval; _clutter_threads_acquire_lock (); *timeout = -1; retval = clutter_events_pending (); _clutter_threads_release_lock (); return retval; } static gboolean clutter_event_check (GSource *source) { ClutterEventSource *event_source = (ClutterEventSource *) source; gboolean retval; _clutter_threads_acquire_lock (); retval = ((event_source->event_poll_fd.revents & G_IO_IN) || clutter_events_pending ()); _clutter_threads_release_lock (); return retval; } static void queue_event (ClutterEvent *event) { if (event == NULL) return; _clutter_event_push (event, FALSE); } static void notify_key (ClutterEventSource *source, guint32 time_, guint32 key, guint32 state) { ClutterInputDevice *input_device = (ClutterInputDevice *) source->device; ClutterStage *stage; ClutterEvent *event = NULL; /* We can drop the event on the floor if no stage has been * associated with the device yet. */ stage = _clutter_input_device_get_stage (input_device); if (!stage) return; /* if we have a mapping for that device, use it to generate the event */ if (source->xkb) { event = _clutter_key_event_new_from_evdev (input_device, stage, source->xkb, time_, key, state); xkb_state_update_key (source->xkb, key, state ? XKB_KEY_DOWN : XKB_KEY_UP); } queue_event (event); } static void notify_motion (ClutterEventSource *source, guint32 time_, gint x, gint y) { ClutterInputDevice *input_device = (ClutterInputDevice *) source->device; gfloat stage_width, stage_height, new_x, new_y; ClutterEvent *event; ClutterStage *stage; /* We can drop the event on the floor if no stage has been * associated with the device yet. */ stage = _clutter_input_device_get_stage (input_device); if (!stage) return; stage_width = clutter_actor_get_width (CLUTTER_ACTOR (stage)); stage_height = clutter_actor_get_height (CLUTTER_ACTOR (stage)); event = clutter_event_new (CLUTTER_MOTION); if (x < 0) new_x = 0.f; else if (x >= stage_width) new_x = stage_width - 1; else new_x = x; if (y < 0) new_y = 0.f; else if (y >= stage_height) new_y = stage_height - 1; else new_y = y; source->x = new_x; source->y = new_y; event->motion.time = time_; event->motion.stage = stage; event->motion.device = input_device; event->motion.modifier_state = source->modifier_state; event->motion.x = new_x; event->motion.y = new_y; queue_event (event); } static void notify_button (ClutterEventSource *source, guint32 time_, guint32 button, guint32 state) { ClutterInputDevice *input_device = (ClutterInputDevice *) source->device; ClutterEvent *event; ClutterStage *stage; gint button_nr; static gint maskmap[8] = { CLUTTER_BUTTON1_MASK, CLUTTER_BUTTON3_MASK, CLUTTER_BUTTON2_MASK, CLUTTER_BUTTON4_MASK, CLUTTER_BUTTON5_MASK, 0, 0, 0 }; /* We can drop the event on the floor if no stage has been * associated with the device yet. */ stage = _clutter_input_device_get_stage (input_device); if (!stage) return; /* The evdev button numbers don't map sequentially to clutter button * numbers (the right and middle mouse buttons are in the opposite * order) so we'll map them directly with a switch statement */ switch (button) { case BTN_LEFT: button_nr = CLUTTER_BUTTON_PRIMARY; break; case BTN_RIGHT: button_nr = CLUTTER_BUTTON_SECONDARY; break; case BTN_MIDDLE: button_nr = CLUTTER_BUTTON_MIDDLE; break; default: button_nr = button - BTN_MOUSE + 1; break; } if (G_UNLIKELY (button_nr < 1 || button_nr > 8)) { g_warning ("Unhandled button event 0x%x", button); return; } if (state) event = clutter_event_new (CLUTTER_BUTTON_PRESS); else event = clutter_event_new (CLUTTER_BUTTON_RELEASE); /* Update the modifiers */ if (state) source->modifier_state |= maskmap[button - BTN_LEFT]; else source->modifier_state &= ~maskmap[button - BTN_LEFT]; event->button.time = time_; event->button.stage = CLUTTER_STAGE (stage); event->button.device = (ClutterInputDevice *) source->device; event->button.modifier_state = source->modifier_state; event->button.button = button_nr; event->button.x = source->x; event->button.y = source->y; queue_event (event); } static gboolean clutter_event_dispatch (GSource *g_source, GSourceFunc callback, gpointer user_data) { ClutterEventSource *source = (ClutterEventSource *) g_source; ClutterInputDevice *input_device = (ClutterInputDevice *) source->device; struct input_event ev[8]; ClutterEvent *event; gint len, i, dx = 0, dy = 0; uint32_t _time; ClutterStage *stage; _clutter_threads_acquire_lock (); stage = _clutter_input_device_get_stage (input_device); /* Don't queue more events if we haven't finished handling the previous batch */ if (!clutter_events_pending ()) { len = read (source->event_poll_fd.fd, &ev, sizeof (ev)); if (len < 0 || len % sizeof (ev[0]) != 0) { if (errno != EAGAIN) { ClutterDeviceManager *manager; ClutterInputDevice *device; const gchar *device_path; device = CLUTTER_INPUT_DEVICE (source->device); if (CLUTTER_HAS_DEBUG (EVENT)) { device_path = _clutter_input_device_evdev_get_device_path (source->device); CLUTTER_NOTE (EVENT, "Could not read device (%s), removing.", device_path); } /* remove the faulty device */ manager = clutter_device_manager_get_default (); _clutter_device_manager_remove_device (manager, device); } goto out; } /* Drop events if we don't have any stage to forward them to */ if (!stage) goto out; for (i = 0; i < len / sizeof (ev[0]); i++) { struct input_event *e = &ev[i]; _time = e->time.tv_sec * 1000 + e->time.tv_usec / 1000; event = NULL; switch (e->type) { case EV_KEY: /* don't repeat mouse buttons */ if (e->code >= BTN_MOUSE && e->code < KEY_OK) if (e->value == 2) continue; switch (e->code) { case BTN_TOUCH: case BTN_TOOL_PEN: case BTN_TOOL_RUBBER: case BTN_TOOL_BRUSH: case BTN_TOOL_PENCIL: case BTN_TOOL_AIRBRUSH: case BTN_TOOL_FINGER: case BTN_TOOL_MOUSE: case BTN_TOOL_LENS: break; case BTN_LEFT: case BTN_RIGHT: case BTN_MIDDLE: case BTN_SIDE: case BTN_EXTRA: case BTN_FORWARD: case BTN_BACK: case BTN_TASK: notify_button(source, _time, e->code, e->value); break; default: notify_key (source, _time, e->code, e->value); break; } break; case EV_SYN: /* Nothing to do here? */ break; case EV_MSC: /* Nothing to do here? */ break; case EV_REL: /* compress the EV_REL events in dx/dy */ switch (e->code) { case REL_X: dx += e->value; break; case REL_Y: dy += e->value; break; } break; case EV_ABS: default: g_warning ("Unhandled event of type %d", e->type); break; } queue_event (event); } if (dx != 0 || dy != 0) notify_motion (source, _time, source->x + dx, source->y + dy); } /* Pop an event off the queue if any */ event = clutter_event_get (); if (event) { /* forward the event into clutter for emission etc. */ clutter_do_event (event); clutter_event_free (event); } out: _clutter_threads_release_lock (); return TRUE; } static GSourceFuncs event_funcs = { clutter_event_prepare, clutter_event_check, clutter_event_dispatch, NULL }; static GSource * clutter_event_source_new (ClutterInputDeviceEvdev *input_device) { GSource *source = g_source_new (&event_funcs, sizeof (ClutterEventSource)); ClutterEventSource *event_source = (ClutterEventSource *) source; ClutterInputDeviceType type; const gchar *node_path; gint fd; /* grab the udev input device node and open it */ node_path = _clutter_input_device_evdev_get_device_path (input_device); CLUTTER_NOTE (EVENT, "Creating GSource for device %s", node_path); fd = open (node_path, O_RDONLY | O_NONBLOCK); if (fd < 0) { g_warning ("Could not open device %s: %s", node_path, strerror (errno)); return NULL; } /* setup the source */ event_source->device = input_device; event_source->event_poll_fd.fd = fd; event_source->event_poll_fd.events = G_IO_IN; type = clutter_input_device_get_device_type (CLUTTER_INPUT_DEVICE (input_device)); if (type == CLUTTER_KEYBOARD_DEVICE) { /* create the xkb description */ event_source->xkb = _clutter_xkb_state_new (NULL, option_xkb_layout, option_xkb_variant, option_xkb_options); if (G_UNLIKELY (event_source->xkb == NULL)) { g_warning ("Could not compile keymap %s:%s:%s", option_xkb_layout, option_xkb_variant, option_xkb_options); close (fd); g_source_unref (source); return NULL; } } else if (type == CLUTTER_POINTER_DEVICE) { event_source->x = 0; event_source->y = 0; } /* and finally configure and attach the GSource */ g_source_set_priority (source, CLUTTER_PRIORITY_EVENTS); g_source_add_poll (source, &event_source->event_poll_fd); g_source_set_can_recurse (source, TRUE); g_source_attach (source, NULL); return source; } static void clutter_event_source_free (ClutterEventSource *source) { GSource *g_source = (GSource *) source; const gchar *node_path; node_path = _clutter_input_device_evdev_get_device_path (source->device); CLUTTER_NOTE (EVENT, "Removing GSource for device %s", node_path); /* ignore the return value of close, it's not like we can do something * about it */ close (source->event_poll_fd.fd); g_source_destroy (g_source); g_source_unref (g_source); } static ClutterEventSource * find_source_by_device (ClutterDeviceManagerEvdev *manager, ClutterInputDevice *device) { ClutterDeviceManagerEvdevPrivate *priv = manager->priv; GSList *l; for (l = priv->event_sources; l; l = g_slist_next (l)) { ClutterEventSource *source = l->data; if (source->device == (ClutterInputDeviceEvdev *) device) return source; } return NULL; } static gboolean is_evdev (const gchar *sysfs_path) { GRegex *regex; gboolean match; regex = g_regex_new ("/input[0-9]+/event[0-9]+$", 0, 0, NULL); match = g_regex_match (regex, sysfs_path, 0, NULL); g_regex_unref (regex); return match; } static void evdev_add_device (ClutterDeviceManagerEvdev *manager_evdev, GUdevDevice *udev_device) { ClutterDeviceManager *manager = (ClutterDeviceManager *) manager_evdev; ClutterInputDeviceType type = CLUTTER_EXTENSION_DEVICE; ClutterInputDevice *device; const gchar *device_file, *sysfs_path, *device_name; device_file = g_udev_device_get_device_file (udev_device); sysfs_path = g_udev_device_get_sysfs_path (udev_device); device_name = g_udev_device_get_name (udev_device); if (device_file == NULL || sysfs_path == NULL) return; if (g_udev_device_get_property (udev_device, "ID_INPUT") == NULL) return; /* Make sure to only add evdev devices, ie the device with a sysfs path that * finishes by input%d/event%d (We don't rely on the node name as this * policy is enforced by udev rules Vs API/ABI guarantees of sysfs) */ if (!is_evdev (sysfs_path)) return; /* Clutter assumes that device types are exclusive in the * ClutterInputDevice API */ if (g_udev_device_has_property (udev_device, "ID_INPUT_KEYBOARD")) type = CLUTTER_KEYBOARD_DEVICE; else if (g_udev_device_has_property (udev_device, "ID_INPUT_MOUSE")) type = CLUTTER_POINTER_DEVICE; else if (g_udev_device_has_property (udev_device, "ID_INPUT_JOYSTICK")) type = CLUTTER_JOYSTICK_DEVICE; else if (g_udev_device_has_property (udev_device, "ID_INPUT_TABLET")) type = CLUTTER_TABLET_DEVICE; else if (g_udev_device_has_property (udev_device, "ID_INPUT_TOUCHPAD")) type = CLUTTER_TOUCHPAD_DEVICE; else if (g_udev_device_has_property (udev_device, "ID_INPUT_TOUCHSCREEN")) type = CLUTTER_TOUCHSCREEN_DEVICE; device = g_object_new (CLUTTER_TYPE_INPUT_DEVICE_EVDEV, "id", 0, "name", device_name, "device-type", type, "sysfs-path", sysfs_path, "device-path", device_file, "enabled", TRUE, NULL); _clutter_input_device_set_stage (device, manager_evdev->priv->stage); _clutter_device_manager_add_device (manager, device); CLUTTER_NOTE (EVENT, "Added device %s, type %d, sysfs %s", device_file, type, sysfs_path); } static ClutterInputDeviceEvdev * find_device_by_udev_device (ClutterDeviceManagerEvdev *manager_evdev, GUdevDevice *udev_device) { ClutterDeviceManagerEvdevPrivate *priv = manager_evdev->priv; GSList *l; const gchar *sysfs_path; sysfs_path = g_udev_device_get_sysfs_path (udev_device); if (sysfs_path == NULL) { g_message ("device file is NULL"); return NULL; } for (l = priv->devices; l; l = g_slist_next (l)) { ClutterInputDeviceEvdev *device = l->data; if (strcmp (sysfs_path, _clutter_input_device_evdev_get_sysfs_path (device)) == 0) { return device; } } return NULL; } static void evdev_remove_device (ClutterDeviceManagerEvdev *manager_evdev, GUdevDevice *device) { ClutterDeviceManager *manager = CLUTTER_DEVICE_MANAGER (manager_evdev); ClutterInputDeviceEvdev *device_evdev; ClutterInputDevice *input_device; device_evdev = find_device_by_udev_device (manager_evdev, device); if (device_evdev == NULL) return; input_device = CLUTTER_INPUT_DEVICE (device_evdev); _clutter_device_manager_remove_device (manager, input_device); } static void on_uevent (GUdevClient *client, gchar *action, GUdevDevice *device, gpointer data) { ClutterDeviceManagerEvdev *manager = CLUTTER_DEVICE_MANAGER_EVDEV (data); ClutterDeviceManagerEvdevPrivate *priv = manager->priv; if (priv->released) return; if (g_strcmp0 (action, "add") == 0) evdev_add_device (manager, device); else if (g_strcmp0 (action, "remove") == 0) evdev_remove_device (manager, device); } /* * ClutterDeviceManager implementation */ static void clutter_device_manager_evdev_add_device (ClutterDeviceManager *manager, ClutterInputDevice *device) { ClutterDeviceManagerEvdev *manager_evdev; ClutterDeviceManagerEvdevPrivate *priv; ClutterInputDeviceType device_type; ClutterInputDeviceEvdev *device_evdev; gboolean is_pointer, is_keyboard; GSource *source; manager_evdev = CLUTTER_DEVICE_MANAGER_EVDEV (manager); priv = manager_evdev->priv; device_evdev = CLUTTER_INPUT_DEVICE_EVDEV (device); device_type = clutter_input_device_get_device_type (device); is_pointer = device_type == CLUTTER_POINTER_DEVICE; is_keyboard = device_type == CLUTTER_KEYBOARD_DEVICE; priv->devices = g_slist_prepend (priv->devices, device); if (is_pointer && priv->core_pointer == NULL) priv->core_pointer = device; if (is_keyboard && priv->core_keyboard == NULL) priv->core_keyboard = device; /* Install the GSource for this device */ source = clutter_event_source_new (device_evdev); if (G_LIKELY (source)) priv->event_sources = g_slist_prepend (priv->event_sources, source); } static void clutter_device_manager_evdev_remove_device (ClutterDeviceManager *manager, ClutterInputDevice *device) { ClutterDeviceManagerEvdev *manager_evdev; ClutterDeviceManagerEvdevPrivate *priv; ClutterEventSource *source; manager_evdev = CLUTTER_DEVICE_MANAGER_EVDEV (manager); priv = manager_evdev->priv; /* Remove the device */ priv->devices = g_slist_remove (priv->devices, device); /* Remove the source */ source = find_source_by_device (manager_evdev, device); if (G_UNLIKELY (source == NULL)) { g_warning ("Trying to remove a device without a source installed ?!"); return; } clutter_event_source_free (source); priv->event_sources = g_slist_remove (priv->event_sources, source); } static const GSList * clutter_device_manager_evdev_get_devices (ClutterDeviceManager *manager) { return CLUTTER_DEVICE_MANAGER_EVDEV (manager)->priv->devices; } static ClutterInputDevice * clutter_device_manager_evdev_get_core_device (ClutterDeviceManager *manager, ClutterInputDeviceType type) { ClutterDeviceManagerEvdev *manager_evdev; ClutterDeviceManagerEvdevPrivate *priv; manager_evdev = CLUTTER_DEVICE_MANAGER_EVDEV (manager); priv = manager_evdev->priv; switch (type) { case CLUTTER_POINTER_DEVICE: return priv->core_pointer; case CLUTTER_KEYBOARD_DEVICE: return priv->core_keyboard; case CLUTTER_EXTENSION_DEVICE: default: return NULL; } return NULL; } static ClutterInputDevice * clutter_device_manager_evdev_get_device (ClutterDeviceManager *manager, gint id) { ClutterDeviceManagerEvdev *manager_evdev; ClutterDeviceManagerEvdevPrivate *priv; GSList *l; manager_evdev = CLUTTER_DEVICE_MANAGER_EVDEV (manager); priv = manager_evdev->priv; for (l = priv->devices; l; l = l->next) { ClutterInputDevice *device = l->data; if (clutter_input_device_get_device_id (device) == id) return device; } return NULL; } static void clutter_device_manager_evdev_probe_devices (ClutterDeviceManagerEvdev *self) { ClutterDeviceManagerEvdevPrivate *priv = self->priv; GList *devices, *l; devices = g_udev_client_query_by_subsystem (priv->udev_client, subsystems[0]); for (l = devices; l; l = g_list_next (l)) { GUdevDevice *device = l->data; evdev_add_device (self, device); g_object_unref (device); } g_list_free (devices); } /* * GObject implementation */ static void clutter_device_manager_evdev_constructed (GObject *gobject) { ClutterDeviceManagerEvdev *manager_evdev; ClutterDeviceManagerEvdevPrivate *priv; manager_evdev = CLUTTER_DEVICE_MANAGER_EVDEV (gobject); priv = manager_evdev->priv; priv->udev_client = g_udev_client_new (subsystems); clutter_device_manager_evdev_probe_devices (manager_evdev); /* subcribe for events on input devices */ g_signal_connect (priv->udev_client, "uevent", G_CALLBACK (on_uevent), manager_evdev); } static void clutter_device_manager_evdev_dispose (GObject *object) { ClutterDeviceManagerEvdev *manager_evdev; ClutterDeviceManagerEvdevPrivate *priv; manager_evdev = CLUTTER_DEVICE_MANAGER_EVDEV (object); priv = manager_evdev->priv; if (priv->stage_added_handler) { g_signal_handler_disconnect (priv->stage_manager, priv->stage_added_handler); priv->stage_added_handler = 0; } if (priv->stage_removed_handler) { g_signal_handler_disconnect (priv->stage_manager, priv->stage_removed_handler); priv->stage_removed_handler = 0; } if (priv->stage_manager) { g_object_unref (priv->stage_manager); priv->stage_manager = NULL; } G_OBJECT_CLASS (clutter_device_manager_evdev_parent_class)->dispose (object); } static void clutter_device_manager_evdev_finalize (GObject *object) { ClutterDeviceManagerEvdev *manager_evdev; ClutterDeviceManagerEvdevPrivate *priv; GSList *l; manager_evdev = CLUTTER_DEVICE_MANAGER_EVDEV (object); priv = manager_evdev->priv; g_object_unref (priv->udev_client); for (l = priv->devices; l; l = g_slist_next (l)) { ClutterInputDevice *device = l->data; g_object_unref (device); } g_slist_free (priv->devices); for (l = priv->event_sources; l; l = g_slist_next (l)) { ClutterEventSource *source = l->data; clutter_event_source_free (source); } g_slist_free (priv->event_sources); G_OBJECT_CLASS (clutter_device_manager_evdev_parent_class)->finalize (object); } static void clutter_device_manager_evdev_class_init (ClutterDeviceManagerEvdevClass *klass) { ClutterDeviceManagerClass *manager_class; GObjectClass *gobject_class = (GObjectClass *) klass; g_type_class_add_private (klass, sizeof (ClutterDeviceManagerEvdevPrivate)); gobject_class->constructed = clutter_device_manager_evdev_constructed; gobject_class->finalize = clutter_device_manager_evdev_finalize; gobject_class->dispose = clutter_device_manager_evdev_dispose; manager_class = CLUTTER_DEVICE_MANAGER_CLASS (klass); manager_class->add_device = clutter_device_manager_evdev_add_device; manager_class->remove_device = clutter_device_manager_evdev_remove_device; manager_class->get_devices = clutter_device_manager_evdev_get_devices; manager_class->get_core_device = clutter_device_manager_evdev_get_core_device; manager_class->get_device = clutter_device_manager_evdev_get_device; } static void clutter_device_manager_evdev_stage_added_cb (ClutterStageManager *manager, ClutterStage *stage, ClutterDeviceManagerEvdev *self) { ClutterDeviceManagerEvdevPrivate *priv = self->priv; GSList *l; /* NB: Currently we can only associate a single stage with all evdev * devices. * * We save a pointer to the stage so if we release/reclaim input * devices due to switching virtual terminals then we know what * stage to re associate the devices with. */ priv->stage = stage; /* Set the stage of any devices that don't already have a stage */ for (l = priv->devices; l; l = l->next) { ClutterInputDevice *device = l->data; if (_clutter_input_device_get_stage (device) == NULL) _clutter_input_device_set_stage (device, stage); } /* We only want to do this once so we can catch the default stage. If the application has multiple stages then it will need to manage the stage of the input devices itself */ g_signal_handler_disconnect (priv->stage_manager, priv->stage_added_handler); priv->stage_added_handler = 0; } static void clutter_device_manager_evdev_stage_removed_cb (ClutterStageManager *manager, ClutterStage *stage, ClutterDeviceManagerEvdev *self) { ClutterDeviceManagerEvdevPrivate *priv = self->priv; GSList *l; /* Remove the stage of any input devices that were pointing to this stage so we don't send events to invalid stages */ for (l = priv->devices; l; l = l->next) { ClutterInputDevice *device = l->data; if (_clutter_input_device_get_stage (device) == stage) _clutter_input_device_set_stage (device, NULL); } } static void clutter_device_manager_evdev_init (ClutterDeviceManagerEvdev *self) { ClutterDeviceManagerEvdevPrivate *priv; priv = self->priv = CLUTTER_DEVICE_MANAGER_EVDEV_GET_PRIVATE (self); priv->stage_manager = clutter_stage_manager_get_default (); g_object_ref (priv->stage_manager); /* evdev doesn't have any way to link an event to a particular stage so we'll have to leave it up to applications to set the corresponding stage for an input device. However to make it easier for applications that are only using one fullscreen stage (which is probably the most frequent use-case for the evdev backend) we'll associate any input devices that don't have a stage with the first stage created. */ priv->stage_added_handler = g_signal_connect (priv->stage_manager, "stage-added", G_CALLBACK (clutter_device_manager_evdev_stage_added_cb), self); priv->stage_removed_handler = g_signal_connect (priv->stage_manager, "stage-removed", G_CALLBACK (clutter_device_manager_evdev_stage_removed_cb), self); } void _clutter_events_evdev_init (ClutterBackend *backend) { CLUTTER_NOTE (EVENT, "Initializing evdev backend"); backend->device_manager = g_object_new (CLUTTER_TYPE_DEVICE_MANAGER_EVDEV, "backend", backend, NULL); } void _clutter_events_evdev_uninit (ClutterBackend *backend) { CLUTTER_NOTE (EVENT, "Uninitializing evdev backend"); } /** * clutter_evdev_release_devices: * * Releases all the evdev devices that Clutter is currently managing. This api * is typically used when switching away from the Clutter application when * switching tty. The devices can be reclaimed later with a call to * clutter_evdev_reclaim_devices(). * * This function should only be called after clutter has been initialized. * * * Stability: unstable */ void clutter_evdev_release_devices (void) { ClutterDeviceManager *manager = clutter_device_manager_get_default (); ClutterDeviceManagerEvdev *evdev_manager; ClutterDeviceManagerEvdevPrivate *priv; GSList *l, *next; if (!manager) { g_warning ("clutter_evdev_release_devices shouldn't be called " "before clutter_init()"); return; } g_return_if_fail (CLUTTER_IS_DEVICE_MANAGER_EVDEV (manager)); evdev_manager = CLUTTER_DEVICE_MANAGER_EVDEV (manager); priv = evdev_manager->priv; if (priv->released) { g_warning ("clutter_evdev_release_devices() shouldn't be called " "multiple times without a corresponding call to " "clutter_evdev_reclaim_devices() first"); return; } for (l = priv->devices; l; l = next) { ClutterInputDevice *device = l->data; /* Be careful about the list we're iterating being modified... */ next = l->next; _clutter_device_manager_remove_device (manager, device); } priv->released = TRUE; } /** * clutter_evdev_reclaim_devices: * * This causes Clutter to re-probe for evdev devices. This is must only be * called after a corresponding call to clutter_evdev_release_devices() * was previously used to release all evdev devices. This API is typically * used when a clutter application using evdev has regained focus due to * switching ttys. * * This function should only be called after clutter has been initialized. * * * Stability: unstable */ void clutter_evdev_reclaim_devices (void) { ClutterDeviceManager *manager = clutter_device_manager_get_default (); ClutterDeviceManagerEvdev *evdev_manager; ClutterDeviceManagerEvdevPrivate *priv; if (!manager) { g_warning ("clutter_evdev_reclaim_devices shouldn't be called " "before clutter_init()"); return; } g_return_if_fail (CLUTTER_IS_DEVICE_MANAGER_EVDEV (manager)); evdev_manager = CLUTTER_DEVICE_MANAGER_EVDEV (manager); priv = evdev_manager->priv; if (!priv->released) { g_warning ("Spurious call to clutter_evdev_reclaim_devices() without " "previous call to clutter_evdev_release_devices"); return; } priv->released = FALSE; clutter_device_manager_evdev_probe_devices (evdev_manager); }
heysion/clutter-clone
clutter/evdev/clutter-device-manager-evdev.c
C
lgpl-2.1
32,748
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtDeclarative module 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$ ** ****************************************************************************/ #ifndef QTCPSERVERCONNECTION_H #define QTCPSERVERCONNECTION_H #include <QtDeclarative/private/qdeclarativedebugserverconnection_p.h> QT_BEGIN_NAMESPACE class QDeclarativeDebugServer; class QTcpServerConnectionPrivate; class QTcpServerConnection : public QObject, public QDeclarativeDebugServerConnection { Q_OBJECT Q_DECLARE_PRIVATE(QTcpServerConnection) Q_DISABLE_COPY(QTcpServerConnection) Q_INTERFACES(QDeclarativeDebugServerConnection) public: QTcpServerConnection(); ~QTcpServerConnection(); void setServer(QDeclarativeDebugServer *server); void setPort(int port, bool bock); bool isConnected() const; void send(const QByteArray &message); void disconnect(); bool waitForMessage(); void listen(); void waitForConnection(); private Q_SLOTS: void readyRead(); void newConnection(); private: QTcpServerConnectionPrivate *d_ptr; }; QT_END_NAMESPACE #endif // QTCPSERVERCONNECTION_H
sicily/qt4.8.4
src/plugins/qmltooling/qmldbg_tcp/qtcpserverconnection.h
C
lgpl-2.1
2,939
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the test suite 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 [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #ifdef QTEST_XMLPATTERNS #include <QtCore/QTextCodec> #include <QtXmlPatterns/QXmlSerializer> #include <QtXmlPatterns/QXmlQuery> #include "../qxmlquery/MessageSilencer.h" /*! \class tst_QXmlSerializer \internal \since 4.4 \brief Tests QSourceLocation */ class tst_QXmlSerializer : public QObject { Q_OBJECT private Q_SLOTS: void constructorTriggerWarnings() const; void objectSize() const; void constCorrectness() const; void setCodec() const; void codec() const; void outputDevice() const; void serializationError() const; void serializationError_data() const; void cleanUpTestCase() const; }; void tst_QXmlSerializer::constructorTriggerWarnings() const { QXmlQuery query; QTest::ignoreMessage(QtWarningMsg, "outputDevice cannot be null."); QXmlSerializer(query, 0); QTest::ignoreMessage(QtWarningMsg, "outputDevice must be opened in write mode."); QBuffer buffer; QXmlSerializer(query, &buffer); } void tst_QXmlSerializer::constCorrectness() const { QXmlQuery query; QFile file(QLatin1String("dummy.xml")); file.open(QIODevice::WriteOnly); const QXmlSerializer serializer(query, &file); /* These functions must be const. */ serializer.outputDevice(); serializer.codec(); } void tst_QXmlSerializer::objectSize() const { QCOMPARE(sizeof(QXmlSerializer), sizeof(QAbstractXmlReceiver)); } void tst_QXmlSerializer::setCodec() const { QFile file(QLatin1String("dummy.xml")); file.open(QIODevice::WriteOnly); /* Ensure we can take a const pointer. */ { QXmlQuery query; QXmlSerializer serializer(query, &file); serializer.setCodec(const_cast<const QTextCodec *>(QTextCodec::codecForName("UTF-8"))); } /* Check that setting the codec has effect. */ { QXmlQuery query; QXmlSerializer serializer(query, &file); serializer.setCodec(const_cast<const QTextCodec *>(QTextCodec::codecForName("UTF-16"))); QCOMPARE(serializer.codec()->name(), QTextCodec::codecForName("UTF-16")->name()); /* Set it back. */ serializer.setCodec(const_cast<const QTextCodec *>(QTextCodec::codecForName("UTF-8"))); QCOMPARE(serializer.codec()->name(), QTextCodec::codecForName("UTF-8")->name()); } } void tst_QXmlSerializer::codec() const { QFile file(QLatin1String("dummy.xml")); file.open(QIODevice::WriteOnly); /* Check default value. */ { const QXmlQuery query; const QXmlSerializer serializer(query, &file); QCOMPARE(serializer.codec()->name(), QTextCodec::codecForName("UTF-8")->name()); } } void tst_QXmlSerializer::outputDevice() const { QFile file(QLatin1String("dummy.xml")); file.open(QIODevice::WriteOnly); /* Check default value. */ { const QXmlQuery query; const QXmlSerializer serializer(query, &file); QCOMPARE(serializer.outputDevice(), static_cast< QIODevice *>(&file)); } } void tst_QXmlSerializer::serializationError() const { QFETCH(QString, queryString); QXmlQuery query; MessageSilencer silencer; query.setMessageHandler(&silencer); query.setQuery(queryString); QByteArray output; QBuffer buffer(&output); QVERIFY(buffer.open(QIODevice::WriteOnly)); QVERIFY(query.isValid()); QXmlSerializer serializer(query, &buffer); QEXPECT_FAIL("Two top elements", "Bug, this is not checked for", Continue); QVERIFY(!query.evaluateTo(&serializer)); } void tst_QXmlSerializer::serializationError_data() const { QTest::addColumn<QString>("queryString"); QTest::newRow("Two top elements") << QString::fromLatin1("<e/>, <e/>"); QTest::newRow("An attribute") << QString::fromLatin1("attribute name {'foo'}"); } void tst_QXmlSerializer::cleanUpTestCase() const { QVERIFY(QFile::remove(QLatin1String("dummy.xml"))); } QTEST_MAIN(tst_QXmlSerializer) #include "tst_qxmlserializer.moc" #else QTEST_NOOP_MAIN #endif // vim: et:ts=4:sw=4:sts=4
igor-sfdc/qt-wk
tests/auto/qxmlserializer/tst_qxmlserializer.cpp
C++
lgpl-2.1
5,537
/* Copyright (C) 2017 Fredrik Johansson This file is part of Arb. Arb is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <http://www.gnu.org/licenses/>. */ #include "arb_fmpz_poly.h" void arb_fmpz_poly_deflate(fmpz_poly_t result, const fmpz_poly_t input, ulong deflation) { slong res_length, i; if (deflation == 0) { flint_printf("Exception (fmpz_poly_deflate). Division by zero.\n"); flint_abort(); } if (input->length <= 1 || deflation == 1) { fmpz_poly_set(result, input); return; } res_length = (input->length - 1) / deflation + 1; fmpz_poly_fit_length(result, res_length); for (i = 0; i < res_length; i++) fmpz_set(result->coeffs + i, input->coeffs + i*deflation); result->length = res_length; }
fredrik-johansson/arb
arb_fmpz_poly/deflate.c
C
lgpl-2.1
1,015
EST_File Track DataType ascii NumFrames 140 NumChannels 0 NumAuxChannels 0 EqualSpace 0 BreaksPresent true EST_Header_End 0.010222 1 0.020444 1 0.030666 1 0.040888 1 0.051110 1 0.061332 1 0.071554 1 0.081776 1 0.091998 1 0.102220 1 0.112442 1 0.122664 1 0.132886 1 0.143108 1 0.153330 1 0.163552 1 0.173774 1 0.183996 1 0.194218 1 0.204440 1 0.214662 1 0.224884 1 0.235106 1 0.245328 1 0.255550 1 0.265772 1 0.275994 1 0.286216 1 0.296438 1 0.303750 1 0.315500 1 0.327250 1 0.338875 1 0.350563 1 0.362312 1 0.374000 1 0.385625 1 0.397250 1 0.408938 1 0.420500 1 0.432063 1 0.443437 1 0.454812 1 0.466062 1 0.477437 1 0.488750 1 0.500000 1 0.511187 1 0.522500 1 0.533813 1 0.545187 1 0.556562 1 0.567937 1 0.579375 1 0.590750 1 0.602375 1 0.614062 1 0.625875 1 0.637563 1 0.649250 1 0.661000 1 0.672562 1 0.684187 1 0.695813 1 0.707500 1 0.719125 1 0.730812 1 0.742437 1 0.754000 1 0.765625 1 0.777188 1 0.788750 1 0.800375 1 0.811938 1 0.823563 1 0.835250 1 0.846875 1 0.858625 1 0.870375 1 0.882187 1 0.893938 1 0.905563 1 0.917125 1 0.928688 1 0.939687 1 0.950688 1 0.962188 1 0.973500 1 0.984875 1 0.996188 1 1.007563 1 1.018813 1 1.030125 1 1.041375 1 1.052750 1 1.064188 1 1.075625 1 1.087000 1 1.098438 1 1.110000 1 1.121375 1 1.133062 1 1.144875 1 1.156687 1 1.168437 1 1.180250 1 1.192062 1 1.204000 1 1.216000 1 1.227687 1 1.239750 1 1.251000 1 1.263250 1 1.273468 1 1.283685 1 1.293903 1 1.304120 1 1.314338 1 1.324556 1 1.334773 1 1.344991 1 1.355208 1 1.365426 1 1.375643 1 1.385861 1 1.396079 1 1.406296 1 1.416514 1 1.426731 1 1.436949 1 1.447167 1 1.457384 1 1.467602 1 1.477819 1 1.488037 1 1.498255 1 1.508472 1 1.518690 1 1.528907 1 1.539125 1
tjyrinki/suopuhe
hy_fi_mv_diphone/pm/0282.pm
Perl
lgpl-2.1
1,942
/**************************************************************************** ** ** 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. ** ****************************************************************************/ #ifndef QMLPROFILERTREEVIEW #define QMLPROFILERTREEVIEW #include <QTreeView> namespace QmlProfiler { namespace Internal { class QmlProfilerTreeView : public QTreeView { Q_OBJECT protected: QmlProfilerTreeView(QWidget *parent = 0); enum Fields { Name, Callee, CalleeDescription, Caller, CallerDescription, CallCount, Details, Location, MaxTime, TimePerCall, SelfTime, SelfTimeInPercent, MinTime, TimeInPercent, TotalTime, Type, MedianTime, MaxFields }; QString displayHeader(Fields header) const; }; } // namespace Internal } // namespace QmlProfiler #endif // QMLPROFILERTREEVIEW
omniacreator/qtcreator
src/plugins/qmlprofiler/qmlprofilertreeview.h
C
lgpl-2.1
2,206
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // 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 Google Inc. 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. // Author: [email protected] (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. // // Edited by Simon Newton for OLA #include <google/protobuf/io/printer.h> #include <map> #include <string> #include "protoc/GeneratorHelpers.h" #include "protoc/ServiceGenerator.h" #include "protoc/StrUtil.h" namespace ola { using google::protobuf::ServiceDescriptor; using google::protobuf::MethodDescriptor; using google::protobuf::io::Printer; using std::map; using std::string; ServiceGenerator::ServiceGenerator(const ServiceDescriptor* descriptor, const Options& options) : descriptor_(descriptor) { vars_["classname"] = descriptor_->name(); vars_["full_name"] = descriptor_->full_name(); if (options.dllexport_decl.empty()) { vars_["dllexport"] = ""; } else { vars_["dllexport"] = options.dllexport_decl + " "; } } ServiceGenerator::~ServiceGenerator() {} void ServiceGenerator::GenerateDeclarations(Printer* printer) { // Forward-declare the stub type. printer->Print(vars_, "class $classname$_Stub;\n" "\n"); GenerateInterface(printer); GenerateStubDefinition(printer); } void ServiceGenerator::GenerateInterface(Printer* printer) { printer->Print(vars_, "class $dllexport$$classname$ : public ola::rpc::RpcService {\n" " protected:\n" " // This class should be treated as an abstract interface.\n" " inline $classname$() {};\n" " public:\n" " virtual ~$classname$();\n"); printer->Indent(); printer->Print(vars_, "\n" "static const ::google::protobuf::ServiceDescriptor* descriptor();\n" "\n"); GenerateMethodSignatures(VIRTUAL, printer); printer->Print( "\n" "// implements Service ----------------------------------------------\n" "\n" "const ::google::protobuf::ServiceDescriptor* GetDescriptor();\n" "void CallMethod(const ::google::protobuf::MethodDescriptor* method,\n" " ola::rpc::RpcController* controller,\n" " const ::google::protobuf::Message* request,\n" " ::google::protobuf::Message* response,\n" " ola::rpc::RpcService::CompletionCallback* done);\n" "const ::google::protobuf::Message& GetRequestPrototype(\n" " const ::google::protobuf::MethodDescriptor* method) const;\n" "const ::google::protobuf::Message& GetResponsePrototype(\n" " const ::google::protobuf::MethodDescriptor* method) const;\n"); printer->Outdent(); printer->Print(vars_, "\n" " private:\n" " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$);\n" "};\n" "\n"); } void ServiceGenerator::GenerateStubDefinition(Printer* printer) { printer->Print(vars_, "class $dllexport$$classname$_Stub : public $classname$ {\n" " public:\n"); printer->Indent(); printer->Print(vars_, "$classname$_Stub(ola::rpc::RpcChannel* channel);\n" "$classname$_Stub(ola::rpc::RpcChannel* channel,\n" " ::google::protobuf::Service::ChannelOwnership ownership" ");\n" "~$classname$_Stub();\n" "\n" "inline ola::rpc::RpcChannel* channel() { return channel_; }\n" "\n" "// implements $classname$ ------------------------------------------\n" "\n"); GenerateMethodSignatures(NON_VIRTUAL, printer); printer->Outdent(); printer->Print(vars_, " private:\n" " ola::rpc::RpcChannel* channel_;\n" " bool owns_channel_;\n" " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$_Stub);\n" "};\n" "\n"); } void ServiceGenerator::GenerateMethodSignatures( VirtualOrNon virtual_or_non, Printer* printer) { for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["name"] = method->name(); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); sub_vars["virtual"] = virtual_or_non == VIRTUAL ? "virtual " : ""; printer->Print(sub_vars, "$virtual$void $name$(ola::rpc::RpcController* controller,\n" " const $input_type$* request,\n" " $output_type$* response,\n" " ola::rpc::RpcService::CompletionCallback* done" ");\n"); } } // =================================================================== void ServiceGenerator::GenerateDescriptorInitializer( Printer* printer, int index) { map<string, string> vars; vars["classname"] = descriptor_->name(); vars["index"] = SimpleItoa(index); printer->Print(vars, "$classname$_descriptor_ = file->service($index$);\n"); } // =================================================================== void ServiceGenerator::GenerateImplementation(Printer* printer) { printer->Print(vars_, "$classname$::~$classname$() {}\n" "\n" "const ::google::protobuf::ServiceDescriptor* $classname$::descriptor() {\n" " protobuf_AssignDescriptorsOnce();\n" " return $classname$_descriptor_;\n" "}\n" "\n" "const ::google::protobuf::ServiceDescriptor* $classname$::GetDescriptor()" " {\n" " protobuf_AssignDescriptorsOnce();\n" " return $classname$_descriptor_;\n" "}\n" "\n"); // Generate methods of the interface. GenerateNotImplementedMethods(printer); GenerateCallMethod(printer); GenerateGetPrototype(REQUEST, printer); GenerateGetPrototype(RESPONSE, printer); // Generate stub implementation. printer->Print(vars_, "$classname$_Stub::$classname$_Stub(ola::rpc::RpcChannel* channel)\n" " : channel_(channel), owns_channel_(false) {}\n" "$classname$_Stub::$classname$_Stub(\n" " ola::rpc::RpcChannel* channel,\n" " ::google::protobuf::Service::ChannelOwnership ownership)\n" " : channel_(channel),\n" " owns_channel_(ownership == " "::google::protobuf::Service::STUB_OWNS_CHANNEL) {}\n" "$classname$_Stub::~$classname$_Stub() {\n" " if (owns_channel_) delete channel_;\n" "}\n" "\n"); GenerateStubMethods(printer); } void ServiceGenerator::GenerateNotImplementedMethods(Printer* printer) { for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["classname"] = descriptor_->name(); sub_vars["name"] = method->name(); sub_vars["index"] = SimpleItoa(i); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); printer->Print(sub_vars, "void $classname$::$name$(ola::rpc::RpcController* controller,\n" " const $input_type$*,\n" " $output_type$*,\n" " ola::rpc::RpcService::CompletionCallback* done" ") {\n" " controller->SetFailed(\"Method $name$() not implemented.\");\n" " done->Run();\n" "}\n" "\n"); } } void ServiceGenerator::GenerateCallMethod(Printer* printer) { printer->Print(vars_, "void $classname$::CallMethod(const ::google::protobuf::MethodDescriptor* " "method,\n" " ola::rpc::RpcController* controller,\n" " const ::google::protobuf::Message* request,\n" " ::google::protobuf::Message* response,\n" " ola::rpc::RpcService::CompletionCallback* " "done) {\n" " GOOGLE_DCHECK_EQ(method->service(), $classname$_descriptor_);\n" " switch(method->index()) {\n"); for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["name"] = method->name(); sub_vars["index"] = SimpleItoa(i); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); // Note: down_cast does not work here because it only works on pointers, // not references. printer->Print(sub_vars, " case $index$:\n" " $name$(controller,\n" " ::google::protobuf::down_cast<const $input_type$*>(request" "),\n" " ::google::protobuf::down_cast< $output_type$*>(response),\n" " done);\n" " break;\n"); } printer->Print(vars_, " default:\n" " GOOGLE_LOG(FATAL) << \"Bad method index; this should never " "happen.\";\n" " break;\n" " }\n" "}\n" "\n"); } void ServiceGenerator::GenerateGetPrototype(RequestOrResponse which, Printer* printer) { if (which == REQUEST) { printer->Print(vars_, "const ::google::protobuf::Message& $classname$::GetRequestPrototype(\n"); } else { printer->Print(vars_, "const ::google::protobuf::Message& $classname$::GetResponsePrototype" "(\n"); } printer->Print(vars_, " const ::google::protobuf::MethodDescriptor* method) const {\n" " GOOGLE_DCHECK_EQ(method->service(), descriptor());\n" " switch(method->index()) {\n"); for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); const google::protobuf::Descriptor* type = (which == REQUEST) ? method->input_type() : method->output_type(); map<string, string> sub_vars; sub_vars["index"] = SimpleItoa(i); sub_vars["type"] = ClassName(type, true); printer->Print(sub_vars, " case $index$:\n" " return $type$::default_instance();\n"); } printer->Print(vars_, " default:\n" " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen." "\";\n" " return *reinterpret_cast< ::google::protobuf::Message*>(NULL);\n" " }\n" "}\n" "\n"); } void ServiceGenerator::GenerateStubMethods(Printer* printer) { for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["classname"] = descriptor_->name(); sub_vars["name"] = method->name(); sub_vars["index"] = SimpleItoa(i); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); printer->Print(sub_vars, "void $classname$_Stub::$name$(ola::rpc::RpcController* controller,\n" " const $input_type$* request,\n" " $output_type$* response,\n" " ola::rpc::RpcService::CompletionCallback*" " done) {\n" " channel_->CallMethod(descriptor()->method($index$),\n" " controller, request, response, done);\n" "}\n"); } } } // namespace ola
nightrune/ola
protoc/ServiceGenerator.cpp
C++
lgpl-2.1
12,657
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtDBus module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // // W A R N I N G // ------------- // // This file is not part of the public API. This header file may // change from version to version without notice, or even be // removed. // // We mean it. // // #ifndef QDBUS_SYMBOLS_P_H #define QDBUS_SYMBOLS_P_H #include <QtCore/qglobal.h> #include <dbus/dbus.h> #ifndef QT_NO_DBUS QT_BEGIN_NAMESPACE #if !defined QT_LINKED_LIBDBUS void *qdbus_resolve_conditionally(const char *name); // doesn't print a warning void *qdbus_resolve_me(const char *name); // prints a warning bool qdbus_loadLibDBus(); # define DEFINEFUNC(ret, func, args, argcall, funcret) \ typedef ret (* _q_PTR_##func) args; \ static inline ret q_##func args \ { \ static _q_PTR_##func ptr; \ if (!ptr) \ ptr = (_q_PTR_##func) qdbus_resolve_me(#func); \ funcret ptr argcall; \ } #else // defined QT_LINKED_LIBDBUS inline bool qdbus_loadLibDBus() { return true; } # define DEFINEFUNC(ret, func, args, argcall, funcret) \ static inline ret q_##func args { funcret func argcall; } #endif // defined QT_LINKED_LIBDBUS /* dbus-bus.h */ DEFINEFUNC(void, dbus_bus_add_match, (DBusConnection *connection, const char *rule, DBusError *error), (connection, rule, error), ) DEFINEFUNC(void, dbus_bus_remove_match, (DBusConnection *connection, const char *rule, DBusError *error), (connection, rule, error), ) DEFINEFUNC(dbus_bool_t, dbus_bus_register,(DBusConnection *connection, DBusError *error), (connection, error), return) DEFINEFUNC(DBusConnection *, dbus_bus_get_private, (DBusBusType type, DBusError *error), (type, error), return) DEFINEFUNC(const char*, dbus_bus_get_unique_name, (DBusConnection *connection), (connection), return) /* dbus-connection.h */ DEFINEFUNC(dbus_bool_t , dbus_connection_add_filter, (DBusConnection *connection, DBusHandleMessageFunction function, void *user_data, DBusFreeFunction free_data_function), (connection, function, user_data, free_data_function), return) DEFINEFUNC(void , dbus_connection_close, (DBusConnection *connection), (connection), return) DEFINEFUNC(DBusDispatchStatus , dbus_connection_dispatch, (DBusConnection *connection), (connection), return) DEFINEFUNC(DBusDispatchStatus , dbus_connection_get_dispatch_status, (DBusConnection *connection), (connection), return) DEFINEFUNC(dbus_bool_t , dbus_connection_get_is_connected, (DBusConnection *connection), (connection), return) DEFINEFUNC(DBusConnection* , dbus_connection_open_private, (const char *address, DBusError *error), (address, error), return) DEFINEFUNC(DBusConnection* , dbus_connection_ref, (DBusConnection *connection), (connection), return) DEFINEFUNC(dbus_bool_t , dbus_connection_send, (DBusConnection *connection, DBusMessage *message, dbus_uint32_t *client_serial), (connection, message, client_serial), return) DEFINEFUNC(dbus_bool_t , dbus_connection_send_with_reply, (DBusConnection *connection, DBusMessage *message, DBusPendingCall **pending_return, int timeout_milliseconds), (connection, message, pending_return, timeout_milliseconds), return) DEFINEFUNC(DBusMessage * , dbus_connection_send_with_reply_and_block, (DBusConnection *connection, DBusMessage *message, int timeout_milliseconds, DBusError *error), (connection, message, timeout_milliseconds, error), return) DEFINEFUNC(void , dbus_connection_set_exit_on_disconnect, (DBusConnection *connection, dbus_bool_t exit_on_disconnect), (connection, exit_on_disconnect), ) DEFINEFUNC(dbus_bool_t , dbus_connection_set_timeout_functions, (DBusConnection *connection, DBusAddTimeoutFunction add_function, DBusRemoveTimeoutFunction remove_function, DBusTimeoutToggledFunction toggled_function, void *data, DBusFreeFunction free_data_function), (connection, add_function, remove_function, toggled_function, data, free_data_function), return) DEFINEFUNC(dbus_bool_t , dbus_connection_set_watch_functions, (DBusConnection *connection, DBusAddWatchFunction add_function, DBusRemoveWatchFunction remove_function, DBusWatchToggledFunction toggled_function, void *data, DBusFreeFunction free_data_function), (connection, add_function, remove_function, toggled_function, data, free_data_function), return) DEFINEFUNC(void , dbus_connection_set_wakeup_main_function, (DBusConnection *connection, DBusWakeupMainFunction wakeup_main_function, void *data, DBusFreeFunction free_data_function), (connection, wakeup_main_function, data, free_data_function), ) DEFINEFUNC(void , dbus_connection_set_dispatch_status_function, (DBusConnection *connection, DBusDispatchStatusFunction function, void *data, DBusFreeFunction free_data_function), (connection, function, data, free_data_function), ) DEFINEFUNC(void , dbus_connection_unref, (DBusConnection *connection), (connection), ) DEFINEFUNC(dbus_bool_t , dbus_timeout_get_enabled, (DBusTimeout *timeout), (timeout), return) DEFINEFUNC(int , dbus_timeout_get_interval, (DBusTimeout *timeout), (timeout), return) DEFINEFUNC(dbus_bool_t , dbus_timeout_handle, (DBusTimeout *timeout), (timeout), return) DEFINEFUNC(dbus_bool_t , dbus_watch_get_enabled, (DBusWatch *watch), (watch), return) DEFINEFUNC(int , dbus_watch_get_fd, (DBusWatch *watch), (watch), return) DEFINEFUNC(unsigned int , dbus_watch_get_flags, (DBusWatch *watch), (watch), return) DEFINEFUNC(dbus_bool_t , dbus_watch_handle, (DBusWatch *watch, unsigned int flags), (watch, flags), return) /* dbus-errors.h */ DEFINEFUNC(void , dbus_error_free, (DBusError *error), (error), ) DEFINEFUNC(void , dbus_error_init, (DBusError *error), (error), ) DEFINEFUNC(dbus_bool_t , dbus_error_is_set, (const DBusError *error), (error), return) /* dbus-memory.h */ DEFINEFUNC(void , dbus_free, (void *memory), (memory), ) /* dbus-message.h */ DEFINEFUNC(DBusMessage* , dbus_message_copy, (const DBusMessage *message), (message), return) DEFINEFUNC(dbus_bool_t , dbus_message_get_auto_start, (DBusMessage *message), (message), return) DEFINEFUNC(const char* , dbus_message_get_error_name, (DBusMessage *message), (message), return) DEFINEFUNC(const char* , dbus_message_get_interface, (DBusMessage *message), (message), return) DEFINEFUNC(const char* , dbus_message_get_member, (DBusMessage *message), (message), return) DEFINEFUNC(dbus_bool_t , dbus_message_get_no_reply, (DBusMessage *message), (message), return) DEFINEFUNC(const char* , dbus_message_get_path, (DBusMessage *message), (message), return) DEFINEFUNC(const char* , dbus_message_get_sender, (DBusMessage *message), (message), return) DEFINEFUNC(dbus_uint32_t , dbus_message_get_serial, (DBusMessage *message), (message), return) DEFINEFUNC(const char* , dbus_message_get_signature, (DBusMessage *message), (message), return) DEFINEFUNC(int , dbus_message_get_type, (DBusMessage *message), (message), return) DEFINEFUNC(dbus_bool_t , dbus_message_iter_append_basic, (DBusMessageIter *iter, int type, const void *value), (iter, type, value), return) DEFINEFUNC(dbus_bool_t , dbus_message_iter_append_fixed_array, (DBusMessageIter *iter, int element_type, const void *value, int n_elements), (iter, element_type, value, n_elements), return) DEFINEFUNC(dbus_bool_t , dbus_message_iter_close_container, (DBusMessageIter *iter, DBusMessageIter *sub), (iter, sub), return) DEFINEFUNC(int , dbus_message_iter_get_arg_type, (DBusMessageIter *iter), (iter), return) DEFINEFUNC(void , dbus_message_iter_get_basic, (DBusMessageIter *iter, void *value), (iter, value), ) DEFINEFUNC(int , dbus_message_iter_get_element_type, (DBusMessageIter *iter), (iter), return) DEFINEFUNC(void , dbus_message_iter_get_fixed_array, (DBusMessageIter *iter, void *value, int *n_elements), (iter, value, n_elements), return) DEFINEFUNC(char* , dbus_message_iter_get_signature, (DBusMessageIter *iter), (iter), return) DEFINEFUNC(dbus_bool_t , dbus_message_iter_init, (DBusMessage *message, DBusMessageIter *iter), (message, iter), return) DEFINEFUNC(void , dbus_message_iter_init_append, (DBusMessage *message, DBusMessageIter *iter), (message, iter), return) DEFINEFUNC(dbus_bool_t , dbus_message_iter_next, (DBusMessageIter *iter), (iter), return) DEFINEFUNC(dbus_bool_t , dbus_message_iter_open_container, (DBusMessageIter *iter, int type, const char *contained_signature, DBusMessageIter *sub), (iter, type, contained_signature, sub), return) DEFINEFUNC(void , dbus_message_iter_recurse, (DBusMessageIter *iter, DBusMessageIter *sub), (iter, sub), ) DEFINEFUNC(DBusMessage* , dbus_message_new, (int message_type), (message_type), return) DEFINEFUNC(DBusMessage* , dbus_message_new_method_call, (const char *bus_name, const char *path, const char *interface, const char *method), (bus_name, path, interface, method), return) DEFINEFUNC(DBusMessage* , dbus_message_new_signal, (const char *path, const char *interface, const char *name), (path, interface, name), return) DEFINEFUNC(DBusMessage* , dbus_message_ref, (DBusMessage *message), (message), return) DEFINEFUNC(void , dbus_message_set_auto_start, (DBusMessage *message, dbus_bool_t auto_start), (message, auto_start), return) DEFINEFUNC(dbus_bool_t , dbus_message_set_destination, (DBusMessage *message, const char *destination), (message, destination), return) DEFINEFUNC(dbus_bool_t , dbus_message_set_error_name, (DBusMessage *message, const char *name), (message, name), return) DEFINEFUNC(void , dbus_message_set_no_reply, (DBusMessage *message, dbus_bool_t no_reply), (message, no_reply), return) DEFINEFUNC(dbus_bool_t , dbus_message_set_path, (DBusMessage *message, const char *object_path), (message, object_path), return) DEFINEFUNC(dbus_bool_t , dbus_message_set_reply_serial, (DBusMessage *message, dbus_uint32_t reply_serial), (message, reply_serial), return) DEFINEFUNC(dbus_bool_t , dbus_message_set_sender, (DBusMessage *message, const char *sender), (message, sender), return) DEFINEFUNC(void , dbus_message_unref, (DBusMessage *message), (message), ) /* dbus-pending-call.h */ DEFINEFUNC(dbus_bool_t , dbus_pending_call_set_notify, (DBusPendingCall *pending, DBusPendingCallNotifyFunction function, void *user_data, DBusFreeFunction free_user_data), (pending, function, user_data, free_user_data), return) DEFINEFUNC(void , dbus_pending_call_block, (DBusPendingCall *pending), (pending), ) DEFINEFUNC(void , dbus_pending_call_cancel, (DBusPendingCall *pending), (pending), ) DEFINEFUNC(dbus_bool_t , dbus_pending_call_get_completed, (DBusPendingCall *pending), (pending), return) DEFINEFUNC(DBusMessage* , dbus_pending_call_steal_reply, (DBusPendingCall *pending), (pending), return) DEFINEFUNC(void , dbus_pending_call_unref, (DBusPendingCall *pending), (pending), return) /* dbus-server.h */ DEFINEFUNC(dbus_bool_t , dbus_server_allocate_data_slot, (dbus_int32_t *slot_p), (slot_p), return) DEFINEFUNC(void , dbus_server_disconnect, (DBusServer *server), (server), ) DEFINEFUNC(char* , dbus_server_get_address, (DBusServer *server), (server), return) DEFINEFUNC(dbus_bool_t , dbus_server_get_is_connected, (DBusServer *server), (server), return) DEFINEFUNC(DBusServer* , dbus_server_listen, (const char *address, DBusError *error), (address, error), return) DEFINEFUNC(dbus_bool_t , dbus_server_set_data, (DBusServer *server, int slot, void *data, DBusFreeFunction free_data_func), (server, slot, data, free_data_func), return) DEFINEFUNC(void , dbus_server_set_new_connection_function, (DBusServer *server, DBusNewConnectionFunction function, void *data, DBusFreeFunction free_data_function), (server, function, data, free_data_function), ) DEFINEFUNC(dbus_bool_t , dbus_server_set_timeout_functions, (DBusServer *server, DBusAddTimeoutFunction add_function, DBusRemoveTimeoutFunction remove_function, DBusTimeoutToggledFunction toggled_function, void *data, DBusFreeFunction free_data_function), (server, add_function, remove_function, toggled_function, data, free_data_function), return) DEFINEFUNC(dbus_bool_t , dbus_server_set_watch_functions, (DBusServer *server, DBusAddWatchFunction add_function, DBusRemoveWatchFunction remove_function, DBusWatchToggledFunction toggled_function, void *data, DBusFreeFunction free_data_function), (server, add_function, remove_function, toggled_function, data, free_data_function), return) DEFINEFUNC(void , dbus_server_unref, (DBusServer *server), (server), ) /* dbus-signature.h */ DEFINEFUNC(dbus_bool_t , dbus_signature_validate, (const char *signature, DBusError *error), (signature, error), return) DEFINEFUNC(dbus_bool_t , dbus_signature_validate_single, (const char *signature, DBusError *error), (signature, error), return) DEFINEFUNC(dbus_bool_t , dbus_type_is_basic, (int typecode), (typecode), return) DEFINEFUNC(dbus_bool_t , dbus_type_is_fixed, (int typecode), (typecode), return) /* dbus-thread.h */ DEFINEFUNC(dbus_bool_t , dbus_threads_init_default, (), (), return) QT_END_NAMESPACE #endif // QT_NO_DBUS #endif // QDBUS_SYMBOLS_P_H
igor-sfdc/qt-wk
src/dbus/qdbus_symbols_p.h
C
lgpl-2.1
22,180
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>CQRS.NET: Cqrs.Azure.ServiceBus.AzureBus.MaximumConcurrentReceiverProcessesCount</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ extensions: ["tex2jax.js"], jax: ["input/TeX","output/HTML-CSS"], }); </script><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">CQRS.NET &#160;<span id="projectnumber">2.0</span> </div> <div id="projectbrief">A lightweight enterprise framework to write CQRS, event-sourced and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('classCqrs_1_1Azure_1_1ServiceBus_1_1AzureBus_a6b517888d91c6a5b026cb5857e75a04f.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <a id="a6b517888d91c6a5b026cb5857e75a04f"></a> <h2 class="memtitle"><span class="permalink"><a href="#a6b517888d91c6a5b026cb5857e75a04f">&#9670;&nbsp;</a></span>MaximumConcurrentReceiverProcessesCount</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">int <a class="el" href="classCqrs_1_1Azure_1_1ServiceBus_1_1AzureBus.html">Cqrs.Azure.ServiceBus.AzureBus</a>&lt; TAuthenticationToken &gt;.MaximumConcurrentReceiverProcessesCount</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">get</span><span class="mlabel">set</span><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Azure.html">Azure</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Azure_1_1ServiceBus.html">ServiceBus</a></li><li class="navelem"><a class="el" href="classCqrs_1_1Azure_1_1ServiceBus_1_1AzureBus.html">AzureBus</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
Chinchilla-Software-Com/CQRS
wiki/docs/2.0/html/classCqrs_1_1Azure_1_1ServiceBus_1_1AzureBus_a6b517888d91c6a5b026cb5857e75a04f.html
HTML
lgpl-2.1
5,170
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** 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 Digia Plc and its Subsidiary(-ies) 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$ ** ****************************************************************************/ #include <iostream> #include "myclass.h" MyClass::MyClass() { std::cout << tr("Hello Qt!\n").toLocal8Bit().constData(); }
nonrational/qt-everywhere-opensource-src-4.8.6
doc/src/snippets/i18n-non-qt-class/myclass.cpp
C++
lgpl-2.1
2,127
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the plugins 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 "qmeegorasterpixmapdata.h" /* Public */ QMeeGoRasterPixmapData::QMeeGoRasterPixmapData() : QRasterPixmapData(QPixmapData::PixmapType) { } QMeeGoRasterPixmapData::QMeeGoRasterPixmapData(QPixmapData::PixelType t) : QRasterPixmapData(t) { } void QMeeGoRasterPixmapData::copy(const QPixmapData *data, const QRect &rect) { if (data->classId() == QPixmapData::OpenGLClass) fromImage(data->toImage(rect).copy(), Qt::NoOpaqueDetection); else QRasterPixmapData::copy(data, rect); }
sicily/qt4.8.4
src/plugins/graphicssystems/meego/qmeegorasterpixmapdata.cpp
C++
lgpl-2.1
2,473
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * 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 * *****************************************************************************/ // mapnik #include <mapnik/value_types.hpp> #include <mapnik/global.hpp> #include <mapnik/debug.hpp> #include <mapnik/box2d.hpp> #include <mapnik/geometry.hpp> #include <mapnik/feature.hpp> #include <mapnik/feature_layer_desc.hpp> #include <mapnik/wkb.hpp> #include <mapnik/unicode.hpp> #include <mapnik/feature_factory.hpp> // boost #ifdef SHAPE_MEMORY_MAPPED_FILE #include <mapnik/mapped_memory_cache.hpp> #include <boost/interprocess/mapped_region.hpp> #include <boost/interprocess/streams/bufferstream.hpp> #endif // ogr #include "ogr_index_featureset.hpp" #include "ogr_converter.hpp" #include "ogr_index.hpp" using mapnik::query; using mapnik::box2d; using mapnik::feature_ptr; using mapnik::geometry_utils; using mapnik::transcoder; using mapnik::feature_factory; template <typename filterT> ogr_index_featureset<filterT>::ogr_index_featureset(mapnik::context_ptr const & ctx, OGRLayer & layer, filterT const& filter, std::string const& index_file, std::string const& encoding) : ctx_(ctx), layer_(layer), layerdef_(layer.GetLayerDefn()), filter_(filter), tr_(new transcoder(encoding)), fidcolumn_(layer_.GetFIDColumn()), feature_envelope_() { #ifdef SHAPE_MEMORY_MAPPED_FILE boost::optional<mapnik::mapped_region_ptr> memory = mapnik::mapped_memory_cache::instance().find(index_file, true); if (memory) { boost::interprocess::ibufferstream file(static_cast<char*>((*memory)->get_address()),(*memory)->get_size()); ogr_index<filterT,boost::interprocess::ibufferstream >::query(filter,file,ids_); } #else #if defined (WINDOWS) std::ifstream file(mapnik::utf8_to_utf16(index_file), std::ios::in | std::ios::binary); #else std::ifstream file(index_file.c_str(), std::ios::in | std::ios::binary); #endif ogr_index<filterT,std::ifstream>::query(filter,file,ids_); #endif std::sort(ids_.begin(),ids_.end()); MAPNIK_LOG_DEBUG(ogr) << "ogr_index_featureset: Query size=" << ids_.size(); itr_ = ids_.begin(); // reset reading layer_.ResetReading(); } template <typename filterT> ogr_index_featureset<filterT>::~ogr_index_featureset() {} template <typename filterT> feature_ptr ogr_index_featureset<filterT>::next() { while (itr_ != ids_.end()) { int pos = *itr_++; layer_.SetNextByIndex (pos); OGRFeature *poFeature = layer_.GetNextFeature(); if (poFeature == nullptr) { return feature_ptr(); } // ogr feature ids start at 0, so add one to stay // consistent with other mapnik datasources that start at 1 mapnik::value_integer feature_id = (poFeature->GetFID() + 1); feature_ptr feature(feature_factory::create(ctx_,feature_id)); OGRGeometry* geom=poFeature->GetGeometryRef(); if (geom && !geom->IsEmpty()) { geom->getEnvelope(&feature_envelope_); if (!filter_.pass(mapnik::box2d<double>(feature_envelope_.MinX,feature_envelope_.MinY, feature_envelope_.MaxX,feature_envelope_.MaxY))) continue; ogr_converter::convert_geometry (geom, feature); } else { MAPNIK_LOG_DEBUG(ogr) << "ogr_index_featureset: Feature with null geometry=" << poFeature->GetFID(); OGRFeature::DestroyFeature( poFeature ); continue; } int fld_count = layerdef_->GetFieldCount(); for (int i = 0; i < fld_count; i++) { OGRFieldDefn* fld = layerdef_->GetFieldDefn (i); OGRFieldType type_oid = fld->GetType (); std::string fld_name = fld->GetNameRef (); switch (type_oid) { case OFTInteger: { feature->put<mapnik::value_integer>(fld_name,poFeature->GetFieldAsInteger (i)); break; } case OFTReal: { feature->put(fld_name,poFeature->GetFieldAsDouble (i)); break; } case OFTString: case OFTWideString: // deprecated ! { feature->put(fld_name,tr_->transcode(poFeature->GetFieldAsString (i))); break; } case OFTIntegerList: case OFTRealList: case OFTStringList: case OFTWideStringList: // deprecated ! { MAPNIK_LOG_WARN(ogr) << "ogr_index_featureset: Unhandled type_oid=" << type_oid; break; } case OFTBinary: { MAPNIK_LOG_WARN(ogr) << "ogr_index_featureset: Unhandled type_oid=" << type_oid; //feature->put(name,feat->GetFieldAsBinary (i, size)); break; } case OFTDate: case OFTTime: case OFTDateTime: // unhandled ! { MAPNIK_LOG_WARN(ogr) << "ogr_index_featureset: Unhandled type_oid=" << type_oid; break; } } } OGRFeature::DestroyFeature( poFeature ); return feature; } return feature_ptr(); } template class ogr_index_featureset<mapnik::filter_in_box>; template class ogr_index_featureset<mapnik::filter_at_point>;
TemplateVoid/mapnik
plugins/input/ogr/ogr_index_featureset.cpp
C++
lgpl-2.1
6,547
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Mobility Components. ** ** $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$ ** ****************************************************************************/ #ifndef MESSAGINGEX_H #define MESSAGINGEX_H #include <QtGui> #include "ui_messagingex.h" #include "ui_smsreceiveddialog.h" #include "ui_accountdialog.h" #include "ui_mmsreceiveddialog.h" #include "qmessageservice.h" #include "qmessagemanager.h" #include "qmessage.h" #include "qmessageaccount.h" QTM_USE_NAMESPACE class MessagingEx : public QMainWindow, public Ui::MessagingExMainWindow { Q_OBJECT public: MessagingEx(QWidget* parent = 0); void createMenus(); private Q_SLOTS: void send(); void on_sendSmsButton_clicked(); void on_sendMmsButton_clicked(); void on_sendEmailButton_clicked(); void messageReceived(const QMessageId& aId); void messageRemoved(const QMessageId& aId); void messageUpdated(const QMessageId& aId); void accountSelected(int index); void addAttachment(); void removeAttachment(); void queryMessages(); void composeSMS(); void composeMMS(); void composeEmail(); void addMessage(); void sortType(); void sortSender(); void sortRecipient(); void sortSubject(); void sortTimestamp(); void sortReceptiontimestamp(); void sortStatus(); void sortParentAccountId(); void sortStandardFolder(); void findMessages(); void messagesFound(const QMessageIdList &ids); private: QMessageService m_service; QMessageManager m_manager; QAction* m_createEmail; QAction* m_createSms; QAction* m_createMms; QAction* m_sortMessages; QList<QAction*> m_accountActions; QStringList m_attachments; QString m_fileNames; QMenu *filterMenu; QMenu *composeMenu; QAction* m_composeSMS; QAction* m_composeMMS; QAction* m_composeEmail; QAction* m_sortId; QAction* m_sortType; QAction* m_sortSender; QAction* m_sortRecipient; QAction* m_sortSubject; QAction* m_sortTimestamp; QAction* m_sortReceptiontimestamp; QAction* m_sortStatus; QAction* m_sortParentAccountId; QAction* m_sortStandardFolder; QAction* m_result; QList<QMessageAccountId> m_accountList; QMessageAccount m_account; }; class SMSReceivedDialog : public QDialog, public Ui::SMSReceivedDialog { Q_OBJECT public: SMSReceivedDialog(const QMessage& aMessage, QWidget* parent = 0); }; class MMSReceivedDialog : public QDialog, public Ui::MMSReceivedDialog { Q_OBJECT public: MMSReceivedDialog(const QMessage& aMessage, QWidget* parent = 0); }; class AccountDialog : public QDialog, public Ui::AccountDialog { Q_OBJECT public: AccountDialog(const QMessageAccount& account, QWidget* parent = 0); }; #endif // MESSAGINGEX_H // End of file
qtproject/qt-mobility
tests/manual/messagingex/messagingex.h
C
lgpl-2.1
4,650
#ifndef __GSK_CGI_REQUEST_H_ #define __GSK_CGI_REQUEST_H_ G_BEGIN_DECLS /* --- typedefs --- */ typedef struct _GskCgiRequest GskCgiRequest; typedef struct _GskCgiRequestClass GskCgiRequestClass; /* --- type macros --- */ GType gsk_cgi_request_get_type(void) G_GNUC_CONST; #define GSK_TYPE_CGI_REQUEST (gsk_cgi_request_get_type ()) #define GSK_CGI_REQUEST(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GSK_TYPE_CGI_REQUEST, GskCgiRequest)) #define GSK_CGI_REQUEST_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), GSK_TYPE_CGI_REQUEST, GskCgiRequestClass)) #define GSK_CGI_REQUEST_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), GSK_TYPE_CGI_REQUEST, GskCgiRequestClass)) #define GSK_IS_CGI_REQUEST(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GSK_TYPE_CGI_REQUEST)) #define GSK_IS_CGI_REQUEST_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GSK_TYPE_CGI_REQUEST)) /* --- structures --- */ struct _GskCgiRequestClass { GObjectClass base_class; }; struct _GskCgiRequest { GObject base_instance; GHashTable *content_parts_by_name; GskCgiContent *content; }; struct _GskCgiResponse { GskHttpResponse *response; /* --- prototypes --- */ GskCgiRequest *gsk_cgi_request_new (void); /* NOTE: either stored by name or stored in 'content' member. * In either event, the destruction of 'request' causes the * destruction of 'content'. */ void gsk_cgi_request_set_content (GskCgiRequest *request, GskCgiContent *content); /* NOTE: 'name' may be NULL, to access the central content. */ G_GNUC_CONST GskCgiContent * gsk_cgi_request_peek_content(GskCgiContent *request, const char *name); G_END_DECLS #endif
novator24/zgsk
src/cgi/gskcgirequest.h
C
lgpl-2.1
1,706
/* GStreamer * Copyright (C) <2008> Edward Hervey <[email protected]> * * 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; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ /** * SECTION:element-hdv1394src * @title: hdv1394src * * Read MPEG-TS data from firewire port. * * ## Example launch line * |[ * gst-launch-1.0 hdv1394src ! queue ! decodebin name=d ! queue ! xvimagesink d. ! queue ! alsasink * ]| captures from the firewire port and plays the streams. * |[ * gst-launch-1.0 hdv1394src ! queue ! filesink location=mydump.ts * ]| capture to a disk file * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <unistd.h> #include <poll.h> #include <sys/socket.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <stdlib.h> #include <libavc1394/avc1394.h> #include <libavc1394/avc1394_vcr.h> #include <libavc1394/rom1394.h> #include <libraw1394/raw1394.h> #include <libiec61883/iec61883.h> #include <gst/gst.h> #include "gsthdv1394src.h" #include "gst1394probe.h" #define CONTROL_STOP 'S' /* stop the select call */ #define CONTROL_SOCKETS(src) src->control_sock #define WRITE_SOCKET(src) src->control_sock[1] #define READ_SOCKET(src) src->control_sock[0] #define SEND_COMMAND(src, command) \ G_STMT_START { \ int G_GNUC_UNUSED _res; unsigned char c; c = command; \ _res = write (WRITE_SOCKET(src), &c, 1); \ } G_STMT_END #define READ_COMMAND(src, command, res) \ G_STMT_START { \ res = read(READ_SOCKET(src), &command, 1); \ } G_STMT_END GST_DEBUG_CATEGORY_STATIC (hdv1394src_debug); #define GST_CAT_DEFAULT (hdv1394src_debug) #define DEFAULT_PORT -1 #define DEFAULT_CHANNEL 63 #define DEFAULT_USE_AVC TRUE #define DEFAULT_GUID 0 enum { PROP_0, PROP_PORT, PROP_CHANNEL, PROP_USE_AVC, PROP_GUID, PROP_DEVICE_NAME }; static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS ("video/mpegts,systemstream=(boolean)true,packetsize=(int)188") ); static void gst_hdv1394src_uri_handler_init (gpointer g_iface, gpointer iface_data); static void gst_hdv1394src_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_hdv1394src_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); static void gst_hdv1394src_dispose (GObject * object); static gboolean gst_hdv1394src_start (GstBaseSrc * bsrc); static gboolean gst_hdv1394src_stop (GstBaseSrc * bsrc); static gboolean gst_hdv1394src_unlock (GstBaseSrc * bsrc); static GstFlowReturn gst_hdv1394src_create (GstPushSrc * psrc, GstBuffer ** buf); static void gst_hdv1394src_update_device_name (GstHDV1394Src * src); #define gst_hdv1394src_parent_class parent_class G_DEFINE_TYPE_WITH_CODE (GstHDV1394Src, gst_hdv1394src, GST_TYPE_PUSH_SRC, G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_hdv1394src_uri_handler_init)); static void gst_hdv1394src_class_init (GstHDV1394SrcClass * klass) { GObjectClass *gobject_class; GstElementClass *gstelement_class; GstBaseSrcClass *gstbasesrc_class; GstPushSrcClass *gstpushsrc_class; gobject_class = (GObjectClass *) klass; gstelement_class = (GstElementClass *) klass; gstbasesrc_class = (GstBaseSrcClass *) klass; gstpushsrc_class = (GstPushSrcClass *) klass; gobject_class->set_property = gst_hdv1394src_set_property; gobject_class->get_property = gst_hdv1394src_get_property; gobject_class->dispose = gst_hdv1394src_dispose; g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_PORT, g_param_spec_int ("port", "Port", "Port number (-1 automatic)", -1, 16, DEFAULT_PORT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_CHANNEL, g_param_spec_int ("channel", "Channel", "Channel number for listening", 0, 64, DEFAULT_CHANNEL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_USE_AVC, g_param_spec_boolean ("use-avc", "Use AV/C", "Use AV/C VTR control", DEFAULT_USE_AVC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_GUID, g_param_spec_uint64 ("guid", "GUID", "select one of multiple DV devices by its GUID. use a hexadecimal " "like 0xhhhhhhhhhhhhhhhh. (0 = no guid)", 0, G_MAXUINT64, DEFAULT_GUID, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * GstHDV1394Src:device-name: * * Descriptive name of the currently opened device */ g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_DEVICE_NAME, g_param_spec_string ("device-name", "device name", "user-friendly name of the device", "Default", G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); gstbasesrc_class->negotiate = NULL; gstbasesrc_class->start = gst_hdv1394src_start; gstbasesrc_class->stop = gst_hdv1394src_stop; gstbasesrc_class->unlock = gst_hdv1394src_unlock; gstpushsrc_class->create = gst_hdv1394src_create; gst_element_class_add_static_pad_template (gstelement_class, &src_factory); gst_element_class_set_static_metadata (gstelement_class, "Firewire (1394) HDV video source", "Source/Video", "Source for MPEG-TS video data from firewire port", "Edward Hervey <[email protected]>"); GST_DEBUG_CATEGORY_INIT (hdv1394src_debug, "hdv1394src", 0, "MPEG-TS firewire source"); } static void gst_hdv1394src_init (GstHDV1394Src * dv1394src) { GstPad *srcpad = GST_BASE_SRC_PAD (dv1394src); gst_base_src_set_live (GST_BASE_SRC (dv1394src), TRUE); gst_pad_use_fixed_caps (srcpad); dv1394src->port = DEFAULT_PORT; dv1394src->channel = DEFAULT_CHANNEL; dv1394src->use_avc = DEFAULT_USE_AVC; dv1394src->guid = DEFAULT_GUID; dv1394src->uri = g_strdup_printf ("hdv://%d", dv1394src->port); dv1394src->device_name = g_strdup_printf ("Default"); READ_SOCKET (dv1394src) = -1; WRITE_SOCKET (dv1394src) = -1; dv1394src->frame_sequence = 0; } static void gst_hdv1394src_dispose (GObject * object) { GstHDV1394Src *src = GST_HDV1394SRC (object); g_free (src->uri); src->uri = NULL; g_free (src->device_name); src->device_name = NULL; G_OBJECT_CLASS (parent_class)->dispose (object); } static void gst_hdv1394src_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstHDV1394Src *filter = GST_HDV1394SRC (object); switch (prop_id) { case PROP_PORT: filter->port = g_value_get_int (value); g_free (filter->uri); filter->uri = g_strdup_printf ("hdv://%d", filter->port); break; case PROP_CHANNEL: filter->channel = g_value_get_int (value); break; case PROP_USE_AVC: filter->use_avc = g_value_get_boolean (value); break; case PROP_GUID: filter->guid = g_value_get_uint64 (value); gst_hdv1394src_update_device_name (filter); break; default: break; } } static void gst_hdv1394src_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstHDV1394Src *filter = GST_HDV1394SRC (object); switch (prop_id) { case PROP_PORT: g_value_set_int (value, filter->port); break; case PROP_CHANNEL: g_value_set_int (value, filter->channel); break; case PROP_USE_AVC: g_value_set_boolean (value, filter->use_avc); break; case PROP_GUID: g_value_set_uint64 (value, filter->guid); break; case PROP_DEVICE_NAME: g_value_set_string (value, filter->device_name); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static GstHDV1394Src * gst_hdv1394src_from_raw1394handle (raw1394handle_t handle) { iec61883_mpeg2_t mpeg2 = (iec61883_mpeg2_t) raw1394_get_userdata (handle); return GST_HDV1394SRC (iec61883_mpeg2_get_callback_data (mpeg2)); } /* Within one loop iteration (which may call _receive() many times), it seems * as though '*data' will always be different. * * We can therefore assume that any '*data' given to us will stay allocated until * the next loop iteration. */ static int gst_hdv1394src_iec61883_receive (unsigned char *data, int len, unsigned int dropped, void *cbdata) { GstHDV1394Src *dv1394src = GST_HDV1394SRC (cbdata); GST_LOG ("data:%p, len:%d, dropped:%d", data, len, dropped); /* error out if we don't have enough room ! */ if (G_UNLIKELY (dv1394src->outoffset > (2048 * 188 - len))) return -1; if (G_LIKELY (len == IEC61883_MPEG2_TSP_SIZE)) { memcpy ((guint8 *) dv1394src->outdata + dv1394src->outoffset, data, len); dv1394src->outoffset += len; } dv1394src->frame_sequence++; return 0; } /* * When an ieee1394 bus reset happens, usually a device has been removed * or added. We send a message on the message bus with the node count * and whether the capture device used in this element connected, disconnected * or was unchanged * Message structure: * nodecount - integer with number of nodes on bus * current-device-change - integer (1 if device connected, 0 if no change to * current device status, -1 if device disconnected) */ static int gst_hdv1394src_bus_reset (raw1394handle_t handle, unsigned int generation) { GstHDV1394Src *src; gint nodecount; GstMessage *message; GstStructure *structure; gint current_device_change; gint i; src = gst_hdv1394src_from_raw1394handle (handle); GST_INFO_OBJECT (src, "have bus reset"); /* update generation - told to do so by docs */ raw1394_update_generation (handle, generation); nodecount = raw1394_get_nodecount (handle); /* allocate memory for portinfo */ /* current_device_change is -1 if camera disconnected, 0 if other device * connected or 1 if camera has now connected */ current_device_change = -1; for (i = 0; i < nodecount; i++) { if (src->guid == rom1394_get_guid (handle, i)) { /* Camera is with us */ GST_DEBUG ("Camera is with us"); if (!src->connected) { current_device_change = 1; src->connected = TRUE; } else current_device_change = 0; } } if (src->connected && current_device_change == -1) { GST_DEBUG ("Camera has disconnected"); src->connected = FALSE; } else if (!src->connected && current_device_change == -1) { GST_DEBUG ("Camera is still not with us"); current_device_change = 0; } structure = gst_structure_new ("ieee1394-bus-reset", "nodecount", G_TYPE_INT, nodecount, "current-device-change", G_TYPE_INT, current_device_change, NULL); message = gst_message_new_element (GST_OBJECT (src), structure); gst_element_post_message (GST_ELEMENT (src), message); return 0; } static GstFlowReturn gst_hdv1394src_create (GstPushSrc * psrc, GstBuffer ** buf) { GstHDV1394Src *dv1394src = GST_HDV1394SRC (psrc); struct pollfd pollfds[2]; pollfds[0].fd = raw1394_get_fd (dv1394src->handle); pollfds[0].events = POLLIN | POLLERR | POLLHUP | POLLPRI; pollfds[1].fd = READ_SOCKET (dv1394src); pollfds[1].events = POLLIN | POLLERR | POLLHUP | POLLPRI; /* allocate a 2048 samples buffer */ dv1394src->outdata = g_malloc (2048 * 188); dv1394src->outoffset = 0; GST_DEBUG ("Create..."); while (TRUE) { int res = poll (pollfds, 2, -1); GST_LOG ("res:%d", res); if (G_UNLIKELY (res < 0)) { if (errno == EAGAIN || errno == EINTR) continue; else goto error_while_polling; } if (G_UNLIKELY (pollfds[1].revents)) { char command; if (pollfds[1].revents & POLLIN) READ_COMMAND (dv1394src, command, res); goto told_to_stop; } else if (G_LIKELY (pollfds[0].revents & POLLIN)) { int pt; pt = dv1394src->frame_sequence; /* shouldn't block in theory */ GST_LOG ("Iterating ! (%d)", dv1394src->frame_sequence); raw1394_loop_iterate (dv1394src->handle); GST_LOG ("After iteration : %d (diff:%d)", dv1394src->frame_sequence, dv1394src->frame_sequence - pt); if (dv1394src->outoffset) break; } } g_assert (dv1394src->outoffset); GST_LOG ("We have some frames (%u bytes)", (guint) dv1394src->outoffset); /* Create the buffer */ *buf = gst_buffer_new_wrapped (dv1394src->outdata, dv1394src->outoffset); dv1394src->outdata = NULL; dv1394src->outoffset = 0; return GST_FLOW_OK; error_while_polling: { GST_ELEMENT_ERROR (dv1394src, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM); return GST_FLOW_EOS; } told_to_stop: { GST_DEBUG_OBJECT (dv1394src, "told to stop, shutting down"); return GST_FLOW_FLUSHING; } } static int gst_hdv1394src_discover_avc_node (GstHDV1394Src * src) { int node = -1; int i, j = 0; int m = src->num_ports; if (src->port >= 0) { /* search on explicit port */ j = src->port; m = j + 1; } /* loop over all our ports */ for (; j < m && node == -1; j++) { raw1394handle_t handle; struct raw1394_portinfo pinf[16]; /* open the port */ handle = raw1394_new_handle (); if (!handle) { GST_WARNING ("raw1394 - failed to get handle: %s.\n", strerror (errno)); continue; } if (raw1394_get_port_info (handle, pinf, 16) < 0) { GST_WARNING ("raw1394 - failed to get port info: %s.\n", strerror (errno)); goto next; } /* tell raw1394 which host adapter to use */ if (raw1394_set_port (handle, j) < 0) { GST_WARNING ("raw1394 - failed to set set port: %s.\n", strerror (errno)); goto next; } /* now loop over all the nodes */ for (i = 0; i < raw1394_get_nodecount (handle); i++) { /* are we looking for an explicit GUID ? */ if (src->guid != 0) { if (src->guid == rom1394_get_guid (handle, i)) { node = i; src->port = j; g_free (src->uri); src->uri = g_strdup_printf ("dv://%d", src->port); break; } } else { rom1394_directory rom_dir; /* select first AV/C Tape Recorder Player node */ if (rom1394_get_directory (handle, i, &rom_dir) < 0) { GST_WARNING ("error reading config rom directory for node %d\n", i); continue; } if ((rom1394_get_node_type (&rom_dir) == ROM1394_NODE_TYPE_AVC) && avc1394_check_subunit_type (handle, i, AVC1394_SUBUNIT_TYPE_VCR)) { node = i; src->port = j; src->guid = rom1394_get_guid (handle, i); g_free (src->uri); src->uri = g_strdup_printf ("dv://%d", src->port); g_free (src->device_name); src->device_name = g_strdup (rom_dir.label); break; } rom1394_free_directory (&rom_dir); } } next: raw1394_destroy_handle (handle); } return node; } static gboolean gst_hdv1394src_start (GstBaseSrc * bsrc) { GstHDV1394Src *src = GST_HDV1394SRC (bsrc); int control_sock[2]; src->connected = FALSE; if (socketpair (PF_UNIX, SOCK_STREAM, 0, control_sock) < 0) goto socket_pair; READ_SOCKET (src) = control_sock[0]; WRITE_SOCKET (src) = control_sock[1]; if (fcntl (READ_SOCKET (src), F_SETFL, O_NONBLOCK) < 0) GST_ERROR_OBJECT (src, "failed to make read socket non-blocking: %s", g_strerror (errno)); if (fcntl (WRITE_SOCKET (src), F_SETFL, O_NONBLOCK) < 0) GST_ERROR_OBJECT (src, "failed to make write socket non-blocking: %s", g_strerror (errno)); src->handle = raw1394_new_handle (); if (!src->handle) { if (errno == EACCES) goto permission_denied; else if (errno == ENOENT) goto not_found; else goto no_handle; } src->num_ports = raw1394_get_port_info (src->handle, src->pinfo, 16); if (src->num_ports == 0) goto no_ports; if (src->use_avc || src->port == -1) src->avc_node = gst_hdv1394src_discover_avc_node (src); /* lets destroy handle and create one on port this is more reliable than setting port on the existing handle */ raw1394_destroy_handle (src->handle); src->handle = raw1394_new_handle_on_port (src->port); if (!src->handle) goto cannot_set_port; raw1394_set_userdata (src->handle, src); raw1394_set_bus_reset_handler (src->handle, gst_hdv1394src_bus_reset); { nodeid_t m_node = (src->avc_node | 0xffc0); int m_channel = -1; int m_bandwidth = 0; int m_outputPort = -1; int m_inputPort = -1; m_channel = iec61883_cmp_connect (src->handle, m_node, &m_outputPort, raw1394_get_local_id (src->handle), &m_inputPort, &m_bandwidth); if (m_channel >= 0) { src->channel = m_channel; } } if ((src->iec61883mpeg2 = iec61883_mpeg2_recv_init (src->handle, gst_hdv1394src_iec61883_receive, src)) == NULL) goto cannot_initialise_dv; #if 0 raw1394_set_iso_handler (src->handle, src->channel, gst_hdv1394src_iso_receive); #endif GST_DEBUG_OBJECT (src, "successfully opened up 1394 connection"); src->connected = TRUE; if (iec61883_mpeg2_recv_start (src->iec61883mpeg2, src->channel) != 0) goto cannot_start; #if 0 if (raw1394_start_iso_rcv (src->handle, src->channel) < 0) goto cannot_start; #endif if (src->use_avc) { raw1394handle_t avc_handle = raw1394_new_handle_on_port (src->port); GST_LOG ("We have an avc_handle"); /* start the VCR */ if (avc_handle) { if (!avc1394_vcr_is_recording (avc_handle, src->avc_node) && avc1394_vcr_is_playing (avc_handle, src->avc_node) != AVC1394_VCR_OPERAND_PLAY_FORWARD) { GST_LOG ("Calling avc1394_vcr_play()"); avc1394_vcr_play (avc_handle, src->avc_node); } raw1394_destroy_handle (avc_handle); } else { GST_WARNING_OBJECT (src, "Starting VCR via avc1394 failed: %s", g_strerror (errno)); } } return TRUE; socket_pair: { GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL), GST_ERROR_SYSTEM); return FALSE; } permission_denied: { GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL), GST_ERROR_SYSTEM); return FALSE; } not_found: { GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), GST_ERROR_SYSTEM); return FALSE; } no_handle: { GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL), ("can't get raw1394 handle (%s)", g_strerror (errno))); return FALSE; } no_ports: { raw1394_destroy_handle (src->handle); src->handle = NULL; GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("no ports available for raw1394")); return FALSE; } cannot_set_port: { GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL), ("can't set 1394 port %d", src->port)); return FALSE; } cannot_start: { raw1394_destroy_handle (src->handle); src->handle = NULL; iec61883_mpeg2_close (src->iec61883mpeg2); src->iec61883mpeg2 = NULL; GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), ("can't start 1394 iso receive")); return FALSE; } cannot_initialise_dv: { raw1394_destroy_handle (src->handle); src->handle = NULL; GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), ("can't initialise iec61883 hdv")); return FALSE; } } static gboolean gst_hdv1394src_stop (GstBaseSrc * bsrc) { GstHDV1394Src *src = GST_HDV1394SRC (bsrc); close (READ_SOCKET (src)); close (WRITE_SOCKET (src)); READ_SOCKET (src) = -1; WRITE_SOCKET (src) = -1; iec61883_mpeg2_close (src->iec61883mpeg2); #if 0 raw1394_stop_iso_rcv (src->handle, src->channel); #endif if (src->use_avc) { raw1394handle_t avc_handle = raw1394_new_handle_on_port (src->port); /* pause and stop the VCR */ if (avc_handle) { if (!avc1394_vcr_is_recording (avc_handle, src->avc_node) && (avc1394_vcr_is_playing (avc_handle, src->avc_node) != AVC1394_VCR_OPERAND_PLAY_FORWARD_PAUSE)) avc1394_vcr_pause (avc_handle, src->avc_node); avc1394_vcr_stop (avc_handle, src->avc_node); raw1394_destroy_handle (avc_handle); } else { GST_WARNING_OBJECT (src, "Starting VCR via avc1394 failed: %s", g_strerror (errno)); } } raw1394_destroy_handle (src->handle); return TRUE; } static gboolean gst_hdv1394src_unlock (GstBaseSrc * bsrc) { GstHDV1394Src *src = GST_HDV1394SRC (bsrc); SEND_COMMAND (src, CONTROL_STOP); return TRUE; } static void gst_hdv1394src_update_device_name (GstHDV1394Src * src) { raw1394handle_t handle; gint portcount, port, nodecount, node; rom1394_directory directory; g_free (src->device_name); src->device_name = NULL; GST_LOG_OBJECT (src, "updating device name for current GUID"); handle = raw1394_new_handle (); if (handle == NULL) goto gethandle_failed; portcount = raw1394_get_port_info (handle, NULL, 0); for (port = 0; port < portcount; port++) { if (raw1394_set_port (handle, port) >= 0) { nodecount = raw1394_get_nodecount (handle); for (node = 0; node < nodecount; node++) { if (src->guid == rom1394_get_guid (handle, node)) { if (rom1394_get_directory (handle, node, &directory) >= 0) { g_free (src->device_name); src->device_name = g_strdup (directory.label); rom1394_free_directory (&directory); goto done; } else { GST_WARNING ("error reading rom directory for node %d", node); } } } } } src->device_name = g_strdup ("Unknown"); /* FIXME: translate? */ done: raw1394_destroy_handle (handle); return; /* ERRORS */ gethandle_failed: { GST_WARNING ("failed to get raw1394 handle: %s", g_strerror (errno)); src->device_name = g_strdup ("Unknown"); /* FIXME: translate? */ return; } } /*** GSTURIHANDLER INTERFACE *************************************************/ static GstURIType gst_hdv1394src_uri_get_type (GType type) { return GST_URI_SRC; } static const gchar *const * gst_hdv1394src_uri_get_protocols (GType type) { static const gchar *protocols[] = { (char *) "hdv", NULL }; return protocols; } static gchar * gst_hdv1394src_uri_get_uri (GstURIHandler * handler) { GstHDV1394Src *gst_hdv1394src = GST_HDV1394SRC (handler); return gst_hdv1394src->uri; } static gboolean gst_hdv1394src_uri_set_uri (GstURIHandler * handler, const gchar * uri, GError ** error) { gchar *protocol, *location; gboolean ret = TRUE; GstHDV1394Src *gst_hdv1394src = GST_HDV1394SRC (handler); protocol = gst_uri_get_protocol (uri); if (strcmp (protocol, "hdv") != 0) { g_free (protocol); g_set_error (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI, "Invalid HDV URI"); return FALSE; } g_free (protocol); location = gst_uri_get_location (uri); if (location && *location != '\0') gst_hdv1394src->port = strtol (location, NULL, 10); else gst_hdv1394src->port = DEFAULT_PORT; g_free (location); g_free (gst_hdv1394src->uri); gst_hdv1394src->uri = g_strdup_printf ("hdv://%d", gst_hdv1394src->port); return ret; } static void gst_hdv1394src_uri_handler_init (gpointer g_iface, gpointer iface_data) { GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface; iface->get_type = gst_hdv1394src_uri_get_type; iface->get_protocols = gst_hdv1394src_uri_get_protocols; iface->get_uri = gst_hdv1394src_uri_get_uri; iface->set_uri = gst_hdv1394src_uri_set_uri; }
pexip/gst-plugins-good
ext/raw1394/gsthdv1394src.c
C
lgpl-2.1
24,279
/* Copyright (C) 2002 by Anders Stenberg Written by Anders Stenberg 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; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __CS_GLSTATES_H__ #define __CS_GLSTATES_H__ /**\file * OpenGL state cache. */ #if defined(CS_OPENGL_PATH) #include CS_HEADER_GLOBAL(CS_OPENGL_PATH,gl.h) #else #include <GL/gl.h> #endif #include "csextern_gl.h" #include "csgeom/math.h" #include "glextmanager.h" /**\addtogroup plugincommon * @{ */ // Set to 'true' to force state changing commands. For debugging. #define FORCE_STATE_CHANGE false/*true*/ #define DECLARE_CACHED_BOOL(name) \ bool enabled_##name; #define IMPLEMENT_CACHED_BOOL(name) \ void Enable_##name () \ { \ if (!currentContext->enabled_##name || FORCE_STATE_CHANGE) \ { \ currentContext->enabled_##name = true; \ glEnable (name); \ } \ } \ void Disable_##name () \ { \ if (currentContext->enabled_##name || FORCE_STATE_CHANGE) { \ currentContext->enabled_##name = false; \ glDisable (name); \ } \ } \ bool IsEnabled_##name () const \ { \ return currentContext->enabled_##name; \ } #define DECLARE_CACHED_BOOL_IMAGEUNIT(name) \ AutoArray<bool> enabled_##name; #define IMPLEMENT_CACHED_BOOL_IMAGEUNIT(name) \ void Enable_##name () \ { \ const int currentUnit = currentContext->currentImageUnit; \ if (!currentContext->enabled_##name[currentUnit] || FORCE_STATE_CHANGE) \ { \ ActivateImageUnit (); \ currentContext->enabled_##name[currentUnit] = true; \ glEnable (name); \ } \ } \ void Disable_##name () \ { \ const int currentUnit = currentContext->currentImageUnit; \ if (currentContext->enabled_##name[currentUnit] || FORCE_STATE_CHANGE) \ { \ ActivateImageUnit (); \ currentContext->enabled_##name[currentUnit] = false; \ glDisable (name); \ } \ } \ bool IsEnabled_##name () const \ { \ const int currentUnit = currentContext->currentImageUnit; \ return currentContext->enabled_##name[currentUnit]; \ } #define DECLARE_CACHED_PARAMETER_1(func, name, type1, param1) \ type1 parameter_##param1; #define IMPLEMENT_CACHED_PARAMETER_1(func, name, type1, param1) \ void Set##name (type1 param1, bool forced = false) \ { \ if (forced || (param1 != currentContext->parameter_##param1) || FORCE_STATE_CHANGE) \ { \ currentContext->parameter_##param1 = param1; \ func (param1); \ } \ } \ void Get##name (type1 & param1) const\ { \ param1 = currentContext->parameter_##param1; \ } #define DECLARE_CACHED_PARAMETER_2(func, name, type1, param1, type2, param2) \ type1 parameter_##param1; \ type2 parameter_##param2; #define IMPLEMENT_CACHED_PARAMETER_2(func, name, type1, param1, type2, param2) \ void Set##name (type1 param1, type2 param2, bool forced = false) \ { \ if (forced || (param1 != currentContext->parameter_##param1) || \ (param2 != currentContext->parameter_##param2) || FORCE_STATE_CHANGE) \ { \ currentContext->parameter_##param1 = param1; \ currentContext->parameter_##param2 = param2; \ func (param1, param2); \ } \ } \ void Get##name (type1 & param1, type2 & param2) const\ { \ param1 = currentContext->parameter_##param1; \ param2 = currentContext->parameter_##param2; \ } #define DECLARE_CACHED_PARAMETER_3(func, name, type1, param1, type2, param2, type3, param3) \ type1 parameter_##param1; \ type2 parameter_##param2; \ type3 parameter_##param3; #define IMPLEMENT_CACHED_PARAMETER_3(func, name, type1, param1, type2, param2, type3, param3) \ void Set##name (type1 param1, type2 param2, type3 param3, bool forced = false) \ { \ if (forced || (param1 != currentContext->parameter_##param1) \ || (param2 != currentContext->parameter_##param2) \ || (param3 != currentContext->parameter_##param3) || FORCE_STATE_CHANGE) \ { \ currentContext->parameter_##param1 = param1; \ currentContext->parameter_##param2 = param2; \ currentContext->parameter_##param3 = param3; \ func (param1, param2, param3); \ } \ } \ void Get##name (type1 &param1, type2 & param2, type3 & param3) const\ { \ param1 = currentContext->parameter_##param1; \ param2 = currentContext->parameter_##param2; \ param3 = currentContext->parameter_##param3; \ } #define DECLARE_CACHED_PARAMETER_3_BUF(func, name, type1, param1, type2, param2, type3, param3, vbo) \ type1 parameter_##param1; \ type2 parameter_##param2; \ type3 parameter_##param3; \ GLuint parameter_##vbo; #define IMPLEMENT_CACHED_PARAMETER_3_BUF(func, name, type1, param1, type2, param2, type3, param3, vbo) \ void Set##name (type1 param1, type2 param2, type3 param3, bool forced = false) \ { \ if (forced || (param1 != currentContext->parameter_##param1) \ || (param2 != currentContext->parameter_##param2) \ || (param3 != currentContext->parameter_##param3) \ || (currentContext->currentBufferID[csGLStateCacheContext::boElementArray] \ != currentContext->parameter_##vbo) \ || FORCE_STATE_CHANGE) \ { \ currentContext->parameter_##param1 = param1; \ currentContext->parameter_##param2 = param2; \ currentContext->parameter_##param3 = param3; \ if (extmgr->CS_GL_ARB_vertex_buffer_object) \ { \ ApplyBufferBinding (csGLStateCacheContext::boElementArray); \ currentContext->parameter_##vbo \ = currentContext->currentBufferID[csGLStateCacheContext::boElementArray];\ } \ func (param1, param2, param3); \ } \ } \ void Get##name (type1 &param1, type2 & param2, type3 & param3) const\ { \ param1 = currentContext->parameter_##param1; \ param2 = currentContext->parameter_##param2; \ param3 = currentContext->parameter_##param3; \ } #define DECLARE_CACHED_PARAMETER_4(func, name, type1, param1, \ type2, param2, type3, param3, type4, param4) \ type1 parameter_##param1; \ type2 parameter_##param2; \ type3 parameter_##param3; \ type4 parameter_##param4; #define IMPLEMENT_CACHED_PARAMETER_4(func, name, type1, param1, \ type2, param2, type3, param3, type4, param4) \ void Set##name (type1 param1, type2 param2, type3 param3, type4 param4, \ bool forced = false) \ { \ if (forced || (param1 != currentContext->parameter_##param1) || \ (param2 != currentContext->parameter_##param2) || \ (param3 != currentContext->parameter_##param3) || \ (param4 != currentContext->parameter_##param4) || FORCE_STATE_CHANGE) \ { \ currentContext->parameter_##param1 = param1; \ currentContext->parameter_##param2 = param2; \ currentContext->parameter_##param3 = param3; \ currentContext->parameter_##param4 = param4; \ func (param1, param2, param3, param4); \ } \ } \ void Get##name (type1 &param1, type2 & param2, type3 & param3, type4& param4) const\ { \ param1 = currentContext->parameter_##param1; \ param2 = currentContext->parameter_##param2; \ param3 = currentContext->parameter_##param3; \ param4 = currentContext->parameter_##param4; \ } #define DECLARE_CACHED_PARAMETER_4_BUF(func, name, type1, param1, \ type2, param2, type3, param3, type4, param4, vbo) \ type1 parameter_##param1; \ type2 parameter_##param2; \ type3 parameter_##param3; \ type4 parameter_##param4; \ GLuint parameter_##vbo; #define IMPLEMENT_CACHED_PARAMETER_4_BUF(func, name, type1, param1, \ type2, param2, type3, param3, type4, param4, vbo) \ void Set##name (type1 param1, type2 param2, type3 param3, type4 param4, \ bool forced = false) \ { \ if (forced || (param1 != currentContext->parameter_##param1) || \ (param2 != currentContext->parameter_##param2) || \ (param3 != currentContext->parameter_##param3) || \ (param4 != currentContext->parameter_##param4) \ || (currentContext->currentBufferID[csGLStateCacheContext::boElementArray] \ != currentContext->parameter_##vbo) \ || FORCE_STATE_CHANGE) \ { \ currentContext->parameter_##param1 = param1; \ currentContext->parameter_##param2 = param2; \ currentContext->parameter_##param3 = param3; \ currentContext->parameter_##param4 = param4; \ if (extmgr->CS_GL_ARB_vertex_buffer_object) \ { \ ApplyBufferBinding (csGLStateCacheContext::boElementArray); \ currentContext->parameter_##vbo = \ currentContext->currentBufferID[csGLStateCacheContext::boElementArray];\ } \ func (param1, param2, param3, param4); \ } \ } \ void Get##name (type1 &param1, type2 & param2, type3 & param3, type4& param4) const\ { \ param1 = currentContext->parameter_##param1; \ param2 = currentContext->parameter_##param2; \ param3 = currentContext->parameter_##param3; \ param4 = currentContext->parameter_##param4; \ } #define DECLARE_CACHED_CLIENT_STATE(name) \ bool enabled_##name; #define IMPLEMENT_CACHED_CLIENT_STATE(name) \ void Enable_##name () \ { \ if (!currentContext->enabled_##name || FORCE_STATE_CHANGE) \ { \ currentContext->enabled_##name = true; \ glEnableClientState (name); \ } \ } \ void Disable_##name () \ { \ if (currentContext->enabled_##name || FORCE_STATE_CHANGE) { \ currentContext->enabled_##name = false; \ glDisableClientState (name); \ } \ } \ bool IsEnabled_##name () const \ { \ return currentContext->enabled_##name; \ } #define DECLARE_CACHED_CLIENT_STATE_TCS(name) \ AutoArray<bool> enabled_##name; #define IMPLEMENT_CACHED_CLIENT_STATE_TCS(name) \ void Enable_##name () \ { \ const int currentUnit = currentContext->currentTCUnit; \ if (!currentContext->enabled_##name[currentUnit] || FORCE_STATE_CHANGE) \ { \ ActivateTCUnit (activateTexCoord); \ currentContext->enabled_##name[currentUnit] = true; \ glEnableClientState (name); \ } \ } \ void Disable_##name () \ { \ const int currentUnit = currentContext->currentTCUnit; \ if (currentContext->enabled_##name[currentUnit] || FORCE_STATE_CHANGE) \ { \ ActivateTCUnit (activateTexCoord); \ currentContext->enabled_##name[currentUnit] = false; \ glDisableClientState (name); \ } \ } \ bool IsEnabled_##name () const \ { \ const int currentUnit = currentContext->currentTCUnit; \ return currentContext->enabled_##name[currentUnit]; \ } #define DECLARE_CACHED_PARAMETER_1_LAYER(func, name, type1, param1) \ AutoArray<type1> parameter_##param1; #define IMPLEMENT_CACHED_PARAMETER_1_LAYER(func, name, type1, param1, limit) \ void Set##name (type1 param1, bool forced = false) \ { \ const int currentUnit = currentContext->currentUnit; \ if (forced || \ (param1 != currentContext->parameter_##param1[currentUnit] \ || FORCE_STATE_CHANGE)) \ { \ ActivateTU (); \ currentContext->parameter_##param1[currentUnit] = param1; \ func (param1); \ } \ } \ void Get##name (type1 &param1) const\ { \ const int currentUnit = currentContext->currentUnit; \ param1 = currentContext->parameter_##param1[currentUnit]; \ } #define DECLARE_CACHED_PARAMETER_2_LAYER(func, name, type1, param1, \ type2, param2) \ AutoArray<type1> parameter_##param1; \ AutoArray<type2> parameter_##param2; #define IMPLEMENT_CACHED_PARAMETER_2_LAYER(func, name, type1, param1, \ type2, param2, limit) \ void Set##name (type1 param1, type2 param2, bool forced = false) \ { \ const int currentUnit = currentContext->currentUnit; \ if (forced || (param1 != currentContext->parameter_##param1[ \ currentUnit]) || \ (param2 != currentContext->parameter_##param2[ \ currentUnit]) \ || FORCE_STATE_CHANGE) \ { \ ActivateTU (); \ currentContext->parameter_##param1[currentUnit] = param1; \ currentContext->parameter_##param2[currentUnit] = param2; \ func (param1, param2); \ } \ } \ void Get##name (type1 &param1, type2 & param2) const\ { \ const int currentUnit = currentContext->currentUnit; \ param1 = currentContext->parameter_##param1[currentUnit]; \ param2 = currentContext->parameter_##param2[currentUnit]; \ } #define DECLARE_CACHED_PARAMETER_3_LAYER(func, name, type1, param1, \ type2, param2, type3, param3) \ AutoArray<type1> parameter_##param1; \ AutoArray<type2> parameter_##param2; \ AutoArray<type3> parameter_##param3; #define IMPLEMENT_CACHED_PARAMETER_3_LAYER(func, name, type1, param1, \ type2, param2, type3, param3, limit) \ void Set##name (type1 param1, type2 param2, type3 param3,\ bool forced = false) \ { \ const int currentUnit = currentContext->currentUnit; \ if (forced || (param1 != currentContext->parameter_##param1[ \ currentUnit]) || \ (param2 != currentContext->parameter_##param2[ \ currentUnit]) || \ (param3 != currentContext->parameter_##param3[ \ currentUnit]) \ || FORCE_STATE_CHANGE) \ { \ ActivateTU (); \ currentContext->parameter_##param1[currentUnit] = param1; \ currentContext->parameter_##param2[currentUnit] = param2; \ currentContext->parameter_##param3[currentUnit] = param3; \ func (param1, param2, param3); \ } \ } \ void Get##name (type1 &param1, type2 & param2, type3 & param3) const\ { \ const int currentUnit = currentContext->currentUnit; \ param1 = currentContext->parameter_##param1[currentUnit]; \ param2 = currentContext->parameter_##param2[currentUnit]; \ param3 = currentContext->parameter_##param3[currentUnit]; \ } #define DECLARE_CACHED_PARAMETER_4_BUF_TCS(func, name, type1, param1, \ type2, param2, type3, param3, type4, param4, vbo) \ AutoArray<type1> parameter_##param1; \ AutoArray<type2> parameter_##param2; \ AutoArray<type3> parameter_##param3; \ AutoArray<type4> parameter_##param4; \ AutoArray<GLuint> parameter_##vbo; #define IMPLEMENT_CACHED_PARAMETER_4_BUF_TCS(func, name, type1, param1, \ type2, param2, type3, param3, type4, param4, vbo) \ void Set##name (type1 param1, type2 param2, type3 param3, type4 param4, \ bool forced = false) \ { \ const int currentUnit = currentContext->currentTCUnit; \ if (forced \ || (param1 != currentContext->parameter_##param1[currentUnit]) \ || (param2 != currentContext->parameter_##param2[currentUnit]) \ || (param3 != currentContext->parameter_##param3[currentUnit]) \ || (param4 != currentContext->parameter_##param4[currentUnit]) \ || (currentContext->currentBufferID[csGLStateCacheContext::boElementArray]\ != currentContext->parameter_##vbo[currentUnit]) \ || FORCE_STATE_CHANGE) \ { \ ActivateTCUnit (activateTexCoord); \ currentContext->parameter_##param1[currentUnit] = param1; \ currentContext->parameter_##param2[currentUnit] = param2; \ currentContext->parameter_##param3[currentUnit] = param3; \ currentContext->parameter_##param4[currentUnit] = param4; \ if (extmgr->CS_GL_ARB_vertex_buffer_object) \ { \ ApplyBufferBinding (csGLStateCacheContext::boElementArray); \ currentContext->parameter_##vbo[currentUnit] = \ currentContext->currentBufferID[csGLStateCacheContext::boElementArray];\ } \ func (param1, param2, param3, param4); \ } \ } \ void Get##name (type1 &param1, type2 & param2, type3 & param3, \ type4& param4) const \ { \ const int currentUnit = currentContext->currentTCUnit; \ param1 = currentContext->parameter_##param1[currentUnit]; \ param2 = currentContext->parameter_##param2[currentUnit]; \ param3 = currentContext->parameter_##param3[currentUnit]; \ param4 = currentContext->parameter_##param4[currentUnit]; \ } class CS_CSPLUGINCOMMON_GL_EXPORT csGLStateCacheContext { template<typename T> struct AutoArray { T* p; AutoArray() : p (0) {} ~AutoArray() { delete[] p; } void Setup (size_t n) { CS_ASSERT (p == 0); p = new T[n]; } T& operator[] (size_t idx) { return p[idx]; } }; public: csGLExtensionManager* extmgr; // Special caches AutoArray<GLuint> boundtexture; GLint numImageUnits; GLint numTexCoords; int currentImageUnit, currentTCUnit; int activeUnit[2]; enum { boElementArray = 0, boIndexArray, boPixelPack, boPixelUnpack, boCount }; GLuint currentBufferID[boCount]; GLuint activeBufferID[boCount]; static int GLBufferTargetToCacheIndex (GLenum target) { switch (target) { case GL_ARRAY_BUFFER_ARB: return boElementArray; case GL_ELEMENT_ARRAY_BUFFER_ARB: return boIndexArray; case GL_PIXEL_PACK_BUFFER_ARB: return boPixelPack; case GL_PIXEL_UNPACK_BUFFER_ARB: return boPixelUnpack; default: return -1; } } static GLenum CacheIndexToGLBufferTarget (int index) { static const GLenum localIndexToGLBufferTarget[boCount] = { GL_ARRAY_BUFFER_ARB, GL_ELEMENT_ARRAY_BUFFER_ARB, GL_PIXEL_PACK_BUFFER_ARB, GL_PIXEL_UNPACK_BUFFER_ARB }; return localIndexToGLBufferTarget[index]; } // BlendFunc/BlendFuncSeparate GLenum blend_sourceRGB; GLenum blend_destinationRGB; GLenum blend_sourceA; GLenum blend_destinationA; // Pixel storage GLint pixelUnpackAlignment; bool pixelUnpackSwapBytes; // Color clamp control enum { clampVertex = 0, clampFragment = 1, clampRead = 2, clampCount }; GLenum clampState[clampCount]; static int GLClampTargetToCacheIndex (GLenum target) { switch (target) { case GL_CLAMP_VERTEX_COLOR_ARB: return clampVertex; case GL_CLAMP_FRAGMENT_COLOR_ARB: return clampFragment; case GL_CLAMP_READ_COLOR_ARB: return clampRead; default: return -1; } } // Standardized caches DECLARE_CACHED_BOOL (GL_DEPTH_TEST) DECLARE_CACHED_BOOL (GL_BLEND) DECLARE_CACHED_BOOL (GL_DITHER) DECLARE_CACHED_BOOL (GL_STENCIL_TEST) DECLARE_CACHED_BOOL (GL_CULL_FACE) DECLARE_CACHED_BOOL (GL_POLYGON_OFFSET_FILL) DECLARE_CACHED_BOOL (GL_LIGHTING) DECLARE_CACHED_BOOL (GL_ALPHA_TEST) DECLARE_CACHED_BOOL (GL_SCISSOR_TEST) DECLARE_CACHED_BOOL (GL_TEXTURE_GEN_S) DECLARE_CACHED_BOOL (GL_TEXTURE_GEN_T) DECLARE_CACHED_BOOL (GL_TEXTURE_GEN_R) DECLARE_CACHED_BOOL (GL_TEXTURE_GEN_Q) DECLARE_CACHED_BOOL (GL_FOG) DECLARE_CACHED_BOOL (GL_COLOR_SUM_EXT) DECLARE_CACHED_BOOL (GL_VERTEX_PROGRAM_POINT_SIZE_ARB) DECLARE_CACHED_BOOL (GL_POINT_SPRITE_ARB) DECLARE_CACHED_BOOL (GL_TEXTURE_CUBE_MAP_SEAMLESS) DECLARE_CACHED_BOOL (GL_SAMPLE_ALPHA_TO_COVERAGE_ARB) DECLARE_CACHED_BOOL (GL_SAMPLE_ALPHA_TO_ONE_ARB) DECLARE_CACHED_BOOL_IMAGEUNIT (GL_TEXTURE_1D) DECLARE_CACHED_BOOL_IMAGEUNIT (GL_TEXTURE_2D) DECLARE_CACHED_BOOL_IMAGEUNIT (GL_TEXTURE_3D) DECLARE_CACHED_BOOL_IMAGEUNIT (GL_TEXTURE_CUBE_MAP) DECLARE_CACHED_BOOL_IMAGEUNIT (GL_TEXTURE_RECTANGLE_ARB) DECLARE_CACHED_PARAMETER_2 (glAlphaFunc, AlphaFunc, GLenum, alpha_func, GLclampf, alpha_ref) DECLARE_CACHED_PARAMETER_1 (glCullFace, CullFace, GLenum, cull_mode) DECLARE_CACHED_PARAMETER_1 (glDepthFunc, DepthFunc, GLenum, depth_func) DECLARE_CACHED_PARAMETER_1 (glDepthMask, DepthMask, GLboolean, depth_mask) DECLARE_CACHED_PARAMETER_1 (glShadeModel, ShadeModel, GLenum, shade_model) DECLARE_CACHED_PARAMETER_3 (glStencilFunc, StencilFunc, GLenum, stencil_func, GLint, stencil_ref, GLuint, stencil_mask) DECLARE_CACHED_PARAMETER_3 (glStencilOp, StencilOp, GLenum, stencil_fail, GLenum, stencil_zfail, GLenum, stencil_zpass) DECLARE_CACHED_PARAMETER_1 (glStencilMask, StencilMask, GLuint, maskl) DECLARE_CACHED_PARAMETER_4 (glColorMask, ColorMask, GLboolean, wmRed, \ GLboolean, wmGreen, GLboolean, wmBlue, GLboolean, wmAlpha) DECLARE_CACHED_CLIENT_STATE (GL_VERTEX_ARRAY) DECLARE_CACHED_CLIENT_STATE (GL_COLOR_ARRAY) DECLARE_CACHED_CLIENT_STATE (GL_SECONDARY_COLOR_ARRAY_EXT) DECLARE_CACHED_CLIENT_STATE (GL_NORMAL_ARRAY) DECLARE_CACHED_CLIENT_STATE_TCS (GL_TEXTURE_COORD_ARRAY) DECLARE_CACHED_PARAMETER_1 (glMatrixMode, MatrixMode, GLenum, matrixMode) DECLARE_CACHED_PARAMETER_4_BUF (glVertexPointer, VertexPointer, GLint, vsize, GLenum, vtype, GLsizei, vstride, GLvoid*, vpointer, vvbo) DECLARE_CACHED_PARAMETER_3_BUF (glNormalPointer, NormalPointer, GLenum, ntype, GLsizei, nstride, GLvoid*, npointer, nvbo) DECLARE_CACHED_PARAMETER_4_BUF (glColorPointer, ColorPointer, GLint, csize, GLenum, ctype, GLsizei, cstride, GLvoid*, cpointer, cvbo) DECLARE_CACHED_PARAMETER_4_BUF (extmgr->glSecondaryColorPointerEXT, SecondaryColorPointerEXT, GLint, scsize, GLenum, sctype, GLsizei, scstride, GLvoid*, scpointer, scvbo); DECLARE_CACHED_PARAMETER_4_BUF_TCS (glTexCoordPointer, TexCoordPointer, GLint, tsize, GLenum, ttype, GLsizei, tstride, GLvoid*, tpointer, tvbo) csGLStateCacheContext (csGLExtensionManager* extmgr); /** * Init cache. Does both retrieval of current GL state as well as setting * some states to known values. */ void InitCache(); }; /** * OpenGL state cache. * All state changes that are made often (possibly with the same value, ie * actually no change) or across plugins should be done through the cache. * \remarks * Since this class is passed directly between plugins the * code in this class cannot do memory allocations or * deallocations. The functions in this class will only * manipulate member variables. */ class csGLStateCache { enum { texServer = 0, texClient = 1 }; public: csGLExtensionManager* extmgr; csGLStateCacheContext* currentContext; csGLStateCache (csGLExtensionManager* extmgr) { csGLStateCache::extmgr = extmgr; currentContext = 0; } void SetContext (csGLStateCacheContext *context) { currentContext = context; } // Standardized caches IMPLEMENT_CACHED_BOOL (GL_DEPTH_TEST) IMPLEMENT_CACHED_BOOL (GL_BLEND) IMPLEMENT_CACHED_BOOL (GL_DITHER) IMPLEMENT_CACHED_BOOL (GL_STENCIL_TEST) IMPLEMENT_CACHED_BOOL (GL_CULL_FACE) IMPLEMENT_CACHED_BOOL (GL_POLYGON_OFFSET_FILL) IMPLEMENT_CACHED_BOOL (GL_LIGHTING) IMPLEMENT_CACHED_BOOL (GL_ALPHA_TEST) IMPLEMENT_CACHED_BOOL (GL_SCISSOR_TEST) IMPLEMENT_CACHED_BOOL (GL_TEXTURE_GEN_S) IMPLEMENT_CACHED_BOOL (GL_TEXTURE_GEN_T) IMPLEMENT_CACHED_BOOL (GL_TEXTURE_GEN_R) IMPLEMENT_CACHED_BOOL (GL_TEXTURE_GEN_Q) IMPLEMENT_CACHED_BOOL (GL_FOG) IMPLEMENT_CACHED_BOOL (GL_COLOR_SUM_EXT) IMPLEMENT_CACHED_BOOL (GL_VERTEX_PROGRAM_POINT_SIZE_ARB) IMPLEMENT_CACHED_BOOL (GL_POINT_SPRITE_ARB) IMPLEMENT_CACHED_BOOL (GL_TEXTURE_CUBE_MAP_SEAMLESS) IMPLEMENT_CACHED_BOOL (GL_SAMPLE_ALPHA_TO_COVERAGE_ARB) IMPLEMENT_CACHED_BOOL (GL_SAMPLE_ALPHA_TO_ONE_ARB) IMPLEMENT_CACHED_BOOL_IMAGEUNIT (GL_TEXTURE_1D) IMPLEMENT_CACHED_BOOL_IMAGEUNIT (GL_TEXTURE_2D) IMPLEMENT_CACHED_BOOL_IMAGEUNIT (GL_TEXTURE_3D) IMPLEMENT_CACHED_BOOL_IMAGEUNIT (GL_TEXTURE_CUBE_MAP) IMPLEMENT_CACHED_BOOL_IMAGEUNIT (GL_TEXTURE_RECTANGLE_ARB) IMPLEMENT_CACHED_PARAMETER_2 (glAlphaFunc, AlphaFunc, GLenum, alpha_func, GLclampf, alpha_ref) IMPLEMENT_CACHED_PARAMETER_1 (glCullFace, CullFace, GLenum, cull_mode) IMPLEMENT_CACHED_PARAMETER_1 (glDepthFunc, DepthFunc, GLenum, depth_func) IMPLEMENT_CACHED_PARAMETER_1 (glDepthMask, DepthMask, GLboolean, depth_mask) IMPLEMENT_CACHED_PARAMETER_1 (glShadeModel, ShadeModel, GLenum, shade_model) IMPLEMENT_CACHED_PARAMETER_3 (glStencilFunc, StencilFunc, GLenum, stencil_func, GLint, stencil_ref, GLuint, stencil_mask) IMPLEMENT_CACHED_PARAMETER_3 (glStencilOp, StencilOp, GLenum, stencil_fail, GLenum, stencil_zfail, GLenum, stencil_zpass) IMPLEMENT_CACHED_PARAMETER_1 (glStencilMask, StencilMask, GLuint, maskl) IMPLEMENT_CACHED_PARAMETER_4 (glColorMask, ColorMask, GLboolean, wmRed, \ GLboolean, wmGreen, GLboolean, wmBlue, GLboolean, wmAlpha) IMPLEMENT_CACHED_CLIENT_STATE (GL_VERTEX_ARRAY) IMPLEMENT_CACHED_CLIENT_STATE (GL_COLOR_ARRAY) IMPLEMENT_CACHED_CLIENT_STATE (GL_SECONDARY_COLOR_ARRAY_EXT) IMPLEMENT_CACHED_CLIENT_STATE (GL_NORMAL_ARRAY) IMPLEMENT_CACHED_CLIENT_STATE_TCS (GL_TEXTURE_COORD_ARRAY) IMPLEMENT_CACHED_PARAMETER_1 (glMatrixMode, MatrixMode, GLenum, matrixMode) IMPLEMENT_CACHED_PARAMETER_4_BUF (glVertexPointer, VertexPointer, GLint, vsize, GLenum, vtype, GLsizei, vstride, GLvoid*, vpointer, vvbo); IMPLEMENT_CACHED_PARAMETER_3_BUF (glNormalPointer, NormalPointer, GLenum, ntype, GLsizei, nstride, GLvoid*, npointer, nvbo); IMPLEMENT_CACHED_PARAMETER_4_BUF (glColorPointer, ColorPointer, GLint, csize, GLenum, ctype, GLsizei, cstride, GLvoid*, cpointer, cvbo); IMPLEMENT_CACHED_PARAMETER_4_BUF (extmgr->glSecondaryColorPointerEXT, SecondaryColorPointerExt, GLint, scsize, GLenum, sctype, GLsizei, scstride, GLvoid*, scpointer, scvbo); IMPLEMENT_CACHED_PARAMETER_4_BUF_TCS (glTexCoordPointer, TexCoordPointer, GLint, tsize, GLenum, ttype, GLsizei, tstride, GLvoid*, tpointer, tvbo); // Special caches void SetTexture (GLenum target, GLuint texture) { const int currentUnit = currentContext->currentImageUnit; if (texture != currentContext->boundtexture[currentUnit]) { ActivateImageUnit (); currentContext->boundtexture[currentUnit] = texture; glBindTexture (target, texture); } } GLuint GetTexture (GLenum /*target*/) { const int currentUnit = currentContext->currentImageUnit; return currentContext->boundtexture[currentUnit]; } GLuint GetTexture (GLenum /*target*/, int unit) { return currentContext->boundtexture[unit]; } /** * Select the currently active image unit. * \remarks Doesn't check whether the multitexture extension is actually * supported, this must be done in calling code. */ void SetCurrentImageUnit (int unit) { CS_ASSERT(unit < currentContext->numImageUnits); currentContext->currentImageUnit = unit; } /// Query active image unit. int GetCurrentImageUnit () { return currentContext->currentImageUnit; } /** * Activate the currently selected image unit. * Use this to bind textures. * \remarks Doesn't check whether the multitexture extension is actually * supported, this must be done in calling code. */ void ActivateImageUnit () { int currentUnit = currentContext->currentImageUnit; if (currentContext->activeUnit[texServer] != currentUnit) { GLuint tu = GL_TEXTURE0_ARB + currentUnit; extmgr->glActiveTextureARB (tu); currentContext->activeUnit[texServer] = currentUnit; } } /** * Select the currently active texture coordinate unit. * Use this to change state of texture coordinate arrays, * change texture matrices, texture environments, * texture coord generation and enabling/disabling textures. * \remarks Doesn't check whether the multitexture extension is actually * supported, this must be done in calling code. */ void SetCurrentTCUnit (int unit) { CS_ASSERT(unit < currentContext->numTexCoords); currentContext->currentTCUnit = unit; } /// Query active texture coordinate set. int GetCurrentTCUnit () { return currentContext->currentTCUnit; } /// Flag that the active TU should be used for setting texture coords static const int activateTexCoord = 1 << texClient; /// Flag that the active TU should be used when changing the texture matrix static const int activateMatrix = 1 << texServer; /// Flag that the active TU should be used when changing the texture environment static const int activateTexEnv = 1 << texServer; /** * Flag that the active TU should be used when changing the texture coord * generation parameters. */ static const int activateTexGen = 1 << texServer; /** * Activate the currently selected coordinate set. * \remarks Doesn't check whether the multitexture extension is actually * supported, this must be done in calling code. */ void ActivateTCUnit (uint usage) { int currentUnit = currentContext->currentTCUnit; for (int i = 0; i < 2; i++) { if (currentContext->activeUnit[i] != currentUnit) { GLuint tu = GL_TEXTURE0_ARB + currentUnit; if (usage & (1 << i)) { if (i == texClient) extmgr->glClientActiveTextureARB (tu); else extmgr->glActiveTextureARB (tu); currentContext->activeUnit[i] = currentUnit; } } } } void ApplyBufferBinding (int index) { GLuint id = currentContext->currentBufferID[index]; if (currentContext->activeBufferID[index] != id) { extmgr->glBindBufferARB ( csGLStateCacheContext::CacheIndexToGLBufferTarget (index), id); currentContext->activeBufferID[index] = id; } } /** * Bind a given VBO/PBO buffer. * \remarks Doesn't check whether the relevant buffer object extension is * actually supported, this must be done in calling code. */ void SetBufferARB (GLenum target, GLuint id, bool applyNow = false) { int index = csGLStateCacheContext::GLBufferTargetToCacheIndex (target); CS_ASSERT (index >= 0); currentContext->currentBufferID[index] = id; if (applyNow) ApplyBufferBinding (index); } /** * Get the currently bound VBO/PBO buffer. * \remarks Doesn't check whether the relevant buffer object extension is * actually supported, this must be done in calling code. */ GLuint GetBufferARB (GLenum target) { int index = csGLStateCacheContext::GLBufferTargetToCacheIndex (target); CS_ASSERT (index >= 0); return currentContext->currentBufferID[index]; } /**\name Blend functions * @{ */ void SetBlendFunc (GLenum blend_source, GLenum blend_destination, bool forced = false) { if (forced || (blend_source != currentContext->blend_sourceRGB) || (blend_source != currentContext->blend_sourceA) || (blend_destination != currentContext->blend_destinationRGB) || (blend_destination != currentContext->blend_destinationA) || FORCE_STATE_CHANGE) { currentContext->blend_sourceRGB = blend_source; currentContext->blend_sourceA = blend_source; currentContext->blend_destinationRGB = blend_destination; currentContext->blend_destinationA = blend_destination; glBlendFunc (blend_source, blend_destination); } } void GetBlendFunc (GLenum& blend_source, GLenum& blend_destination) const { blend_source = currentContext->blend_sourceRGB; blend_destination = currentContext->blend_destinationRGB; } void SetBlendFuncSeparate (GLenum blend_sourceRGB, GLenum blend_destinationRGB, GLenum blend_sourceA, GLenum blend_destinationA, bool forced = false) { if (forced || (blend_sourceRGB != currentContext->blend_sourceRGB) || (blend_sourceA != currentContext->blend_sourceA) || (blend_destinationRGB != currentContext->blend_destinationRGB) || (blend_destinationA != currentContext->blend_destinationA) || FORCE_STATE_CHANGE) { currentContext->blend_sourceRGB = blend_sourceRGB; currentContext->blend_sourceA = blend_sourceA; currentContext->blend_destinationRGB = blend_destinationRGB; currentContext->blend_destinationA = blend_destinationA; extmgr->glBlendFuncSeparateEXT (blend_sourceRGB, blend_destinationRGB, blend_sourceA, blend_destinationA); } } void GetBlendFuncSeparate (GLenum& blend_sourceRGB, GLenum& blend_destinationRGB, GLenum& blend_sourceA, GLenum& blend_destinationA) const { blend_sourceRGB = currentContext->blend_sourceRGB; blend_destinationRGB = currentContext->blend_destinationRGB; blend_sourceA = currentContext->blend_sourceA; blend_destinationA = currentContext->blend_destinationA; } /** @} */ /**\name Pixel storage * @{ */ GLint GetPixelUnpackAlignment () { return currentContext->pixelUnpackAlignment; } void SetPixelUnpackAlignment (GLint alignment) { if (alignment != currentContext->pixelUnpackAlignment) { glPixelStorei (GL_UNPACK_ALIGNMENT, alignment); currentContext->pixelUnpackAlignment = alignment; } } bool GetPixelUnpackSwapBytes () { return currentContext->pixelUnpackSwapBytes; } void SetPixelUnpackSwapBytes (GLint swap) { bool swapAsbool = (swap != 0); if (swapAsbool != currentContext->pixelUnpackSwapBytes) { glPixelStorei (GL_UNPACK_SWAP_BYTES, (GLint)swap); currentContext->pixelUnpackSwapBytes = swapAsbool; } } /** @} */ /**\name Clamp control * @{ */ void SetClampColor (GLenum target, GLenum clamp) { int index = csGLStateCacheContext::GLClampTargetToCacheIndex (target); CS_ASSERT (index >= 0); if (clamp != currentContext->clampState[index]) { extmgr->glClampColorARB (target, clamp); currentContext->clampState[index] = clamp; } } GLenum GetClampColor (GLenum target) const { int index = csGLStateCacheContext::GLClampTargetToCacheIndex (target); CS_ASSERT (index >= 0); return currentContext->clampState[index]; } /** @} */ /// Query the number of texture image units supported by OpenGL GLint GetNumImageUnits() const { return currentContext->numImageUnits; } /// Query the number of texture coordinate sets supported by OpenGL GLint GetNumTexCoords() const { return currentContext->numTexCoords; } }; #undef IMPLEMENT_CACHED_BOOL #undef IMPLEMENT_CACHED_BOOL_IMAGEUNIT #undef IMPLEMENT_CACHED_PARAMETER_1 #undef IMPLEMENT_CACHED_PARAMETER_2 #undef IMPLEMENT_CACHED_PARAMETER_3 #undef IMPLEMENT_CACHED_PARAMETER_4 #undef IMPLEMENT_CACHED_PARAMETER_1_LAYER #undef IMPLEMENT_CACHED_PARAMETER_2_LAYER #undef IMPLEMENT_CACHED_PARAMETER_3_LAYER #undef IMPLEMENT_CACHED_PARAMETER_4_LAYER #undef IMPLEMENT_CACHED_CLIENT_STATE #undef IMPLEMENT_CACHED_CLIENT_STATE_LAYER #undef DECLARE_CACHED_BOOL #undef DECLARE_CACHED_BOOL_IMAGEUNIT #undef DECLARE_CACHED_PARAMETER_1 #undef DECLARE_CACHED_PARAMETER_2 #undef DECLARE_CACHED_PARAMETER_3 #undef DECLARE_CACHED_PARAMETER_4 #undef DECLARE_CACHED_PARAMETER_1_LAYER #undef DECLARE_CACHED_PARAMETER_2_LAYER #undef DECLARE_CACHED_PARAMETER_3_LAYER #undef DECLARE_CACHED_PARAMETER_4_LAYER #undef DECLARE_CACHED_CLIENT_STATE #undef DECLARE_CACHED_CLIENT_STATE_LAYER #undef FORCE_STATE_CHANGE /** @} */ #endif // __CS_GLSTATES_H__
crystalspace/CS
include/csplugincommon/opengl/glstates.h
C
lgpl-2.1
39,566
<?php /** * Generates media thumbnails for the video scrubber * * @package Site * @copyright 2013-2016 silverorange */ class SiteVideoScrubberImageGenerator extends SiteCommandLineApplication { // {{{ protected properties /** * The directory containing the media hierarchy * * @var string */ protected $media_file_base; /** * The directory containing the image hierarchy * * @var string */ protected $image_file_base; // }}} // {{{ public function setMediaFileBase() public function setMediaFileBase($media_file_base) { $this->media_file_base = $media_file_base; } // }}} // {{{ public function setImageFileBase() public function setImageFileBase($image_file_base) { $this->image_file_base = $image_file_base; } // }}} // {{{ public function run() public function run() { $this->initModules(); $this->parseCommandLineArguments(); if ($this->image_file_base === null) { throw new SiteCommandLineException('Image file base must be set'); } elseif ($this->media_file_base === null) { throw new SiteCommandLineException('Media file base must be set'); } $this->lock(); $pending_media = $this->getPendingMedia(); $this->debug(count($pending_media)." pending videos\n\n"); if (count($pending_media) > 0) { $encoding_shortname = $this->getMediaEncodingShortname( $pending_media); foreach ($pending_media as $media) { $this->debug("Media: ".$media->id."\n"); $media->setFileBase($this->media_file_base); $path = $this->getMediaPath($media, $encoding_shortname); if ($path === null) { continue; } $this->processMedia($media, $path); } } $this->unlock(); $this->debug("done\n"); } // }}} // {{{ protected function getPendingMedia() protected function getPendingMedia() { $sql = sprintf('select Media.* from Media inner join MediaSet on Media.media_set = MediaSet.id where %s order by Media.id', $this->getPendingMediaWhereClause()); $media = SwatDB::query($this->db, $sql, SwatDBClassMap::get('SiteVideoMediaWrapper')); return $media; } // }}} // {{{ protected function getPendingMediaWhereClause() protected function getPendingMediaWhereClause() { return 'Media.scrubber_image is null and Media.id in (select media from MediaEncodingBinding) and MediaSet.id in (select media_set from MediaEncoding where width is not null)'; } // }}} // {{{ protected function getMediaEncodingShortname() protected function getMediaEncodingShortname(SiteMediaWrapper $media) { $encoding_shortname = null; // TODO: switch to caching the encoding-shortname per media-set $m = $media->getFirst(); if ($m !== null) { foreach ($m->media_set->encodings as $encoding) { if ($encoding->width !== null && $encoding->width > $m->getScrubberImageWidth()) { $encoding_shortname = $encoding->shortname; } } } if ($encoding_shortname === null) { throw new SiteCommandLineException('No encodings big enough'); } return $encoding_shortname; } // }}} // {{{ protected function getMediaPath() protected function getMediaPath(SiteMedia $media, $encoding_shortname) { $path = null; if ($media->encodingExists($encoding_shortname)) { $path = $media->getFilePath($encoding_shortname); if (!file_exists($path)) { $message = "'".$path."' not found for media ".$media->id; $exception = new SiteCommandLineException($message); $exception->processAndContinue(); $this->debug($message."\n\n"); $path = null; } } else { $message = "Encoding '".$encoding_shortname."' not found for ". "media ".$media->id; $exception = new SiteCommandLineException($message); $exception->processAndContinue(); $this->debug($message."\n\n"); } return $path; } // }}} // {{{ protected function processMedia() protected function processMedia(SiteMedia $media, $path) { $movie = new FFmpegMovie($path); $grid = new Imagick(); $position = 0; $count = 0; $this->debug("Processing Frames:\n"); while ($position < $movie->getDuration() - 2) { $frame = $movie->getFrameAtTime($position); $img = $frame->toGDImage(); ob_start(); imagejpeg($img); $thumb = new Imagick(); $thumb->readImageBlob(ob_get_clean()); $thumb->resizeImage( $media->getScrubberImageWidth(), $media->getScrubberImageWidth(), Imagick::FILTER_LANCZOS, 1, true); $grid->addImage($thumb); $position += $media->getScrubberImageInterval(); $count++; $this->debug("\033[100D"); // reset the line $this->debug(sprintf('%d of %d (%d%%)', $count, $media->getDefaultScrubberImageCount(), $count / $media->getDefaultScrubberImageCount() * 100)); } $grid->resetIterator(); $output = $grid->appendImages(false); $output->setImageFormat('jpeg'); $tmp_file = tempnam(sys_get_temp_dir(), 'scrubber-image-'); $output->writeImage($tmp_file); if ($media->scrubber_image instanceof SiteVideoScrubberImage) { $media->scrubber_image->setFileBase($this->image_file_base); $media->scrubber_image->delete(); } $image = $this->getImageObject(); $image->process($tmp_file); $image->save(); $media->scrubber_image_count = $media->getDefaultScrubberImageCount(); $media->scrubber_image = $image; $media->save(); $this->debug("\nComposite Saved!\n\n"); } // }}} // {{{ protected function getImageObject() protected function getImageObject() { $class_name = SwatDBClassMap::get('SiteVideoScrubberImage'); $image_object = new $class_name(); $image_object->setDatabase($this->db); $image_object->setFileBase($this->image_file_base); return $image_object; } // }}} // boilerplate // {{{ protected function getDefaultModuleList() /** * Gets the list of modules to load for this search indexer * * @return array the list of modules to load for this application. * * @see SiteApplication::getDefaultModuleList() */ protected function getDefaultModuleList() { return array_merge( parent::getDefaultModuleList(), [ 'config' => SiteConfigModule::class, 'database' => SiteDatabaseModule::class, ] ); } // }}} // {{{ protected function configure() protected function configure(SiteConfigModule $config) { parent::configure($config); $this->database->dsn = $config->database->dsn; } // }}} } ?>
silverorange/site
Site/SiteVideoScrubberImageGenerator.php
PHP
lgpl-2.1
6,360
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.16"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>CQRS.NET: Cqrs.MongoDB.Events.MongoDbEventStore.MongoCollection</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(initResizable); /* @license-end */</script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ extensions: ["tex2jax.js"], jax: ["input/TeX","output/HTML-CSS"], }); </script><script type="text/javascript" async="async" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">CQRS.NET &#160;<span id="projectnumber">4.2</span> </div> <div id="projectbrief">A lightweight enterprise Function as a Service (FaaS) framework to write function based serverless and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.16 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(function(){initNavTree('classCqrs_1_1MongoDB_1_1Events_1_1MongoDbEventStore_af2dfb3af9b76e8b1cab0f7dc68cdc377.html','');}); /* @license-end */ </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <a id="af2dfb3af9b76e8b1cab0f7dc68cdc377"></a> <h2 class="memtitle"><span class="permalink"><a href="#af2dfb3af9b76e8b1cab0f7dc68cdc377">&#9670;&nbsp;</a></span>MongoCollection</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">IMongoCollection&lt;<a class="el" href="classCqrs_1_1MongoDB_1_1Events_1_1MongoDbEventData.html">MongoDbEventData</a>&gt; <a class="el" href="classCqrs_1_1MongoDB_1_1Events_1_1MongoDbEventStore.html">Cqrs.MongoDB.Events.MongoDbEventStore</a>&lt; TAuthenticationToken &gt;.MongoCollection</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">get</span><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Gets or sets the IMongoCollection&lt;TData&gt; </p> </div> </div> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1MongoDB.html">MongoDB</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1MongoDB_1_1Events.html">Events</a></li><li class="navelem"><a class="el" href="classCqrs_1_1MongoDB_1_1Events_1_1MongoDbEventStore.html">MongoDbEventStore</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.16 </li> </ul> </div> </body> </html>
Chinchilla-Software-Com/CQRS
wiki/docs/4.2/html/classCqrs_1_1MongoDB_1_1Events_1_1MongoDbEventStore_af2dfb3af9b76e8b1cab0f7dc68cdc377.html
HTML
lgpl-2.1
5,815
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2006 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: geom/IntersectionMatrix.java rev. 1.18 * **********************************************************************/ #ifndef GEOS_GEOM_INTERSECTIONMATRIX_H #define GEOS_GEOM_INTERSECTIONMATRIX_H #include <geos/export.h> #include <string> #include <geos/inline.h> namespace geos { namespace geom { // geos::geom /** \brief * Implementation of Dimensionally Extended Nine-Intersection Model * (DE-9IM) matrix. * * Dimensionally Extended Nine-Intersection Model (DE-9IM) matrix. * This class can used to represent both computed DE-9IM's (like 212FF1FF2) * as well as patterns for matching them (like T*T******). * * Methods are provided to: * * - set and query the elements of the matrix in a convenient fashion * - convert to and from the standard string representation * (specified in SFS Section 2.1.13.2). * - test to see if a matrix matches a given pattern string. * * For a description of the DE-9IM, see the * <a href="http://www.opengis.org/techno/specs.htm">OpenGIS Simple * Features Specification for SQL.</a> * * \todo Suggestion: add equal and not-equal operator to this class. */ class GEOS_DLL IntersectionMatrix { public: /** \brief * Default constructor. * * Creates an IntersectionMatrix with Dimension::False * dimension values ('F'). */ IntersectionMatrix(); /** \brief * Overriden constructor. * * Creates an IntersectionMatrix with the given dimension symbols. * * @param elements - reference to string containing pattern * of dimension values for elements. */ IntersectionMatrix(const std::string& elements); /** \brief * Copy constructor. * * Creates an IntersectionMatrix with the same elements as other. * * \todo Add assignment operator to make this class fully copyable. */ IntersectionMatrix(const IntersectionMatrix &other); /** \brief * Returns whether the elements of this IntersectionMatrix * satisfies the required dimension symbols. * * @param requiredDimensionSymbols - nine dimension symbols with * which to compare the elements of this IntersectionMatrix. * Possible values are {T, F, * , 0, 1, 2}. * @return true if this IntersectionMatrix matches the required * dimension symbols. */ bool matches(const std::string& requiredDimensionSymbols) const; /** \brief * Tests if given dimension value satisfies the dimension symbol. * * @param actualDimensionValue - valid dimension value stored in * the IntersectionMatrix. * Possible values are {TRUE, FALSE, DONTCARE, 0, 1, 2}. * @param requiredDimensionSymbol - a character used in the string * representation of an IntersectionMatrix. * Possible values are {T, F, * , 0, 1, 2}. * @return true if the dimension symbol encompasses the * dimension value. */ static bool matches(int actualDimensionValue, char requiredDimensionSymbol); /** \brief * Returns true if each of the actual dimension symbols satisfies * the corresponding required dimension symbol. * * @param actualDimensionSymbols - nine dimension symbols to validate. * Possible values are {T, F, * , 0, 1, 2}. * @param requiredDimensionSymbols - nine dimension symbols to * validate against. * Possible values are {T, F, * , 0, 1, 2}. * @return true if each of the required dimension symbols encompass * the corresponding actual dimension symbol. */ static bool matches(const std::string& actualDimensionSymbols, const std::string& requiredDimensionSymbols); /** \brief * Adds one matrix to another. * * Addition is defined by taking the maximum dimension value * of each position in the summand matrices. * * @param other - the matrix to add. * * \todo Why the 'other' matrix is not passed by const-reference? */ void add(IntersectionMatrix* other); /** \brief * Changes the value of one of this IntersectionMatrixs elements. * * @param row - the row of this IntersectionMatrix, indicating * the interior, boundary or exterior of the first Geometry. * @param column - the column of this IntersectionMatrix, * indicating the interior, boundary or exterior of the * second Geometry. * @param dimensionValue - the new value of the element. */ void set(int row, int column, int dimensionValue); /** \brief * Changes the elements of this IntersectionMatrix to the dimension * symbols in dimensionSymbols. * * @param dimensionSymbols - nine dimension symbols to which to * set this IntersectionMatrix elements. * Possible values are {T, F, * , 0, 1, 2}. */ void set(const std::string& dimensionSymbols); /** \brief * Changes the specified element to minimumDimensionValue if the * element is less. * * @param row - the row of this IntersectionMatrix, indicating * the interior, boundary or exterior of the first Geometry. * @param column - the column of this IntersectionMatrix, indicating * the interior, boundary or exterior of the second Geometry. * @param minimumDimensionValue - the dimension value with which * to compare the element. The order of dimension values * from least to greatest is {DONTCARE, TRUE, FALSE, 0, 1, 2}. */ void setAtLeast(int row, int column, int minimumDimensionValue); /** \brief * If row >= 0 and column >= 0, changes the specified element * to minimumDimensionValue if the element is less. * Does nothing if row <0 or column < 0. * * @param row - * the row of this IntersectionMatrix, * indicating the interior, boundary or exterior of the * first Geometry. * * @param column - * the column of this IntersectionMatrix, * indicating the interior, boundary or exterior of the * second Geometry. * * @param minimumDimensionValue - * the dimension value with which * to compare the element. The order of dimension values * from least to greatest is {DONTCARE, TRUE, FALSE, 0, 1, 2}. */ void setAtLeastIfValid(int row, int column, int minimumDimensionValue); /** \brief * For each element in this IntersectionMatrix, changes the element to * the corresponding minimum dimension symbol if the element is less. * * @param minimumDimensionSymbols - * nine dimension symbols with which * to compare the elements of this IntersectionMatrix. * The order of dimension values from least to greatest is * {DONTCARE, TRUE, FALSE, 0, 1, 2} . */ void setAtLeast(std::string minimumDimensionSymbols); /** \brief * Changes the elements of this IntersectionMatrix to dimensionValue. * * @param dimensionValue - * the dimension value to which to set this * IntersectionMatrix elements. Possible values {TRUE, * FALSE, DONTCARE, 0, 1, 2}. */ void setAll(int dimensionValue); /** \brief * Returns the value of one of this IntersectionMatrixs elements. * * @param row - * the row of this IntersectionMatrix, indicating the * interior, boundary or exterior of the first Geometry. * * @param column - * the column of this IntersectionMatrix, indicating the * interior, boundary or exterior of the second Geometry. * * @return the dimension value at the given matrix position. */ int get(int row, int column) const; /** \brief * Returns true if this IntersectionMatrix is FF*FF****. * * @return true if the two Geometrys related by this * IntersectionMatrix are disjoint. */ bool isDisjoint() const; /** \brief * Returns true if isDisjoint returns false. * * @return true if the two Geometrys related by this * IntersectionMatrix intersect. */ bool isIntersects() const; /** \brief * Returns true if this IntersectionMatrix is FT*******, F**T***** * or F***T****. * * @param dimensionOfGeometryA - the dimension of the first Geometry. * * @param dimensionOfGeometryB - the dimension of the second Geometry. * * @return true if the two Geometry's related by this * IntersectionMatrix touch, false if both Geometrys * are points. */ bool isTouches(int dimensionOfGeometryA, int dimensionOfGeometryB) const; /** \brief * Returns true if this IntersectionMatrix is: * - T*T****** (for a point and a curve, a point and an area or * a line and an area) * - 0******** (for two curves) * * @param dimensionOfGeometryA - he dimension of the first Geometry. * * @param dimensionOfGeometryB - the dimension of the second Geometry. * * @return true if the two Geometry's related by this * IntersectionMatrix cross. * * For this function to return true, the Geometrys must be a point * and a curve; a point and a surface; two curves; or a curve and * a surface. */ bool isCrosses(int dimensionOfGeometryA, int dimensionOfGeometryB) const; /** \brief * Returns true if this IntersectionMatrix is T*F**F***. * * @return true if the first Geometry is within the second. */ bool isWithin() const; /** \brief * Returns true if this IntersectionMatrix is T*****FF*. * * @return true if the first Geometry contains the second. */ bool isContains() const; /** \brief * Returns true if this IntersectionMatrix is T*F**FFF*. * * @param dimensionOfGeometryA - he dimension of the first Geometry. * @param dimensionOfGeometryB - the dimension of the second Geometry. * @return true if the two Geometry's related by this * IntersectionMatrix are equal; the Geometrys must have * the same dimension for this function to return true */ bool isEquals(int dimensionOfGeometryA, int dimensionOfGeometryB) const; /** \brief * Returns true if this IntersectionMatrix is: * - T*T***T** (for two points or two surfaces) * - 1*T***T** (for two curves) * * @param dimensionOfGeometryA - he dimension of the first Geometry. * @param dimensionOfGeometryB - the dimension of the second Geometry. * @return true if the two Geometry's related by this * IntersectionMatrix overlap. * * For this function to return true, the Geometrys must be two points, * two curves or two surfaces. */ bool isOverlaps(int dimensionOfGeometryA, int dimensionOfGeometryB) const; /** \brief * Returns true if this IntersectionMatrix is <code>T*****FF*</code> * or <code>*T****FF*</code> or <code>***T**FF*</code> * or <code>****T*FF*</code> * * @return <code>true</code> if the first Geometry covers the * second */ bool isCovers() const; /** \brief * Returns true if this IntersectionMatrix is <code>T*F**F***</code> * <code>*TF**F***</code> or <code>**FT*F***</code> * or <code>**F*TF***</code> * * @return <code>true</code> if the first Geometry is covered by * the second */ bool isCoveredBy() const; /** \brief * Transposes this IntersectionMatrix. * * @return this IntersectionMatrix as a convenience. * * \todo It returns 'this' pointer so why not to return const-pointer? * \todo May be it would be better to return copy of transposed matrix? */ IntersectionMatrix* transpose(); /** \brief * Returns a nine-character String representation of this * IntersectionMatrix. * * @return the nine dimension symbols of this IntersectionMatrix * in row-major order. */ std::string toString() const; private: static const int firstDim; // = 3; static const int secondDim; // = 3; // Internal buffer for 3x3 matrix. int matrix[3][3]; }; // class IntersectionMatrix GEOS_DLL std::ostream& operator<< (std::ostream&os, const IntersectionMatrix& im); } // namespace geos::geom } // namespace geos //#ifdef GEOS_INLINE //# include "geos/geom/IntersectionMatrix.inl" //#endif #endif // ndef GEOS_GEOM_INTERSECTIONMATRIX_H /********************************************************************** * $Log$ * Revision 1.6 2006/05/17 17:41:10 strk * Added output operator + test * * Revision 1.5 2006/05/17 17:24:17 strk * Added port info, fixed isCoveredBy() comment. * * Revision 1.4 2006/05/17 17:20:10 strk * added isCovers() and isCoveredBy() public methods to IntersectionMatrix and associated tests. * * Revision 1.3 2006/04/09 01:46:13 mloskot * [SORRY] Added comments for doxygen based on JTS docs. Added row/col dimension consts. Added asserts in functions to check if given row/col is in range. * * Revision 1.2 2006/03/24 09:52:41 strk * USE_INLINE => GEOS_INLINE * * Revision 1.1 2006/03/09 16:46:49 strk * geos::geom namespace definition, first pass at headers split * **********************************************************************/
CartoDB/libgeos
include/geos/geom/IntersectionMatrix.h
C
lgpl-2.1
13,275
/* * Copyright (C) 2005 Marc Boris Duerner * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * 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 cxxtools_TypeTraits_h #define cxxtools_TypeTraits_h #include <cxxtools/api.h> #include <cxxtools/config.h> #include <cstddef> #include <stdint.h> namespace cxxtools { template <typename T> struct TypeTraitsBase { typedef T Value; typedef const T ConstValue; typedef T& Reference; typedef const T& ConstReference; typedef T* Pointer; typedef const T* ConstPointer; }; /** @brief Type-traits for for non-const value types Compile time type information (CTTI) is implemented in cxxtools by the means of TypeTraits. A number of specialisations allows compile type branching in gerneric code depending on the type. */ template <typename T> struct TypeTraits : public TypeTraitsBase<T> { static const unsigned int isConst = 0; static const unsigned int isPointer = 0; static const unsigned int isReference = 0; }; /** @brief Type-traits for for const value types */ template <typename T> struct TypeTraits<const T> : public TypeTraitsBase<T> { static const unsigned int isConst = 1; static const unsigned int isPointer = 0; static const unsigned int isReference = 0; }; /** @brief Type-traits for for non-const reference types */ template <typename T> struct TypeTraits<T&> : public TypeTraitsBase<T> { static const unsigned int isConst = 0; static const unsigned int isPointer = 0; static const unsigned int isReference = 1; }; /** @brief Type-traits for for const reference types */ template <typename T> struct TypeTraits<const T&> : public TypeTraitsBase<T> { static const unsigned int isConst = 1; static const unsigned int isPointer = 0; static const unsigned int isReference = 1; }; /** @brief Type-traits for for non-const pointer types */ template <typename T> struct TypeTraits<T*> : public TypeTraitsBase<T> { static const unsigned int isConst = 0; static const unsigned int isPointer = 1; static const unsigned int isReference = 0; }; /** @brief Type-traits for for const pointer types */ template <typename T> struct TypeTraits<const T*> : public TypeTraitsBase<T> { static const unsigned int isConst = 1; static const unsigned int isPointer = 1; static const unsigned int isReference = 0; }; /** @brief Type-traits for for fixed-size array types */ template <typename T, std::size_t N> struct TypeTraits<T[N]> : public TypeTraitsBase<T> { static const unsigned int isConst = 0; static const unsigned int isPointer = 1; static const unsigned int isReference = 0; }; /** @brief Type-traits for for void */ template <> struct TypeTraits<void> { typedef void Value; typedef void ConstType; typedef void Reference; typedef void ConstReference; typedef void* Pointer; typedef void* ConstPointer; static const unsigned int isConst = 0; static const unsigned int isPointer = 0; static const unsigned int isReference = 0; }; template <typename T> struct IntTraits {}; template <> struct IntTraits<signed char> { typedef unsigned char Unsigned; typedef signed char Signed; }; template <> struct IntTraits<unsigned char> { typedef unsigned char Unsigned; typedef signed char Signed; }; template <> struct IntTraits<short> { typedef unsigned short Unsigned; typedef signed short Signed; }; template <> struct IntTraits<unsigned short> { typedef unsigned short Unsigned; typedef signed short Signed; }; template <> struct IntTraits<int> { typedef unsigned int Unsigned; typedef signed int Signed; }; template <> struct IntTraits<unsigned int> { typedef unsigned int Unsigned; typedef signed int Signed; }; template <> struct IntTraits<long> { typedef unsigned long Unsigned; typedef signed long Signed; }; template <> struct IntTraits<unsigned long> { typedef unsigned long Unsigned; typedef signed long Signed; }; #ifdef HAVE_LONG_LONG template <> struct IntTraits<long long> { typedef unsigned long long Unsigned; typedef signed long long Signed; }; #endif #ifdef HAVE_UNSIGNED_LONG_LONG template <> struct IntTraits<unsigned long long> { typedef unsigned long long Unsigned; typedef signed long long Signed; }; #endif } // !namespace cxxtools #endif
OlafRadicke/cxxtools
include/cxxtools/typetraits.h
C
lgpl-2.1
6,207
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited 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. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * HighLowRendererTests.java * ------------------------- * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 25-Mar-2003 : Version 1 (DG); * 22-Oct-2003 : Added hashCode test (DG); * 01-Nov-2005 : Added tests for new fields (DG); * 17-Aug-2006 : Added testFindRangeBounds() method (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * 29-Apr-2008 : Extended testEquals() for new field (DG); * */ package org.jfree.chart.renderer.xy.junit; import java.awt.Color; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.Date; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.renderer.xy.HighLowRenderer; import org.jfree.data.Range; import org.jfree.data.xy.DefaultOHLCDataset; import org.jfree.data.xy.OHLCDataItem; import org.jfree.data.xy.OHLCDataset; import org.jfree.util.PublicCloneable; /** * Tests for the {@link HighLowRenderer} class. */ public class HighLowRendererTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(HighLowRendererTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public HighLowRendererTests(String name) { super(name); } /** * Check that the equals() method distinguishes all fields. */ public void testEquals() { HighLowRenderer r1 = new HighLowRenderer(); HighLowRenderer r2 = new HighLowRenderer(); assertEquals(r1, r2); // drawOpenTicks r1.setDrawOpenTicks(false); assertFalse(r1.equals(r2)); r2.setDrawOpenTicks(false); assertTrue(r1.equals(r2)); // drawCloseTicks r1.setDrawCloseTicks(false); assertFalse(r1.equals(r2)); r2.setDrawCloseTicks(false); assertTrue(r1.equals(r2)); // openTickPaint r1.setOpenTickPaint(Color.red); assertFalse(r1.equals(r2)); r2.setOpenTickPaint(Color.red); assertTrue(r1.equals(r2)); // closeTickPaint r1.setCloseTickPaint(Color.blue); assertFalse(r1.equals(r2)); r2.setCloseTickPaint(Color.blue); assertTrue(r1.equals(r2)); // tickLength r1.setTickLength(99.9); assertFalse(r1.equals(r2)); r2.setTickLength(99.9); assertTrue(r1.equals(r2)); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashcode() { HighLowRenderer r1 = new HighLowRenderer(); HighLowRenderer r2 = new HighLowRenderer(); assertTrue(r1.equals(r2)); int h1 = r1.hashCode(); int h2 = r2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ public void testCloning() { HighLowRenderer r1 = new HighLowRenderer(); r1.setCloseTickPaint(Color.green); HighLowRenderer r2 = null; try { r2 = (HighLowRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); } /** * Verify that this class implements {@link PublicCloneable}. */ public void testPublicCloneable() { HighLowRenderer r1 = new HighLowRenderer(); assertTrue(r1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { HighLowRenderer r1 = new HighLowRenderer(); r1.setCloseTickPaint(Color.green); HighLowRenderer r2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(r1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); r2 = (HighLowRenderer) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(r1, r2); } /** * Some checks for the findRangeBounds() method. */ public void testFindRangeBounds() { HighLowRenderer renderer = new HighLowRenderer(); OHLCDataItem item1 = new OHLCDataItem(new Date(1L), 2.0, 4.0, 1.0, 3.0, 100); OHLCDataset dataset = new DefaultOHLCDataset("S1", new OHLCDataItem[] {item1}); Range range = renderer.findRangeBounds(dataset); assertEquals(new Range(1.0, 4.0), range); OHLCDataItem item2 = new OHLCDataItem(new Date(1L), -1.0, 3.0, -1.0, 3.0, 100); dataset = new DefaultOHLCDataset("S1", new OHLCDataItem[] {item1, item2}); range = renderer.findRangeBounds(dataset); assertEquals(new Range(-1.0, 4.0), range); // try an empty dataset - should return a null range dataset = new DefaultOHLCDataset("S1", new OHLCDataItem[] {}); range = renderer.findRangeBounds(dataset); assertNull(range); // try a null dataset - should return a null range range = renderer.findRangeBounds(null); assertNull(range); } }
integrated/jfreechart
tests/org/jfree/chart/renderer/xy/junit/HighLowRendererTests.java
Java
lgpl-2.1
7,020
# -*- coding: utf-8 -*- # *************************************************************************** # * * # * Copyright (c) 2015 Dan Falck <[email protected]> * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * 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 Library 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 * # * * # *************************************************************************** ''' A CNC machine object to define how code is posted ''' import FreeCAD import Path import PathScripts from PathScripts import PathUtils from PySide import QtCore, QtGui import os import sys # Qt tanslation handling try: _encoding = QtGui.QApplication.UnicodeUTF8 def translate(context, text, disambig=None): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def translate(context, text, disambig=None): return QtGui.QApplication.translate(context, text, disambig) class Machine: def __init__(self, obj): obj.addProperty("App::PropertyString", "MachineName", "Base", "Name of the Machine that will use the CNC program") obj.addProperty("App::PropertyFile", "PostProcessor", "CodeOutput", "Select the Post Processor file for this machine") obj.addProperty("App::PropertyEnumeration", "MachineUnits", "CodeOutput", "Units that the machine works in, ie Metric or Inch") obj.MachineUnits = ['Metric', 'Inch'] obj.addProperty("Path::PropertyTooltable", "Tooltable", "Base", "The tooltable used for this CNC program") obj.addProperty("App::PropertyDistance", "X_Max", "Limits", "The Maximum distance in X the machine can travel") obj.addProperty("App::PropertyDistance", "Y_Max", "Limits", "The Maximum distance in X the machine can travel") obj.addProperty("App::PropertyDistance", "Z_Max", "Limits", "The Maximum distance in X the machine can travel") obj.addProperty("App::PropertyDistance", "X_Min", "Limits", "The Minimum distance in X the machine can travel") obj.addProperty("App::PropertyDistance", "Y_Min", "Limits", "The Minimum distance in X the machine can travel") obj.addProperty("App::PropertyDistance", "Z_Min", "Limits", "The Minimum distance in X the machine can travel") obj.addProperty("App::PropertyDistance", "X", "HomePosition", "Home position of machine, in X (mainly for visualization)") obj.addProperty("App::PropertyDistance", "Y", "HomePosition", "Home position of machine, in Y (mainly for visualization)") obj.addProperty("App::PropertyDistance", "Z", "HomePosition", "Home position of machine, in Z (mainly for visualization)") obj.Proxy = self mode = 2 obj.setEditorMode('Placement', mode) def execute(self, obj): obj.Label = "Machine_" + str(obj.MachineName) # need to filter this path out in post- only for visualization #gcode = 'G0 X' + str(obj.X.Value) + ' Y' + \ # str(obj.Y.Value) + ' Z' + str(obj.Z.Value) gcode = '(' + str(obj.Label) + ')' obj.Path = Path.Path(gcode) def onChanged(self, obj, prop): mode = 2 obj.setEditorMode('Placement', mode) if prop == "PostProcessor": sys.path.append(os.path.split(obj.PostProcessor)[0]) lessextn = os.path.splitext(obj.PostProcessor)[0] postname = os.path.split(lessextn)[1] exec "import %s as current_post" % postname if hasattr(current_post, "UNITS"): if current_post.UNITS == "G21": obj.MachineUnits = "Metric" else: obj.MachineUnits = "Inch" if hasattr(current_post, "MACHINE_NAME"): obj.MachineName = current_post.MACHINE_NAME if hasattr(current_post, "CORNER_MAX"): obj.X_Max = current_post.CORNER_MAX['x'] obj.Y_Max = current_post.CORNER_MAX['y'] obj.Z_Max = current_post.CORNER_MAX['z'] if hasattr(current_post, "CORNER_MIN"): obj.X_Min = current_post.CORNER_MIN['x'] obj.Y_Min = current_post.CORNER_MIN['y'] obj.Z_Min = current_post.CORNER_MIN['z'] if prop == "Tooltable": proj = PathUtils.findProj() for g in proj.Group: if not(isinstance(g.Proxy, PathScripts.PathMachine.Machine)): g.touch() class _ViewProviderMachine: def __init__(self, vobj): vobj.Proxy = self vobj.addProperty("App::PropertyBool", "ShowLimits", "Path", translate( "ShowMinMaxTravel", "Switch the machine max and minimum travel bounding box on/off")) mode = 2 vobj.setEditorMode('LineWidth', mode) vobj.setEditorMode('MarkerColor', mode) vobj.setEditorMode('NormalColor', mode) vobj.setEditorMode('ShowFirstRapid', 0) vobj.setEditorMode('DisplayMode', mode) vobj.setEditorMode('BoundingBox', mode) vobj.setEditorMode('Selectable', mode) def __getstate__(self): # mandatory return None def __setstate__(self, state): # mandatory return None def getIcon(self): # optional return ":/icons/Path-Machine.svg" def attach(self, vobj): from pivy import coin self.extentsBox = coin.SoSeparator() vobj.RootNode.addChild(self.extentsBox) def onChanged(self, vobj, prop): if prop == "ShowLimits": self.extentsBox.removeAllChildren() if vobj.ShowLimits and hasattr(vobj, "Object"): from pivy import coin parent = coin.SoType.fromName( "SoSkipBoundingGroup").createInstance() self.extentsBox.addChild(parent) # set pattern pattern = FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/Mod/Part").GetInt("GridLinePattern", 0x0f0f) defStyle = coin.SoDrawStyle() defStyle.lineWidth = 1 defStyle.linePattern = pattern parent.addChild(defStyle) # set color c = FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/Mod/Path").GetUnsigned("DefaultExtentsColor", 3418866943) r = float((c >> 24) & 0xFF) / 255.0 g = float((c >> 16) & 0xFF) / 255.0 b = float((c >> 8) & 0xFF) / 255.0 color = coin.SoBaseColor() parent.addChild(color) # set boundbox extents = coin.SoType.fromName( "SoFCBoundingBox").createInstance() extents.coordsOn.setValue(False) extents.dimensionsOn.setValue(False) XMax, YMax, ZMax = vobj.Object.X_Max.Value, vobj.Object.Y_Max.Value, vobj.Object.Z_Max.Value XMin, YMin, ZMin = vobj.Object.X_Min.Value, vobj.Object.Y_Min.Value, vobj.Object.Z_Min.Value # UnitParams = FreeCAD.ParamGet( # "User parameter:BaseApp/Preferences/Units") extents.minBounds.setValue(XMax, YMax, ZMax) extents.maxBounds.setValue(XMin, YMin, ZMin) parent.addChild(extents) mode = 2 vobj.setEditorMode('LineWidth', mode) vobj.setEditorMode('MarkerColor', mode) vobj.setEditorMode('NormalColor', mode) vobj.setEditorMode('ShowFirstRapid', 0) vobj.setEditorMode('DisplayMode', mode) vobj.setEditorMode('BoundingBox', mode) vobj.setEditorMode('Selectable', mode) def updateData(self, vobj, prop): # optional # this is executed when a property of the APP OBJECT changes pass def setEdit(self, vobj, mode=0): # optional # this is executed when the object is double-clicked in the tree pass def unsetEdit(self, vobj, mode=0): # optional # this is executed when the user cancels or terminates edit mode pass def doubleClicked(self, vobj): from PathScripts import TooltableEditor TooltableEditor.edit(vobj.Object.Name) class CommandPathMachine: def GetResources(self): return {'Pixmap': 'Path-Machine', 'MenuText': QtCore.QT_TRANSLATE_NOOP("PathMachine", "Machine Object"), 'Accel': "P, M", 'ToolTip': QtCore.QT_TRANSLATE_NOOP("PathMachine", "Create a Machine object")} def IsActive(self): return FreeCAD.ActiveDocument is not None def Activated(self): FreeCAD.ActiveDocument.openTransaction( translate("PathMachine", "Create a Machine object")) CommandPathMachine.Create() FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute() @staticmethod def Create(): obj = FreeCAD.ActiveDocument.addObject( "Path::FeaturePython", "Machine") Machine(obj) _ViewProviderMachine(obj.ViewObject) PathUtils.addToProject(obj) UnitParams = FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/Units") if UnitParams.GetInt('UserSchema') == 0: obj.MachineUnits = 'Metric' # metric mode else: obj.MachineUnits = 'Inch' obj.ViewObject.ShowFirstRapid = False return obj if FreeCAD.GuiUp: # register the FreeCAD command import FreeCADGui FreeCADGui.addCommand('Path_Machine', CommandPathMachine()) FreeCAD.Console.PrintLog("Loading PathMachine... done\n")
timthelion/FreeCAD
src/Mod/Path/PathScripts/PathMachine.py
Python
lgpl-2.1
10,868
<html lang="en"> <head> <title>Insn Splitting - GNU Compiler Collection (GCC) Internals</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="GNU Compiler Collection (GCC) Internals"> <meta name="generator" content="makeinfo 4.11"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Machine-Desc.html#Machine-Desc" title="Machine Desc"> <link rel="prev" href="Expander-Definitions.html#Expander-Definitions" title="Expander Definitions"> <link rel="next" href="Including-Patterns.html#Including-Patterns" title="Including Patterns"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- Copyright (C) 1988, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2010 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being ``Funding Free Software'', the Front-Cover Texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). A copy of the license is included in the section entitled ``GNU Free Documentation License''. (a) The FSF's Front-Cover Text is: A GNU Manual (b) The FSF's Back-Cover Text is: You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development.--> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <p> <a name="Insn-Splitting"></a> Next:&nbsp;<a rel="next" accesskey="n" href="Including-Patterns.html#Including-Patterns">Including Patterns</a>, Previous:&nbsp;<a rel="previous" accesskey="p" href="Expander-Definitions.html#Expander-Definitions">Expander Definitions</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Machine-Desc.html#Machine-Desc">Machine Desc</a> <hr> </div> <h3 class="section">16.16 Defining How to Split Instructions</h3> <p><a name="index-insn-splitting-3617"></a><a name="index-instruction-splitting-3618"></a><a name="index-splitting-instructions-3619"></a> There are two cases where you should specify how to split a pattern into multiple insns. On machines that have instructions requiring delay slots (see <a href="Delay-Slots.html#Delay-Slots">Delay Slots</a>) or that have instructions whose output is not available for multiple cycles (see <a href="Processor-pipeline-description.html#Processor-pipeline-description">Processor pipeline description</a>), the compiler phases that optimize these cases need to be able to move insns into one-instruction delay slots. However, some insns may generate more than one machine instruction. These insns cannot be placed into a delay slot. <p>Often you can rewrite the single insn as a list of individual insns, each corresponding to one machine instruction. The disadvantage of doing so is that it will cause the compilation to be slower and require more space. If the resulting insns are too complex, it may also suppress some optimizations. The compiler splits the insn if there is a reason to believe that it might improve instruction or delay slot scheduling. <p>The insn combiner phase also splits putative insns. If three insns are merged into one insn with a complex expression that cannot be matched by some <code>define_insn</code> pattern, the combiner phase attempts to split the complex pattern into two insns that are recognized. Usually it can break the complex pattern into two patterns by splitting out some subexpression. However, in some other cases, such as performing an addition of a large constant in two insns on a RISC machine, the way to split the addition into two insns is machine-dependent. <p><a name="index-define_005fsplit-3620"></a>The <code>define_split</code> definition tells the compiler how to split a complex insn into several simpler insns. It looks like this: <pre class="smallexample"> (define_split [<var>insn-pattern</var>] "<var>condition</var>" [<var>new-insn-pattern-1</var> <var>new-insn-pattern-2</var> ...] "<var>preparation-statements</var>") </pre> <p><var>insn-pattern</var> is a pattern that needs to be split and <var>condition</var> is the final condition to be tested, as in a <code>define_insn</code>. When an insn matching <var>insn-pattern</var> and satisfying <var>condition</var> is found, it is replaced in the insn list with the insns given by <var>new-insn-pattern-1</var>, <var>new-insn-pattern-2</var>, etc. <p>The <var>preparation-statements</var> are similar to those statements that are specified for <code>define_expand</code> (see <a href="Expander-Definitions.html#Expander-Definitions">Expander Definitions</a>) and are executed before the new RTL is generated to prepare for the generated code or emit some insns whose pattern is not fixed. Unlike those in <code>define_expand</code>, however, these statements must not generate any new pseudo-registers. Once reload has completed, they also must not allocate any space in the stack frame. <p>Patterns are matched against <var>insn-pattern</var> in two different circumstances. If an insn needs to be split for delay slot scheduling or insn scheduling, the insn is already known to be valid, which means that it must have been matched by some <code>define_insn</code> and, if <code>reload_completed</code> is nonzero, is known to satisfy the constraints of that <code>define_insn</code>. In that case, the new insn patterns must also be insns that are matched by some <code>define_insn</code> and, if <code>reload_completed</code> is nonzero, must also satisfy the constraints of those definitions. <p>As an example of this usage of <code>define_split</code>, consider the following example from <samp><span class="file">a29k.md</span></samp>, which splits a <code>sign_extend</code> from <code>HImode</code> to <code>SImode</code> into a pair of shift insns: <pre class="smallexample"> (define_split [(set (match_operand:SI 0 "gen_reg_operand" "") (sign_extend:SI (match_operand:HI 1 "gen_reg_operand" "")))] "" [(set (match_dup 0) (ashift:SI (match_dup 1) (const_int 16))) (set (match_dup 0) (ashiftrt:SI (match_dup 0) (const_int 16)))] " { operands[1] = gen_lowpart (SImode, operands[1]); }") </pre> <p>When the combiner phase tries to split an insn pattern, it is always the case that the pattern is <em>not</em> matched by any <code>define_insn</code>. The combiner pass first tries to split a single <code>set</code> expression and then the same <code>set</code> expression inside a <code>parallel</code>, but followed by a <code>clobber</code> of a pseudo-reg to use as a scratch register. In these cases, the combiner expects exactly two new insn patterns to be generated. It will verify that these patterns match some <code>define_insn</code> definitions, so you need not do this test in the <code>define_split</code> (of course, there is no point in writing a <code>define_split</code> that will never produce insns that match). <p>Here is an example of this use of <code>define_split</code>, taken from <samp><span class="file">rs6000.md</span></samp>: <pre class="smallexample"> (define_split [(set (match_operand:SI 0 "gen_reg_operand" "") (plus:SI (match_operand:SI 1 "gen_reg_operand" "") (match_operand:SI 2 "non_add_cint_operand" "")))] "" [(set (match_dup 0) (plus:SI (match_dup 1) (match_dup 3))) (set (match_dup 0) (plus:SI (match_dup 0) (match_dup 4)))] " { int low = INTVAL (operands[2]) &amp; 0xffff; int high = (unsigned) INTVAL (operands[2]) &gt;&gt; 16; if (low &amp; 0x8000) high++, low |= 0xffff0000; operands[3] = GEN_INT (high &lt;&lt; 16); operands[4] = GEN_INT (low); }") </pre> <p>Here the predicate <code>non_add_cint_operand</code> matches any <code>const_int</code> that is <em>not</em> a valid operand of a single add insn. The add with the smaller displacement is written so that it can be substituted into the address of a subsequent operation. <p>An example that uses a scratch register, from the same file, generates an equality comparison of a register and a large constant: <pre class="smallexample"> (define_split [(set (match_operand:CC 0 "cc_reg_operand" "") (compare:CC (match_operand:SI 1 "gen_reg_operand" "") (match_operand:SI 2 "non_short_cint_operand" ""))) (clobber (match_operand:SI 3 "gen_reg_operand" ""))] "find_single_use (operands[0], insn, 0) &amp;&amp; (GET_CODE (*find_single_use (operands[0], insn, 0)) == EQ || GET_CODE (*find_single_use (operands[0], insn, 0)) == NE)" [(set (match_dup 3) (xor:SI (match_dup 1) (match_dup 4))) (set (match_dup 0) (compare:CC (match_dup 3) (match_dup 5)))] " { /* <span class="roman">Get the constant we are comparing against, C, and see what it looks like sign-extended to 16 bits. Then see what constant could be XOR'ed with C to get the sign-extended value.</span> */ int c = INTVAL (operands[2]); int sextc = (c &lt;&lt; 16) &gt;&gt; 16; int xorv = c ^ sextc; operands[4] = GEN_INT (xorv); operands[5] = GEN_INT (sextc); }") </pre> <p>To avoid confusion, don't write a single <code>define_split</code> that accepts some insns that match some <code>define_insn</code> as well as some insns that don't. Instead, write two separate <code>define_split</code> definitions, one for the insns that are valid and one for the insns that are not valid. <p>The splitter is allowed to split jump instructions into sequence of jumps or create new jumps in while splitting non-jump instructions. As the central flowgraph and branch prediction information needs to be updated, several restriction apply. <p>Splitting of jump instruction into sequence that over by another jump instruction is always valid, as compiler expect identical behavior of new jump. When new sequence contains multiple jump instructions or new labels, more assistance is needed. Splitter is required to create only unconditional jumps, or simple conditional jump instructions. Additionally it must attach a <code>REG_BR_PROB</code> note to each conditional jump. A global variable <code>split_branch_probability</code> holds the probability of the original branch in case it was a simple conditional jump, &minus;1 otherwise. To simplify recomputing of edge frequencies, the new sequence is required to have only forward jumps to the newly created labels. <p><a name="index-define_005finsn_005fand_005fsplit-3621"></a>For the common case where the pattern of a define_split exactly matches the pattern of a define_insn, use <code>define_insn_and_split</code>. It looks like this: <pre class="smallexample"> (define_insn_and_split [<var>insn-pattern</var>] "<var>condition</var>" "<var>output-template</var>" "<var>split-condition</var>" [<var>new-insn-pattern-1</var> <var>new-insn-pattern-2</var> ...] "<var>preparation-statements</var>" [<var>insn-attributes</var>]) </pre> <p><var>insn-pattern</var>, <var>condition</var>, <var>output-template</var>, and <var>insn-attributes</var> are used as in <code>define_insn</code>. The <var>new-insn-pattern</var> vector and the <var>preparation-statements</var> are used as in a <code>define_split</code>. The <var>split-condition</var> is also used as in <code>define_split</code>, with the additional behavior that if the condition starts with &lsquo;<samp><span class="samp">&amp;&amp;</span></samp>&rsquo;, the condition used for the split will be the constructed as a logical &ldquo;and&rdquo; of the split condition with the insn condition. For example, from i386.md: <pre class="smallexample"> (define_insn_and_split "zero_extendhisi2_and" [(set (match_operand:SI 0 "register_operand" "=r") (zero_extend:SI (match_operand:HI 1 "register_operand" "0"))) (clobber (reg:CC 17))] "TARGET_ZERO_EXTEND_WITH_AND &amp;&amp; !optimize_size" "#" "&amp;&amp; reload_completed" [(parallel [(set (match_dup 0) (and:SI (match_dup 0) (const_int 65535))) (clobber (reg:CC 17))])] "" [(set_attr "type" "alu1")]) </pre> <p>In this case, the actual split condition will be &lsquo;<samp><span class="samp">TARGET_ZERO_EXTEND_WITH_AND &amp;&amp; !optimize_size &amp;&amp; reload_completed</span></samp>&rsquo;. <p>The <code>define_insn_and_split</code> construction provides exactly the same functionality as two separate <code>define_insn</code> and <code>define_split</code> patterns. It exists for compactness, and as a maintenance tool to prevent having to ensure the two patterns' templates match. </body></html>
dcuartielles/SmartWatch
build/linux/work/hardware/tools/arm/share/doc/gcc-arm-none-eabi/html/gccint/Insn-Splitting.html
HTML
lgpl-2.1
13,744
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the examples 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 "worker.h" #include "tools.h" Worker::Worker() { status = "Idle"; } void Worker::setStatusString(const QString &string) { status = string; emit statusStringChanged(status); } QString Worker::statusString() const { return status; }
RLovelett/qt
examples/activeqt/dotnet/wrapper/lib/worker.cpp
C++
lgpl-2.1
2,223
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>GTK+ 3 Reference Manual: GtkPrintSettings</title> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="index.html" title="GTK+ 3 Reference Manual"> <link rel="up" href="Printing.html" title="Printing"> <link rel="prev" href="GtkPrintContext.html" title="GtkPrintContext"> <link rel="next" href="GtkPageSetup.html" title="GtkPageSetup"> <meta name="generator" content="GTK-Doc V1.21.1 (XML mode)"> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table class="navigation" id="top" width="100%" summary="Navigation header" cellpadding="2" cellspacing="5"><tr valign="middle"> <td width="100%" align="left" class="shortcuts"> <a href="#" class="shortcut">Top</a><span id="nav_description">  <span class="dim">|</span>  <a href="#GtkPrintSettings.description" class="shortcut">Description</a></span><span id="nav_hierarchy">  <span class="dim">|</span>  <a href="#GtkPrintSettings.object-hierarchy" class="shortcut">Object Hierarchy</a></span> </td> <td><a accesskey="h" href="index.html"><img src="home.png" width="16" height="16" border="0" alt="Home"></a></td> <td><a accesskey="u" href="Printing.html"><img src="up.png" width="16" height="16" border="0" alt="Up"></a></td> <td><a accesskey="p" href="GtkPrintContext.html"><img src="left.png" width="16" height="16" border="0" alt="Prev"></a></td> <td><a accesskey="n" href="GtkPageSetup.html"><img src="right.png" width="16" height="16" border="0" alt="Next"></a></td> </tr></table> <div class="refentry"> <a name="GtkPrintSettings"></a><div class="titlepage"></div> <div class="refnamediv"><table width="100%"><tr> <td valign="top"> <h2><span class="refentrytitle"><a name="GtkPrintSettings.top_of_page"></a>GtkPrintSettings</span></h2> <p>GtkPrintSettings — Stores print settings</p> </td> <td class="gallery_image" valign="top" align="right"></td> </tr></table></div> <div class="refsect1"> <a name="GtkPrintSettings.functions"></a><h2>Functions</h2> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="functions_return"> <col class="functions_name"> </colgroup> <tbody> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <span class="c_punctuation">(</span><a class="link" href="GtkPrintSettings.html#GtkPrintSettingsFunc" title="GtkPrintSettingsFunc ()">*GtkPrintSettingsFunc</a><span class="c_punctuation">)</span> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="returnvalue">GtkPrintSettings</span></a> * </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-new" title="gtk_print_settings_new ()">gtk_print_settings_new</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="returnvalue">GtkPrintSettings</span></a> * </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-copy" title="gtk_print_settings_copy ()">gtk_print_settings_copy</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-has-key" title="gtk_print_settings_has_key ()">gtk_print_settings_has_key</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type">const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get" title="gtk_print_settings_get ()">gtk_print_settings_get</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set" title="gtk_print_settings_set ()">gtk_print_settings_set</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-unset" title="gtk_print_settings_unset ()">gtk_print_settings_unset</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-foreach" title="gtk_print_settings_foreach ()">gtk_print_settings_foreach</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-bool" title="gtk_print_settings_get_bool ()">gtk_print_settings_get_bool</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-bool" title="gtk_print_settings_set_bool ()">gtk_print_settings_set_bool</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="returnvalue">gdouble</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-double" title="gtk_print_settings_get_double ()">gtk_print_settings_get_double</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="returnvalue">gdouble</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-double-with-default" title="gtk_print_settings_get_double_with_default ()">gtk_print_settings_get_double_with_default</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-double" title="gtk_print_settings_set_double ()">gtk_print_settings_set_double</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="returnvalue">gdouble</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-length" title="gtk_print_settings_get_length ()">gtk_print_settings_get_length</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-length" title="gtk_print_settings_set_length ()">gtk_print_settings_set_length</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="returnvalue">gint</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-int" title="gtk_print_settings_get_int ()">gtk_print_settings_get_int</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="returnvalue">gint</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-int-with-default" title="gtk_print_settings_get_int_with_default ()">gtk_print_settings_get_int_with_default</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-int" title="gtk_print_settings_set_int ()">gtk_print_settings_set_int</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type">const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-printer" title="gtk_print_settings_get_printer ()">gtk_print_settings_get_printer</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-printer" title="gtk_print_settings_set_printer ()">gtk_print_settings_set_printer</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="GtkPrintSettings.html#GtkPageOrientation" title="enum GtkPageOrientation"><span class="returnvalue">GtkPageOrientation</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-orientation" title="gtk_print_settings_get_orientation ()">gtk_print_settings_get_orientation</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-orientation" title="gtk_print_settings_set_orientation ()">gtk_print_settings_set_orientation</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="GtkPaperSize.html" title="GtkPaperSize"><span class="returnvalue">GtkPaperSize</span></a> * </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-paper-size" title="gtk_print_settings_get_paper_size ()">gtk_print_settings_get_paper_size</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-paper-size" title="gtk_print_settings_set_paper_size ()">gtk_print_settings_set_paper_size</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="returnvalue">gdouble</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-paper-width" title="gtk_print_settings_get_paper_width ()">gtk_print_settings_get_paper_width</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-paper-width" title="gtk_print_settings_set_paper_width ()">gtk_print_settings_set_paper_width</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="returnvalue">gdouble</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-paper-height" title="gtk_print_settings_get_paper_height ()">gtk_print_settings_get_paper_height</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-paper-height" title="gtk_print_settings_set_paper_height ()">gtk_print_settings_set_paper_height</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-use-color" title="gtk_print_settings_get_use_color ()">gtk_print_settings_get_use_color</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-use-color" title="gtk_print_settings_set_use_color ()">gtk_print_settings_set_use_color</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-collate" title="gtk_print_settings_get_collate ()">gtk_print_settings_get_collate</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-collate" title="gtk_print_settings_set_collate ()">gtk_print_settings_set_collate</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-reverse" title="gtk_print_settings_get_reverse ()">gtk_print_settings_get_reverse</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-reverse" title="gtk_print_settings_set_reverse ()">gtk_print_settings_set_reverse</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="GtkPrintSettings.html#GtkPrintDuplex" title="enum GtkPrintDuplex"><span class="returnvalue">GtkPrintDuplex</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-duplex" title="gtk_print_settings_get_duplex ()">gtk_print_settings_get_duplex</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-duplex" title="gtk_print_settings_set_duplex ()">gtk_print_settings_set_duplex</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="GtkPrintSettings.html#GtkPrintQuality" title="enum GtkPrintQuality"><span class="returnvalue">GtkPrintQuality</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-quality" title="gtk_print_settings_get_quality ()">gtk_print_settings_get_quality</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-quality" title="gtk_print_settings_set_quality ()">gtk_print_settings_set_quality</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="returnvalue">gint</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-n-copies" title="gtk_print_settings_get_n_copies ()">gtk_print_settings_get_n_copies</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-n-copies" title="gtk_print_settings_set_n_copies ()">gtk_print_settings_set_n_copies</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="returnvalue">gint</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-number-up" title="gtk_print_settings_get_number_up ()">gtk_print_settings_get_number_up</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-number-up" title="gtk_print_settings_set_number_up ()">gtk_print_settings_set_number_up</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="GtkPrintSettings.html#GtkNumberUpLayout" title="enum GtkNumberUpLayout"><span class="returnvalue">GtkNumberUpLayout</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-number-up-layout" title="gtk_print_settings_get_number_up_layout ()">gtk_print_settings_get_number_up_layout</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-number-up-layout" title="gtk_print_settings_set_number_up_layout ()">gtk_print_settings_set_number_up_layout</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="returnvalue">gint</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-resolution" title="gtk_print_settings_get_resolution ()">gtk_print_settings_get_resolution</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-resolution" title="gtk_print_settings_set_resolution ()">gtk_print_settings_set_resolution</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-resolution-xy" title="gtk_print_settings_set_resolution_xy ()">gtk_print_settings_set_resolution_xy</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="returnvalue">gint</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-resolution-x" title="gtk_print_settings_get_resolution_x ()">gtk_print_settings_get_resolution_x</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="returnvalue">gint</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-resolution-y" title="gtk_print_settings_get_resolution_y ()">gtk_print_settings_get_resolution_y</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="returnvalue">gdouble</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-printer-lpi" title="gtk_print_settings_get_printer_lpi ()">gtk_print_settings_get_printer_lpi</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-printer-lpi" title="gtk_print_settings_set_printer_lpi ()">gtk_print_settings_set_printer_lpi</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="returnvalue">gdouble</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-scale" title="gtk_print_settings_get_scale ()">gtk_print_settings_get_scale</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-scale" title="gtk_print_settings_set_scale ()">gtk_print_settings_set_scale</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="GtkPrintSettings.html#GtkPrintPages" title="enum GtkPrintPages"><span class="returnvalue">GtkPrintPages</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-print-pages" title="gtk_print_settings_get_print_pages ()">gtk_print_settings_get_print_pages</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-print-pages" title="gtk_print_settings_set_print_pages ()">gtk_print_settings_set_print_pages</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="GtkPrintSettings.html#GtkPageRange" title="struct GtkPageRange"><span class="returnvalue">GtkPageRange</span></a> * </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-page-ranges" title="gtk_print_settings_get_page_ranges ()">gtk_print_settings_get_page_ranges</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-page-ranges" title="gtk_print_settings_set_page_ranges ()">gtk_print_settings_set_page_ranges</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="GtkPrintSettings.html#GtkPageSet" title="enum GtkPageSet"><span class="returnvalue">GtkPageSet</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-page-set" title="gtk_print_settings_get_page_set ()">gtk_print_settings_get_page_set</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-page-set" title="gtk_print_settings_set_page_set ()">gtk_print_settings_set_page_set</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type">const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-default-source" title="gtk_print_settings_get_default_source ()">gtk_print_settings_get_default_source</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-default-source" title="gtk_print_settings_set_default_source ()">gtk_print_settings_set_default_source</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type">const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-media-type" title="gtk_print_settings_get_media_type ()">gtk_print_settings_get_media_type</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-media-type" title="gtk_print_settings_set_media_type ()">gtk_print_settings_set_media_type</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type">const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-dither" title="gtk_print_settings_get_dither ()">gtk_print_settings_get_dither</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-dither" title="gtk_print_settings_set_dither ()">gtk_print_settings_set_dither</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type">const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-finishings" title="gtk_print_settings_get_finishings ()">gtk_print_settings_get_finishings</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-finishings" title="gtk_print_settings_set_finishings ()">gtk_print_settings_set_finishings</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type">const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-get-output-bin" title="gtk_print_settings_get_output_bin ()">gtk_print_settings_get_output_bin</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-output-bin" title="gtk_print_settings_set_output_bin ()">gtk_print_settings_set_output_bin</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="returnvalue">GtkPrintSettings</span></a> * </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-new-from-file" title="gtk_print_settings_new_from_file ()">gtk_print_settings_new_from_file</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="returnvalue">GtkPrintSettings</span></a> * </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-new-from-key-file" title="gtk_print_settings_new_from_key_file ()">gtk_print_settings_new_from_key_file</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-load-file" title="gtk_print_settings_load_file ()">gtk_print_settings_load_file</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-load-key-file" title="gtk_print_settings_load_key_file ()">gtk_print_settings_load_key_file</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-to-file" title="gtk_print_settings_to_file ()">gtk_print_settings_to_file</a> <span class="c_punctuation">()</span> </td> </tr> <tr> <td class="function_type"> <span class="returnvalue">void</span> </td> <td class="function_name"> <a class="link" href="GtkPrintSettings.html#gtk-print-settings-to-key-file" title="gtk_print_settings_to_key_file ()">gtk_print_settings_to_key_file</a> <span class="c_punctuation">()</span> </td> </tr> </tbody> </table></div> </div> <div class="refsect1"> <a name="GtkPrintSettings.other"></a><h2>Types and Values</h2> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="name"> <col class="description"> </colgroup> <tbody> <tr> <td class="datatype_keyword"> </td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GtkPrintSettings-struct" title="GtkPrintSettings">GtkPrintSettings</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PRINTER:CAPS" title="GTK_PRINT_SETTINGS_PRINTER">GTK_PRINT_SETTINGS_PRINTER</a></td> </tr> <tr> <td class="datatype_keyword">enum</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GtkPageOrientation" title="enum GtkPageOrientation">GtkPageOrientation</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-ORIENTATION:CAPS" title="GTK_PRINT_SETTINGS_ORIENTATION">GTK_PRINT_SETTINGS_ORIENTATION</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAPER-FORMAT:CAPS" title="GTK_PRINT_SETTINGS_PAPER_FORMAT">GTK_PRINT_SETTINGS_PAPER_FORMAT</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAPER-WIDTH:CAPS" title="GTK_PRINT_SETTINGS_PAPER_WIDTH">GTK_PRINT_SETTINGS_PAPER_WIDTH</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAPER-HEIGHT:CAPS" title="GTK_PRINT_SETTINGS_PAPER_HEIGHT">GTK_PRINT_SETTINGS_PAPER_HEIGHT</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-USE-COLOR:CAPS" title="GTK_PRINT_SETTINGS_USE_COLOR">GTK_PRINT_SETTINGS_USE_COLOR</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-COLLATE:CAPS" title="GTK_PRINT_SETTINGS_COLLATE">GTK_PRINT_SETTINGS_COLLATE</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-REVERSE:CAPS" title="GTK_PRINT_SETTINGS_REVERSE">GTK_PRINT_SETTINGS_REVERSE</a></td> </tr> <tr> <td class="datatype_keyword">enum</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GtkPrintDuplex" title="enum GtkPrintDuplex">GtkPrintDuplex</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-DUPLEX:CAPS" title="GTK_PRINT_SETTINGS_DUPLEX">GTK_PRINT_SETTINGS_DUPLEX</a></td> </tr> <tr> <td class="datatype_keyword">enum</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GtkPrintQuality" title="enum GtkPrintQuality">GtkPrintQuality</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-QUALITY:CAPS" title="GTK_PRINT_SETTINGS_QUALITY">GTK_PRINT_SETTINGS_QUALITY</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-N-COPIES:CAPS" title="GTK_PRINT_SETTINGS_N_COPIES">GTK_PRINT_SETTINGS_N_COPIES</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-NUMBER-UP:CAPS" title="GTK_PRINT_SETTINGS_NUMBER_UP">GTK_PRINT_SETTINGS_NUMBER_UP</a></td> </tr> <tr> <td class="datatype_keyword">enum</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GtkNumberUpLayout" title="enum GtkNumberUpLayout">GtkNumberUpLayout</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-NUMBER-UP-LAYOUT:CAPS" title="GTK_PRINT_SETTINGS_NUMBER_UP_LAYOUT">GTK_PRINT_SETTINGS_NUMBER_UP_LAYOUT</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-RESOLUTION:CAPS" title="GTK_PRINT_SETTINGS_RESOLUTION">GTK_PRINT_SETTINGS_RESOLUTION</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-RESOLUTION-X:CAPS" title="GTK_PRINT_SETTINGS_RESOLUTION_X">GTK_PRINT_SETTINGS_RESOLUTION_X</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-RESOLUTION-Y:CAPS" title="GTK_PRINT_SETTINGS_RESOLUTION_Y">GTK_PRINT_SETTINGS_RESOLUTION_Y</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PRINTER-LPI:CAPS" title="GTK_PRINT_SETTINGS_PRINTER_LPI">GTK_PRINT_SETTINGS_PRINTER_LPI</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-SCALE:CAPS" title="GTK_PRINT_SETTINGS_SCALE">GTK_PRINT_SETTINGS_SCALE</a></td> </tr> <tr> <td class="datatype_keyword">enum</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GtkPrintPages" title="enum GtkPrintPages">GtkPrintPages</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PRINT-PAGES:CAPS" title="GTK_PRINT_SETTINGS_PRINT_PAGES">GTK_PRINT_SETTINGS_PRINT_PAGES</a></td> </tr> <tr> <td class="datatype_keyword">struct</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GtkPageRange" title="struct GtkPageRange">GtkPageRange</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAGE-RANGES:CAPS" title="GTK_PRINT_SETTINGS_PAGE_RANGES">GTK_PRINT_SETTINGS_PAGE_RANGES</a></td> </tr> <tr> <td class="datatype_keyword">enum</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GtkPageSet" title="enum GtkPageSet">GtkPageSet</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAGE-SET:CAPS" title="GTK_PRINT_SETTINGS_PAGE_SET">GTK_PRINT_SETTINGS_PAGE_SET</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-DEFAULT-SOURCE:CAPS" title="GTK_PRINT_SETTINGS_DEFAULT_SOURCE">GTK_PRINT_SETTINGS_DEFAULT_SOURCE</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-MEDIA-TYPE:CAPS" title="GTK_PRINT_SETTINGS_MEDIA_TYPE">GTK_PRINT_SETTINGS_MEDIA_TYPE</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-DITHER:CAPS" title="GTK_PRINT_SETTINGS_DITHER">GTK_PRINT_SETTINGS_DITHER</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-FINISHINGS:CAPS" title="GTK_PRINT_SETTINGS_FINISHINGS">GTK_PRINT_SETTINGS_FINISHINGS</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-OUTPUT-BIN:CAPS" title="GTK_PRINT_SETTINGS_OUTPUT_BIN">GTK_PRINT_SETTINGS_OUTPUT_BIN</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-OUTPUT-DIR:CAPS" title="GTK_PRINT_SETTINGS_OUTPUT_DIR">GTK_PRINT_SETTINGS_OUTPUT_DIR</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-OUTPUT-BASENAME:CAPS" title="GTK_PRINT_SETTINGS_OUTPUT_BASENAME">GTK_PRINT_SETTINGS_OUTPUT_BASENAME</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-OUTPUT-FILE-FORMAT:CAPS" title="GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT">GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-OUTPUT-URI:CAPS" title="GTK_PRINT_SETTINGS_OUTPUT_URI">GTK_PRINT_SETTINGS_OUTPUT_URI</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-WIN32-DRIVER-EXTRA:CAPS" title="GTK_PRINT_SETTINGS_WIN32_DRIVER_EXTRA">GTK_PRINT_SETTINGS_WIN32_DRIVER_EXTRA</a></td> </tr> <tr> <td class="define_keyword">#define</td> <td class="function_name"><a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-WIN32-DRIVER-VERSION:CAPS" title="GTK_PRINT_SETTINGS_WIN32_DRIVER_VERSION">GTK_PRINT_SETTINGS_WIN32_DRIVER_VERSION</a></td> </tr> </tbody> </table></div> </div> <div class="refsect1"> <a name="GtkPrintSettings.object-hierarchy"></a><h2>Object Hierarchy</h2> <pre class="screen"> <a href="https://developer.gnome.org/gobject/unstable/gobject-The-Base-Object-Type.html#GObject">GObject</a> <span class="lineart">╰──</span> GtkPrintSettings </pre> </div> <div class="refsect1"> <a name="GtkPrintSettings.includes"></a><h2>Includes</h2> <pre class="synopsis">#include &lt;gtk/gtk.h&gt; </pre> </div> <div class="refsect1"> <a name="GtkPrintSettings.description"></a><h2>Description</h2> <p>A GtkPrintSettings object represents the settings of a print dialog in a system-independent way. The main use for this object is that once you’ve printed you can get a settings object that represents the settings the user chose, and the next time you print you can pass that object in so that the user doesn’t have to re-set all his settings.</p> <p>Its also possible to enumerate the settings so that you can easily save the settings for the next time your app runs, or even store them in a document. The predefined keys try to use shared values as much as possible so that moving such a document between systems still works.</p> <p>Printing support was added in GTK+ 2.10.</p> </div> <div class="refsect1"> <a name="GtkPrintSettings.functions_details"></a><h2>Functions</h2> <div class="refsect2"> <a name="GtkPrintSettingsFunc"></a><h3>GtkPrintSettingsFunc ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> <span class="c_punctuation">(</span>*GtkPrintSettingsFunc<span class="c_punctuation">)</span> (<em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *key</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *value</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gpointer"><span class="type">gpointer</span></a> user_data</code></em>);</pre> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-new"></a><h3>gtk_print_settings_new ()</h3> <pre class="programlisting"><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="returnvalue">GtkPrintSettings</span></a> * gtk_print_settings_new (<em class="parameter"><code><span class="type">void</span></code></em>);</pre> <p>Creates a new <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> object.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.3.5"></a><h4>Returns</h4> <p> a new <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> object</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-copy"></a><h3>gtk_print_settings_copy ()</h3> <pre class="programlisting"><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="returnvalue">GtkPrintSettings</span></a> * gtk_print_settings_copy (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *other</code></em>);</pre> <p>Copies a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> object.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.4.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>other</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.4.6"></a><h4>Returns</h4> <p> a newly allocated copy of <em class="parameter"><code>other</code></em> . </p> <p><span class="annotation">[<acronym title="Free data after the code is done."><span class="acronym">transfer full</span></acronym>]</span></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-has-key"></a><h3>gtk_print_settings_has_key ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> gtk_print_settings_has_key (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *key</code></em>);</pre> <p>Returns <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a>, if a value is associated with <em class="parameter"><code>key</code></em> .</p> <div class="refsect3"> <a name="id-1.3.17.4.8.5.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key</p></td> <td class="parameter_description"><p>a key</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.5.6"></a><h4>Returns</h4> <p> <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a>, if <em class="parameter"><code>key</code></em> has a value</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get"></a><h3>gtk_print_settings_get ()</h3> <pre class="programlisting">const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * gtk_print_settings_get (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *key</code></em>);</pre> <p>Looks up the string value associated with <em class="parameter"><code>key</code></em> .</p> <div class="refsect3"> <a name="id-1.3.17.4.8.6.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key</p></td> <td class="parameter_description"><p>a key</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.6.6"></a><h4>Returns</h4> <p> the string value for <em class="parameter"><code>key</code></em> </p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set"></a><h3>gtk_print_settings_set ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *key</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *value</code></em>);</pre> <p>Associates <em class="parameter"><code>value</code></em> with <em class="parameter"><code>key</code></em> .</p> <div class="refsect3"> <a name="id-1.3.17.4.8.7.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key</p></td> <td class="parameter_description"><p>a key</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>value</p></td> <td class="parameter_description"><p> a string value, or <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#NULL:CAPS"><code class="literal">NULL</code></a>. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-unset"></a><h3>gtk_print_settings_unset ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_unset (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *key</code></em>);</pre> <p>Removes any value associated with <em class="parameter"><code>key</code></em> . This has the same effect as setting the value to <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#NULL:CAPS"><code class="literal">NULL</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.8.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key</p></td> <td class="parameter_description"><p>a key</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-foreach"></a><h3>gtk_print_settings_foreach ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_foreach (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a class="link" href="GtkPrintSettings.html#GtkPrintSettingsFunc" title="GtkPrintSettingsFunc ()"><span class="type">GtkPrintSettingsFunc</span></a> func</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gpointer"><span class="type">gpointer</span></a> user_data</code></em>);</pre> <p>Calls <em class="parameter"><code>func</code></em> for each key-value pair of <em class="parameter"><code>settings</code></em> .</p> <div class="refsect3"> <a name="id-1.3.17.4.8.9.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>func</p></td> <td class="parameter_description"><p> the function to call. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="The callback is valid only during the call to the method."><span class="acronym">scope call</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>user_data</p></td> <td class="parameter_description"><p>user data for <em class="parameter"><code>func</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-bool"></a><h3>gtk_print_settings_get_bool ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> gtk_print_settings_get_bool (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *key</code></em>);</pre> <p>Returns the boolean represented by the value that is associated with <em class="parameter"><code>key</code></em> . </p> <p>The string “true” represents <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a>, any other string <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#FALSE:CAPS"><code class="literal">FALSE</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.10.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key</p></td> <td class="parameter_description"><p>a key</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.10.7"></a><h4>Returns</h4> <p> <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a>, if <em class="parameter"><code>key</code></em> maps to a true value.</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-bool"></a><h3>gtk_print_settings_set_bool ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_bool (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *key</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="type">gboolean</span></a> value</code></em>);</pre> <p>Sets <em class="parameter"><code>key</code></em> to a boolean value.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.11.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key</p></td> <td class="parameter_description"><p>a key</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>value</p></td> <td class="parameter_description"><p>a boolean</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-double"></a><h3>gtk_print_settings_get_double ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="returnvalue">gdouble</span></a> gtk_print_settings_get_double (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *key</code></em>);</pre> <p>Returns the double value associated with <em class="parameter"><code>key</code></em> , or 0.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.12.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key</p></td> <td class="parameter_description"><p>a key</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.12.6"></a><h4>Returns</h4> <p> the double value of <em class="parameter"><code>key</code></em> </p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-double-with-default"></a><h3>gtk_print_settings_get_double_with_default ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="returnvalue">gdouble</span></a> gtk_print_settings_get_double_with_default (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *key</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="type">gdouble</span></a> def</code></em>);</pre> <p>Returns the floating point number represented by the value that is associated with <em class="parameter"><code>key</code></em> , or <em class="parameter"><code>default_val</code></em> if the value does not represent a floating point number.</p> <p>Floating point numbers are parsed with <a href="https://developer.gnome.org/glib/unstable/glib-String-Utility-Functions.html#g-ascii-strtod"><code class="function">g_ascii_strtod()</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.13.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key</p></td> <td class="parameter_description"><p>a key</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>def</p></td> <td class="parameter_description"><p>the default value</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.13.7"></a><h4>Returns</h4> <p> the floating point number associated with <em class="parameter"><code>key</code></em> </p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-double"></a><h3>gtk_print_settings_set_double ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_double (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *key</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="type">gdouble</span></a> value</code></em>);</pre> <p>Sets <em class="parameter"><code>key</code></em> to a double value.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.14.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key</p></td> <td class="parameter_description"><p>a key </p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>value</p></td> <td class="parameter_description"><p>a double value</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-length"></a><h3>gtk_print_settings_get_length ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="returnvalue">gdouble</span></a> gtk_print_settings_get_length (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *key</code></em>, <em class="parameter"><code><a class="link" href="GtkPaperSize.html#GtkUnit" title="enum GtkUnit"><span class="type">GtkUnit</span></a> unit</code></em>);</pre> <p>Returns the value associated with <em class="parameter"><code>key</code></em> , interpreted as a length. The returned value is converted to <em class="parameter"><code>units</code></em> .</p> <div class="refsect3"> <a name="id-1.3.17.4.8.15.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key</p></td> <td class="parameter_description"><p>a key</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>unit</p></td> <td class="parameter_description"><p>the unit of the return value</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.15.6"></a><h4>Returns</h4> <p> the length value of <em class="parameter"><code>key</code></em> , converted to <em class="parameter"><code>unit</code></em> </p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-length"></a><h3>gtk_print_settings_set_length ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_length (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *key</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="type">gdouble</span></a> value</code></em>, <em class="parameter"><code><a class="link" href="GtkPaperSize.html#GtkUnit" title="enum GtkUnit"><span class="type">GtkUnit</span></a> unit</code></em>);</pre> <p>Associates a length in units of <em class="parameter"><code>unit</code></em> with <em class="parameter"><code>key</code></em> .</p> <div class="refsect3"> <a name="id-1.3.17.4.8.16.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key</p></td> <td class="parameter_description"><p>a key</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>value</p></td> <td class="parameter_description"><p>a length</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>unit</p></td> <td class="parameter_description"><p>the unit of <em class="parameter"><code>length</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-int"></a><h3>gtk_print_settings_get_int ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="returnvalue">gint</span></a> gtk_print_settings_get_int (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *key</code></em>);</pre> <p>Returns the integer value of <em class="parameter"><code>key</code></em> , or 0.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.17.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key</p></td> <td class="parameter_description"><p>a key</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.17.6"></a><h4>Returns</h4> <p> the integer value of <em class="parameter"><code>key</code></em> </p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-int-with-default"></a><h3>gtk_print_settings_get_int_with_default ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="returnvalue">gint</span></a> gtk_print_settings_get_int_with_default (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *key</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="type">gint</span></a> def</code></em>);</pre> <p>Returns the value of <em class="parameter"><code>key</code></em> , interpreted as an integer, or the default value.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.18.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key</p></td> <td class="parameter_description"><p>a key</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>def</p></td> <td class="parameter_description"><p>the default value</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.18.6"></a><h4>Returns</h4> <p> the integer value of <em class="parameter"><code>key</code></em> </p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-int"></a><h3>gtk_print_settings_set_int ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_int (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *key</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="type">gint</span></a> value</code></em>);</pre> <p>Sets <em class="parameter"><code>key</code></em> to an integer value.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.19.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key</p></td> <td class="parameter_description"><p>a key</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>value</p></td> <td class="parameter_description"><p>an integer </p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-printer"></a><h3>gtk_print_settings_get_printer ()</h3> <pre class="programlisting">const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * gtk_print_settings_get_printer (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Convenience function to obtain the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PRINTER:CAPS" title="GTK_PRINT_SETTINGS_PRINTER"><code class="literal">GTK_PRINT_SETTINGS_PRINTER</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.20.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.20.6"></a><h4>Returns</h4> <p> the printer name</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-printer"></a><h3>gtk_print_settings_set_printer ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_printer (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *printer</code></em>);</pre> <p>Convenience function to set <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PRINTER:CAPS" title="GTK_PRINT_SETTINGS_PRINTER"><code class="literal">GTK_PRINT_SETTINGS_PRINTER</code></a> to <em class="parameter"><code>printer</code></em> .</p> <div class="refsect3"> <a name="id-1.3.17.4.8.21.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>printer</p></td> <td class="parameter_description"><p>the printer name</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-orientation"></a><h3>gtk_print_settings_get_orientation ()</h3> <pre class="programlisting"><a class="link" href="GtkPrintSettings.html#GtkPageOrientation" title="enum GtkPageOrientation"><span class="returnvalue">GtkPageOrientation</span></a> gtk_print_settings_get_orientation (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Get the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-ORIENTATION:CAPS" title="GTK_PRINT_SETTINGS_ORIENTATION"><code class="literal">GTK_PRINT_SETTINGS_ORIENTATION</code></a>, converted to a <a class="link" href="GtkPrintSettings.html#GtkPageOrientation" title="enum GtkPageOrientation"><span class="type">GtkPageOrientation</span></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.22.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.22.6"></a><h4>Returns</h4> <p> the orientation</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-orientation"></a><h3>gtk_print_settings_set_orientation ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_orientation (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a class="link" href="GtkPrintSettings.html#GtkPageOrientation" title="enum GtkPageOrientation"><span class="type">GtkPageOrientation</span></a> orientation</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-ORIENTATION:CAPS" title="GTK_PRINT_SETTINGS_ORIENTATION"><code class="literal">GTK_PRINT_SETTINGS_ORIENTATION</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.23.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>orientation</p></td> <td class="parameter_description"><p>a page orientation</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-paper-size"></a><h3>gtk_print_settings_get_paper_size ()</h3> <pre class="programlisting"><a class="link" href="GtkPaperSize.html" title="GtkPaperSize"><span class="returnvalue">GtkPaperSize</span></a> * gtk_print_settings_get_paper_size (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAPER-FORMAT:CAPS" title="GTK_PRINT_SETTINGS_PAPER_FORMAT"><code class="literal">GTK_PRINT_SETTINGS_PAPER_FORMAT</code></a>, converted to a <a class="link" href="GtkPaperSize.html" title="GtkPaperSize"><span class="type">GtkPaperSize</span></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.24.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.24.6"></a><h4>Returns</h4> <p> the paper size</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-paper-size"></a><h3>gtk_print_settings_set_paper_size ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_paper_size (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a class="link" href="GtkPaperSize.html" title="GtkPaperSize"><span class="type">GtkPaperSize</span></a> *paper_size</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAPER-FORMAT:CAPS" title="GTK_PRINT_SETTINGS_PAPER_FORMAT"><code class="literal">GTK_PRINT_SETTINGS_PAPER_FORMAT</code></a>, <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAPER-WIDTH:CAPS" title="GTK_PRINT_SETTINGS_PAPER_WIDTH"><code class="literal">GTK_PRINT_SETTINGS_PAPER_WIDTH</code></a> and <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAPER-HEIGHT:CAPS" title="GTK_PRINT_SETTINGS_PAPER_HEIGHT"><code class="literal">GTK_PRINT_SETTINGS_PAPER_HEIGHT</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.25.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>paper_size</p></td> <td class="parameter_description"><p>a paper size</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-paper-width"></a><h3>gtk_print_settings_get_paper_width ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="returnvalue">gdouble</span></a> gtk_print_settings_get_paper_width (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a class="link" href="GtkPaperSize.html#GtkUnit" title="enum GtkUnit"><span class="type">GtkUnit</span></a> unit</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAPER-WIDTH:CAPS" title="GTK_PRINT_SETTINGS_PAPER_WIDTH"><code class="literal">GTK_PRINT_SETTINGS_PAPER_WIDTH</code></a>, converted to <em class="parameter"><code>unit</code></em> .</p> <div class="refsect3"> <a name="id-1.3.17.4.8.26.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>unit</p></td> <td class="parameter_description"><p>the unit for the return value</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.26.6"></a><h4>Returns</h4> <p> the paper width, in units of <em class="parameter"><code>unit</code></em> </p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-paper-width"></a><h3>gtk_print_settings_set_paper_width ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_paper_width (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="type">gdouble</span></a> width</code></em>, <em class="parameter"><code><a class="link" href="GtkPaperSize.html#GtkUnit" title="enum GtkUnit"><span class="type">GtkUnit</span></a> unit</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAPER-WIDTH:CAPS" title="GTK_PRINT_SETTINGS_PAPER_WIDTH"><code class="literal">GTK_PRINT_SETTINGS_PAPER_WIDTH</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.27.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>width</p></td> <td class="parameter_description"><p>the paper width</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>unit</p></td> <td class="parameter_description"><p>the units of <em class="parameter"><code>width</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-paper-height"></a><h3>gtk_print_settings_get_paper_height ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="returnvalue">gdouble</span></a> gtk_print_settings_get_paper_height (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a class="link" href="GtkPaperSize.html#GtkUnit" title="enum GtkUnit"><span class="type">GtkUnit</span></a> unit</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAPER-HEIGHT:CAPS" title="GTK_PRINT_SETTINGS_PAPER_HEIGHT"><code class="literal">GTK_PRINT_SETTINGS_PAPER_HEIGHT</code></a>, converted to <em class="parameter"><code>unit</code></em> .</p> <div class="refsect3"> <a name="id-1.3.17.4.8.28.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>unit</p></td> <td class="parameter_description"><p>the unit for the return value</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.28.6"></a><h4>Returns</h4> <p> the paper height, in units of <em class="parameter"><code>unit</code></em> </p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-paper-height"></a><h3>gtk_print_settings_set_paper_height ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_paper_height (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="type">gdouble</span></a> height</code></em>, <em class="parameter"><code><a class="link" href="GtkPaperSize.html#GtkUnit" title="enum GtkUnit"><span class="type">GtkUnit</span></a> unit</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAPER-HEIGHT:CAPS" title="GTK_PRINT_SETTINGS_PAPER_HEIGHT"><code class="literal">GTK_PRINT_SETTINGS_PAPER_HEIGHT</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.29.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>height</p></td> <td class="parameter_description"><p>the paper height</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>unit</p></td> <td class="parameter_description"><p>the units of <em class="parameter"><code>height</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-use-color"></a><h3>gtk_print_settings_get_use_color ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> gtk_print_settings_get_use_color (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-USE-COLOR:CAPS" title="GTK_PRINT_SETTINGS_USE_COLOR"><code class="literal">GTK_PRINT_SETTINGS_USE_COLOR</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.30.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.30.6"></a><h4>Returns</h4> <p> whether to use color</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-use-color"></a><h3>gtk_print_settings_set_use_color ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_use_color (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="type">gboolean</span></a> use_color</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-USE-COLOR:CAPS" title="GTK_PRINT_SETTINGS_USE_COLOR"><code class="literal">GTK_PRINT_SETTINGS_USE_COLOR</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.31.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>use_color</p></td> <td class="parameter_description"><p>whether to use color</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-collate"></a><h3>gtk_print_settings_get_collate ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> gtk_print_settings_get_collate (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-COLLATE:CAPS" title="GTK_PRINT_SETTINGS_COLLATE"><code class="literal">GTK_PRINT_SETTINGS_COLLATE</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.32.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.32.6"></a><h4>Returns</h4> <p> whether to collate the printed pages</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-collate"></a><h3>gtk_print_settings_set_collate ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_collate (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="type">gboolean</span></a> collate</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-COLLATE:CAPS" title="GTK_PRINT_SETTINGS_COLLATE"><code class="literal">GTK_PRINT_SETTINGS_COLLATE</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.33.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>collate</p></td> <td class="parameter_description"><p>whether to collate the output</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-reverse"></a><h3>gtk_print_settings_get_reverse ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> gtk_print_settings_get_reverse (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-REVERSE:CAPS" title="GTK_PRINT_SETTINGS_REVERSE"><code class="literal">GTK_PRINT_SETTINGS_REVERSE</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.34.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.34.6"></a><h4>Returns</h4> <p> whether to reverse the order of the printed pages</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-reverse"></a><h3>gtk_print_settings_set_reverse ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_reverse (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="type">gboolean</span></a> reverse</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-REVERSE:CAPS" title="GTK_PRINT_SETTINGS_REVERSE"><code class="literal">GTK_PRINT_SETTINGS_REVERSE</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.35.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>reverse</p></td> <td class="parameter_description"><p>whether to reverse the output</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-duplex"></a><h3>gtk_print_settings_get_duplex ()</h3> <pre class="programlisting"><a class="link" href="GtkPrintSettings.html#GtkPrintDuplex" title="enum GtkPrintDuplex"><span class="returnvalue">GtkPrintDuplex</span></a> gtk_print_settings_get_duplex (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-DUPLEX:CAPS" title="GTK_PRINT_SETTINGS_DUPLEX"><code class="literal">GTK_PRINT_SETTINGS_DUPLEX</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.36.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.36.6"></a><h4>Returns</h4> <p> whether to print the output in duplex.</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-duplex"></a><h3>gtk_print_settings_set_duplex ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_duplex (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a class="link" href="GtkPrintSettings.html#GtkPrintDuplex" title="enum GtkPrintDuplex"><span class="type">GtkPrintDuplex</span></a> duplex</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-DUPLEX:CAPS" title="GTK_PRINT_SETTINGS_DUPLEX"><code class="literal">GTK_PRINT_SETTINGS_DUPLEX</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.37.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>duplex</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html#GtkPrintDuplex" title="enum GtkPrintDuplex"><span class="type">GtkPrintDuplex</span></a> value</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-quality"></a><h3>gtk_print_settings_get_quality ()</h3> <pre class="programlisting"><a class="link" href="GtkPrintSettings.html#GtkPrintQuality" title="enum GtkPrintQuality"><span class="returnvalue">GtkPrintQuality</span></a> gtk_print_settings_get_quality (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-QUALITY:CAPS" title="GTK_PRINT_SETTINGS_QUALITY"><code class="literal">GTK_PRINT_SETTINGS_QUALITY</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.38.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.38.6"></a><h4>Returns</h4> <p> the print quality</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-quality"></a><h3>gtk_print_settings_set_quality ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_quality (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a class="link" href="GtkPrintSettings.html#GtkPrintQuality" title="enum GtkPrintQuality"><span class="type">GtkPrintQuality</span></a> quality</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-QUALITY:CAPS" title="GTK_PRINT_SETTINGS_QUALITY"><code class="literal">GTK_PRINT_SETTINGS_QUALITY</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.39.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>quality</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html#GtkPrintQuality" title="enum GtkPrintQuality"><span class="type">GtkPrintQuality</span></a> value</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-n-copies"></a><h3>gtk_print_settings_get_n_copies ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="returnvalue">gint</span></a> gtk_print_settings_get_n_copies (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-N-COPIES:CAPS" title="GTK_PRINT_SETTINGS_N_COPIES"><code class="literal">GTK_PRINT_SETTINGS_N_COPIES</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.40.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.40.6"></a><h4>Returns</h4> <p> the number of copies to print</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-n-copies"></a><h3>gtk_print_settings_set_n_copies ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_n_copies (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="type">gint</span></a> num_copies</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-N-COPIES:CAPS" title="GTK_PRINT_SETTINGS_N_COPIES"><code class="literal">GTK_PRINT_SETTINGS_N_COPIES</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.41.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>num_copies</p></td> <td class="parameter_description"><p>the number of copies </p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-number-up"></a><h3>gtk_print_settings_get_number_up ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="returnvalue">gint</span></a> gtk_print_settings_get_number_up (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-NUMBER-UP:CAPS" title="GTK_PRINT_SETTINGS_NUMBER_UP"><code class="literal">GTK_PRINT_SETTINGS_NUMBER_UP</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.42.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.42.6"></a><h4>Returns</h4> <p> the number of pages per sheet</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-number-up"></a><h3>gtk_print_settings_set_number_up ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_number_up (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="type">gint</span></a> number_up</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-NUMBER-UP:CAPS" title="GTK_PRINT_SETTINGS_NUMBER_UP"><code class="literal">GTK_PRINT_SETTINGS_NUMBER_UP</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.43.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>number_up</p></td> <td class="parameter_description"><p>the number of pages per sheet </p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-number-up-layout"></a><h3>gtk_print_settings_get_number_up_layout ()</h3> <pre class="programlisting"><a class="link" href="GtkPrintSettings.html#GtkNumberUpLayout" title="enum GtkNumberUpLayout"><span class="returnvalue">GtkNumberUpLayout</span></a> gtk_print_settings_get_number_up_layout (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-NUMBER-UP-LAYOUT:CAPS" title="GTK_PRINT_SETTINGS_NUMBER_UP_LAYOUT"><code class="literal">GTK_PRINT_SETTINGS_NUMBER_UP_LAYOUT</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.44.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.44.6"></a><h4>Returns</h4> <p> layout of page in number-up mode</p> <p></p> </div> <p class="since">Since 2.14</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-number-up-layout"></a><h3>gtk_print_settings_set_number_up_layout ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_number_up_layout (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a class="link" href="GtkPrintSettings.html#GtkNumberUpLayout" title="enum GtkNumberUpLayout"><span class="type">GtkNumberUpLayout</span></a> number_up_layout</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-NUMBER-UP-LAYOUT:CAPS" title="GTK_PRINT_SETTINGS_NUMBER_UP_LAYOUT"><code class="literal">GTK_PRINT_SETTINGS_NUMBER_UP_LAYOUT</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.45.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>number_up_layout</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html#GtkNumberUpLayout" title="enum GtkNumberUpLayout"><span class="type">GtkNumberUpLayout</span></a> value</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.14</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-resolution"></a><h3>gtk_print_settings_get_resolution ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="returnvalue">gint</span></a> gtk_print_settings_get_resolution (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-RESOLUTION:CAPS" title="GTK_PRINT_SETTINGS_RESOLUTION"><code class="literal">GTK_PRINT_SETTINGS_RESOLUTION</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.46.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.46.6"></a><h4>Returns</h4> <p> the resolution in dpi</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-resolution"></a><h3>gtk_print_settings_set_resolution ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_resolution (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="type">gint</span></a> resolution</code></em>);</pre> <p>Sets the values of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-RESOLUTION:CAPS" title="GTK_PRINT_SETTINGS_RESOLUTION"><code class="literal">GTK_PRINT_SETTINGS_RESOLUTION</code></a>, <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-RESOLUTION-X:CAPS" title="GTK_PRINT_SETTINGS_RESOLUTION_X"><code class="literal">GTK_PRINT_SETTINGS_RESOLUTION_X</code></a> and <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-RESOLUTION-Y:CAPS" title="GTK_PRINT_SETTINGS_RESOLUTION_Y"><code class="literal">GTK_PRINT_SETTINGS_RESOLUTION_Y</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.47.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>resolution</p></td> <td class="parameter_description"><p>the resolution in dpi</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-resolution-xy"></a><h3>gtk_print_settings_set_resolution_xy ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_resolution_xy (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="type">gint</span></a> resolution_x</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="type">gint</span></a> resolution_y</code></em>);</pre> <p>Sets the values of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-RESOLUTION:CAPS" title="GTK_PRINT_SETTINGS_RESOLUTION"><code class="literal">GTK_PRINT_SETTINGS_RESOLUTION</code></a>, <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-RESOLUTION-X:CAPS" title="GTK_PRINT_SETTINGS_RESOLUTION_X"><code class="literal">GTK_PRINT_SETTINGS_RESOLUTION_X</code></a> and <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-RESOLUTION-Y:CAPS" title="GTK_PRINT_SETTINGS_RESOLUTION_Y"><code class="literal">GTK_PRINT_SETTINGS_RESOLUTION_Y</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.48.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>resolution_x</p></td> <td class="parameter_description"><p>the horizontal resolution in dpi</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>resolution_y</p></td> <td class="parameter_description"><p>the vertical resolution in dpi</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.16</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-resolution-x"></a><h3>gtk_print_settings_get_resolution_x ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="returnvalue">gint</span></a> gtk_print_settings_get_resolution_x (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-RESOLUTION-X:CAPS" title="GTK_PRINT_SETTINGS_RESOLUTION_X"><code class="literal">GTK_PRINT_SETTINGS_RESOLUTION_X</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.49.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.49.6"></a><h4>Returns</h4> <p> the horizontal resolution in dpi</p> <p></p> </div> <p class="since">Since 2.16</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-resolution-y"></a><h3>gtk_print_settings_get_resolution_y ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="returnvalue">gint</span></a> gtk_print_settings_get_resolution_y (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-RESOLUTION-Y:CAPS" title="GTK_PRINT_SETTINGS_RESOLUTION_Y"><code class="literal">GTK_PRINT_SETTINGS_RESOLUTION_Y</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.50.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.50.6"></a><h4>Returns</h4> <p> the vertical resolution in dpi</p> <p></p> </div> <p class="since">Since 2.16</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-printer-lpi"></a><h3>gtk_print_settings_get_printer_lpi ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="returnvalue">gdouble</span></a> gtk_print_settings_get_printer_lpi (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PRINTER-LPI:CAPS" title="GTK_PRINT_SETTINGS_PRINTER_LPI"><code class="literal">GTK_PRINT_SETTINGS_PRINTER_LPI</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.51.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.51.6"></a><h4>Returns</h4> <p> the resolution in lpi (lines per inch)</p> <p></p> </div> <p class="since">Since 2.16</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-printer-lpi"></a><h3>gtk_print_settings_set_printer_lpi ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_printer_lpi (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="type">gdouble</span></a> lpi</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PRINTER-LPI:CAPS" title="GTK_PRINT_SETTINGS_PRINTER_LPI"><code class="literal">GTK_PRINT_SETTINGS_PRINTER_LPI</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.52.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>lpi</p></td> <td class="parameter_description"><p>the resolution in lpi (lines per inch)</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.16</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-scale"></a><h3>gtk_print_settings_get_scale ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="returnvalue">gdouble</span></a> gtk_print_settings_get_scale (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-SCALE:CAPS" title="GTK_PRINT_SETTINGS_SCALE"><code class="literal">GTK_PRINT_SETTINGS_SCALE</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.53.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.53.6"></a><h4>Returns</h4> <p> the scale in percent</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-scale"></a><h3>gtk_print_settings_set_scale ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_scale (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gdouble"><span class="type">gdouble</span></a> scale</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-SCALE:CAPS" title="GTK_PRINT_SETTINGS_SCALE"><code class="literal">GTK_PRINT_SETTINGS_SCALE</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.54.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>scale</p></td> <td class="parameter_description"><p>the scale in percent</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-print-pages"></a><h3>gtk_print_settings_get_print_pages ()</h3> <pre class="programlisting"><a class="link" href="GtkPrintSettings.html#GtkPrintPages" title="enum GtkPrintPages"><span class="returnvalue">GtkPrintPages</span></a> gtk_print_settings_get_print_pages (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PRINT-PAGES:CAPS" title="GTK_PRINT_SETTINGS_PRINT_PAGES"><code class="literal">GTK_PRINT_SETTINGS_PRINT_PAGES</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.55.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.55.6"></a><h4>Returns</h4> <p> which pages to print</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-print-pages"></a><h3>gtk_print_settings_set_print_pages ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_print_pages (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a class="link" href="GtkPrintSettings.html#GtkPrintPages" title="enum GtkPrintPages"><span class="type">GtkPrintPages</span></a> pages</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PRINT-PAGES:CAPS" title="GTK_PRINT_SETTINGS_PRINT_PAGES"><code class="literal">GTK_PRINT_SETTINGS_PRINT_PAGES</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.56.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>pages</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html#GtkPrintPages" title="enum GtkPrintPages"><span class="type">GtkPrintPages</span></a> value</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-page-ranges"></a><h3>gtk_print_settings_get_page_ranges ()</h3> <pre class="programlisting"><a class="link" href="GtkPrintSettings.html#GtkPageRange" title="struct GtkPageRange"><span class="returnvalue">GtkPageRange</span></a> * gtk_print_settings_get_page_ranges (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="type">gint</span></a> *num_ranges</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAGE-RANGES:CAPS" title="GTK_PRINT_SETTINGS_PAGE_RANGES"><code class="literal">GTK_PRINT_SETTINGS_PAGE_RANGES</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.57.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>num_ranges</p></td> <td class="parameter_description"><p> return location for the length of the returned array. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="Parameter for returning results. Default is transfer full."><span class="acronym">out</span></acronym>]</span></td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.57.6"></a><h4>Returns</h4> <p> an array of <a href="GtkPrintSettings.html#GtkPageRange"><span class="type">GtkPageRanges</span></a>. Use <a href="https://developer.gnome.org/glib/unstable/glib-Memory-Allocation.html#g-free"><code class="function">g_free()</code></a> to free the array when it is no longer needed. </p> <p><span class="annotation">[<acronym title="Parameter points to an array of items."><span class="acronym">array</span></acronym> length=num_ranges][<acronym title="Free data after the code is done."><span class="acronym">transfer full</span></acronym>]</span></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-page-ranges"></a><h3>gtk_print_settings_set_page_ranges ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_page_ranges (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a class="link" href="GtkPrintSettings.html#GtkPageRange" title="struct GtkPageRange"><span class="type">GtkPageRange</span></a> *page_ranges</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="type">gint</span></a> num_ranges</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAGE-RANGES:CAPS" title="GTK_PRINT_SETTINGS_PAGE_RANGES"><code class="literal">GTK_PRINT_SETTINGS_PAGE_RANGES</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.58.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>page_ranges</p></td> <td class="parameter_description"><p> an array of <a href="GtkPrintSettings.html#GtkPageRange"><span class="type">GtkPageRanges</span></a>. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="Parameter points to an array of items."><span class="acronym">array</span></acronym> length=num_ranges]</span></td> </tr> <tr> <td class="parameter_name"><p>num_ranges</p></td> <td class="parameter_description"><p>the length of <em class="parameter"><code>page_ranges</code></em> </p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-page-set"></a><h3>gtk_print_settings_get_page_set ()</h3> <pre class="programlisting"><a class="link" href="GtkPrintSettings.html#GtkPageSet" title="enum GtkPageSet"><span class="returnvalue">GtkPageSet</span></a> gtk_print_settings_get_page_set (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAGE-SET:CAPS" title="GTK_PRINT_SETTINGS_PAGE_SET"><code class="literal">GTK_PRINT_SETTINGS_PAGE_SET</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.59.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.59.6"></a><h4>Returns</h4> <p> the set of pages to print</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-page-set"></a><h3>gtk_print_settings_set_page_set ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_page_set (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a class="link" href="GtkPrintSettings.html#GtkPageSet" title="enum GtkPageSet"><span class="type">GtkPageSet</span></a> page_set</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-PAGE-SET:CAPS" title="GTK_PRINT_SETTINGS_PAGE_SET"><code class="literal">GTK_PRINT_SETTINGS_PAGE_SET</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.60.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>page_set</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html#GtkPageSet" title="enum GtkPageSet"><span class="type">GtkPageSet</span></a> value</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-default-source"></a><h3>gtk_print_settings_get_default_source ()</h3> <pre class="programlisting">const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * gtk_print_settings_get_default_source (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-DEFAULT-SOURCE:CAPS" title="GTK_PRINT_SETTINGS_DEFAULT_SOURCE"><code class="literal">GTK_PRINT_SETTINGS_DEFAULT_SOURCE</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.61.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.61.6"></a><h4>Returns</h4> <p> the default source</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-default-source"></a><h3>gtk_print_settings_set_default_source ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_default_source (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *default_source</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-DEFAULT-SOURCE:CAPS" title="GTK_PRINT_SETTINGS_DEFAULT_SOURCE"><code class="literal">GTK_PRINT_SETTINGS_DEFAULT_SOURCE</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.62.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>default_source</p></td> <td class="parameter_description"><p>the default source</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-media-type"></a><h3>gtk_print_settings_get_media_type ()</h3> <pre class="programlisting">const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * gtk_print_settings_get_media_type (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-MEDIA-TYPE:CAPS" title="GTK_PRINT_SETTINGS_MEDIA_TYPE"><code class="literal">GTK_PRINT_SETTINGS_MEDIA_TYPE</code></a>.</p> <p>The set of media types is defined in PWG 5101.1-2002 PWG.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.63.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.63.7"></a><h4>Returns</h4> <p> the media type</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-media-type"></a><h3>gtk_print_settings_set_media_type ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_media_type (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *media_type</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-MEDIA-TYPE:CAPS" title="GTK_PRINT_SETTINGS_MEDIA_TYPE"><code class="literal">GTK_PRINT_SETTINGS_MEDIA_TYPE</code></a>.</p> <p>The set of media types is defined in PWG 5101.1-2002 PWG.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.64.6"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>media_type</p></td> <td class="parameter_description"><p>the media type</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-dither"></a><h3>gtk_print_settings_get_dither ()</h3> <pre class="programlisting">const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * gtk_print_settings_get_dither (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-DITHER:CAPS" title="GTK_PRINT_SETTINGS_DITHER"><code class="literal">GTK_PRINT_SETTINGS_DITHER</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.65.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.65.6"></a><h4>Returns</h4> <p> the dithering that is used</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-dither"></a><h3>gtk_print_settings_set_dither ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_dither (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *dither</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-DITHER:CAPS" title="GTK_PRINT_SETTINGS_DITHER"><code class="literal">GTK_PRINT_SETTINGS_DITHER</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.66.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>dither</p></td> <td class="parameter_description"><p>the dithering that is used</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-finishings"></a><h3>gtk_print_settings_get_finishings ()</h3> <pre class="programlisting">const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * gtk_print_settings_get_finishings (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-FINISHINGS:CAPS" title="GTK_PRINT_SETTINGS_FINISHINGS"><code class="literal">GTK_PRINT_SETTINGS_FINISHINGS</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.67.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.67.6"></a><h4>Returns</h4> <p> the finishings</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-finishings"></a><h3>gtk_print_settings_set_finishings ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_finishings (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *finishings</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-FINISHINGS:CAPS" title="GTK_PRINT_SETTINGS_FINISHINGS"><code class="literal">GTK_PRINT_SETTINGS_FINISHINGS</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.68.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>finishings</p></td> <td class="parameter_description"><p>the finishings</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-get-output-bin"></a><h3>gtk_print_settings_get_output_bin ()</h3> <pre class="programlisting">const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * gtk_print_settings_get_output_bin (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>);</pre> <p>Gets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-OUTPUT-BIN:CAPS" title="GTK_PRINT_SETTINGS_OUTPUT_BIN"><code class="literal">GTK_PRINT_SETTINGS_OUTPUT_BIN</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.69.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody><tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr></tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.69.6"></a><h4>Returns</h4> <p> the output bin</p> <p></p> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-set-output-bin"></a><h3>gtk_print_settings_set_output_bin ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_set_output_bin (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *output_bin</code></em>);</pre> <p>Sets the value of <a class="link" href="GtkPrintSettings.html#GTK-PRINT-SETTINGS-OUTPUT-BIN:CAPS" title="GTK_PRINT_SETTINGS_OUTPUT_BIN"><code class="literal">GTK_PRINT_SETTINGS_OUTPUT_BIN</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.70.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>output_bin</p></td> <td class="parameter_description"><p>the output bin</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.10</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-new-from-file"></a><h3>gtk_print_settings_new_from_file ()</h3> <pre class="programlisting"><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="returnvalue">GtkPrintSettings</span></a> * gtk_print_settings_new_from_file (<em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *file_name</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Error-Reporting.html#GError"><span class="type">GError</span></a> **error</code></em>);</pre> <p>Reads the print settings from <em class="parameter"><code>file_name</code></em> . Returns a new <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> object with the restored settings, or <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#NULL:CAPS"><code class="literal">NULL</code></a> if an error occurred. If the file could not be loaded then error is set to either a <a href="https://developer.gnome.org/glib/unstable/glib-File-Utilities.html#GFileError"><span class="type">GFileError</span></a> or <a href="https://developer.gnome.org/glib/unstable/glib-Key-value-file-parser.html#GKeyFileError"><span class="type">GKeyFileError</span></a>. See <a class="link" href="GtkPrintSettings.html#gtk-print-settings-to-file" title="gtk_print_settings_to_file ()"><code class="function">gtk_print_settings_to_file()</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.71.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>file_name</p></td> <td class="parameter_description"><p> the filename to read the settings from. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="Override the parsed C type with given type."><span class="acronym">type</span></acronym> filename]</span></td> </tr> <tr> <td class="parameter_name"><p>error</p></td> <td class="parameter_description"><p> return location for errors, or <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#NULL:CAPS"><code class="literal">NULL</code></a>. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.71.6"></a><h4>Returns</h4> <p> the restored <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p> <p></p> </div> <p class="since">Since 2.12</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-new-from-key-file"></a><h3>gtk_print_settings_new_from_key_file ()</h3> <pre class="programlisting"><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="returnvalue">GtkPrintSettings</span></a> * gtk_print_settings_new_from_key_file (<em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Key-value-file-parser.html#GKeyFile"><span class="type">GKeyFile</span></a> *key_file</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *group_name</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Error-Reporting.html#GError"><span class="type">GError</span></a> **error</code></em>);</pre> <p>Reads the print settings from the group <em class="parameter"><code>group_name</code></em> in <em class="parameter"><code>key_file</code></em> . Returns a new <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> object with the restored settings, or <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#NULL:CAPS"><code class="literal">NULL</code></a> if an error occurred. If the file could not be loaded then error is set to either a <a href="https://developer.gnome.org/glib/unstable/glib-File-Utilities.html#GFileError"><span class="type">GFileError</span></a> or <a href="https://developer.gnome.org/glib/unstable/glib-Key-value-file-parser.html#GKeyFileError"><span class="type">GKeyFileError</span></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.72.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>key_file</p></td> <td class="parameter_description"><p>the <a href="https://developer.gnome.org/glib/unstable/glib-Key-value-file-parser.html#GKeyFile"><span class="type">GKeyFile</span></a> to retrieve the settings from</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>group_name</p></td> <td class="parameter_description"><p> the name of the group to use, or <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#NULL:CAPS"><code class="literal">NULL</code></a> to use the default “Print Settings”. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>error</p></td> <td class="parameter_description"><p> return location for errors, or <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#NULL:CAPS"><code class="literal">NULL</code></a>. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.72.6"></a><h4>Returns</h4> <p> the restored <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p> <p></p> </div> <p class="since">Since 2.12</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-load-file"></a><h3>gtk_print_settings_load_file ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> gtk_print_settings_load_file (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *file_name</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Error-Reporting.html#GError"><span class="type">GError</span></a> **error</code></em>);</pre> <p>Reads the print settings from <em class="parameter"><code>file_name</code></em> . If the file could not be loaded then error is set to either a <a href="https://developer.gnome.org/glib/unstable/glib-File-Utilities.html#GFileError"><span class="type">GFileError</span></a> or <a href="https://developer.gnome.org/glib/unstable/glib-Key-value-file-parser.html#GKeyFileError"><span class="type">GKeyFileError</span></a>. See <a class="link" href="GtkPrintSettings.html#gtk-print-settings-to-file" title="gtk_print_settings_to_file ()"><code class="function">gtk_print_settings_to_file()</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.73.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>file_name</p></td> <td class="parameter_description"><p> the filename to read the settings from. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="Override the parsed C type with given type."><span class="acronym">type</span></acronym> filename]</span></td> </tr> <tr> <td class="parameter_name"><p>error</p></td> <td class="parameter_description"><p> return location for errors, or <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#NULL:CAPS"><code class="literal">NULL</code></a>. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.73.6"></a><h4>Returns</h4> <p> <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> on success</p> <p></p> </div> <p class="since">Since 2.14</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-load-key-file"></a><h3>gtk_print_settings_load_key_file ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> gtk_print_settings_load_key_file (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Key-value-file-parser.html#GKeyFile"><span class="type">GKeyFile</span></a> *key_file</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *group_name</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Error-Reporting.html#GError"><span class="type">GError</span></a> **error</code></em>);</pre> <p>Reads the print settings from the group <em class="parameter"><code>group_name</code></em> in <em class="parameter"><code>key_file</code></em> . If the file could not be loaded then error is set to either a <a href="https://developer.gnome.org/glib/unstable/glib-File-Utilities.html#GFileError"><span class="type">GFileError</span></a> or <a href="https://developer.gnome.org/glib/unstable/glib-Key-value-file-parser.html#GKeyFileError"><span class="type">GKeyFileError</span></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.74.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key_file</p></td> <td class="parameter_description"><p>the <a href="https://developer.gnome.org/glib/unstable/glib-Key-value-file-parser.html#GKeyFile"><span class="type">GKeyFile</span></a> to retrieve the settings from</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>group_name</p></td> <td class="parameter_description"><p> the name of the group to use, or <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#NULL:CAPS"><code class="literal">NULL</code></a> to use the default “Print Settings”. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> <tr> <td class="parameter_name"><p>error</p></td> <td class="parameter_description"><p> return location for errors, or <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#NULL:CAPS"><code class="literal">NULL</code></a>. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.74.6"></a><h4>Returns</h4> <p> <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> on success</p> <p></p> </div> <p class="since">Since 2.14</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-to-file"></a><h3>gtk_print_settings_to_file ()</h3> <pre class="programlisting"><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> gtk_print_settings_to_file (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *file_name</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Error-Reporting.html#GError"><span class="type">GError</span></a> **error</code></em>);</pre> <p>This function saves the print settings from <em class="parameter"><code>settings</code></em> to <em class="parameter"><code>file_name</code></em> . If the file could not be loaded then error is set to either a <a href="https://developer.gnome.org/glib/unstable/glib-File-Utilities.html#GFileError"><span class="type">GFileError</span></a> or <a href="https://developer.gnome.org/glib/unstable/glib-Key-value-file-parser.html#GKeyFileError"><span class="type">GKeyFileError</span></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.8.75.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>file_name</p></td> <td class="parameter_description"><p> the file to save to. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="Override the parsed C type with given type."><span class="acronym">type</span></acronym> filename]</span></td> </tr> <tr> <td class="parameter_name"><p>error</p></td> <td class="parameter_description"><p> return location for errors, or <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#NULL:CAPS"><code class="literal">NULL</code></a>. </p></td> <td class="parameter_annotations"><span class="annotation">[<acronym title="NULL is OK, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span></td> </tr> </tbody> </table></div> </div> <div class="refsect3"> <a name="id-1.3.17.4.8.75.6"></a><h4>Returns</h4> <p> <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> on success</p> <p></p> </div> <p class="since">Since 2.12</p> </div> <hr> <div class="refsect2"> <a name="gtk-print-settings-to-key-file"></a><h3>gtk_print_settings_to_key_file ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> gtk_print_settings_to_key_file (<em class="parameter"><code><a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a> *settings</code></em>, <em class="parameter"><code><a href="https://developer.gnome.org/glib/unstable/glib-Key-value-file-parser.html#GKeyFile"><span class="type">GKeyFile</span></a> *key_file</code></em>, <em class="parameter"><code>const <a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a> *group_name</code></em>);</pre> <p>This function adds the print settings from <em class="parameter"><code>settings</code></em> to <em class="parameter"><code>key_file</code></em> .</p> <div class="refsect3"> <a name="id-1.3.17.4.8.76.5"></a><h4>Parameters</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="150px" class="parameters_name"> <col class="parameters_description"> <col width="200px" class="parameters_annotations"> </colgroup> <tbody> <tr> <td class="parameter_name"><p>settings</p></td> <td class="parameter_description"><p>a <a class="link" href="GtkPrintSettings.html" title="GtkPrintSettings"><span class="type">GtkPrintSettings</span></a></p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>key_file</p></td> <td class="parameter_description"><p>the <a href="https://developer.gnome.org/glib/unstable/glib-Key-value-file-parser.html#GKeyFile"><span class="type">GKeyFile</span></a> to save the print settings to</p></td> <td class="parameter_annotations"> </td> </tr> <tr> <td class="parameter_name"><p>group_name</p></td> <td class="parameter_description"><p>the group to add the settings to in <em class="parameter"><code>key_file</code></em> , or <a href="https://developer.gnome.org/glib/unstable/glib-Standard-Macros.html#NULL:CAPS"><code class="literal">NULL</code></a> to use the default “Print Settings”</p></td> <td class="parameter_annotations"> </td> </tr> </tbody> </table></div> </div> <p class="since">Since 2.12</p> </div> </div> <div class="refsect1"> <a name="GtkPrintSettings.other_details"></a><h2>Types and Values</h2> <div class="refsect2"> <a name="GtkPrintSettings-struct"></a><h3>GtkPrintSettings</h3> <pre class="programlisting">typedef struct _GtkPrintSettings GtkPrintSettings;</pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-PRINTER:CAPS"></a><h3>GTK_PRINT_SETTINGS_PRINTER</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_PRINTER "printer" </pre> </div> <hr> <div class="refsect2"> <a name="GtkPageOrientation"></a><h3>enum GtkPageOrientation</h3> <p>See also <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-orientation" title="gtk_print_settings_set_orientation ()"><code class="function">gtk_print_settings_set_orientation()</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.9.4.4"></a><h4>Members</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="300px" class="enum_members_name"> <col class="enum_members_description"> <col width="200px" class="enum_members_annotations"> </colgroup> <tbody> <tr> <td class="enum_member_name"><p><a name="GTK-PAGE-ORIENTATION-PORTRAIT:CAPS"></a>GTK_PAGE_ORIENTATION_PORTRAIT</p></td> <td class="enum_member_description"> <p>Portrait mode.</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-PAGE-ORIENTATION-LANDSCAPE:CAPS"></a>GTK_PAGE_ORIENTATION_LANDSCAPE</p></td> <td class="enum_member_description"> <p>Landscape mode.</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-PAGE-ORIENTATION-REVERSE-PORTRAIT:CAPS"></a>GTK_PAGE_ORIENTATION_REVERSE_PORTRAIT</p></td> <td class="enum_member_description"> <p>Reverse portrait mode.</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-PAGE-ORIENTATION-REVERSE-LANDSCAPE:CAPS"></a>GTK_PAGE_ORIENTATION_REVERSE_LANDSCAPE</p></td> <td class="enum_member_description"> <p>Reverse landscape mode.</p> </td> <td class="enum_member_annotations"> </td> </tr> </tbody> </table></div> </div> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-ORIENTATION:CAPS"></a><h3>GTK_PRINT_SETTINGS_ORIENTATION</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_ORIENTATION "orientation" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-PAPER-FORMAT:CAPS"></a><h3>GTK_PRINT_SETTINGS_PAPER_FORMAT</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_PAPER_FORMAT "paper-format" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-PAPER-WIDTH:CAPS"></a><h3>GTK_PRINT_SETTINGS_PAPER_WIDTH</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_PAPER_WIDTH "paper-width" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-PAPER-HEIGHT:CAPS"></a><h3>GTK_PRINT_SETTINGS_PAPER_HEIGHT</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_PAPER_HEIGHT "paper-height" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-USE-COLOR:CAPS"></a><h3>GTK_PRINT_SETTINGS_USE_COLOR</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_USE_COLOR "use-color" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-COLLATE:CAPS"></a><h3>GTK_PRINT_SETTINGS_COLLATE</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_COLLATE "collate" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-REVERSE:CAPS"></a><h3>GTK_PRINT_SETTINGS_REVERSE</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_REVERSE "reverse" </pre> </div> <hr> <div class="refsect2"> <a name="GtkPrintDuplex"></a><h3>enum GtkPrintDuplex</h3> <p>See also <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-duplex" title="gtk_print_settings_set_duplex ()"><code class="function">gtk_print_settings_set_duplex()</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.9.12.4"></a><h4>Members</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="300px" class="enum_members_name"> <col class="enum_members_description"> <col width="200px" class="enum_members_annotations"> </colgroup> <tbody> <tr> <td class="enum_member_name"><p><a name="GTK-PRINT-DUPLEX-SIMPLEX:CAPS"></a>GTK_PRINT_DUPLEX_SIMPLEX</p></td> <td class="enum_member_description"> <p>No duplex.</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-PRINT-DUPLEX-HORIZONTAL:CAPS"></a>GTK_PRINT_DUPLEX_HORIZONTAL</p></td> <td class="enum_member_description"> <p>Horizontal duplex.</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-PRINT-DUPLEX-VERTICAL:CAPS"></a>GTK_PRINT_DUPLEX_VERTICAL</p></td> <td class="enum_member_description"> <p>Vertical duplex.</p> </td> <td class="enum_member_annotations"> </td> </tr> </tbody> </table></div> </div> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-DUPLEX:CAPS"></a><h3>GTK_PRINT_SETTINGS_DUPLEX</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_DUPLEX "duplex" </pre> </div> <hr> <div class="refsect2"> <a name="GtkPrintQuality"></a><h3>enum GtkPrintQuality</h3> <p>See also <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-quality" title="gtk_print_settings_set_quality ()"><code class="function">gtk_print_settings_set_quality()</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.9.14.4"></a><h4>Members</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="300px" class="enum_members_name"> <col class="enum_members_description"> <col width="200px" class="enum_members_annotations"> </colgroup> <tbody> <tr> <td class="enum_member_name"><p><a name="GTK-PRINT-QUALITY-LOW:CAPS"></a>GTK_PRINT_QUALITY_LOW</p></td> <td class="enum_member_description"> <p>Low quality.</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-PRINT-QUALITY-NORMAL:CAPS"></a>GTK_PRINT_QUALITY_NORMAL</p></td> <td class="enum_member_description"> <p>Normal quality.</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-PRINT-QUALITY-HIGH:CAPS"></a>GTK_PRINT_QUALITY_HIGH</p></td> <td class="enum_member_description"> <p>High quality.</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-PRINT-QUALITY-DRAFT:CAPS"></a>GTK_PRINT_QUALITY_DRAFT</p></td> <td class="enum_member_description"> <p>Draft quality.</p> </td> <td class="enum_member_annotations"> </td> </tr> </tbody> </table></div> </div> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-QUALITY:CAPS"></a><h3>GTK_PRINT_SETTINGS_QUALITY</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_QUALITY "quality" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-N-COPIES:CAPS"></a><h3>GTK_PRINT_SETTINGS_N_COPIES</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_N_COPIES "n-copies" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-NUMBER-UP:CAPS"></a><h3>GTK_PRINT_SETTINGS_NUMBER_UP</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_NUMBER_UP "number-up" </pre> </div> <hr> <div class="refsect2"> <a name="GtkNumberUpLayout"></a><h3>enum GtkNumberUpLayout</h3> <p>Used to determine the layout of pages on a sheet when printing multiple pages per sheet.</p> <div class="refsect3"> <a name="id-1.3.17.4.9.18.4"></a><h4>Members</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="300px" class="enum_members_name"> <col class="enum_members_description"> <col width="200px" class="enum_members_annotations"> </colgroup> <tbody> <tr> <td class="enum_member_name"><p><a name="GTK-NUMBER-UP-LAYOUT-LEFT-TO-RIGHT-TOP-TO-BOTTOM:CAPS"></a>GTK_NUMBER_UP_LAYOUT_LEFT_TO_RIGHT_TOP_TO_BOTTOM</p></td> <td class="enum_member_description"> <p><span class="inlinemediaobject"><img src="layout-lrtb.png"></span></p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-NUMBER-UP-LAYOUT-LEFT-TO-RIGHT-BOTTOM-TO-TOP:CAPS"></a>GTK_NUMBER_UP_LAYOUT_LEFT_TO_RIGHT_BOTTOM_TO_TOP</p></td> <td class="enum_member_description"> <p><span class="inlinemediaobject"><img src="layout-lrbt.png"></span></p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-NUMBER-UP-LAYOUT-RIGHT-TO-LEFT-TOP-TO-BOTTOM:CAPS"></a>GTK_NUMBER_UP_LAYOUT_RIGHT_TO_LEFT_TOP_TO_BOTTOM</p></td> <td class="enum_member_description"> <p><span class="inlinemediaobject"><img src="layout-rltb.png"></span></p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-NUMBER-UP-LAYOUT-RIGHT-TO-LEFT-BOTTOM-TO-TOP:CAPS"></a>GTK_NUMBER_UP_LAYOUT_RIGHT_TO_LEFT_BOTTOM_TO_TOP</p></td> <td class="enum_member_description"> <p><span class="inlinemediaobject"><img src="layout-rlbt.png"></span></p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-NUMBER-UP-LAYOUT-TOP-TO-BOTTOM-LEFT-TO-RIGHT:CAPS"></a>GTK_NUMBER_UP_LAYOUT_TOP_TO_BOTTOM_LEFT_TO_RIGHT</p></td> <td class="enum_member_description"> <p><span class="inlinemediaobject"><img src="layout-tblr.png"></span></p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-NUMBER-UP-LAYOUT-TOP-TO-BOTTOM-RIGHT-TO-LEFT:CAPS"></a>GTK_NUMBER_UP_LAYOUT_TOP_TO_BOTTOM_RIGHT_TO_LEFT</p></td> <td class="enum_member_description"> <p><span class="inlinemediaobject"><img src="layout-tbrl.png"></span></p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-NUMBER-UP-LAYOUT-BOTTOM-TO-TOP-LEFT-TO-RIGHT:CAPS"></a>GTK_NUMBER_UP_LAYOUT_BOTTOM_TO_TOP_LEFT_TO_RIGHT</p></td> <td class="enum_member_description"> <p><span class="inlinemediaobject"><img src="layout-btlr.png"></span></p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-NUMBER-UP-LAYOUT-BOTTOM-TO-TOP-RIGHT-TO-LEFT:CAPS"></a>GTK_NUMBER_UP_LAYOUT_BOTTOM_TO_TOP_RIGHT_TO_LEFT</p></td> <td class="enum_member_description"> <p><span class="inlinemediaobject"><img src="layout-btrl.png"></span></p> </td> <td class="enum_member_annotations"> </td> </tr> </tbody> </table></div> </div> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-NUMBER-UP-LAYOUT:CAPS"></a><h3>GTK_PRINT_SETTINGS_NUMBER_UP_LAYOUT</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_NUMBER_UP_LAYOUT "number-up-layout" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-RESOLUTION:CAPS"></a><h3>GTK_PRINT_SETTINGS_RESOLUTION</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_RESOLUTION "resolution" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-RESOLUTION-X:CAPS"></a><h3>GTK_PRINT_SETTINGS_RESOLUTION_X</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_RESOLUTION_X "resolution-x" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-RESOLUTION-Y:CAPS"></a><h3>GTK_PRINT_SETTINGS_RESOLUTION_Y</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_RESOLUTION_Y "resolution-y" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-PRINTER-LPI:CAPS"></a><h3>GTK_PRINT_SETTINGS_PRINTER_LPI</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_PRINTER_LPI "printer-lpi" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-SCALE:CAPS"></a><h3>GTK_PRINT_SETTINGS_SCALE</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_SCALE "scale" </pre> </div> <hr> <div class="refsect2"> <a name="GtkPrintPages"></a><h3>enum GtkPrintPages</h3> <p>See also <a class="link" href="GtkPrintJob.html#gtk-print-job-set-pages" title="gtk_print_job_set_pages ()"><code class="function">gtk_print_job_set_pages()</code></a></p> <div class="refsect3"> <a name="id-1.3.17.4.9.25.4"></a><h4>Members</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="300px" class="enum_members_name"> <col class="enum_members_description"> <col width="200px" class="enum_members_annotations"> </colgroup> <tbody> <tr> <td class="enum_member_name"><p><a name="GTK-PRINT-PAGES-ALL:CAPS"></a>GTK_PRINT_PAGES_ALL</p></td> <td class="enum_member_description"> <p>All pages.</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-PRINT-PAGES-CURRENT:CAPS"></a>GTK_PRINT_PAGES_CURRENT</p></td> <td class="enum_member_description"> <p>Current page.</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-PRINT-PAGES-RANGES:CAPS"></a>GTK_PRINT_PAGES_RANGES</p></td> <td class="enum_member_description"> <p>Range of pages.</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-PRINT-PAGES-SELECTION:CAPS"></a>GTK_PRINT_PAGES_SELECTION</p></td> <td class="enum_member_description"> <p>Selected pages.</p> </td> <td class="enum_member_annotations"> </td> </tr> </tbody> </table></div> </div> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-PRINT-PAGES:CAPS"></a><h3>GTK_PRINT_SETTINGS_PRINT_PAGES</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_PRINT_PAGES "print-pages" </pre> </div> <hr> <div class="refsect2"> <a name="GtkPageRange"></a><h3>struct GtkPageRange</h3> <pre class="programlisting">struct GtkPageRange { gint start; gint end; }; </pre> <p>See also <a class="link" href="GtkPrintSettings.html#gtk-print-settings-set-page-ranges" title="gtk_print_settings_set_page_ranges ()"><code class="function">gtk_print_settings_set_page_ranges()</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.9.27.5"></a><h4>Members</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="300px" class="struct_members_name"> <col class="struct_members_description"> <col width="200px" class="struct_members_annotations"> </colgroup> <tbody> <tr> <td class="struct_member_name"><p><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="type">gint</span></a> <em class="structfield"><code><a name="GtkPageRange.start"></a>start</code></em>;</p></td> <td class="struct_member_description"><p>start of page range.</p></td> <td class="struct_member_annotations"> </td> </tr> <tr> <td class="struct_member_name"><p><a href="https://developer.gnome.org/glib/unstable/glib-Basic-Types.html#gint"><span class="type">gint</span></a> <em class="structfield"><code><a name="GtkPageRange.end"></a>end</code></em>;</p></td> <td class="struct_member_description"><p>end of page range.</p></td> <td class="struct_member_annotations"> </td> </tr> </tbody> </table></div> </div> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-PAGE-RANGES:CAPS"></a><h3>GTK_PRINT_SETTINGS_PAGE_RANGES</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_PAGE_RANGES "page-ranges" </pre> </div> <hr> <div class="refsect2"> <a name="GtkPageSet"></a><h3>enum GtkPageSet</h3> <p>See also <a class="link" href="GtkPrintJob.html#gtk-print-job-set-page-set" title="gtk_print_job_set_page_set ()"><code class="function">gtk_print_job_set_page_set()</code></a>.</p> <div class="refsect3"> <a name="id-1.3.17.4.9.29.4"></a><h4>Members</h4> <div class="informaltable"><table width="100%" border="0"> <colgroup> <col width="300px" class="enum_members_name"> <col class="enum_members_description"> <col width="200px" class="enum_members_annotations"> </colgroup> <tbody> <tr> <td class="enum_member_name"><p><a name="GTK-PAGE-SET-ALL:CAPS"></a>GTK_PAGE_SET_ALL</p></td> <td class="enum_member_description"> <p>All pages.</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-PAGE-SET-EVEN:CAPS"></a>GTK_PAGE_SET_EVEN</p></td> <td class="enum_member_description"> <p>Even pages.</p> </td> <td class="enum_member_annotations"> </td> </tr> <tr> <td class="enum_member_name"><p><a name="GTK-PAGE-SET-ODD:CAPS"></a>GTK_PAGE_SET_ODD</p></td> <td class="enum_member_description"> <p>Odd pages.</p> </td> <td class="enum_member_annotations"> </td> </tr> </tbody> </table></div> </div> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-PAGE-SET:CAPS"></a><h3>GTK_PRINT_SETTINGS_PAGE_SET</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_PAGE_SET "page-set" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-DEFAULT-SOURCE:CAPS"></a><h3>GTK_PRINT_SETTINGS_DEFAULT_SOURCE</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_DEFAULT_SOURCE "default-source" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-MEDIA-TYPE:CAPS"></a><h3>GTK_PRINT_SETTINGS_MEDIA_TYPE</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_MEDIA_TYPE "media-type" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-DITHER:CAPS"></a><h3>GTK_PRINT_SETTINGS_DITHER</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_DITHER "dither" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-FINISHINGS:CAPS"></a><h3>GTK_PRINT_SETTINGS_FINISHINGS</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_FINISHINGS "finishings" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-OUTPUT-BIN:CAPS"></a><h3>GTK_PRINT_SETTINGS_OUTPUT_BIN</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_OUTPUT_BIN "output-bin" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-OUTPUT-DIR:CAPS"></a><h3>GTK_PRINT_SETTINGS_OUTPUT_DIR</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_OUTPUT_DIR "output-dir" </pre> <p>The key used by the “Print to file” printer to store the directory to which the output should be written.</p> <p class="since">Since 3.6</p> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-OUTPUT-BASENAME:CAPS"></a><h3>GTK_PRINT_SETTINGS_OUTPUT_BASENAME</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_OUTPUT_BASENAME "output-basename" </pre> <p>The key used by the “Print to file” printer to store the file name of the output without the path to the directory and the file extension.</p> <p class="since">Since 3.6</p> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-OUTPUT-FILE-FORMAT:CAPS"></a><h3>GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT "output-file-format" </pre> <p>The key used by the “Print to file” printer to store the format of the output. The supported values are “PS” and “PDF”.</p> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-OUTPUT-URI:CAPS"></a><h3>GTK_PRINT_SETTINGS_OUTPUT_URI</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_OUTPUT_URI "output-uri" </pre> <p>The key used by the “Print to file” printer to store the URI to which the output should be written. GTK+ itself supports only “file://” URIs.</p> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-WIN32-DRIVER-EXTRA:CAPS"></a><h3>GTK_PRINT_SETTINGS_WIN32_DRIVER_EXTRA</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_WIN32_DRIVER_EXTRA "win32-driver-extra" </pre> </div> <hr> <div class="refsect2"> <a name="GTK-PRINT-SETTINGS-WIN32-DRIVER-VERSION:CAPS"></a><h3>GTK_PRINT_SETTINGS_WIN32_DRIVER_VERSION</h3> <pre class="programlisting">#define GTK_PRINT_SETTINGS_WIN32_DRIVER_VERSION "win32-driver-version" </pre> </div> </div> </div> <div class="footer"> <hr> Generated by GTK-Doc V1.21.1</div> </body> </html>
linuxmint/gtk
docs/reference/gtk/html/GtkPrintSettings.html
HTML
lgpl-2.1
195,776
/* * This file emulates the db3/4 structures * ...this is supposed to be compatable w/ the _real_ db.h! */ #ifndef __DB_EMU_H #define __DB_EMU_H struct __db; typedef struct __db DB; struct __db_dbt; typedef struct __db_dbt DBT; struct __db_env; typedef struct __db_env DB_ENV; struct __dbc; typedef struct __dbc DBC; struct __db_txn; typedef struct __db_txn DB_TXN; struct __db_h_stat; typedef struct __db_h_stat DB_HASH_STAT; /* Database handle */ struct __db { void *app_private; }; struct __db_dbt { rpmuint32_t size; void *data; #define DB_DBT_MALLOC 0x01 /* We malloc the memory and hand off a copy. */ rpmuint32_t flags; }; struct __db_env { void *app_private; }; struct __dbc { DB *dbp; }; struct __db_txn { /* NULL */ ; }; struct __db_h_stat { rpmuint32_t hash_nkeys; }; #define DB_FAST_STAT 11 #define DB_KEYLAST 19 #define DB_NEXT 21 #define DB_SET 32 #define DB_WRITECURSOR 39 #define DB_NOTFOUND (-30990) #define DB_PRIVATE 0x0200000 #define DB_EXCL 0x0004000 #define DB_VERSION_MAJOR 3 #define DB_VERSION_MINOR 0 #define DB_VERSION_PATCH 0 #endif
devzero2000/RPM5
rpmdb/db_emu.h
C
lgpl-2.1
1,112
// The libMesh Finite Element Library. // Copyright (C) 2002-2020 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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 // DiffSystem framework files #include "libmesh/fem_system.h" using namespace libMesh; // The Navier-Stokes system class. // FEMSystem, TimeSolver and NewtonSolver will handle most tasks, // but we must specify element residuals class NavierSystem : public FEMSystem { public: // Constructor NavierSystem(EquationSystems & es, const std::string & name_in, const unsigned int number_in) : FEMSystem(es, name_in, number_in), Reynolds(1.), application(0) {} // System initialization virtual void init_data (); // Context initialization virtual void init_context(DiffContext & context); // Element residual and jacobian calculations // Time dependent parts virtual bool element_time_derivative (bool request_jacobian, DiffContext & context); // Constraint parts virtual bool element_constraint (bool request_jacobian, DiffContext & context); virtual bool side_constraint (bool request_jacobian, DiffContext & context); // Mass matrix part virtual bool mass_residual (bool request_jacobian, DiffContext & context); // Postprocessed output virtual void postprocess (); // Indices for each variable; unsigned int p_var, u_var, v_var, w_var; // The Reynolds number to solve for Real Reynolds; // The application number controls what boundary conditions and/or // forcing functions are applied. Current options are: // 0 - discontinuous lid velocity driven cavity // 1 - homogeneous Dirichlet BC with smooth forcing unsigned int application; // Returns the value of a forcing function at point p. This value // depends on which application is being used. Point forcing(const Point & p); };
capitalaslash/libmesh
examples/fem_system/fem_system_ex1/naviersystem.h
C
lgpl-2.1
2,674
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>libsigc++: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- Generated by Doxygen 1.7.3 --> <div id="top"> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">libsigc++&#160;<span id="projectnumber">2.2.10</span></div> </td> </tr> </tbody> </table> </div> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacesigc.html">sigc</a> </li> <li class="navelem"><a class="el" href="classsigc_1_1signal5.html">signal5</a> </li> </ul> </div> </div> <div class="header"> <div class="headertitle"> <h1>sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt; Member List</h1> </div> </div> <div class="contents"> This is the complete list of members for <a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a>, including all inherited members.<table> <tr class="memlist"><td><a class="el" href="structsigc_1_1trackable.html#ab14931670837728e49bb5ca88fb16db5">add_destroy_notify_callback</a>(void* data, func_destroy_notify func) const </td><td><a class="el" href="structsigc_1_1trackable.html">sigc::trackable</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="structsigc_1_1signal__base.html#a17597d66e680d222248c523985f0afd6">clear</a>()</td><td><a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classsigc_1_1signal5.html#a057789cc27a920700e240f8f3d78dd65">connect</a>(const slot_type&amp; slot_)</td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="structsigc_1_1signal__base.html#a5c89a76a27d69c512f554b841b1bd08a">sigc::signal_base::connect</a>(const slot_base&amp; slot_)</td><td><a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a></td><td><code> [protected]</code></td></tr> <tr bgcolor="#f0f0f0"><td><b>const_iterator</b> typedef (defined in <a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a>)</td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>const_reverse_iterator</b> typedef (defined in <a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a>)</td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classsigc_1_1signal5.html#adb7ae6a12e70f96bfdf2b0d36ba0d974">emit</a>(typename type_trait&lt; T_arg1 &gt;::take _A_a1, typename type_trait&lt; T_arg2 &gt;::take _A_a2, typename type_trait&lt; T_arg3 &gt;::take _A_a3, typename type_trait&lt; T_arg4 &gt;::take _A_a4, typename type_trait&lt; T_arg5 &gt;::take _A_a5) const </td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classsigc_1_1signal5.html#ac9a8f41617fae87eeb809f8f542a5f93">emit_reverse</a>(typename type_trait&lt; T_arg1 &gt;::take _A_a1, typename type_trait&lt; T_arg2 &gt;::take _A_a2, typename type_trait&lt; T_arg3 &gt;::take _A_a3, typename type_trait&lt; T_arg4 &gt;::take _A_a4, typename type_trait&lt; T_arg5 &gt;::take _A_a5) const </td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td><code> [inline]</code></td></tr> <tr bgcolor="#f0f0f0"><td><b>emitter_type</b> typedef (defined in <a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a>)</td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="structsigc_1_1signal__base.html#abc8fe88ca813837ff3fb3ef4ecb4e8a7">empty</a>() const </td><td><a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="structsigc_1_1signal__base.html#a21efc57eea29c3139855909ad4807984">erase</a>(iterator_type i)</td><td><a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a></td><td><code> [protected]</code></td></tr> <tr bgcolor="#f0f0f0"><td><b>func_destroy_notify</b> typedef (defined in <a class="el" href="structsigc_1_1trackable.html">sigc::trackable</a>)</td><td><a class="el" href="structsigc_1_1trackable.html">sigc::trackable</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="structsigc_1_1signal__base.html#ab1b7d9bc2a59c4c67d0123a65a7baab9">impl</a>() const </td><td><a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="structsigc_1_1signal__base.html#a747d448c28fd256ef580d165eb69f17a">impl_</a></td><td><a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a></td><td><code> [mutable, protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="structsigc_1_1signal__base.html#a87da23ad801faa9e2b6b4be2a747e757">insert</a>(iterator_type i, const slot_base&amp; slot_)</td><td><a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a></td><td><code> [protected]</code></td></tr> <tr bgcolor="#f0f0f0"><td><b>iterator</b> typedef (defined in <a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a>)</td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>iterator_type</b> typedef (defined in <a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a>)</td><td><a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classsigc_1_1signal5.html#a7ed3002fdf8a0b3cb3769d7edc0c729b">make_slot</a>() const </td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="structsigc_1_1trackable.html#af2e23cfe7adc1ca844a3350bbac557cb">notify_callbacks</a>()</td><td><a class="el" href="structsigc_1_1trackable.html">sigc::trackable</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classsigc_1_1signal5.html#a17d8e59e84767681fc29d679287f7770">operator()</a>(typename type_trait&lt; T_arg1 &gt;::take _A_a1, typename type_trait&lt; T_arg2 &gt;::take _A_a2, typename type_trait&lt; T_arg3 &gt;::take _A_a3, typename type_trait&lt; T_arg4 &gt;::take _A_a4, typename type_trait&lt; T_arg5 &gt;::take _A_a5) const </td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td><code> [inline]</code></td></tr> <tr bgcolor="#f0f0f0"><td><b>operator=</b>(const signal_base&amp; src) (defined in <a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a>)</td><td><a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>operator=</b>(const trackable&amp; src) (defined in <a class="el" href="structsigc_1_1trackable.html">sigc::trackable</a>)</td><td><a class="el" href="structsigc_1_1trackable.html">sigc::trackable</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="structsigc_1_1trackable.html#a8b9dffa8a50ff13ba33e6c7f10468e2b">remove_destroy_notify_callback</a>(void* data) const </td><td><a class="el" href="structsigc_1_1trackable.html">sigc::trackable</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>result_type</b> typedef (defined in <a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a>)</td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>reverse_iterator</b> typedef (defined in <a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a>)</td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>signal5</b>() (defined in <a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a>)</td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td><code> [inline]</code></td></tr> <tr bgcolor="#f0f0f0"><td><b>signal5</b>(const signal5&amp; src) (defined in <a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a>)</td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td><code> [inline]</code></td></tr> <tr bgcolor="#f0f0f0"><td><b>signal_base</b>() (defined in <a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a>)</td><td><a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>signal_base</b>(const signal_base&amp; src) (defined in <a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a>)</td><td><a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="structsigc_1_1signal__base.html#a06e0889c75cccc15dcec71a48acae00d">size</a>() const </td><td><a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>size_type</b> typedef (defined in <a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a>)</td><td><a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>slot_list_type</b> typedef (defined in <a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a>)</td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>slot_type</b> typedef (defined in <a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a>)</td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classsigc_1_1signal5.html#ad6a4ae2a214d8710be6e36bb425587fc">slots</a>()</td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classsigc_1_1signal5.html#a84f5c68895c8d6da07c1caa00088617b">slots</a>() const </td><td><a class="el" href="classsigc_1_1signal5.html">sigc::signal5&lt; T_return, T_arg1, T_arg2, T_arg3, T_arg4, T_arg5, T_accumulator &gt;</a></td><td><code> [inline]</code></td></tr> <tr bgcolor="#f0f0f0"><td><b>trackable</b>() (defined in <a class="el" href="structsigc_1_1trackable.html">sigc::trackable</a>)</td><td><a class="el" href="structsigc_1_1trackable.html">sigc::trackable</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>trackable</b>(const trackable&amp; src) (defined in <a class="el" href="structsigc_1_1trackable.html">sigc::trackable</a>)</td><td><a class="el" href="structsigc_1_1trackable.html">sigc::trackable</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>~signal_base</b>() (defined in <a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a>)</td><td><a class="el" href="structsigc_1_1signal__base.html">sigc::signal_base</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>~trackable</b>() (defined in <a class="el" href="structsigc_1_1trackable.html">sigc::trackable</a>)</td><td><a class="el" href="structsigc_1_1trackable.html">sigc::trackable</a></td><td></td></tr> </table></div> <hr class="footer"/><address class="footer"><small>Generated on Mon Jul 25 2011 09:51:24 for libsigc++ by&#160; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.3 </small></address> </body> </html>
reven86/libsigcpp-multiplatform
docs/reference/html/classsigc_1_1signal5-members.html
HTML
lgpl-2.1
14,704
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** 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 [email protected]. ** **************************************************************************/ // Copyright (c) 2008 Roberto Raggi <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "TranslationUnit.h" #include "Control.h" #include "Parser.h" #include "Lexer.h" #include "MemoryPool.h" #include "AST.h" #include "Literals.h" #include "DiagnosticClient.h" #include <stack> #include <cstdarg> #include <algorithm> #ifdef _MSC_VER # define va_copy(dst, src) ((dst) = (src)) #elif defined(__INTEL_COMPILER) && !defined(va_copy) # define va_copy __va_copy #endif using namespace CPlusPlus; TranslationUnit::TranslationUnit(Control *control, const StringLiteral *fileId) : _control(control), _fileId(fileId), _firstSourceChar(0), _lastSourceChar(0), _pool(0), _ast(0), _flags(0) { _tokens = new std::vector<Token>(); _previousTranslationUnit = control->switchTranslationUnit(this); _pool = new MemoryPool(); } TranslationUnit::~TranslationUnit() { (void) _control->switchTranslationUnit(_previousTranslationUnit); delete _tokens; delete _pool; } bool TranslationUnit::qtMocRunEnabled() const { return f._qtMocRunEnabled; } void TranslationUnit::setQtMocRunEnabled(bool onoff) { f._qtMocRunEnabled = onoff; } bool TranslationUnit::cxx0xEnabled() const { return f._cxx0xEnabled; } void TranslationUnit::setCxxOxEnabled(bool onoff) { f._cxx0xEnabled = onoff; } bool TranslationUnit::objCEnabled() const { return f._objCEnabled; } void TranslationUnit::setObjCEnabled(bool onoff) { f._objCEnabled = onoff; } Control *TranslationUnit::control() const { return _control; } const StringLiteral *TranslationUnit::fileId() const { return _fileId; } const char *TranslationUnit::fileName() const { return _fileId->chars(); } unsigned TranslationUnit::fileNameLength() const { return _fileId->size(); } const char *TranslationUnit::firstSourceChar() const { return _firstSourceChar; } const char *TranslationUnit::lastSourceChar() const { return _lastSourceChar; } unsigned TranslationUnit::sourceLength() const { return _lastSourceChar - _firstSourceChar; } void TranslationUnit::setSource(const char *source, unsigned size) { _firstSourceChar = source; _lastSourceChar = source + size; } unsigned TranslationUnit::tokenCount() const { return _tokens->size(); } const Token &TranslationUnit::tokenAt(unsigned index) const { return _tokens->at(index); } int TranslationUnit::tokenKind(unsigned index) const { return _tokens->at(index).f.kind; } const char *TranslationUnit::spell(unsigned index) const { if (! index) return 0; return _tokens->at(index).spell(); } const Identifier *TranslationUnit::identifier(unsigned index) const { return _tokens->at(index).identifier; } const Literal *TranslationUnit::literal(unsigned index) const { return _tokens->at(index).literal; } const StringLiteral *TranslationUnit::stringLiteral(unsigned index) const { return _tokens->at(index).string; } const NumericLiteral *TranslationUnit::numericLiteral(unsigned index) const { return _tokens->at(index).number; } unsigned TranslationUnit::matchingBrace(unsigned index) const { return _tokens->at(index).close_brace; } MemoryPool *TranslationUnit::memoryPool() const { return _pool; } AST *TranslationUnit::ast() const { return _ast; } bool TranslationUnit::isTokenized() const { return f._tokenized; } bool TranslationUnit::isParsed() const { return f._parsed; } void TranslationUnit::tokenize() { if (isTokenized()) return; f._tokenized = true; Lexer lex(this); lex.setQtMocRunEnabled(f._qtMocRunEnabled); lex.setCxxOxEnabled(f._cxx0xEnabled); lex.setObjCEnabled(f._objCEnabled); std::stack<unsigned> braces; _tokens->push_back(Token()); // the first token needs to be invalid! pushLineOffset(0); pushPreprocessorLine(0, 1, fileId()); const Identifier *lineId = control()->identifier("line"); const Identifier *genId = control()->identifier("gen"); bool generated = false; Token tk; do { lex(&tk); _Lrecognize: if (tk.is(T_POUND) && tk.newline()) { unsigned offset = tk.offset; lex(&tk); if (! tk.f.newline && tk.is(T_IDENTIFIER) && tk.identifier == genId) { // it's a gen directive. lex(&tk); if (! tk.f.newline && tk.is(T_TRUE)) { lex(&tk); generated = true; } else { generated = false; } } else { if (! tk.f.newline && tk.is(T_IDENTIFIER) && tk.identifier == lineId) lex(&tk); if (! tk.f.newline && tk.is(T_NUMERIC_LITERAL)) { unsigned line = (unsigned) strtoul(tk.spell(), 0, 0); lex(&tk); if (! tk.f.newline && tk.is(T_STRING_LITERAL)) { const StringLiteral *fileName = control()->stringLiteral(tk.string->chars(), tk.string->size()); pushPreprocessorLine(offset, line, fileName); lex(&tk); } } } while (tk.isNot(T_EOF_SYMBOL) && ! tk.f.newline) lex(&tk); goto _Lrecognize; } else if (tk.f.kind == T_LBRACE) { braces.push(_tokens->size()); } else if (tk.f.kind == T_RBRACE && ! braces.empty()) { const unsigned open_brace_index = braces.top(); braces.pop(); (*_tokens)[open_brace_index].close_brace = _tokens->size(); } tk.f.generated = generated; _tokens->push_back(tk); } while (tk.f.kind); for (; ! braces.empty(); braces.pop()) { unsigned open_brace_index = braces.top(); (*_tokens)[open_brace_index].close_brace = _tokens->size(); } } bool TranslationUnit::skipFunctionBody() const { return f._skipFunctionBody; } void TranslationUnit::setSkipFunctionBody(bool skipFunctionBody) { f._skipFunctionBody = skipFunctionBody; } bool TranslationUnit::parse(ParseMode mode) { if (isParsed()) return false; if (! isTokenized()) tokenize(); f._parsed = true; Parser parser(this); parser.setQtMocRunEnabled(f._qtMocRunEnabled); parser.setCxxOxEnabled(f._cxx0xEnabled); parser.setObjCEnabled(f._objCEnabled); bool parsed = false; switch (mode) { case ParseTranlationUnit: { TranslationUnitAST *node = 0; parsed = parser.parseTranslationUnit(node); _ast = node; } break; case ParseDeclaration: { DeclarationAST *node = 0; parsed = parser.parseDeclaration(node); _ast = node; } break; case ParseExpression: { ExpressionAST *node = 0; parsed = parser.parseExpression(node); _ast = node; } break; case ParseDeclarator: { DeclaratorAST *node = 0; parsed = parser.parseDeclarator(node, /*decl_specifier_list =*/ 0); _ast = node; } break; case ParseStatement: { StatementAST *node = 0; parsed = parser.parseStatement(node); _ast = node; } break; default: break; } // switch return parsed; } void TranslationUnit::pushLineOffset(unsigned offset) { _lineOffsets.push_back(offset); } void TranslationUnit::pushPreprocessorLine(unsigned offset, unsigned line, const StringLiteral *fileName) { _ppLines.push_back(PPLine(offset, line, fileName)); } unsigned TranslationUnit::findLineNumber(unsigned offset) const { std::vector<unsigned>::const_iterator it = std::lower_bound(_lineOffsets.begin(), _lineOffsets.end(), offset); if (it != _lineOffsets.begin()) --it; return it - _lineOffsets.begin(); } TranslationUnit::PPLine TranslationUnit::findPreprocessorLine(unsigned offset) const { std::vector<PPLine>::const_iterator it = std::lower_bound(_ppLines.begin(), _ppLines.end(), PPLine(offset)); if (it != _ppLines.begin()) --it; return *it; } unsigned TranslationUnit::findColumnNumber(unsigned offset, unsigned lineNumber) const { if (! offset) return 0; return offset - _lineOffsets[lineNumber]; } void TranslationUnit::getTokenPosition(unsigned index, unsigned *line, unsigned *column, const StringLiteral **fileName) const { return getPosition(tokenAt(index).offset, line, column, fileName); } void TranslationUnit::getTokenStartPosition(unsigned index, unsigned *line, unsigned *column, const StringLiteral **fileName) const { return getPosition(tokenAt(index).begin(), line, column, fileName); } void TranslationUnit::getTokenEndPosition(unsigned index, unsigned *line, unsigned *column, const StringLiteral **fileName) const { return getPosition(tokenAt(index).end(), line, column, fileName); } void TranslationUnit::getPosition(unsigned tokenOffset, unsigned *line, unsigned *column, const StringLiteral **fileName) const { unsigned lineNumber = findLineNumber(tokenOffset); unsigned columnNumber = findColumnNumber(tokenOffset, lineNumber); const PPLine ppLine = findPreprocessorLine(tokenOffset); lineNumber -= findLineNumber(ppLine.offset) + 1; lineNumber += ppLine.line; if (line) *line = lineNumber; if (column) *column = columnNumber; if (fileName) *fileName = ppLine.fileName; } bool TranslationUnit::blockErrors(bool block) { bool previous = f._blockErrors; f._blockErrors = block; return previous; } void TranslationUnit::message(DiagnosticClient::Level level, unsigned index, const char *format, va_list args) { if (f._blockErrors) return; index = std::min(index, tokenCount() - 1); unsigned line = 0, column = 0; const StringLiteral *fileName = 0; getTokenPosition(index, &line, &column, &fileName); if (DiagnosticClient *client = control()->diagnosticClient()) { client->report(level, fileName, line, column, format, args); } else { fprintf(stderr, "%s:%d: ", fileName->chars(), line); const char *l = "error"; if (level == DiagnosticClient::Warning) l = "warning"; else if (level == DiagnosticClient::Fatal) l = "fatal"; fprintf(stderr, "%s: ", l); vfprintf(stderr, format, args); fputc('\n', stderr); showErrorLine(index, column, stderr); } if (level == DiagnosticClient::Fatal) exit(EXIT_FAILURE); } void TranslationUnit::warning(unsigned index, const char *format, ...) { if (f._blockErrors) return; va_list args, ap; va_start(args, format); va_copy(ap, args); message(DiagnosticClient::Warning, index, format, args); va_end(ap); va_end(args); } void TranslationUnit::error(unsigned index, const char *format, ...) { if (f._blockErrors) return; va_list args, ap; va_start(args, format); va_copy(ap, args); message(DiagnosticClient::Error, index, format, args); va_end(ap); va_end(args); } void TranslationUnit::fatal(unsigned index, const char *format, ...) { if (f._blockErrors) return; va_list args, ap; va_start(args, format); va_copy(ap, args); message(DiagnosticClient::Fatal, index, format, args); va_end(ap); va_end(args); } unsigned TranslationUnit::findPreviousLineOffset(unsigned tokenIndex) const { unsigned lineOffset = _lineOffsets[findLineNumber(_tokens->at(tokenIndex).offset)]; return lineOffset; } void TranslationUnit::showErrorLine(unsigned index, unsigned column, FILE *out) { unsigned lineOffset = _lineOffsets[findLineNumber(_tokens->at(index).offset)]; for (const char *cp = _firstSourceChar + lineOffset + 1; *cp && *cp != '\n'; ++cp) { fputc(*cp, out); } fputc('\n', out); const char *end = _firstSourceChar + lineOffset + 1 + column - 1; for (const char *cp = _firstSourceChar + lineOffset + 1; cp != end; ++cp) { if (*cp != '\t') fputc(' ', out); else fputc('\t', out); } fputc('^', out); fputc('\n', out); } void TranslationUnit::resetAST() { delete _pool; _pool = 0; _ast = 0; } void TranslationUnit::release() { resetAST(); delete _tokens; _tokens = 0; }
yinyunqiao/qtcreator
src/shared/cplusplus/TranslationUnit.cpp
C++
lgpl-2.1
15,284
package org.neuroph.contrib.graphml; /** * XML header, specifying the XML version and character encoding standard. * * Here XML version is set to 1.0 and encoding to UTF-8. * * @author fernando carrillo ([email protected]) * */ public class XMLHeader { public static String getHeader() { return getHeader("1.0", "UTF-8"); } public static String getHeader( final String version, final String encoding ) { String out = "<?xml"; out += " " + new XMLAttribute("version", version ); out += " " + new XMLAttribute("encoding", encoding ); out += " ?>"; return out; } }
mhl787156/MinecraftAI
libraries/neuroph-2.92/sources/neuroph-2.92/Contrib/src/main/java/org/neuroph/contrib/graphml/XMLHeader.java
Java
lgpl-2.1
604
#include <math.h> #include <iostream> #include "../libvideogfx/libvideogfx.hh" #include <unistd.h> using namespace std; using namespace videogfx; int main() { try { int16 sine [44100]; int16 sine2[44100]; for (int i=0;i<44100;i++) { sine [i] = (int)(20000*sin(2*M_PI*i* 500/44100)); sine2[i] = (int)(20000*sin(2*M_PI*i* 750/44100)); } AudioSink_LinuxSndCard snd; AudioParam param; param.n_channels = 2; param.rate = 44100; snd.SetParam(param); param = snd.AskParam(); int16 buf[2*44100]; for (int i=0;i<44100;i++) { buf[2*i ]=sine [i]; buf[2*i+1]=sine2[i]; } for (int i=0;i<5;i++) { snd.SendSamples(buf,2*44100); } while (snd.PresentationDataPending()) { snd.PresentData(snd.NextDataPresentationTime()); usleep(100000); } } catch (const Excpt_Base& e) { MessageDisplay::Show(e); } return 0; }
swederik/libvideogfx
examples/audioout.cc
C++
lgpl-2.1
939
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2016, by Object Refinery Limited 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.] * * ----------- * XYPlot.java * ----------- * (C) Copyright 2000-2016, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Craig MacFarlane; * Mark Watson (www.markwatson.com); * Jonathan Nash; * Gideon Krause; * Klaus Rheinwald; * Xavier Poinsard; * Richard Atkinson; * Arnaud Lelievre; * Nicolas Brodu; * Eduardo Ramalho; * Sergei Ivanov; * Richard West, Advanced Micro Devices, Inc.; * Ulrich Voigt - patches 1997549 and 2686040; * Peter Kolb - patches 1934255, 2603321 and 2809117; * Andrew Mickish - patch 1868749; * * Changes (from 21-Jun-2001) * -------------------------- * 21-Jun-2001 : Removed redundant JFreeChart parameter from constructors (DG); * 18-Sep-2001 : Updated header and fixed DOS encoding problem (DG); * 15-Oct-2001 : Data source classes moved to com.jrefinery.data.* (DG); * 19-Oct-2001 : Removed the code for drawing the visual representation of each * data point into a separate class StandardXYItemRenderer. * This will make it easier to add variations to the way the * charts are drawn. Based on code contributed by Mark * Watson (DG); * 22-Oct-2001 : Renamed DataSource.java --> Dataset.java etc. (DG); * 20-Nov-2001 : Fixed clipping bug that shows up when chart is displayed * inside JScrollPane (DG); * 12-Dec-2001 : Removed unnecessary 'throws' clauses from constructor (DG); * 13-Dec-2001 : Added skeleton code for tooltips. Added new constructor. (DG); * 16-Jan-2002 : Renamed the tooltips class (DG); * 22-Jan-2002 : Added DrawInfo class, incorporating tooltips and crosshairs. * Crosshairs based on code by Jonathan Nash (DG); * 05-Feb-2002 : Added alpha-transparency setting based on code by Sylvain * Vieujot (DG); * 26-Feb-2002 : Updated getMinimumXXX() and getMaximumXXX() methods to handle * special case when chart is null (DG); * 28-Feb-2002 : Renamed Datasets.java --> DatasetUtilities.java (DG); * 28-Mar-2002 : The plot now registers with the renderer as a property change * listener. Also added a new constructor (DG); * 09-Apr-2002 : Removed the transRangeZero from the renderer.drawItem() * method. Moved the tooltip generator into the renderer (DG); * 23-Apr-2002 : Fixed bug in methods for drawing horizontal and vertical * lines (DG); * 13-May-2002 : Small change to the draw() method so that it works for * OverlaidXYPlot also (DG); * 25-Jun-2002 : Removed redundant import (DG); * 20-Aug-2002 : Renamed getItemRenderer() --> getRenderer(), and * setXYItemRenderer() --> setRenderer() (DG); * 28-Aug-2002 : Added mechanism for (optional) plot annotations (DG); * 02-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 18-Nov-2002 : Added grid settings for both domain and range axis (previously * these were set in the axes) (DG); * 09-Jan-2003 : Further additions to the grid settings, plus integrated plot * border bug fix contributed by Gideon Krause (DG); * 22-Jan-2003 : Removed monolithic constructor (DG); * 04-Mar-2003 : Added 'no data' message, see bug report 691634. Added * secondary range markers using code contributed by Klaus * Rheinwald (DG); * 26-Mar-2003 : Implemented Serializable (DG); * 03-Apr-2003 : Added setDomainAxisLocation() method (DG); * 30-Apr-2003 : Moved annotation drawing into a separate method (DG); * 01-May-2003 : Added multi-pass mechanism for renderers (DG); * 02-May-2003 : Changed axis locations from int to AxisLocation (DG); * 15-May-2003 : Added an orientation attribute (DG); * 02-Jun-2003 : Removed range axis compatibility test (DG); * 05-Jun-2003 : Added domain and range grid bands (sponsored by Focus Computer * Services Ltd) (DG); * 26-Jun-2003 : Fixed bug (757303) in getDataRange() method (DG); * 02-Jul-2003 : Added patch from bug report 698646 (secondary axes for * overlaid plots) (DG); * 23-Jul-2003 : Added support for multiple secondary datasets, axes and * renderers (DG); * 27-Jul-2003 : Added support for stacked XY area charts (RA); * 19-Aug-2003 : Implemented Cloneable (DG); * 01-Sep-2003 : Fixed bug where change to secondary datasets didn't generate * change event (797466) (DG) * 08-Sep-2003 : Added internationalization via use of properties * resourceBundle (RFE 690236) (AL); * 08-Sep-2003 : Changed ValueAxis API (DG); * 08-Sep-2003 : Fixes for serialization (NB); * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG); * 17-Sep-2003 : Fixed zooming to include secondary domain axes (DG); * 18-Sep-2003 : Added getSecondaryDomainAxisCount() and * getSecondaryRangeAxisCount() methods suggested by Eduardo * Ramalho (RFE 808548) (DG); * 23-Sep-2003 : Split domain and range markers into foreground and * background (DG); * 06-Oct-2003 : Fixed bug in clearDomainMarkers() and clearRangeMarkers() * methods. Fixed bug (815876) in addSecondaryRangeMarker() * method. Added new addSecondaryDomainMarker methods (see bug * id 815869) (DG); * 10-Nov-2003 : Added getSecondaryDomain/RangeAxisMappedToDataset() methods * requested by Eduardo Ramalho (DG); * 24-Nov-2003 : Removed unnecessary notification when updating axis anchor * values (DG); * 21-Jan-2004 : Update for renamed method in ValueAxis (DG); * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState (DG); * 12-Mar-2004 : Fixed bug where primary renderer is always used to determine * range type (DG); * 22-Mar-2004 : Fixed cloning bug (DG); * 23-Mar-2004 : Fixed more cloning bugs (DG); * 07-Apr-2004 : Fixed problem with axis range when the secondary renderer is * stacked, see this post in the forum: * http://www.jfree.org/phpBB2/viewtopic.php?t=8204 (DG); * 07-Apr-2004 : Added get/setDatasetRenderingOrder() methods (DG); * 26-Apr-2004 : Added option to fill quadrant areas in the background of the * plot (DG); * 27-Apr-2004 : Removed major distinction between primary and secondary * datasets, renderers and axes (DG); * 30-Apr-2004 : Modified to make use of the new getRangeExtent() method in the * renderer interface (DG); * 13-May-2004 : Added optional fixedLegendItems attribute (DG); * 19-May-2004 : Added indexOf() method (DG); * 03-Jun-2004 : Fixed zooming bug (DG); * 18-Aug-2004 : Added removedAnnotation() method (by tkram01) (DG); * 05-Oct-2004 : Modified storage type for dataset-to-axis maps (DG); * 06-Oct-2004 : Modified getDataRange() method to use renderer to determine * the x-value range (now matches behaviour for y-values). Added * getDomainAxisIndex() method (DG); * 12-Nov-2004 : Implemented new Zoomable interface (DG); * 25-Nov-2004 : Small update to clone() implementation (DG); * 22-Feb-2005 : Changed axis offsets from Spacer --> RectangleInsets (DG); * 24-Feb-2005 : Added indexOf(XYItemRenderer) method (DG); * 21-Mar-2005 : Register plot as change listener in setRenderer() method (DG); * 21-Apr-2005 : Added get/setSeriesRenderingOrder() methods (ET); * 26-Apr-2005 : Removed LOGGER (DG); * 04-May-2005 : Fixed serialization of domain and range markers (DG); * 05-May-2005 : Removed unused draw() method (DG); * 20-May-2005 : Added setDomainAxes() and setRangeAxes() methods, as per * RFE 1183100 (DG); * 01-Jun-2005 : Upon deserialization, register plot as a listener with its * axes, dataset(s) and renderer(s) - see patch 1209475 (DG); * 01-Jun-2005 : Added clearDomainMarkers(int) method to match * clearRangeMarkers(int) (DG); * 06-Jun-2005 : Fixed equals() method to handle GradientPaint (DG); * 09-Jun-2005 : Added setRenderers(), as per RFE 1183100 (DG); * 06-Jul-2005 : Fixed crosshair bug (id = 1233336) (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 26-Jan-2006 : Added getAnnotations() method (DG); * 05-Sep-2006 : Added MarkerChangeEvent support (DG); * 13-Oct-2006 : Fixed initialisation of CrosshairState - see bug report * 1565168 (DG); * 22-Nov-2006 : Fixed equals() and cloning() for quadrant attributes, plus * API doc updates (DG); * 29-Nov-2006 : Added argument checks (DG); * 15-Jan-2007 : Fixed bug in drawRangeMarkers() (DG); * 07-Feb-2007 : Fixed bug 1654215, renderer with no dataset (DG); * 26-Feb-2007 : Added missing setDomainAxisLocation() and * setRangeAxisLocation() methods (DG); * 02-Mar-2007 : Fix for crosshair positioning with horizontal orientation * (see patch 1671648 by Sergei Ivanov) (DG); * 13-Mar-2007 : Added null argument checks for crosshair attributes (DG); * 23-Mar-2007 : Added domain zero base line facility (DG); * 04-May-2007 : Render only visible data items if possible (DG); * 24-May-2007 : Fixed bug in render method for an empty series (DG); * 07-Jun-2007 : Modified drawBackground() to pass orientation to * fillBackground() for handling GradientPaint (DG); * 24-Sep-2007 : Added new zoom methods (DG); * 26-Sep-2007 : Include index value in IllegalArgumentExceptions (DG); * 05-Nov-2007 : Applied patch 1823697, by Richard West, for removal of domain * and range markers (DG); * 12-Nov-2007 : Fixed bug in equals() method for domain and range tick * band paint attributes (DG); * 27-Nov-2007 : Added new setFixedDomain/RangeAxisSpace() methods (DG); * 04-Jan-2008 : Fix for quadrant painting error - see patch 1849564 (DG); * 25-Mar-2008 : Added new methods with optional notification - see patch * 1913751 (DG); * 07-Apr-2008 : Fixed NPE in removeDomainMarker() and * removeRangeMarker() (DG); * 22-May-2008 : Modified calculateAxisSpace() to process range axes first, * then adjust the plot area before calculating the space * for the domain axes (DG); * 09-Jul-2008 : Added renderer state notification when series pass begins * and ends - see patch 1997549 by Ulrich Voigt (DG); * 25-Jul-2008 : Fixed NullPointerException for plots with no axes (DG); * 15-Aug-2008 : Added getRendererCount() method (DG); * 25-Sep-2008 : Added minor tick support, see patch 1934255 by Peter Kolb (DG); * 25-Nov-2008 : Allow datasets to be mapped to multiple axes - based on patch * 1868749 by Andrew Mickish (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see patch 1607918 by * Jess Thrysoee (DG); * 10-Mar-2009 : Allow some annotations to contribute to axis autoRange (DG); * 18-Mar-2009 : Modified anchored zoom behaviour and fixed bug in * "process visible range" rendering (DG); * 19-Mar-2009 : Added panning support based on patch 2686040 by Ulrich * Voigt (DG); * 19-Mar-2009 : Added entity support - see patch 2603321 by Peter Kolb (DG); * 30-Mar-2009 : Delegate panning to axes (DG); * 10-May-2009 : Added check for fixedLegendItems in equals(), and code to * handle cloning (DG); * 24-Jun-2009 : Added support for annotation events - see patch 2809117 * by PK (DG); * 06-Jul-2009 : Fix for cloning of renderers - see bug 2817504 (DG) * 10-Jul-2009 : Added optional drop shadow generator (DG); * 18-Oct-2011 : Fix tooltip offset with shadow renderer (DG); * 12-Sep-2013 : Check for KEY_SUPPRESS_SHADOW_GENERATION rendering hint (DG); * 10-Mar-2014 : Updated Javadocs for issue #1123 (DG); * 29-Jul-2014 : Add hints to normalise stroke for crosshairs (DG); * */ package org.jfree.chart.plot; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.ResourceBundle; import java.util.Set; import java.util.TreeMap; import org.jfree.chart.JFreeChart; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.annotations.Annotation; import org.jfree.chart.annotations.XYAnnotation; import org.jfree.chart.annotations.XYAnnotationBoundsInfo; import org.jfree.chart.axis.Axis; import org.jfree.chart.axis.AxisCollection; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.AxisSpace; import org.jfree.chart.axis.AxisState; import org.jfree.chart.axis.TickType; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.axis.ValueTick; import org.jfree.chart.event.AnnotationChangeEvent; import org.jfree.chart.event.ChartChangeEventType; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.event.RendererChangeListener; import org.jfree.chart.renderer.RendererUtilities; import org.jfree.chart.renderer.xy.AbstractXYItemRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYItemRendererState; import org.jfree.chart.util.CloneUtils; import org.jfree.chart.util.ParamChecks; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.chart.util.ShadowGenerator; import org.jfree.data.Range; import org.jfree.data.general.DatasetChangeEvent; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.xy.XYDataset; import org.jfree.io.SerialUtilities; import org.jfree.ui.Layer; import org.jfree.ui.RectangleEdge; import org.jfree.ui.RectangleInsets; import org.jfree.util.ObjectUtilities; import org.jfree.util.PaintUtilities; import org.jfree.util.PublicCloneable; /** * A general class for plotting data in the form of (x, y) pairs. This plot can * use data from any class that implements the {@link XYDataset} interface. * <P> * {@code XYPlot} makes use of an {@link XYItemRenderer} to draw each point * on the plot. By using different renderers, various chart types can be * produced. * <p> * The {@link org.jfree.chart.ChartFactory} class contains static methods for * creating pre-configured charts. */ public class XYPlot extends Plot implements ValueAxisPlot, Pannable, Zoomable, RendererChangeListener, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 7044148245716569264L; /** The default grid line stroke. */ public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f, new float[] {2.0f, 2.0f}, 0.0f); /** The default grid line paint. */ public static final Paint DEFAULT_GRIDLINE_PAINT = Color.lightGray; /** The default crosshair visibility. */ public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false; /** The default crosshair stroke. */ public static final Stroke DEFAULT_CROSSHAIR_STROKE = DEFAULT_GRIDLINE_STROKE; /** The default crosshair paint. */ public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.blue; /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.plot.LocalizationBundle"); /** The plot orientation. */ private PlotOrientation orientation; /** The offset between the data area and the axes. */ private RectangleInsets axisOffset; /** The domain axis / axes (used for the x-values). */ private Map<Integer, ValueAxis> domainAxes; /** The domain axis locations. */ private Map<Integer, AxisLocation> domainAxisLocations; /** The range axis (used for the y-values). */ private Map<Integer, ValueAxis> rangeAxes; /** The range axis location. */ private Map<Integer, AxisLocation> rangeAxisLocations; /** Storage for the datasets. */ private Map<Integer, XYDataset> datasets; /** Storage for the renderers. */ private Map<Integer, XYItemRenderer> renderers; /** * Storage for the mapping between datasets/renderers and domain axes. The * keys in the map are Integer objects, corresponding to the dataset * index. The values in the map are List objects containing Integer * objects (corresponding to the axis indices). If the map contains no * entry for a dataset, it is assumed to map to the primary domain axis * (index = 0). */ private Map<Integer, List<Integer>> datasetToDomainAxesMap; /** * Storage for the mapping between datasets/renderers and range axes. The * keys in the map are Integer objects, corresponding to the dataset * index. The values in the map are List objects containing Integer * objects (corresponding to the axis indices). If the map contains no * entry for a dataset, it is assumed to map to the primary domain axis * (index = 0). */ private Map<Integer, List<Integer>> datasetToRangeAxesMap; /** The origin point for the quadrants (if drawn). */ private transient Point2D quadrantOrigin = new Point2D.Double(0.0, 0.0); /** The paint used for each quadrant. */ private transient Paint[] quadrantPaint = new Paint[] {null, null, null, null}; /** A flag that controls whether the domain grid-lines are visible. */ private boolean domainGridlinesVisible; /** The stroke used to draw the domain grid-lines. */ private transient Stroke domainGridlineStroke; /** The paint used to draw the domain grid-lines. */ private transient Paint domainGridlinePaint; /** A flag that controls whether the range grid-lines are visible. */ private boolean rangeGridlinesVisible; /** The stroke used to draw the range grid-lines. */ private transient Stroke rangeGridlineStroke; /** The paint used to draw the range grid-lines. */ private transient Paint rangeGridlinePaint; /** * A flag that controls whether the domain minor grid-lines are visible. * * @since 1.0.12 */ private boolean domainMinorGridlinesVisible; /** * The stroke used to draw the domain minor grid-lines. * * @since 1.0.12 */ private transient Stroke domainMinorGridlineStroke; /** * The paint used to draw the domain minor grid-lines. * * @since 1.0.12 */ private transient Paint domainMinorGridlinePaint; /** * A flag that controls whether the range minor grid-lines are visible. * * @since 1.0.12 */ private boolean rangeMinorGridlinesVisible; /** * The stroke used to draw the range minor grid-lines. * * @since 1.0.12 */ private transient Stroke rangeMinorGridlineStroke; /** * The paint used to draw the range minor grid-lines. * * @since 1.0.12 */ private transient Paint rangeMinorGridlinePaint; /** * A flag that controls whether or not the zero baseline against the domain * axis is visible. * * @since 1.0.5 */ private boolean domainZeroBaselineVisible; /** * The stroke used for the zero baseline against the domain axis. * * @since 1.0.5 */ private transient Stroke domainZeroBaselineStroke; /** * The paint used for the zero baseline against the domain axis. * * @since 1.0.5 */ private transient Paint domainZeroBaselinePaint; /** * A flag that controls whether or not the zero baseline against the range * axis is visible. */ private boolean rangeZeroBaselineVisible; /** The stroke used for the zero baseline against the range axis. */ private transient Stroke rangeZeroBaselineStroke; /** The paint used for the zero baseline against the range axis. */ private transient Paint rangeZeroBaselinePaint; /** A flag that controls whether or not a domain crosshair is drawn..*/ private boolean domainCrosshairVisible; /** The domain crosshair value. */ private double domainCrosshairValue; /** The pen/brush used to draw the crosshair (if any). */ private transient Stroke domainCrosshairStroke; /** The color used to draw the crosshair (if any). */ private transient Paint domainCrosshairPaint; /** * A flag that controls whether or not the crosshair locks onto actual * data points. */ private boolean domainCrosshairLockedOnData = true; /** A flag that controls whether or not a range crosshair is drawn..*/ private boolean rangeCrosshairVisible; /** The range crosshair value. */ private double rangeCrosshairValue; /** The pen/brush used to draw the crosshair (if any). */ private transient Stroke rangeCrosshairStroke; /** The color used to draw the crosshair (if any). */ private transient Paint rangeCrosshairPaint; /** * A flag that controls whether or not the crosshair locks onto actual * data points. */ private boolean rangeCrosshairLockedOnData = true; /** A map of lists of foreground markers (optional) for the domain axes. */ private Map foregroundDomainMarkers; /** A map of lists of background markers (optional) for the domain axes. */ private Map backgroundDomainMarkers; /** A map of lists of foreground markers (optional) for the range axes. */ private Map foregroundRangeMarkers; /** A map of lists of background markers (optional) for the range axes. */ private Map backgroundRangeMarkers; /** * A (possibly empty) list of annotations for the plot. The list should * be initialised in the constructor and never allowed to be * {@code null}. */ private List<XYAnnotation> annotations; /** The paint used for the domain tick bands (if any). */ private transient Paint domainTickBandPaint; /** The paint used for the range tick bands (if any). */ private transient Paint rangeTickBandPaint; /** The fixed domain axis space. */ private AxisSpace fixedDomainAxisSpace; /** The fixed range axis space. */ private AxisSpace fixedRangeAxisSpace; /** * The order of the dataset rendering (REVERSE draws the primary dataset * last so that it appears to be on top). */ private DatasetRenderingOrder datasetRenderingOrder = DatasetRenderingOrder.REVERSE; /** * The order of the series rendering (REVERSE draws the primary series * last so that it appears to be on top). */ private SeriesRenderingOrder seriesRenderingOrder = SeriesRenderingOrder.REVERSE; /** * The weight for this plot (only relevant if this is a subplot in a * combined plot). */ private int weight; /** * An optional collection of legend items that can be returned by the * getLegendItems() method. */ private LegendItemCollection fixedLegendItems; /** * A flag that controls whether or not panning is enabled for the domain * axis/axes. * * @since 1.0.13 */ private boolean domainPannable; /** * A flag that controls whether or not panning is enabled for the range * axis/axes. * * @since 1.0.13 */ private boolean rangePannable; /** * The shadow generator ({@code null} permitted). * * @since 1.0.14 */ private ShadowGenerator shadowGenerator; /** * Creates a new {@code XYPlot} instance with no dataset, no axes and * no renderer. You should specify these items before using the plot. */ public XYPlot() { this(null, null, null, null); } /** * Creates a new plot with the specified dataset, axes and renderer. Any * of the arguments can be {@code null}, but in that case you should * take care to specify the value before using the plot (otherwise a * {@code NullPointerException} may be thrown). * * @param dataset the dataset ({@code null} permitted). * @param domainAxis the domain axis ({@code null} permitted). * @param rangeAxis the range axis ({@code null} permitted). * @param renderer the renderer ({@code null} permitted). */ public XYPlot(XYDataset dataset, ValueAxis domainAxis, ValueAxis rangeAxis, XYItemRenderer renderer) { super(); this.orientation = PlotOrientation.VERTICAL; this.weight = 1; // only relevant when this is a subplot this.axisOffset = RectangleInsets.ZERO_INSETS; // allocate storage for datasets, axes and renderers (all optional) this.domainAxes = new HashMap<Integer, ValueAxis>(); this.domainAxisLocations = new HashMap<Integer, AxisLocation>(); this.foregroundDomainMarkers = new HashMap(); this.backgroundDomainMarkers = new HashMap(); this.rangeAxes = new HashMap<Integer, ValueAxis>(); this.rangeAxisLocations = new HashMap<Integer, AxisLocation>(); this.foregroundRangeMarkers = new HashMap(); this.backgroundRangeMarkers = new HashMap(); this.datasets = new HashMap<Integer, XYDataset>(); this.renderers = new HashMap<Integer, XYItemRenderer>(); this.datasetToDomainAxesMap = new TreeMap(); this.datasetToRangeAxesMap = new TreeMap(); this.annotations = new java.util.ArrayList(); this.datasets.put(0, dataset); if (dataset != null) { dataset.addChangeListener(this); } this.renderers.put(0, renderer); if (renderer != null) { renderer.setPlot(this); renderer.addChangeListener(this); } this.domainAxes.put(0, domainAxis); mapDatasetToDomainAxis(0, 0); if (domainAxis != null) { domainAxis.setPlot(this); domainAxis.addChangeListener(this); } this.domainAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT); this.rangeAxes.put(0, rangeAxis); mapDatasetToRangeAxis(0, 0); if (rangeAxis != null) { rangeAxis.setPlot(this); rangeAxis.addChangeListener(this); } this.rangeAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT); configureDomainAxes(); configureRangeAxes(); this.domainGridlinesVisible = true; this.domainGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.domainGridlinePaint = DEFAULT_GRIDLINE_PAINT; this.domainMinorGridlinesVisible = false; this.domainMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.domainMinorGridlinePaint = Color.white; this.domainZeroBaselineVisible = false; this.domainZeroBaselinePaint = Color.black; this.domainZeroBaselineStroke = new BasicStroke(0.5f); this.rangeGridlinesVisible = true; this.rangeGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.rangeGridlinePaint = DEFAULT_GRIDLINE_PAINT; this.rangeMinorGridlinesVisible = false; this.rangeMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.rangeMinorGridlinePaint = Color.white; this.rangeZeroBaselineVisible = false; this.rangeZeroBaselinePaint = Color.black; this.rangeZeroBaselineStroke = new BasicStroke(0.5f); this.domainCrosshairVisible = false; this.domainCrosshairValue = 0.0; this.domainCrosshairStroke = DEFAULT_CROSSHAIR_STROKE; this.domainCrosshairPaint = DEFAULT_CROSSHAIR_PAINT; this.rangeCrosshairVisible = false; this.rangeCrosshairValue = 0.0; this.rangeCrosshairStroke = DEFAULT_CROSSHAIR_STROKE; this.rangeCrosshairPaint = DEFAULT_CROSSHAIR_PAINT; this.shadowGenerator = null; } /** * Returns the plot type as a string. * * @return A short string describing the type of plot. */ @Override public String getPlotType() { return localizationResources.getString("XY_Plot"); } /** * Returns the orientation of the plot. * * @return The orientation (never {@code null}). * * @see #setOrientation(PlotOrientation) */ @Override public PlotOrientation getOrientation() { return this.orientation; } /** * Sets the orientation for the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param orientation the orientation ({@code null} not allowed). * * @see #getOrientation() */ public void setOrientation(PlotOrientation orientation) { ParamChecks.nullNotPermitted(orientation, "orientation"); if (orientation != this.orientation) { this.orientation = orientation; fireChangeEvent(); } } /** * Returns the axis offset. * * @return The axis offset (never {@code null}). * * @see #setAxisOffset(RectangleInsets) */ public RectangleInsets getAxisOffset() { return this.axisOffset; } /** * Sets the axis offsets (gap between the data area and the axes) and sends * a {@link PlotChangeEvent} to all registered listeners. * * @param offset the offset ({@code null} not permitted). * * @see #getAxisOffset() */ public void setAxisOffset(RectangleInsets offset) { ParamChecks.nullNotPermitted(offset, "offset"); this.axisOffset = offset; fireChangeEvent(); } /** * Returns the domain axis with index 0. If the domain axis for this plot * is {@code null}, then the method will return the parent plot's * domain axis (if there is a parent plot). * * @return The domain axis (possibly {@code null}). * * @see #getDomainAxis(int) * @see #setDomainAxis(ValueAxis) */ public ValueAxis getDomainAxis() { return getDomainAxis(0); } /** * Returns the domain axis with the specified index, or {@code null} if * there is no axis with that index. * * @param index the axis index. * * @return The axis ({@code null} possible). * * @see #setDomainAxis(int, ValueAxis) */ public ValueAxis getDomainAxis(int index) { ValueAxis result = this.domainAxes.get(index); if (result == null) { Plot parent = getParent(); if (parent instanceof XYPlot) { XYPlot xy = (XYPlot) parent; result = xy.getDomainAxis(index); } } return result; } /** * Sets the domain axis for the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param axis the new axis ({@code null} permitted). * * @see #getDomainAxis() * @see #setDomainAxis(int, ValueAxis) */ public void setDomainAxis(ValueAxis axis) { setDomainAxis(0, axis); } /** * Sets a domain axis and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param index the axis index. * @param axis the axis ({@code null} permitted). * * @see #getDomainAxis(int) * @see #setRangeAxis(int, ValueAxis) */ public void setDomainAxis(int index, ValueAxis axis) { setDomainAxis(index, axis, true); } /** * Sets a domain axis and, if requested, sends a {@link PlotChangeEvent} to * all registered listeners. * * @param index the axis index. * @param axis the axis. * @param notify notify listeners? * * @see #getDomainAxis(int) */ public void setDomainAxis(int index, ValueAxis axis, boolean notify) { ValueAxis existing = getDomainAxis(index); if (existing != null) { existing.removeChangeListener(this); } if (axis != null) { axis.setPlot(this); } this.domainAxes.put(index, axis); if (axis != null) { axis.configure(); axis.addChangeListener(this); } if (notify) { fireChangeEvent(); } } /** * Sets the domain axes for this plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param axes the axes ({@code null} not permitted). * * @see #setRangeAxes(ValueAxis[]) */ public void setDomainAxes(ValueAxis[] axes) { for (int i = 0; i < axes.length; i++) { setDomainAxis(i, axes[i], false); } fireChangeEvent(); } /** * Returns the location of the primary domain axis. * * @return The location (never {@code null}). * * @see #setDomainAxisLocation(AxisLocation) */ public AxisLocation getDomainAxisLocation() { return (AxisLocation) this.domainAxisLocations.get(0); } /** * Sets the location of the primary domain axis and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location ({@code null} not permitted). * * @see #getDomainAxisLocation() */ public void setDomainAxisLocation(AxisLocation location) { // delegate... setDomainAxisLocation(0, location, true); } /** * Sets the location of the domain axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location ({@code null} not permitted). * @param notify notify listeners? * * @see #getDomainAxisLocation() */ public void setDomainAxisLocation(AxisLocation location, boolean notify) { // delegate... setDomainAxisLocation(0, location, notify); } /** * Returns the edge for the primary domain axis (taking into account the * plot's orientation). * * @return The edge. * * @see #getDomainAxisLocation() * @see #getOrientation() */ public RectangleEdge getDomainAxisEdge() { return Plot.resolveDomainAxisLocation(getDomainAxisLocation(), this.orientation); } /** * Returns the number of domain axes. * * @return The axis count. * * @see #getRangeAxisCount() */ public int getDomainAxisCount() { return this.domainAxes.size(); } /** * Clears the domain axes from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @see #clearRangeAxes() */ public void clearDomainAxes() { for (ValueAxis axis: this.domainAxes.values()) { if (axis != null) { axis.removeChangeListener(this); } } this.domainAxes.clear(); fireChangeEvent(); } /** * Configures the domain axes. */ public void configureDomainAxes() { for (ValueAxis axis: this.domainAxes.values()) { if (axis != null) { axis.configure(); } } } /** * Returns the location for a domain axis. If this hasn't been set * explicitly, the method returns the location that is opposite to the * primary domain axis location. * * @param index the axis index (must be &gt;= 0). * * @return The location (never {@code null}). * * @see #setDomainAxisLocation(int, AxisLocation) */ public AxisLocation getDomainAxisLocation(int index) { AxisLocation result = this.domainAxisLocations.get(index); if (result == null) { result = AxisLocation.getOpposite(getDomainAxisLocation()); } return result; } /** * Sets the location for a domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param index the axis index. * @param location the location ({@code null} not permitted for index * 0). * * @see #getDomainAxisLocation(int) */ public void setDomainAxisLocation(int index, AxisLocation location) { // delegate... setDomainAxisLocation(index, location, true); } /** * Sets the axis location for a domain axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the axis index (must be &gt;= 0). * @param location the location ({@code null} not permitted for * index 0). * @param notify notify listeners? * * @since 1.0.5 * * @see #getDomainAxisLocation(int) * @see #setRangeAxisLocation(int, AxisLocation, boolean) */ public void setDomainAxisLocation(int index, AxisLocation location, boolean notify) { if (index == 0 && location == null) { throw new IllegalArgumentException( "Null 'location' for index 0 not permitted."); } this.domainAxisLocations.put(index, location); if (notify) { fireChangeEvent(); } } /** * Returns the edge for a domain axis. * * @param index the axis index. * * @return The edge. * * @see #getRangeAxisEdge(int) */ public RectangleEdge getDomainAxisEdge(int index) { AxisLocation location = getDomainAxisLocation(index); return Plot.resolveDomainAxisLocation(location, this.orientation); } /** * Returns the range axis for the plot. If the range axis for this plot is * {@code null}, then the method will return the parent plot's range * axis (if there is a parent plot). * * @return The range axis. * * @see #getRangeAxis(int) * @see #setRangeAxis(ValueAxis) */ public ValueAxis getRangeAxis() { return getRangeAxis(0); } /** * Sets the range axis for the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param axis the axis ({@code null} permitted). * * @see #getRangeAxis() * @see #setRangeAxis(int, ValueAxis) */ public void setRangeAxis(ValueAxis axis) { if (axis != null) { axis.setPlot(this); } // plot is likely registered as a listener with the existing axis... ValueAxis existing = getRangeAxis(); if (existing != null) { existing.removeChangeListener(this); } this.rangeAxes.put(0, axis); if (axis != null) { axis.configure(); axis.addChangeListener(this); } fireChangeEvent(); } /** * Returns the location of the primary range axis. * * @return The location (never {@code null}). * * @see #setRangeAxisLocation(AxisLocation) */ public AxisLocation getRangeAxisLocation() { return (AxisLocation) this.rangeAxisLocations.get(0); } /** * Sets the location of the primary range axis and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location ({@code null} not permitted). * * @see #getRangeAxisLocation() */ public void setRangeAxisLocation(AxisLocation location) { // delegate... setRangeAxisLocation(0, location, true); } /** * Sets the location of the primary range axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location ({@code null} not permitted). * @param notify notify listeners? * * @see #getRangeAxisLocation() */ public void setRangeAxisLocation(AxisLocation location, boolean notify) { // delegate... setRangeAxisLocation(0, location, notify); } /** * Returns the edge for the primary range axis. * * @return The range axis edge. * * @see #getRangeAxisLocation() * @see #getOrientation() */ public RectangleEdge getRangeAxisEdge() { return Plot.resolveRangeAxisLocation(getRangeAxisLocation(), this.orientation); } /** * Returns the range axis with the specified index, or {@code null} if * there is no axis with that index. * * @param index the axis index (must be &gt;= 0). * * @return The axis ({@code null} possible). * * @see #setRangeAxis(int, ValueAxis) */ public ValueAxis getRangeAxis(int index) { ValueAxis result = this.rangeAxes.get(index); if (result == null) { Plot parent = getParent(); if (parent instanceof XYPlot) { XYPlot xy = (XYPlot) parent; result = xy.getRangeAxis(index); } } return result; } /** * Sets a range axis and sends a {@link PlotChangeEvent} to all registered * listeners. * * @param index the axis index. * @param axis the axis ({@code null} permitted). * * @see #getRangeAxis(int) */ public void setRangeAxis(int index, ValueAxis axis) { setRangeAxis(index, axis, true); } /** * Sets a range axis and, if requested, sends a {@link PlotChangeEvent} to * all registered listeners. * * @param index the axis index. * @param axis the axis ({@code null} permitted). * @param notify notify listeners? * * @see #getRangeAxis(int) */ public void setRangeAxis(int index, ValueAxis axis, boolean notify) { ValueAxis existing = getRangeAxis(index); if (existing != null) { existing.removeChangeListener(this); } if (axis != null) { axis.setPlot(this); } this.rangeAxes.put(index, axis); if (axis != null) { axis.configure(); axis.addChangeListener(this); } if (notify) { fireChangeEvent(); } } /** * Sets the range axes for this plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param axes the axes ({@code null} not permitted). * * @see #setDomainAxes(ValueAxis[]) */ public void setRangeAxes(ValueAxis[] axes) { for (int i = 0; i < axes.length; i++) { setRangeAxis(i, axes[i], false); } fireChangeEvent(); } /** * Returns the number of range axes. * * @return The axis count. * * @see #getDomainAxisCount() */ public int getRangeAxisCount() { return this.rangeAxes.size(); } /** * Clears the range axes from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @see #clearDomainAxes() */ public void clearRangeAxes() { for (ValueAxis axis: this.rangeAxes.values()) { if (axis != null) { axis.removeChangeListener(this); } } this.rangeAxes.clear(); fireChangeEvent(); } /** * Configures the range axes. * * @see #configureDomainAxes() */ public void configureRangeAxes() { for (ValueAxis axis: this.rangeAxes.values()) { if (axis != null) { axis.configure(); } } } /** * Returns the location for a range axis. If this hasn't been set * explicitly, the method returns the location that is opposite to the * primary range axis location. * * @param index the axis index (must be &gt;= 0). * * @return The location (never {@code null}). * * @see #setRangeAxisLocation(int, AxisLocation) */ public AxisLocation getRangeAxisLocation(int index) { AxisLocation result = this.rangeAxisLocations.get(index); if (result == null) { result = AxisLocation.getOpposite(getRangeAxisLocation()); } return result; } /** * Sets the location for a range axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param index the axis index. * @param location the location ({@code null} permitted). * * @see #getRangeAxisLocation(int) */ public void setRangeAxisLocation(int index, AxisLocation location) { // delegate... setRangeAxisLocation(index, location, true); } /** * Sets the axis location for a domain axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the axis index. * @param location the location ({@code null} not permitted for * index 0). * @param notify notify listeners? * * @since 1.0.5 * * @see #getRangeAxisLocation(int) * @see #setDomainAxisLocation(int, AxisLocation, boolean) */ public void setRangeAxisLocation(int index, AxisLocation location, boolean notify) { if (index == 0 && location == null) { throw new IllegalArgumentException( "Null 'location' for index 0 not permitted."); } this.rangeAxisLocations.put(index, location); if (notify) { fireChangeEvent(); } } /** * Returns the edge for a range axis. * * @param index the axis index. * * @return The edge. * * @see #getRangeAxisLocation(int) * @see #getOrientation() */ public RectangleEdge getRangeAxisEdge(int index) { AxisLocation location = getRangeAxisLocation(index); return Plot.resolveRangeAxisLocation(location, this.orientation); } /** * Returns the primary dataset for the plot. * * @return The primary dataset (possibly {@code null}). * * @see #getDataset(int) * @see #setDataset(XYDataset) */ public XYDataset getDataset() { return getDataset(0); } /** * Returns the dataset with the specified index, or {@code null} if there * is no dataset with that index. * * @param index the dataset index (must be &gt;= 0). * * @return The dataset (possibly {@code null}). * * @see #setDataset(int, XYDataset) */ public XYDataset getDataset(int index) { return (XYDataset) this.datasets.get(index); } /** * Sets the primary dataset for the plot, replacing the existing dataset if * there is one. * * @param dataset the dataset ({@code null} permitted). * * @see #getDataset() * @see #setDataset(int, XYDataset) */ public void setDataset(XYDataset dataset) { setDataset(0, dataset); } /** * Sets a dataset for the plot and sends a change event to all registered * listeners. * * @param index the dataset index (must be &gt;= 0). * @param dataset the dataset ({@code null} permitted). * * @see #getDataset(int) */ public void setDataset(int index, XYDataset dataset) { XYDataset existing = getDataset(index); if (existing != null) { existing.removeChangeListener(this); } this.datasets.put(index, dataset); if (dataset != null) { dataset.addChangeListener(this); } // send a dataset change event to self... DatasetChangeEvent event = new DatasetChangeEvent(this, dataset); datasetChanged(event); } /** * Returns the number of datasets. * * @return The number of datasets. */ public int getDatasetCount() { return this.datasets.size(); } /** * Returns the index of the specified dataset, or {@code -1} if the * dataset does not belong to the plot. * * @param dataset the dataset ({@code null} not permitted). * * @return The index or -1. */ public int indexOf(XYDataset dataset) { for (Map.Entry<Integer, XYDataset> entry: this.datasets.entrySet()) { if (dataset == entry.getValue()) { return entry.getKey(); } } return -1; } /** * Maps a dataset to a particular domain axis. All data will be plotted * against axis zero by default, no mapping is required for this case. * * @param index the dataset index (zero-based). * @param axisIndex the axis index. * * @see #mapDatasetToRangeAxis(int, int) */ public void mapDatasetToDomainAxis(int index, int axisIndex) { List axisIndices = new java.util.ArrayList(1); axisIndices.add(new Integer(axisIndex)); mapDatasetToDomainAxes(index, axisIndices); } /** * Maps the specified dataset to the axes in the list. Note that the * conversion of data values into Java2D space is always performed using * the first axis in the list. * * @param index the dataset index (zero-based). * @param axisIndices the axis indices ({@code null} permitted). * * @since 1.0.12 */ public void mapDatasetToDomainAxes(int index, List axisIndices) { ParamChecks.requireNonNegative(index, "index"); checkAxisIndices(axisIndices); Integer key = new Integer(index); this.datasetToDomainAxesMap.put(key, new ArrayList(axisIndices)); // fake a dataset change event to update axes... datasetChanged(new DatasetChangeEvent(this, getDataset(index))); } /** * Maps a dataset to a particular range axis. All data will be plotted * against axis zero by default, no mapping is required for this case. * * @param index the dataset index (zero-based). * @param axisIndex the axis index. * * @see #mapDatasetToDomainAxis(int, int) */ public void mapDatasetToRangeAxis(int index, int axisIndex) { List axisIndices = new java.util.ArrayList(1); axisIndices.add(new Integer(axisIndex)); mapDatasetToRangeAxes(index, axisIndices); } /** * Maps the specified dataset to the axes in the list. Note that the * conversion of data values into Java2D space is always performed using * the first axis in the list. * * @param index the dataset index (zero-based). * @param axisIndices the axis indices ({@code null} permitted). * * @since 1.0.12 */ public void mapDatasetToRangeAxes(int index, List axisIndices) { ParamChecks.requireNonNegative(index, "index"); checkAxisIndices(axisIndices); Integer key = new Integer(index); this.datasetToRangeAxesMap.put(key, new ArrayList(axisIndices)); // fake a dataset change event to update axes... datasetChanged(new DatasetChangeEvent(this, getDataset(index))); } /** * This method is used to perform argument checking on the list of * axis indices passed to mapDatasetToDomainAxes() and * mapDatasetToRangeAxes(). * * @param indices the list of indices ({@code null} permitted). */ private void checkAxisIndices(List<Integer> indices) { // axisIndices can be: // 1. null; // 2. non-empty, containing only Integer objects that are unique. if (indices == null) { return; // OK } int count = indices.size(); if (count == 0) { throw new IllegalArgumentException("Empty list not permitted."); } Set<Integer> set = new HashSet<Integer>(); for (Integer item : indices) { if (set.contains(item)) { throw new IllegalArgumentException("Indices must be unique."); } set.add(item); } } /** * Returns the number of renderer slots for this plot. * * @return The number of renderer slots. * * @since 1.0.11 */ public int getRendererCount() { return this.renderers.size(); } /** * Returns the renderer for the primary dataset. * * @return The item renderer (possibly {@code null}). * * @see #setRenderer(XYItemRenderer) */ public XYItemRenderer getRenderer() { return getRenderer(0); } /** * Returns the renderer with the specified index, or {@code null}. * * @param index the renderer index (must be &gt;= 0). * * @return The renderer (possibly {@code null}). * * @see #setRenderer(int, XYItemRenderer) */ public XYItemRenderer getRenderer(int index) { return (XYItemRenderer) this.renderers.get(index); } /** * Sets the renderer for the primary dataset and sends a change event to * all registered listeners. If the renderer is set to {@code null}, * no data will be displayed. * * @param renderer the renderer ({@code null} permitted). * * @see #getRenderer() */ public void setRenderer(XYItemRenderer renderer) { setRenderer(0, renderer); } /** * Sets the renderer for the dataset with the specified index and sends a * change event to all registered listeners. Note that each dataset should * have its own renderer, you should not use one renderer for multiple * datasets. * * @param index the index (must be &gt;= 0). * @param renderer the renderer. * * @see #getRenderer(int) */ public void setRenderer(int index, XYItemRenderer renderer) { setRenderer(index, renderer, true); } /** * Sets the renderer for the dataset with the specified index and, if * requested, sends a change event to all registered listeners. Note that * each dataset should have its own renderer, you should not use one * renderer for multiple datasets. * * @param index the index (must be &gt;= 0). * @param renderer the renderer. * @param notify notify listeners? * * @see #getRenderer(int) */ public void setRenderer(int index, XYItemRenderer renderer, boolean notify) { XYItemRenderer existing = getRenderer(index); if (existing != null) { existing.removeChangeListener(this); } this.renderers.put(index, renderer); if (renderer != null) { renderer.setPlot(this); renderer.addChangeListener(this); } configureDomainAxes(); configureRangeAxes(); if (notify) { fireChangeEvent(); } } /** * Sets the renderers for this plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param renderers the renderers ({@code null} not permitted). */ public void setRenderers(XYItemRenderer[] renderers) { for (int i = 0; i < renderers.length; i++) { setRenderer(i, renderers[i], false); } fireChangeEvent(); } /** * Returns the dataset rendering order. * * @return The order (never {@code null}). * * @see #setDatasetRenderingOrder(DatasetRenderingOrder) */ public DatasetRenderingOrder getDatasetRenderingOrder() { return this.datasetRenderingOrder; } /** * Sets the rendering order and sends a {@link PlotChangeEvent} to all * registered listeners. By default, the plot renders the primary dataset * last (so that the primary dataset overlays the secondary datasets). * You can reverse this if you want to. * * @param order the rendering order ({@code null} not permitted). * * @see #getDatasetRenderingOrder() */ public void setDatasetRenderingOrder(DatasetRenderingOrder order) { ParamChecks.nullNotPermitted(order, "order"); this.datasetRenderingOrder = order; fireChangeEvent(); } /** * Returns the series rendering order. * * @return the order (never {@code null}). * * @see #setSeriesRenderingOrder(SeriesRenderingOrder) */ public SeriesRenderingOrder getSeriesRenderingOrder() { return this.seriesRenderingOrder; } /** * Sets the series order and sends a {@link PlotChangeEvent} to all * registered listeners. By default, the plot renders the primary series * last (so that the primary series appears to be on top). * You can reverse this if you want to. * * @param order the rendering order ({@code null} not permitted). * * @see #getSeriesRenderingOrder() */ public void setSeriesRenderingOrder(SeriesRenderingOrder order) { ParamChecks.nullNotPermitted(order, "order"); this.seriesRenderingOrder = order; fireChangeEvent(); } /** * Returns the index of the specified renderer, or {@code -1} if the * renderer is not assigned to this plot. * * @param renderer the renderer ({@code null} permitted). * * @return The renderer index. */ public int getIndexOf(XYItemRenderer renderer) { for (Map.Entry<Integer, XYItemRenderer> entry : this.renderers.entrySet()) { if (entry.getValue() == renderer) { return entry.getKey(); } } return -1; } /** * Returns the renderer for the specified dataset (this is either the * renderer with the same index as the dataset or, if there isn't a * renderer with the same index, the default renderer). If the dataset * does not belong to the plot, this method will return {@code null}. * * @param dataset the dataset ({@code null} permitted). * * @return The renderer (possibly {@code null}). */ public XYItemRenderer getRendererForDataset(XYDataset dataset) { int datasetIndex = indexOf(dataset); if (datasetIndex < 0) { return null; } XYItemRenderer result = this.renderers.get(datasetIndex); if (result == null) { result = getRenderer(); } return result; } /** * Returns the weight for this plot when it is used as a subplot within a * combined plot. * * @return The weight. * * @see #setWeight(int) */ public int getWeight() { return this.weight; } /** * Sets the weight for the plot and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param weight the weight. * * @see #getWeight() */ public void setWeight(int weight) { this.weight = weight; fireChangeEvent(); } /** * Returns {@code true} if the domain gridlines are visible, and * {@code false} otherwise. * * @return {@code true} or {@code false}. * * @see #setDomainGridlinesVisible(boolean) */ public boolean isDomainGridlinesVisible() { return this.domainGridlinesVisible; } /** * Sets the flag that controls whether or not the domain grid-lines are * visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isDomainGridlinesVisible() */ public void setDomainGridlinesVisible(boolean visible) { if (this.domainGridlinesVisible != visible) { this.domainGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns {@code true} if the domain minor gridlines are visible, and * {@code false} otherwise. * * @return {@code true} or {@code false}. * * @see #setDomainMinorGridlinesVisible(boolean) * * @since 1.0.12 */ public boolean isDomainMinorGridlinesVisible() { return this.domainMinorGridlinesVisible; } /** * Sets the flag that controls whether or not the domain minor grid-lines * are visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isDomainMinorGridlinesVisible() * * @since 1.0.12 */ public void setDomainMinorGridlinesVisible(boolean visible) { if (this.domainMinorGridlinesVisible != visible) { this.domainMinorGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the stroke for the grid-lines (if any) plotted against the * domain axis. * * @return The stroke (never {@code null}). * * @see #setDomainGridlineStroke(Stroke) */ public Stroke getDomainGridlineStroke() { return this.domainGridlineStroke; } /** * Sets the stroke for the grid lines plotted against the domain axis, and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @throws IllegalArgumentException if {@code stroke} is * {@code null}. * * @see #getDomainGridlineStroke() */ public void setDomainGridlineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.domainGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the stroke for the minor grid-lines (if any) plotted against the * domain axis. * * @return The stroke (never {@code null}). * * @see #setDomainMinorGridlineStroke(Stroke) * * @since 1.0.12 */ public Stroke getDomainMinorGridlineStroke() { return this.domainMinorGridlineStroke; } /** * Sets the stroke for the minor grid lines plotted against the domain * axis, and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @throws IllegalArgumentException if {@code stroke} is * {@code null}. * * @see #getDomainMinorGridlineStroke() * * @since 1.0.12 */ public void setDomainMinorGridlineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.domainMinorGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the grid lines (if any) plotted against the domain * axis. * * @return The paint (never {@code null}). * * @see #setDomainGridlinePaint(Paint) */ public Paint getDomainGridlinePaint() { return this.domainGridlinePaint; } /** * Sets the paint for the grid lines plotted against the domain axis, and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @throws IllegalArgumentException if {@code Paint} is * {@code null}. * * @see #getDomainGridlinePaint() */ public void setDomainGridlinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.domainGridlinePaint = paint; fireChangeEvent(); } /** * Returns the paint for the minor grid lines (if any) plotted against the * domain axis. * * @return The paint (never {@code null}). * * @see #setDomainMinorGridlinePaint(Paint) * * @since 1.0.12 */ public Paint getDomainMinorGridlinePaint() { return this.domainMinorGridlinePaint; } /** * Sets the paint for the minor grid lines plotted against the domain axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @throws IllegalArgumentException if {@code Paint} is * {@code null}. * * @see #getDomainMinorGridlinePaint() * * @since 1.0.12 */ public void setDomainMinorGridlinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.domainMinorGridlinePaint = paint; fireChangeEvent(); } /** * Returns {@code true} if the range axis grid is visible, and * {@code false} otherwise. * * @return A boolean. * * @see #setRangeGridlinesVisible(boolean) */ public boolean isRangeGridlinesVisible() { return this.rangeGridlinesVisible; } /** * Sets the flag that controls whether or not the range axis grid lines * are visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isRangeGridlinesVisible() */ public void setRangeGridlinesVisible(boolean visible) { if (this.rangeGridlinesVisible != visible) { this.rangeGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the stroke for the grid lines (if any) plotted against the * range axis. * * @return The stroke (never {@code null}). * * @see #setRangeGridlineStroke(Stroke) */ public Stroke getRangeGridlineStroke() { return this.rangeGridlineStroke; } /** * Sets the stroke for the grid lines plotted against the range axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @see #getRangeGridlineStroke() */ public void setRangeGridlineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the grid lines (if any) plotted against the range * axis. * * @return The paint (never {@code null}). * * @see #setRangeGridlinePaint(Paint) */ public Paint getRangeGridlinePaint() { return this.rangeGridlinePaint; } /** * Sets the paint for the grid lines plotted against the range axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @see #getRangeGridlinePaint() */ public void setRangeGridlinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeGridlinePaint = paint; fireChangeEvent(); } /** * Returns {@code true} if the range axis minor grid is visible, and * {@code false} otherwise. * * @return A boolean. * * @see #setRangeMinorGridlinesVisible(boolean) * * @since 1.0.12 */ public boolean isRangeMinorGridlinesVisible() { return this.rangeMinorGridlinesVisible; } /** * Sets the flag that controls whether or not the range axis minor grid * lines are visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isRangeMinorGridlinesVisible() * * @since 1.0.12 */ public void setRangeMinorGridlinesVisible(boolean visible) { if (this.rangeMinorGridlinesVisible != visible) { this.rangeMinorGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the stroke for the minor grid lines (if any) plotted against the * range axis. * * @return The stroke (never {@code null}). * * @see #setRangeMinorGridlineStroke(Stroke) * * @since 1.0.12 */ public Stroke getRangeMinorGridlineStroke() { return this.rangeMinorGridlineStroke; } /** * Sets the stroke for the minor grid lines plotted against the range axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @see #getRangeMinorGridlineStroke() * * @since 1.0.12 */ public void setRangeMinorGridlineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeMinorGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the minor grid lines (if any) plotted against the * range axis. * * @return The paint (never {@code null}). * * @see #setRangeMinorGridlinePaint(Paint) * * @since 1.0.12 */ public Paint getRangeMinorGridlinePaint() { return this.rangeMinorGridlinePaint; } /** * Sets the paint for the minor grid lines plotted against the range axis * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @see #getRangeMinorGridlinePaint() * * @since 1.0.12 */ public void setRangeMinorGridlinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeMinorGridlinePaint = paint; fireChangeEvent(); } /** * Returns a flag that controls whether or not a zero baseline is * displayed for the domain axis. * * @return A boolean. * * @since 1.0.5 * * @see #setDomainZeroBaselineVisible(boolean) */ public boolean isDomainZeroBaselineVisible() { return this.domainZeroBaselineVisible; } /** * Sets the flag that controls whether or not the zero baseline is * displayed for the domain axis, and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param visible the flag. * * @since 1.0.5 * * @see #isDomainZeroBaselineVisible() */ public void setDomainZeroBaselineVisible(boolean visible) { this.domainZeroBaselineVisible = visible; fireChangeEvent(); } /** * Returns the stroke used for the zero baseline against the domain axis. * * @return The stroke (never {@code null}). * * @since 1.0.5 * * @see #setDomainZeroBaselineStroke(Stroke) */ public Stroke getDomainZeroBaselineStroke() { return this.domainZeroBaselineStroke; } /** * Sets the stroke for the zero baseline for the domain axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @since 1.0.5 * * @see #getRangeZeroBaselineStroke() */ public void setDomainZeroBaselineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.domainZeroBaselineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the zero baseline (if any) plotted against the * domain axis. * * @since 1.0.5 * * @return The paint (never {@code null}). * * @see #setDomainZeroBaselinePaint(Paint) */ public Paint getDomainZeroBaselinePaint() { return this.domainZeroBaselinePaint; } /** * Sets the paint for the zero baseline plotted against the domain axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @since 1.0.5 * * @see #getDomainZeroBaselinePaint() */ public void setDomainZeroBaselinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.domainZeroBaselinePaint = paint; fireChangeEvent(); } /** * Returns a flag that controls whether or not a zero baseline is * displayed for the range axis. * * @return A boolean. * * @see #setRangeZeroBaselineVisible(boolean) */ public boolean isRangeZeroBaselineVisible() { return this.rangeZeroBaselineVisible; } /** * Sets the flag that controls whether or not the zero baseline is * displayed for the range axis, and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param visible the flag. * * @see #isRangeZeroBaselineVisible() */ public void setRangeZeroBaselineVisible(boolean visible) { this.rangeZeroBaselineVisible = visible; fireChangeEvent(); } /** * Returns the stroke used for the zero baseline against the range axis. * * @return The stroke (never {@code null}). * * @see #setRangeZeroBaselineStroke(Stroke) */ public Stroke getRangeZeroBaselineStroke() { return this.rangeZeroBaselineStroke; } /** * Sets the stroke for the zero baseline for the range axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @see #getRangeZeroBaselineStroke() */ public void setRangeZeroBaselineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeZeroBaselineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the zero baseline (if any) plotted against the * range axis. * * @return The paint (never {@code null}). * * @see #setRangeZeroBaselinePaint(Paint) */ public Paint getRangeZeroBaselinePaint() { return this.rangeZeroBaselinePaint; } /** * Sets the paint for the zero baseline plotted against the range axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @see #getRangeZeroBaselinePaint() */ public void setRangeZeroBaselinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeZeroBaselinePaint = paint; fireChangeEvent(); } /** * Returns the paint used for the domain tick bands. If this is * {@code null}, no tick bands will be drawn. * * @return The paint (possibly {@code null}). * * @see #setDomainTickBandPaint(Paint) */ public Paint getDomainTickBandPaint() { return this.domainTickBandPaint; } /** * Sets the paint for the domain tick bands. * * @param paint the paint ({@code null} permitted). * * @see #getDomainTickBandPaint() */ public void setDomainTickBandPaint(Paint paint) { this.domainTickBandPaint = paint; fireChangeEvent(); } /** * Returns the paint used for the range tick bands. If this is * {@code null}, no tick bands will be drawn. * * @return The paint (possibly {@code null}). * * @see #setRangeTickBandPaint(Paint) */ public Paint getRangeTickBandPaint() { return this.rangeTickBandPaint; } /** * Sets the paint for the range tick bands. * * @param paint the paint ({@code null} permitted). * * @see #getRangeTickBandPaint() */ public void setRangeTickBandPaint(Paint paint) { this.rangeTickBandPaint = paint; fireChangeEvent(); } /** * Returns the origin for the quadrants that can be displayed on the plot. * This defaults to (0, 0). * * @return The origin point (never {@code null}). * * @see #setQuadrantOrigin(Point2D) */ public Point2D getQuadrantOrigin() { return this.quadrantOrigin; } /** * Sets the quadrant origin and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param origin the origin ({@code null} not permitted). * * @see #getQuadrantOrigin() */ public void setQuadrantOrigin(Point2D origin) { ParamChecks.nullNotPermitted(origin, "origin"); this.quadrantOrigin = origin; fireChangeEvent(); } /** * Returns the paint used for the specified quadrant. * * @param index the quadrant index (0-3). * * @return The paint (possibly {@code null}). * * @see #setQuadrantPaint(int, Paint) */ public Paint getQuadrantPaint(int index) { if (index < 0 || index > 3) { throw new IllegalArgumentException("The index value (" + index + ") should be in the range 0 to 3."); } return this.quadrantPaint[index]; } /** * Sets the paint used for the specified quadrant and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the quadrant index (0-3). * @param paint the paint ({@code null} permitted). * * @see #getQuadrantPaint(int) */ public void setQuadrantPaint(int index, Paint paint) { if (index < 0 || index > 3) { throw new IllegalArgumentException("The index value (" + index + ") should be in the range 0 to 3."); } this.quadrantPaint[index] = paint; fireChangeEvent(); } /** * Adds a marker for the domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the domain axis, however this is entirely up to the renderer. * * @param marker the marker ({@code null} not permitted). * * @see #addDomainMarker(Marker, Layer) * @see #clearDomainMarkers() */ public void addDomainMarker(Marker marker) { // defer argument checking... addDomainMarker(marker, Layer.FOREGROUND); } /** * Adds a marker for the domain axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the domain axis, however this is entirely up to the renderer. * * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background). * * @see #addDomainMarker(int, Marker, Layer) */ public void addDomainMarker(Marker marker, Layer layer) { addDomainMarker(0, marker, layer); } /** * Clears all the (foreground and background) domain markers and sends a * {@link PlotChangeEvent} to all registered listeners. * * @see #addDomainMarker(int, Marker, Layer) */ public void clearDomainMarkers() { if (this.backgroundDomainMarkers != null) { Set<Integer> keys = this.backgroundDomainMarkers.keySet(); for (Integer key : keys) { clearDomainMarkers(key); } this.backgroundDomainMarkers.clear(); } if (this.foregroundDomainMarkers != null) { Set<Integer> keys = this.foregroundDomainMarkers.keySet(); for (Integer key : keys) { clearDomainMarkers(key); } this.foregroundDomainMarkers.clear(); } fireChangeEvent(); } /** * Clears the (foreground and background) domain markers for a particular * renderer and sends a {@link PlotChangeEvent} to all registered listeners. * * @param index the renderer index. * * @see #clearRangeMarkers(int) */ public void clearDomainMarkers(int index) { Integer key = new Integer(index); if (this.backgroundDomainMarkers != null) { Collection markers = (Collection) this.backgroundDomainMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); m.removeChangeListener(this); } markers.clear(); } } if (this.foregroundRangeMarkers != null) { Collection markers = (Collection) this.foregroundDomainMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); m.removeChangeListener(this); } markers.clear(); } } fireChangeEvent(); } /** * Adds a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the domain axis (that the renderer is mapped to), however this is * entirely up to the renderer. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * * @see #clearDomainMarkers(int) * @see #addRangeMarker(int, Marker, Layer) */ public void addDomainMarker(int index, Marker marker, Layer layer) { addDomainMarker(index, marker, layer, true); } /** * Adds a marker for a specific dataset/renderer and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the domain axis (that the renderer is mapped to), however this is * entirely up to the renderer. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * @param notify notify listeners? * * @since 1.0.10 */ public void addDomainMarker(int index, Marker marker, Layer layer, boolean notify) { ParamChecks.nullNotPermitted(marker, "marker"); ParamChecks.nullNotPermitted(layer, "layer"); Collection markers; if (layer == Layer.FOREGROUND) { markers = (Collection) this.foregroundDomainMarkers.get( new Integer(index)); if (markers == null) { markers = new java.util.ArrayList(); this.foregroundDomainMarkers.put(new Integer(index), markers); } markers.add(marker); } else if (layer == Layer.BACKGROUND) { markers = (Collection) this.backgroundDomainMarkers.get( new Integer(index)); if (markers == null) { markers = new java.util.ArrayList(); this.backgroundDomainMarkers.put(new Integer(index), markers); } markers.add(marker); } marker.addChangeListener(this); if (notify) { fireChangeEvent(); } } /** * Removes a marker for the domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param marker the marker. * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeDomainMarker(Marker marker) { return removeDomainMarker(marker, Layer.FOREGROUND); } /** * Removes a marker for the domain axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeDomainMarker(Marker marker, Layer layer) { return removeDomainMarker(0, marker, layer); } /** * Removes a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeDomainMarker(int index, Marker marker, Layer layer) { return removeDomainMarker(index, marker, layer, true); } /** * Removes a marker for a specific dataset/renderer and, if requested, * sends a {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * @param notify notify listeners? * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.10 */ public boolean removeDomainMarker(int index, Marker marker, Layer layer, boolean notify) { ArrayList markers; if (layer == Layer.FOREGROUND) { markers = (ArrayList) this.foregroundDomainMarkers.get( new Integer(index)); } else { markers = (ArrayList) this.backgroundDomainMarkers.get( new Integer(index)); } if (markers == null) { return false; } boolean removed = markers.remove(marker); if (removed && notify) { fireChangeEvent(); } return removed; } /** * Adds a marker for the range axis and sends a {@link PlotChangeEvent} to * all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the range axis, however this is entirely up to the renderer. * * @param marker the marker ({@code null} not permitted). * * @see #addRangeMarker(Marker, Layer) */ public void addRangeMarker(Marker marker) { addRangeMarker(marker, Layer.FOREGROUND); } /** * Adds a marker for the range axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the range axis, however this is entirely up to the renderer. * * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background). * * @see #addRangeMarker(int, Marker, Layer) */ public void addRangeMarker(Marker marker, Layer layer) { addRangeMarker(0, marker, layer); } /** * Clears all the range markers and sends a {@link PlotChangeEvent} to all * registered listeners. * * @see #clearRangeMarkers() */ public void clearRangeMarkers() { if (this.backgroundRangeMarkers != null) { Set<Integer> keys = this.backgroundRangeMarkers.keySet(); for (Integer key : keys) { clearRangeMarkers(key); } this.backgroundRangeMarkers.clear(); } if (this.foregroundRangeMarkers != null) { Set<Integer> keys = this.foregroundRangeMarkers.keySet(); for (Integer key : keys) { clearRangeMarkers(key); } this.foregroundRangeMarkers.clear(); } fireChangeEvent(); } /** * Adds a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the range axis, however this is entirely up to the renderer. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * * @see #clearRangeMarkers(int) * @see #addDomainMarker(int, Marker, Layer) */ public void addRangeMarker(int index, Marker marker, Layer layer) { addRangeMarker(index, marker, layer, true); } /** * Adds a marker for a specific dataset/renderer and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the range axis, however this is entirely up to the renderer. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * @param notify notify listeners? * * @since 1.0.10 */ public void addRangeMarker(int index, Marker marker, Layer layer, boolean notify) { Collection markers; if (layer == Layer.FOREGROUND) { markers = (Collection) this.foregroundRangeMarkers.get( new Integer(index)); if (markers == null) { markers = new java.util.ArrayList(); this.foregroundRangeMarkers.put(new Integer(index), markers); } markers.add(marker); } else if (layer == Layer.BACKGROUND) { markers = (Collection) this.backgroundRangeMarkers.get( new Integer(index)); if (markers == null) { markers = new java.util.ArrayList(); this.backgroundRangeMarkers.put(new Integer(index), markers); } markers.add(marker); } marker.addChangeListener(this); if (notify) { fireChangeEvent(); } } /** * Clears the (foreground and background) range markers for a particular * renderer. * * @param index the renderer index. */ public void clearRangeMarkers(int index) { Integer key = new Integer(index); if (this.backgroundRangeMarkers != null) { Collection markers = (Collection) this.backgroundRangeMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); m.removeChangeListener(this); } markers.clear(); } } if (this.foregroundRangeMarkers != null) { Collection markers = (Collection) this.foregroundRangeMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); m.removeChangeListener(this); } markers.clear(); } } fireChangeEvent(); } /** * Removes a marker for the range axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param marker the marker. * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeRangeMarker(Marker marker) { return removeRangeMarker(marker, Layer.FOREGROUND); } /** * Removes a marker for the range axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeRangeMarker(Marker marker, Layer layer) { return removeRangeMarker(0, marker, layer); } /** * Removes a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeRangeMarker(int index, Marker marker, Layer layer) { return removeRangeMarker(index, marker, layer, true); } /** * Removes a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background) ({@code null} not permitted). * @param notify notify listeners? * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.10 */ public boolean removeRangeMarker(int index, Marker marker, Layer layer, boolean notify) { ParamChecks.nullNotPermitted(marker, "marker"); ParamChecks.nullNotPermitted(layer, "layer"); List markers; if (layer == Layer.FOREGROUND) { markers = (List) this.foregroundRangeMarkers.get( new Integer(index)); } else { markers = (List) this.backgroundRangeMarkers.get( new Integer(index)); } if (markers == null) { return false; } boolean removed = markers.remove(marker); if (removed && notify) { fireChangeEvent(); } return removed; } /** * Adds an annotation to the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param annotation the annotation ({@code null} not permitted). * * @see #getAnnotations() * @see #removeAnnotation(XYAnnotation) */ public void addAnnotation(XYAnnotation annotation) { addAnnotation(annotation, true); } /** * Adds an annotation to the plot and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param annotation the annotation ({@code null} not permitted). * @param notify notify listeners? * * @since 1.0.10 */ public void addAnnotation(XYAnnotation annotation, boolean notify) { ParamChecks.nullNotPermitted(annotation, "annotation"); this.annotations.add(annotation); annotation.addChangeListener(this); if (notify) { fireChangeEvent(); } } /** * Removes an annotation from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param annotation the annotation ({@code null} not permitted). * * @return A boolean (indicates whether or not the annotation was removed). * * @see #addAnnotation(XYAnnotation) * @see #getAnnotations() */ public boolean removeAnnotation(XYAnnotation annotation) { return removeAnnotation(annotation, true); } /** * Removes an annotation from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param annotation the annotation ({@code null} not permitted). * @param notify notify listeners? * * @return A boolean (indicates whether or not the annotation was removed). * * @since 1.0.10 */ public boolean removeAnnotation(XYAnnotation annotation, boolean notify) { ParamChecks.nullNotPermitted(annotation, "annotation"); boolean removed = this.annotations.remove(annotation); annotation.removeChangeListener(this); if (removed && notify) { fireChangeEvent(); } return removed; } /** * Returns the list of annotations. * * @return The list of annotations. * * @since 1.0.1 * * @see #addAnnotation(XYAnnotation) */ public List getAnnotations() { return new ArrayList(this.annotations); } /** * Clears all the annotations and sends a {@link PlotChangeEvent} to all * registered listeners. * * @see #addAnnotation(XYAnnotation) */ public void clearAnnotations() { for (XYAnnotation annotation : this.annotations) { annotation.removeChangeListener(this); } this.annotations.clear(); fireChangeEvent(); } /** * Returns the shadow generator for the plot, if any. * * @return The shadow generator (possibly {@code null}). * * @since 1.0.14 */ public ShadowGenerator getShadowGenerator() { return this.shadowGenerator; } /** * Sets the shadow generator for the plot and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param generator the generator ({@code null} permitted). * * @since 1.0.14 */ public void setShadowGenerator(ShadowGenerator generator) { this.shadowGenerator = generator; fireChangeEvent(); } /** * Calculates the space required for all the axes in the plot. * * @param g2 the graphics device. * @param plotArea the plot area. * * @return The required space. */ protected AxisSpace calculateAxisSpace(Graphics2D g2, Rectangle2D plotArea) { AxisSpace space = new AxisSpace(); space = calculateRangeAxisSpace(g2, plotArea, space); Rectangle2D revPlotArea = space.shrink(plotArea, null); space = calculateDomainAxisSpace(g2, revPlotArea, space); return space; } /** * Calculates the space required for the domain axis/axes. * * @param g2 the graphics device. * @param plotArea the plot area. * @param space a carrier for the result ({@code null} permitted). * * @return The required space. */ protected AxisSpace calculateDomainAxisSpace(Graphics2D g2, Rectangle2D plotArea, AxisSpace space) { if (space == null) { space = new AxisSpace(); } // reserve some space for the domain axis... if (this.fixedDomainAxisSpace != null) { if (this.orientation == PlotOrientation.HORIZONTAL) { space.ensureAtLeast(this.fixedDomainAxisSpace.getLeft(), RectangleEdge.LEFT); space.ensureAtLeast(this.fixedDomainAxisSpace.getRight(), RectangleEdge.RIGHT); } else if (this.orientation == PlotOrientation.VERTICAL) { space.ensureAtLeast(this.fixedDomainAxisSpace.getTop(), RectangleEdge.TOP); space.ensureAtLeast(this.fixedDomainAxisSpace.getBottom(), RectangleEdge.BOTTOM); } } else { // reserve space for the domain axes... for (ValueAxis axis: this.domainAxes.values()) { if (axis != null) { RectangleEdge edge = getDomainAxisEdge( findDomainAxisIndex(axis)); space = axis.reserveSpace(g2, this, plotArea, edge, space); } } } return space; } /** * Calculates the space required for the range axis/axes. * * @param g2 the graphics device. * @param plotArea the plot area. * @param space a carrier for the result ({@code null} permitted). * * @return The required space. */ protected AxisSpace calculateRangeAxisSpace(Graphics2D g2, Rectangle2D plotArea, AxisSpace space) { if (space == null) { space = new AxisSpace(); } // reserve some space for the range axis... if (this.fixedRangeAxisSpace != null) { if (this.orientation == PlotOrientation.HORIZONTAL) { space.ensureAtLeast(this.fixedRangeAxisSpace.getTop(), RectangleEdge.TOP); space.ensureAtLeast(this.fixedRangeAxisSpace.getBottom(), RectangleEdge.BOTTOM); } else if (this.orientation == PlotOrientation.VERTICAL) { space.ensureAtLeast(this.fixedRangeAxisSpace.getLeft(), RectangleEdge.LEFT); space.ensureAtLeast(this.fixedRangeAxisSpace.getRight(), RectangleEdge.RIGHT); } } else { // reserve space for the range axes... for (ValueAxis axis: this.rangeAxes.values()) { if (axis != null) { RectangleEdge edge = getRangeAxisEdge( findRangeAxisIndex(axis)); space = axis.reserveSpace(g2, this, plotArea, edge, space); } } } return space; } /** * Trims a rectangle to integer coordinates. * * @param rect the incoming rectangle. * * @return A rectangle with integer coordinates. */ private Rectangle integerise(Rectangle2D rect) { int x0 = (int) Math.ceil(rect.getMinX()); int y0 = (int) Math.ceil(rect.getMinY()); int x1 = (int) Math.floor(rect.getMaxX()); int y1 = (int) Math.floor(rect.getMaxY()); return new Rectangle(x0, y0, (x1 - x0), (y1 - y0)); } /** * Draws the plot within the specified area on a graphics device. * * @param g2 the graphics device. * @param area the plot area (in Java2D space). * @param anchor an anchor point in Java2D space ({@code null} * permitted). * @param parentState the state from the parent plot, if there is one * ({@code null} permitted). * @param info collects chart drawing information ({@code null} * permitted). */ @Override public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info) { // if the plot area is too small, just return... boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW); boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW); if (b1 || b2) { return; } // record the plot area... if (info != null) { info.setPlotArea(area); } // adjust the drawing area for the plot insets (if any)... RectangleInsets insets = getInsets(); insets.trim(area); AxisSpace space = calculateAxisSpace(g2, area); Rectangle2D dataArea = space.shrink(area, null); this.axisOffset.trim(dataArea); dataArea = integerise(dataArea); if (dataArea.isEmpty()) { return; } createAndAddEntity((Rectangle2D) dataArea.clone(), info, null, null); if (info != null) { info.setDataArea(dataArea); } // draw the plot background and axes... drawBackground(g2, dataArea); Map axisStateMap = drawAxes(g2, area, dataArea, info); PlotOrientation orient = getOrientation(); // the anchor point is typically the point where the mouse last // clicked - the crosshairs will be driven off this point... if (anchor != null && !dataArea.contains(anchor)) { anchor = null; } CrosshairState crosshairState = new CrosshairState(); crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY); crosshairState.setAnchor(anchor); crosshairState.setAnchorX(Double.NaN); crosshairState.setAnchorY(Double.NaN); if (anchor != null) { ValueAxis domainAxis = getDomainAxis(); if (domainAxis != null) { double x; if (orient == PlotOrientation.VERTICAL) { x = domainAxis.java2DToValue(anchor.getX(), dataArea, getDomainAxisEdge()); } else { x = domainAxis.java2DToValue(anchor.getY(), dataArea, getDomainAxisEdge()); } crosshairState.setAnchorX(x); } ValueAxis rangeAxis = getRangeAxis(); if (rangeAxis != null) { double y; if (orient == PlotOrientation.VERTICAL) { y = rangeAxis.java2DToValue(anchor.getY(), dataArea, getRangeAxisEdge()); } else { y = rangeAxis.java2DToValue(anchor.getX(), dataArea, getRangeAxisEdge()); } crosshairState.setAnchorY(y); } } crosshairState.setCrosshairX(getDomainCrosshairValue()); crosshairState.setCrosshairY(getRangeCrosshairValue()); Shape originalClip = g2.getClip(); Composite originalComposite = g2.getComposite(); g2.clip(dataArea); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha())); AxisState domainAxisState = (AxisState) axisStateMap.get( getDomainAxis()); if (domainAxisState == null) { if (parentState != null) { domainAxisState = (AxisState) parentState.getSharedAxisStates() .get(getDomainAxis()); } } AxisState rangeAxisState = (AxisState) axisStateMap.get(getRangeAxis()); if (rangeAxisState == null) { if (parentState != null) { rangeAxisState = (AxisState) parentState.getSharedAxisStates() .get(getRangeAxis()); } } if (domainAxisState != null) { drawDomainTickBands(g2, dataArea, domainAxisState.getTicks()); } if (rangeAxisState != null) { drawRangeTickBands(g2, dataArea, rangeAxisState.getTicks()); } if (domainAxisState != null) { drawDomainGridlines(g2, dataArea, domainAxisState.getTicks()); drawZeroDomainBaseline(g2, dataArea); } if (rangeAxisState != null) { drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks()); drawZeroRangeBaseline(g2, dataArea); } Graphics2D savedG2 = g2; BufferedImage dataImage = null; boolean suppressShadow = Boolean.TRUE.equals(g2.getRenderingHint( JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION)); if (this.shadowGenerator != null && !suppressShadow) { dataImage = new BufferedImage((int) dataArea.getWidth(), (int)dataArea.getHeight(), BufferedImage.TYPE_INT_ARGB); g2 = dataImage.createGraphics(); g2.translate(-dataArea.getX(), -dataArea.getY()); g2.setRenderingHints(savedG2.getRenderingHints()); } // draw the markers that are associated with a specific dataset... for (XYDataset dataset: this.datasets.values()) { int datasetIndex = indexOf(dataset); drawDomainMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND); } for (XYDataset dataset: this.datasets.values()) { int datasetIndex = indexOf(dataset); drawRangeMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND); } // now draw annotations and render data items... boolean foundData = false; DatasetRenderingOrder order = getDatasetRenderingOrder(); List<Integer> rendererIndices = getRendererIndices(order); List<Integer> datasetIndices = getDatasetIndices(order); // draw background annotations for (int i : rendererIndices) { XYItemRenderer renderer = getRenderer(i); if (renderer != null) { ValueAxis domainAxis = getDomainAxisForDataset(i); ValueAxis rangeAxis = getRangeAxisForDataset(i); renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, Layer.BACKGROUND, info); } } // render data items... for (int datasetIndex : datasetIndices) { XYDataset dataset = this.getDataset(datasetIndex); foundData = render(g2, dataArea, datasetIndex, info, crosshairState) || foundData; } // draw foreground annotations for (int i : rendererIndices) { XYItemRenderer renderer = getRenderer(i); if (renderer != null) { ValueAxis domainAxis = getDomainAxisForDataset(i); ValueAxis rangeAxis = getRangeAxisForDataset(i); renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, Layer.FOREGROUND, info); } } // draw domain crosshair if required... int datasetIndex = crosshairState.getDatasetIndex(); ValueAxis xAxis = this.getDomainAxisForDataset(datasetIndex); RectangleEdge xAxisEdge = getDomainAxisEdge(getDomainAxisIndex(xAxis)); if (!this.domainCrosshairLockedOnData && anchor != null) { double xx; if (orient == PlotOrientation.VERTICAL) { xx = xAxis.java2DToValue(anchor.getX(), dataArea, xAxisEdge); } else { xx = xAxis.java2DToValue(anchor.getY(), dataArea, xAxisEdge); } crosshairState.setCrosshairX(xx); } setDomainCrosshairValue(crosshairState.getCrosshairX(), false); if (isDomainCrosshairVisible()) { double x = getDomainCrosshairValue(); Paint paint = getDomainCrosshairPaint(); Stroke stroke = getDomainCrosshairStroke(); drawDomainCrosshair(g2, dataArea, orient, x, xAxis, stroke, paint); } // draw range crosshair if required... ValueAxis yAxis = getRangeAxisForDataset(datasetIndex); RectangleEdge yAxisEdge = getRangeAxisEdge(getRangeAxisIndex(yAxis)); if (!this.rangeCrosshairLockedOnData && anchor != null) { double yy; if (orient == PlotOrientation.VERTICAL) { yy = yAxis.java2DToValue(anchor.getY(), dataArea, yAxisEdge); } else { yy = yAxis.java2DToValue(anchor.getX(), dataArea, yAxisEdge); } crosshairState.setCrosshairY(yy); } setRangeCrosshairValue(crosshairState.getCrosshairY(), false); if (isRangeCrosshairVisible()) { double y = getRangeCrosshairValue(); Paint paint = getRangeCrosshairPaint(); Stroke stroke = getRangeCrosshairStroke(); drawRangeCrosshair(g2, dataArea, orient, y, yAxis, stroke, paint); } if (!foundData) { drawNoDataMessage(g2, dataArea); } for (int i : rendererIndices) { drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND); } for (int i : rendererIndices) { drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND); } drawAnnotations(g2, dataArea, info); if (this.shadowGenerator != null && !suppressShadow) { BufferedImage shadowImage = this.shadowGenerator.createDropShadow(dataImage); g2 = savedG2; g2.drawImage(shadowImage, (int) dataArea.getX() + this.shadowGenerator.calculateOffsetX(), (int) dataArea.getY() + this.shadowGenerator.calculateOffsetY(), null); g2.drawImage(dataImage, (int) dataArea.getX(), (int) dataArea.getY(), null); } g2.setClip(originalClip); g2.setComposite(originalComposite); drawOutline(g2, dataArea); } /** * Returns the indices of the non-null datasets in the specified order. * * @param order the order ({@code null} not permitted). * * @return The list of indices. */ private List<Integer> getDatasetIndices(DatasetRenderingOrder order) { List<Integer> result = new ArrayList<Integer>(); for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) { if (entry.getValue() != null) { result.add(entry.getKey()); } } Collections.sort(result); if (order == DatasetRenderingOrder.REVERSE) { Collections.reverse(result); } return result; } private List<Integer> getRendererIndices(DatasetRenderingOrder order) { List<Integer> result = new ArrayList<Integer>(); for (Entry<Integer, XYItemRenderer> entry : this.renderers.entrySet()) { if (entry.getValue() != null) { result.add(entry.getKey()); } } Collections.sort(result); if (order == DatasetRenderingOrder.REVERSE) { Collections.reverse(result); } return result; } /** * Draws the background for the plot. * * @param g2 the graphics device. * @param area the area. */ @Override public void drawBackground(Graphics2D g2, Rectangle2D area) { fillBackground(g2, area, this.orientation); drawQuadrants(g2, area); drawBackgroundImage(g2, area); } /** * Draws the quadrants. * * @param g2 the graphics device. * @param area the area. * * @see #setQuadrantOrigin(Point2D) * @see #setQuadrantPaint(int, Paint) */ protected void drawQuadrants(Graphics2D g2, Rectangle2D area) { // 0 | 1 // --+-- // 2 | 3 boolean somethingToDraw = false; ValueAxis xAxis = getDomainAxis(); if (xAxis == null) { // we can't draw quadrants without a valid x-axis return; } double x = xAxis.getRange().constrain(this.quadrantOrigin.getX()); double xx = xAxis.valueToJava2D(x, area, getDomainAxisEdge()); ValueAxis yAxis = getRangeAxis(); if (yAxis == null) { // we can't draw quadrants without a valid y-axis return; } double y = yAxis.getRange().constrain(this.quadrantOrigin.getY()); double yy = yAxis.valueToJava2D(y, area, getRangeAxisEdge()); double xmin = xAxis.getLowerBound(); double xxmin = xAxis.valueToJava2D(xmin, area, getDomainAxisEdge()); double xmax = xAxis.getUpperBound(); double xxmax = xAxis.valueToJava2D(xmax, area, getDomainAxisEdge()); double ymin = yAxis.getLowerBound(); double yymin = yAxis.valueToJava2D(ymin, area, getRangeAxisEdge()); double ymax = yAxis.getUpperBound(); double yymax = yAxis.valueToJava2D(ymax, area, getRangeAxisEdge()); Rectangle2D[] r = new Rectangle2D[] {null, null, null, null}; if (this.quadrantPaint[0] != null) { if (x > xmin && y < ymax) { if (this.orientation == PlotOrientation.HORIZONTAL) { r[0] = new Rectangle2D.Double(Math.min(yymax, yy), Math.min(xxmin, xx), Math.abs(yy - yymax), Math.abs(xx - xxmin)); } else { // PlotOrientation.VERTICAL r[0] = new Rectangle2D.Double(Math.min(xxmin, xx), Math.min(yymax, yy), Math.abs(xx - xxmin), Math.abs(yy - yymax)); } somethingToDraw = true; } } if (this.quadrantPaint[1] != null) { if (x < xmax && y < ymax) { if (this.orientation == PlotOrientation.HORIZONTAL) { r[1] = new Rectangle2D.Double(Math.min(yymax, yy), Math.min(xxmax, xx), Math.abs(yy - yymax), Math.abs(xx - xxmax)); } else { // PlotOrientation.VERTICAL r[1] = new Rectangle2D.Double(Math.min(xx, xxmax), Math.min(yymax, yy), Math.abs(xx - xxmax), Math.abs(yy - yymax)); } somethingToDraw = true; } } if (this.quadrantPaint[2] != null) { if (x > xmin && y > ymin) { if (this.orientation == PlotOrientation.HORIZONTAL) { r[2] = new Rectangle2D.Double(Math.min(yymin, yy), Math.min(xxmin, xx), Math.abs(yy - yymin), Math.abs(xx - xxmin)); } else { // PlotOrientation.VERTICAL r[2] = new Rectangle2D.Double(Math.min(xxmin, xx), Math.min(yymin, yy), Math.abs(xx - xxmin), Math.abs(yy - yymin)); } somethingToDraw = true; } } if (this.quadrantPaint[3] != null) { if (x < xmax && y > ymin) { if (this.orientation == PlotOrientation.HORIZONTAL) { r[3] = new Rectangle2D.Double(Math.min(yymin, yy), Math.min(xxmax, xx), Math.abs(yy - yymin), Math.abs(xx - xxmax)); } else { // PlotOrientation.VERTICAL r[3] = new Rectangle2D.Double(Math.min(xx, xxmax), Math.min(yymin, yy), Math.abs(xx - xxmax), Math.abs(yy - yymin)); } somethingToDraw = true; } } if (somethingToDraw) { Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getBackgroundAlpha())); for (int i = 0; i < 4; i++) { if (this.quadrantPaint[i] != null && r[i] != null) { g2.setPaint(this.quadrantPaint[i]); g2.fill(r[i]); } } g2.setComposite(originalComposite); } } /** * Draws the domain tick bands, if any. * * @param g2 the graphics device. * @param dataArea the data area. * @param ticks the ticks. * * @see #setDomainTickBandPaint(Paint) */ public void drawDomainTickBands(Graphics2D g2, Rectangle2D dataArea, List ticks) { Paint bandPaint = getDomainTickBandPaint(); if (bandPaint != null) { boolean fillBand = false; ValueAxis xAxis = getDomainAxis(); double previous = xAxis.getLowerBound(); Iterator iterator = ticks.iterator(); while (iterator.hasNext()) { ValueTick tick = (ValueTick) iterator.next(); double current = tick.getValue(); if (fillBand) { getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea, previous, current); } previous = current; fillBand = !fillBand; } double end = xAxis.getUpperBound(); if (fillBand) { getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea, previous, end); } } } /** * Draws the range tick bands, if any. * * @param g2 the graphics device. * @param dataArea the data area. * @param ticks the ticks. * * @see #setRangeTickBandPaint(Paint) */ public void drawRangeTickBands(Graphics2D g2, Rectangle2D dataArea, List ticks) { Paint bandPaint = getRangeTickBandPaint(); if (bandPaint != null) { boolean fillBand = false; ValueAxis axis = getRangeAxis(); double previous = axis.getLowerBound(); Iterator iterator = ticks.iterator(); while (iterator.hasNext()) { ValueTick tick = (ValueTick) iterator.next(); double current = tick.getValue(); if (fillBand) { getRenderer().fillRangeGridBand(g2, this, axis, dataArea, previous, current); } previous = current; fillBand = !fillBand; } double end = axis.getUpperBound(); if (fillBand) { getRenderer().fillRangeGridBand(g2, this, axis, dataArea, previous, end); } } } /** * A utility method for drawing the axes. * * @param g2 the graphics device ({@code null} not permitted). * @param plotArea the plot area ({@code null} not permitted). * @param dataArea the data area ({@code null} not permitted). * @param plotState collects information about the plot ({@code null} * permitted). * * @return A map containing the state for each axis drawn. */ protected Map<Axis, AxisState> drawAxes(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, PlotRenderingInfo plotState) { AxisCollection axisCollection = new AxisCollection(); // add domain axes to lists... for (ValueAxis axis : this.domainAxes.values()) { if (axis != null) { int axisIndex = findDomainAxisIndex(axis); axisCollection.add(axis, getDomainAxisEdge(axisIndex)); } } // add range axes to lists... for (ValueAxis axis : this.rangeAxes.values()) { if (axis != null) { int axisIndex = findRangeAxisIndex(axis); axisCollection.add(axis, getRangeAxisEdge(axisIndex)); } } Map axisStateMap = new HashMap(); // draw the top axes double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset( dataArea.getHeight()); Iterator iterator = axisCollection.getAxesAtTop().iterator(); while (iterator.hasNext()) { ValueAxis axis = (ValueAxis) iterator.next(); AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.TOP, plotState); cursor = info.getCursor(); axisStateMap.put(axis, info); } // draw the bottom axes cursor = dataArea.getMaxY() + this.axisOffset.calculateBottomOutset(dataArea.getHeight()); iterator = axisCollection.getAxesAtBottom().iterator(); while (iterator.hasNext()) { ValueAxis axis = (ValueAxis) iterator.next(); AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.BOTTOM, plotState); cursor = info.getCursor(); axisStateMap.put(axis, info); } // draw the left axes cursor = dataArea.getMinX() - this.axisOffset.calculateLeftOutset(dataArea.getWidth()); iterator = axisCollection.getAxesAtLeft().iterator(); while (iterator.hasNext()) { ValueAxis axis = (ValueAxis) iterator.next(); AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.LEFT, plotState); cursor = info.getCursor(); axisStateMap.put(axis, info); } // draw the right axes cursor = dataArea.getMaxX() + this.axisOffset.calculateRightOutset(dataArea.getWidth()); iterator = axisCollection.getAxesAtRight().iterator(); while (iterator.hasNext()) { ValueAxis axis = (ValueAxis) iterator.next(); AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.RIGHT, plotState); cursor = info.getCursor(); axisStateMap.put(axis, info); } return axisStateMap; } /** * Draws a representation of the data within the dataArea region, using the * current renderer. * <P> * The {@code info} and {@code crosshairState} arguments may be * {@code null}. * * @param g2 the graphics device. * @param dataArea the region in which the data is to be drawn. * @param index the dataset index. * @param info an optional object for collection dimension information. * @param crosshairState collects crosshair information * ({@code null} permitted). * * @return A flag that indicates whether any data was actually rendered. */ public boolean render(Graphics2D g2, Rectangle2D dataArea, int index, PlotRenderingInfo info, CrosshairState crosshairState) { boolean foundData = false; XYDataset dataset = getDataset(index); if (!DatasetUtilities.isEmptyOrNull(dataset)) { foundData = true; ValueAxis xAxis = getDomainAxisForDataset(index); ValueAxis yAxis = getRangeAxisForDataset(index); if (xAxis == null || yAxis == null) { return foundData; // can't render anything without axes } XYItemRenderer renderer = getRenderer(index); if (renderer == null) { renderer = getRenderer(); if (renderer == null) { // no default renderer available return foundData; } } XYItemRendererState state = renderer.initialise(g2, dataArea, this, dataset, info); int passCount = renderer.getPassCount(); SeriesRenderingOrder seriesOrder = getSeriesRenderingOrder(); if (seriesOrder == SeriesRenderingOrder.REVERSE) { //render series in reverse order for (int pass = 0; pass < passCount; pass++) { int seriesCount = dataset.getSeriesCount(); for (int series = seriesCount - 1; series >= 0; series--) { int firstItem = 0; int lastItem = dataset.getItemCount(series) - 1; if (lastItem == -1) { continue; } if (state.getProcessVisibleItemsOnly()) { int[] itemBounds = RendererUtilities.findLiveItems( dataset, series, xAxis.getLowerBound(), xAxis.getUpperBound()); firstItem = Math.max(itemBounds[0] - 1, 0); lastItem = Math.min(itemBounds[1] + 1, lastItem); } state.startSeriesPass(dataset, series, firstItem, lastItem, pass, passCount); for (int item = firstItem; item <= lastItem; item++) { renderer.drawItem(g2, state, dataArea, info, this, xAxis, yAxis, dataset, series, item, crosshairState, pass); } state.endSeriesPass(dataset, series, firstItem, lastItem, pass, passCount); } } } else { //render series in forward order for (int pass = 0; pass < passCount; pass++) { int seriesCount = dataset.getSeriesCount(); for (int series = 0; series < seriesCount; series++) { int firstItem = 0; int lastItem = dataset.getItemCount(series) - 1; if (state.getProcessVisibleItemsOnly()) { int[] itemBounds = RendererUtilities.findLiveItems( dataset, series, xAxis.getLowerBound(), xAxis.getUpperBound()); firstItem = Math.max(itemBounds[0] - 1, 0); lastItem = Math.min(itemBounds[1] + 1, lastItem); } state.startSeriesPass(dataset, series, firstItem, lastItem, pass, passCount); for (int item = firstItem; item <= lastItem; item++) { renderer.drawItem(g2, state, dataArea, info, this, xAxis, yAxis, dataset, series, item, crosshairState, pass); } state.endSeriesPass(dataset, series, firstItem, lastItem, pass, passCount); } } } } return foundData; } /** * Returns the domain axis for a dataset. * * @param index the dataset index (must be &gt;= 0). * * @return The axis. */ public ValueAxis getDomainAxisForDataset(int index) { ParamChecks.requireNonNegative(index, "index"); ValueAxis valueAxis; List axisIndices = (List) this.datasetToDomainAxesMap.get( new Integer(index)); if (axisIndices != null) { // the first axis in the list is used for data <--> Java2D Integer axisIndex = (Integer) axisIndices.get(0); valueAxis = getDomainAxis(axisIndex.intValue()); } else { valueAxis = getDomainAxis(0); } return valueAxis; } /** * Returns the range axis for a dataset. * * @param index the dataset index (must be &gt;= 0). * * @return The axis. */ public ValueAxis getRangeAxisForDataset(int index) { ParamChecks.requireNonNegative(index, "index"); ValueAxis valueAxis; List axisIndices = (List) this.datasetToRangeAxesMap.get( new Integer(index)); if (axisIndices != null) { // the first axis in the list is used for data <--> Java2D Integer axisIndex = (Integer) axisIndices.get(0); valueAxis = getRangeAxis(axisIndex.intValue()); } else { valueAxis = getRangeAxis(0); } return valueAxis; } /** * Draws the gridlines for the plot, if they are visible. * * @param g2 the graphics device. * @param dataArea the data area. * @param ticks the ticks. * * @see #drawRangeGridlines(Graphics2D, Rectangle2D, List) */ protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea, List ticks) { // no renderer, no gridlines... if (getRenderer() == null) { return; } // draw the domain grid lines, if any... if (isDomainGridlinesVisible() || isDomainMinorGridlinesVisible()) { Stroke gridStroke = null; Paint gridPaint = null; Iterator iterator = ticks.iterator(); boolean paintLine; while (iterator.hasNext()) { paintLine = false; ValueTick tick = (ValueTick) iterator.next(); if ((tick.getTickType() == TickType.MINOR) && isDomainMinorGridlinesVisible()) { gridStroke = getDomainMinorGridlineStroke(); gridPaint = getDomainMinorGridlinePaint(); paintLine = true; } else if ((tick.getTickType() == TickType.MAJOR) && isDomainGridlinesVisible()) { gridStroke = getDomainGridlineStroke(); gridPaint = getDomainGridlinePaint(); paintLine = true; } XYItemRenderer r = getRenderer(); if ((r instanceof AbstractXYItemRenderer) && paintLine) { ((AbstractXYItemRenderer) r).drawDomainLine(g2, this, getDomainAxis(), dataArea, tick.getValue(), gridPaint, gridStroke); } } } } /** * Draws the gridlines for the plot's primary range axis, if they are * visible. * * @param g2 the graphics device. * @param area the data area. * @param ticks the ticks. * * @see #drawDomainGridlines(Graphics2D, Rectangle2D, List) */ protected void drawRangeGridlines(Graphics2D g2, Rectangle2D area, List ticks) { // no renderer, no gridlines... if (getRenderer() == null) { return; } // draw the range grid lines, if any... if (isRangeGridlinesVisible() || isRangeMinorGridlinesVisible()) { Stroke gridStroke = null; Paint gridPaint = null; ValueAxis axis = getRangeAxis(); if (axis != null) { Iterator iterator = ticks.iterator(); boolean paintLine; while (iterator.hasNext()) { paintLine = false; ValueTick tick = (ValueTick) iterator.next(); if ((tick.getTickType() == TickType.MINOR) && isRangeMinorGridlinesVisible()) { gridStroke = getRangeMinorGridlineStroke(); gridPaint = getRangeMinorGridlinePaint(); paintLine = true; } else if ((tick.getTickType() == TickType.MAJOR) && isRangeGridlinesVisible()) { gridStroke = getRangeGridlineStroke(); gridPaint = getRangeGridlinePaint(); paintLine = true; } if ((tick.getValue() != 0.0 || !isRangeZeroBaselineVisible()) && paintLine) { getRenderer().drawRangeLine(g2, this, getRangeAxis(), area, tick.getValue(), gridPaint, gridStroke); } } } } } /** * Draws a base line across the chart at value zero on the domain axis. * * @param g2 the graphics device. * @param area the data area. * * @see #setDomainZeroBaselineVisible(boolean) * * @since 1.0.5 */ protected void drawZeroDomainBaseline(Graphics2D g2, Rectangle2D area) { if (isDomainZeroBaselineVisible()) { XYItemRenderer r = getRenderer(); // FIXME: the renderer interface doesn't have the drawDomainLine() // method, so we have to rely on the renderer being a subclass of // AbstractXYItemRenderer (which is lame) if (r instanceof AbstractXYItemRenderer) { AbstractXYItemRenderer renderer = (AbstractXYItemRenderer) r; renderer.drawDomainLine(g2, this, getDomainAxis(), area, 0.0, this.domainZeroBaselinePaint, this.domainZeroBaselineStroke); } } } /** * Draws a base line across the chart at value zero on the range axis. * * @param g2 the graphics device. * @param area the data area. * * @see #setRangeZeroBaselineVisible(boolean) */ protected void drawZeroRangeBaseline(Graphics2D g2, Rectangle2D area) { if (isRangeZeroBaselineVisible()) { getRenderer().drawRangeLine(g2, this, getRangeAxis(), area, 0.0, this.rangeZeroBaselinePaint, this.rangeZeroBaselineStroke); } } /** * Draws the annotations for the plot. * * @param g2 the graphics device. * @param dataArea the data area. * @param info the chart rendering info. */ public void drawAnnotations(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info) { Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); ValueAxis xAxis = getDomainAxis(); ValueAxis yAxis = getRangeAxis(); annotation.draw(g2, this, dataArea, xAxis, yAxis, 0, info); } } /** * Draws the domain markers (if any) for an axis and layer. This method is * typically called from within the draw() method. * * @param g2 the graphics device. * @param dataArea the data area. * @param index the dataset/renderer index. * @param layer the layer (foreground or background). */ protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea, int index, Layer layer) { XYItemRenderer r = getRenderer(index); if (r == null) { return; } // check that the renderer has a corresponding dataset (it doesn't // matter if the dataset is null) if (index >= getDatasetCount()) { return; } Collection markers = getDomainMarkers(index, layer); ValueAxis axis = getDomainAxisForDataset(index); if (markers != null && axis != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker marker = (Marker) iterator.next(); r.drawDomainMarker(g2, this, axis, marker, dataArea); } } } /** * Draws the range markers (if any) for a renderer and layer. This method * is typically called from within the draw() method. * * @param g2 the graphics device. * @param dataArea the data area. * @param index the renderer index. * @param layer the layer (foreground or background). */ protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea, int index, Layer layer) { XYItemRenderer r = getRenderer(index); if (r == null) { return; } // check that the renderer has a corresponding dataset (it doesn't // matter if the dataset is null) if (index >= getDatasetCount()) { return; } Collection markers = getRangeMarkers(index, layer); ValueAxis axis = getRangeAxisForDataset(index); if (markers != null && axis != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker marker = (Marker) iterator.next(); r.drawRangeMarker(g2, this, axis, marker, dataArea); } } } /** * Returns the list of domain markers (read only) for the specified layer. * * @param layer the layer (foreground or background). * * @return The list of domain markers. * * @see #getRangeMarkers(Layer) */ public Collection getDomainMarkers(Layer layer) { return getDomainMarkers(0, layer); } /** * Returns the list of range markers (read only) for the specified layer. * * @param layer the layer (foreground or background). * * @return The list of range markers. * * @see #getDomainMarkers(Layer) */ public Collection getRangeMarkers(Layer layer) { return getRangeMarkers(0, layer); } /** * Returns a collection of domain markers for a particular renderer and * layer. * * @param index the renderer index. * @param layer the layer. * * @return A collection of markers (possibly {@code null}). * * @see #getRangeMarkers(int, Layer) */ public Collection getDomainMarkers(int index, Layer layer) { Collection result = null; Integer key = new Integer(index); if (layer == Layer.FOREGROUND) { result = (Collection) this.foregroundDomainMarkers.get(key); } else if (layer == Layer.BACKGROUND) { result = (Collection) this.backgroundDomainMarkers.get(key); } if (result != null) { result = Collections.unmodifiableCollection(result); } return result; } /** * Returns a collection of range markers for a particular renderer and * layer. * * @param index the renderer index. * @param layer the layer. * * @return A collection of markers (possibly {@code null}). * * @see #getDomainMarkers(int, Layer) */ public Collection getRangeMarkers(int index, Layer layer) { Collection result = null; Integer key = new Integer(index); if (layer == Layer.FOREGROUND) { result = (Collection) this.foregroundRangeMarkers.get(key); } else if (layer == Layer.BACKGROUND) { result = (Collection) this.backgroundRangeMarkers.get(key); } if (result != null) { result = Collections.unmodifiableCollection(result); } return result; } /** * Utility method for drawing a horizontal line across the data area of the * plot. * * @param g2 the graphics device. * @param dataArea the data area. * @param value the coordinate, where to draw the line. * @param stroke the stroke to use. * @param paint the paint to use. */ protected void drawHorizontalLine(Graphics2D g2, Rectangle2D dataArea, double value, Stroke stroke, Paint paint) { ValueAxis axis = getRangeAxis(); if (getOrientation() == PlotOrientation.HORIZONTAL) { axis = getDomainAxis(); } if (axis.getRange().contains(value)) { double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); Line2D line = new Line2D.Double(dataArea.getMinX(), yy, dataArea.getMaxX(), yy); g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); } } /** * Draws a domain crosshair. * * @param g2 the graphics target. * @param dataArea the data area. * @param orientation the plot orientation. * @param value the crosshair value. * @param axis the axis against which the value is measured. * @param stroke the stroke used to draw the crosshair line. * @param paint the paint used to draw the crosshair line. * * @since 1.0.4 */ protected void drawDomainCrosshair(Graphics2D g2, Rectangle2D dataArea, PlotOrientation orientation, double value, ValueAxis axis, Stroke stroke, Paint paint) { if (!axis.getRange().contains(value)) { return; } Line2D line; if (orientation == PlotOrientation.VERTICAL) { double xx = axis.valueToJava2D(value, dataArea, RectangleEdge.BOTTOM); line = new Line2D.Double(xx, dataArea.getMinY(), xx, dataArea.getMaxY()); } else { double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); line = new Line2D.Double(dataArea.getMinX(), yy, dataArea.getMaxX(), yy); } Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved); } /** * Utility method for drawing a vertical line on the data area of the plot. * * @param g2 the graphics device. * @param dataArea the data area. * @param value the coordinate, where to draw the line. * @param stroke the stroke to use. * @param paint the paint to use. */ protected void drawVerticalLine(Graphics2D g2, Rectangle2D dataArea, double value, Stroke stroke, Paint paint) { ValueAxis axis = getDomainAxis(); if (getOrientation() == PlotOrientation.HORIZONTAL) { axis = getRangeAxis(); } if (axis.getRange().contains(value)) { double xx = axis.valueToJava2D(value, dataArea, RectangleEdge.BOTTOM); Line2D line = new Line2D.Double(xx, dataArea.getMinY(), xx, dataArea.getMaxY()); g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); } } /** * Draws a range crosshair. * * @param g2 the graphics target. * @param dataArea the data area. * @param orientation the plot orientation. * @param value the crosshair value. * @param axis the axis against which the value is measured. * @param stroke the stroke used to draw the crosshair line. * @param paint the paint used to draw the crosshair line. * * @since 1.0.4 */ protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea, PlotOrientation orientation, double value, ValueAxis axis, Stroke stroke, Paint paint) { if (!axis.getRange().contains(value)) { return; } Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); Line2D line; if (orientation == PlotOrientation.HORIZONTAL) { double xx = axis.valueToJava2D(value, dataArea, RectangleEdge.BOTTOM); line = new Line2D.Double(xx, dataArea.getMinY(), xx, dataArea.getMaxY()); } else { double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); line = new Line2D.Double(dataArea.getMinX(), yy, dataArea.getMaxX(), yy); } g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved); } /** * Handles a 'click' on the plot by updating the anchor values. * * @param x the x-coordinate, where the click occurred, in Java2D space. * @param y the y-coordinate, where the click occurred, in Java2D space. * @param info object containing information about the plot dimensions. */ @Override public void handleClick(int x, int y, PlotRenderingInfo info) { Rectangle2D dataArea = info.getDataArea(); if (dataArea.contains(x, y)) { // set the anchor value for the horizontal axis... ValueAxis xaxis = getDomainAxis(); if (xaxis != null) { double hvalue = xaxis.java2DToValue(x, info.getDataArea(), getDomainAxisEdge()); setDomainCrosshairValue(hvalue); } // set the anchor value for the vertical axis... ValueAxis yaxis = getRangeAxis(); if (yaxis != null) { double vvalue = yaxis.java2DToValue(y, info.getDataArea(), getRangeAxisEdge()); setRangeCrosshairValue(vvalue); } } } /** * A utility method that returns a list of datasets that are mapped to a * particular axis. * * @param axisIndex the axis index ({@code null} not permitted). * * @return A list of datasets. */ private List<XYDataset> getDatasetsMappedToDomainAxis(Integer axisIndex) { ParamChecks.nullNotPermitted(axisIndex, "axisIndex"); List<XYDataset> result = new ArrayList<XYDataset>(); for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) { int index = entry.getKey(); List<Integer> mappedAxes = this.datasetToDomainAxesMap.get(index); if (mappedAxes == null) { if (axisIndex.equals(ZERO)) { result.add(entry.getValue()); } } else { if (mappedAxes.contains(axisIndex)) { result.add(entry.getValue()); } } } return result; } /** * A utility method that returns a list of datasets that are mapped to a * particular axis. * * @param axisIndex the axis index ({@code null} not permitted). * * @return A list of datasets. */ private List<XYDataset> getDatasetsMappedToRangeAxis(Integer axisIndex) { ParamChecks.nullNotPermitted(axisIndex, "axisIndex"); List<XYDataset> result = new ArrayList<XYDataset>(); for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) { int index = entry.getKey(); List<Integer> mappedAxes = this.datasetToRangeAxesMap.get(index); if (mappedAxes == null) { if (axisIndex.equals(ZERO)) { result.add(entry.getValue()); } } else { if (mappedAxes.contains(axisIndex)) { result.add(entry.getValue()); } } } return result; } /** * Returns the index of the given domain axis. * * @param axis the axis. * * @return The axis index. * * @see #getRangeAxisIndex(ValueAxis) */ public int getDomainAxisIndex(ValueAxis axis) { int result = findDomainAxisIndex(axis); if (result < 0) { // try the parent plot Plot parent = getParent(); if (parent instanceof XYPlot) { XYPlot p = (XYPlot) parent; result = p.getDomainAxisIndex(axis); } } return result; } private int findDomainAxisIndex(ValueAxis axis) { for (Map.Entry<Integer, ValueAxis> entry : this.domainAxes.entrySet()) { if (entry.getValue() == axis) { return entry.getKey(); } } return -1; } /** * Returns the index of the given range axis. * * @param axis the axis. * * @return The axis index. * * @see #getDomainAxisIndex(ValueAxis) */ public int getRangeAxisIndex(ValueAxis axis) { int result = findRangeAxisIndex(axis); if (result < 0) { // try the parent plot Plot parent = getParent(); if (parent instanceof XYPlot) { XYPlot p = (XYPlot) parent; result = p.getRangeAxisIndex(axis); } } return result; } private int findRangeAxisIndex(ValueAxis axis) { for (Map.Entry<Integer, ValueAxis> entry : this.rangeAxes.entrySet()) { if (entry.getValue() == axis) { return entry.getKey(); } } return -1; } /** * Returns the range for the specified axis. * * @param axis the axis. * * @return The range. */ @Override public Range getDataRange(ValueAxis axis) { Range result = null; List<XYDataset> mappedDatasets = new ArrayList<XYDataset>(); List<XYAnnotation> includedAnnotations = new ArrayList<XYAnnotation>(); boolean isDomainAxis = true; // is it a domain axis? int domainIndex = getDomainAxisIndex(axis); if (domainIndex >= 0) { isDomainAxis = true; mappedDatasets.addAll(getDatasetsMappedToDomainAxis(domainIndex)); if (domainIndex == 0) { // grab the plot's annotations Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); if (annotation instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(annotation); } } } } // or is it a range axis? int rangeIndex = getRangeAxisIndex(axis); if (rangeIndex >= 0) { isDomainAxis = false; mappedDatasets.addAll(getDatasetsMappedToRangeAxis(rangeIndex)); if (rangeIndex == 0) { Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); if (annotation instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(annotation); } } } } // iterate through the datasets that map to the axis and get the union // of the ranges. for (XYDataset d : mappedDatasets) { if (d != null) { XYItemRenderer r = getRendererForDataset(d); if (isDomainAxis) { if (r != null) { result = Range.combine(result, r.findDomainBounds(d)); } else { result = Range.combine(result, DatasetUtilities.findDomainBounds(d)); } } else { if (r != null) { result = Range.combine(result, r.findRangeBounds(d)); } else { result = Range.combine(result, DatasetUtilities.findRangeBounds(d)); } } // FIXME: the XYItemRenderer interface doesn't specify the // getAnnotations() method but it should if (r instanceof AbstractXYItemRenderer) { AbstractXYItemRenderer rr = (AbstractXYItemRenderer) r; Collection c = rr.getAnnotations(); Iterator i = c.iterator(); while (i.hasNext()) { XYAnnotation a = (XYAnnotation) i.next(); if (a instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(a); } } } } } Iterator it = includedAnnotations.iterator(); while (it.hasNext()) { XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next(); if (xyabi.getIncludeInDataBounds()) { if (isDomainAxis) { result = Range.combine(result, xyabi.getXRange()); } else { result = Range.combine(result, xyabi.getYRange()); } } } return result; } /** * Receives notification of a change to an {@link Annotation} added to * this plot. * * @param event information about the event (not used here). * * @since 1.0.14 */ @Override public void annotationChanged(AnnotationChangeEvent event) { if (getParent() != null) { getParent().annotationChanged(event); } else { PlotChangeEvent e = new PlotChangeEvent(this); notifyListeners(e); } } /** * Receives notification of a change to the plot's dataset. * <P> * The axis ranges are updated if necessary. * * @param event information about the event (not used here). */ @Override public void datasetChanged(DatasetChangeEvent event) { configureDomainAxes(); configureRangeAxes(); if (getParent() != null) { getParent().datasetChanged(event); } else { PlotChangeEvent e = new PlotChangeEvent(this); e.setType(ChartChangeEventType.DATASET_UPDATED); notifyListeners(e); } } /** * Receives notification of a renderer change event. * * @param event the event. */ @Override public void rendererChanged(RendererChangeEvent event) { // if the event was caused by a change to series visibility, then // the axis ranges might need updating... if (event.getSeriesVisibilityChanged()) { configureDomainAxes(); configureRangeAxes(); } fireChangeEvent(); } /** * Returns a flag indicating whether or not the domain crosshair is visible. * * @return The flag. * * @see #setDomainCrosshairVisible(boolean) */ public boolean isDomainCrosshairVisible() { return this.domainCrosshairVisible; } /** * Sets the flag indicating whether or not the domain crosshair is visible * and, if the flag changes, sends a {@link PlotChangeEvent} to all * registered listeners. * * @param flag the new value of the flag. * * @see #isDomainCrosshairVisible() */ public void setDomainCrosshairVisible(boolean flag) { if (this.domainCrosshairVisible != flag) { this.domainCrosshairVisible = flag; fireChangeEvent(); } } /** * Returns a flag indicating whether or not the crosshair should "lock-on" * to actual data values. * * @return The flag. * * @see #setDomainCrosshairLockedOnData(boolean) */ public boolean isDomainCrosshairLockedOnData() { return this.domainCrosshairLockedOnData; } /** * Sets the flag indicating whether or not the domain crosshair should * "lock-on" to actual data values. If the flag value changes, this * method sends a {@link PlotChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #isDomainCrosshairLockedOnData() */ public void setDomainCrosshairLockedOnData(boolean flag) { if (this.domainCrosshairLockedOnData != flag) { this.domainCrosshairLockedOnData = flag; fireChangeEvent(); } } /** * Returns the domain crosshair value. * * @return The value. * * @see #setDomainCrosshairValue(double) */ public double getDomainCrosshairValue() { return this.domainCrosshairValue; } /** * Sets the domain crosshair value and sends a {@link PlotChangeEvent} to * all registered listeners (provided that the domain crosshair is visible). * * @param value the value. * * @see #getDomainCrosshairValue() */ public void setDomainCrosshairValue(double value) { setDomainCrosshairValue(value, true); } /** * Sets the domain crosshair value and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners (provided that the * domain crosshair is visible). * * @param value the new value. * @param notify notify listeners? * * @see #getDomainCrosshairValue() */ public void setDomainCrosshairValue(double value, boolean notify) { this.domainCrosshairValue = value; if (isDomainCrosshairVisible() && notify) { fireChangeEvent(); } } /** * Returns the {@link Stroke} used to draw the crosshair (if visible). * * @return The crosshair stroke (never {@code null}). * * @see #setDomainCrosshairStroke(Stroke) * @see #isDomainCrosshairVisible() * @see #getDomainCrosshairPaint() */ public Stroke getDomainCrosshairStroke() { return this.domainCrosshairStroke; } /** * Sets the Stroke used to draw the crosshairs (if visible) and notifies * registered listeners that the axis has been modified. * * @param stroke the new crosshair stroke ({@code null} not * permitted). * * @see #getDomainCrosshairStroke() */ public void setDomainCrosshairStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.domainCrosshairStroke = stroke; fireChangeEvent(); } /** * Returns the domain crosshair paint. * * @return The crosshair paint (never {@code null}). * * @see #setDomainCrosshairPaint(Paint) * @see #isDomainCrosshairVisible() * @see #getDomainCrosshairStroke() */ public Paint getDomainCrosshairPaint() { return this.domainCrosshairPaint; } /** * Sets the paint used to draw the crosshairs (if visible) and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param paint the new crosshair paint ({@code null} not permitted). * * @see #getDomainCrosshairPaint() */ public void setDomainCrosshairPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.domainCrosshairPaint = paint; fireChangeEvent(); } /** * Returns a flag indicating whether or not the range crosshair is visible. * * @return The flag. * * @see #setRangeCrosshairVisible(boolean) * @see #isDomainCrosshairVisible() */ public boolean isRangeCrosshairVisible() { return this.rangeCrosshairVisible; } /** * Sets the flag indicating whether or not the range crosshair is visible. * If the flag value changes, this method sends a {@link PlotChangeEvent} * to all registered listeners. * * @param flag the new value of the flag. * * @see #isRangeCrosshairVisible() */ public void setRangeCrosshairVisible(boolean flag) { if (this.rangeCrosshairVisible != flag) { this.rangeCrosshairVisible = flag; fireChangeEvent(); } } /** * Returns a flag indicating whether or not the crosshair should "lock-on" * to actual data values. * * @return The flag. * * @see #setRangeCrosshairLockedOnData(boolean) */ public boolean isRangeCrosshairLockedOnData() { return this.rangeCrosshairLockedOnData; } /** * Sets the flag indicating whether or not the range crosshair should * "lock-on" to actual data values. If the flag value changes, this method * sends a {@link PlotChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #isRangeCrosshairLockedOnData() */ public void setRangeCrosshairLockedOnData(boolean flag) { if (this.rangeCrosshairLockedOnData != flag) { this.rangeCrosshairLockedOnData = flag; fireChangeEvent(); } } /** * Returns the range crosshair value. * * @return The value. * * @see #setRangeCrosshairValue(double) */ public double getRangeCrosshairValue() { return this.rangeCrosshairValue; } /** * Sets the range crosshair value. * <P> * Registered listeners are notified that the plot has been modified, but * only if the crosshair is visible. * * @param value the new value. * * @see #getRangeCrosshairValue() */ public void setRangeCrosshairValue(double value) { setRangeCrosshairValue(value, true); } /** * Sets the range crosshair value and sends a {@link PlotChangeEvent} to * all registered listeners, but only if the crosshair is visible. * * @param value the new value. * @param notify a flag that controls whether or not listeners are * notified. * * @see #getRangeCrosshairValue() */ public void setRangeCrosshairValue(double value, boolean notify) { this.rangeCrosshairValue = value; if (isRangeCrosshairVisible() && notify) { fireChangeEvent(); } } /** * Returns the stroke used to draw the crosshair (if visible). * * @return The crosshair stroke (never {@code null}). * * @see #setRangeCrosshairStroke(Stroke) * @see #isRangeCrosshairVisible() * @see #getRangeCrosshairPaint() */ public Stroke getRangeCrosshairStroke() { return this.rangeCrosshairStroke; } /** * Sets the stroke used to draw the crosshairs (if visible) and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param stroke the new crosshair stroke ({@code null} not * permitted). * * @see #getRangeCrosshairStroke() */ public void setRangeCrosshairStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeCrosshairStroke = stroke; fireChangeEvent(); } /** * Returns the range crosshair paint. * * @return The crosshair paint (never {@code null}). * * @see #setRangeCrosshairPaint(Paint) * @see #isRangeCrosshairVisible() * @see #getRangeCrosshairStroke() */ public Paint getRangeCrosshairPaint() { return this.rangeCrosshairPaint; } /** * Sets the paint used to color the crosshairs (if visible) and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param paint the new crosshair paint ({@code null} not permitted). * * @see #getRangeCrosshairPaint() */ public void setRangeCrosshairPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeCrosshairPaint = paint; fireChangeEvent(); } /** * Returns the fixed domain axis space. * * @return The fixed domain axis space (possibly {@code null}). * * @see #setFixedDomainAxisSpace(AxisSpace) */ public AxisSpace getFixedDomainAxisSpace() { return this.fixedDomainAxisSpace; } /** * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param space the space ({@code null} permitted). * * @see #getFixedDomainAxisSpace() */ public void setFixedDomainAxisSpace(AxisSpace space) { setFixedDomainAxisSpace(space, true); } /** * Sets the fixed domain axis space and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param space the space ({@code null} permitted). * @param notify notify listeners? * * @see #getFixedDomainAxisSpace() * * @since 1.0.9 */ public void setFixedDomainAxisSpace(AxisSpace space, boolean notify) { this.fixedDomainAxisSpace = space; if (notify) { fireChangeEvent(); } } /** * Returns the fixed range axis space. * * @return The fixed range axis space (possibly {@code null}). * * @see #setFixedRangeAxisSpace(AxisSpace) */ public AxisSpace getFixedRangeAxisSpace() { return this.fixedRangeAxisSpace; } /** * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param space the space ({@code null} permitted). * * @see #getFixedRangeAxisSpace() */ public void setFixedRangeAxisSpace(AxisSpace space) { setFixedRangeAxisSpace(space, true); } /** * Sets the fixed range axis space and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param space the space ({@code null} permitted). * @param notify notify listeners? * * @see #getFixedRangeAxisSpace() * * @since 1.0.9 */ public void setFixedRangeAxisSpace(AxisSpace space, boolean notify) { this.fixedRangeAxisSpace = space; if (notify) { fireChangeEvent(); } } /** * Returns {@code true} if panning is enabled for the domain axes, * and {@code false} otherwise. * * @return A boolean. * * @since 1.0.13 */ @Override public boolean isDomainPannable() { return this.domainPannable; } /** * Sets the flag that enables or disables panning of the plot along the * domain axes. * * @param pannable the new flag value. * * @since 1.0.13 */ public void setDomainPannable(boolean pannable) { this.domainPannable = pannable; } /** * Returns {@code true} if panning is enabled for the range axis/axes, * and {@code false} otherwise. The default value is {@code false}. * * @return A boolean. * * @since 1.0.13 */ @Override public boolean isRangePannable() { return this.rangePannable; } /** * Sets the flag that enables or disables panning of the plot along * the range axis/axes. * * @param pannable the new flag value. * * @since 1.0.13 */ public void setRangePannable(boolean pannable) { this.rangePannable = pannable; } /** * Pans the domain axes by the specified percentage. * * @param percent the distance to pan (as a percentage of the axis length). * @param info the plot info * @param source the source point where the pan action started. * * @since 1.0.13 */ @Override public void panDomainAxes(double percent, PlotRenderingInfo info, Point2D source) { if (!isDomainPannable()) { return; } int domainAxisCount = getDomainAxisCount(); for (int i = 0; i < domainAxisCount; i++) { ValueAxis axis = getDomainAxis(i); if (axis == null) { continue; } if (axis.isInverted()) { percent = -percent; } axis.pan(percent); } } /** * Pans the range axes by the specified percentage. * * @param percent the distance to pan (as a percentage of the axis length). * @param info the plot info * @param source the source point where the pan action started. * * @since 1.0.13 */ @Override public void panRangeAxes(double percent, PlotRenderingInfo info, Point2D source) { if (!isRangePannable()) { return; } int rangeAxisCount = getRangeAxisCount(); for (int i = 0; i < rangeAxisCount; i++) { ValueAxis axis = getRangeAxis(i); if (axis == null) { continue; } if (axis.isInverted()) { percent = -percent; } axis.pan(percent); } } /** * Multiplies the range on the domain axis/axes by the specified factor. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point (in Java2D space). * * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D) */ @Override public void zoomDomainAxes(double factor, PlotRenderingInfo info, Point2D source) { // delegate to other method zoomDomainAxes(factor, info, source, false); } /** * Multiplies the range on the domain axis/axes by the specified factor. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point (in Java2D space). * @param useAnchor use source point as zoom anchor? * * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean) * * @since 1.0.7 */ @Override public void zoomDomainAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor) { // perform the zoom on each domain axis for (ValueAxis xAxis : this.domainAxes.values()) { if (xAxis == null) { continue; } if (useAnchor) { // get the relevant source coordinate given the plot orientation double sourceX = source.getX(); if (this.orientation == PlotOrientation.HORIZONTAL) { sourceX = source.getY(); } double anchorX = xAxis.java2DToValue(sourceX, info.getDataArea(), getDomainAxisEdge()); xAxis.resizeRange2(factor, anchorX); } else { xAxis.resizeRange(factor); } } } /** * Zooms in on the domain axis/axes. The new lower and upper bounds are * specified as percentages of the current axis range, where 0 percent is * the current lower bound and 100 percent is the current upper bound. * * @param lowerPercent a percentage that determines the new lower bound * for the axis (e.g. 0.20 is twenty percent). * @param upperPercent a percentage that determines the new upper bound * for the axis (e.g. 0.80 is eighty percent). * @param info the plot rendering info. * @param source the source point (ignored). * * @see #zoomRangeAxes(double, double, PlotRenderingInfo, Point2D) */ @Override public void zoomDomainAxes(double lowerPercent, double upperPercent, PlotRenderingInfo info, Point2D source) { for (ValueAxis xAxis : this.domainAxes.values()) { if (xAxis != null) { xAxis.zoomRange(lowerPercent, upperPercent); } } } /** * Multiplies the range on the range axis/axes by the specified factor. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point. * * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean) */ @Override public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source) { // delegate to other method zoomRangeAxes(factor, info, source, false); } /** * Multiplies the range on the range axis/axes by the specified factor. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point. * @param useAnchor a flag that controls whether or not the source point * is used for the zoom anchor. * * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean) * * @since 1.0.7 */ @Override public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor) { // perform the zoom on each range axis for (ValueAxis yAxis : this.rangeAxes.values()) { if (yAxis == null) { continue; } if (useAnchor) { // get the relevant source coordinate given the plot orientation double sourceY = source.getY(); if (this.orientation == PlotOrientation.HORIZONTAL) { sourceY = source.getX(); } double anchorY = yAxis.java2DToValue(sourceY, info.getDataArea(), getRangeAxisEdge()); yAxis.resizeRange2(factor, anchorY); } else { yAxis.resizeRange(factor); } } } /** * Zooms in on the range axes. * * @param lowerPercent the lower bound. * @param upperPercent the upper bound. * @param info the plot rendering info. * @param source the source point. * * @see #zoomDomainAxes(double, double, PlotRenderingInfo, Point2D) */ @Override public void zoomRangeAxes(double lowerPercent, double upperPercent, PlotRenderingInfo info, Point2D source) { for (ValueAxis yAxis : this.rangeAxes.values()) { if (yAxis != null) { yAxis.zoomRange(lowerPercent, upperPercent); } } } /** * Returns {@code true}, indicating that the domain axis/axes for this * plot are zoomable. * * @return A boolean. * * @see #isRangeZoomable() */ @Override public boolean isDomainZoomable() { return true; } /** * Returns {@code true}, indicating that the range axis/axes for this * plot are zoomable. * * @return A boolean. * * @see #isDomainZoomable() */ @Override public boolean isRangeZoomable() { return true; } /** * Returns the number of series in the primary dataset for this plot. If * the dataset is {@code null}, the method returns 0. * * @return The series count. */ public int getSeriesCount() { int result = 0; XYDataset dataset = getDataset(); if (dataset != null) { result = dataset.getSeriesCount(); } return result; } /** * Returns the fixed legend items, if any. * * @return The legend items (possibly {@code null}). * * @see #setFixedLegendItems(LegendItemCollection) */ public LegendItemCollection getFixedLegendItems() { return this.fixedLegendItems; } /** * Sets the fixed legend items for the plot. Leave this set to * {@code null} if you prefer the legend items to be created * automatically. * * @param items the legend items ({@code null} permitted). * * @see #getFixedLegendItems() */ public void setFixedLegendItems(LegendItemCollection items) { this.fixedLegendItems = items; fireChangeEvent(); } /** * Returns the legend items for the plot. Each legend item is generated by * the plot's renderer, since the renderer is responsible for the visual * representation of the data. * * @return The legend items. */ @Override public LegendItemCollection getLegendItems() { if (this.fixedLegendItems != null) { return this.fixedLegendItems; } LegendItemCollection result = new LegendItemCollection(); for (XYDataset dataset : this.datasets.values()) { if (dataset == null) { continue; } int datasetIndex = indexOf(dataset); XYItemRenderer renderer = getRenderer(datasetIndex); if (renderer == null) { renderer = getRenderer(0); } if (renderer != null) { int seriesCount = dataset.getSeriesCount(); for (int i = 0; i < seriesCount; i++) { if (renderer.isSeriesVisible(i) && renderer.isSeriesVisibleInLegend(i)) { LegendItem item = renderer.getLegendItem( datasetIndex, i); if (item != null) { result.add(item); } } } } } return result; } /** * Tests this plot for equality with another object. * * @param obj the object ({@code null} permitted). * * @return {@code true} or {@code false}. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYPlot)) { return false; } XYPlot that = (XYPlot) obj; if (this.weight != that.weight) { return false; } if (this.orientation != that.orientation) { return false; } if (!this.domainAxes.equals(that.domainAxes)) { return false; } if (!this.domainAxisLocations.equals(that.domainAxisLocations)) { return false; } if (this.rangeCrosshairLockedOnData != that.rangeCrosshairLockedOnData) { return false; } if (this.domainGridlinesVisible != that.domainGridlinesVisible) { return false; } if (this.rangeGridlinesVisible != that.rangeGridlinesVisible) { return false; } if (this.domainMinorGridlinesVisible != that.domainMinorGridlinesVisible) { return false; } if (this.rangeMinorGridlinesVisible != that.rangeMinorGridlinesVisible) { return false; } if (this.domainZeroBaselineVisible != that.domainZeroBaselineVisible) { return false; } if (this.rangeZeroBaselineVisible != that.rangeZeroBaselineVisible) { return false; } if (this.domainCrosshairVisible != that.domainCrosshairVisible) { return false; } if (this.domainCrosshairValue != that.domainCrosshairValue) { return false; } if (this.domainCrosshairLockedOnData != that.domainCrosshairLockedOnData) { return false; } if (this.rangeCrosshairVisible != that.rangeCrosshairVisible) { return false; } if (this.rangeCrosshairValue != that.rangeCrosshairValue) { return false; } if (!ObjectUtilities.equal(this.axisOffset, that.axisOffset)) { return false; } if (!ObjectUtilities.equal(this.renderers, that.renderers)) { return false; } if (!ObjectUtilities.equal(this.rangeAxes, that.rangeAxes)) { return false; } if (!this.rangeAxisLocations.equals(that.rangeAxisLocations)) { return false; } if (!ObjectUtilities.equal(this.datasetToDomainAxesMap, that.datasetToDomainAxesMap)) { return false; } if (!ObjectUtilities.equal(this.datasetToRangeAxesMap, that.datasetToRangeAxesMap)) { return false; } if (!ObjectUtilities.equal(this.domainGridlineStroke, that.domainGridlineStroke)) { return false; } if (!PaintUtilities.equal(this.domainGridlinePaint, that.domainGridlinePaint)) { return false; } if (!ObjectUtilities.equal(this.rangeGridlineStroke, that.rangeGridlineStroke)) { return false; } if (!PaintUtilities.equal(this.rangeGridlinePaint, that.rangeGridlinePaint)) { return false; } if (!ObjectUtilities.equal(this.domainMinorGridlineStroke, that.domainMinorGridlineStroke)) { return false; } if (!PaintUtilities.equal(this.domainMinorGridlinePaint, that.domainMinorGridlinePaint)) { return false; } if (!ObjectUtilities.equal(this.rangeMinorGridlineStroke, that.rangeMinorGridlineStroke)) { return false; } if (!PaintUtilities.equal(this.rangeMinorGridlinePaint, that.rangeMinorGridlinePaint)) { return false; } if (!PaintUtilities.equal(this.domainZeroBaselinePaint, that.domainZeroBaselinePaint)) { return false; } if (!ObjectUtilities.equal(this.domainZeroBaselineStroke, that.domainZeroBaselineStroke)) { return false; } if (!PaintUtilities.equal(this.rangeZeroBaselinePaint, that.rangeZeroBaselinePaint)) { return false; } if (!ObjectUtilities.equal(this.rangeZeroBaselineStroke, that.rangeZeroBaselineStroke)) { return false; } if (!ObjectUtilities.equal(this.domainCrosshairStroke, that.domainCrosshairStroke)) { return false; } if (!PaintUtilities.equal(this.domainCrosshairPaint, that.domainCrosshairPaint)) { return false; } if (!ObjectUtilities.equal(this.rangeCrosshairStroke, that.rangeCrosshairStroke)) { return false; } if (!PaintUtilities.equal(this.rangeCrosshairPaint, that.rangeCrosshairPaint)) { return false; } if (!ObjectUtilities.equal(this.foregroundDomainMarkers, that.foregroundDomainMarkers)) { return false; } if (!ObjectUtilities.equal(this.backgroundDomainMarkers, that.backgroundDomainMarkers)) { return false; } if (!ObjectUtilities.equal(this.foregroundRangeMarkers, that.foregroundRangeMarkers)) { return false; } if (!ObjectUtilities.equal(this.backgroundRangeMarkers, that.backgroundRangeMarkers)) { return false; } if (!ObjectUtilities.equal(this.foregroundDomainMarkers, that.foregroundDomainMarkers)) { return false; } if (!ObjectUtilities.equal(this.backgroundDomainMarkers, that.backgroundDomainMarkers)) { return false; } if (!ObjectUtilities.equal(this.foregroundRangeMarkers, that.foregroundRangeMarkers)) { return false; } if (!ObjectUtilities.equal(this.backgroundRangeMarkers, that.backgroundRangeMarkers)) { return false; } if (!ObjectUtilities.equal(this.annotations, that.annotations)) { return false; } if (!ObjectUtilities.equal(this.fixedLegendItems, that.fixedLegendItems)) { return false; } if (!PaintUtilities.equal(this.domainTickBandPaint, that.domainTickBandPaint)) { return false; } if (!PaintUtilities.equal(this.rangeTickBandPaint, that.rangeTickBandPaint)) { return false; } if (!this.quadrantOrigin.equals(that.quadrantOrigin)) { return false; } for (int i = 0; i < 4; i++) { if (!PaintUtilities.equal(this.quadrantPaint[i], that.quadrantPaint[i])) { return false; } } if (!ObjectUtilities.equal(this.shadowGenerator, that.shadowGenerator)) { return false; } return super.equals(obj); } /** * Returns a clone of the plot. * * @return A clone. * * @throws CloneNotSupportedException this can occur if some component of * the plot cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { XYPlot clone = (XYPlot) super.clone(); clone.domainAxes = CloneUtils.cloneMapValues(this.domainAxes); for (ValueAxis axis : clone.domainAxes.values()) { if (axis != null) { axis.setPlot(clone); axis.addChangeListener(clone); } } clone.rangeAxes = CloneUtils.cloneMapValues(this.rangeAxes); for (ValueAxis axis : clone.rangeAxes.values()) { if (axis != null) { axis.setPlot(clone); axis.addChangeListener(clone); } } clone.domainAxisLocations = new HashMap<Integer, AxisLocation>( this.domainAxisLocations); clone.rangeAxisLocations = new HashMap<Integer, AxisLocation>( this.rangeAxisLocations); // the datasets are not cloned, but listeners need to be added... clone.datasets = new HashMap<Integer, XYDataset>(this.datasets); for (XYDataset dataset : clone.datasets.values()) { if (dataset != null) { dataset.addChangeListener(clone); } } clone.datasetToDomainAxesMap = new TreeMap(); clone.datasetToDomainAxesMap.putAll(this.datasetToDomainAxesMap); clone.datasetToRangeAxesMap = new TreeMap(); clone.datasetToRangeAxesMap.putAll(this.datasetToRangeAxesMap); clone.renderers = CloneUtils.cloneMapValues(this.renderers); for (XYItemRenderer renderer : clone.renderers.values()) { if (renderer != null) { renderer.setPlot(clone); renderer.addChangeListener(clone); } } clone.foregroundDomainMarkers = (Map) ObjectUtilities.clone( this.foregroundDomainMarkers); clone.backgroundDomainMarkers = (Map) ObjectUtilities.clone( this.backgroundDomainMarkers); clone.foregroundRangeMarkers = (Map) ObjectUtilities.clone( this.foregroundRangeMarkers); clone.backgroundRangeMarkers = (Map) ObjectUtilities.clone( this.backgroundRangeMarkers); clone.annotations = (List) ObjectUtilities.deepClone(this.annotations); if (this.fixedDomainAxisSpace != null) { clone.fixedDomainAxisSpace = (AxisSpace) ObjectUtilities.clone( this.fixedDomainAxisSpace); } if (this.fixedRangeAxisSpace != null) { clone.fixedRangeAxisSpace = (AxisSpace) ObjectUtilities.clone( this.fixedRangeAxisSpace); } if (this.fixedLegendItems != null) { clone.fixedLegendItems = (LegendItemCollection) this.fixedLegendItems.clone(); } clone.quadrantOrigin = (Point2D) ObjectUtilities.clone( this.quadrantOrigin); clone.quadrantPaint = this.quadrantPaint.clone(); return clone; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeStroke(this.domainGridlineStroke, stream); SerialUtilities.writePaint(this.domainGridlinePaint, stream); SerialUtilities.writeStroke(this.rangeGridlineStroke, stream); SerialUtilities.writePaint(this.rangeGridlinePaint, stream); SerialUtilities.writeStroke(this.domainMinorGridlineStroke, stream); SerialUtilities.writePaint(this.domainMinorGridlinePaint, stream); SerialUtilities.writeStroke(this.rangeMinorGridlineStroke, stream); SerialUtilities.writePaint(this.rangeMinorGridlinePaint, stream); SerialUtilities.writeStroke(this.rangeZeroBaselineStroke, stream); SerialUtilities.writePaint(this.rangeZeroBaselinePaint, stream); SerialUtilities.writeStroke(this.domainCrosshairStroke, stream); SerialUtilities.writePaint(this.domainCrosshairPaint, stream); SerialUtilities.writeStroke(this.rangeCrosshairStroke, stream); SerialUtilities.writePaint(this.rangeCrosshairPaint, stream); SerialUtilities.writePaint(this.domainTickBandPaint, stream); SerialUtilities.writePaint(this.rangeTickBandPaint, stream); SerialUtilities.writePoint2D(this.quadrantOrigin, stream); for (int i = 0; i < 4; i++) { SerialUtilities.writePaint(this.quadrantPaint[i], stream); } SerialUtilities.writeStroke(this.domainZeroBaselineStroke, stream); SerialUtilities.writePaint(this.domainZeroBaselinePaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.domainGridlineStroke = SerialUtilities.readStroke(stream); this.domainGridlinePaint = SerialUtilities.readPaint(stream); this.rangeGridlineStroke = SerialUtilities.readStroke(stream); this.rangeGridlinePaint = SerialUtilities.readPaint(stream); this.domainMinorGridlineStroke = SerialUtilities.readStroke(stream); this.domainMinorGridlinePaint = SerialUtilities.readPaint(stream); this.rangeMinorGridlineStroke = SerialUtilities.readStroke(stream); this.rangeMinorGridlinePaint = SerialUtilities.readPaint(stream); this.rangeZeroBaselineStroke = SerialUtilities.readStroke(stream); this.rangeZeroBaselinePaint = SerialUtilities.readPaint(stream); this.domainCrosshairStroke = SerialUtilities.readStroke(stream); this.domainCrosshairPaint = SerialUtilities.readPaint(stream); this.rangeCrosshairStroke = SerialUtilities.readStroke(stream); this.rangeCrosshairPaint = SerialUtilities.readPaint(stream); this.domainTickBandPaint = SerialUtilities.readPaint(stream); this.rangeTickBandPaint = SerialUtilities.readPaint(stream); this.quadrantOrigin = SerialUtilities.readPoint2D(stream); this.quadrantPaint = new Paint[4]; for (int i = 0; i < 4; i++) { this.quadrantPaint[i] = SerialUtilities.readPaint(stream); } this.domainZeroBaselineStroke = SerialUtilities.readStroke(stream); this.domainZeroBaselinePaint = SerialUtilities.readPaint(stream); // register the plot as a listener with its axes, datasets, and // renderers... for (ValueAxis axis : this.domainAxes.values()) { if (axis != null) { axis.setPlot(this); axis.addChangeListener(this); } } for (ValueAxis axis : this.rangeAxes.values()) { if (axis != null) { axis.setPlot(this); axis.addChangeListener(this); } } for (XYDataset dataset : this.datasets.values()) { if (dataset != null) { dataset.addChangeListener(this); } } for (XYItemRenderer renderer : this.renderers.values()) { if (renderer != null) { renderer.addChangeListener(this); } } } }
GitoMat/jfreechart
src/main/java/org/jfree/chart/plot/XYPlot.java
Java
lgpl-2.1
197,216
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>CQRS.NET: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ extensions: ["tex2jax.js"], jax: ["input/TeX","output/HTML-CSS"], }); </script><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">CQRS.NET &#160;<span id="projectnumber">2.1</span> </div> <div id="projectbrief">A lightweight enterprise framework to write CQRS, event-sourced and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('classCqrs_1_1Tests_1_1Snapshots_1_1When__saving__a__snapshotable__aggregate__for__each__change.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">Cqrs.Tests.Snapshots.When_saving_a_snapshotable_aggregate_for_each_change Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classCqrs_1_1Tests_1_1Snapshots_1_1When__saving__a__snapshotable__aggregate__for__each__change.html">Cqrs.Tests.Snapshots.When_saving_a_snapshotable_aggregate_for_each_change</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="classCqrs_1_1Tests_1_1Snapshots_1_1When__saving__a__snapshotable__aggregate__for__each__change_aa446b50b08f2cbc836471526b558d23f.html#aa446b50b08f2cbc836471526b558d23f">Setup</a>()</td><td class="entry"><a class="el" href="classCqrs_1_1Tests_1_1Snapshots_1_1When__saving__a__snapshotable__aggregate__for__each__change.html">Cqrs.Tests.Snapshots.When_saving_a_snapshotable_aggregate_for_each_change</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classCqrs_1_1Tests_1_1Snapshots_1_1When__saving__a__snapshotable__aggregate__for__each__change_a0bca19df42bb57b1182ceb130a4f925d.html#a0bca19df42bb57b1182ceb130a4f925d">Should_get_aggregate_back_correct</a>()</td><td class="entry"><a class="el" href="classCqrs_1_1Tests_1_1Snapshots_1_1When__saving__a__snapshotable__aggregate__for__each__change.html">Cqrs.Tests.Snapshots.When_saving_a_snapshotable_aggregate_for_each_change</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classCqrs_1_1Tests_1_1Snapshots_1_1When__saving__a__snapshotable__aggregate__for__each__change_a2564934da88a06a394930323fe2fb06c.html#a2564934da88a06a394930323fe2fb06c">Should_not_snapshot_first_event</a>()</td><td class="entry"><a class="el" href="classCqrs_1_1Tests_1_1Snapshots_1_1When__saving__a__snapshotable__aggregate__for__each__change.html">Cqrs.Tests.Snapshots.When_saving_a_snapshotable_aggregate_for_each_change</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classCqrs_1_1Tests_1_1Snapshots_1_1When__saving__a__snapshotable__aggregate__for__each__change_a81e76663141dcb1c2dbe730c8c50eb9e.html#a81e76663141dcb1c2dbe730c8c50eb9e">Should_snapshot_15th_change</a>()</td><td class="entry"><a class="el" href="classCqrs_1_1Tests_1_1Snapshots_1_1When__saving__a__snapshotable__aggregate__for__each__change.html">Cqrs.Tests.Snapshots.When_saving_a_snapshotable_aggregate_for_each_change</a></td><td class="entry"></td></tr> </table></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
cdmdotnet/CQRS
wiki/docs/2.1/html/classCqrs_1_1Tests_1_1Snapshots_1_1When__saving__a__snapshotable__aggregate__for__each__change-members.html
HTML
lgpl-2.1
6,448
/* +-----------------------------------------------------------------------------------------+ | | | OCILIB - C Driver for Oracle | | | | (C Wrapper for Oracle OCI) | | | | Website : http://www.ocilib.net | | | | Copyright (c) 2007-2015 Vincent ROGIER <[email protected]> | | | +-----------------------------------------------------------------------------------------+ | | | This library is free software; you can redistribute it and/or | | modify it under the terms of the GNU Lesser General Public | | License as published by the Free Software Foundation; either | | version 2 of the License, or (at your option) any later version. | | | | This library is distributed in the hope that it will be useful, | | but WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | | Lesser General Public License for more details. | | | | You should have received a copy of the GNU Lesser General Public | | License along with this library; if not, write to the Free | | Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. | | | +-----------------------------------------------------------------------------------------+ */ /* --------------------------------------------------------------------------------------------- * * $Id: number.c, Vincent Rogier $ * --------------------------------------------------------------------------------------------- */ #include "ocilib_internal.h" /* ********************************************************************************************* * * PRIVATE FUNCTIONS * ********************************************************************************************* */ /* --------------------------------------------------------------------------------------------- * * OCI_NumberGet * --------------------------------------------------------------------------------------------- */ boolean OCI_NumberGet ( OCI_Connection *con, void *number, uword size, uword type, int sqlcode, void *out_value ) { boolean res = TRUE; OCI_CHECK(NULL == con, FALSE) OCI_CHECK(NULL == number, FALSE) OCI_CHECK(NULL == out_value, FALSE) #if OCI_VERSION_COMPILE < OCI_10_1 OCI_NOT_USED(sqlcode) #endif if (OCI_NUM_NUMBER == type) { memcpy(out_value, number, size); } else if (type & OCI_NUM_DOUBLE || type & OCI_NUM_FLOAT) { #if OCI_VERSION_COMPILE >= OCI_10_1 if ((OCILib.version_runtime >= OCI_10_1) && ((sqlcode != SQLT_VNU))) { if (((type & OCI_NUM_DOUBLE) && (SQLT_BDOUBLE == sqlcode)) || ((type & OCI_NUM_FLOAT ) && (SQLT_BFLOAT == sqlcode))) { memcpy(out_value, number, size); } else if (type & OCI_NUM_DOUBLE && (SQLT_BFLOAT == sqlcode)) { *((double *) out_value) = (double) *((float *) number); } else if (type & OCI_NUM_FLOAT && (SQLT_BDOUBLE == sqlcode)) { *((float *) out_value) = (float) *((double *) number); } } else #endif { OCI_CALL2 ( res, con, OCINumberToReal(con->err, (OCINumber *) number, size, out_value) ) } } else { uword sign = (type & OCI_NUM_UNSIGNED) ? OCI_NUMBER_UNSIGNED : OCI_NUMBER_SIGNED; OCI_CALL2 ( res, con, OCINumberToInt(con->err, (OCINumber *) number, size, sign, out_value) ) } return res; } /* --------------------------------------------------------------------------------------------- * * OCI_NumberSet * --------------------------------------------------------------------------------------------- */ boolean OCI_NumberSet ( OCI_Connection *con, void *number, uword size, uword type, int sqlcode, void *in_value ) { boolean res = TRUE; OCI_CHECK(NULL == con, FALSE) OCI_CHECK(NULL == number, FALSE) OCI_CHECK(NULL == in_value, FALSE) #if OCI_VERSION_COMPILE < OCI_10_1 OCI_NOT_USED(sqlcode) #endif if (type & OCI_NUM_DOUBLE || type & OCI_NUM_FLOAT) { #if OCI_VERSION_COMPILE >= OCI_10_1 if ((OCILib.version_runtime >= OCI_10_1) && ((sqlcode != SQLT_VNU))) { if (((type & OCI_NUM_DOUBLE) && (SQLT_BDOUBLE == sqlcode)) || ((type & OCI_NUM_FLOAT ) && (SQLT_BFLOAT == sqlcode))) { memcpy(number, in_value, size); } else if (type & OCI_NUM_DOUBLE && SQLT_BFLOAT == sqlcode) { *((double *) number) = (double) *((float *) in_value); } else if (type & OCI_NUM_FLOAT && SQLT_BDOUBLE == sqlcode) { *((float *) number) = (float) *((double *) in_value); } } else #endif { OCI_CALL2 ( res, con, OCINumberFromReal(con->err, in_value, size, (OCINumber *) number) ) } } else { uword sign = (type & OCI_NUM_UNSIGNED) ? OCI_NUMBER_UNSIGNED : OCI_NUMBER_SIGNED; OCI_CALL2 ( res, con, OCINumberFromInt(con->err, in_value, size, sign, (OCINumber *) number) ) } return res; } /* --------------------------------------------------------------------------------------------- * * OCI_NumberFromString * --------------------------------------------------------------------------------------------- */ boolean OCI_NumberFromString ( OCI_Connection *con, void *out_value, uword size, uword type, int sqlcode, const otext *in_value, const otext * fmt ) { boolean res = TRUE; boolean done = FALSE; /* For binary types, perform a C based conversion */ if (type & OCI_NUM_DOUBLE || type & OCI_NUM_FLOAT || (SQLT_VNU != sqlcode)) { #if OCI_VERSION_COMPILE >= OCI_12_1 if ((OCILib.version_runtime >= OCI_12_1) && ((SQLT_VNU != sqlcode))) { if (type & OCI_NUM_SHORT) { res = (osscanf(in_value, OCI_STRING_FORMAT_NUM_SHORT, (short *)out_value) == 1); done = TRUE; } if (type & OCI_NUM_INT) { res = (osscanf(in_value, OCI_STRING_FORMAT_NUM_INT, (int *)out_value) == 1); done = TRUE; } } #endif #if OCI_VERSION_COMPILE >= OCI_10_1 if (!done && OCILib.version_runtime >= OCI_10_1) { fmt = OCI_GetFormat(con, type & OCI_NUM_DOUBLE ? OCI_FMT_BINARY_DOUBLE : OCI_FMT_BINARY_FLOAT); if (type & OCI_NUM_DOUBLE) { res = (osscanf(in_value, fmt, (double *)out_value) == 1); } else if (type & OCI_NUM_FLOAT) { res = (osscanf(in_value, fmt, (float *)out_value) == 1); } done = TRUE; } #endif } /* use OCINumber conversion if not processed yet */ if (!done) { dbtext *dbstr1 = NULL; dbtext *dbstr2 = NULL; int dbsize1 = -1; int dbsize2 = -1; OCINumber number; if (!fmt) { fmt = OCI_GetFormat(con, OCI_FMT_NUMERIC); } dbstr1 = OCI_StringGetOracleString(in_value, &dbsize1); dbstr2 = OCI_StringGetOracleString(fmt, &dbsize2); memset(&number, 0, sizeof(number)); OCI_CALL2 ( res, con, OCINumberFromText(con->err, (oratext *) dbstr1, (ub4) dbsize1, (oratext *) dbstr2, (ub4) dbsize2, (oratext *) NULL, (ub4) 0, (OCINumber *) &number) ) OCI_StringReleaseOracleString(dbstr2); OCI_StringReleaseOracleString(dbstr1); res = res && OCI_NumberGet(con, (void *) &number, size, type, sqlcode, out_value); } return res; } /* --------------------------------------------------------------------------------------------- * * OCI_NumberToString * --------------------------------------------------------------------------------------------- */ boolean OCI_NumberToString ( OCI_Connection *con, void *number, uword type, int sqlcode, otext *out_value, int out_value_size, const otext * fmt ) { boolean res = TRUE; boolean done = FALSE; out_value[0] = 0; /* For binary types, perform a C based conversion */ if (type & OCI_NUM_DOUBLE || type & OCI_NUM_FLOAT || (SQLT_VNU != sqlcode)) { #if OCI_VERSION_COMPILE >= OCI_12_1 if ((OCILib.version_runtime >= OCI_12_1) && ((SQLT_VNU != sqlcode))) { if (type & OCI_NUM_SHORT) { out_value_size = osprintf(out_value, out_value_size, OCI_STRING_FORMAT_NUM_SHORT, *((short *)number)); done = TRUE; } if (type & OCI_NUM_INT) { out_value_size = osprintf(out_value, out_value_size, OCI_STRING_FORMAT_NUM_INT, *((int *)number)); done = TRUE; } } #endif #if OCI_VERSION_COMPILE >= OCI_10_1 if (!done && (OCILib.version_runtime >= OCI_10_1) && ((SQLT_VNU != sqlcode))) { if (!fmt) { fmt = OCI_GetFormat(con, type & OCI_NUM_DOUBLE ? OCI_FMT_BINARY_DOUBLE : OCI_FMT_BINARY_FLOAT); } if (type & OCI_NUM_DOUBLE && (SQLT_BDOUBLE == sqlcode)) { out_value_size = osprintf(out_value, out_value_size, fmt, *((double *)number)); } else if (type & OCI_NUM_FLOAT && (SQLT_BFLOAT == sqlcode)) { out_value_size = osprintf(out_value, out_value_size, fmt, *((float *)number)); } done = TRUE; if ((out_value_size) > 0) { while (out_value[out_value_size-1] == OTEXT('0')) { out_value[out_value_size-1] = 0; } out_value--; } } #else OCI_NOT_USED(sqlcode) #endif } /* use OCINumber conversion if not processed yet */ if (!done) { dbtext *dbstr1 = NULL; dbtext *dbstr2 = NULL; int dbsize1 = out_value_size * (int) sizeof(otext); int dbsize2 = -1; if (!fmt) { fmt = OCI_GetFormat(con, OCI_FMT_NUMERIC); } dbstr1 = OCI_StringGetOracleString(out_value, &dbsize1); dbstr2 = OCI_StringGetOracleString(fmt, &dbsize2); OCI_CALL2 ( res, con, OCINumberToText(con->err, (OCINumber *) number, (oratext *) dbstr2, (ub4) dbsize2, (oratext *) NULL, (ub4) 0, (ub4 *) &dbsize1, (oratext *) dbstr1) ) OCI_StringCopyOracleStringToNativeString(dbstr1, out_value, dbcharcount(dbsize1)); OCI_StringReleaseOracleString(dbstr2); OCI_StringReleaseOracleString(dbstr1); out_value_size = (dbsize1 / (int) sizeof(dbtext)); } /* do we need to suppress last '.' or ',' from integers */ if ((--out_value_size) >= 0) { if ((out_value[out_value_size] == OTEXT('.')) || (out_value[out_value_size] == OTEXT(','))) { out_value[out_value_size] = 0; } } return res; }
alexeyvo/ocilib
src/number.c
C
lgpl-2.1
13,621
<?php namespace PhpAmqpLib\Helper; class MiscHelper { /** * @param string|array $a * @return string */ public static function methodSig($a) { if (is_string($a)) { return $a; } return sprintf('%d,%d', $a[0], $a[1]); } /** * Gets a number (either int or float) and returns an array containing its integer part as first element and its * decimal part mutliplied by 10^6. Useful for some PHP stream functions that need seconds and microseconds as * different arguments * * @param int|float $number * @return int[] */ public static function splitSecondsMicroseconds($number) { return array((int)floor($number), (int)(fmod($number, 1) * 1000000)); } /** * View any string as a hexdump. * * This is most commonly used to view binary data from streams * or sockets while debugging, but can be used to view any string * with non-viewable characters. * * @version 1.3.2 * @author Aidan Lister <[email protected]> * @author Peter Waller <[email protected]> * @link http://aidanlister.com/repos/v/function.hexdump.php * * @param string $data The string to be dumped * @param bool $htmloutput Set to false for non-HTML output * @param bool $uppercase Set to true for uppercase hex * @param bool $return Set to true to return the dump * @return string|null */ public static function hexdump($data, $htmloutput = true, $uppercase = false, $return = false) { // Init $hexi = ''; $ascii = ''; $dump = $htmloutput ? '<pre>' : ''; $offset = 0; $len = mb_strlen($data, 'ASCII'); // Upper or lower case hexidecimal $hexFormat = $uppercase ? 'X' : 'x'; // Iterate string for ($i = $j = 0; $i < $len; $i++) { // Convert to hexidecimal // We must use concatenation here because the $hexFormat value // is needed for sprintf() to parse the format $hexi .= sprintf('%02' . $hexFormat . ' ', ord($data[$i])); // Replace non-viewable bytes with '.' if (ord($data[$i]) >= 32) { $ascii .= $htmloutput ? htmlentities($data[$i]) : $data[$i]; } else { $ascii .= '.'; } // Add extra column spacing if ($j === 7) { $hexi .= ' '; $ascii .= ' '; } // Add row if (++$j === 16 || $i === $len - 1) { // Join the hexi / ascii output // We must use concatenation here because the $hexFormat value // is needed for sprintf() to parse the format $dump .= sprintf('%04' . $hexFormat . ' %-49s %s', $offset, $hexi, $ascii); // Reset vars $hexi = $ascii = ''; $offset += 16; $j = 0; // Add newline if ($i !== $len - 1) { $dump .= PHP_EOL; } } } // Finish dump $dump .= $htmloutput ? '</pre>' : ''; $dump .= PHP_EOL; if ($return) { return $dump; } echo $dump; return null; } /** * @param array $table * @return string */ public static function dump_table($table) { $tokens = array(); foreach ($table as $name => $value) { switch ($value[0]) { case 'D': $val = $value[1]->n . 'E' . $value[1]->e; break; case 'F': $val = '(' . self::dump_table($value[1]) . ')'; break; case 'T': $val = date('Y-m-d H:i:s', $value[1]); break; default: $val = $value[1]; } $tokens[] = $name . '=' . $val; } return implode(', ', $tokens); } }
php-amqplib/php-amqplib
PhpAmqpLib/Helper/MiscHelper.php
PHP
lgpl-2.1
4,122